onionwire/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt
apk-dev e923e06891
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
2026-09-12 16:34:40 -04:00

380 lines
14 KiB
Kotlin

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 com.siriusdevops.onionwire.keepalive.KeepAliveService
import com.siriusdevops.onionwire.keepalive.KeepAliveStatus
import com.siriusdevops.onionwire.keepalive.NodeHost
import kotlinx.coroutines.Dispatchers
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.ChatMessage
import uniffi.onionwire_sdk.FriendInfo
import uniffi.onionwire_sdk.InviteInfo
import uniffi.onionwire_sdk.RotateOutcome
import uniffi.onionwire_sdk.Wire
import uniffi.onionwire_sdk.decodeInvite
import java.io.File
sealed interface Phase {
/** No identity unlocked. Nothing Tor-related is running. */
data object Locked : Phase
/** Bootstrap + onion publish. Cold start is minutes, not seconds. */
data object Opening : Phase
data class Ready(
val fingerprint: String,
val onion: String,
val sdkVersion: String,
) : Phase
data class Failed(val message: String) : Phase
}
/**
* How the lock screen expects the next unlock to happen.
*
* This is a probe of local state, not a promise: [OneTap] means a blob exists
* *and* decrypted successfully during this process's lifetime.
*/
sealed interface Unlock {
/**
* The passphrase must be typed. [notice] explains why a stored one is not
* being used (key invalidated, blob corrupt, nothing stored yet).
*/
data class TypeIt(val notice: String? = null) : Unlock
/** A stored, decryptable passphrase exists — one tap. */
data class OneTap(val backing: KeyBacking) : Unlock
}
/**
* Owns the UI side of the process's single node.
*
* 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) {
/** `context.filesDir` — app-private, never external storage. */
private val home: File = File(app.filesDir, "onionwire")
/**
* The Keystore-wrapped passphrase. Two files at most: this blob and the
* KeyStore key under alias [KeystorePassphraseCipher.ALIAS]. Nothing else
* on disk ever sees the plaintext.
*/
private val secrets: StoredPassphraseStore = StoredPassphraseStore(
File(File(app.filesDir, "secrets"), "store-passphrase.bin"),
KeystorePassphraseCipher(app),
)
private val _phase = MutableStateFlow<Phase>(Phase.Locked)
val phase: StateFlow<Phase> = _phase.asStateFlow()
private val _unlock = MutableStateFlow<Unlock>(Unlock.TypeIt())
val unlock: StateFlow<Unlock> = _unlock.asStateFlow()
private val _friends = MutableStateFlow<List<FriendInfo>>(emptyList())
val friends: StateFlow<List<FriendInfo>> = _friends.asStateFlow()
/**
* 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 val _keepAliveNote = MutableStateFlow<String?>(null)
val keepAliveNote: StateFlow<String?> = _keepAliveNote.asStateFlow()
init {
// A node the foreground service kept alive is still open. Adopt it and
// go straight to the roster: showing an unlock screen for a store that
// 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) }
}
}
/**
* Unlocks with a typed passphrase. Empty fails closed — the SDK maps it
* straight to an error, it is not a "skip" path.
*
* [remember] wraps the passphrase with the Keystore key so later launches
* are one tap. It is opt-in in the UI (and on by default there); it is
* never implied by this call.
*/
fun unlock(passphrase: String, remember: Boolean = false) {
if (passphrase.isEmpty()) return
openWith(passphrase.toCharArray(), storeAfterwards = remember)
}
/**
* One-tap unlock from the stored blob.
*
* Any failure — key deleted, blob corrupt, GCM tag mismatch — degrades to
* "type it" with the reason on screen. It never crashes and never silently
* unlocks with something else.
*/
fun unlockStored() {
if (_phase.value is Phase.Opening) return
viewModelScope.launch {
val loaded = withContext(Dispatchers.IO) { secrets.load() }
when (loaded) {
is StoredPassphraseStore.Load.Loaded ->
openWith(loaded.passphrase, storeAfterwards = false)
StoredPassphraseStore.Load.Absent -> {
_unlock.value = Unlock.TypeIt("No passphrase is stored on this device.")
}
is StoredPassphraseStore.Load.Unavailable -> {
_unlock.value = Unlock.TypeIt(unavailableNotice(loaded.reason))
}
}
}
}
/** Drops the stored passphrase and its Keystore key. Irreversible. */
fun forgetStoredPassphrase() {
viewModelScope.launch {
withContext(Dispatchers.IO) { secrets.forget() }
_unlock.value = Unlock.TypeIt(
"Stored passphrase deleted. Type it to open the store again.",
)
}
}
/**
* Explicit Lock: stops the node and the keep-alive with it.
*
* 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() {
if (NodeHost.current() == null) return
KeepAliveService.stop(getApplication())
NodeHost.lock()
_friends.value = emptyList()
_phase.value = Phase.Locked
refreshUnlockState()
}
/**
* 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() {
NodeHost.onUiDetached()
super.onCleared()
}
/** 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() {
viewModelScope.launch {
val state = withContext(Dispatchers.IO) {
when (val loaded = secrets.load()) {
is StoredPassphraseStore.Load.Loaded -> {
// We only needed to know it decrypts. Wipe immediately.
StoreSecret.wipe(loaded.passphrase)
Unlock.OneTap(secrets.backing())
}
StoredPassphraseStore.Load.Absent -> Unlock.TypeIt()
is StoredPassphraseStore.Load.Unavailable ->
Unlock.TypeIt(unavailableNotice(loaded.reason))
}
}
_unlock.value = state
}
}
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 = NodeHost.requireOpen()
suspend fun refreshFriends() {
_friends.value = requireWire().friends()
}
suspend fun invite(): String = requireWire().invite()
suspend fun addFriend(invite: String): FriendInfo {
val f = requireWire().addFriend(invite)
refreshFriends()
return f
}
suspend fun setPetname(pubkeyHex: String, petname: String?) {
requireWire().setPetname(pubkeyHex, petname?.takeIf { it.isNotBlank() })
refreshFriends()
}
suspend fun messages(pubkeyHex: String): List<ChatMessage> =
requireWire().messages(pubkeyHex)
suspend fun send(pubkeyHex: String, body: String) =
requireWire().send(pubkeyHex, body)
suspend fun wipeMessages() {
requireWire().wipeMessages()
}
suspend fun rotateOnion(): RotateOutcome {
val out = requireWire().rotateOnion()
_phase.value = (_phase.value as? Phase.Ready)?.copy(onion = requireWire().onion())
?: _phase.value
refreshFriends()
return out
}
suspend fun decode(invite: String): InviteInfo = decodeInvite(invite)
}