Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0999601e6a |
||
|
|
cce0721ba9 |
||
|
|
381f424733 |
||
| 46cff770ab | |||
| 18ccab5464 | |||
| 175cb58aba | |||
| 111e90ce0a | |||
| c55dfd2492 | |||
| 5032243934 | |||
| dc4ed84a19 | |||
|
|
d256d3bb8e |
||
|
|
e923e06891 |
||
|
|
2c3d9fd176 |
25 changed files with 2210 additions and 244 deletions
|
|
@ -39,6 +39,11 @@ env:
|
||||||
CARGO_REGISTRY_VOLUME: onionwire-cargo-registry
|
CARGO_REGISTRY_VOLUME: onionwire-cargo-registry
|
||||||
CARGO_TARGET_VOLUME: onionwire-target-ci
|
CARGO_TARGET_VOLUME: onionwire-target-ci
|
||||||
BUILD_CONTAINER: onionwire-ci-${{ github.run_id }}
|
BUILD_CONTAINER: onionwire-ci-${{ github.run_id }}
|
||||||
|
# The SDK job gets its own target volume: it resolves the root crate with
|
||||||
|
# `rustls` instead of `native-tls`, so sharing a target dir would thrash both
|
||||||
|
# jobs' feature-unified artifacts.
|
||||||
|
SDK_CARGO_TARGET_VOLUME: onionwire-target-ci-sdk
|
||||||
|
SDK_BUILD_CONTAINER: onionwire-ci-sdk-${{ github.run_id }}
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
|
|
@ -73,3 +78,44 @@ jobs:
|
||||||
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees . \
|
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees . \
|
||||||
| docker start -a -i "$BUILD_CONTAINER"
|
| docker start -a -i "$BUILD_CONTAINER"
|
||||||
docker rm -f "$BUILD_CONTAINER" > /dev/null
|
docker rm -f "$BUILD_CONTAINER" > /dev/null
|
||||||
|
|
||||||
|
# `crates/onionwire-sdk` is a SEPARATE cargo workspace: its own Cargo.lock and
|
||||||
|
# a path dependency on the root crate, resolved with `rustls` instead of
|
||||||
|
# `native-tls`. The `test` job above therefore never compiles it, so a
|
||||||
|
# root-crate signature change (`Node::send` gaining the outbox result, the
|
||||||
|
# SQLCipher passphrase entry points) breaks the Android SDK — and the tagged
|
||||||
|
# release AAR, since android-release.yml only builds on `v*.*.*` — while both
|
||||||
|
# the root suites and local `cargo test` stay green. Build it here.
|
||||||
|
sdk:
|
||||||
|
runs-on: docker
|
||||||
|
timeout-minutes: 120
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: https://code.forgejo.org/actions/checkout@v4
|
||||||
|
|
||||||
|
- name: cargo test + clippy for crates/onionwire-sdk on aarch64
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
cd "${GITHUB_WORKSPACE}"
|
||||||
|
echo "workspace: $GITHUB_WORKSPACE"
|
||||||
|
docker volume create "$CARGO_REGISTRY_VOLUME" > /dev/null
|
||||||
|
docker volume create "$SDK_CARGO_TARGET_VOLUME" > /dev/null
|
||||||
|
docker rm -f "$SDK_BUILD_CONTAINER" > /dev/null 2>&1 || true
|
||||||
|
docker create --name "$SDK_BUILD_CONTAINER" -i \
|
||||||
|
-e CARGO_TARGET_DIR=/target \
|
||||||
|
-e CARGO_BUILD_JOBS=2 \
|
||||||
|
-e CARGO_TERM_COLOR=never \
|
||||||
|
-v "$CARGO_REGISTRY_VOLUME":/usr/local/cargo/registry \
|
||||||
|
-v "$SDK_CARGO_TARGET_VOLUME":/target \
|
||||||
|
-w /src \
|
||||||
|
"$RUST_IMAGE" \
|
||||||
|
sh -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src/crates/onionwire-sdk \
|
||||||
|
&& apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends pkg-config libssl-dev \
|
||||||
|
&& rustup component add clippy \
|
||||||
|
&& cargo test --locked \
|
||||||
|
&& cargo clippy --locked --all-targets -- -D warnings'
|
||||||
|
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees \
|
||||||
|
--exclude=./crates/onionwire-sdk/target . \
|
||||||
|
| docker start -a -i "$SDK_BUILD_CONTAINER"
|
||||||
|
docker rm -f "$SDK_BUILD_CONTAINER" > /dev/null
|
||||||
|
|
|
||||||
15
README.md
15
README.md
|
|
@ -3,7 +3,7 @@
|
||||||
Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process Arti).
|
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.
|
No hosted server. Identity is a public key; the onion is only a locator.
|
||||||
|
|
||||||
**v0.2** — Linux TUI. Two people add each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There is no QR graphic. Chat is Noise IK over your own v3 onion. Optional Monero invoices if you point at a local `monero-wallet-rpc`. Fail closed: peer down → send fails. Arti onion services are still experimental. Chat bodies are encrypted at rest; identity keys in sqlite are still plaintext.
|
**v0.2** — Linux TUI. Two people add each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There is no QR graphic. Chat is Noise IK over your own v3 onion. Optional Monero invoices if you point at a local `monero-wallet-rpc`. Fail closed: peer down → send fails. Arti onion services are still experimental. The whole store is encrypted at rest with SQLCipher; message bodies add a row-bound AEAD layer on top.
|
||||||
|
|
||||||
You do **not** install a `tor` daemon, `torrc`, Prosody, or XMPP. OnionWire embeds Arti and publishes its own v3 onion.
|
You do **not** install a `tor` daemon, `torrc`, Prosody, or XMPP. OnionWire embeds Arti and publishes its own v3 onion.
|
||||||
|
|
||||||
|
|
@ -222,14 +222,11 @@ If you set `ONIONWIRE_HOME`, delete that directory instead.
|
||||||
|
|
||||||
## Seized laptop
|
## Seized laptop
|
||||||
|
|
||||||
Chat bodies in sqlite are ChaCha20-Poly1305 (`nonce || ciphertext` in `messages.plaintext`) with AAD bound to `friend_id`, `dir`, and row id, wrapped by a passphrase-derived Argon2id key. A disk grep of `onionwire.db` must not yield the message log. Empty-AAD v0.2 blobs are rewrapped once on unlock.
|
The whole sqlite file is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`). A 32-byte key is derived from the store passphrase with Argon2id over a per-install 16-byte salt in `store_salt` (mode 0600, in `ONIONWIRE_HOME`) and handed to SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) as the first statement after open. The file header, schema, `self.identity_sk`, friend public keys, locators, profiles and payment rows are all ciphertext on disk, so a disk grep of `onionwire.db` must not yield the message log, your identity key or your roster. A wrong or empty passphrase fails closed before any write; an encrypted store whose `store_salt` is missing refuses to open instead of guessing. v0.2.1 plaintext installs upgrade in place on the first open with the right passphrase; a wrong one leaves the plaintext file untouched.
|
||||||
|
|
||||||
Still plaintext on disk (unless you add OS/FDE):
|
Chat bodies carry a second, row-bound layer: ChaCha20-Poly1305 (`nonce || ciphertext` in `messages.plaintext`) with AAD `owmsg1 || friend_id_le64 || dir || 0x00 || row_id_le64`, plus a random 32-byte data key in `store_meta` wrapped with Argon2id from the same passphrase. Whole-file encryption does not stop someone who can write the file from moving one row's ciphertext into another row; the row-bound AAD does, and it stays. Empty-AAD v0.2 blobs are rewrapped once on unlock.
|
||||||
|
|
||||||
- your identity secret key (`self.identity_sk`)
|
At-rest encryption is not a defense against a live compromise: while OnionWire runs, the passphrase, the db key and decrypted rows are in process memory, and SQLCipher's page cache holds decrypted pages. It also does not stop an attacker who has your passphrase. `/wipe` deletes chat and payments history; it is not a forensic erase — SSD wear-levelling can keep copies. Roster and identity stay. `/wipe-all` deletes the data dir (new identity). Ctrl-Q can clear history on the way out (`CLEAR`) without becoming a new person.
|
||||||
- friend public keys and current locators
|
|
||||||
|
|
||||||
The message key is **not** wrapped with `identity_sk` (that key is in the same file). sqlcipher is out of v1. `/wipe` deletes chat and payments history; it is not a forensic erase. Roster and identity stay. `/wipe-all` deletes the data dir (new identity). Ctrl-Q can clear history on the way out (`CLEAR`) without becoming a new person.
|
|
||||||
|
|
||||||
Threat model: [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md).
|
Threat model: [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md).
|
||||||
|
|
||||||
|
|
@ -289,7 +286,7 @@ FORGEJO_TOKEN=<pat> scripts/build-release-local.sh vX.Y.Z
|
||||||
|
|
||||||
Workflows (Forgejo Actions, `.forgejo/workflows/`):
|
Workflows (Forgejo Actions, `.forgejo/workflows/`):
|
||||||
|
|
||||||
- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. Pi runner, `docker` label.
|
- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — two jobs on the Pi runner (`docker` label), serialized by `onionwire-ci-pi`. `test`: `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` at the repo root. `sdk`: the same for `crates/onionwire-sdk` (separate cargo workspace — own `Cargo.lock`, root crate by path, `rustls` instead of `native-tls` — so a root signature change cannot silently break the Android SDK). Both run on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite.
|
||||||
- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — on core paths to `main` (`src/`, `crates/`, `Cargo.toml`, `Cargo.lock`, `scripts/release-body.md`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release. `workflow_dispatch` rebuilds a tag or `dry_run`s. Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`.
|
- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — on core paths to `main` (`src/`, `crates/`, `Cargo.toml`, `Cargo.lock`, `scripts/release-body.md`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release. `workflow_dispatch` rebuilds a tag or `dry_run`s. Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`.
|
||||||
|
|
||||||
Scripts:
|
Scripts:
|
||||||
|
|
@ -316,7 +313,7 @@ Do not run `cargo publish`; `publish = false`. CI needs the repo secret
|
||||||
|
|
||||||
## Not in v1
|
## Not in v1
|
||||||
|
|
||||||
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, sqlcipher, QR codes, A/V. Protocol lock: [docs/PROTOCOL.md](docs/PROTOCOL.md).
|
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, QR codes, A/V. Protocol lock: [docs/PROTOCOL.md](docs/PROTOCOL.md).
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,10 +4,33 @@
|
||||||
<!--
|
<!--
|
||||||
INTERNET is the only permission requested at first launch.
|
INTERNET is the only permission requested at first launch.
|
||||||
No camera (invites are typed/pasted, not scanned), no contacts, no
|
No camera (invites are typed/pasted, not scanned), no contacts, no
|
||||||
storage. Tor runs in-process; there is no foreground service and no
|
storage.
|
||||||
keep-alive notification in v1, so the node only lives while the app does.
|
|
||||||
|
Tor runs in-process, and the node is kept published across Doze and
|
||||||
|
backgrounding by KeepAliveService: a foreground service with an ongoing
|
||||||
|
notification, started on unlock, stopped by Lock or by the notification's
|
||||||
|
Stop action. Its anchors and the node's lifetime are arbitrated in
|
||||||
|
NodeHost/NodeLifetime; the service never owns the node itself.
|
||||||
-->
|
-->
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
|
||||||
|
<!--
|
||||||
|
specialUse, not dataSync. dataSync is documented as "data transfer
|
||||||
|
operations" (upload/download, backup/restore, import/export) and the
|
||||||
|
official alternatives guide points at WorkManager or a user-initiated
|
||||||
|
transfer job — all of which assume a transfer with an end. A node holding
|
||||||
|
an inbound onion service open and draining a retry queue has no end and no
|
||||||
|
progress to report, so specialUse ("valid foreground service use cases
|
||||||
|
that aren't covered by the other types") is the honest declaration. It
|
||||||
|
costs a Play Console justification; dataSync would cost a lie.
|
||||||
|
-->
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||||
|
|
||||||
|
<!-- API 33+. Without it the keep-alive still runs, but its notification is
|
||||||
|
hidden from the drawer (the user sees the service in the Task Manager
|
||||||
|
instead). Denial is handled, not fatal: see WireViewModel.keepAliveNote. -->
|
||||||
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
|
||||||
<application
|
<application
|
||||||
android:allowBackup="false"
|
android:allowBackup="false"
|
||||||
|
|
@ -30,6 +53,21 @@
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Not exported: only this app starts it, from a user-visible unlock.
|
||||||
|
stopWithTask is left at its default (false) on purpose — swiping the
|
||||||
|
task away must not take the onion offline; the activity is destroyed,
|
||||||
|
NodeHost flushes the outbox, and the onion stays published.
|
||||||
|
-->
|
||||||
|
<service
|
||||||
|
android:name=".keepalive.KeepAliveService"
|
||||||
|
android:exported="false"
|
||||||
|
android:foregroundServiceType="specialUse">
|
||||||
|
<property
|
||||||
|
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||||
|
android:value="peer-to-peer messaging node: keeps an inbound onion service published and an outbox retry queue running so peers can deliver messages while the app is backgrounded; there is no user-initiated transfer to bound the work" />
|
||||||
|
</service>
|
||||||
|
|
||||||
</application>
|
</application>
|
||||||
|
|
||||||
</manifest>
|
</manifest>
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,18 @@
|
||||||
package com.siriusdevops.onionwire
|
package com.siriusdevops.onionwire
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
import androidx.activity.enableEdgeToEdge
|
import androidx.activity.enableEdgeToEdge
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
|
@ -48,9 +53,27 @@ class MainActivity : ComponentActivity() {
|
||||||
private fun AppRoot(vm: WireViewModel = viewModel()) {
|
private fun AppRoot(vm: WireViewModel = viewModel()) {
|
||||||
val phase by vm.phase.collectAsStateWithLifecycle()
|
val phase by vm.phase.collectAsStateWithLifecycle()
|
||||||
val unlock by vm.unlock.collectAsStateWithLifecycle()
|
val unlock by vm.unlock.collectAsStateWithLifecycle()
|
||||||
|
val keepAliveNote by vm.keepAliveNote.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
// Asked in context: the notification is the keep-alive's only visible
|
||||||
|
// trace, so the prompt lands when the node becomes reachable rather than at
|
||||||
|
// first launch. Denial is not fatal — the service runs either way and the
|
||||||
|
// roster says the notice is hidden.
|
||||||
|
val askNotifications = rememberLauncherForActivityResult(
|
||||||
|
ActivityResultContracts.RequestPermission(),
|
||||||
|
) { vm.onNotificationPermissionChanged() }
|
||||||
|
|
||||||
|
LaunchedEffect(phase) {
|
||||||
|
if (phase is Phase.Ready &&
|
||||||
|
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||||
|
!vm.notificationsAllowed()
|
||||||
|
) {
|
||||||
|
askNotifications.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
when (val p = phase) {
|
when (val p = phase) {
|
||||||
is Phase.Ready -> ReadyGraph(vm, p)
|
is Phase.Ready -> ReadyGraph(vm, p, keepAliveNote)
|
||||||
else -> UnlockScreen(
|
else -> UnlockScreen(
|
||||||
phase = p,
|
phase = p,
|
||||||
unlock = unlock,
|
unlock = unlock,
|
||||||
|
|
@ -62,7 +85,7 @@ private fun AppRoot(vm: WireViewModel = viewModel()) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready) {
|
private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: String?) {
|
||||||
val nav = rememberNavController()
|
val nav = rememberNavController()
|
||||||
val friends by vm.friends.collectAsStateWithLifecycle()
|
val friends by vm.friends.collectAsStateWithLifecycle()
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
|
|
@ -74,6 +97,7 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready) {
|
||||||
onion = ready.onion,
|
onion = ready.onion,
|
||||||
sdkVersion = ready.sdkVersion,
|
sdkVersion = ready.sdkVersion,
|
||||||
friends = friends,
|
friends = friends,
|
||||||
|
keepAliveNote = keepAliveNote,
|
||||||
onOpenChat = { nav.navigate("chat/${it.pubkeyHex}") },
|
onOpenChat = { nav.navigate("chat/${it.pubkeyHex}") },
|
||||||
onShare = { nav.navigate("share") },
|
onShare = { nav.navigate("share") },
|
||||||
onPaste = { nav.navigate("paste") },
|
onPaste = { nav.navigate("paste") },
|
||||||
|
|
@ -119,6 +143,8 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready) {
|
||||||
fingerprint = friend?.fingerprint ?: pk.take(16),
|
fingerprint = friend?.fingerprint ?: pk.take(16),
|
||||||
onion = friend?.onion.orEmpty(),
|
onion = friend?.onion.orEmpty(),
|
||||||
loadMessages = { vm.messages(pk) },
|
loadMessages = { vm.messages(pk) },
|
||||||
|
loadOutbox = { vm.outbox(pk) },
|
||||||
|
loadMaxAttempts = { vm.outboxMaxAttempts() },
|
||||||
onSend = { body -> vm.send(pk, body) },
|
onSend = { body -> vm.send(pk, body) },
|
||||||
onBack = { nav.popBackStack() },
|
onBack = { nav.popBackStack() },
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,17 @@
|
||||||
package com.siriusdevops.onionwire
|
package com.siriusdevops.onionwire
|
||||||
|
|
||||||
import android.app.Application
|
import android.app.Application
|
||||||
|
import androidx.core.app.NotificationManagerCompat
|
||||||
import androidx.lifecycle.AndroidViewModel
|
import androidx.lifecycle.AndroidViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.siriusdevops.onionwire.crypto.KeyBacking
|
import com.siriusdevops.onionwire.crypto.KeyBacking
|
||||||
import com.siriusdevops.onionwire.crypto.KeystorePassphraseCipher
|
import com.siriusdevops.onionwire.crypto.KeystorePassphraseCipher
|
||||||
import com.siriusdevops.onionwire.crypto.StoreSecret
|
import com.siriusdevops.onionwire.crypto.StoreSecret
|
||||||
import com.siriusdevops.onionwire.crypto.StoredPassphraseStore
|
import com.siriusdevops.onionwire.crypto.StoredPassphraseStore
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import com.siriusdevops.onionwire.keepalive.KeepAliveService
|
||||||
|
import com.siriusdevops.onionwire.keepalive.KeepAliveStatus
|
||||||
|
import com.siriusdevops.onionwire.keepalive.NodeHost
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.SupervisorJob
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
|
@ -19,10 +20,11 @@ import kotlinx.coroutines.withContext
|
||||||
import uniffi.onionwire_sdk.ChatMessage
|
import uniffi.onionwire_sdk.ChatMessage
|
||||||
import uniffi.onionwire_sdk.FriendInfo
|
import uniffi.onionwire_sdk.FriendInfo
|
||||||
import uniffi.onionwire_sdk.InviteInfo
|
import uniffi.onionwire_sdk.InviteInfo
|
||||||
|
import uniffi.onionwire_sdk.OutboxRow
|
||||||
import uniffi.onionwire_sdk.RotateOutcome
|
import uniffi.onionwire_sdk.RotateOutcome
|
||||||
|
import uniffi.onionwire_sdk.SendState
|
||||||
import uniffi.onionwire_sdk.Wire
|
import uniffi.onionwire_sdk.Wire
|
||||||
import uniffi.onionwire_sdk.decodeInvite
|
import uniffi.onionwire_sdk.decodeInvite
|
||||||
import uniffi.onionwire_sdk.openWire
|
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
sealed interface Phase {
|
sealed interface Phase {
|
||||||
|
|
@ -59,18 +61,13 @@ sealed interface Unlock {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Teardown work must outlive the ViewModel: `onCleared()` runs *after*
|
* Owns the UI side of the process's single node.
|
||||||
* `viewModelScope` is already cancelled, and stopping the node means draining
|
|
||||||
* the outbox and stopping Arti, not just dropping a reference. One process-wide
|
|
||||||
* scope is enough — there is one node per process.
|
|
||||||
*/
|
|
||||||
private val TEARDOWN = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Owns the single Wire node for the process.
|
|
||||||
*
|
*
|
||||||
* The node lives in the ViewModel because a configuration change must not
|
* The node itself lives in [NodeHost], not here, because it now has two
|
||||||
* drop a published onion service and re-bootstrap Tor.
|
* possible owners: this ViewModel while the UI is up, and [KeepAliveService]
|
||||||
|
* while the screen is off. A configuration change still must not drop a
|
||||||
|
* published onion, and neither must the activity being destroyed — that part
|
||||||
|
* is unchanged.
|
||||||
*/
|
*/
|
||||||
class WireViewModel(app: Application) : AndroidViewModel(app) {
|
class WireViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
|
|
||||||
|
|
@ -96,22 +93,30 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
private val _friends = MutableStateFlow<List<FriendInfo>>(emptyList())
|
private val _friends = MutableStateFlow<List<FriendInfo>>(emptyList())
|
||||||
val friends: StateFlow<List<FriendInfo>> = _friends.asStateFlow()
|
val friends: StateFlow<List<FriendInfo>> = _friends.asStateFlow()
|
||||||
|
|
||||||
private var wire: Wire? = null
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The in-flight teardown, if any. Unlocking again has to wait for it: the
|
* One line of battery honesty for the roster: what is still running once
|
||||||
* old node holds the sqlite file and Arti's state lock until `shutdown()`
|
* the screen is off, or why it is not. Null while locked.
|
||||||
* returns, and racing it makes the new node fail to open.
|
|
||||||
*/
|
*/
|
||||||
private var stopping: Job? = null
|
private val _keepAliveNote = MutableStateFlow<String?>(null)
|
||||||
|
val keepAliveNote: StateFlow<String?> = _keepAliveNote.asStateFlow()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
// Probe on a background dispatcher: this touches the Keystore and does
|
// A node the foreground service kept alive is still open. Adopt it and
|
||||||
// a full GCM decrypt. Doing it here means a killed Keystore key is
|
// go straight to the roster: showing an unlock screen for a store that
|
||||||
// reported on the lock screen instead of at the first tap.
|
// is already open would be theatre, and unlocking again would race the
|
||||||
|
// live node for the sqlite file.
|
||||||
|
val existing = NodeHost.current()
|
||||||
|
if (existing != null) {
|
||||||
|
viewModelScope.launch { adopt(existing) }
|
||||||
|
} else {
|
||||||
refreshUnlockState()
|
refreshUnlockState()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
viewModelScope.launch {
|
||||||
|
NodeHost.keepAlive.collect { renderKeepAliveNote(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unlocks with a typed passphrase. Empty fails closed — the SDK maps it
|
* Unlocks with a typed passphrase. Empty fails closed — the SDK maps it
|
||||||
* straight to an error, it is not a "skip" path.
|
* straight to an error, it is not a "skip" path.
|
||||||
|
|
@ -162,44 +167,155 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stops the node and drops our handle. Nothing is sent after this.
|
* Explicit Lock: stops the node and the keep-alive with it.
|
||||||
*
|
*
|
||||||
* Flush first — the outbox is the whole point of losing the process — then
|
* Order matters. The service goes first — a still-running keep-alive would
|
||||||
* `shutdown()`, which stops the onion service, aborts the retry worker and
|
* re-anchor the node and leave a notification pointing at a dead onion —
|
||||||
* checkpoints the sqlite WAL. Both calls are on [TEARDOWN] because this
|
* then the policy tears the node down, flush before `shutdown()` so the
|
||||||
* runs from an `onClick`.
|
* outbox survives.
|
||||||
*/
|
*/
|
||||||
fun lock() {
|
fun lock() {
|
||||||
val w = wire ?: return
|
if (NodeHost.current() == null) return
|
||||||
wire = null
|
KeepAliveService.stop(getApplication())
|
||||||
|
NodeHost.lock()
|
||||||
_friends.value = emptyList()
|
_friends.value = emptyList()
|
||||||
_phase.value = Phase.Locked
|
_phase.value = Phase.Locked
|
||||||
refreshUnlockState()
|
refreshUnlockState()
|
||||||
stopping = TEARDOWN.launch { stopNode(w) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The node must not outlive the UI. Doze and the background-process killer
|
* The UI is going away: a normal finish, a task swipe, or the process being
|
||||||
* skip this entirely (that is what the outbox is for), but a normal finish
|
* killed. This deliberately does **not** shut the node down — [NodeHost]
|
||||||
* tears Tor down here instead of leaving Arti running behind a dead screen.
|
* decides between "flush and stay published" (a keep-alive is holding it)
|
||||||
|
* and "flush and stop" (nothing is). A ViewModel that shut down a node the
|
||||||
|
* foreground service owns is the bug this card exists to avoid.
|
||||||
*/
|
*/
|
||||||
override fun onCleared() {
|
override fun onCleared() {
|
||||||
val w = wire
|
NodeHost.onUiDetached()
|
||||||
wire = null
|
|
||||||
if (w != null) stopping = TEARDOWN.launch { stopNode(w) }
|
|
||||||
super.onCleared()
|
super.onCleared()
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun stopNode(w: Wire) {
|
/** Re-reads the notification state after the runtime prompt resolves. */
|
||||||
// Best effort, both steps: teardown runs on a process-scope job after
|
fun onNotificationPermissionChanged() {
|
||||||
// the UI is gone, so there is nobody to show an error to and nothing
|
renderKeepAliveNote(NodeHost.keepAlive.value)
|
||||||
// useful to retry. `shutdown()` drains again with a shorter budget, so
|
// Android does not retroactively post a foreground notification that was
|
||||||
// a flush that times out is not fatal.
|
// suppressed while POST_NOTIFICATIONS was denied — the service started,
|
||||||
runCatching { w.flush() }
|
// the user then granted, and the shade stayed empty. Re-announce, so the
|
||||||
// A second shutdown — `lock()` and then `onCleared()`, say — lands here
|
// grant actually produces the one honest signal the user has.
|
||||||
// too: the SDK reports it as a typed WireException.Stopped, never a
|
if (NodeHost.keepAlive.value is KeepAliveStatus.On) {
|
||||||
// panic, so swallowing it is correct.
|
viewModelScope.launch {
|
||||||
runCatching { w.shutdown() }
|
NodeHost.current()?.let { KeepAliveService.start(getApplication(), it.onion()) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the keep-alive's notification can actually be posted. */
|
||||||
|
fun notificationsAllowed(): Boolean =
|
||||||
|
NotificationManagerCompat.from(getApplication()).areNotificationsEnabled()
|
||||||
|
|
||||||
|
private fun renderKeepAliveNote(status: KeepAliveStatus) {
|
||||||
|
val text = getApplication<Application>()
|
||||||
|
_keepAliveNote.value = when (status) {
|
||||||
|
// Not a null note: "off" is a real state the user should be able to
|
||||||
|
// read, right after the notification's Stop action.
|
||||||
|
KeepAliveStatus.Off -> text.getString(R.string.keep_alive_note_off)
|
||||||
|
|
||||||
|
KeepAliveStatus.On -> text.getString(
|
||||||
|
if (notificationsAllowed()) {
|
||||||
|
R.string.keep_alive_note_on
|
||||||
|
} else {
|
||||||
|
// Denial is not fatal: the service runs either way and
|
||||||
|
// Android lists it in the Task Manager. Say that instead of
|
||||||
|
// pretending the notification is there.
|
||||||
|
R.string.keep_alive_note_hidden
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
is KeepAliveStatus.Unavailable ->
|
||||||
|
text.getString(R.string.keep_alive_note_unavailable, status.reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The one path that opens the SDK.
|
||||||
|
*
|
||||||
|
* [secret] is wiped in `finally`, including when the Keystore write or the
|
||||||
|
* SDK call throws. The SDK's UniFFI signature takes a `String`, so one
|
||||||
|
* immutable copy is unavoidable here — see PR #49 for the follow-up SDK
|
||||||
|
* signature this card cannot make itself.
|
||||||
|
*/
|
||||||
|
private fun openWith(secret: CharArray, storeAfterwards: Boolean) {
|
||||||
|
if (secret.isEmpty() || _phase.value is Phase.Opening) {
|
||||||
|
StoreSecret.wipe(secret)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val existing = NodeHost.current()
|
||||||
|
if (existing != null) {
|
||||||
|
// Already open, kept alive while the UI was gone: adopt, never
|
||||||
|
// re-open. The live node holds the sqlite file and Arti's state
|
||||||
|
// lock, so a second open would fail — or worse, half-succeed.
|
||||||
|
StoreSecret.wipe(secret)
|
||||||
|
viewModelScope.launch { adopt(existing) }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_phase.value = Phase.Opening
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
// The SDK open is dispatched to Dispatchers.IO inside NodeHost:
|
||||||
|
// cold start is minutes of Tor bootstrap, which the main thread
|
||||||
|
// does not survive.
|
||||||
|
val w = NodeHost.open(home, secret.concatToString())
|
||||||
|
if (storeAfterwards) store(secret)
|
||||||
|
adopt(w)
|
||||||
|
startKeepAlive(w)
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
_phase.value = Phase.Failed(t.message ?: t.toString())
|
||||||
|
} finally {
|
||||||
|
StoreSecret.wipe(secret)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Points the UI at a node that is already running. The SDK getters are
|
||||||
|
* `suspend`, hence the coroutine call sites.
|
||||||
|
*/
|
||||||
|
private suspend fun adopt(w: Wire) {
|
||||||
|
_phase.value = Phase.Ready(
|
||||||
|
fingerprint = w.fingerprint(),
|
||||||
|
onion = w.onion(),
|
||||||
|
sdkVersion = w.version(),
|
||||||
|
)
|
||||||
|
runCatching { refreshFriends() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts the foreground keep-alive. Always reached from a user-visible
|
||||||
|
* unlock, so the API 31+ background-start restriction does not apply; if
|
||||||
|
* the system refuses anyway, [NodeHost] records why and the roster says so.
|
||||||
|
*/
|
||||||
|
private suspend fun startKeepAlive(w: Wire) {
|
||||||
|
if (NodeHost.keepAlive.value is KeepAliveStatus.On) return
|
||||||
|
KeepAliveService.start(getApplication(), w.onion())
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun store(secret: CharArray) {
|
||||||
|
val outcome: Result<KeyBacking> = withContext(Dispatchers.IO) {
|
||||||
|
try {
|
||||||
|
secrets.save(secret)
|
||||||
|
Result.success(secrets.backing())
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
Result.failure(t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_unlock.value = outcome.fold(
|
||||||
|
onSuccess = { Unlock.OneTap(it) },
|
||||||
|
onFailure = {
|
||||||
|
// Unlock succeeded, so this is not fatal — say so plainly
|
||||||
|
// instead of pretending the passphrase was stored.
|
||||||
|
Unlock.TypeIt("Could not store the passphrase: ${it.message ?: it}.")
|
||||||
|
},
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun refreshUnlockState() {
|
private fun refreshUnlockState() {
|
||||||
|
|
@ -222,66 +338,10 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* The one path that calls the SDK.
|
|
||||||
*
|
|
||||||
* [secret] is wiped in `finally`, including when the Keystore write or the
|
|
||||||
* SDK call throws. The SDK's UniFFI signature takes a `String`, so one
|
|
||||||
* immutable copy is unavoidable here — see the PR description for the
|
|
||||||
* follow-up SDK signature this card cannot make itself.
|
|
||||||
*/
|
|
||||||
private fun openWith(secret: CharArray, storeAfterwards: Boolean) {
|
|
||||||
if (secret.isEmpty() || _phase.value is Phase.Opening || wire != null) {
|
|
||||||
StoreSecret.wipe(secret)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
_phase.value = Phase.Opening
|
|
||||||
viewModelScope.launch {
|
|
||||||
try {
|
|
||||||
// Any previous node must be fully stopped first: the old node
|
|
||||||
// holds the sqlite file and Arti's state lock until its teardown
|
|
||||||
// returns, and racing it makes this open fail.
|
|
||||||
stopping?.join()
|
|
||||||
val w = openWire(home.absolutePath, secret.concatToString())
|
|
||||||
wire = w
|
|
||||||
if (storeAfterwards) store(secret)
|
|
||||||
_phase.value = Phase.Ready(
|
|
||||||
fingerprint = w.fingerprint(),
|
|
||||||
onion = w.onion(),
|
|
||||||
sdkVersion = w.version(),
|
|
||||||
)
|
|
||||||
refreshFriends()
|
|
||||||
} catch (t: Throwable) {
|
|
||||||
_phase.value = Phase.Failed(t.message ?: t.toString())
|
|
||||||
} finally {
|
|
||||||
StoreSecret.wipe(secret)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun store(secret: CharArray) {
|
|
||||||
val outcome: Result<KeyBacking> = withContext(Dispatchers.IO) {
|
|
||||||
try {
|
|
||||||
secrets.save(secret)
|
|
||||||
Result.success(secrets.backing())
|
|
||||||
} catch (t: Throwable) {
|
|
||||||
Result.failure(t)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_unlock.value = outcome.fold(
|
|
||||||
onSuccess = { Unlock.OneTap(it) },
|
|
||||||
onFailure = {
|
|
||||||
// Unlock succeeded, so this is not fatal — say so plainly
|
|
||||||
// instead of pretending the passphrase was stored.
|
|
||||||
Unlock.TypeIt("Could not store the passphrase: ${it.message ?: it}.")
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun unavailableNotice(reason: String): String =
|
private fun unavailableNotice(reason: String): String =
|
||||||
"The stored passphrase could not be read — $reason. Type it once to store it again."
|
"The stored passphrase could not be read — $reason. Type it once to store it again."
|
||||||
|
|
||||||
private fun requireWire(): Wire = wire ?: error("locked")
|
private fun requireWire(): Wire = NodeHost.requireOpen()
|
||||||
|
|
||||||
suspend fun refreshFriends() {
|
suspend fun refreshFriends() {
|
||||||
_friends.value = requireWire().friends()
|
_friends.value = requireWire().friends()
|
||||||
|
|
@ -303,7 +363,33 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
suspend fun messages(pubkeyHex: String): List<ChatMessage> =
|
suspend fun messages(pubkeyHex: String): List<ChatMessage> =
|
||||||
requireWire().messages(pubkeyHex)
|
requireWire().messages(pubkeyHex)
|
||||||
|
|
||||||
suspend fun send(pubkeyHex: String, body: String) =
|
/**
|
||||||
|
* The core's outbox rows for one friend: the `"queued"` / `"sending"` /
|
||||||
|
* `"failed"` rows behind [ChatMessage.delivery], each with the attempt count
|
||||||
|
* and absolute next-attempt time the store holds. Empty means nothing is
|
||||||
|
* outstanding for them. Read this instead of guessing a retry schedule in
|
||||||
|
* the app.
|
||||||
|
*/
|
||||||
|
suspend fun outbox(pubkeyHex: String): List<OutboxRow> =
|
||||||
|
requireWire().outbox(pubkeyHex)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The core's retry budget — the denominator in `try n/8`. A constant of the
|
||||||
|
* outbox, not per-node state, so it is fetched from the SDK rather than
|
||||||
|
* duplicated here; the app must not hardcode it.
|
||||||
|
*/
|
||||||
|
suspend fun outboxMaxAttempts(): UInt = uniffi.onionwire_sdk.outboxMaxAttempts()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends one chat message and reports what the core did with it.
|
||||||
|
*
|
||||||
|
* `SENT` — the peer's onion took the frame during this call. `QUEUED` — it
|
||||||
|
* was unreachable, so the message is in the local outbox and the retry
|
||||||
|
* worker will dial again with backoff until it lands or fails terminally.
|
||||||
|
* The state is returned rather than swallowed so the UI never shows a
|
||||||
|
* queued message as delivered.
|
||||||
|
*/
|
||||||
|
suspend fun send(pubkeyHex: String, body: String): SendState =
|
||||||
requireWire().send(pubkeyHex, body)
|
requireWire().send(pubkeyHex, body)
|
||||||
|
|
||||||
suspend fun wipeMessages() {
|
suspend fun wipeMessages() {
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,181 @@
|
||||||
|
package com.siriusdevops.onionwire.keepalive
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.app.Service
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.ServiceInfo
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.IBinder
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.core.app.NotificationCompat
|
||||||
|
import com.siriusdevops.onionwire.MainActivity
|
||||||
|
import com.siriusdevops.onionwire.R
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Holds the process (and therefore the in-process Arti node) in the foreground
|
||||||
|
* so the onion stays published after the screen goes off.
|
||||||
|
*
|
||||||
|
* The service does *not* own the node — [NodeHost] does. This reports its
|
||||||
|
* anchor and lets the policy decide: starting the keep-alive keeps the node
|
||||||
|
* alive, and losing it (user tapped Stop, or the system killed us) shuts the
|
||||||
|
* node down only if nothing else is holding it.
|
||||||
|
*
|
||||||
|
* Returns `START_NOT_STICKY` deliberately. A sticky restart would bring the
|
||||||
|
* service back with no node behind it — the passphrase is not held in memory
|
||||||
|
* after unlock — and a notification claiming "OnionWire is reachable" over a
|
||||||
|
* dead onion is worse than no service at all.
|
||||||
|
*/
|
||||||
|
class KeepAliveService : Service() {
|
||||||
|
|
||||||
|
override fun onBind(intent: Intent?): IBinder? = null
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
if (intent?.action == ACTION_STOP) {
|
||||||
|
// The user ended the keep-alive from the notification. `onDestroy()`
|
||||||
|
// reports the lost anchor: the node stops if nothing else holds it,
|
||||||
|
// and stays up while the app is still open in front of them (the UI
|
||||||
|
// anchor). The action is labelled "Stop keep-alive", not "Lock", so
|
||||||
|
// that is the behaviour it promises.
|
||||||
|
stopSelf()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
if (NodeHost.current() == null) {
|
||||||
|
// Nothing to keep alive. A notification here would be a lie.
|
||||||
|
stopSelf()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!startInForeground(intent?.getStringExtra(EXTRA_ONION).orEmpty())) {
|
||||||
|
stopSelf()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
NodeHost.onKeepAliveStarted()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
NodeHost.onKeepAliveStopped()
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return false when the system refused the foreground start, in which case
|
||||||
|
* the anchor was never taken and the node stays foreground-only.
|
||||||
|
*/
|
||||||
|
private fun startInForeground(onion: String): Boolean {
|
||||||
|
return try {
|
||||||
|
createChannel()
|
||||||
|
val notification = buildNotification(onion)
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||||
|
startForeground(
|
||||||
|
NOTIFICATION_ID,
|
||||||
|
notification,
|
||||||
|
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// API 26-33: the manifest-declared type is what the platform
|
||||||
|
// records; the three-arg overload only exists from 29.
|
||||||
|
startForeground(NOTIFICATION_ID, notification)
|
||||||
|
}
|
||||||
|
true
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
// API 31+: a start from the background throws
|
||||||
|
// ForegroundServiceStartNotAllowedException. Degrade to "the node
|
||||||
|
// lives only while the app does" instead of taking the process
|
||||||
|
// down; the roster says so on screen.
|
||||||
|
Log.w(TAG, "foreground start refused; node stays foreground-only", t)
|
||||||
|
NodeHost.onKeepAliveRefused(t.message ?: t.toString())
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createChannel() {
|
||||||
|
val manager = getSystemService(NotificationManager::class.java) ?: return
|
||||||
|
val channel = NotificationChannel(
|
||||||
|
CHANNEL_ID,
|
||||||
|
getString(R.string.keep_alive_channel_name),
|
||||||
|
// LOW: present in the shade, never a sound or a heads-up. This is a
|
||||||
|
// status light, not an alert.
|
||||||
|
NotificationManager.IMPORTANCE_LOW,
|
||||||
|
).apply {
|
||||||
|
description = getString(R.string.keep_alive_channel_description)
|
||||||
|
setShowBadge(false)
|
||||||
|
}
|
||||||
|
manager.createNotificationChannel(channel)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildNotification(onion: String): Notification {
|
||||||
|
val open = PendingIntent.getActivity(
|
||||||
|
this,
|
||||||
|
0,
|
||||||
|
Intent(this, MainActivity::class.java),
|
||||||
|
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||||
|
)
|
||||||
|
val stop = PendingIntent.getService(
|
||||||
|
this,
|
||||||
|
1,
|
||||||
|
Intent(this, KeepAliveService::class.java).setAction(ACTION_STOP),
|
||||||
|
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||||
|
)
|
||||||
|
// Never the full v3 locator: a notification body is lock-screen public.
|
||||||
|
val short = onion.take(ONION_PREFIX)
|
||||||
|
val text = if (short.isEmpty()) {
|
||||||
|
getString(R.string.keep_alive_text)
|
||||||
|
} else {
|
||||||
|
getString(R.string.keep_alive_text_onion, short)
|
||||||
|
}
|
||||||
|
return NotificationCompat.Builder(this, CHANNEL_ID)
|
||||||
|
.setSmallIcon(R.drawable.ic_stat_onion)
|
||||||
|
.setContentTitle(getString(R.string.keep_alive_title))
|
||||||
|
.setContentText(text)
|
||||||
|
.setContentIntent(open)
|
||||||
|
.addAction(0, getString(R.string.keep_alive_stop), stop)
|
||||||
|
.setCategory(NotificationCompat.CATEGORY_SERVICE)
|
||||||
|
.setPriority(NotificationCompat.PRIORITY_LOW)
|
||||||
|
.setOngoing(true)
|
||||||
|
.setOnlyAlertOnce(true)
|
||||||
|
.setShowWhen(false)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "OnionWireKeepAlive"
|
||||||
|
|
||||||
|
const val ACTION_STOP = "com.siriusdevops.onionwire.keepalive.STOP"
|
||||||
|
const val EXTRA_ONION = "onion"
|
||||||
|
|
||||||
|
private const val CHANNEL_ID = "keep-alive"
|
||||||
|
private const val NOTIFICATION_ID = 1
|
||||||
|
|
||||||
|
/** Characters of the onion address shown, prefix only. */
|
||||||
|
private const val ONION_PREFIX = 10
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Brings up the keep-alive. Must be called while the app is visible —
|
||||||
|
* an unlock is, and that is the only caller — so the API 31+
|
||||||
|
* background-start restriction does not apply.
|
||||||
|
*/
|
||||||
|
fun start(context: Context, onion: String) {
|
||||||
|
val intent = Intent(context, KeepAliveService::class.java)
|
||||||
|
.putExtra(EXTRA_ONION, onion)
|
||||||
|
try {
|
||||||
|
context.startForegroundService(intent)
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
// Same refusal as in the service, just one call earlier.
|
||||||
|
Log.w(TAG, "startForegroundService refused", t)
|
||||||
|
NodeHost.onKeepAliveRefused(t.message ?: t.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ends the keep-alive; `onDestroy()` reports the lost anchor. */
|
||||||
|
fun stop(context: Context) {
|
||||||
|
context.stopService(Intent(context, KeepAliveService::class.java))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,153 @@
|
||||||
|
package com.siriusdevops.onionwire.keepalive
|
||||||
|
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import uniffi.onionwire_sdk.Wire
|
||||||
|
import uniffi.onionwire_sdk.openWire
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How visible the keep-alive currently is, for the one line of battery honesty
|
||||||
|
* the roster shows.
|
||||||
|
*/
|
||||||
|
sealed interface KeepAliveStatus {
|
||||||
|
/** No foreground service. The node lives only while the app does. */
|
||||||
|
data object Off : KeepAliveStatus
|
||||||
|
|
||||||
|
/** A foreground service is holding the node, notification and all. */
|
||||||
|
data object On : KeepAliveStatus
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The system refused the foreground start (API 31+ background-start rules,
|
||||||
|
* an OEM battery policy). The node is still up, but it dies with the app.
|
||||||
|
*/
|
||||||
|
data class Unavailable(val reason: String) : KeepAliveStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process-wide owner of the single `Wire` node.
|
||||||
|
*
|
||||||
|
* Ownership rule: whoever opens the node hands the handle here, and **only this
|
||||||
|
* object ever calls `shutdown()` or `flush()` on it**. The ViewModel and
|
||||||
|
* [KeepAliveService] report lifecycle transitions; [NodeLifetime] decides
|
||||||
|
* whether the node survives, and this object executes that decision.
|
||||||
|
*
|
||||||
|
* That indirection is the point. `WireViewModel.onCleared()` used to shut the
|
||||||
|
* node down unconditionally, so a foreground service holding the same node
|
||||||
|
* would have been torn down by the first configuration change — or worse, the
|
||||||
|
* service would have kept a notification up for a node the UI had already
|
||||||
|
* killed. Neither side owns the node now; the policy does.
|
||||||
|
*
|
||||||
|
* Threading: every mutation runs on the main thread except the SDK call inside
|
||||||
|
* [open], which is dispatched to [Dispatchers.IO] and hops back.
|
||||||
|
*/
|
||||||
|
object NodeHost {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Teardown must outlive the object graph that asked for it: `onCleared()`
|
||||||
|
* runs *after* `viewModelScope` is already cancelled, and stopping the node
|
||||||
|
* means draining the outbox and stopping Arti, not dropping a reference.
|
||||||
|
* One process-wide scope is enough — there is one node per process.
|
||||||
|
*/
|
||||||
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
|
||||||
|
private val lifetime = NodeLifetime()
|
||||||
|
|
||||||
|
private var wire: Wire? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The in-flight teardown, if any. Re-opening has to wait for it: the old
|
||||||
|
* node holds the sqlite file and Arti's state lock until `shutdown()`
|
||||||
|
* returns, and racing it makes the new node fail to open.
|
||||||
|
*/
|
||||||
|
private var stopping: Job? = null
|
||||||
|
|
||||||
|
private val _keepAlive = MutableStateFlow<KeepAliveStatus>(KeepAliveStatus.Off)
|
||||||
|
val keepAlive: StateFlow<KeepAliveStatus> = _keepAlive.asStateFlow()
|
||||||
|
|
||||||
|
/** The live node, or null when locked. */
|
||||||
|
fun current(): Wire? = wire
|
||||||
|
|
||||||
|
/** The live node, or a hard error. Callers are UI paths that require unlock. */
|
||||||
|
fun requireOpen(): Wire = wire ?: error("locked")
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens the node and anchors it to the UI.
|
||||||
|
*
|
||||||
|
* Suspends inside Arti's bootstrap — minutes on a cold start — so this must
|
||||||
|
* never run on the main thread. Callers are `viewModelScope` coroutines.
|
||||||
|
*/
|
||||||
|
suspend fun open(home: File, passphrase: String): Wire {
|
||||||
|
stopping?.join()
|
||||||
|
val opened = withContext(Dispatchers.IO) { openWire(home.absolutePath, passphrase) }
|
||||||
|
wire = opened
|
||||||
|
_keepAlive.value = KeepAliveStatus.Off
|
||||||
|
lifetime.onOpened()
|
||||||
|
return opened
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The UI is going away: finish, task swipe, or process death. */
|
||||||
|
fun onUiDetached(): NodeAction = apply(lifetime.onUnanchored(NodeAnchor.UI))
|
||||||
|
|
||||||
|
/** The keep-alive reached the foreground with its notification. */
|
||||||
|
fun onKeepAliveStarted(): NodeAction {
|
||||||
|
_keepAlive.value = KeepAliveStatus.On
|
||||||
|
return apply(lifetime.onAnchored(NodeAnchor.KEEP_ALIVE))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The keep-alive stopped, or the system destroyed it. */
|
||||||
|
fun onKeepAliveStopped(): NodeAction {
|
||||||
|
if (_keepAlive.value is KeepAliveStatus.On) _keepAlive.value = KeepAliveStatus.Off
|
||||||
|
return apply(lifetime.onUnanchored(NodeAnchor.KEEP_ALIVE))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `startForeground()` was refused. Nothing is anchoring the node at the OS
|
||||||
|
* level, so fail over to the honest pre-existing behaviour: the node lives
|
||||||
|
* as long as the app does, and the roster says why.
|
||||||
|
*/
|
||||||
|
fun onKeepAliveRefused(reason: String): NodeAction {
|
||||||
|
_keepAlive.value = KeepAliveStatus.Unavailable(reason)
|
||||||
|
return apply(lifetime.onUnanchored(NodeAnchor.KEEP_ALIVE))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Explicit Lock, from the UI or the notification's Stop action. The caller
|
||||||
|
* stops the keep-alive first — a service that is still running would
|
||||||
|
* re-anchor a node that no longer exists.
|
||||||
|
*/
|
||||||
|
fun lock(): NodeAction = apply(lifetime.onLocked())
|
||||||
|
|
||||||
|
private fun apply(action: NodeAction): NodeAction {
|
||||||
|
when (action) {
|
||||||
|
NodeAction.Keep -> Unit
|
||||||
|
NodeAction.Flush -> scope.launch { runCatching { wire?.flush() } }
|
||||||
|
NodeAction.Stop -> stopNode()
|
||||||
|
}
|
||||||
|
return action
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stopNode() {
|
||||||
|
val dying = wire ?: return
|
||||||
|
wire = null
|
||||||
|
lifetime.onClosed()
|
||||||
|
// Best effort, both steps: teardown runs on a process-scope job after
|
||||||
|
// the UI is gone, so there is nobody to show an error to and nothing
|
||||||
|
// useful to retry. `shutdown()` drains again with a shorter budget, so
|
||||||
|
// a flush that times out is not fatal.
|
||||||
|
stopping = scope.launch {
|
||||||
|
runCatching { dying.flush() }
|
||||||
|
// A second shutdown — `lock()` and then `onCleared()`, say — lands
|
||||||
|
// here too: the SDK reports it as a typed WireException.Stopped,
|
||||||
|
// never a panic, so swallowing it is correct.
|
||||||
|
runCatching { dying.shutdown() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,99 @@
|
||||||
|
package com.siriusdevops.onionwire.keepalive
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Who currently requires the in-process Tor node to stay alive.
|
||||||
|
*
|
||||||
|
* [UI] is a live `WireViewModel`; [KEEP_ALIVE] is a running [KeepAliveService].
|
||||||
|
* Both can be present at the same time — that is the interesting case: the
|
||||||
|
* screen can go away while the keep-alive stays up, and the node must survive
|
||||||
|
* it. This enum exists so "who owns the node" is a value, not a convention.
|
||||||
|
*/
|
||||||
|
enum class NodeAnchor {
|
||||||
|
UI,
|
||||||
|
KEEP_ALIVE,
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the caller must do to the node after reporting a transition. */
|
||||||
|
sealed interface NodeAction {
|
||||||
|
/** Nothing to do; the node's fate is unchanged. */
|
||||||
|
data object Keep : NodeAction
|
||||||
|
|
||||||
|
/** Drain the outbox, leave the node published. */
|
||||||
|
data object Flush : NodeAction
|
||||||
|
|
||||||
|
/** Drain the outbox, then `shutdown()`. The node is gone. */
|
||||||
|
data object Stop : NodeAction
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pure policy for the single node's lifetime: no Android, no coroutines, no
|
||||||
|
* SDK. The ViewModel and the foreground service both report transitions here
|
||||||
|
* and execute the returned [NodeAction].
|
||||||
|
*
|
||||||
|
* The rule the whole card turns on: **the UI going away does not stop the node
|
||||||
|
* while a keep-alive anchor is held.** Before this, `WireViewModel.onCleared()`
|
||||||
|
* called `shutdown()` unconditionally, which is exactly the bug a foreground
|
||||||
|
* service would have walked into.
|
||||||
|
*
|
||||||
|
* Threading: state is mutated only from the main thread — [NodeHost] is the
|
||||||
|
* only caller, and it hops back to the main thread after the SDK's blocking
|
||||||
|
* open. There is no lock here on purpose.
|
||||||
|
*/
|
||||||
|
class NodeLifetime {
|
||||||
|
|
||||||
|
private var open = false
|
||||||
|
private val anchors = LinkedHashSet<NodeAnchor>()
|
||||||
|
|
||||||
|
/** True between [onOpened] and [onClosed]/[onLocked]. */
|
||||||
|
val isOpen: Boolean get() = open
|
||||||
|
|
||||||
|
fun anchoredBy(anchor: NodeAnchor): Boolean = anchor in anchors
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The unlock path opened a node. The UI is by definition present — the user
|
||||||
|
* typed the passphrase into it.
|
||||||
|
*/
|
||||||
|
fun onOpened(): NodeAction {
|
||||||
|
open = true
|
||||||
|
anchors.add(NodeAnchor.UI)
|
||||||
|
return NodeAction.Keep
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Teardown finished; the node no longer exists. */
|
||||||
|
fun onClosed(): NodeAction {
|
||||||
|
open = false
|
||||||
|
anchors.clear()
|
||||||
|
return NodeAction.Keep
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A keep-alive reached the foreground. */
|
||||||
|
fun onAnchored(anchor: NodeAnchor): NodeAction {
|
||||||
|
anchors.add(anchor)
|
||||||
|
return NodeAction.Keep
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An anchor went away: the UI was destroyed, or the keep-alive stopped or
|
||||||
|
* was killed. Removing the anchor first means a repeat report (the service
|
||||||
|
* action and `onDestroy()` both fire) cannot double-count.
|
||||||
|
*/
|
||||||
|
fun onUnanchored(anchor: NodeAnchor): NodeAction {
|
||||||
|
anchors.remove(anchor)
|
||||||
|
if (!open) return NodeAction.Keep
|
||||||
|
// Flush rather than Keep when another anchor remains: the process may
|
||||||
|
// be killed at any moment once the screen is gone, and the outbox is
|
||||||
|
// the whole point of surviving that.
|
||||||
|
return if (anchors.isEmpty()) NodeAction.Stop else NodeAction.Flush
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The user pressed Lock. Every anchor is dropped: a keep-alive that outlived
|
||||||
|
* an explicit lock would leave a notification pointing at a dead onion.
|
||||||
|
*/
|
||||||
|
fun onLocked(): NodeAction {
|
||||||
|
val wasOpen = open
|
||||||
|
open = false
|
||||||
|
anchors.clear()
|
||||||
|
return if (wasOpen) NodeAction.Stop else NodeAction.Keep
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -10,9 +10,10 @@ import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.itemsIndexed
|
||||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
|
|
@ -33,10 +34,15 @@ import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
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.font.FontFamily
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import uniffi.onionwire_sdk.ChatMessage
|
import uniffi.onionwire_sdk.ChatMessage
|
||||||
|
import uniffi.onionwire_sdk.OutboxRow
|
||||||
|
import uniffi.onionwire_sdk.SendState
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
|
|
@ -45,32 +51,63 @@ fun ChatScreen(
|
||||||
fingerprint: String,
|
fingerprint: String,
|
||||||
onion: String,
|
onion: String,
|
||||||
loadMessages: suspend () -> List<ChatMessage>,
|
loadMessages: suspend () -> List<ChatMessage>,
|
||||||
onSend: suspend (String) -> Unit,
|
loadOutbox: suspend () -> List<OutboxRow>,
|
||||||
|
loadMaxAttempts: suspend () -> UInt,
|
||||||
|
onSend: suspend (String) -> SendState,
|
||||||
onBack: () -> Unit,
|
onBack: () -> Unit,
|
||||||
|
/**
|
||||||
|
* Wall clock in unix seconds. `next_attempt_at` is absolute, so the
|
||||||
|
* countdown is computed here rather than baked into the store — injectable
|
||||||
|
* so a test can pin "now" instead of racing the clock.
|
||||||
|
*/
|
||||||
|
nowSeconds: () -> Long = { System.currentTimeMillis() / 1_000L },
|
||||||
) {
|
) {
|
||||||
var messages by remember { mutableStateOf<List<ChatMessage>?>(null) }
|
var messages by remember { mutableStateOf<List<ChatMessage>?>(null) }
|
||||||
|
var outbox by remember { mutableStateOf<List<OutboxRow>>(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<UInt?>(null) }
|
||||||
var draft by remember { mutableStateOf("") }
|
var draft by remember { mutableStateOf("") }
|
||||||
var pending by remember { mutableStateOf<String?>(null) }
|
var pending by remember { mutableStateOf<String?>(null) }
|
||||||
var error by remember { mutableStateOf<String?>(null) }
|
var error by remember { mutableStateOf<String?>(null) }
|
||||||
|
var notice by remember { mutableStateOf<String?>(null) }
|
||||||
val listState = rememberLazyListState()
|
val listState = rememberLazyListState()
|
||||||
|
|
||||||
// Poll: the node appends inbound messages in the background; there is no
|
// Poll: the node appends inbound messages in the background and the retry
|
||||||
// push channel into the UI in v1.
|
// 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) {
|
LaunchedEffect(Unit) {
|
||||||
|
runCatching { loadMaxAttempts() }.onSuccess { maxAttempts = it }
|
||||||
while (true) {
|
while (true) {
|
||||||
runCatching { loadMessages() }
|
runCatching { loadMessages() }
|
||||||
.onSuccess { messages = it }
|
.onSuccess { messages = it }
|
||||||
.onFailure { error = it.message ?: it.toString() }
|
.onFailure { error = it.message ?: it.toString() }
|
||||||
|
runCatching { loadOutbox() }
|
||||||
|
.onSuccess { outbox = it }
|
||||||
|
.onFailure { error = it.message ?: it.toString() }
|
||||||
delay(2_000)
|
delay(2_000)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fail-closed send. `send` retries the peer's onion for up to 3 minutes and
|
// Send. An unreachable peer's onion is not an error any more: the core
|
||||||
// then errors — nothing is spooled, so a failure is a real failure.
|
// stores the message in its local outbox and the retry worker dials again
|
||||||
|
// with backoff (30s doubling, capped at 30 min, 8 attempts, then terminal
|
||||||
|
// `failed`). A protocol error is still a real failure here — nothing is
|
||||||
|
// queued for those.
|
||||||
LaunchedEffect(pending) {
|
LaunchedEffect(pending) {
|
||||||
val body = pending ?: return@LaunchedEffect
|
val body = pending ?: return@LaunchedEffect
|
||||||
error = null
|
error = null
|
||||||
|
notice = null
|
||||||
runCatching { onSend(body) }
|
runCatching { onSend(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 { error = it.message ?: it.toString() }
|
||||||
pending = null
|
pending = null
|
||||||
}
|
}
|
||||||
|
|
@ -127,8 +164,11 @@ fun ChatScreen(
|
||||||
Text("No messages", style = MaterialTheme.typography.titleSmall)
|
Text("No messages", style = MaterialTheme.typography.titleSmall)
|
||||||
Spacer(Modifier.height(6.dp))
|
Spacer(Modifier.height(6.dp))
|
||||||
Text(
|
Text(
|
||||||
"Sends fail closed: if their onion is down the message is " +
|
"If their onion is unreachable the message is queued in a " +
|
||||||
"not spooled anywhere. There is no outbox in v1.",
|
"local outbox on this device and retried with backoff " +
|
||||||
|
"(30s doubling, up to 30 min, 8 attempts) — never handed " +
|
||||||
|
"to a third party. A queued message is local-only until " +
|
||||||
|
"their onion takes it.",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
|
|
@ -136,18 +176,45 @@ fun ChatScreen(
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
|
// The outbox rows behind the pending sends: `queued (try
|
||||||
|
// 3/8, retry 45s)` needs the store's own counters and the
|
||||||
|
// core's retry budget. With either missing, or with a join
|
||||||
|
// that cannot prove itself, the rows keep the flat state
|
||||||
|
// marker — wrong numbers would be worse than none.
|
||||||
|
val max = maxAttempts
|
||||||
|
val details = if (max == null) {
|
||||||
|
List(list.size) { null }
|
||||||
|
} else {
|
||||||
|
outboxDetails(
|
||||||
|
rows = list.map { ChatRowInput(it.direction, it.delivery) },
|
||||||
|
outbox = outbox.map {
|
||||||
|
OutboxRowInput(
|
||||||
|
messageId = it.messageId,
|
||||||
|
status = it.status,
|
||||||
|
attempts = it.attempts,
|
||||||
|
nextAttemptAt = it.nextAttemptAt,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
maxAttempts = max,
|
||||||
|
now = nowSeconds(),
|
||||||
|
)
|
||||||
|
}
|
||||||
LazyColumn(
|
LazyColumn(
|
||||||
state = listState,
|
state = listState,
|
||||||
modifier = Modifier.weight(1f).fillMaxWidth(),
|
modifier = Modifier.weight(1f).fillMaxWidth(),
|
||||||
contentPadding = PaddingValues(12.dp),
|
contentPadding = PaddingValues(12.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
) {
|
) {
|
||||||
items(list) { m ->
|
itemsIndexed(list) { i, m ->
|
||||||
val mine = m.direction == "out"
|
val mine = m.direction == "out"
|
||||||
Row(
|
Row(
|
||||||
Modifier.fillMaxWidth(),
|
Modifier.fillMaxWidth(),
|
||||||
horizontalArrangement =
|
horizontalArrangement =
|
||||||
if (mine) Arrangement.End else Arrangement.Start,
|
if (mine) Arrangement.End else Arrangement.Start,
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
horizontalAlignment = if (mine) Alignment.End
|
||||||
|
else Alignment.Start,
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
m.body,
|
m.body,
|
||||||
|
|
@ -162,11 +229,41 @@ fun ChatScreen(
|
||||||
)
|
)
|
||||||
.padding(horizontal = 10.dp, vertical = 8.dp),
|
.padding(horizontal = 10.dp, vertical = 8.dp),
|
||||||
)
|
)
|
||||||
|
parseDelivery(m.direction, m.delivery)?.let { d ->
|
||||||
|
DeliveryMarker(d, details.getOrNull(i))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Chat-level outbox state: what is still coming, and whether
|
||||||
|
// anything has terminated as failed.
|
||||||
|
val summary = outboxSummary(
|
||||||
|
messages.orEmpty().map { parseDelivery(it.direction, it.delivery) },
|
||||||
|
)
|
||||||
|
summary.note?.let { note ->
|
||||||
|
Text(
|
||||||
|
note,
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = if (summary.hasFailures) MaterialTheme.colorScheme.error
|
||||||
|
else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
modifier = Modifier
|
||||||
|
.padding(horizontal = 12.dp, vertical = 2.dp)
|
||||||
|
.testTag("outbox-summary"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
notice?.let {
|
||||||
|
Text(
|
||||||
|
it,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
error?.let {
|
error?.let {
|
||||||
Text(
|
Text(
|
||||||
|
|
@ -204,3 +301,46 @@ fun ChatScreen(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One message's delivery marker, straight from the core's outbox state.
|
||||||
|
*
|
||||||
|
* The row carries an explicit announcement so a screen reader says
|
||||||
|
* "Queued, not delivered yet: retrying their onion (try 3/8, retry 45s)"
|
||||||
|
* instead of reading a clock glyph, and a [Delivery.testTag] so a UI test can
|
||||||
|
* find the state without depending on the glyph. [detail] is the outbox row's
|
||||||
|
* own counters when the join landed; when it is `null` the row keeps the flat
|
||||||
|
* marker. `send` shows a small indeterminate spinner while the worker has an
|
||||||
|
* attempt in flight.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
private fun DeliveryMarker(d: Delivery, detail: QueuedRowDetail?) {
|
||||||
|
val tint = when (d) {
|
||||||
|
is Delivery.Failed -> MaterialTheme.colorScheme.error
|
||||||
|
Delivery.Sent -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
else -> MaterialTheme.colorScheme.primary
|
||||||
|
}
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier
|
||||||
|
.padding(horizontal = 4.dp, vertical = 1.dp)
|
||||||
|
.testTag(d.testTag)
|
||||||
|
.semantics(mergeDescendants = true) {
|
||||||
|
contentDescription = deliveryAnnouncement(d, detail)
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
if (d is Delivery.Sending) {
|
||||||
|
CircularProgressIndicator(
|
||||||
|
modifier = Modifier.size(10.dp),
|
||||||
|
strokeWidth = 1.5.dp,
|
||||||
|
color = tint,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(4.dp))
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
deliveryMarkerText(d, detail),
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = tint,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,176 @@
|
||||||
|
package com.siriusdevops.onionwire.ui
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delivery state of one outgoing chat row.
|
||||||
|
*
|
||||||
|
* The states are the core's own — `Queued` / `Sending` / `Sent` / `Failed`
|
||||||
|
* (`src/store.rs::OutboxStatus`), surfaced verbatim over UniFFI as
|
||||||
|
* `ChatMessage.delivery` (`crates/onionwire-sdk/src/lib.rs::delivery_of`, fed by
|
||||||
|
* `Node::outbox_status_of_message`). There is no parallel model here and nothing
|
||||||
|
* is inferred from a timeout: if the state is not in that string it is not
|
||||||
|
* rendered.
|
||||||
|
*
|
||||||
|
* [testTag] and [contentDescription] are the assertable handles: the Composable
|
||||||
|
* applies exactly these values, and `MessageDeliveryTest` asserts on them, so a
|
||||||
|
* change to the marker without a change to the announcement fails a test.
|
||||||
|
* A screen reader must never be left hearing a bare glyph like "clock" — that is
|
||||||
|
* why every state carries a sentence.
|
||||||
|
*/
|
||||||
|
sealed interface Delivery {
|
||||||
|
|
||||||
|
/** Stable handle for Compose semantics and tests. */
|
||||||
|
val testTag: String
|
||||||
|
|
||||||
|
/** What a screen reader announces. Always a sentence, never a glyph. */
|
||||||
|
val contentDescription: String
|
||||||
|
|
||||||
|
/** Marker drawn next to the message body. */
|
||||||
|
val glyph: String
|
||||||
|
|
||||||
|
/** Short text drawn after the glyph. Empty for a wordless state. */
|
||||||
|
val label: String
|
||||||
|
|
||||||
|
/** The frame reached the peer's onion during the send call. */
|
||||||
|
data object Sent : Delivery {
|
||||||
|
override val testTag: String = "delivery-sent"
|
||||||
|
override val contentDescription: String = "Delivered"
|
||||||
|
override val glyph: String = "✓✓"
|
||||||
|
override val label: String = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The peer's onion was unreachable: the message is in the local outbox and
|
||||||
|
* the retry worker will dial again with backoff. Local-only — not delivered.
|
||||||
|
*/
|
||||||
|
data object Queued : Delivery {
|
||||||
|
override val testTag: String = "delivery-queued"
|
||||||
|
override val contentDescription: String =
|
||||||
|
"Queued, not delivered yet: retrying their onion"
|
||||||
|
override val glyph: String = "◷"
|
||||||
|
override val label: String = "queued"
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The worker has a delivery attempt in flight right now. */
|
||||||
|
data object Sending : Delivery {
|
||||||
|
override val testTag: String = "delivery-sending"
|
||||||
|
override val contentDescription: String = "Sending"
|
||||||
|
override val glyph: String = "»"
|
||||||
|
override val label: String = "sending"
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Terminal: retries are exhausted or the failure cannot be retried. */
|
||||||
|
data class Failed(val reason: String) : Delivery {
|
||||||
|
override val testTag: String = "delivery-failed"
|
||||||
|
override val contentDescription: String = "Failed: $reason"
|
||||||
|
override val glyph: String = "✗"
|
||||||
|
override val label: String = "failed: $reason"
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `"◷ queued"`, `"✓✓"`, `"✗ failed: no route"` — the row's marker text. */
|
||||||
|
val marker: String
|
||||||
|
get() = if (label.isEmpty()) glyph else "$glyph $label"
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Longest short-form failure reason rendered in a chat row. Mirrors
|
||||||
|
* `src/tui.rs::FAIL_REASON_BUDGET` so both clients cut the same way. */
|
||||||
|
const val FAIL_REASON_BUDGET: Int = 24
|
||||||
|
|
||||||
|
private val STRIPPED: CharRange = '\u0000'..'\u001f'
|
||||||
|
private val STRIPPED_C1: CharRange = '\u007f'..'\u009f'
|
||||||
|
|
||||||
|
/** C0/C1 controls and bidi/format marks — mirrors `src/sanitize.rs`. */
|
||||||
|
internal fun isControlOrBidi(c: Char): Boolean =
|
||||||
|
c in STRIPPED || c in STRIPPED_C1 ||
|
||||||
|
c in '\u202a'..'\u202e' || c in '\u2066'..'\u2069' ||
|
||||||
|
c == '\u200e' || c == '\u200f' || c == '\u200b' || c == '\u200c'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transport failure text, short form: sanitized, tail of the `a: b: c` chain,
|
||||||
|
* capped at [budget] cells so one peer's error cannot blow out the row.
|
||||||
|
* Mirrors `src/tui.rs::short_send_reason`.
|
||||||
|
*/
|
||||||
|
fun shortSendReason(why: String, budget: Int = FAIL_REASON_BUDGET): String {
|
||||||
|
val clean = why.filterNot(::isControlOrBidi)
|
||||||
|
val tail = clean.split(": ").lastOrNull().orEmpty().trim()
|
||||||
|
val text = tail.ifEmpty { clean.trim() }
|
||||||
|
if (text.length <= budget) return text
|
||||||
|
if (budget <= 1) return "…".take(budget)
|
||||||
|
return text.take(budget - 1) + "…"
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Maps one history row onto a [Delivery], or `null` for anything that is not an
|
||||||
|
* outgoing message.
|
||||||
|
*
|
||||||
|
* [delivery] is `ChatMessage.delivery`: `"sent"`, `"queued"`, `"sending"`,
|
||||||
|
* `"failed: <reason>"`, or `null` for inbound rows. The SDK already resolves an
|
||||||
|
* outgoing row with no outbox row to `"sent"` (it was accepted on the first
|
||||||
|
* attempt), so a *missing* value on an outgoing row means the core did not
|
||||||
|
* confirm anything — and that is reported as [Delivery.Queued], never as
|
||||||
|
* delivered. Same rule for a status this build does not recognise: the only
|
||||||
|
* direction that cannot lie is "not confirmed delivered yet".
|
||||||
|
*/
|
||||||
|
fun parseDelivery(direction: String, delivery: String?): Delivery? {
|
||||||
|
if (direction != "out") return null
|
||||||
|
return when (val raw = delivery?.trim().orEmpty()) {
|
||||||
|
"" -> Delivery.Queued
|
||||||
|
"sent" -> Delivery.Sent
|
||||||
|
"sending" -> Delivery.Sending
|
||||||
|
"queued" -> Delivery.Queued
|
||||||
|
else ->
|
||||||
|
if (raw.startsWith("failed")) {
|
||||||
|
val why = raw.substringAfter(':', "").trim().ifEmpty { "unknown" }
|
||||||
|
Delivery.Failed(shortSendReason(why))
|
||||||
|
} else {
|
||||||
|
Delivery.Queued
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Chat-level delivery summary derived from the rendered rows.
|
||||||
|
*
|
||||||
|
* Mirrors `src/tui.rs::OutboxSummary`: `Queued` + `Sending` are "still coming",
|
||||||
|
* `Failed` is terminal and keeps a fail-closed statement on screen.
|
||||||
|
*/
|
||||||
|
data class OutboxSummary(
|
||||||
|
val queued: Int = 0,
|
||||||
|
val failed: Int = 0,
|
||||||
|
val firstError: String? = null,
|
||||||
|
) {
|
||||||
|
/** Footer note, or `null` when nothing is outstanding. */
|
||||||
|
val note: String?
|
||||||
|
get() {
|
||||||
|
val reason = shortSendReason(firstError ?: "unknown")
|
||||||
|
return when {
|
||||||
|
queued == 0 && failed == 0 -> null
|
||||||
|
failed == 0 -> "$queued queued"
|
||||||
|
queued == 0 && failed == 1 -> "send failed: $reason"
|
||||||
|
queued == 0 -> "send failed: $reason ($failed failed)"
|
||||||
|
else -> "$queued queued, send failed: $reason"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `true` when at least one send has terminated as failed. */
|
||||||
|
val hasFailures: Boolean get() = failed > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Summarizes the rows currently on screen. */
|
||||||
|
fun outboxSummary(deliveries: Iterable<Delivery?>): OutboxSummary {
|
||||||
|
var queued = 0
|
||||||
|
var failed = 0
|
||||||
|
var firstError: String? = null
|
||||||
|
for (d in deliveries) {
|
||||||
|
when (d) {
|
||||||
|
null, Delivery.Sent -> Unit
|
||||||
|
|
||||||
|
is Delivery.Failed -> {
|
||||||
|
failed++
|
||||||
|
if (firstError == null) firstError = d.reason
|
||||||
|
}
|
||||||
|
|
||||||
|
Delivery.Queued, Delivery.Sending -> queued++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return OutboxSummary(queued = queued, failed = failed, firstError = firstError)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,141 @@
|
||||||
|
package com.siriusdevops.onionwire.ui
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Why a chat row is still queued, read from the SDK's outbox rows
|
||||||
|
* (`Wire.outbox(pubkeyHex)` → `OutboxRow { messageId, status, attempts,
|
||||||
|
* nextAttemptAt, lastError }`).
|
||||||
|
*
|
||||||
|
* [Delivery] answers *what* state a row is in; this file answers *how far along*
|
||||||
|
* it is — `queued (try 3/8, retry 45s)` — from the store's own counters, never
|
||||||
|
* from a time the app invented. Mirrors `src/tui.rs::retry_in_text` /
|
||||||
|
* `delivery_tag` so both clients word the same state the same way.
|
||||||
|
*
|
||||||
|
* Nothing here is Android-specific: the join and the wording are pure functions
|
||||||
|
* so `OutboxDetailTest` can assert them on the JVM without a device or the
|
||||||
|
* native binding.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Next-attempt age for a queued row, from the absolute `next_attempt_at` the
|
||||||
|
* store holds. Mirrors `src/tui.rs::retry_in_text`:
|
||||||
|
* `<= 0` → `retry now`; `< 60` → `retry {n}s`; else → `retry {ceil-minutes}m`.
|
||||||
|
*/
|
||||||
|
fun retryInText(nextInSecs: Long): String = when {
|
||||||
|
nextInSecs <= 0L -> "retry now"
|
||||||
|
nextInSecs < 60L -> "retry ${nextInSecs}s"
|
||||||
|
else -> "retry ${(nextInSecs + 59L) / 60L}m"
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The outbox row's own numbers for one queued chat row.
|
||||||
|
*
|
||||||
|
* Only `"queued"` rows produce one: a terminal `"failed"` row keeps the last
|
||||||
|
* time it was *scheduled* for, so rendering it as a countdown would be a lie —
|
||||||
|
* a failed row is rendered from [Delivery.Failed] alone. `"sending"` has an
|
||||||
|
* attempt in flight and no next-attempt time worth showing, matching the TUI's
|
||||||
|
* bare `sending` tag.
|
||||||
|
*/
|
||||||
|
data class QueuedRowDetail(
|
||||||
|
val attempts: UInt,
|
||||||
|
val maxAttempts: UInt,
|
||||||
|
val nextInSecs: Long,
|
||||||
|
) {
|
||||||
|
/** `queued (try 3/8, retry 45s)` — the row text, mirroring the TUI. */
|
||||||
|
val text: String = "queued (try $attempts/$maxAttempts, ${retryInText(nextInSecs)})"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `try 3/8, retry 45s` — the same numbers without the state word, for a
|
||||||
|
* screen reader that has already heard "Queued, not delivered yet".
|
||||||
|
*/
|
||||||
|
val announcement: String = "try $attempts/$maxAttempts, ${retryInText(nextInSecs)}"
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One SDK `ChatMessage`, narrowed to the fields the join reads. */
|
||||||
|
data class ChatRowInput(val direction: String, val delivery: String?)
|
||||||
|
|
||||||
|
/** One SDK `OutboxRow`, narrowed to the fields the join reads. */
|
||||||
|
data class OutboxRowInput(
|
||||||
|
val messageId: Long,
|
||||||
|
val status: String,
|
||||||
|
val attempts: UInt,
|
||||||
|
val nextAttemptAt: Long,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** The store's own three pending encodings, trimmed and lowercased. */
|
||||||
|
private fun outboxKind(status: String): String? = when (val s = status.trim().lowercase()) {
|
||||||
|
"queued", "sending", "failed" -> s
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The same kind, read off the status the SDK already resolved for the message. */
|
||||||
|
private fun deliveryKind(d: Delivery?): String? = when (d) {
|
||||||
|
Delivery.Queued -> "queued"
|
||||||
|
Delivery.Sending -> "sending"
|
||||||
|
is Delivery.Failed -> "failed"
|
||||||
|
Delivery.Sent, null -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The SDK's `OutboxRow.message_id` is `messages.id` — the key the chat list is
|
||||||
|
* ordered by. The SDK's `ChatMessage` does not carry that id yet, so this join
|
||||||
|
* is positional: `messages()` is `ORDER BY m.id` and the outbox rows are one
|
||||||
|
* per pending send, so the *n*th pending chat row owns the *n*th outbox row
|
||||||
|
* (rows are sorted by `messageId` to make that explicit rather than trusting the
|
||||||
|
* core's row order).
|
||||||
|
*
|
||||||
|
* A positional join is only allowed to speak when it can prove itself: if the
|
||||||
|
* counts disagree, if a row carries a status this build does not know, or if a
|
||||||
|
* row's status does not match the status the SDK already resolved for the
|
||||||
|
* message in that slot, *every* detail is dropped and the rows fall back to the
|
||||||
|
* flat `queued` / `sending` / `failed` markers. Wrong numbers are worse than
|
||||||
|
* none. (`ChatMessage.id` would remove the positional part entirely; tracked
|
||||||
|
* as follow-up work.)
|
||||||
|
*
|
||||||
|
* Returns one entry per input row, `null` wherever there is nothing to add.
|
||||||
|
*/
|
||||||
|
fun outboxDetails(
|
||||||
|
rows: List<ChatRowInput>,
|
||||||
|
outbox: List<OutboxRowInput>,
|
||||||
|
maxAttempts: UInt,
|
||||||
|
now: Long,
|
||||||
|
): List<QueuedRowDetail?> {
|
||||||
|
val none: List<QueuedRowDetail?> = List(rows.size) { null }
|
||||||
|
|
||||||
|
val pending = rows.indices.filter {
|
||||||
|
deliveryKind(parseDelivery(rows[it].direction, rows[it].delivery)) != null
|
||||||
|
}
|
||||||
|
val ordered = outbox.sortedBy { it.messageId }
|
||||||
|
if (pending.size != ordered.size) return none
|
||||||
|
|
||||||
|
val details = arrayOfNulls<QueuedRowDetail>(rows.size)
|
||||||
|
for ((slot, index) in pending.withIndex()) {
|
||||||
|
val row = ordered[slot]
|
||||||
|
val kind = outboxKind(row.status) ?: return none
|
||||||
|
if (kind != deliveryKind(parseDelivery(rows[index].direction, rows[index].delivery))) {
|
||||||
|
return none
|
||||||
|
}
|
||||||
|
if (kind == "queued") {
|
||||||
|
details[index] = QueuedRowDetail(
|
||||||
|
attempts = row.attempts,
|
||||||
|
maxAttempts = maxAttempts,
|
||||||
|
nextInSecs = row.nextAttemptAt - now,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return details.toList()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Marker text for one row: the outbox row's own numbers when the join landed,
|
||||||
|
* otherwise the flat state marker `MessageDelivery` already produced.
|
||||||
|
*/
|
||||||
|
fun deliveryMarkerText(d: Delivery, detail: QueuedRowDetail?): String =
|
||||||
|
if (detail == null) d.marker else "${d.glyph} ${detail.text}"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a screen reader announces for one row. The detail is appended to the
|
||||||
|
* sentence [Delivery] carries, never replaces it: a bare `try 3/8` is not a
|
||||||
|
* sentence.
|
||||||
|
*/
|
||||||
|
fun deliveryAnnouncement(d: Delivery, detail: QueuedRowDetail?): String =
|
||||||
|
if (detail == null) d.contentDescription else "${d.contentDescription} (${detail.announcement})"
|
||||||
|
|
@ -40,6 +40,7 @@ fun RosterScreen(
|
||||||
onion: String,
|
onion: String,
|
||||||
sdkVersion: String,
|
sdkVersion: String,
|
||||||
friends: List<FriendInfo>,
|
friends: List<FriendInfo>,
|
||||||
|
keepAliveNote: String?,
|
||||||
onOpenChat: (FriendInfo) -> Unit,
|
onOpenChat: (FriendInfo) -> Unit,
|
||||||
onShare: () -> Unit,
|
onShare: () -> Unit,
|
||||||
onPaste: () -> Unit,
|
onPaste: () -> Unit,
|
||||||
|
|
@ -82,6 +83,14 @@ fun RosterScreen(
|
||||||
style = MaterialTheme.typography.labelSmall,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
|
if (keepAliveNote != null) {
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
Text(
|
||||||
|
keepAliveNote,
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -223,7 +223,9 @@ fun UnlockScreen(
|
||||||
|
|
||||||
Spacer(Modifier.height(24.dp))
|
Spacer(Modifier.height(24.dp))
|
||||||
Text(
|
Text(
|
||||||
"INTERNET is the only permission this app requests.",
|
"Permissions: internet, plus a foreground service and its notification so " +
|
||||||
|
"the onion stays reachable while the screen is off. No camera, contacts " +
|
||||||
|
"or storage.",
|
||||||
style = MaterialTheme.typography.labelSmall,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
|
|
|
||||||
17
android/app/src/main/res/drawable/ic_stat_onion.xml
Normal file
17
android/app/src/main/res/drawable/ic_stat_onion.xml
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!--
|
||||||
|
Status-bar icon for the keep-alive notification. Notification icons are
|
||||||
|
alpha masks, so this is a flat white silhouette: an onion bulb with a sprout.
|
||||||
|
-->
|
||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="24dp"
|
||||||
|
android:height="24dp"
|
||||||
|
android:viewportWidth="24"
|
||||||
|
android:viewportHeight="24">
|
||||||
|
<path
|
||||||
|
android:fillColor="#FFFFFFFF"
|
||||||
|
android:pathData="M12,2.6c-0.7,1.2 -1.1,2.3 -1.1,3.2 0,0.5 0.5,0.9 1.1,0.9s1.1,-0.4 1.1,-0.9c0,-0.9 -0.4,-2 -1.1,-3.2z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#FFFFFFFF"
|
||||||
|
android:pathData="M12,6.4c-2.2,2 -3.6,4.6 -3.6,7.3 0,3.9 1.6,7.3 3.6,7.3s3.6,-3.4 3.6,-7.3c0,-2.7 -1.4,-5.3 -3.6,-7.3zM12,8.2c1.1,1.3 2.1,3 2.1,5.5 0,1.5 -0.5,2.9 -1,3.3 -0.6,-0.4 -1.1,-1.8 -1.1,-3.3 0,-2.5 1,-4.2 2.1,-5.5z" />
|
||||||
|
</vector>
|
||||||
|
|
@ -1,4 +1,20 @@
|
||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources>
|
<resources>
|
||||||
<string name="app_name">OnionWire</string>
|
<string name="app_name">OnionWire</string>
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Foreground keep-alive. The notification text is the only place the user
|
||||||
|
can see what is still running once the screen is off, so it names the
|
||||||
|
moving parts instead of saying "running in the background".
|
||||||
|
-->
|
||||||
|
<string name="keep_alive_channel_name">Node keep-alive</string>
|
||||||
|
<string name="keep_alive_channel_description">Shown while OnionWire keeps your onion address reachable in the background.</string>
|
||||||
|
<string name="keep_alive_title">OnionWire is reachable</string>
|
||||||
|
<string name="keep_alive_text">Tor and the outbox are running so peers can deliver messages.</string>
|
||||||
|
<string name="keep_alive_text_onion">Tor and the outbox are running so peers can reach %1$s…</string>
|
||||||
|
<string name="keep_alive_stop">Stop keep-alive</string>
|
||||||
|
<string name="keep_alive_note_off">Reachable only while this app is open.</string>
|
||||||
|
<string name="keep_alive_note_on">Kept alive — Tor and the outbox run until you tap Lock.</string>
|
||||||
|
<string name="keep_alive_note_hidden">Kept alive, but notifications are blocked, so the status notice is hidden. Android still lists the service in the Task Manager.</string>
|
||||||
|
<string name="keep_alive_note_unavailable">Not kept alive (%1$s). The node stops when the app does.</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,130 @@
|
||||||
|
package com.siriusdevops.onionwire.keepalive
|
||||||
|
|
||||||
|
import com.siriusdevops.onionwire.keepalive.NodeAction.Flush
|
||||||
|
import com.siriusdevops.onionwire.keepalive.NodeAction.Keep
|
||||||
|
import com.siriusdevops.onionwire.keepalive.NodeAction.Stop
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The service-lifetime state machine, no device required: [NodeLifetime] is
|
||||||
|
* pure. Every case here is a transition the app actually produces — unlock,
|
||||||
|
* background, task swipe, notification Stop, explicit Lock, re-unlock.
|
||||||
|
*/
|
||||||
|
class NodeLifetimeTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun ui_detach_with_no_keep_alive_stops_the_node() {
|
||||||
|
val l = NodeLifetime()
|
||||||
|
l.onOpened()
|
||||||
|
|
||||||
|
assertEquals(Stop, l.onUnanchored(NodeAnchor.UI))
|
||||||
|
assertTrue(l.isOpen) // the caller still has to run flush+shutdown
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun keep_alive_anchor_survives_ui_detach_and_only_flushes() {
|
||||||
|
val l = NodeLifetime()
|
||||||
|
l.onOpened()
|
||||||
|
l.onAnchored(NodeAnchor.KEEP_ALIVE)
|
||||||
|
|
||||||
|
// Task swiped: the activity is gone, the service is not.
|
||||||
|
assertEquals(Flush, l.onUnanchored(NodeAnchor.UI))
|
||||||
|
assertFalse(l.anchoredBy(NodeAnchor.UI))
|
||||||
|
assertTrue(l.anchoredBy(NodeAnchor.KEEP_ALIVE))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun losing_the_last_anchor_stops_the_node() {
|
||||||
|
val l = NodeLifetime()
|
||||||
|
l.onOpened()
|
||||||
|
l.onAnchored(NodeAnchor.KEEP_ALIVE)
|
||||||
|
l.onUnanchored(NodeAnchor.UI)
|
||||||
|
|
||||||
|
// Notification Stop, or the system killing the service.
|
||||||
|
assertEquals(Stop, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun service_stopping_while_the_ui_is_up_keeps_the_node() {
|
||||||
|
val l = NodeLifetime()
|
||||||
|
l.onOpened()
|
||||||
|
l.onAnchored(NodeAnchor.KEEP_ALIVE)
|
||||||
|
|
||||||
|
assertEquals(Flush, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
|
||||||
|
assertTrue(l.anchoredBy(NodeAnchor.UI))
|
||||||
|
assertTrue(l.isOpen)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun repeated_anchor_loss_is_idempotent() {
|
||||||
|
val l = NodeLifetime()
|
||||||
|
l.onOpened()
|
||||||
|
l.onAnchored(NodeAnchor.KEEP_ALIVE)
|
||||||
|
l.onUnanchored(NodeAnchor.UI)
|
||||||
|
|
||||||
|
// The Stop action and onDestroy both report the same loss.
|
||||||
|
assertEquals(Stop, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
|
||||||
|
l.onClosed()
|
||||||
|
assertEquals(Keep, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun lock_drops_every_anchor() {
|
||||||
|
val l = NodeLifetime()
|
||||||
|
l.onOpened()
|
||||||
|
l.onAnchored(NodeAnchor.KEEP_ALIVE)
|
||||||
|
|
||||||
|
assertEquals(Stop, l.onLocked())
|
||||||
|
assertFalse(l.isOpen)
|
||||||
|
assertFalse(l.anchoredBy(NodeAnchor.KEEP_ALIVE))
|
||||||
|
assertFalse(l.anchoredBy(NodeAnchor.UI))
|
||||||
|
l.onClosed()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun re_unlock_after_lock_starts_from_a_clean_slate() {
|
||||||
|
val l = NodeLifetime()
|
||||||
|
l.onOpened()
|
||||||
|
l.onAnchored(NodeAnchor.KEEP_ALIVE)
|
||||||
|
l.onLocked()
|
||||||
|
l.onClosed()
|
||||||
|
|
||||||
|
// Second unlock: only the UI anchors, so backgrounding really stops.
|
||||||
|
assertEquals(Keep, l.onOpened())
|
||||||
|
assertFalse(l.anchoredBy(NodeAnchor.KEEP_ALIVE))
|
||||||
|
assertEquals(Stop, l.onUnanchored(NodeAnchor.UI))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun re_unlock_while_the_keep_alive_still_holds_the_node_adopts_it() {
|
||||||
|
// Process relaunch with the service still up: the ViewModel adopts the
|
||||||
|
// live node and never calls onOpened(), so the KEEP_ALIVE anchor (and
|
||||||
|
// the node) is untouched by the new UI attaching.
|
||||||
|
val l = NodeLifetime()
|
||||||
|
l.onOpened()
|
||||||
|
l.onAnchored(NodeAnchor.KEEP_ALIVE)
|
||||||
|
l.onUnanchored(NodeAnchor.UI)
|
||||||
|
|
||||||
|
assertTrue(l.isOpen)
|
||||||
|
assertTrue(l.anchoredBy(NodeAnchor.KEEP_ALIVE))
|
||||||
|
assertFalse(l.anchoredBy(NodeAnchor.UI))
|
||||||
|
|
||||||
|
// The adopted UI leaves again: still flush, still alive.
|
||||||
|
assertEquals(Flush, l.onUnanchored(NodeAnchor.UI))
|
||||||
|
assertTrue(l.isOpen)
|
||||||
|
assertEquals(Stop, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun transitions_on_a_closed_node_do_nothing() {
|
||||||
|
val l = NodeLifetime()
|
||||||
|
|
||||||
|
assertEquals(Keep, l.onUnanchored(NodeAnchor.UI))
|
||||||
|
assertEquals(Keep, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
|
||||||
|
assertEquals(Keep, l.onLocked())
|
||||||
|
assertEquals(Keep, l.onAnchored(NodeAnchor.KEEP_ALIVE)) // service up, still locked
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,180 @@
|
||||||
|
package com.siriusdevops.onionwire.ui
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders each of the four core outbox states and asserts the semantic the
|
||||||
|
* Composable applies for it — the same `testTag` / `contentDescription` values
|
||||||
|
* `ChatScreen`'s delivery row uses, so a marker change without an announcement
|
||||||
|
* change fails here.
|
||||||
|
*
|
||||||
|
* `compose.ui.test` is not on the JVM unit-test classpath (and adding it is
|
||||||
|
* outside this card's scope), so the assertion target is the state model that
|
||||||
|
* the Composable renders from, not a laid-out node. Same shape as
|
||||||
|
* `InviteAddFlowTest`.
|
||||||
|
*/
|
||||||
|
class MessageDeliveryTest {
|
||||||
|
|
||||||
|
private val glyphs = listOf("✓", "◷", "»", "✗")
|
||||||
|
|
||||||
|
private fun out(delivery: String?) = parseDelivery("out", delivery)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun every_core_state_is_rendered_with_its_own_handle_and_sentence() {
|
||||||
|
val sent = requireNotNull(out("sent"))
|
||||||
|
val queued = requireNotNull(out("queued"))
|
||||||
|
val sending = requireNotNull(out("sending"))
|
||||||
|
val failed = requireNotNull(out("failed: connection timed out"))
|
||||||
|
|
||||||
|
assertEquals(Delivery.Sent, sent)
|
||||||
|
assertEquals(Delivery.Queued, queued)
|
||||||
|
assertEquals(Delivery.Sending, sending)
|
||||||
|
assertEquals(Delivery.Failed("connection timed out"), failed)
|
||||||
|
|
||||||
|
assertEquals("delivery-sent", sent.testTag)
|
||||||
|
assertEquals("delivery-queued", queued.testTag)
|
||||||
|
assertEquals("delivery-sending", sending.testTag)
|
||||||
|
assertEquals("delivery-failed", failed.testTag)
|
||||||
|
|
||||||
|
assertEquals("Delivered", sent.contentDescription)
|
||||||
|
assertEquals("Queued, not delivered yet: retrying their onion", queued.contentDescription)
|
||||||
|
assertEquals("Sending", sending.contentDescription)
|
||||||
|
assertEquals("Failed: connection timed out", failed.contentDescription)
|
||||||
|
|
||||||
|
// Four states, four distinct handles and four distinct sentences.
|
||||||
|
val all = listOf(sent, queued, sending, failed)
|
||||||
|
assertEquals(4, all.map { it.testTag }.toSet().size)
|
||||||
|
assertEquals(4, all.map { it.contentDescription }.toSet().size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun markers_are_visually_distinct_per_state() {
|
||||||
|
assertEquals("✓✓", Delivery.Sent.marker)
|
||||||
|
assertEquals("◷ queued", Delivery.Queued.marker)
|
||||||
|
assertEquals("» sending", Delivery.Sending.marker)
|
||||||
|
assertEquals("✗ failed: no route", Delivery.Failed("no route").marker)
|
||||||
|
|
||||||
|
val all = listOf(
|
||||||
|
Delivery.Sent.marker,
|
||||||
|
Delivery.Queued.marker,
|
||||||
|
Delivery.Sending.marker,
|
||||||
|
Delivery.Failed("no route").marker,
|
||||||
|
)
|
||||||
|
assertEquals(4, all.toSet().size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun every_state_announces_words_not_a_bare_glyph() {
|
||||||
|
val all = listOf(
|
||||||
|
Delivery.Sent,
|
||||||
|
Delivery.Queued,
|
||||||
|
Delivery.Sending,
|
||||||
|
Delivery.Failed("no route"),
|
||||||
|
)
|
||||||
|
for (d in all) {
|
||||||
|
for (glyph in glyphs) {
|
||||||
|
assertFalse(
|
||||||
|
"${d.testTag} announces a glyph: ${d.contentDescription}",
|
||||||
|
d.contentDescription.contains(glyph),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
assertTrue(
|
||||||
|
"${d.testTag} must announce words, not an icon name: ${d.contentDescription}",
|
||||||
|
d.contentDescription.length >= 7 && d.contentDescription.any { it.isLetter() },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun failed_reason_is_sanitized_tailed_and_capped_like_the_tui() {
|
||||||
|
// C0 controls and bidi marks are stripped.
|
||||||
|
assertEquals("badsignature", shortSendReason("bad\u0007\u202esignature"))
|
||||||
|
// Tail of the `a: b: c` chain.
|
||||||
|
assertEquals(
|
||||||
|
"connection timed out",
|
||||||
|
shortSendReason("dial 7f4k.onion: onion: connection timed out"),
|
||||||
|
)
|
||||||
|
// Capped at the row budget, with the ellipsis inside it.
|
||||||
|
val long = "x".repeat(80)
|
||||||
|
val cut = shortSendReason(long)
|
||||||
|
assertEquals(FAIL_REASON_BUDGET, cut.length)
|
||||||
|
assertTrue(cut.endsWith("…"))
|
||||||
|
assertEquals(long, shortSendReason(long, budget = 80))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun an_unrecognised_status_is_queued_never_delivered() {
|
||||||
|
// A status this build does not know must not read as delivered.
|
||||||
|
assertEquals(Delivery.Queued, out("spooling"))
|
||||||
|
assertEquals(Delivery.Queued, out("SENDING"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun a_missing_delivery_on_an_outgoing_row_is_not_called_delivered() {
|
||||||
|
// The SDK reports "sent" explicitly for an outgoing row with no outbox
|
||||||
|
// row, so a missing value means nothing was confirmed.
|
||||||
|
assertEquals(Delivery.Queued, out(null))
|
||||||
|
assertEquals(Delivery.Queued, out(" "))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun the_core_reporting_sent_is_the_only_way_to_render_delivered() {
|
||||||
|
assertEquals(Delivery.Sent, out("sent"))
|
||||||
|
assertEquals(Delivery.Sent, out(" sent "))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun inbound_rows_carry_no_delivery_state() {
|
||||||
|
assertNull(parseDelivery("in", null))
|
||||||
|
assertNull(parseDelivery("in", "sent"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun blank_failure_reason_still_says_failed() {
|
||||||
|
val d = out("failed:") as Delivery.Failed
|
||||||
|
assertEquals("unknown", d.reason)
|
||||||
|
assertEquals("Failed: unknown", d.contentDescription)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun footer_reports_pending_sends_and_keeps_a_failure_statement() {
|
||||||
|
// Nothing outstanding: no note at all.
|
||||||
|
assertNull(outboxSummary(listOf(Delivery.Sent, null)).note)
|
||||||
|
|
||||||
|
// Anything still coming is counted, queued and sending alike.
|
||||||
|
assertEquals(
|
||||||
|
"2 queued",
|
||||||
|
outboxSummary(listOf(Delivery.Queued, Delivery.Sending, Delivery.Sent)).note,
|
||||||
|
)
|
||||||
|
|
||||||
|
// A terminal failure is stated, not hidden behind the queue count.
|
||||||
|
val withFailure = outboxSummary(listOf(Delivery.Queued, Delivery.Failed("no route")))
|
||||||
|
assertEquals(1, withFailure.queued)
|
||||||
|
assertEquals(1, withFailure.failed)
|
||||||
|
assertTrue(withFailure.hasFailures)
|
||||||
|
assertEquals("1 queued, send failed: no route", withFailure.note)
|
||||||
|
|
||||||
|
// No queue, one failure.
|
||||||
|
assertEquals(
|
||||||
|
"send failed: no route",
|
||||||
|
outboxSummary(listOf(Delivery.Failed("no route"))).note,
|
||||||
|
)
|
||||||
|
// No queue, several failures: first reason plus how many.
|
||||||
|
assertEquals(
|
||||||
|
"send failed: no route (3 failed)",
|
||||||
|
outboxSummary(
|
||||||
|
listOf(
|
||||||
|
Delivery.Failed("no route"),
|
||||||
|
Delivery.Failed("timeout"),
|
||||||
|
Delivery.Failed("bad identity"),
|
||||||
|
),
|
||||||
|
).note,
|
||||||
|
)
|
||||||
|
// Nothing pending and nothing failed: silent.
|
||||||
|
assertFalse(outboxSummary(listOf(Delivery.Sent)).hasFailures)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,278 @@
|
||||||
|
package com.siriusdevops.onionwire.ui
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The SDK's outbox rows turned into chat-row wording: `queued (try 3/8, retry
|
||||||
|
* 45s)`.
|
||||||
|
*
|
||||||
|
* These assert the pure model `ChatScreen` renders from — the same shape as
|
||||||
|
* `MessageDeliveryTest` — so the retry wording, the fail-closed join and the
|
||||||
|
* "a failed row never shows a countdown" rule are all covered on the JVM
|
||||||
|
* without a device.
|
||||||
|
*/
|
||||||
|
class OutboxDetailTest {
|
||||||
|
|
||||||
|
private fun out(delivery: String?) = ChatRowInput("out", delivery)
|
||||||
|
|
||||||
|
private fun row(
|
||||||
|
messageId: Long,
|
||||||
|
status: String,
|
||||||
|
attempts: UInt = 0u,
|
||||||
|
nextAttemptAt: Long = 0L,
|
||||||
|
) = OutboxRowInput(messageId, status, attempts, nextAttemptAt)
|
||||||
|
|
||||||
|
// --- retry_in_text: the three buckets, mirroring src/tui.rs -------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun retry_in_text_is_now_at_or_before_the_next_attempt_time() {
|
||||||
|
assertEquals("retry now", retryInText(0L))
|
||||||
|
assertEquals("retry now", retryInText(-45L))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun retry_in_text_counts_seconds_below_a_minute() {
|
||||||
|
assertEquals("retry 1s", retryInText(1L))
|
||||||
|
assertEquals("retry 45s", retryInText(45L))
|
||||||
|
assertEquals("retry 59s", retryInText(59L))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun retry_in_text_rounds_minutes_up_from_the_first_minute() {
|
||||||
|
// 60s is one minute, not "retry 1s" and not "retry 0m".
|
||||||
|
assertEquals("retry 1m", retryInText(60L))
|
||||||
|
// Anything over the boundary rounds up, so the app never promises an
|
||||||
|
// attempt sooner than the store will make one.
|
||||||
|
assertEquals("retry 2m", retryInText(61L))
|
||||||
|
assertEquals("retry 10m", retryInText(600L))
|
||||||
|
assertEquals("retry 25m", retryInText(1500L))
|
||||||
|
// The core's backoff caps at 30 minutes.
|
||||||
|
assertEquals("retry 30m", retryInText(1800L))
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- the queued row's own numbers ---------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun a_queued_row_renders_the_tui_wording() {
|
||||||
|
val details = outboxDetails(
|
||||||
|
rows = listOf(out("queued")),
|
||||||
|
outbox = listOf(row(7L, "queued", attempts = 3u, nextAttemptAt = 1_000L + 45L)),
|
||||||
|
maxAttempts = 8u,
|
||||||
|
now = 1_000L,
|
||||||
|
)
|
||||||
|
val detail = requireNotNull(details.single())
|
||||||
|
assertEquals("queued (try 3/8, retry 45s)", detail.text)
|
||||||
|
assertEquals("◷ queued (try 3/8, retry 45s)", deliveryMarkerText(Delivery.Queued, detail))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun the_denominator_comes_from_the_core_not_a_constant_here() {
|
||||||
|
val detail = requireNotNull(
|
||||||
|
outboxDetails(
|
||||||
|
rows = listOf(out("queued")),
|
||||||
|
outbox = listOf(row(1L, "queued", attempts = 3u, nextAttemptAt = 0L)),
|
||||||
|
maxAttempts = 12u,
|
||||||
|
now = 0L,
|
||||||
|
).single(),
|
||||||
|
)
|
||||||
|
assertEquals("queued (try 3/12, retry now)", detail.text)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun an_overdue_attempt_reads_retry_now() {
|
||||||
|
val detail = requireNotNull(
|
||||||
|
outboxDetails(
|
||||||
|
rows = listOf(out("queued")),
|
||||||
|
outbox = listOf(row(1L, "queued", attempts = 1u, nextAttemptAt = 900L)),
|
||||||
|
maxAttempts = 8u,
|
||||||
|
now = 1_000L,
|
||||||
|
).single(),
|
||||||
|
)
|
||||||
|
assertEquals("queued (try 1/8, retry now)", detail.text)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun the_countdown_is_computed_from_the_absolute_time_the_store_holds() {
|
||||||
|
val first = requireNotNull(
|
||||||
|
outboxDetails(
|
||||||
|
rows = listOf(out("queued")),
|
||||||
|
outbox = listOf(row(1L, "queued", attempts = 2u, nextAttemptAt = 1_000L + 600L)),
|
||||||
|
maxAttempts = 8u,
|
||||||
|
now = 1_000L,
|
||||||
|
).single(),
|
||||||
|
)
|
||||||
|
assertEquals("queued (try 2/8, retry 10m)", first.text)
|
||||||
|
|
||||||
|
// Same row, one minute later: the wording moves with `now`.
|
||||||
|
val later = requireNotNull(
|
||||||
|
outboxDetails(
|
||||||
|
rows = listOf(out("queued")),
|
||||||
|
outbox = listOf(row(1L, "queued", attempts = 2u, nextAttemptAt = 1_000L + 600L)),
|
||||||
|
maxAttempts = 8u,
|
||||||
|
now = 1_060L,
|
||||||
|
).single(),
|
||||||
|
)
|
||||||
|
assertEquals("queued (try 2/8, retry 9m)", later.text)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- the states that must not show a countdown --------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun a_failed_row_shows_no_countdown() {
|
||||||
|
// A terminal row keeps the last time it was scheduled for. Rendering
|
||||||
|
// that as "retry 15m" would promise an attempt that will never happen.
|
||||||
|
val details = outboxDetails(
|
||||||
|
rows = listOf(out("failed: connection timed out")),
|
||||||
|
outbox = listOf(row(4L, "failed", attempts = 8u, nextAttemptAt = 1_900L)),
|
||||||
|
maxAttempts = 8u,
|
||||||
|
now = 1_000L,
|
||||||
|
)
|
||||||
|
assertNull(details.single())
|
||||||
|
|
||||||
|
val d = requireNotNull(parseDelivery("out", "failed: connection timed out"))
|
||||||
|
assertEquals("✗ failed: connection timed out", deliveryMarkerText(d, details.single()))
|
||||||
|
assertEquals("Failed: connection timed out", deliveryAnnouncement(d, details.single()))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun a_sending_row_shows_no_countdown() {
|
||||||
|
val details = outboxDetails(
|
||||||
|
rows = listOf(out("sending")),
|
||||||
|
outbox = listOf(row(4L, "sending", attempts = 2u, nextAttemptAt = 1_900L)),
|
||||||
|
maxAttempts = 8u,
|
||||||
|
now = 1_000L,
|
||||||
|
)
|
||||||
|
assertNull(details.single())
|
||||||
|
|
||||||
|
val d = requireNotNull(parseDelivery("out", "sending"))
|
||||||
|
assertEquals("» sending", deliveryMarkerText(d, details.single()))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun delivered_and_inbound_rows_never_take_an_outbox_row() {
|
||||||
|
// No outbox rows at all: an accepted send and an inbound row are quiet.
|
||||||
|
val details = outboxDetails(
|
||||||
|
rows = listOf(ChatRowInput("in", null), out("sent")),
|
||||||
|
outbox = emptyList(),
|
||||||
|
maxAttempts = 8u,
|
||||||
|
now = 1_000L,
|
||||||
|
)
|
||||||
|
assertEquals(listOf(null, null), details)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- the join is positional, so it has to prove itself ------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun details_are_attached_to_the_pending_row_in_order() {
|
||||||
|
val rows = listOf(out("sent"), ChatRowInput("in", null), out("queued"), out("failed: no route"))
|
||||||
|
val details = outboxDetails(
|
||||||
|
rows = rows,
|
||||||
|
outbox = listOf(
|
||||||
|
row(12L, "queued", attempts = 1u, nextAttemptAt = 1_030L),
|
||||||
|
row(15L, "failed", attempts = 8u, nextAttemptAt = 1_500L),
|
||||||
|
),
|
||||||
|
maxAttempts = 8u,
|
||||||
|
now = 1_000L,
|
||||||
|
)
|
||||||
|
assertNull(details[0])
|
||||||
|
assertNull(details[1])
|
||||||
|
assertEquals("queued (try 1/8, retry 30s)", requireNotNull(details[2]).text)
|
||||||
|
assertNull(details[3])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun the_join_ignores_the_row_order_the_core_returned() {
|
||||||
|
val details = outboxDetails(
|
||||||
|
rows = listOf(out("queued"), out("queued")),
|
||||||
|
outbox = listOf(
|
||||||
|
row(20L, "queued", attempts = 1u, nextAttemptAt = 1_010L),
|
||||||
|
row(10L, "queued", attempts = 2u, nextAttemptAt = 1_020L),
|
||||||
|
),
|
||||||
|
maxAttempts = 8u,
|
||||||
|
now = 1_000L,
|
||||||
|
)
|
||||||
|
// Sorted by messageId, so the older message owns the 20s row.
|
||||||
|
assertEquals("queued (try 2/8, retry 20s)", requireNotNull(details[0]).text)
|
||||||
|
assertEquals("queued (try 1/8, retry 10s)", requireNotNull(details[1]).text)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun a_row_count_that_does_not_match_the_pending_sends_drops_every_detail() {
|
||||||
|
// The app cannot prove which message owns which row, so it says nothing
|
||||||
|
// rather than showing the wrong attempt count.
|
||||||
|
val details = outboxDetails(
|
||||||
|
rows = listOf(out("queued"), out("queued")),
|
||||||
|
outbox = listOf(row(1L, "queued", attempts = 3u, nextAttemptAt = 1_010L)),
|
||||||
|
maxAttempts = 8u,
|
||||||
|
now = 1_000L,
|
||||||
|
)
|
||||||
|
assertEquals(listOf(null, null), details)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun a_status_that_contradicts_the_message_drops_every_detail() {
|
||||||
|
// Positional join + the SDK's own per-message status is the check: the
|
||||||
|
// first message is queued, the row in its slot says failed.
|
||||||
|
val details = outboxDetails(
|
||||||
|
rows = listOf(out("queued"), out("queued")),
|
||||||
|
outbox = listOf(
|
||||||
|
row(1L, "failed", attempts = 8u, nextAttemptAt = 1_010L),
|
||||||
|
row(2L, "queued", attempts = 1u, nextAttemptAt = 1_010L),
|
||||||
|
),
|
||||||
|
maxAttempts = 8u,
|
||||||
|
now = 1_000L,
|
||||||
|
)
|
||||||
|
assertEquals(listOf(null, null), details)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun a_status_this_build_does_not_know_drops_every_detail() {
|
||||||
|
val details = outboxDetails(
|
||||||
|
rows = listOf(out("queued")),
|
||||||
|
outbox = listOf(row(1L, "spooling", attempts = 1u, nextAttemptAt = 1_010L)),
|
||||||
|
maxAttempts = 8u,
|
||||||
|
now = 1_000L,
|
||||||
|
)
|
||||||
|
assertEquals(listOf(null), details)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun an_unknown_delivery_on_a_pending_row_is_treated_as_pending() {
|
||||||
|
// parseDelivery maps an unrecognised outgoing status to Queued (never
|
||||||
|
// delivered), so the row still wants its outbox row.
|
||||||
|
val detail = requireNotNull(
|
||||||
|
outboxDetails(
|
||||||
|
rows = listOf(out("spooling")),
|
||||||
|
outbox = listOf(row(1L, "queued", attempts = 1u, nextAttemptAt = 1_000L)),
|
||||||
|
maxAttempts = 8u,
|
||||||
|
now = 1_000L,
|
||||||
|
).single(),
|
||||||
|
)
|
||||||
|
assertEquals("queued (try 1/8, retry now)", detail.text)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- a11y ---------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun the_announcement_keeps_the_sentence_and_adds_the_numbers() {
|
||||||
|
val detail = requireNotNull(
|
||||||
|
outboxDetails(
|
||||||
|
rows = listOf(out("queued")),
|
||||||
|
outbox = listOf(row(1L, "queued", attempts = 3u, nextAttemptAt = 1_045L)),
|
||||||
|
maxAttempts = 8u,
|
||||||
|
now = 1_000L,
|
||||||
|
).single(),
|
||||||
|
)
|
||||||
|
val said = deliveryAnnouncement(Delivery.Queued, detail)
|
||||||
|
assertEquals(
|
||||||
|
"Queued, not delivered yet: retrying their onion (try 3/8, retry 45s)",
|
||||||
|
said,
|
||||||
|
)
|
||||||
|
// Never a bare glyph, and never only numbers.
|
||||||
|
assertTrue(said.any { it.isLetter() })
|
||||||
|
assertTrue(!said.contains("◷"))
|
||||||
|
}
|
||||||
|
}
|
||||||
25
crates/onionwire-sdk/Cargo.lock
generated
25
crates/onionwire-sdk/Cargo.lock
generated
|
|
@ -2443,6 +2443,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15"
|
checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cc",
|
"cc",
|
||||||
|
"openssl-sys",
|
||||||
"pkg-config",
|
"pkg-config",
|
||||||
"vcpkg",
|
"vcpkg",
|
||||||
]
|
]
|
||||||
|
|
@ -2774,6 +2775,7 @@ dependencies = [
|
||||||
"rusqlite",
|
"rusqlite",
|
||||||
"safelog",
|
"safelog",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"sha2",
|
||||||
"sha3 0.10.9",
|
"sha3 0.10.9",
|
||||||
"snow",
|
"snow",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
|
@ -2781,6 +2783,7 @@ dependencies = [
|
||||||
"tor-hsservice",
|
"tor-hsservice",
|
||||||
"tor-rtcompat",
|
"tor-rtcompat",
|
||||||
"x25519-dalek",
|
"x25519-dalek",
|
||||||
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -2801,6 +2804,28 @@ version = "0.3.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
|
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "openssl-src"
|
||||||
|
version = "300.6.1+3.6.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "openssl-sys"
|
||||||
|
version = "0.9.117"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"libc",
|
||||||
|
"openssl-src",
|
||||||
|
"pkg-config",
|
||||||
|
"vcpkg",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "option-ext"
|
name = "option-ext"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
|
|
|
||||||
|
|
@ -18,8 +18,8 @@ onions directly. There is no `tor` binary, no torrc, no Orbot as the pipe.
|
||||||
| Onion | A **locator**, not an identity. It rotates. |
|
| Onion | A **locator**, not an identity. It rotates. |
|
||||||
| Invite | `onionwire:v1:k=…:o=…:spk=…:sig=…` |
|
| Invite | `onionwire:v1:k=…:o=…:spk=…:sig=…` |
|
||||||
| Crypto | Noise IK (`Noise_IK_25519_ChaChaPoly_BLAKE2s`). `spk` is x25519. |
|
| Crypto | Noise IK (`Noise_IK_25519_ChaChaPoly_BLAKE2s`). `spk` is x25519. |
|
||||||
| Fail closed | Peer onion down → the send fails. No outbox, no spool in v1. |
|
| Chat send | Unreachable peer onion → the message goes to the **local outbox** and is retried with backoff. `send()` returns `SendState.Sent` or `SendState.Queued`. File transfer and payments stay fail-closed. |
|
||||||
| At rest | Chat bodies encrypted (Argon2id wrap + ChaCha20-Poly1305). Identity keys in sqlite are plaintext — that is honest, not an oversight. |
|
| At rest | The whole sqlite file is SQLCipher (key = Argon2id of the store passphrase), and chat bodies carry a second per-row ChaCha20-Poly1305 layer with row-bound AAD. Identity keys live in that same encrypted file. |
|
||||||
|
|
||||||
### Invite string
|
### Invite string
|
||||||
|
|
||||||
|
|
@ -66,8 +66,10 @@ Requirements:
|
||||||
|
|
||||||
## Kotlin surface
|
## Kotlin surface
|
||||||
|
|
||||||
Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes,
|
Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes.
|
||||||
and a send retries the peer for up to 3 minutes before failing.
|
A send that cannot reach the peer comes back immediately as `QUEUED` (it is not
|
||||||
|
a long retry inside the call): the message is stored locally and a background
|
||||||
|
worker in the core keeps retrying it.
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
import uniffi.onionwire_sdk.*
|
import uniffi.onionwire_sdk.*
|
||||||
|
|
@ -88,8 +90,16 @@ val friend: FriendInfo = wire.addFriend(pasted)
|
||||||
// 4. Roster and chat.
|
// 4. Roster and chat.
|
||||||
val roster: List<FriendInfo> = wire.friends()
|
val roster: List<FriendInfo> = wire.friends()
|
||||||
wire.setPetname(friend.pubkeyHex, "ada")
|
wire.setPetname(friend.pubkeyHex, "ada")
|
||||||
wire.send(friend.pubkeyHex, "hello wire")
|
when (wire.send(friend.pubkeyHex, "hello wire")) {
|
||||||
|
SendState.SENT -> { /* the peer's onion took the frame */ }
|
||||||
|
SendState.QUEUED -> { /* unreachable: stored in the local outbox and
|
||||||
|
retried in the background. Show it as pending —
|
||||||
|
it is local-only until a circuit takes it. */ }
|
||||||
|
}
|
||||||
val msgs: List<ChatMessage> = wire.messages(friend.pubkeyHex)
|
val msgs: List<ChatMessage> = wire.messages(friend.pubkeyHex)
|
||||||
|
// msgs[i].direction == "out" -> msgs[i].delivery is "sent" | "queued" |
|
||||||
|
// "sending" | "failed: <reason>"; null for incoming messages. Render the
|
||||||
|
// queued and failed states distinctly from sent.
|
||||||
|
|
||||||
// 5. Locator rotation. Do NOT wire this to a single tap — the app that embeds
|
// 5. Locator rotation. Do NOT wire this to a single tap — the app that embeds
|
||||||
// the SDK owns the typed confirmation.
|
// the SDK owns the typed confirmation.
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,10 @@
|
||||||
//! the friend.
|
//! the friend.
|
||||||
//! * Transport is in-process Arti. There is no `tor` binary, no torrc, no
|
//! * Transport is in-process Arti. There is no `tor` binary, no torrc, no
|
||||||
//! Orbot pipe. If the onion service cannot publish, this fails closed.
|
//! Orbot pipe. If the onion service cannot publish, this fails closed.
|
||||||
//! * Chat bodies are encrypted at rest. Identity keys in sqlite are not.
|
//! * Chat bodies are encrypted at rest, and the whole sqlite file is
|
||||||
|
//! SQLCipher on top of that (see the root crate).
|
||||||
|
//! * A chat send that cannot reach the peer's onion is queued in a local
|
||||||
|
//! outbox and retried — see [`SendState`]. Nothing leaves the device.
|
||||||
//!
|
//!
|
||||||
//! Lifecycle: a node is started by [`open_wire`] and stopped by
|
//! Lifecycle: a node is started by [`open_wire`] and stopped by
|
||||||
//! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable
|
//! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable
|
||||||
|
|
@ -27,6 +30,7 @@ use std::sync::{Arc, Mutex, OnceLock};
|
||||||
|
|
||||||
use onionwire::hs::TorState as CoreTorState;
|
use onionwire::hs::TorState as CoreTorState;
|
||||||
use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node};
|
use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node};
|
||||||
|
use onionwire::outbox::{DEFAULT_MAX_ATTEMPTS, OutboxEntry, OutboxStatus};
|
||||||
use onionwire::qr;
|
use onionwire::qr;
|
||||||
|
|
||||||
uniffi::setup_scaffolding!();
|
uniffi::setup_scaffolding!();
|
||||||
|
|
@ -98,11 +102,74 @@ pub struct FriendInfo {
|
||||||
pub last_connect_ok: bool,
|
pub last_connect_ok: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What `send()` did with the message.
|
||||||
|
///
|
||||||
|
/// The core has a local outbox: when a friend's onion is unreachable the
|
||||||
|
/// message is written to the local sqlite store and a background worker
|
||||||
|
/// retries it with backoff. Nothing is handed to a third party — every attempt
|
||||||
|
/// is a fresh handshake straight to that friend's onion — but until a circuit
|
||||||
|
/// takes it the message exists only on this device. A consumer must not render
|
||||||
|
/// `Queued` as delivered.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
|
||||||
|
pub enum SendState {
|
||||||
|
/// The frame reached the peer's onion service during this call.
|
||||||
|
Sent,
|
||||||
|
/// The peer's onion was unreachable: the message is in the local outbox,
|
||||||
|
/// local-only until the retry worker delivers it (or it ends `Failed`).
|
||||||
|
Queued,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, uniffi::Record)]
|
#[derive(Debug, Clone, uniffi::Record)]
|
||||||
pub struct ChatMessage {
|
pub struct ChatMessage {
|
||||||
/// "in" or "out".
|
/// "in" or "out".
|
||||||
pub direction: String,
|
pub direction: String,
|
||||||
pub body: String,
|
pub body: String,
|
||||||
|
/// Outgoing messages only: `"sent"`, `"queued"`, `"sending"` or
|
||||||
|
/// `"failed: <reason>"`. `None` for incoming messages. An outgoing row with
|
||||||
|
/// no outbox row is one the peer accepted on the first attempt, so it reads
|
||||||
|
/// `"sent"` — never treat a missing value as "delivered" on the app side,
|
||||||
|
/// read this field.
|
||||||
|
pub delivery: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One row of the local outbox for a friend: a chat send the core has not
|
||||||
|
/// finished delivering.
|
||||||
|
///
|
||||||
|
/// The join key is `message_id` — the `messages.id` a [`ChatMessage`] belongs
|
||||||
|
/// to — so a client matches these against its own list instead of matching
|
||||||
|
/// bodies. Delivered rows are deleted, which is why a message with no row here
|
||||||
|
/// was accepted by the peer and never needed a retry.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
|
||||||
|
pub struct OutboxRow {
|
||||||
|
/// `messages.id` of the chat row this outbox row belongs to.
|
||||||
|
pub message_id: i64,
|
||||||
|
/// `"queued"`, `"sending"` or `"failed"` — the store's own encoding of
|
||||||
|
/// `OutboxStatus`, the same string [`ChatMessage::delivery`] uses.
|
||||||
|
/// `"sent"` does not occur: a delivered row is deleted before this is read.
|
||||||
|
pub status: String,
|
||||||
|
/// Attempts already spent on this row. Compare against
|
||||||
|
/// [`outbox_max_attempts`] to render `try n/8`.
|
||||||
|
pub attempts: u32,
|
||||||
|
/// Absolute unix seconds of the next attempt, so the client renders its own
|
||||||
|
/// countdown from `now` instead of a stale number baked into a record.
|
||||||
|
/// Only meaningful while `status == "queued"`: a `"failed"` row is terminal
|
||||||
|
/// and keeps the last time it was scheduled for, which must not be shown as
|
||||||
|
/// a countdown.
|
||||||
|
pub next_attempt_at: i64,
|
||||||
|
/// Why the last attempt failed, as the core reported it. `None` until the
|
||||||
|
/// row has been attempted once.
|
||||||
|
pub last_error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retry budget after which a queued message turns terminally `"failed"` — the
|
||||||
|
/// denominator in `try n/8`.
|
||||||
|
///
|
||||||
|
/// A constant of the core's outbox, not per-node state, so it is a free
|
||||||
|
/// function: fetch it once and render `attempts` against it. It is exposed at
|
||||||
|
/// all because the client cannot read the Rust constant.
|
||||||
|
#[uniffi::export]
|
||||||
|
pub fn outbox_max_attempts() -> u32 {
|
||||||
|
DEFAULT_MAX_ATTEMPTS
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, uniffi::Record)]
|
#[derive(Debug, Clone, uniffi::Record)]
|
||||||
|
|
@ -332,34 +399,59 @@ impl Wire {
|
||||||
.map_err(WireError::new)
|
.map_err(WireError::new)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send one message. Returns once the outcome is known: delivered now, or
|
/// Send one chat message.
|
||||||
/// queued for retry because the peer's onion is unreachable. A protocol
|
///
|
||||||
/// error (bad signature, bad frame) still fails immediately and is never
|
/// Returns [`SendState::Sent`] when the frame reached the peer's onion
|
||||||
/// queued. Use [`flush`](Self::flush) to retry the queue on demand.
|
/// service during this call, and [`SendState::Queued`] when it did not: the
|
||||||
pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> {
|
/// message is then in the local outbox and a background worker retries it
|
||||||
|
/// with exponential backoff (30s doubling, capped at 30 min, 8 attempts)
|
||||||
|
/// until it lands or ends terminally failed. A queued send is local-only —
|
||||||
|
/// show it as pending, not delivered.
|
||||||
|
///
|
||||||
|
/// A protocol error (signature mismatch, malformed or oversize frame) is
|
||||||
|
/// not retryable and still fails here; nothing is queued in that case.
|
||||||
|
pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<SendState> {
|
||||||
let pk = unhex(&pubkey_hex)?;
|
let pk = unhex(&pubkey_hex)?;
|
||||||
self.node()?
|
let status = self
|
||||||
|
.node()?
|
||||||
.send(&pk, body.as_bytes())
|
.send(&pk, body.as_bytes())
|
||||||
.await
|
.await
|
||||||
.map_err(WireError::new)?;
|
.map_err(WireError::new)?;
|
||||||
Ok(())
|
Ok(send_state(status)) }
|
||||||
}
|
|
||||||
|
|
||||||
/// Chat history for a friend, oldest first. Bodies are decrypted here;
|
/// Chat history for a friend, oldest first. Bodies are decrypted here;
|
||||||
/// they are stored encrypted at rest.
|
/// they are stored encrypted at rest. Outgoing rows carry their delivery
|
||||||
|
/// state in [`ChatMessage::delivery`].
|
||||||
pub async fn messages(&self, pubkey_hex: String) -> WResult<Vec<ChatMessage>> {
|
pub async fn messages(&self, pubkey_hex: String) -> WResult<Vec<ChatMessage>> {
|
||||||
let pk = unhex(&pubkey_hex)?;
|
let pk = unhex(&pubkey_hex)?;
|
||||||
let rows = self
|
let rows = self.node()?.list_messages(&pk).map_err(WireError::new)?;
|
||||||
|
let mut out = Vec::with_capacity(rows.len());
|
||||||
|
for m in rows {
|
||||||
|
let status = self
|
||||||
.node()?
|
.node()?
|
||||||
.list_messages(&pk)
|
.outbox_status_of_message(m.id)
|
||||||
.map_err(WireError::new)?;
|
.map_err(WireError::new)?;
|
||||||
Ok(rows
|
out.push(ChatMessage { body: String::from_utf8_lossy(&m.plaintext).into_owned(),
|
||||||
.into_iter()
|
delivery: delivery_of(&m.dir, status),
|
||||||
.map(|m| ChatMessage {
|
|
||||||
direction: m.dir,
|
direction: m.dir,
|
||||||
body: String::from_utf8_lossy(&m.plaintext).into_owned(),
|
});
|
||||||
})
|
}
|
||||||
.collect())
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Outbox rows for one friend that the core has not delivered yet: the
|
||||||
|
/// `"queued"` / `"sending"` / `"failed"` rows behind
|
||||||
|
/// [`ChatMessage::delivery`], with the core's own attempt counter and next
|
||||||
|
/// attempt time attached.
|
||||||
|
///
|
||||||
|
/// This is what lets a chat row say *why* it is still queued — `try 3/8,
|
||||||
|
/// retry 45s` — instead of a flat `"queued"`: [`OutboxRow::attempts`] and
|
||||||
|
/// [`OutboxRow::next_attempt_at`] are read from the store, never guessed by
|
||||||
|
/// the client. An empty result means nothing is outstanding for that friend.
|
||||||
|
pub async fn outbox(&self, pubkey_hex: String) -> WResult<Vec<OutboxRow>> {
|
||||||
|
let pk = unhex(&pubkey_hex)?;
|
||||||
|
let rows = self.node()?.outbox_pending(&pk).map_err(WireError::new)?;
|
||||||
|
Ok(rows.iter().map(outbox_row).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Delete every message body. Identity and friends survive.
|
/// Delete every message body. Identity and friends survive.
|
||||||
|
|
@ -415,6 +507,46 @@ fn unhex(s: &str) -> WResult<Vec<u8>> {
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `Node::send` only ever yields `Sent` or `Queued`; `Sending`/`Failed` exist
|
||||||
|
/// only on stored outbox rows. Everything that is not a completed send maps to
|
||||||
|
/// `Queued`, so a status this build does not know about is never reported as
|
||||||
|
/// delivered — the fail-safe direction for a caller that hides its retry UI.
|
||||||
|
fn send_state(status: OutboxStatus) -> SendState {
|
||||||
|
match status {
|
||||||
|
OutboxStatus::Sent => SendState::Sent,
|
||||||
|
_ => SendState::Queued,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delivery string for one stored chat row. `None` for incoming rows. An
|
||||||
|
/// outgoing row with no outbox row was accepted on the first attempt, so it is
|
||||||
|
/// reported as `"sent"` rather than left blank.
|
||||||
|
fn delivery_of(dir: &str, status: Option<OutboxStatus>) -> Option<String> {
|
||||||
|
if dir != "out" {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(match status {
|
||||||
|
None | Some(OutboxStatus::Sent) => "sent".to_string(),
|
||||||
|
Some(other) => other.to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One core outbox row as the record a client renders.
|
||||||
|
///
|
||||||
|
/// Field-for-field, so the client shows the store's numbers instead of a
|
||||||
|
/// timeout it invented: the row is keyed by `message_id` (the chat row to
|
||||||
|
/// patch), carries the store's own status string, and next-attempt as an
|
||||||
|
/// absolute unix second for the client to count down from.
|
||||||
|
fn outbox_row(entry: &OutboxEntry) -> OutboxRow {
|
||||||
|
OutboxRow {
|
||||||
|
message_id: entry.message_id,
|
||||||
|
status: entry.status.as_db_str().to_string(),
|
||||||
|
attempts: entry.attempts,
|
||||||
|
next_attempt_at: entry.next_attempt_at,
|
||||||
|
last_error: entry.last_error.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
//! No Tor here on purpose: these exercise the *lifecycle* contract of the
|
//! No Tor here on purpose: these exercise the *lifecycle* contract of the
|
||||||
|
|
@ -422,6 +554,7 @@ mod tests {
|
||||||
//! node is exactly the state `shutdown()` leaves behind.
|
//! node is exactly the state `shutdown()` leaves behind.
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use onionwire::outbox::OutboxStatus;
|
||||||
|
|
||||||
fn stopped_wire() -> Wire {
|
fn stopped_wire() -> Wire {
|
||||||
Wire {
|
Wire {
|
||||||
|
|
@ -482,4 +615,109 @@ mod tests {
|
||||||
);
|
);
|
||||||
assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped);
|
assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sent_is_sent_everything_else_is_queued() {
|
||||||
|
assert_eq!(send_state(OutboxStatus::Sent), SendState::Sent);
|
||||||
|
assert_eq!(send_state(OutboxStatus::Queued), SendState::Queued);
|
||||||
|
// `Node::send` never returns these today, but they exist on stored
|
||||||
|
// rows. Unknown states map to `Queued` — the safe direction: never
|
||||||
|
// report a send as delivered unless the core says `Sent`.
|
||||||
|
assert_eq!(send_state(OutboxStatus::Sending), SendState::Queued);
|
||||||
|
assert_eq!(
|
||||||
|
send_state(OutboxStatus::Failed("no route".into())),
|
||||||
|
SendState::Queued
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn delivery_is_reported_for_outgoing_rows_only() {
|
||||||
|
assert_eq!(delivery_of("in", Some(OutboxStatus::Queued)), None);
|
||||||
|
// Outgoing row with no outbox row: delivered on the first attempt.
|
||||||
|
assert_eq!(delivery_of("out", None).as_deref(), Some("sent"));
|
||||||
|
assert_eq!(
|
||||||
|
delivery_of("out", Some(OutboxStatus::Sent)).as_deref(),
|
||||||
|
Some("sent")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
delivery_of("out", Some(OutboxStatus::Queued)).as_deref(),
|
||||||
|
Some("queued")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
delivery_of("out", Some(OutboxStatus::Sending)).as_deref(),
|
||||||
|
Some("sending")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
delivery_of("out", Some(OutboxStatus::Failed("no route".into()))).as_deref(),
|
||||||
|
Some("failed: no route")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One core outbox row with only the fields a record carries filled in
|
||||||
|
/// interestingly. `id`, `friend_pk`, `body` and `created_at` do not cross
|
||||||
|
/// UniFFI, so their values are irrelevant.
|
||||||
|
fn entry(status: OutboxStatus, attempts: u32, last_error: Option<&str>) -> OutboxEntry {
|
||||||
|
OutboxEntry {
|
||||||
|
id: 3,
|
||||||
|
friend_pk: vec![0xaa; 32],
|
||||||
|
message_id: 42,
|
||||||
|
body: b"hello".to_vec(),
|
||||||
|
attempts,
|
||||||
|
next_attempt_at: 1_700_000_045,
|
||||||
|
created_at: 1_700_000_000,
|
||||||
|
status,
|
||||||
|
last_error: last_error.map(str::to_string),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn outbox_row_carries_the_join_key_the_attempt_count_and_the_next_attempt_time() {
|
||||||
|
let row = outbox_row(&entry(
|
||||||
|
OutboxStatus::Queued,
|
||||||
|
3,
|
||||||
|
Some("peer onion unreachable"),
|
||||||
|
));
|
||||||
|
assert_eq!(row.message_id, 42);
|
||||||
|
assert_eq!(row.status, "queued");
|
||||||
|
assert_eq!(row.attempts, 3);
|
||||||
|
assert_eq!(row.next_attempt_at, 1_700_000_045);
|
||||||
|
assert_eq!(row.last_error.as_deref(), Some("peer onion unreachable"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn outbox_row_keeps_the_stores_own_status_encoding() {
|
||||||
|
// These four strings are the `outbox.status` CHECK constraint in
|
||||||
|
// `src/store.rs`; a client switches on them verbatim.
|
||||||
|
for (status, want) in [
|
||||||
|
(OutboxStatus::Queued, "queued"),
|
||||||
|
(OutboxStatus::Sending, "sending"),
|
||||||
|
(OutboxStatus::Sent, "sent"),
|
||||||
|
(
|
||||||
|
OutboxStatus::Failed("peer onion unreachable".into()),
|
||||||
|
"failed",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
assert_eq!(outbox_row(&entry(status, 0, None)).status, want);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_failed_outbox_row_carries_the_cores_reason_verbatim() {
|
||||||
|
let row = outbox_row(&entry(
|
||||||
|
OutboxStatus::Failed("peer onion unreachable".into()),
|
||||||
|
8,
|
||||||
|
Some("peer onion unreachable"),
|
||||||
|
));
|
||||||
|
assert_eq!(row.status, "failed");
|
||||||
|
assert_eq!(row.attempts, 8);
|
||||||
|
assert_eq!(row.last_error.as_deref(), Some("peer onion unreachable"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn outbox_max_attempts_is_the_denominator_a_client_renders_against() {
|
||||||
|
// The Android chat row renders `try n/8`. Pin the number so the SDK and
|
||||||
|
// the core's retry budget cannot drift apart silently.
|
||||||
|
assert_eq!(outbox_max_attempts(), 8);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -24,7 +24,7 @@ Original pass: rust-dev, no live hidden service / live wallet. Ignored tests
|
||||||
|
|
||||||
## Still true / not a “finding we forgot”
|
## Still true / not a “finding we forgot”
|
||||||
|
|
||||||
- Identity secret key and roster (pubkeys + locators) are **plaintext** in sqlite. Chat bodies are not. Seized laptop without FDE yields who you are and who you talk to.
|
- At rest the whole store is SQLCipher (Argon2id key over a 16-byte `store_salt`), so the identity secret key, roster (pubkeys + locators) and chat bodies are ciphertext on disk; chat bodies add a row-bound AEAD layer on top. That is not a defense against a live compromise or an attacker who has the passphrase — see [THREAT_MODEL.md](THREAT_MODEL.md).
|
||||||
- Arti onion services are experimental. Fail closed; no C-tor fallback.
|
- Arti onion services are experimental. Fail closed; no C-tor fallback.
|
||||||
- No public third-party audit, no `cargo-audit` gate in CI as of the original pass.
|
- No public third-party audit, no `cargo-audit` gate in CI as of the original pass.
|
||||||
- Invite decode still accepts the legacy concat signature (compatibility).
|
- Invite decode still accepts the legacy concat signature (compatibility).
|
||||||
|
|
|
||||||
105
src/node.rs
105
src/node.rs
|
|
@ -293,7 +293,14 @@ impl Node {
|
||||||
/// so this is about leaving less to replay (and less on disk) if the
|
/// so this is about leaving less to replay (and less on disk) if the
|
||||||
/// process is killed right after teardown — not about correctness.
|
/// process is killed right after teardown — not about correctness.
|
||||||
fn checkpoint(&self) {
|
fn checkpoint(&self) {
|
||||||
if let Err(e) = checkpoint_wal(&self.home) {
|
let store = match self.store.lock() {
|
||||||
|
Ok(s) => s,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("wal checkpoint: store lock poisoned: {e}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Err(e) = store.checkpoint_wal() {
|
||||||
eprintln!("wal checkpoint: {e}");
|
eprintln!("wal checkpoint: {e}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1036,49 +1043,6 @@ fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checkpoint the sqlite WAL into the main db file and truncate it.
|
|
||||||
///
|
|
||||||
/// `Store` owns the write connection and deliberately does not lend it out, and
|
|
||||||
/// a checkpoint is a property of the *database*, not of one connection — so a
|
|
||||||
/// short-lived second connection to the same file is the least invasive way to
|
|
||||||
/// reach it from the node without widening `Store`'s API.
|
|
||||||
///
|
|
||||||
/// That works because the connection needs no passphrase: it moves
|
|
||||||
/// already-committed pages, it does not decrypt them. It stops working the
|
|
||||||
/// moment the store is SQLCipher-encrypted (PR #43), because the key lives only
|
|
||||||
/// inside `Store` and a second connection cannot read the file at all. That case
|
|
||||||
/// is detected and reported as a skip rather than a failure: nothing is lost
|
|
||||||
/// (sqlite folds the WAL into the db when the last connection closes) — the
|
|
||||||
/// explicit truncation just has to move inside `Store` to happen here.
|
|
||||||
fn checkpoint_wal(home: &Path) -> Result<(), String> {
|
|
||||||
let db = home.join("onionwire.db");
|
|
||||||
if !db.exists() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let conn = rusqlite::Connection::open(&db).map_err(|e| format!("open {}: {e}", db.display()))?;
|
|
||||||
let (busy, log, checkpointed): (i64, i64, i64) = conn
|
|
||||||
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
|
|
||||||
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
|
|
||||||
})
|
|
||||||
.map_err(|e| {
|
|
||||||
let msg = e.to_string();
|
|
||||||
if msg.contains("not a database") {
|
|
||||||
// SQLCipher store: no key here, so this connection sees noise.
|
|
||||||
format!("store is SQLCipher-encrypted — skipped ({msg})")
|
|
||||||
} else {
|
|
||||||
format!("wal_checkpoint: {msg}")
|
|
||||||
}
|
|
||||||
})?;
|
|
||||||
if busy != 0 {
|
|
||||||
// Another connection is reading/writing: pages are still safe in the
|
|
||||||
// WAL, they just were not moved this time.
|
|
||||||
return Err(format!(
|
|
||||||
"busy ({checkpointed}/{log} pages moved, another connection active)"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn next_hs_nickname(cur: &str) -> String {
|
fn next_hs_nickname(cur: &str) -> String {
|
||||||
let n = cur
|
let n = cur
|
||||||
.strip_prefix("ow")
|
.strip_prefix("ow")
|
||||||
|
|
@ -1122,56 +1086,3 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod lifecycle_tests {
|
|
||||||
//! Offline half of the shutdown contract. The live-Tor half lives in
|
|
||||||
//! `tests/tor_lifecycle.rs` (ignored) — everything here runs in CI.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
/// `checkpoint_wal` reaches the database through a *second* connection,
|
|
||||||
/// because `Store` owns the write one. That assumption is the whole reason
|
|
||||||
/// the helper can live in `node.rs`, so prove it against a real WAL.
|
|
||||||
#[test]
|
|
||||||
fn checkpoint_wal_truncates_a_live_wal() {
|
|
||||||
let root = tempfile::tempdir().expect("tempdir");
|
|
||||||
let home = root.path();
|
|
||||||
let db = home.join("onionwire.db");
|
|
||||||
let conn = rusqlite::Connection::open(&db).expect("open db");
|
|
||||||
let mode: String = conn
|
|
||||||
.query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0))
|
|
||||||
.expect("wal mode");
|
|
||||||
assert_eq!(mode.to_lowercase(), "wal");
|
|
||||||
conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v BLOB);")
|
|
||||||
.expect("create table");
|
|
||||||
for _ in 0..64 {
|
|
||||||
conn.execute("INSERT INTO t (v) VALUES (?1)", rusqlite::params![vec![7u8; 512]])
|
|
||||||
.expect("insert");
|
|
||||||
}
|
|
||||||
|
|
||||||
let wal = home.join("onionwire.db-wal");
|
|
||||||
let before = std::fs::metadata(&wal).expect("wal file").len();
|
|
||||||
assert!(before > 0, "expected pending WAL frames, got {before}");
|
|
||||||
|
|
||||||
checkpoint_wal(home).expect("checkpoint");
|
|
||||||
|
|
||||||
let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0);
|
|
||||||
assert_eq!(after, 0, "WAL not truncated ({before} bytes before)");
|
|
||||||
|
|
||||||
// The rows are still there — a checkpoint moves pages, it never drops
|
|
||||||
// committed data.
|
|
||||||
let n: i64 = conn
|
|
||||||
.query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0))
|
|
||||||
.expect("count");
|
|
||||||
assert_eq!(n, 64);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A home directory with no store yet is not an error: `shutdown` and
|
|
||||||
/// `flush` are safe to call on a node whose db was never created (tests,
|
|
||||||
/// wiped installs).
|
|
||||||
#[test]
|
|
||||||
fn checkpoint_wal_is_a_no_op_without_a_database() {
|
|
||||||
let root = tempfile::tempdir().expect("tempdir");
|
|
||||||
checkpoint_wal(root.path()).expect("no db, no error");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
54
src/store.rs
54
src/store.rs
|
|
@ -1054,6 +1054,31 @@ impl Store {
|
||||||
Ok(out)
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Fold the WAL into the main db file and truncate it.
|
||||||
|
///
|
||||||
|
/// Runs on this store's own keyed connection: a second, unkeyed connection
|
||||||
|
/// cannot even read a SQLCipher store (`SQLITE_NOTADB`), so the checkpoint
|
||||||
|
/// has to happen here, not from `node.rs`.
|
||||||
|
///
|
||||||
|
/// Best effort on purpose: WAL replay on open recovers everything committed,
|
||||||
|
/// so this is about leaving less to replay (and less on disk) if the process
|
||||||
|
/// is killed right after teardown — not about correctness.
|
||||||
|
pub fn checkpoint_wal(&self) -> Result<()> {
|
||||||
|
let (busy, log, checkpointed): (i64, i64, i64) =
|
||||||
|
self.conn
|
||||||
|
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
|
||||||
|
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
|
||||||
|
})?;
|
||||||
|
if busy != 0 {
|
||||||
|
// Another connection is reading/writing: pages are still safe in the
|
||||||
|
// WAL, they just were not moved this time.
|
||||||
|
return Err(Error(format!(
|
||||||
|
"busy ({checkpointed}/{log} pages moved, another connection active)"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Drop chat + payments history. Identity + friends stay.
|
/// Drop chat + payments history. Identity + friends stay.
|
||||||
/// Not a forensic erase: SSD wear-leveling can keep copies.
|
/// Not a forensic erase: SSD wear-leveling can keep copies.
|
||||||
pub fn wipe_messages(&self) -> Result<()> {
|
pub fn wipe_messages(&self) -> Result<()> {
|
||||||
|
|
@ -1065,7 +1090,7 @@ impl Store {
|
||||||
self.conn.execute("DELETE FROM messages", [])?;
|
self.conn.execute("DELETE FROM messages", [])?;
|
||||||
self.conn.execute("DELETE FROM payments", [])?;
|
self.conn.execute("DELETE FROM payments", [])?;
|
||||||
self.conn.execute_batch("VACUUM")?;
|
self.conn.execute_batch("VACUUM")?;
|
||||||
self.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?;
|
self.checkpoint_wal()?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1379,6 +1404,33 @@ mod at_rest {
|
||||||
use super::*;
|
use super::*;
|
||||||
use zeroize::Zeroize;
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
|
/// `Node::shutdown`/`flush` checkpoint the WAL through this method, so it has
|
||||||
|
/// to run on the store's own keyed connection: a second, unkeyed one cannot
|
||||||
|
/// read a SQLCipher file at all (`SQLITE_NOTADB`) and the truncation silently
|
||||||
|
/// never happened.
|
||||||
|
#[test]
|
||||||
|
fn checkpoint_wal_truncates_an_encrypted_store_wal() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), "checkpoint-pass").unwrap();
|
||||||
|
let pk = [3u8; 32];
|
||||||
|
store.upsert_friend(&pk, "peer.onion", None).unwrap();
|
||||||
|
for _ in 0..64 {
|
||||||
|
store.append_message(&pk, "out", &[7u8; 512]).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
let wal = dir.path().join("onionwire.db-wal");
|
||||||
|
let before = std::fs::metadata(&wal).expect("wal file").len();
|
||||||
|
assert!(before > 0, "expected pending WAL frames, got {before}");
|
||||||
|
|
||||||
|
store.checkpoint_wal().expect("checkpoint");
|
||||||
|
|
||||||
|
let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0);
|
||||||
|
assert_eq!(after, 0, "WAL not truncated ({before} bytes before)");
|
||||||
|
|
||||||
|
// A checkpoint moves pages into the db; it never drops committed data.
|
||||||
|
assert_eq!(store.list_messages(&pk).unwrap().len(), 64);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn store_data_key_is_a_zeroizing_wrapper_that_wipes() {
|
fn store_data_key_is_a_zeroizing_wrapper_that_wipes() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@
|
||||||
//!
|
//!
|
||||||
//! The offline half of this contract — the Arti-status projection, the WAL
|
//! The offline half of this contract — the Arti-status projection, the WAL
|
||||||
//! checkpoint, and the SDK's typed error after shutdown — runs in the normal
|
//! checkpoint, and the SDK's typed error after shutdown — runs in the normal
|
||||||
//! suite (`tests/hs.rs`, `src/node.rs`, `crates/onionwire-sdk/src/lib.rs`).
|
//! suite (`tests/hs.rs`, `src/store.rs`, `crates/onionwire-sdk/src/lib.rs`).
|
||||||
|
|
||||||
use onionwire::node::{FlushOutcome, Node};
|
use onionwire::node::{FlushOutcome, Node};
|
||||||
use onionwire::hs::TorState;
|
use onionwire::hs::TorState;
|
||||||
|
|
@ -52,10 +52,25 @@ async fn shutdown_stops_the_node_and_later_calls_are_typed_errors() {
|
||||||
"start returned Ok but tor_state() is {started_state:?}"
|
"start returned Ok but tor_state() is {started_state:?}"
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Rows written by `start` (self row, current onion) are still in the WAL at
|
||||||
|
// this point: no checkpoint has run, and the connection that wrote them is
|
||||||
|
// still open.
|
||||||
|
let wal = home.join("onionwire.db-wal");
|
||||||
|
let before = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0);
|
||||||
|
assert!(
|
||||||
|
before > 0,
|
||||||
|
"expected pending WAL frames before flush, got {before}"
|
||||||
|
);
|
||||||
|
|
||||||
// A flush with nothing queued is a no-op that reports it, not an error.
|
// A flush with nothing queued is a no-op that reports it, not an error.
|
||||||
let drained: FlushOutcome = node.flush().await.expect("flush on a live node");
|
let drained: FlushOutcome = node.flush().await.expect("flush on a live node");
|
||||||
assert_eq!(drained.remaining, 0, "empty outbox: {drained:?}");
|
assert_eq!(drained.remaining, 0, "empty outbox: {drained:?}");
|
||||||
|
|
||||||
|
// `flush` promises a truncated WAL, and on an encrypted store that only
|
||||||
|
// works through the store's own keyed connection.
|
||||||
|
let left = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0);
|
||||||
|
assert_eq!(left, 0, "flush left {left} bytes of WAL to replay");
|
||||||
|
|
||||||
node.shutdown().await.expect("shutdown");
|
node.shutdown().await.expect("shutdown");
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue