Merge branch 'main' into feat/store-checkpoint-wal
All checks were successful
ci / test (pull_request) Successful in 4m18s
All checks were successful
ci / test (pull_request) Successful in 4m18s
This commit is contained in:
commit
111e90ce0a
23 changed files with 2283 additions and 207 deletions
13
README.md
13
README.md
|
|
@ -3,7 +3,7 @@
|
|||
Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process Arti).
|
||||
No hosted server. Identity is a public key; the onion is only a locator.
|
||||
|
||||
**v0.2** — Linux TUI. 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.
|
||||
|
||||
|
|
@ -222,14 +222,11 @@ If you set `ONIONWIRE_HOME`, delete that directory instead.
|
|||
|
||||
## 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`)
|
||||
- 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.
|
||||
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.
|
||||
|
||||
Threat model: [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md).
|
||||
|
||||
|
|
@ -316,7 +313,7 @@ Do not run `cargo publish`; `publish = false`. CI needs the repo secret
|
|||
|
||||
## 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
|
||||
|
||||
|
|
|
|||
|
|
@ -4,10 +4,33 @@
|
|||
<!--
|
||||
INTERNET is the only permission requested at first launch.
|
||||
No camera (invites are typed/pasted, not scanned), no contacts, no
|
||||
storage. Tor runs in-process; there is no foreground service and no
|
||||
keep-alive notification in v1, so the node only lives while the app does.
|
||||
storage.
|
||||
|
||||
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.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
|
||||
android:allowBackup="false"
|
||||
|
|
@ -30,6 +53,21 @@
|
|||
</intent-filter>
|
||||
</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>
|
||||
|
||||
</manifest>
|
||||
|
|
|
|||
|
|
@ -1,13 +1,18 @@
|
|||
package com.siriusdevops.onionwire
|
||||
|
||||
import android.Manifest
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.Modifier
|
||||
|
|
@ -48,9 +53,27 @@ class MainActivity : ComponentActivity() {
|
|||
private fun AppRoot(vm: WireViewModel = viewModel()) {
|
||||
val phase by vm.phase.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) {
|
||||
is Phase.Ready -> ReadyGraph(vm, p)
|
||||
is Phase.Ready -> ReadyGraph(vm, p, keepAliveNote)
|
||||
else -> UnlockScreen(
|
||||
phase = p,
|
||||
unlock = unlock,
|
||||
|
|
@ -62,7 +85,7 @@ private fun AppRoot(vm: WireViewModel = viewModel()) {
|
|||
}
|
||||
|
||||
@Composable
|
||||
private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready) {
|
||||
private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: String?) {
|
||||
val nav = rememberNavController()
|
||||
val friends by vm.friends.collectAsStateWithLifecycle()
|
||||
val scope = rememberCoroutineScope()
|
||||
|
|
@ -74,6 +97,7 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready) {
|
|||
onion = ready.onion,
|
||||
sdkVersion = ready.sdkVersion,
|
||||
friends = friends,
|
||||
keepAliveNote = keepAliveNote,
|
||||
onOpenChat = { nav.navigate("chat/${it.pubkeyHex}") },
|
||||
onShare = { nav.navigate("share") },
|
||||
onPaste = { nav.navigate("paste") },
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
sdkVersion: String,
|
||||
friends: List<FriendInfo>,
|
||||
keepAliveNote: String?,
|
||||
onOpenChat: (FriendInfo) -> Unit,
|
||||
onShare: () -> Unit,
|
||||
onPaste: () -> Unit,
|
||||
|
|
@ -82,6 +83,14 @@ fun RosterScreen(
|
|||
style = MaterialTheme.typography.labelSmall,
|
||||
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))
|
||||
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,
|
||||
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"?>
|
||||
<resources>
|
||||
<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>
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
@ -24,7 +24,7 @@ Original pass: rust-dev, no live hidden service / live wallet. Ignored tests
|
|||
|
||||
## 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.
|
||||
- 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).
|
||||
|
|
|
|||
|
|
@ -73,6 +73,18 @@ A signed `prf` frame is shown to people who already have a session with you. App
|
|||
|
||||
OnionWire never holds spend keys. Optional `ONIONWIRE_WALLET_RPC` talks HTTP Digest to a user-hosted `monero-wallet-rpc` on loopback (`--rpc-login` required; open RPC is refused). A Noise friend can sign any `rcp`; the signature proves who sent the claim, not that a payment happened. `verified=1` only after a conjunctive RPC match: one `get_transfers` row with the same non-empty `txid`, `amount`, and `address`. Incoming `rcp` stays `verified=0` if RPC is down, errors, or no exact row. Subaddress reuse is the user’s wallet policy.
|
||||
|
||||
Run it **view-only** (recommended). `/pay` and receipt verification need only
|
||||
`create_address`/`get_transfers`, which a wallet without a spend key serves
|
||||
fine; `ONIONWIRE_WALLET_NO_SPEND=1` disables `/tip` locally, before any RPC
|
||||
dial, and a view-only wallet is detected over RPC (`query_key`
|
||||
`key_type=spend_key` → `-29`, `WALLET_RPC_ERROR_CODE_WATCH_ONLY`) so `/tip` says
|
||||
so plainly instead of failing with a raw wallet error. The trade-off is
|
||||
explicit: an OnionWire instance pointed at a **spend-capable** wallet is a local
|
||||
spend authority — any process that can read the RPC credentials can move the
|
||||
balance, and `/tip` gives a chat peer a supported way to ask for a transfer.
|
||||
Loopback binding is not an authorization boundary. Full setup, view-only wallet
|
||||
creation, and the credential/loopback reasoning: [WALLET.md](WALLET.md).
|
||||
|
||||
## Backup file is the identity
|
||||
|
||||
`/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table.
|
||||
|
|
|
|||
52
docs/TUI.md
52
docs/TUI.md
|
|
@ -351,6 +351,16 @@ Else RGB as today.
|
|||
| box | ratatui `Borders::ALL` (light) | `+` `-` `\|` via `border::Set` |
|
||||
| alert prefix | `! ` | `! ` |
|
||||
| stale | word `stale` | `stale` |
|
||||
| delivery: delivered | `✓` | `ok` |
|
||||
| delivery: queued | `◷` | (word) `queued` |
|
||||
| delivery: sending | `»` | (word) `sending` |
|
||||
| delivery: failed | `✗` | (word) `failed` |
|
||||
|
||||
`queued` / `sending` / `failed` always carry their state word, so the ASCII
|
||||
fallback drops the glyph instead of inventing one. Only `✓` is wordless, so it
|
||||
falls back to `ok`. `delivery_glyph()` /
|
||||
`tests/tui_spec.rs::delivery_markers_have_exercised_ascii_fallbacks` exercise the
|
||||
fallback path.
|
||||
|
||||
No emoji. `onion_glyph()` stays for callers that already use it; do not put it
|
||||
on the main header.
|
||||
|
|
@ -401,6 +411,9 @@ Do not soften fail-closed into a loader.
|
|||
| sending | `sending` (keep, no spinner) |
|
||||
| sent | `sent` |
|
||||
| peer down / send err | `send failed: {e}` (visible) |
|
||||
| queued (outbox) | `{n} queued` — replaces the flat `sent`/`send failed` while rows are outstanding |
|
||||
| queued + terminal failure | `{n} queued, send failed: {short}` |
|
||||
| terminal failure | `send failed: {short}` (`{f} failed` when more than one) |
|
||||
| already sending | `already sending` (keep) |
|
||||
| stale friend | `stale` suffix (keep) |
|
||||
| empty composer | `message` as dim placeholder (not the slash list). Slash list stays in `?` |
|
||||
|
|
@ -570,3 +583,42 @@ cargo test --locked --test tui_spec -- --nocapture dump_spec_frames
|
|||
Copy wired in `src/tui.rs` (not in the reconstructed standin): empty thread is
|
||||
`no messages` / `type below, Enter sends`; paste error is `{err}` then
|
||||
`Enter resubmits Esc back`; alerts truncate to the frame width.
|
||||
|
||||
## Delivery state (outbox) — implemented
|
||||
|
||||
Per-message state, read from the local outbox. The states are the store's own
|
||||
(`Queued` / `Sending` / `Sent` / `Failed`) — no parallel model, no new wire
|
||||
prefix, no server.
|
||||
|
||||
| Row | Marker |
|
||||
|---|---|
|
||||
| delivered | `you: ping ✓` |
|
||||
| queued (2nd attempt, 45s out) | `you: pong ◷ queued (try 2/8, retry 45s)` |
|
||||
| sending | `you: pong » sending` |
|
||||
| failed | `you: pong ✗ failed: connection timed out` |
|
||||
| inbound | `them: pong` (no marker) |
|
||||
|
||||
- `try {n}/{8}` is the outbox attempt count; `retry {s}s` / `retry {m}m` /
|
||||
`retry now` comes from the stored absolute `next_attempt_at`.
|
||||
- Failed reasons are sanitized, cut to the tail of the `a: b: c` chain and
|
||||
capped at 24 cells (`short_send_reason`).
|
||||
- Footer while rows are outstanding: `{n} queued`; any terminal failure keeps a
|
||||
fail-closed `send failed: {short}` statement (with `! ` when colour is off).
|
||||
- The tag trails the body and wraps with it, so it is never clipped away.
|
||||
|
||||
Correlation: a delivered row is deleted from the outbox, so an outbound message
|
||||
with no row is `Sent`; pending rows are matched to messages by body, newest send
|
||||
first (`chat_with_delivery`). The outbox holds no message id the UI can join on,
|
||||
so two identical bodies where only the newer one is still queued attach the
|
||||
marker to the newer send. An id-bearing accessor would remove that last
|
||||
ambiguity; see the follow-up card noted in the PR.
|
||||
|
||||
### Size floor / target
|
||||
|
||||
- **Floor: 80x24.** Everything above must render there.
|
||||
- **Target: 120x40.**
|
||||
- `tests/tui_spec.rs::chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping`
|
||||
draws the real `draw_chat` + `status_footer` at 80x24 and asserts every chat
|
||||
and footer row is `<=` the terminal width, that the markers render, and that
|
||||
an over-long message wraps instead of being clipped.
|
||||
- Dump frames: `cargo test --locked --test tui_spec -- --nocapture dump_spec_frames`.
|
||||
|
|
|
|||
184
docs/WALLET.md
Normal file
184
docs/WALLET.md
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
# OnionWire + monero-wallet-rpc
|
||||
|
||||
OnionWire is not a wallet. It never holds a seed, a spend key, or a view key.
|
||||
It talks optional JSON-RPC to a `monero-wallet-rpc` that **you** run, on
|
||||
loopback, only to:
|
||||
|
||||
- hand out a receive subaddress for `/pay` invoices (`create_address`),
|
||||
- read incoming transfers to verify a peer's receipt (`get_transfers`),
|
||||
- and — only if you let it — spend for `/tip` (`transfer`).
|
||||
|
||||
**Run it view-only, and switch `/tip` off explicitly.** Everything else in this
|
||||
document explains why, and what breaks when you do.
|
||||
|
||||
## Env vars
|
||||
|
||||
| Variable | Meaning |
|
||||
|---|---|
|
||||
| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]`. Unset → no wallet; chat still works and `/pay` falls back to the profile `xmr_addr`. |
|
||||
| `ONIONWIRE_WALLET_RPC_LOGIN` | `user:pass` when you do not want the password in the URL. Ignored if the URL carries userinfo. |
|
||||
| `ONIONWIRE_WALLET_NO_SPEND` | `1` / `true` / `yes` / `on` → view-only deployment: `/tip` is refused locally, before any RPC dial. `/pay` and receipt verification keep working. |
|
||||
|
||||
`README.md` carries the operator summary; this file is the long form.
|
||||
|
||||
## Recommended topology
|
||||
|
||||
```
|
||||
wallet host (this machine)
|
||||
┌──────────────────────────────────────────────────────────────┐
|
||||
│ monero-wallet-rpc --rpc-bind-ip 127.0.0.1 --rpc-login u:p │
|
||||
│ ▲ HTTP Digest, loopback only │
|
||||
│ │ │
|
||||
│ OnionWire (ONIONWIRE_WALLET_NO_SPEND=1) ── /pay, receipts │
|
||||
│ └── /tip refused locally │
|
||||
└──────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Loopback is the only address OnionWire will dial. `.onion` RPC URLs are
|
||||
rejected: there is no Arti dial for the wallet, and a remote wallet would move
|
||||
your key material off the box.
|
||||
|
||||
## Create a view-only wallet
|
||||
|
||||
Either path produces a wallet file with the view key only. Keep the seed /
|
||||
spend key on a machine that is **not** running OnionWire.
|
||||
|
||||
With `monero-wallet-cli` (`--generate-from-view-key` prompts for the *standard*
|
||||
address the view key belongs to, then the secret view key):
|
||||
|
||||
```bash
|
||||
monero-wallet-cli --generate-from-view-key "$HOME/.onionwire-viewonly" \
|
||||
--daemon-address "$YOUR_MONEROD:18089" --restore-height "$BIRTH_HEIGHT"
|
||||
# Standard address: 4...
|
||||
# Secret view key: <hex>
|
||||
```
|
||||
|
||||
Or through a running RPC that was started with `--wallet-dir` (`generate_from_keys`
|
||||
without `spendkey` writes a watch-only wallet):
|
||||
|
||||
```bash
|
||||
curl -u onionwire:secret http://127.0.0.1:18083/json_rpc \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"jsonrpc":"2.0","id":"0","method":"generate_from_keys","params":{
|
||||
"filename":"viewonly","password":"walletpass",
|
||||
"address":"4...","viewkey":"<hex>","restore_height":<height>}}'
|
||||
# → "Watch-only wallet has been generated successfully."
|
||||
```
|
||||
|
||||
Then serve it:
|
||||
|
||||
```bash
|
||||
monero-wallet-rpc --wallet-file "$HOME/.onionwire-viewonly" \
|
||||
--rpc-bind-ip 127.0.0.1 --rpc-bind-port 18083 --rpc-login onionwire:secret \
|
||||
--daemon-address "$YOUR_MONEROD:18089"
|
||||
|
||||
export ONIONWIRE_WALLET_RPC=http://127.0.0.1:18083
|
||||
export ONIONWIRE_WALLET_RPC_LOGIN=onionwire:secret
|
||||
export ONIONWIRE_WALLET_NO_SPEND=1
|
||||
```
|
||||
|
||||
Restore the wallet from a height *at or before* its first incoming transaction
|
||||
— a view-only wallet cannot rescan cheaply from height 0.
|
||||
|
||||
## What works, what does not
|
||||
|
||||
| Feature | View-only | Spend-capable |
|
||||
|---|---|---|
|
||||
| `/pay <xmr>` invoice subaddress (`create_address`) | works | works |
|
||||
| Receipt verification (`get_transfers`) | works | works |
|
||||
| Profile `xmr_addr` fallback when RPC is down | works | works |
|
||||
| `/tip <xmr>` (`transfer`) | **cannot work** | works |
|
||||
| OnionWire learns your spend key | never | never (it stays in the wallet) |
|
||||
|
||||
With `ONIONWIRE_WALLET_NO_SPEND=1` a `/tip` is refused before the RPC is
|
||||
contacted, with:
|
||||
|
||||
```
|
||||
wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work
|
||||
```
|
||||
|
||||
Without the flag, `/tip` against a view-only wallet fails at the wallet and
|
||||
OnionWire then asks the wallet directly whether it can spend (see below), so you
|
||||
get the same sentence instead of a raw RPC error.
|
||||
|
||||
## How OnionWire detects view-only over RPC
|
||||
|
||||
The signal people usually reach for is `query_key` with `key_type=mnemonic`. It
|
||||
works, but it is the wrong key to ask for: on a spend-capable wallet it hands
|
||||
over the whole seed (full spend ability) over loopback HTTP, and it answers
|
||||
`-43` for wallets that have no mnemonic at all. The spend key is narrower and
|
||||
just as unambiguous:
|
||||
|
||||
```
|
||||
query_key {"key_type":"spend_key"}
|
||||
spend-capable → result.key = <hex secret spend key>
|
||||
view-only → error code -29, "The wallet is watch-only. Cannot retrieve spend key."
|
||||
```
|
||||
|
||||
(`query_key key_type=mnemonic` returns `-29` for a view-only wallet too, so the
|
||||
two agree — OnionWire asks for the spend key because it is the smaller secret.)
|
||||
|
||||
- Method: [`query_key`](https://www.getmonero.org/resources/developer-guides/wallet-rpc.html#query_key)
|
||||
- `-29` is `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in
|
||||
[`wallet_rpc_server_error_codes.h`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server_error_codes.h)
|
||||
- The view-only branch is `on_query_key` in
|
||||
[`wallet_rpc_server.cpp`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server.cpp)
|
||||
|
||||
OnionWire only calls this **after** a `transfer` has already failed — it never
|
||||
probes a healthy wallet — and it discards `result.key` immediately. There is no
|
||||
RPC method that reports "view-only" as a plain field; `query_key` is the
|
||||
documented signal and this is its only cost: a spend-capable wallet answers with
|
||||
its spend key over loopback HTTP, which is one more reason to run view-only.
|
||||
|
||||
Fail-closed details: if the probe cannot answer (wallet down, `--restricted-rpc`
|
||||
answers `-7 DENIED` instead), OnionWire surfaces the wallet's own error
|
||||
unchanged. It never guesses "view-only" from an unrelated failure.
|
||||
|
||||
## Why loopback still needs authentication
|
||||
|
||||
`--rpc-bind-ip 127.0.0.1` keeps the port off the network; it does **not** keep it
|
||||
away from other users or processes on the same machine. Any local process can
|
||||
`connect(127.0.0.1:18083)`.
|
||||
|
||||
- OnionWire refuses an RPC that answers HTTP 200 without a Digest challenge, and
|
||||
refuses URLs without credentials. Unset the credentials and the wallet is open
|
||||
to every local process — with a spend-capable wallet file, that is a
|
||||
one-curl drain of your balance.
|
||||
- `--rpc-login` is HTTP Digest (MD5), so the password is not sent in cleartext,
|
||||
but Digest gives no confidentiality: a local attacker who can sniff loopback
|
||||
can replay it. Treat loopback as trusted-ish, not safe.
|
||||
- Do not log the password, and do not put it in a shell history you share.
|
||||
Prefer `ONIONWIRE_WALLET_RPC_LOGIN` over userinfo in the URL.
|
||||
|
||||
## The spend-authority warning
|
||||
|
||||
An OnionWire instance pointed at a **spend-capable** `monero-wallet-rpc` is a
|
||||
local spend authority: any process that can read the RPC credentials (env var,
|
||||
`/proc/<pid>/environ`, shell history, a stored URL) can spend the wallet's
|
||||
balance, and `/tip` gives a chat peer a supported path to ask for a transfer.
|
||||
|
||||
That is why view-only plus `ONIONWIRE_WALLET_NO_SPEND=1` is the recommended
|
||||
default:
|
||||
|
||||
- the wallet file holds no spend key, so a stolen wallet file cannot be used to
|
||||
move funds;
|
||||
- the RPC credentials grant only receive-address and history reads;
|
||||
- `/tip` fails locally with a plain message, so nothing in the UI pretends the
|
||||
spend path exists.
|
||||
|
||||
If you want tips to work, understand that you are deliberately making the
|
||||
OnionWire process able to spend. Give it a **separate hot wallet with a small
|
||||
balance**, not your savings wallet.
|
||||
|
||||
## References
|
||||
|
||||
- Monero Wallet RPC reference:
|
||||
<https://www.getmonero.org/resources/developer-guides/wallet-rpc.html>
|
||||
- `on_query_key` (view-only → `-29`):
|
||||
<https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server.cpp>
|
||||
- `WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29`:
|
||||
<https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server_error_codes.h>
|
||||
- `--generate-from-view-key` (incoming-only wallet):
|
||||
<https://github.com/monero-project/monero/blob/master/src/simplewallet/simplewallet.cpp>
|
||||
- `generate_from_keys` (watch-only when `spendkey` is omitted):
|
||||
<https://www.getmonero.org/resources/developer-guides/wallet-rpc.html#generate_from_keys>
|
||||
|
|
@ -23,9 +23,10 @@ pub struct Loc {
|
|||
const PREFIX: &[u8] = b"loc ";
|
||||
|
||||
pub fn sign(identity_sk: &[u8], onion: &str, ts: i64) -> Result<Loc> {
|
||||
let sk_bytes: [u8; 32] = identity_sk
|
||||
.try_into()
|
||||
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?;
|
||||
// Same one-shot raw identity-secret copy as `profile::sign`; shared so
|
||||
// `Zeroize` covers it here too.
|
||||
let sk_bytes =
|
||||
crate::profile::signing_key_bytes(identity_sk).map_err(|e| Error(e.to_string()))?;
|
||||
let sk = SigningKey::from_bytes(&sk_bytes);
|
||||
let sig = sk.sign(&sign_msg_v2(onion, ts)).to_bytes().to_vec();
|
||||
Ok(Loc {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
|
|
@ -30,6 +31,23 @@ pub fn validate(display_name: &str, bio: &str, xmr_addr: &str) -> Result<()> {
|
|||
check_fields(display_name, bio, xmr_addr)
|
||||
}
|
||||
|
||||
/// The raw 32-byte identity-secret copy that `ed25519-dalek` needs in order to
|
||||
/// build a `SigningKey`.
|
||||
///
|
||||
/// `SigningKey` wipes its own copy on drop (its default `zeroize` feature);
|
||||
/// the raw bytes are ours to wipe, so they live in a `Zeroizing` buffer rather
|
||||
/// than on the stack in a bare `[u8; 32]`. Same pattern as `pay::sign_bytes`
|
||||
/// and `qr::encode`; `loc::sign` shares this helper for the identical copy it
|
||||
/// used to make.
|
||||
pub fn signing_key_bytes(identity_sk: &[u8]) -> Result<Zeroizing<[u8; 32]>> {
|
||||
if identity_sk.len() != 32 {
|
||||
return Err(Error("identity secret key must be 32 bytes".into()));
|
||||
}
|
||||
let mut bytes = Zeroizing::new([0u8; 32]);
|
||||
bytes[..].copy_from_slice(identity_sk);
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
pub fn sign(
|
||||
identity_sk: &[u8],
|
||||
display_name: &str,
|
||||
|
|
@ -38,9 +56,7 @@ pub fn sign(
|
|||
ts: i64,
|
||||
) -> Result<Profile> {
|
||||
check_fields(display_name, bio, xmr_addr)?;
|
||||
let sk_bytes: [u8; 32] = identity_sk
|
||||
.try_into()
|
||||
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?;
|
||||
let sk_bytes = signing_key_bytes(identity_sk)?;
|
||||
let sk = SigningKey::from_bytes(&sk_bytes);
|
||||
let sig = sk
|
||||
.sign(&sign_msg_v2(display_name, bio, xmr_addr, ts))
|
||||
|
|
|
|||
555
src/tui.rs
555
src/tui.rs
|
|
@ -1,6 +1,7 @@
|
|||
use std::collections::HashMap;
|
||||
use std::io::{self, IsTerminal};
|
||||
use std::sync::{Arc, mpsc};
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
|
||||
use ratatui::layout::{Constraint, Layout, Rect};
|
||||
|
|
@ -8,11 +9,13 @@ use ratatui::style::{Color, Modifier, Style};
|
|||
use ratatui::symbols::border;
|
||||
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
|
||||
use ratatui::{DefaultTerminal, Frame};
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
use crate::node::Node;
|
||||
use crate::outbox::DEFAULT_MAX_ATTEMPTS;
|
||||
use crate::qr::{self, QrPayload};
|
||||
use crate::sanitize;
|
||||
use crate::store::{Friend, FriendProfile};
|
||||
use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus};
|
||||
|
||||
const C_ACCENT: Color = Color::Rgb(232, 165, 75);
|
||||
const C_TEXT: Color = Color::Rgb(196, 214, 176);
|
||||
|
|
@ -116,6 +119,202 @@ pub fn empty_friend_chat_text() -> &'static str {
|
|||
"no messages\ntype below, Enter sends"
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Delivery state (outbox)
|
||||
//
|
||||
// The outbox is the only source of per-message state: `Queued` / `Sending` /
|
||||
// `Failed` rows are what `Node::outbox_pending` still holds, and a row is
|
||||
// deleted the moment the send crosses the circuit — so an outbound message with
|
||||
// no row is `Sent`. No parallel state model, no new wire prefix.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Longest short-form failure reason shown in a chat row.
|
||||
pub const FAIL_REASON_BUDGET: usize = 24;
|
||||
|
||||
/// Marker glyph for one delivery state. ASCII chrome falls back to `ok` for the
|
||||
/// wordless delivered state; `queued` / `sending` / `failed` already carry their
|
||||
/// word, so their glyph is dropped rather than invented.
|
||||
pub fn delivery_glyph(status: &OutboxStatus) -> &'static str {
|
||||
let ascii = ascii_chrome();
|
||||
match status {
|
||||
OutboxStatus::Sent => {
|
||||
if ascii {
|
||||
"ok"
|
||||
} else {
|
||||
"✓"
|
||||
}
|
||||
}
|
||||
OutboxStatus::Queued => {
|
||||
if ascii {
|
||||
""
|
||||
} else {
|
||||
"◷"
|
||||
}
|
||||
}
|
||||
OutboxStatus::Sending => {
|
||||
if ascii {
|
||||
""
|
||||
} else {
|
||||
"»"
|
||||
}
|
||||
}
|
||||
OutboxStatus::Failed(_) => {
|
||||
if ascii {
|
||||
""
|
||||
} else {
|
||||
"✗"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Next-attempt age for a queued row, from the absolute `next_attempt_at` the
|
||||
/// outbox stores.
|
||||
pub fn retry_in_text(next_in_secs: i64) -> String {
|
||||
if next_in_secs <= 0 {
|
||||
"retry now".to_string()
|
||||
} else if next_in_secs < 60 {
|
||||
format!("retry {next_in_secs}s")
|
||||
} else {
|
||||
format!("retry {}m", (next_in_secs + 59) / 60)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn short_send_reason(why: &str, budget: usize) -> String {
|
||||
let clean = sanitize::display_text(why.as_bytes());
|
||||
let tail = clean.rsplit(": ").next().unwrap_or("").trim();
|
||||
let text = if tail.is_empty() { clean.trim() } else { tail };
|
||||
truncate_chars(text, budget)
|
||||
}
|
||||
|
||||
/// One row's delivery marker, straight from the outbox state.
|
||||
pub fn delivery_tag(status: &OutboxStatus, attempts: u32, next_in_secs: i64) -> String {
|
||||
let glyph = delivery_glyph(status);
|
||||
let body = match status {
|
||||
OutboxStatus::Sent => String::new(),
|
||||
OutboxStatus::Queued => format!(
|
||||
"queued (try {attempts}/{DEFAULT_MAX_ATTEMPTS}, {})",
|
||||
retry_in_text(next_in_secs)
|
||||
),
|
||||
OutboxStatus::Sending => "sending".to_string(),
|
||||
OutboxStatus::Failed(why) => {
|
||||
format!("failed: {}", short_send_reason(why, FAIL_REASON_BUDGET))
|
||||
}
|
||||
};
|
||||
match (glyph.is_empty(), body.is_empty()) {
|
||||
(_, true) => glyph.to_string(),
|
||||
(true, false) => body,
|
||||
(false, false) => format!("{glyph} {body}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Footer summary derived from the outbox rows of the selected friend.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct OutboxSummary {
|
||||
/// `Queued` + `Sending`: rows the worker may still deliver.
|
||||
pub queued: usize,
|
||||
/// Terminal failures — these never retry.
|
||||
pub failed: usize,
|
||||
/// First terminal failure, for the fail-closed footer copy.
|
||||
pub first_error: Option<String>,
|
||||
}
|
||||
|
||||
impl OutboxSummary {
|
||||
/// Footer note, or `None` when nothing is outstanding. Any terminal failure
|
||||
/// keeps a `send failed` statement so the fail-closed copy stays visible.
|
||||
pub fn note(&self) -> Option<String> {
|
||||
let reason = || {
|
||||
short_send_reason(
|
||||
self.first_error.as_deref().unwrap_or("unknown"),
|
||||
FAIL_REASON_BUDGET,
|
||||
)
|
||||
};
|
||||
match (self.queued, self.failed) {
|
||||
(0, 0) => None,
|
||||
(queued, 0) => Some(format!("{queued} queued")),
|
||||
(0, 1) => Some(format!("send failed: {}", reason())),
|
||||
(0, failed) => Some(format!("send failed: {} ({failed} failed)", reason())),
|
||||
(queued, _) => Some(format!("{queued} queued, send failed: {}", reason())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Chat transcript with per-message delivery state, plus the footer summary.
|
||||
///
|
||||
/// Pending rows are matched to messages by body, newest send first: an
|
||||
/// outstanding retry is the most recent send of that text, and the outbox holds
|
||||
/// no message id the UI could join on.
|
||||
pub fn chat_with_delivery(
|
||||
msgs: &[Message],
|
||||
pending: &[OutboxEntry],
|
||||
now: i64,
|
||||
) -> (Vec<String>, OutboxSummary) {
|
||||
let mut summary = OutboxSummary::default();
|
||||
for entry in pending {
|
||||
match &entry.status {
|
||||
OutboxStatus::Failed(why) => {
|
||||
summary.failed += 1;
|
||||
summary.first_error.get_or_insert_with(|| why.clone());
|
||||
}
|
||||
_ => summary.queued += 1,
|
||||
}
|
||||
}
|
||||
if msgs.is_empty() {
|
||||
return (
|
||||
empty_friend_chat_text()
|
||||
.lines()
|
||||
.map(str::to_string)
|
||||
.collect(),
|
||||
summary,
|
||||
);
|
||||
}
|
||||
|
||||
let mut by_body: HashMap<&[u8], Vec<&OutboxEntry>> = HashMap::new();
|
||||
for entry in pending {
|
||||
by_body
|
||||
.entry(entry.body.as_slice())
|
||||
.or_default()
|
||||
.push(entry);
|
||||
}
|
||||
let mut tags: Vec<Option<String>> = vec![None; msgs.len()];
|
||||
for (i, msg) in msgs.iter().enumerate().rev() {
|
||||
if msg.dir != "out" {
|
||||
continue;
|
||||
}
|
||||
if let Some(rows) = by_body.get_mut(msg.plaintext.as_slice())
|
||||
&& let Some(entry) = rows.pop()
|
||||
{
|
||||
tags[i] = Some(delivery_tag(
|
||||
&entry.status,
|
||||
entry.attempts,
|
||||
entry.next_attempt_at - now,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let lines = msgs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, msg)| {
|
||||
let side = if msg.dir == "out" { "you" } else { "them" };
|
||||
let body = sanitize::display_text(&msg.plaintext);
|
||||
let tag = match tags[i].clone() {
|
||||
Some(tag) => tag,
|
||||
None if msg.dir == "out" => delivery_tag(&OutboxStatus::Sent, 0, 0),
|
||||
None => String::new(),
|
||||
};
|
||||
if tag.is_empty() {
|
||||
format!("{side}: {body}")
|
||||
} else {
|
||||
format!("{side}: {body} {tag}")
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
(lines, summary)
|
||||
}
|
||||
|
||||
/// Paste overlay copy. Error keeps the resubmit hint.
|
||||
pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String {
|
||||
let hint = match err {
|
||||
|
|
@ -761,6 +960,78 @@ impl BackupPrompt {
|
|||
}
|
||||
}
|
||||
|
||||
/// The in-progress passphrase on the backup/restore screen: the hidden buffer
|
||||
/// plus the first entry, kept across the second prompt of the backup flow.
|
||||
///
|
||||
/// Both are `Zeroizing<String>`, so the passphrase does not sit in a plain
|
||||
/// heap `String` for the life of the screen; `close()` wipes eagerly on every
|
||||
/// exit path (submit, mismatch, cancel) instead of waiting for the screen
|
||||
/// value to be dropped, and the wrapper covers the paths that cannot call it
|
||||
/// (Ctrl-Q, a panic).
|
||||
pub struct PassphraseEntry {
|
||||
first: Option<Zeroizing<String>>,
|
||||
buf: Zeroizing<String>,
|
||||
}
|
||||
|
||||
impl Default for PassphraseEntry {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
first: None,
|
||||
buf: Zeroizing::new(String::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PassphraseEntry {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Second prompt of the backup flow: the first passphrase was already typed.
|
||||
pub fn with_first(first: &str) -> Self {
|
||||
Self {
|
||||
first: Some(Zeroizing::new(first.to_string())),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push(&mut self, c: char) {
|
||||
self.buf.push(c);
|
||||
}
|
||||
|
||||
pub fn backspace(&mut self) {
|
||||
self.buf.pop();
|
||||
}
|
||||
|
||||
/// What the screen echoes back — the passphrase itself is not drawn.
|
||||
pub fn buf(&self) -> &str {
|
||||
self.buf.as_str()
|
||||
}
|
||||
|
||||
pub fn first(&self) -> Option<&str> {
|
||||
self.first.as_deref().map(String::as_str)
|
||||
}
|
||||
|
||||
/// Take the typed passphrase for submission, leaving this entry empty.
|
||||
pub fn take_buf(&mut self) -> Zeroizing<String> {
|
||||
std::mem::replace(&mut self.buf, Zeroizing::new(String::new()))
|
||||
}
|
||||
|
||||
/// Take the first-passphrase copy for the confirm comparison.
|
||||
pub fn take_first(&mut self) -> Option<Zeroizing<String>> {
|
||||
self.first.take()
|
||||
}
|
||||
|
||||
/// Wipe both buffers: the screen is done with them.
|
||||
pub fn close(&mut self) {
|
||||
self.buf.zeroize();
|
||||
if let Some(first) = self.first.as_mut() {
|
||||
first.zeroize();
|
||||
}
|
||||
self.first = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn backup_screen_text() -> &'static str {
|
||||
"Write encrypted identity backup?\n\
|
||||
This file is your identity secret. Treat it like the database.\n\
|
||||
|
|
@ -840,8 +1111,7 @@ enum Screen {
|
|||
Passphrase {
|
||||
kind: BackupKind,
|
||||
path: String,
|
||||
first: Option<String>,
|
||||
buf: String,
|
||||
entry: PassphraseEntry,
|
||||
},
|
||||
Quit {
|
||||
prompt: QuitPrompt,
|
||||
|
|
@ -929,6 +1199,7 @@ impl App {
|
|||
let mut tip_cmd = None;
|
||||
let mut file_cmd = None;
|
||||
let mut chat_send = None;
|
||||
let mut pass_submit = None;
|
||||
match &mut self.screen {
|
||||
Screen::Main => match key.code {
|
||||
KeyCode::Tab => self.focus = self.focus.next(),
|
||||
|
|
@ -1090,8 +1361,7 @@ impl App {
|
|||
self.screen = Screen::Passphrase {
|
||||
kind,
|
||||
path: path.clone(),
|
||||
first: None,
|
||||
buf: String::new(),
|
||||
entry: PassphraseEntry::new(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1101,25 +1371,17 @@ impl App {
|
|||
_ => {}
|
||||
}
|
||||
}
|
||||
Screen::Passphrase {
|
||||
kind,
|
||||
path,
|
||||
first,
|
||||
buf,
|
||||
} => match key.code {
|
||||
KeyCode::Esc => self.screen = Screen::Main,
|
||||
KeyCode::Backspace => {
|
||||
buf.pop();
|
||||
Screen::Passphrase { kind, path, entry } => match key.code {
|
||||
KeyCode::Esc => {
|
||||
entry.close();
|
||||
self.screen = Screen::Main;
|
||||
}
|
||||
KeyCode::Backspace => entry.backspace(),
|
||||
KeyCode::Enter => {
|
||||
let kind = *kind;
|
||||
let path = path.clone();
|
||||
let first = first.clone();
|
||||
let pass = buf.clone();
|
||||
self.submit_passphrase(kind, &path, first.as_deref(), &pass)?;
|
||||
pass_submit = Some((*kind, path.clone(), entry.take_first(), entry.take_buf()));
|
||||
}
|
||||
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
buf.push(c);
|
||||
entry.push(c);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
|
|
@ -1166,6 +1428,9 @@ impl App {
|
|||
if let Some(text) = chat_send {
|
||||
self.send_chat(&text)?;
|
||||
}
|
||||
if let Some((kind, path, first, pass)) = pass_submit {
|
||||
self.submit_passphrase(kind, &path, first.as_deref().map(String::as_str), &pass)?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
|
|
@ -1279,8 +1544,7 @@ impl App {
|
|||
self.screen = Screen::Passphrase {
|
||||
kind,
|
||||
path: path.to_string(),
|
||||
first: Some(pass.to_string()),
|
||||
buf: String::new(),
|
||||
entry: PassphraseEntry::with_first(pass),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1449,11 +1713,13 @@ impl App {
|
|||
let (tx, rx) = mpsc::channel();
|
||||
self.status_note = Some("sending".into());
|
||||
std::mem::drop(self.rt.spawn(async move {
|
||||
// send() now reports `Sent`/`Queued`; surfacing `queued` in the
|
||||
// footer is a follow-up card, so this arm keeps today's wording.
|
||||
// `send()` reports `Sent` when the circuit took it and `Queued` when
|
||||
// the peer's onion is unreachable. The footer then reads the real
|
||||
// row count from the outbox, so this note is only the first word.
|
||||
let note = match node.send(&pk, &body).await {
|
||||
Ok(_) => "sent".to_string(),
|
||||
Err(e) => format!("send failed: {e}"),
|
||||
Ok(OutboxStatus::Sent) => "sent".to_string(),
|
||||
Ok(_) => "queued".to_string(),
|
||||
Err(e) => format!("send failed: {}", short_send_reason(&e, FAIL_REASON_BUDGET)),
|
||||
};
|
||||
let _ = tx.send(note);
|
||||
}));
|
||||
|
|
@ -1487,9 +1753,9 @@ impl App {
|
|||
Screen::Wipe { kind, prompt } => draw_wipe(f, *kind, prompt.typed()),
|
||||
Screen::Profile { editor } => draw_profile(f, editor),
|
||||
Screen::ConfirmKeys { kind, prompt, .. } => draw_confirm_keys(f, *kind, prompt.typed()),
|
||||
Screen::Passphrase {
|
||||
kind, first, buf, ..
|
||||
} => draw_passphrase(f, *kind, first.is_some(), buf),
|
||||
Screen::Passphrase { kind, entry, .. } => {
|
||||
draw_passphrase(f, *kind, entry.first().is_some(), entry.buf())
|
||||
}
|
||||
Screen::Quit { prompt } => draw_quit(f, prompt.typed()),
|
||||
}
|
||||
if self.help_open {
|
||||
|
|
@ -1563,38 +1829,22 @@ impl App {
|
|||
}
|
||||
f.render_stateful_widget(roster, panes[0], &mut roster_state);
|
||||
|
||||
let chat_lines = self.chat_lines();
|
||||
let inner_h = panes[1].height.saturating_sub(2);
|
||||
let nlines = chat_lines.len();
|
||||
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
|
||||
let scroll = self.chat_scroll.min(max_scroll);
|
||||
let overflow = nlines > inner_h as usize && inner_h > 0;
|
||||
let chat_title = {
|
||||
let name = self.friends.get(self.selected).map(|friend| {
|
||||
friend
|
||||
.petname
|
||||
.as_deref()
|
||||
.unwrap_or(&friend.fingerprint)
|
||||
.to_string()
|
||||
});
|
||||
let mut t = match name {
|
||||
Some(n) => format!("chat {n}"),
|
||||
None => "chat".to_string(),
|
||||
};
|
||||
if overflow {
|
||||
let end = (scroll as usize + inner_h as usize).min(nlines);
|
||||
t.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
|
||||
}
|
||||
let mark = if self.focus == Pane::Chat { "> " } else { " " };
|
||||
format!("{mark}{t}")
|
||||
};
|
||||
let chat_text = chat_lines.join("\n");
|
||||
let chat = Paragraph::new(chat_text)
|
||||
.style(style_text())
|
||||
.wrap(Wrap { trim: false })
|
||||
.scroll((scroll, 0))
|
||||
.block(self.pane_block(&chat_title, Pane::Chat));
|
||||
f.render_widget(chat, panes[1]);
|
||||
let (chat_lines, summary) = self.chat_view();
|
||||
let chat_name = self.friends.get(self.selected).map(|friend| {
|
||||
friend
|
||||
.petname
|
||||
.as_deref()
|
||||
.unwrap_or(&friend.fingerprint)
|
||||
.to_string()
|
||||
});
|
||||
draw_chat(
|
||||
f,
|
||||
panes[1],
|
||||
&chat_lines,
|
||||
chat_name.as_deref(),
|
||||
self.focus == Pane::Chat,
|
||||
self.chat_scroll,
|
||||
);
|
||||
|
||||
let mark = if self.focus == Pane::Composer {
|
||||
"> "
|
||||
|
|
@ -1618,62 +1868,108 @@ impl App {
|
|||
cols[3],
|
||||
);
|
||||
|
||||
let footer = self.footer_line(area.width);
|
||||
let footer = self.footer_line(area.width, &summary);
|
||||
f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]);
|
||||
}
|
||||
|
||||
fn footer_line(&self, width: u16) -> String {
|
||||
fn footer_line(&self, width: u16, summary: &OutboxSummary) -> String {
|
||||
// The outbox is the source of truth while anything is outstanding; the
|
||||
// transient note still covers "sending", "sent file x", "invoice sent".
|
||||
let note = summary.note().or_else(|| self.status_note.clone());
|
||||
status_footer(
|
||||
width,
|
||||
&self.me_fp,
|
||||
&self.me_onion,
|
||||
self.status_note.as_deref(),
|
||||
note.as_deref(),
|
||||
footer_hints(&self.screen),
|
||||
)
|
||||
}
|
||||
|
||||
fn chat_lines(&self) -> Vec<String> {
|
||||
fn chat_view(&self) -> (Vec<String>, OutboxSummary) {
|
||||
let Some(friend) = self.friends.get(self.selected) else {
|
||||
return vec![
|
||||
"no friends yet".into(),
|
||||
"F3 paste an invite to add one".into(),
|
||||
];
|
||||
return (
|
||||
vec![
|
||||
"no friends yet".into(),
|
||||
"F3 paste an invite to add one".into(),
|
||||
],
|
||||
OutboxSummary::default(),
|
||||
);
|
||||
};
|
||||
match self.node.list_messages(&friend.pubkey) {
|
||||
Ok(msgs) if msgs.is_empty() => empty_friend_chat_text()
|
||||
.lines()
|
||||
.map(str::to_string)
|
||||
.collect(),
|
||||
Ok(msgs) => msgs
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let side = if m.dir == "out" { "you" } else { "them" };
|
||||
format!("{side}: {}", sanitize::display_text(&m.plaintext))
|
||||
})
|
||||
.collect(),
|
||||
Err(e) => vec![e],
|
||||
Ok(msgs) => {
|
||||
let pending = self.node.outbox_pending(&friend.pubkey).unwrap_or_default();
|
||||
chat_with_delivery(&msgs, &pending, unix_now_secs())
|
||||
}
|
||||
Err(e) => (vec![e], OutboxSummary::default()),
|
||||
}
|
||||
}
|
||||
|
||||
fn pane_block<'a>(&self, title: &'a str, pane: Pane) -> Block<'a> {
|
||||
let focused = self.focus == pane;
|
||||
let border = if focused {
|
||||
style_accent()
|
||||
} else {
|
||||
style_border()
|
||||
};
|
||||
let title_style = if focused {
|
||||
style_accent().add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
style_dim()
|
||||
};
|
||||
apply_chrome_borders(Block::default())
|
||||
.border_style(border)
|
||||
.title(title)
|
||||
.title_style(title_style)
|
||||
pane_block_for(title, self.focus == pane)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pane chrome without an `App`: focus is accent border + bold title, never
|
||||
/// color alone (the `> ` marks come from the callers).
|
||||
fn pane_block_for(title: &str, focused: bool) -> Block<'_> {
|
||||
let border = if focused {
|
||||
style_accent()
|
||||
} else {
|
||||
style_border()
|
||||
};
|
||||
let title_style = if focused {
|
||||
style_accent().add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
style_dim()
|
||||
};
|
||||
apply_chrome_borders(Block::default())
|
||||
.border_style(border)
|
||||
.title(title)
|
||||
.title_style(title_style)
|
||||
}
|
||||
|
||||
fn unix_now_secs() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Real chat-pane renderer: `App::draw_main` calls this, so width, wrap and
|
||||
/// delivery-marker behaviour are testable without constructing a `Node`.
|
||||
pub fn draw_chat(
|
||||
f: &mut Frame,
|
||||
area: Rect,
|
||||
lines: &[String],
|
||||
name: Option<&str>,
|
||||
focused: bool,
|
||||
scroll: u16,
|
||||
) {
|
||||
let inner_h = area.height.saturating_sub(2);
|
||||
let nlines = lines.len();
|
||||
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
|
||||
let scroll = scroll.min(max_scroll);
|
||||
let overflow = nlines > inner_h as usize && inner_h > 0;
|
||||
let mut title = match name {
|
||||
Some(n) => format!("chat {n}"),
|
||||
None => "chat".to_string(),
|
||||
};
|
||||
if overflow {
|
||||
let end = (scroll as usize + inner_h as usize).min(nlines);
|
||||
title.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
|
||||
}
|
||||
let mark = if focused { "> " } else { " " };
|
||||
let title = format!("{mark}{title}");
|
||||
f.render_widget(
|
||||
Paragraph::new(lines.join("\n"))
|
||||
.style(style_text())
|
||||
.wrap(Wrap { trim: false })
|
||||
.scroll((scroll, 0))
|
||||
.block(pane_block_for(&title, focused)),
|
||||
area,
|
||||
);
|
||||
}
|
||||
|
||||
/// Status bar: never drop a non-empty `status_note`. Always keep `TOR`, `me:`, `? help`.
|
||||
pub fn status_footer(
|
||||
width: u16,
|
||||
|
|
@ -1689,7 +1985,7 @@ pub fn status_footer(
|
|||
let mut note = status_note.unwrap_or("").trim().to_string();
|
||||
if !note.is_empty()
|
||||
&& color_mode() == ColorMode::None
|
||||
&& (note.starts_with("send failed") || note == "fingerprint mismatch")
|
||||
&& (note.contains("send failed") || note == "fingerprint mismatch")
|
||||
&& !note.starts_with("! ")
|
||||
{
|
||||
note = format!("! {note}");
|
||||
|
|
@ -2017,3 +2313,66 @@ fn to_hex(bytes: &[u8]) -> String {
|
|||
fn io_err(e: io::Error) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod passphrase_buffer_tests {
|
||||
use super::*;
|
||||
|
||||
fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
|
||||
|
||||
/// The typed passphrase lives in `Zeroizing` buffers, not in bare
|
||||
/// `String`s that sit in the heap for the life of the screen.
|
||||
#[test]
|
||||
fn passphrase_buffers_are_zeroizing() {
|
||||
let mut entry = PassphraseEntry::new();
|
||||
entry.push('x');
|
||||
|
||||
let _: &Zeroizing<String> = &entry.buf;
|
||||
let _: &Option<Zeroizing<String>> = &entry.first;
|
||||
assert_zeroize_on_drop::<Zeroizing<String>>();
|
||||
}
|
||||
|
||||
/// Closing the screen (submit, mismatch or cancel) must leave nothing of
|
||||
/// the typed passphrase behind in its heap buffer.
|
||||
#[test]
|
||||
fn closing_the_passphrase_screen_wipes_the_typed_secret() {
|
||||
let mut entry = PassphraseEntry::new();
|
||||
for c in "hunter2-secret".chars() {
|
||||
entry.push(c);
|
||||
}
|
||||
assert_eq!(entry.buf(), "hunter2-secret");
|
||||
|
||||
let ptr = entry.buf.as_ptr();
|
||||
let cap = entry.buf.capacity();
|
||||
assert!(cap >= 14, "expected a heap buffer, capacity {cap}");
|
||||
|
||||
entry.close();
|
||||
|
||||
assert!(entry.buf().is_empty(), "buffer not cleared");
|
||||
// SAFETY: `close()` wipes through `Zeroize`, which zeroes the whole
|
||||
// capacity and *keeps* the allocation (`Vec::zeroize`: zero the
|
||||
// elements, clear the length, zero the spare capacity). `entry` still
|
||||
// owns that buffer, so these `cap` bytes are live memory.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(ptr, cap) };
|
||||
assert!(
|
||||
bytes.iter().all(|b| *b == 0),
|
||||
"typed passphrase survived close(): {bytes:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The first entry of the two-step backup flow is a secret too, and the
|
||||
/// screen holds it across the second prompt.
|
||||
#[test]
|
||||
fn closing_the_passphrase_screen_drops_the_first_entry_copy() {
|
||||
let mut entry = PassphraseEntry::with_first("first-typed");
|
||||
assert_eq!(entry.first(), Some("first-typed"));
|
||||
|
||||
entry.close();
|
||||
|
||||
assert_eq!(
|
||||
entry.first(),
|
||||
None,
|
||||
"first passphrase copy survived close()"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,8 +42,18 @@ impl std::fmt::Debug for Endpoint {
|
|||
#[derive(Debug, Clone)]
|
||||
pub struct Wallet {
|
||||
endpoint: Option<Endpoint>,
|
||||
no_spend: bool,
|
||||
}
|
||||
|
||||
/// What /tip says when the wallet cannot spend. Same text for the explicit
|
||||
/// `ONIONWIRE_WALLET_NO_SPEND=1` switch and for a view-only wallet detected over
|
||||
/// RPC, so the operator never has to guess which one it was.
|
||||
const VIEW_ONLY_MSG: &str = "wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work";
|
||||
|
||||
/// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in monero's
|
||||
/// `src/wallet/wallet_rpc_server_error_codes.h`.
|
||||
const WATCH_ONLY_CODE: i64 = -29;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TransferRow {
|
||||
pub txid: String,
|
||||
|
|
@ -55,10 +65,17 @@ const RPC_TIMEOUT: Duration = Duration::from_secs(5);
|
|||
|
||||
impl Wallet {
|
||||
pub fn disabled() -> Self {
|
||||
Self { endpoint: None }
|
||||
Self {
|
||||
endpoint: None,
|
||||
no_spend: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `ONIONWIRE_WALLET_NO_SPEND=1` asks for a view-only deployment: `/tip` is
|
||||
/// refused locally, before any RPC dial. `/pay` and receipt verification
|
||||
/// keep working.
|
||||
pub fn from_env() -> Self {
|
||||
let no_spend = env_flag("ONIONWIRE_WALLET_NO_SPEND");
|
||||
match std::env::var("ONIONWIRE_WALLET_RPC") {
|
||||
// The URL can carry `user:pass@` in its userinfo: keep it in a
|
||||
// wiping buffer, not a bare `String`.
|
||||
|
|
@ -71,23 +88,41 @@ impl Wallet {
|
|||
match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) {
|
||||
Ok(endpoint) => Self {
|
||||
endpoint: Some(endpoint),
|
||||
no_spend,
|
||||
},
|
||||
Err(e) => {
|
||||
eprintln!("ONIONWIRE_WALLET_RPC: {e}");
|
||||
Self::disabled()
|
||||
Self {
|
||||
endpoint: None,
|
||||
no_spend,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Self::disabled(),
|
||||
_ => Self {
|
||||
endpoint: None,
|
||||
no_spend,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_url(url: &str) -> Result<Self> {
|
||||
Ok(Self {
|
||||
endpoint: Some(parse_http_url(url, None)?),
|
||||
no_spend: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// No-spend (view-only) mode. Same switch as `ONIONWIRE_WALLET_NO_SPEND`.
|
||||
pub fn with_no_spend(mut self, on: bool) -> Self {
|
||||
self.no_spend = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn no_spend(&self) -> bool {
|
||||
self.no_spend
|
||||
}
|
||||
|
||||
pub fn configured(&self) -> bool {
|
||||
self.endpoint.is_some()
|
||||
}
|
||||
|
|
@ -107,7 +142,10 @@ impl Wallet {
|
|||
}
|
||||
|
||||
pub async fn transfer(&self, address: &str, amount: u64) -> Result<String> {
|
||||
let v = self
|
||||
if self.no_spend {
|
||||
return Err(Error(VIEW_ONLY_MSG.into()));
|
||||
}
|
||||
let sent = self
|
||||
.rpc(
|
||||
"transfer",
|
||||
serde_json::json!({
|
||||
|
|
@ -115,10 +153,36 @@ impl Wallet {
|
|||
"account_index": 0
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
.await;
|
||||
let v = match sent {
|
||||
Ok(v) => v,
|
||||
// The wallet's own refusal is opaque, so ask the documented
|
||||
// pre-transfer signal before surfacing it. Fail closed: if the
|
||||
// probe cannot answer, the original error stands.
|
||||
Err(e) => {
|
||||
if self.view_only().await {
|
||||
return Err(Error(VIEW_ONLY_MSG.into()));
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
json_str(&v, "tx_hash")
|
||||
}
|
||||
|
||||
/// View-only detection over RPC: `query_key` with `key_type=spend_key` is
|
||||
/// the signal monero actually exposes for a wallet with no spend key.
|
||||
/// A view-only wallet answers `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29)
|
||||
/// ("Cannot retrieve spend key"); a spend-capable wallet returns the key,
|
||||
/// which this discards.
|
||||
/// Source: `src/wallet/wallet_rpc_server.cpp` `on_query_key`.
|
||||
async fn view_only(&self) -> bool {
|
||||
matches!(
|
||||
self.rpc("query_key", serde_json::json!({"key_type": "spend_key"}))
|
||||
.await,
|
||||
Err(e) if e.to_string() == VIEW_ONLY_MSG
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn get_transfers(&self) -> Result<Vec<TransferRow>> {
|
||||
let v = self
|
||||
.rpc(
|
||||
|
|
@ -189,6 +253,17 @@ fn credentials_required() -> Error {
|
|||
Error("wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN)".into())
|
||||
}
|
||||
|
||||
/// `1` / `true` / `yes` / `on` (case-insensitive) mean set; anything else (or
|
||||
/// unset) means off.
|
||||
fn env_flag(name: &str) -> bool {
|
||||
matches!(
|
||||
std::env::var(name)
|
||||
.map(|v| v.trim().to_ascii_lowercase())
|
||||
.as_deref(),
|
||||
Ok("1" | "true" | "yes" | "on")
|
||||
)
|
||||
}
|
||||
|
||||
fn parse_login(login: &str) -> Result<(String, Zeroizing<String>)> {
|
||||
let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?;
|
||||
if user.is_empty() || pass.is_empty() {
|
||||
|
|
@ -455,6 +530,11 @@ fn parse_json_rpc(raw: &[u8]) -> Result<serde_json::Value> {
|
|||
.get("message")
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or("rpc error");
|
||||
// The one RPC-level error we translate: a view-only wallet has no
|
||||
// spend key (monero `WALLET_RPC_ERROR_CODE_WATCH_ONLY`).
|
||||
if err.get("code").and_then(|c| c.as_i64()) == Some(WATCH_ONLY_CODE) {
|
||||
return Err(Error(VIEW_ONLY_MSG.into()));
|
||||
}
|
||||
return Err(Error(msg.into()));
|
||||
}
|
||||
json.get("result")
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
//! Spec implementation tests for docs/TUI.md (this card).
|
||||
//! Does not own `tests/tui_frames.rs` (PR #23).
|
||||
|
||||
use onionwire::Message;
|
||||
use onionwire::outbox::{OutboxEntry, OutboxStatus};
|
||||
use onionwire::qr;
|
||||
use onionwire::tui::{
|
||||
alert_line, ascii_chrome, draw_share, draw_text_overlay, empty_friend_chat_text,
|
||||
help_overlay_text, main_footer_hints, main_header_line, paste_screen_text, roster_col_width,
|
||||
OutboxSummary, alert_line, ascii_chrome, chat_with_delivery, delivery_tag, draw_chat,
|
||||
draw_share, draw_text_overlay, empty_friend_chat_text, help_overlay_text, main_footer_hints,
|
||||
main_header_line, paste_screen_text, retry_in_text, roster_col_width, short_send_reason,
|
||||
status_footer, wrap_invite,
|
||||
};
|
||||
use ratatui::Frame;
|
||||
|
|
@ -376,3 +379,376 @@ fn ascii_switch_80x24_frame_is_pure_ascii() {
|
|||
println!("===== AFTER ascii share 80x24 =====\n{screen}");
|
||||
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Outbox delivery state (card t_d9a5b065)
|
||||
//
|
||||
// States come from the outbox API (`Outbox::pending` → `Queued` / `Sending` /
|
||||
// `Failed`; delivered rows are deleted, so absence means `Sent`). No new wire
|
||||
// prefix, no parallel state model.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn out_msg(body: &str) -> Message {
|
||||
Message {
|
||||
dir: "out".into(),
|
||||
plaintext: body.as_bytes().to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
fn in_msg(body: &str) -> Message {
|
||||
Message {
|
||||
dir: "in".into(),
|
||||
plaintext: body.as_bytes().to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_row(
|
||||
body: &str,
|
||||
status: OutboxStatus,
|
||||
attempts: u32,
|
||||
next_in: i64,
|
||||
now: i64,
|
||||
) -> OutboxEntry {
|
||||
OutboxEntry {
|
||||
id: 1,
|
||||
friend_pk: vec![9u8; 32],
|
||||
message_id: 1,
|
||||
body: body.as_bytes().to_vec(),
|
||||
attempts,
|
||||
next_attempt_at: now + next_in,
|
||||
created_at: now,
|
||||
status,
|
||||
last_error: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn queued_row(body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry {
|
||||
pending_row(body, OutboxStatus::Queued, attempts, next_in, now)
|
||||
}
|
||||
|
||||
fn sending_row(body: &str, now: i64) -> OutboxEntry {
|
||||
pending_row(body, OutboxStatus::Sending, 1, 0, now)
|
||||
}
|
||||
|
||||
fn failed_row(body: &str, why: &str, now: i64) -> OutboxEntry {
|
||||
pending_row(body, OutboxStatus::Failed(why.into()), 8, 0, now)
|
||||
}
|
||||
|
||||
/// Marker is everything after the two-space separator the render helper uses.
|
||||
fn marker_of(line: &str) -> &str {
|
||||
line.rsplit(" ").next().unwrap_or("")
|
||||
}
|
||||
|
||||
/// Force the non-ASCII (unicode glyph) path. Caller holds `ASCII_ENV`.
|
||||
fn force_unicode_mode() {
|
||||
unsafe {
|
||||
std::env::remove_var("ONIONWIRE_ASCII");
|
||||
std::env::remove_var("NO_COLOR");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_and_delivered_messages_render_different_markers() {
|
||||
let guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
force_unicode_mode();
|
||||
let _guard = guard;
|
||||
let now = 1_700_000_000;
|
||||
let msgs = vec![out_msg("ping"), out_msg("pong")];
|
||||
let pending = vec![queued_row("pong", 2, 45, now)];
|
||||
|
||||
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
|
||||
|
||||
assert!(
|
||||
lines[0].contains('✓'),
|
||||
"delivered row lost its mark: {:?}",
|
||||
lines[0]
|
||||
);
|
||||
assert!(!lines[0].contains("queued"), "{:?}", lines[0]);
|
||||
assert!(
|
||||
lines[1].contains('◷'),
|
||||
"queued row lost its glyph: {:?}",
|
||||
lines[1]
|
||||
);
|
||||
assert!(lines[1].contains("queued"), "{:?}", lines[1]);
|
||||
assert!(
|
||||
lines[1].contains("try 2/8"),
|
||||
"attempt count missing: {:?}",
|
||||
lines[1]
|
||||
);
|
||||
assert!(
|
||||
lines[1].contains("retry 45s"),
|
||||
"retry age missing: {:?}",
|
||||
lines[1]
|
||||
);
|
||||
assert_ne!(
|
||||
marker_of(&lines[0]),
|
||||
marker_of(&lines[1]),
|
||||
"queued and delivered must not share a marker"
|
||||
);
|
||||
assert_eq!(summary.queued, 1);
|
||||
assert_eq!(summary.failed, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivery_markers_have_exercised_ascii_fallbacks() {
|
||||
let _guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
unsafe {
|
||||
std::env::set_var("ONIONWIRE_ASCII", "1");
|
||||
std::env::remove_var("NO_COLOR");
|
||||
}
|
||||
let now = 500;
|
||||
let msgs = vec![
|
||||
out_msg("alpha"),
|
||||
out_msg("beta"),
|
||||
out_msg("gamma"),
|
||||
out_msg("delta"),
|
||||
in_msg("epsilon"),
|
||||
];
|
||||
let pending = vec![
|
||||
failed_row("alpha", "connect peer.onion:80: connection timed out", now),
|
||||
queued_row("beta", 1, 30, now),
|
||||
sending_row("gamma", now),
|
||||
];
|
||||
|
||||
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
|
||||
for line in &lines {
|
||||
assert!(
|
||||
line.is_ascii(),
|
||||
"ASCII fallback missing, non-ASCII in {line:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(marker_of(&lines[0]), "failed: connection timed out");
|
||||
assert_eq!(marker_of(&lines[1]), "queued (try 1/8, retry 30s)");
|
||||
assert_eq!(marker_of(&lines[2]), "sending");
|
||||
assert_eq!(marker_of(&lines[3]), "ok", "delivered fallback is `ok`");
|
||||
assert_eq!(lines[4], "them: epsilon", "inbound rows carry no state");
|
||||
assert_eq!(summary.queued, 2, "queued + sending are both outstanding");
|
||||
assert_eq!(summary.failed, 1);
|
||||
|
||||
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_age_and_failure_reason_are_short_forms() {
|
||||
assert_eq!(retry_in_text(45), "retry 45s");
|
||||
assert_eq!(retry_in_text(59), "retry 59s");
|
||||
assert_eq!(retry_in_text(60), "retry 1m");
|
||||
assert_eq!(retry_in_text(720), "retry 12m");
|
||||
assert_eq!(retry_in_text(0), "retry now");
|
||||
assert_eq!(retry_in_text(-30), "retry now");
|
||||
|
||||
assert_eq!(
|
||||
short_send_reason("connect abcdef.onion:80: connection timed out", 24),
|
||||
"connection timed out"
|
||||
);
|
||||
let long = short_send_reason("a-really-long-failure-description-here", 12);
|
||||
assert!(long.chars().count() <= 12, "{long:?}");
|
||||
assert!(
|
||||
long.contains('…') || long.contains("..."),
|
||||
"truncation marker missing: {long:?}"
|
||||
);
|
||||
assert_eq!(short_send_reason("nope", 24), "nope");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivery_tag_reads_the_outbox_status_enum() {
|
||||
let guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
force_unicode_mode();
|
||||
let _guard = guard;
|
||||
assert_eq!(delivery_tag(&OutboxStatus::Sent, 0, 0), "✓");
|
||||
assert_eq!(
|
||||
delivery_tag(&OutboxStatus::Queued, 3, 120),
|
||||
"◷ queued (try 3/8, retry 2m)"
|
||||
);
|
||||
assert_eq!(delivery_tag(&OutboxStatus::Sending, 1, 0), "» sending");
|
||||
assert_eq!(
|
||||
delivery_tag(&OutboxStatus::Failed("connect x:80: nope".into()), 8, 0),
|
||||
"✗ failed: nope"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn footer_summary_counts_queued_and_keeps_fail_closed() {
|
||||
let none = OutboxSummary::default();
|
||||
assert_eq!(none.note(), None);
|
||||
|
||||
let queued = OutboxSummary {
|
||||
queued: 2,
|
||||
failed: 0,
|
||||
first_error: None,
|
||||
};
|
||||
assert_eq!(queued.note().as_deref(), Some("2 queued"));
|
||||
|
||||
let failed = OutboxSummary {
|
||||
queued: 0,
|
||||
failed: 1,
|
||||
first_error: Some("connect peer.onion:80: connection timed out".into()),
|
||||
};
|
||||
let note = failed.note().expect("failed rows must produce a note");
|
||||
assert!(note.starts_with("send failed:"), "{note:?}");
|
||||
assert!(note.contains("connection timed out"), "{note:?}");
|
||||
|
||||
let mixed = OutboxSummary {
|
||||
queued: 3,
|
||||
failed: 1,
|
||||
first_error: Some("connect peer.onion:80: connection timed out".into()),
|
||||
};
|
||||
let mixed_note = mixed.note().expect("mixed rows must produce a note");
|
||||
assert!(mixed_note.contains("3 queued"), "{mixed_note:?}");
|
||||
assert!(mixed_note.contains("send failed"), "{mixed_note:?}");
|
||||
|
||||
// Fail-closed copy stays visible in the real footer at the 80-col floor.
|
||||
let line = status_footer(80, FP, ONION, Some(¬e), main_footer_hints());
|
||||
assert!(
|
||||
line.chars().count() <= 80,
|
||||
"{} {line:?}",
|
||||
line.chars().count()
|
||||
);
|
||||
assert!(line.contains("send failed"), "footer dropped it: {line:?}");
|
||||
assert!(line.contains("TOR") && line.contains("? help"), "{line:?}");
|
||||
|
||||
let queued_line = status_footer(80, FP, ONION, queued.note().as_deref(), main_footer_hints());
|
||||
assert!(queued_line.contains("2 queued"), "{queued_line:?}");
|
||||
assert!(queued_line.chars().count() <= 80);
|
||||
|
||||
// `! ` ornament (colour off) still lands on the derived failing note.
|
||||
let _guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
unsafe { std::env::set_var("NO_COLOR", "1") };
|
||||
let no_color = status_footer(80, FP, ONION, Some(¬e), main_footer_hints());
|
||||
assert!(no_color.contains("! send failed"), "{no_color:?}");
|
||||
unsafe { std::env::remove_var("NO_COLOR") };
|
||||
}
|
||||
|
||||
/// The card's width criterion: draw the real helpers at the documented floor
|
||||
/// (80x24) and prove nothing in the chat/footer region exceeds the width, and
|
||||
/// that an over-long row wraps in the pane instead of being clipped.
|
||||
#[test]
|
||||
fn chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping() {
|
||||
let guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
force_unicode_mode();
|
||||
let _guard = guard;
|
||||
let now = 1_700_000_000;
|
||||
let long = "this is a very long chat line that should wrap inside the chat pane instead of running off the right edge of an 80-column terminal and colliding with the roster border";
|
||||
let msgs = vec![out_msg("ok"), in_msg("pong"), out_msg(long)];
|
||||
let pending = vec![queued_row(long, 3, 45, now)];
|
||||
|
||||
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
|
||||
for line in lines.iter().take(2) {
|
||||
assert!(
|
||||
line.chars().count() <= 80,
|
||||
"short row wider than 80: {} {line:?}",
|
||||
line.chars().count()
|
||||
);
|
||||
}
|
||||
let footer = status_footer(
|
||||
80,
|
||||
FP,
|
||||
ONION,
|
||||
summary.note().as_deref(),
|
||||
main_footer_hints(),
|
||||
);
|
||||
assert!(footer.chars().count() <= 80, "{footer:?}");
|
||||
|
||||
let backend = TestBackend::new(80, 24);
|
||||
let mut terminal = Terminal::new(backend).expect("terminal");
|
||||
terminal
|
||||
.draw(|f| {
|
||||
let area = f.area();
|
||||
let cols = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area);
|
||||
draw_chat(f, cols[0], &lines, Some("alice"), true, 0);
|
||||
f.render_widget(Paragraph::new(footer.clone()), cols[1]);
|
||||
})
|
||||
.expect("draw");
|
||||
|
||||
let buf = terminal.backend().buffer();
|
||||
let mut screen = String::new();
|
||||
for y in 0..24u16 {
|
||||
for x in 0..80u16 {
|
||||
screen.push_str(buf[(x, y)].symbol());
|
||||
}
|
||||
screen.push('\n');
|
||||
}
|
||||
for (y, row) in screen.lines().enumerate() {
|
||||
assert!(
|
||||
row.chars().count() <= 80,
|
||||
"80x24 chat/footer row {y} wider than the terminal: {} {row:?}",
|
||||
row.chars().count()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
screen.contains('◷'),
|
||||
"queued glyph missing from frame:\n{screen}"
|
||||
);
|
||||
assert!(screen.contains("queued"), "queued word missing:\n{screen}");
|
||||
assert!(screen.contains('✓'), "delivered glyph missing:\n{screen}");
|
||||
assert!(
|
||||
screen.contains("with the roster border"),
|
||||
"long row was clipped, not wrapped:\n{screen}"
|
||||
);
|
||||
assert!(
|
||||
screen.contains("1 queued"),
|
||||
"footer summary missing:\n{screen}"
|
||||
);
|
||||
println!("===== AFTER outbox 80x24 (real draw_chat + status_footer) =====\n{screen}");
|
||||
}
|
||||
|
||||
/// The renderer consumes the real outbox API, not a hand-written fixture: a
|
||||
/// genuine unreachable-onion send leaves a `Queued` row, and that row is what
|
||||
/// the chat line and the footer note are built from.
|
||||
#[tokio::test]
|
||||
async fn renders_a_queued_row_from_a_real_outbox_send() {
|
||||
use onionwire::Store;
|
||||
use onionwire::outbox::{BoxFut, Deliverer, Outbox};
|
||||
use std::sync::Arc;
|
||||
|
||||
struct Dead;
|
||||
impl Deliverer for Dead {
|
||||
fn deliver<'a>(
|
||||
&'a self,
|
||||
_onion: &'a str,
|
||||
_pinned_id: &'a [u8],
|
||||
_prekey: &'a [u8],
|
||||
_plaintext: &'a [u8],
|
||||
) -> BoxFut<'a, Result<(), String>> {
|
||||
Box::pin(async { Err("connect dead.onion:80: timed out".to_string()) })
|
||||
}
|
||||
}
|
||||
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let store = Store::open_at_with_passphrase(dir.path(), "tui-spec-pass").expect("open store");
|
||||
let pk = [1u8; 32];
|
||||
store
|
||||
.upsert_friend(&pk, "dead.onion", None)
|
||||
.expect("friend");
|
||||
store.set_friend_prekey(&pk, &[7u8; 32]).expect("prekey");
|
||||
let store = Arc::new(std::sync::Mutex::new(store));
|
||||
let outbox = Outbox::new(Arc::clone(&store), Arc::new(Dead));
|
||||
|
||||
assert_eq!(
|
||||
outbox.send(&pk, b"queued for a dead peer").await,
|
||||
Ok(OutboxStatus::Queued)
|
||||
);
|
||||
let pending = outbox.pending(&pk).expect("pending rows");
|
||||
assert_eq!(pending.len(), 1, "one queued row");
|
||||
let msgs = store
|
||||
.lock()
|
||||
.expect("store lock")
|
||||
.list_messages(&pk)
|
||||
.expect("messages");
|
||||
|
||||
let now = pending[0].next_attempt_at - 45;
|
||||
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
|
||||
assert_eq!(lines.len(), 1);
|
||||
assert!(
|
||||
lines[0].contains("queued (try 1/8, retry 45s)"),
|
||||
"real outbox row did not render: {:?}",
|
||||
lines[0]
|
||||
);
|
||||
assert_eq!(summary.note().as_deref(), Some("1 queued"));
|
||||
|
||||
// And once a send crosses the circuit the row is gone, so the same message
|
||||
// renders as delivered.
|
||||
let (delivered, summary) = chat_with_delivery(&msgs, &[], now);
|
||||
assert!(delivered[0].contains('✓'), "{:?}", delivered[0]);
|
||||
assert_eq!(summary.note(), None);
|
||||
}
|
||||
|
|
|
|||
233
tests/wallet.rs
233
tests/wallet.rs
|
|
@ -1,5 +1,7 @@
|
|||
//! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use ed25519_dalek::SigningKey;
|
||||
use onionwire::pay;
|
||||
use onionwire::wallet::{self, TransferRow, Wallet};
|
||||
|
|
@ -8,6 +10,10 @@ use rand::rngs::OsRng;
|
|||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
/// `ONIONWIRE_WALLET_NO_SPEND` is process-wide; tests that touch env serialize.
|
||||
static ENV_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
|
||||
fn row(txid: &str, amount: &str, address: &str) -> TransferRow {
|
||||
TransferRow {
|
||||
txid: txid.into(),
|
||||
|
|
@ -241,6 +247,233 @@ async fn oversized_rpc_response_is_err() {
|
|||
);
|
||||
}
|
||||
|
||||
/// Records every request the client sends, answers the Digest challenge and
|
||||
/// then replies per RPC method. Lets a test assert on the *request log*.
|
||||
async fn serve_recording(
|
||||
listener: TcpListener,
|
||||
log: Arc<Mutex<Vec<String>>>,
|
||||
reply: Arc<dyn Fn(&str) -> String + Send + Sync>,
|
||||
) {
|
||||
loop {
|
||||
let Ok((mut sock, _)) = listener.accept().await else {
|
||||
return;
|
||||
};
|
||||
let mut buf = vec![0u8; 8192];
|
||||
let n = sock.read(&mut buf).await.unwrap_or(0);
|
||||
let req = String::from_utf8_lossy(&buf[..n]).to_string();
|
||||
log.lock().expect("log").push(req.clone());
|
||||
if req.contains("Authorization:") {
|
||||
let body = reply(&rpc_method(&req));
|
||||
let _ = sock.write_all(http_200_body(&body).as_bytes()).await;
|
||||
} else {
|
||||
let _ = sock.write_all(digest_401().as_bytes()).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn rpc_method(req: &str) -> String {
|
||||
let body = req.split_once("\r\n\r\n").map(|(_, b)| b).unwrap_or(req);
|
||||
serde_json::from_str::<serde_json::Value>(body.trim())
|
||||
.ok()
|
||||
.and_then(|v| v.get("method").and_then(|m| m.as_str()).map(str::to_string))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn http_200_body(body: &str) -> String {
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
}
|
||||
|
||||
fn rpc_error(code: i64, message: &str) -> String {
|
||||
format!(r#"{{"jsonrpc":"2.0","id":"0","error":{{"code":{code},"message":"{message}"}}}}"#)
|
||||
}
|
||||
|
||||
/// JSON-RPC body only (the server wraps it in an HTTP 200).
|
||||
fn rpc_result(result: &str) -> String {
|
||||
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#)
|
||||
}
|
||||
|
||||
fn recording_wallet(port: u16) -> Wallet {
|
||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("url")
|
||||
}
|
||||
|
||||
/// The wallet mock speaks the two methods `/tip` can reach, and refuses the
|
||||
/// local `transfer` before any socket is opened.
|
||||
#[tokio::test]
|
||||
async fn no_spend_mode_refuses_transfer_with_no_rpc_request() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let log = Arc::new(Mutex::new(Vec::new()));
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::clone(&log),
|
||||
Arc::new(|_| rpc_result(r#"{"tx_hash":"abc123"}"#)),
|
||||
));
|
||||
let w = recording_wallet(port).with_no_spend(true);
|
||||
assert!(w.no_spend());
|
||||
let err = w
|
||||
.transfer(
|
||||
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||||
1,
|
||||
)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(
|
||||
err.to_ascii_lowercase().contains("view-only"),
|
||||
"got {err}"
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
let seen = log.lock().expect("log").clone();
|
||||
assert!(seen.is_empty(), "no RPC request may be made: {seen:?}");
|
||||
// Positive control: the recorder is live, so the emptiness above is real.
|
||||
let _ = w.get_address().await;
|
||||
assert!(!log.lock().expect("log").is_empty(), "recorder saw nothing");
|
||||
}
|
||||
|
||||
/// `/pay` (subaddress) and receipt verification (`get_transfers`) keep working
|
||||
/// with the no-spend flag on — only `transfer` is refused.
|
||||
#[tokio::test]
|
||||
async fn no_spend_mode_keeps_invoice_and_receipt_paths_working() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let log = Arc::new(Mutex::new(Vec::new()));
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::clone(&log),
|
||||
Arc::new(|method| match method {
|
||||
"create_address" => rpc_result(
|
||||
r#"{"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}"#,
|
||||
),
|
||||
"get_transfers" => rpc_result(
|
||||
r#"{"in":[{"txid":"deadbeef","amount":5,"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}],"pending":[]}"#,
|
||||
),
|
||||
_ => rpc_result(r#"{}"#),
|
||||
}),
|
||||
));
|
||||
let w = recording_wallet(port).with_no_spend(true);
|
||||
let created = w.create_address().await.expect("create_address");
|
||||
assert!(created.starts_with('8'), "got {created}");
|
||||
let rows = w.get_transfers().await.expect("get_transfers");
|
||||
assert!(wallet::transfers_match(&rows, "deadbeef", "5", &created));
|
||||
let seen = log.lock().expect("log").clone();
|
||||
assert!(
|
||||
seen.iter()
|
||||
.any(|r| r.contains("\"method\":\"create_address\"")),
|
||||
"recorder must have seen the invoice path: {seen:?}"
|
||||
);
|
||||
assert!(
|
||||
!seen.iter().any(|r| r.contains("\"method\":\"transfer\"")),
|
||||
"transfer must never be dialed in no-spend mode"
|
||||
);
|
||||
}
|
||||
|
||||
/// A view-only wallet refuses `transfer` with its own opaque error. The
|
||||
/// pre-transfer signal is `query_key` key_type=spend_key (Monero answers
|
||||
/// WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29), so /tip must say so plainly.
|
||||
#[tokio::test]
|
||||
async fn view_only_wallet_maps_transfer_failure_to_clear_message() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let log = Arc::new(Mutex::new(Vec::new()));
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::clone(&log),
|
||||
Arc::new(|method| match method {
|
||||
"query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
|
||||
_ => rpc_error(-18, "No transaction created"),
|
||||
}),
|
||||
));
|
||||
let w = recording_wallet(port);
|
||||
assert!(!w.no_spend());
|
||||
let err = w
|
||||
.transfer(
|
||||
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||||
1,
|
||||
)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}");
|
||||
let seen = log.lock().expect("log").clone();
|
||||
assert!(
|
||||
seen.iter().any(|r| r.contains("\"method\":\"query_key\"")),
|
||||
"must ask the RPC-side signal: {seen:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A spend-capable wallet must keep its real error: no fabricated detection.
|
||||
#[tokio::test]
|
||||
async fn spend_capable_wallet_keeps_the_original_transfer_error() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::new(Mutex::new(Vec::new())),
|
||||
Arc::new(|method| match method {
|
||||
"query_key" => rpc_result(r#"{"key":"00112233"}"#),
|
||||
_ => rpc_error(-18, "No transaction created"),
|
||||
}),
|
||||
));
|
||||
let err = recording_wallet(port)
|
||||
.transfer(
|
||||
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||||
1,
|
||||
)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("No transaction created"), "got {err}");
|
||||
assert!(!err.to_ascii_lowercase().contains("view-only"), "got {err}");
|
||||
}
|
||||
|
||||
/// F5 must not regress: an open RPC (HTTP 200, no Digest challenge) is refused.
|
||||
#[tokio::test]
|
||||
async fn open_rpc_without_digest_challenge_is_still_refused() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let canned = http_200_body(
|
||||
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}"#,
|
||||
);
|
||||
tokio::spawn(async move {
|
||||
let (mut sock, _) = listener.accept().await.expect("accept");
|
||||
let mut buf = vec![0u8; 4096];
|
||||
let _ = sock.read(&mut buf).await;
|
||||
let _ = sock.write_all(canned.as_bytes()).await;
|
||||
});
|
||||
let err = recording_wallet(port)
|
||||
.get_address()
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.to_ascii_lowercase().contains("digest"), "got {err}");
|
||||
}
|
||||
|
||||
/// `ONIONWIRE_WALLET_NO_SPEND` is the operator-facing switch.
|
||||
#[test]
|
||||
fn from_env_reads_no_spend_flag() {
|
||||
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
unsafe {
|
||||
std::env::set_var("ONIONWIRE_WALLET_RPC", "http://ow:[email protected]:18083");
|
||||
std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "1");
|
||||
}
|
||||
let on = Wallet::from_env();
|
||||
assert!(on.no_spend(), "flag 1 must mean no-spend");
|
||||
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "true") };
|
||||
assert!(Wallet::from_env().no_spend(), "\"true\" must mean no-spend");
|
||||
for off in ["0", "no", "off"] {
|
||||
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", off) };
|
||||
assert!(!Wallet::from_env().no_spend(), "{off} must be off");
|
||||
}
|
||||
unsafe {
|
||||
std::env::remove_var("ONIONWIRE_WALLET_NO_SPEND");
|
||||
std::env::remove_var("ONIONWIRE_WALLET_RPC");
|
||||
}
|
||||
assert!(!Wallet::from_env().no_spend(), "unset must be off");
|
||||
}
|
||||
|
||||
fn digest_401() -> String {
|
||||
"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
//! Noise handshake/transport state that lives inside `snow`.
|
||||
|
||||
use onionwire::backup::BackupKeys;
|
||||
use onionwire::profile;
|
||||
use onionwire::session::Keys;
|
||||
use onionwire::wallet::Wallet;
|
||||
use onionwire::Store;
|
||||
|
|
@ -52,6 +53,20 @@ unsafe fn drop_in_place_and_peek_identity_sk(v: &mut Keys) -> [u8; 32] {
|
|||
}
|
||||
}
|
||||
|
||||
/// Drops a `Zeroizing<[u8; 32]>` in place and reads its buffer back.
|
||||
///
|
||||
/// SAFETY: only for `ManuallyDrop<Zeroizing<[u8; 32]>>` locals — same contract
|
||||
/// as `drop_in_place_and_peek_identity_sk`.
|
||||
unsafe fn drop_in_place_and_peek_zeroizing_u8x32(v: &mut Zeroizing<[u8; 32]>) -> [u8; 32] {
|
||||
let p: *const [u8; 32] = &**v;
|
||||
// SAFETY: the caller guarantees `v` is dropped exactly once and is still
|
||||
// alive at its own address when read back.
|
||||
unsafe {
|
||||
std::ptr::drop_in_place(v as *mut Zeroizing<[u8; 32]>);
|
||||
std::ptr::read_volatile(p)
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop behaviour, not a comment: after the value drops, the local secret key
|
||||
/// material that feeds the Noise IK handshake is gone from its memory.
|
||||
#[test]
|
||||
|
|
@ -116,3 +131,27 @@ fn wallet_endpoint_debug_redacts_the_rpc_password() {
|
|||
);
|
||||
assert!(dbg.contains("<redacted>"), "{dbg}");
|
||||
}
|
||||
|
||||
/// `profile::sign` needs a raw 32-byte copy of the identity secret to build the
|
||||
/// dalek `SigningKey`. That copy is a `Zeroizing` buffer, not a bare array that
|
||||
/// stays on the stack until the function returns.
|
||||
#[test]
|
||||
fn profile_signing_key_bytes_are_zeroizing_and_wipe() {
|
||||
let secret = [0x5au8; 32];
|
||||
let bytes = profile::signing_key_bytes(&secret).expect("32 bytes");
|
||||
|
||||
let _: &Zeroizing<[u8; 32]> = &bytes;
|
||||
assert_eq!(&bytes[..], &secret[..], "buffer must hold the secret");
|
||||
|
||||
let mut probe = std::mem::ManuallyDrop::new(bytes);
|
||||
let after = unsafe { drop_in_place_and_peek_zeroizing_u8x32(&mut probe) };
|
||||
|
||||
assert_eq!(after, [0u8; 32], "identity secret survived its drop");
|
||||
}
|
||||
|
||||
/// A length-mismatched secret is an error, not a truncated/padded key.
|
||||
#[test]
|
||||
fn profile_signing_key_bytes_rejects_a_short_secret() {
|
||||
assert!(profile::signing_key_bytes(&[7u8; 31]).is_err());
|
||||
assert!(profile::signing_key_bytes(&[7u8; 33]).is_err());
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue