Merge pull request 'feat(android): foreground service keeps the onion reachable through Doze' (#60) from feat/android-foreground-keepalive into main
Reviewed-on: #60
This commit is contained in:
commit
c55dfd2492
11 changed files with 814 additions and 87 deletions
|
|
@ -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") },
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
|
@ -22,7 +23,6 @@ import uniffi.onionwire_sdk.InviteInfo
|
||||||
import uniffi.onionwire_sdk.RotateOutcome
|
import uniffi.onionwire_sdk.RotateOutcome
|
||||||
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 +59,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,20 +91,28 @@ 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
|
||||||
refreshUnlockState()
|
// 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
|
* 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 +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 =
|
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()
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue