feat(android): keep the onion published through Doze with a foreground service

WireViewModel owned the single Wire node and called shutdown() from
onCleared(), so a backgrounded node died with the UI. Node lifetime is now
arbitrated by a pure policy (NodeLifetime) with two anchors — UI and
keep-alive — and one process-wide owner (NodeHost) that is the only caller
of flush()/shutdown() in the app.

KeepAliveService holds the process in the foreground behind an ongoing
notification from the "keep-alive" channel, started on unlock and stopped
by Lock or the notification action, so peers can still reach the device
while the screen is off.

- foregroundServiceType="specialUse": dataSync is documented as a finite
  transfer (upload/download/backup) and this is an always-on node
- POST_NOTIFICATIONS requested when the node becomes reachable; denial
  keeps the service running with no visible notice instead of failing
- re-unlock with a node the service kept alive adopts it rather than
  reopening the store the live node still holds
- 9 device-free unit tests for the start/stop/re-unlock state machine
This commit is contained in:
apk-dev 2026-09-12 16:34:40 -04:00
commit e923e06891
No known key found for this signature in database
11 changed files with 814 additions and 87 deletions

View file

@ -1,16 +1,17 @@
package com.siriusdevops.onionwire
import android.app.Application
import androidx.core.app.NotificationManagerCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.siriusdevops.onionwire.crypto.KeyBacking
import com.siriusdevops.onionwire.crypto.KeystorePassphraseCipher
import com.siriusdevops.onionwire.crypto.StoreSecret
import com.siriusdevops.onionwire.crypto.StoredPassphraseStore
import kotlinx.coroutines.CoroutineScope
import com.siriusdevops.onionwire.keepalive.KeepAliveService
import com.siriusdevops.onionwire.keepalive.KeepAliveStatus
import com.siriusdevops.onionwire.keepalive.NodeHost
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
@ -22,7 +23,6 @@ import uniffi.onionwire_sdk.InviteInfo
import uniffi.onionwire_sdk.RotateOutcome
import uniffi.onionwire_sdk.Wire
import uniffi.onionwire_sdk.decodeInvite
import uniffi.onionwire_sdk.openWire
import java.io.File
sealed interface Phase {
@ -59,18 +59,13 @@ sealed interface Unlock {
}
/**
* Teardown work must outlive the ViewModel: `onCleared()` runs *after*
* `viewModelScope` is already cancelled, and stopping the node means draining
* the outbox and stopping Arti, not just dropping a reference. One process-wide
* scope is enough — there is one node per process.
*/
private val TEARDOWN = CoroutineScope(SupervisorJob() + Dispatchers.IO)
/**
* Owns the single Wire node for the process.
* Owns the UI side of the process's single node.
*
* The node lives in the ViewModel because a configuration change must not
* drop a published onion service and re-bootstrap Tor.
* The node itself lives in [NodeHost], not here, because it now has two
* possible owners: this ViewModel while the UI is up, and [KeepAliveService]
* while the screen is off. A configuration change still must not drop a
* published onion, and neither must the activity being destroyed — that part
* is unchanged.
*/
class WireViewModel(app: Application) : AndroidViewModel(app) {
@ -96,20 +91,28 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
private val _friends = MutableStateFlow<List<FriendInfo>>(emptyList())
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
* old node holds the sqlite file and Arti's state lock until `shutdown()`
* returns, and racing it makes the new node fail to open.
* One line of battery honesty for the roster: what is still running once
* the screen is off, or why it is not. Null while locked.
*/
private var stopping: Job? = null
private val _keepAliveNote = MutableStateFlow<String?>(null)
val keepAliveNote: StateFlow<String?> = _keepAliveNote.asStateFlow()
init {
// Probe on a background dispatcher: this touches the Keystore and does
// a full GCM decrypt. Doing it here means a killed Keystore key is
// reported on the lock screen instead of at the first tap.
refreshUnlockState()
// A node the foreground service kept alive is still open. Adopt it and
// go straight to the roster: showing an unlock screen for a store that
// is already open would be theatre, and unlocking again would race the
// live node for the sqlite file.
val existing = NodeHost.current()
if (existing != null) {
viewModelScope.launch { adopt(existing) }
} else {
refreshUnlockState()
}
viewModelScope.launch {
NodeHost.keepAlive.collect { renderKeepAliveNote(it) }
}
}
/**
@ -162,44 +165,155 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
}
/**
* Stops the node and drops our handle. Nothing is sent after this.
* Explicit Lock: stops the node and the keep-alive with it.
*
* Flush first — the outbox is the whole point of losing the process — then
* `shutdown()`, which stops the onion service, aborts the retry worker and
* checkpoints the sqlite WAL. Both calls are on [TEARDOWN] because this
* runs from an `onClick`.
* Order matters. The service goes first — a still-running keep-alive would
* re-anchor the node and leave a notification pointing at a dead onion —
* then the policy tears the node down, flush before `shutdown()` so the
* outbox survives.
*/
fun lock() {
val w = wire ?: return
wire = null
if (NodeHost.current() == null) return
KeepAliveService.stop(getApplication())
NodeHost.lock()
_friends.value = emptyList()
_phase.value = Phase.Locked
refreshUnlockState()
stopping = TEARDOWN.launch { stopNode(w) }
}
/**
* The node must not outlive the UI. Doze and the background-process killer
* skip this entirely (that is what the outbox is for), but a normal finish
* tears Tor down here instead of leaving Arti running behind a dead screen.
* The UI is going away: a normal finish, a task swipe, or the process being
* killed. This deliberately does **not** shut the node down — [NodeHost]
* decides between "flush and stay published" (a keep-alive is holding it)
* and "flush and stop" (nothing is). A ViewModel that shut down a node the
* foreground service owns is the bug this card exists to avoid.
*/
override fun onCleared() {
val w = wire
wire = null
if (w != null) stopping = TEARDOWN.launch { stopNode(w) }
NodeHost.onUiDetached()
super.onCleared()
}
private suspend fun stopNode(w: Wire) {
// Best effort, both steps: teardown runs on a process-scope job after
// the UI is gone, so there is nobody to show an error to and nothing
// useful to retry. `shutdown()` drains again with a shorter budget, so
// a flush that times out is not fatal.
runCatching { w.flush() }
// A second shutdown — `lock()` and then `onCleared()`, say — lands here
// too: the SDK reports it as a typed WireException.Stopped, never a
// panic, so swallowing it is correct.
runCatching { w.shutdown() }
/** Re-reads the notification state after the runtime prompt resolves. */
fun onNotificationPermissionChanged() {
renderKeepAliveNote(NodeHost.keepAlive.value)
// Android does not retroactively post a foreground notification that was
// suppressed while POST_NOTIFICATIONS was denied — the service started,
// the user then granted, and the shade stayed empty. Re-announce, so the
// grant actually produces the one honest signal the user has.
if (NodeHost.keepAlive.value is KeepAliveStatus.On) {
viewModelScope.launch {
NodeHost.current()?.let { KeepAliveService.start(getApplication(), it.onion()) }
}
}
}
/** Whether the keep-alive's notification can actually be posted. */
fun notificationsAllowed(): Boolean =
NotificationManagerCompat.from(getApplication()).areNotificationsEnabled()
private fun renderKeepAliveNote(status: KeepAliveStatus) {
val text = getApplication<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() {
@ -222,66 +336,10 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
}
}
/**
* The one path that calls the SDK.
*
* [secret] is wiped in `finally`, including when the Keystore write or the
* SDK call throws. The SDK's UniFFI signature takes a `String`, so one
* immutable copy is unavoidable here — see the PR description for the
* follow-up SDK signature this card cannot make itself.
*/
private fun openWith(secret: CharArray, storeAfterwards: Boolean) {
if (secret.isEmpty() || _phase.value is Phase.Opening || wire != null) {
StoreSecret.wipe(secret)
return
}
_phase.value = Phase.Opening
viewModelScope.launch {
try {
// Any previous node must be fully stopped first: the old node
// holds the sqlite file and Arti's state lock until its teardown
// returns, and racing it makes this open fail.
stopping?.join()
val w = openWire(home.absolutePath, secret.concatToString())
wire = w
if (storeAfterwards) store(secret)
_phase.value = Phase.Ready(
fingerprint = w.fingerprint(),
onion = w.onion(),
sdkVersion = w.version(),
)
refreshFriends()
} catch (t: Throwable) {
_phase.value = Phase.Failed(t.message ?: t.toString())
} finally {
StoreSecret.wipe(secret)
}
}
}
private suspend fun store(secret: CharArray) {
val outcome: Result<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 =
"The stored passphrase could not be read — $reason. Type it once to store it again."
private fun requireWire(): Wire = wire ?: error("locked")
private fun requireWire(): Wire = NodeHost.requireOpen()
suspend fun refreshFriends() {
_friends.value = requireWire().friends()