Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2fd640e230 |
||
| e6e2a158a8 | |||
|
|
35b8caa716 |
16 changed files with 1582 additions and 61 deletions
|
|
@ -94,6 +94,49 @@ exclusions, because an auto-backup of `onionwire.db` would hand the wrapped
|
|||
message key *and* the plaintext identity keys to Google Drive. Chat bodies are
|
||||
encrypted at rest; identity keys are not — that is the locked v1 posture.
|
||||
|
||||
### The store passphrase at rest
|
||||
|
||||
Typing the passphrase on every launch is no longer required. On first unlock
|
||||
the passphrase can be remembered (checkbox, on by default), and it is then
|
||||
stored as an AES-256-GCM blob:
|
||||
|
||||
* the wrapping key is generated inside the **Android Keystore** under alias
|
||||
`onionwire.store`, AES-256-GCM, `setUserAuthenticationRequired(false)` —
|
||||
deliberately **not** biometric-gated, because a fingerprint prompt would turn
|
||||
"the node opens or tells you why it did not" into "the node is unusable";
|
||||
* **StrongBox is requested first** (`setIsStrongBoxBacked(true)`, guarded by
|
||||
`FEATURE_STRONGBOX_KEYSTORE` on API 28+) and falls back to an ordinary
|
||||
TEE-backed or software Keystore key when the chip refuses AES-256
|
||||
(`StrongBoxUnavailableException is a ProviderException`). The fallback is
|
||||
reported, not hidden: the lock screen prints what `KeyInfo` actually said,
|
||||
and a software key is labelled **NOT hardware-backed**;
|
||||
* only ciphertext + IV reach disk, at
|
||||
`filesDir/secrets/store-passphrase.bin` — an `OWSEAL1` envelope of
|
||||
magic + IV + ciphertext + GCM tag. No second copy, no `SharedPreferences`,
|
||||
no plaintext in logs, and the typed `CharArray` is zeroed as soon as the
|
||||
unlock call returns. The text field is a plain `remember`, so the typed
|
||||
passphrase is never written into saved instance state;
|
||||
* **Keystore invalidation is a supported path, not a crash.** A factory reset,
|
||||
an app-data wipe, or a key the platform invalidates leaves a blob that cannot
|
||||
authenticate: `StoredPassphraseStore.load()` returns `Unavailable`, the lock
|
||||
screen explains it, and the user types the passphrase again. A failed read
|
||||
does **not** delete the blob — a transient Keystore failure must not destroy
|
||||
the only copy;
|
||||
* `forget` deletes the blob **and** the Keystore key.
|
||||
|
||||
The one plaintext copy this cannot erase is the immutable `String` the UniFFI
|
||||
binding takes (`openWire(home, passphrase: String)`). A follow-up SDK change
|
||||
should accept the key (or a `ByteArray`) so the passphrase never becomes a
|
||||
`String` at all.
|
||||
|
||||
`app/src/test/.../crypto/` covers the envelope and the file handling on the JVM
|
||||
(the real `StoreSecret` code, with a JVM AES key standing in). The Keystore
|
||||
provider only exists on a device:
|
||||
|
||||
```bash
|
||||
./gradlew :app:connectedDebugAndroidTest # prints the KeyInfo/hardware report
|
||||
```
|
||||
|
||||
### Signing
|
||||
|
||||
Release APKs are signed with a **repo-owned keystore**, not the debug key.
|
||||
|
|
@ -153,5 +196,8 @@ android/
|
|||
src/main/java/com/siriusdevops/onionwire/
|
||||
MainActivity.kt # NavHost
|
||||
WireViewModel.kt # owns the single Wire node
|
||||
crypto/ # Keystore-wrapped store passphrase
|
||||
ui/ # Compose screens (M3)
|
||||
src/test/ # JVM tests (envelope, store, invite flow)
|
||||
src/androidTest/ # device-only: AndroidKeyStore
|
||||
```
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ android {
|
|||
// the offline default and match the first automated tag (v0.1.0 → 100).
|
||||
versionCode = (findProperty("onionwire.versionCode") as String?)?.toIntOrNull() ?: 100
|
||||
versionName = (findProperty("onionwire.versionName") as String?) ?: "0.1.0"
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
ndk {
|
||||
abiFilters += onionwireAbis
|
||||
}
|
||||
|
|
@ -129,4 +130,10 @@ dependencies {
|
|||
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.kotlinx.coroutines.test)
|
||||
|
||||
// Device-only: the AndroidKeyStore provider does not exist in the unit-test
|
||||
// JVM. These run under `./gradlew :app:connectedDebugAndroidTest`.
|
||||
androidTestImplementation(libs.junit)
|
||||
androidTestImplementation(libs.androidx.test.ext.junit)
|
||||
androidTestImplementation(libs.androidx.test.runner)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,150 @@
|
|||
package com.siriusdevops.onionwire.crypto
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The device half of the Keystore story. The unit-test JVM has no
|
||||
* `AndroidKeyStore` provider, so nothing here can run as a plain JUnit test.
|
||||
*
|
||||
* Run on a real device or an emulator:
|
||||
*
|
||||
* ./gradlew :app:connectedDebugAndroidTest
|
||||
*
|
||||
* and read the `OnionWireKeystore` tag in logcat for the actual
|
||||
* `KeyInfo`/`isInsideSecureHardware`/`securityLevel` report — the point of
|
||||
* [key_backing_is_reported_and_logged] is to print the truth, not to assert a
|
||||
* hardware-backed key on hardware that does not have one.
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class KeystorePassphraseCipherTest {
|
||||
|
||||
private val context: Context =
|
||||
InstrumentationRegistry.getInstrumentation().targetContext
|
||||
|
||||
private val cipher = KeystorePassphraseCipher(context)
|
||||
|
||||
private val passphrase = "correct horse battery staple".toCharArray()
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
cipher.deleteKey()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun seal_open_round_trips_through_the_android_keystore() {
|
||||
val blob = cipher.seal(passphrase)
|
||||
assertTrue(
|
||||
"envelope is magic + IV + ciphertext + tag",
|
||||
blob.size >= passphrase.size + StoreSecret.IV_BYTES + 16 + 9,
|
||||
)
|
||||
val out = cipher.open(blob)
|
||||
try {
|
||||
assertArrayEquals(passphrase, out)
|
||||
} finally {
|
||||
StoreSecret.wipe(out)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stored_blob_on_a_device_is_not_the_plaintext() {
|
||||
val dir = File(context.filesDir, "secrets-test")
|
||||
dir.mkdirs()
|
||||
val store = StoredPassphraseStore(File(dir, "store-passphrase.bin"), cipher)
|
||||
try {
|
||||
store.save(passphrase)
|
||||
|
||||
val raw = File(store.path).readBytes()
|
||||
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
|
||||
assertFalse(
|
||||
"the passphrase must not appear in the file",
|
||||
String(raw, Charsets.ISO_8859_1).contains(String(needle, Charsets.ISO_8859_1)),
|
||||
)
|
||||
|
||||
val loaded = store.load() as StoredPassphraseStore.Load.Loaded
|
||||
try {
|
||||
assertArrayEquals(passphrase, loaded.passphrase)
|
||||
} finally {
|
||||
StoreSecret.wipe(loaded.passphrase)
|
||||
}
|
||||
} finally {
|
||||
store.forget()
|
||||
dir.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun key_backing_is_reported_and_logged() {
|
||||
cipher.seal(passphrase) // force key creation
|
||||
|
||||
val strongBoxAdvertised = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
|
||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
|
||||
val backing = cipher.backing()
|
||||
|
||||
Log.i(
|
||||
"OnionWireKeystore",
|
||||
"alias=${KeystorePassphraseCipher.ALIAS} backing=$backing " +
|
||||
"strongBoxAdvertised=$strongBoxAdvertised " +
|
||||
"sdk=${Build.VERSION.SDK_INT} device=${Build.MANUFACTURER} ${Build.MODEL}",
|
||||
)
|
||||
|
||||
if (strongBoxAdvertised) {
|
||||
assertTrue(
|
||||
"StrongBox is advertised but the key did not land in a secure element: $backing",
|
||||
backing == KeyBacking.STRONGBOX || backing == KeyBacking.HARDWARE,
|
||||
)
|
||||
} else {
|
||||
assertNotEquals("the API refused to report the backing at all", KeyBacking.UNKNOWN, backing)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun open_does_not_require_user_authentication() {
|
||||
// The card's contract: unlocking must not need a fingerprint. If the
|
||||
// key had been created with setUserAuthenticationRequired(true), this
|
||||
// open() would throw UserNotAuthenticatedException.
|
||||
val out = cipher.open(cipher.seal(passphrase))
|
||||
StoreSecret.wipe(out)
|
||||
assertTrue(cipher.keyPresent())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deleted_key_reports_unavailable_instead_of_crashing() {
|
||||
val blob = cipher.seal(passphrase)
|
||||
cipher.deleteKey()
|
||||
|
||||
assertFalse(cipher.keyPresent())
|
||||
try {
|
||||
cipher.open(blob)
|
||||
fail("expected SecretUnavailable after the key was deleted")
|
||||
} catch (e: SecretUnavailable) {
|
||||
assertTrue(e.message!!.contains("gone"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun a_regenerated_key_cannot_open_an_old_blob() {
|
||||
val blob = cipher.seal(passphrase)
|
||||
cipher.deleteKey() // a reset that leaves the app's data dir intact
|
||||
cipher.seal(passphrase) // same alias, brand-new key
|
||||
|
||||
try {
|
||||
cipher.open(blob)
|
||||
fail("expected SecretUnavailable for a blob wrapped by the deleted key")
|
||||
} catch (_: SecretUnavailable) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -47,10 +47,17 @@ class MainActivity : ComponentActivity() {
|
|||
@Composable
|
||||
private fun AppRoot(vm: WireViewModel = viewModel()) {
|
||||
val phase by vm.phase.collectAsStateWithLifecycle()
|
||||
val unlock by vm.unlock.collectAsStateWithLifecycle()
|
||||
|
||||
when (val p = phase) {
|
||||
is Phase.Ready -> ReadyGraph(vm, p)
|
||||
else -> UnlockScreen(phase = p, onUnlock = vm::unlock)
|
||||
else -> UnlockScreen(
|
||||
phase = p,
|
||||
unlock = unlock,
|
||||
onUnlock = vm::unlock,
|
||||
onUnlockStored = vm::unlockStored,
|
||||
onForgetStored = vm::forgetStoredPassphrase,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,10 +3,16 @@ package com.siriusdevops.onionwire
|
|||
import android.app.Application
|
||||
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.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import uniffi.onionwire_sdk.ChatMessage
|
||||
import uniffi.onionwire_sdk.FriendInfo
|
||||
import uniffi.onionwire_sdk.InviteInfo
|
||||
|
|
@ -32,6 +38,23 @@ sealed interface Phase {
|
|||
data class Failed(val message: String) : Phase
|
||||
}
|
||||
|
||||
/**
|
||||
* How the lock screen expects the next unlock to happen.
|
||||
*
|
||||
* This is a probe of local state, not a promise: [OneTap] means a blob exists
|
||||
* *and* decrypted successfully during this process's lifetime.
|
||||
*/
|
||||
sealed interface Unlock {
|
||||
/**
|
||||
* The passphrase must be typed. [notice] explains why a stored one is not
|
||||
* being used (key invalidated, blob corrupt, nothing stored yet).
|
||||
*/
|
||||
data class TypeIt(val notice: String? = null) : Unlock
|
||||
|
||||
/** A stored, decryptable passphrase exists — one tap. */
|
||||
data class OneTap(val backing: KeyBacking) : Unlock
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the single Wire node for the process.
|
||||
*
|
||||
|
|
@ -43,46 +66,166 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
|||
/** `context.filesDir` — app-private, never external storage. */
|
||||
private val home: File = File(app.filesDir, "onionwire")
|
||||
|
||||
/**
|
||||
* The Keystore-wrapped passphrase. Two files at most: this blob and the
|
||||
* KeyStore key under alias [KeystorePassphraseCipher.ALIAS]. Nothing else
|
||||
* on disk ever sees the plaintext.
|
||||
*/
|
||||
private val secrets: StoredPassphraseStore = StoredPassphraseStore(
|
||||
File(File(app.filesDir, "secrets"), "store-passphrase.bin"),
|
||||
KeystorePassphraseCipher(app),
|
||||
)
|
||||
|
||||
private val _phase = MutableStateFlow<Phase>(Phase.Locked)
|
||||
val phase: StateFlow<Phase> = _phase.asStateFlow()
|
||||
|
||||
private val _unlock = MutableStateFlow<Unlock>(Unlock.TypeIt())
|
||||
val unlock: StateFlow<Unlock> = _unlock.asStateFlow()
|
||||
|
||||
private val _friends = MutableStateFlow<List<FriendInfo>>(emptyList())
|
||||
val friends: StateFlow<List<FriendInfo>> = _friends.asStateFlow()
|
||||
|
||||
private var wire: Wire? = null
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens (or on first run, creates) the identity and starts hosting.
|
||||
* Unlocks with a typed passphrase. Empty fails closed — the SDK maps it
|
||||
* straight to an error, it is not a "skip" path.
|
||||
*
|
||||
* An empty passphrase fails closed — the SDK maps it straight to an error,
|
||||
* it is not a "skip" path.
|
||||
* [remember] wraps the passphrase with the Keystore key so later launches
|
||||
* are one tap. It is opt-in in the UI (and on by default there); it is
|
||||
* never implied by this call.
|
||||
*/
|
||||
fun unlock(passphrase: String) {
|
||||
fun unlock(passphrase: String, remember: Boolean = false) {
|
||||
if (passphrase.isEmpty()) return
|
||||
openWith(passphrase.toCharArray(), storeAfterwards = remember)
|
||||
}
|
||||
|
||||
/**
|
||||
* One-tap unlock from the stored blob.
|
||||
*
|
||||
* Any failure — key deleted, blob corrupt, GCM tag mismatch — degrades to
|
||||
* "type it" with the reason on screen. It never crashes and never silently
|
||||
* unlocks with something else.
|
||||
*/
|
||||
fun unlockStored() {
|
||||
if (_phase.value is Phase.Opening) return
|
||||
_phase.value = Phase.Opening
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val w = openWire(home.absolutePath, passphrase)
|
||||
wire = w
|
||||
_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())
|
||||
val loaded = withContext(Dispatchers.IO) { secrets.load() }
|
||||
when (loaded) {
|
||||
is StoredPassphraseStore.Load.Loaded ->
|
||||
openWith(loaded.passphrase, storeAfterwards = false)
|
||||
|
||||
StoredPassphraseStore.Load.Absent -> {
|
||||
_unlock.value = Unlock.TypeIt("No passphrase is stored on this device.")
|
||||
}
|
||||
|
||||
is StoredPassphraseStore.Load.Unavailable -> {
|
||||
_unlock.value = Unlock.TypeIt(unavailableNotice(loaded.reason))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops the stored passphrase and its Keystore key. Irreversible. */
|
||||
fun forgetStoredPassphrase() {
|
||||
viewModelScope.launch {
|
||||
withContext(Dispatchers.IO) { secrets.forget() }
|
||||
_unlock.value = Unlock.TypeIt(
|
||||
"Stored passphrase deleted. Type it to open the store again.",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops our handle. The onion service stops; nothing is sent after this. */
|
||||
fun lock() {
|
||||
wire = null
|
||||
_friends.value = emptyList()
|
||||
_phase.value = Phase.Locked
|
||||
refreshUnlockState()
|
||||
}
|
||||
|
||||
private fun refreshUnlockState() {
|
||||
viewModelScope.launch {
|
||||
val state = withContext(Dispatchers.IO) {
|
||||
when (val loaded = secrets.load()) {
|
||||
is StoredPassphraseStore.Load.Loaded -> {
|
||||
// We only needed to know it decrypts. Wipe immediately.
|
||||
StoreSecret.wipe(loaded.passphrase)
|
||||
Unlock.OneTap(secrets.backing())
|
||||
}
|
||||
|
||||
StoredPassphraseStore.Load.Absent -> Unlock.TypeIt()
|
||||
|
||||
is StoredPassphraseStore.Load.Unavailable ->
|
||||
Unlock.TypeIt(unavailableNotice(loaded.reason))
|
||||
}
|
||||
}
|
||||
_unlock.value = state
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
StoreSecret.wipe(secret)
|
||||
return
|
||||
}
|
||||
_phase.value = Phase.Opening
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
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")
|
||||
|
||||
suspend fun refreshFriends() {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,139 @@
|
|||
package com.siriusdevops.onionwire.crypto
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyInfo
|
||||
import android.security.keystore.KeyProperties
|
||||
import java.security.KeyStore
|
||||
import java.security.ProviderException
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.SecretKeyFactory
|
||||
|
||||
/**
|
||||
* AES-256-GCM key held by the Android Keystore under [ALIAS].
|
||||
*
|
||||
* The key material is never readable by this process (`SecretKey.encoded` is
|
||||
* null for AndroidKeyStore keys) — that is the whole point: pulling
|
||||
* `/data/data/com.siriusdevops.onionwire/` off a rooted device yields the
|
||||
* ciphertext, not the passphrase.
|
||||
*
|
||||
* StrongBox is requested first and falls back to the ordinary TEE-backed (or
|
||||
* software) Keystore without a crash. The fallback is not silent: call
|
||||
* [backing] and report what the Keystore actually produced.
|
||||
*
|
||||
* `setUserAuthenticationRequired` is deliberately **false**. Requiring a
|
||||
* fingerprint to unlock the node would turn "fail closed" into "unusable
|
||||
* unattended", and the SDK's contract is that an unlock either opens the node
|
||||
* or reports why it did not.
|
||||
*/
|
||||
class KeystorePassphraseCipher(private val context: Context) : PassphraseCipher {
|
||||
|
||||
private var cached: SecretKey? = null
|
||||
|
||||
override fun seal(plaintext: CharArray): ByteArray =
|
||||
StoreSecret.seal(loadOrCreateKey(), plaintext)
|
||||
|
||||
/**
|
||||
* Never creates a key. A freshly generated key cannot decrypt an old blob,
|
||||
* and generating one here would turn "the key is gone" into a confusing
|
||||
* GCM tag failure. The caller needs the real reason to tell the user.
|
||||
*/
|
||||
override fun open(blob: ByteArray): CharArray {
|
||||
val key = cached ?: existingKey()
|
||||
?: throw SecretUnavailable("the device's Keystore key for OnionWire is gone")
|
||||
return StoreSecret.open(key, blob)
|
||||
}
|
||||
|
||||
override fun keyPresent(): Boolean = (cached ?: existingKey()) != null
|
||||
|
||||
override fun backing(): KeyBacking {
|
||||
val key = cached ?: existingKey() ?: return KeyBacking.UNKNOWN
|
||||
val info = try {
|
||||
SecretKeyFactory.getInstance(key.algorithm, PROVIDER)
|
||||
.getKeySpec(key, KeyInfo::class.java) as KeyInfo
|
||||
} catch (_: Exception) {
|
||||
// Some OEM Keystore implementations refuse getKeySpec. Report
|
||||
// UNKNOWN rather than guessing hardware backing.
|
||||
return KeyBacking.UNKNOWN
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
|
||||
info.securityLevel == KeyProperties.SECURITY_LEVEL_STRONGBOX
|
||||
) {
|
||||
return KeyBacking.STRONGBOX
|
||||
}
|
||||
// Deprecated in API 31 in favour of securityLevel, but it is the only
|
||||
// TEE/software answer available on 26–30, and minSdk is 26.
|
||||
@Suppress("DEPRECATION")
|
||||
val inSecureHardware = info.isInsideSecureHardware
|
||||
return if (inSecureHardware) KeyBacking.HARDWARE else KeyBacking.SOFTWARE
|
||||
}
|
||||
|
||||
override fun deleteKey() {
|
||||
cached = null
|
||||
try {
|
||||
keyStore().deleteEntry(ALIAS)
|
||||
} catch (_: Exception) {
|
||||
// Nothing usable to delete.
|
||||
}
|
||||
}
|
||||
|
||||
private fun existingKey(): SecretKey? {
|
||||
cached?.let { return it }
|
||||
val key = try {
|
||||
keyStore().getKey(ALIAS, null) as? SecretKey
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
cached = key
|
||||
return key
|
||||
}
|
||||
|
||||
private fun loadOrCreateKey(): SecretKey = cached ?: existingKey() ?: createKey()
|
||||
|
||||
private fun createKey(): SecretKey {
|
||||
val strongBoxAdvertised =
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
|
||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
|
||||
if (strongBoxAdvertised) {
|
||||
try {
|
||||
return generate(strongBox = true).also { cached = it }
|
||||
} catch (_: ProviderException) {
|
||||
// StrongBoxUnavailableException is a ProviderException: the chip
|
||||
// exists but its slots are full, or it refuses AES-256. Fall
|
||||
// through to a normal Keystore key instead of failing unlock.
|
||||
}
|
||||
}
|
||||
return generate(strongBox = false).also { cached = it }
|
||||
}
|
||||
|
||||
private fun generate(strongBox: Boolean): SecretKey {
|
||||
val builder = KeyGenParameterSpec.Builder(
|
||||
ALIAS,
|
||||
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
|
||||
)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setKeySize(StoreSecret.KEY_BITS)
|
||||
// Our IV comes from Cipher.init, and the Keystore supplies it.
|
||||
.setRandomizedEncryptionRequired(true)
|
||||
.setUserAuthenticationRequired(false)
|
||||
if (strongBox && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
builder.setIsStrongBoxBacked(true)
|
||||
}
|
||||
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER)
|
||||
generator.init(builder.build())
|
||||
return generator.generateKey()
|
||||
}
|
||||
|
||||
private fun keyStore(): KeyStore = KeyStore.getInstance(PROVIDER).apply { load(null) }
|
||||
|
||||
companion object {
|
||||
const val PROVIDER = "AndroidKeyStore"
|
||||
|
||||
/** One key per app: the passphrase it wraps is the only secret here. */
|
||||
const val ALIAS = "onionwire.store"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
package com.siriusdevops.onionwire.crypto
|
||||
|
||||
/**
|
||||
* Wraps the store passphrase with a key that never leaves the Keystore.
|
||||
*
|
||||
* Implementations must not persist the plaintext anywhere, and must not log it.
|
||||
*/
|
||||
interface PassphraseCipher {
|
||||
|
||||
/** Encrypts [plaintext]. The returned blob is the only thing that may hit disk. */
|
||||
fun seal(plaintext: CharArray): ByteArray
|
||||
|
||||
/**
|
||||
* Decrypts a blob produced by [seal].
|
||||
*
|
||||
* @throws SecretUnavailable when the key is gone, invalidated, or the blob
|
||||
* does not authenticate. Callers fall back to asking the user to type.
|
||||
*/
|
||||
fun open(blob: ByteArray): CharArray
|
||||
|
||||
/** True when a usable key is already in the Keystore. */
|
||||
fun keyPresent(): Boolean
|
||||
|
||||
/**
|
||||
* Where the key actually lives, as reported by the Keystore itself.
|
||||
*
|
||||
* This is an observation, not a claim: on a device without a StrongBox or
|
||||
* TEE the honest answer is [KeyBacking.SOFTWARE], and the UI says so.
|
||||
*/
|
||||
fun backing(): KeyBacking
|
||||
|
||||
/** Removes the key. The ciphertext becomes permanently undecryptable. */
|
||||
fun deleteKey()
|
||||
}
|
||||
|
||||
/** Result of asking the Keystore where the key lives. */
|
||||
enum class KeyBacking {
|
||||
/** Dedicated security chip (API 28+, Pixel 3-class and up). */
|
||||
STRONGBOX,
|
||||
|
||||
/** Key is inside a TEE. Good. */
|
||||
HARDWARE,
|
||||
|
||||
/** Keystore software implementation. Passphrase is still not plaintext on disk. */
|
||||
SOFTWARE,
|
||||
|
||||
/** No key created yet, or the API could not be queried. Never claim hardware here. */
|
||||
UNKNOWN,
|
||||
}
|
||||
|
|
@ -0,0 +1,130 @@
|
|||
package com.siriusdevops.onionwire.crypto
|
||||
|
||||
import java.nio.CharBuffer
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.security.GeneralSecurityException
|
||||
import java.util.Arrays
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
/**
|
||||
* AES-256-GCM envelope for the store passphrase.
|
||||
*
|
||||
* This file is deliberately free of `android.*` imports so the exact
|
||||
* seal/open code that runs on a device can also run in a plain JVM unit test
|
||||
* with a JVM-generated AES key. The Android Keystore only supplies the key —
|
||||
* the framing and the AEAD call are these functions.
|
||||
*
|
||||
* Wire format (little of it is secret, all of it is authenticated):
|
||||
*
|
||||
* magic "OWSEAL1\n" 8 bytes
|
||||
* iv length 1 byte (always [IV_BYTES])
|
||||
* iv [IV_BYTES] bytes, from the cipher
|
||||
* ciphertext n + [TAG_BITS]/8 bytes (GCM tag is appended)
|
||||
*
|
||||
* The IV is generated by `Cipher.init` rather than by us: an AndroidKeyStore
|
||||
* key created with `setRandomizedEncryptionRequired(true)` refuses an
|
||||
* app-supplied IV, and SunJCE likewise default-generates one. Nothing here
|
||||
* ever writes the plaintext passphrase to disk.
|
||||
*/
|
||||
object StoreSecret {
|
||||
|
||||
/** AES-256 per the card. Keystore key size and this constant must agree. */
|
||||
const val KEY_BITS: Int = 256
|
||||
|
||||
/** 96-bit IV is the GCM-recommended size; AndroidKeyStore defaults to it. */
|
||||
const val IV_BYTES: Int = 12
|
||||
|
||||
/** Full-length GCM tag. Truncating it saves 6 bytes and buys nothing. */
|
||||
private const val TAG_BITS: Int = 128
|
||||
|
||||
private val MAGIC = byteArrayOf('O'.code.toByte(), 'W'.code.toByte(), 'S'.code.toByte(), 'E'.code.toByte(), 'A'.code.toByte(), 'L'.code.toByte(), '1'.code.toByte(), '\n'.code.toByte())
|
||||
|
||||
private const val TRANSFORMATION = "AES/GCM/NoPadding"
|
||||
|
||||
/**
|
||||
* Encrypts [plaintext] under [key]. The passphrase is never converted to a
|
||||
* `String` on this path: the UTF-8 encoder reads the `CharArray` directly.
|
||||
*/
|
||||
fun seal(key: SecretKey, plaintext: CharArray): ByteArray {
|
||||
require(plaintext.isNotEmpty()) { "refusing to seal an empty passphrase" }
|
||||
val bytes = utf8(plaintext)
|
||||
try {
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key)
|
||||
val iv = cipher.iv
|
||||
val ct = cipher.doFinal(bytes)
|
||||
return ByteArray(MAGIC.size + 1 + iv.size + ct.size).also { out ->
|
||||
var p = 0
|
||||
MAGIC.copyInto(out, p); p += MAGIC.size
|
||||
out[p] = iv.size.toByte(); p += 1
|
||||
iv.copyInto(out, p); p += iv.size
|
||||
ct.copyInto(out, p)
|
||||
}
|
||||
} catch (e: GeneralSecurityException) {
|
||||
throw SecretUnavailable("could not encrypt the passphrase", e)
|
||||
} finally {
|
||||
wipe(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverses [seal]. Throws [SecretUnavailable] on a wrong key, a truncated
|
||||
* blob, or a failed GCM tag check — never returns partial plaintext.
|
||||
*/
|
||||
fun open(key: SecretKey, blob: ByteArray): CharArray {
|
||||
if (blob.size < MAGIC.size + 1 + IV_BYTES + TAG_BITS / 8) {
|
||||
throw SecretUnavailable("stored secret is truncated")
|
||||
}
|
||||
for (i in MAGIC.indices) {
|
||||
if (blob[i] != MAGIC[i]) throw SecretUnavailable("stored secret is not an OnionWire envelope")
|
||||
}
|
||||
var p = MAGIC.size
|
||||
val ivLen = blob[p].toInt() and 0xFF
|
||||
p += 1
|
||||
if (ivLen != IV_BYTES) throw SecretUnavailable("unexpected IV length $ivLen")
|
||||
if (blob.size < p + ivLen + TAG_BITS / 8) throw SecretUnavailable("stored secret is truncated")
|
||||
val iv = blob.copyOfRange(p, p + ivLen)
|
||||
val ct = blob.copyOfRange(p + ivLen, blob.size)
|
||||
val plain = try {
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BITS, iv))
|
||||
cipher.doFinal(ct)
|
||||
} catch (e: GeneralSecurityException) {
|
||||
throw SecretUnavailable("stored secret did not authenticate", e)
|
||||
}
|
||||
return try {
|
||||
decodeUtf8(plain)
|
||||
} finally {
|
||||
wipe(plain)
|
||||
}
|
||||
}
|
||||
|
||||
/** Zeroes [bytes]. Cheap, and it shortens the window a heap dump can read. */
|
||||
fun wipe(bytes: ByteArray) {
|
||||
Arrays.fill(bytes, 0)
|
||||
}
|
||||
|
||||
/** Zeroes [chars]. Kotlin/Java strings are immutable, so this is the best we get. */
|
||||
fun wipe(chars: CharArray) {
|
||||
Arrays.fill(chars, '\u0000')
|
||||
}
|
||||
|
||||
private fun utf8(chars: CharArray): ByteArray {
|
||||
val bb = StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(chars))
|
||||
return ByteArray(bb.remaining()).also(bb::get)
|
||||
}
|
||||
|
||||
private fun decodeUtf8(bytes: ByteArray): CharArray {
|
||||
val cb = StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes))
|
||||
return CharArray(cb.remaining()).also(cb::get)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The passphrase could not be recovered. The caller must fall back to typing
|
||||
* it — a Keystore key does not survive a factory reset, a lock-screen change
|
||||
* that invalidates keys, or an app-data wipe.
|
||||
*/
|
||||
class SecretUnavailable(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
package com.siriusdevops.onionwire.crypto
|
||||
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* The only on-disk copy of the passphrase: an AES-GCM blob under
|
||||
* `context.filesDir`, which is app-private and excluded from backup and
|
||||
* device transfer (`AndroidManifest.xml`, `res/xml/data_extraction_rules.xml`).
|
||||
*
|
||||
* The blob is the envelope from [StoreSecret] — magic + IV + ciphertext + tag.
|
||||
* There is no second copy, no SharedPreferences mirror, and nothing outside the
|
||||
* app's data dir.
|
||||
*/
|
||||
class StoredPassphraseStore(
|
||||
private val file: File,
|
||||
private val cipher: PassphraseCipher,
|
||||
) {
|
||||
|
||||
sealed interface Load {
|
||||
/** Decrypted for this call only. The caller must wipe the array. */
|
||||
class Loaded(val passphrase: CharArray) : Load
|
||||
|
||||
/** Nothing stored yet — first run, or the user forgot it. */
|
||||
data object Absent : Load
|
||||
|
||||
/**
|
||||
* Something is stored but cannot be read: the Keystore key is gone or
|
||||
* invalidated, or the file is corrupt. Fall back to typing.
|
||||
*/
|
||||
data class Unavailable(val reason: String) : Load
|
||||
}
|
||||
|
||||
fun exists(): Boolean = file.isFile && file.length() > 0L
|
||||
|
||||
/** Where the wrapping key actually lives. See [PassphraseCipher.backing]. */
|
||||
fun backing(): KeyBacking = cipher.backing()
|
||||
|
||||
/** Path for diagnostics in tests. Never logged with its contents. */
|
||||
val path: String get() = file.absolutePath
|
||||
|
||||
/**
|
||||
* Encrypts and replaces the stored blob. Atomic-ish: written to a sibling
|
||||
* temp file and renamed, so a crash mid-write cannot leave half a blob.
|
||||
*/
|
||||
fun save(passphrase: CharArray) {
|
||||
require(passphrase.isNotEmpty()) { "refusing to store an empty passphrase" }
|
||||
val blob = cipher.seal(passphrase)
|
||||
try {
|
||||
file.parentFile?.mkdirs()
|
||||
val tmp = File(file.parentFile, file.name + ".tmp")
|
||||
tmp.writeBytes(blob)
|
||||
if (!tmp.renameTo(file)) {
|
||||
file.writeBytes(blob)
|
||||
tmp.delete()
|
||||
}
|
||||
} finally {
|
||||
StoreSecret.wipe(blob)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads and decrypts the blob. The returned array is the caller's to wipe.
|
||||
*
|
||||
* A failed decrypt does **not** delete the blob: a transient Keystore
|
||||
* failure must not silently destroy the user's only copy. Use [forget] to
|
||||
* drop it deliberately.
|
||||
*/
|
||||
fun load(): Load {
|
||||
if (!exists()) return Load.Absent
|
||||
val blob = try {
|
||||
file.readBytes()
|
||||
} catch (e: IOException) {
|
||||
return Load.Unavailable("the stored passphrase file could not be read (${e.message})")
|
||||
}
|
||||
return try {
|
||||
Load.Loaded(cipher.open(blob))
|
||||
} catch (e: SecretUnavailable) {
|
||||
Load.Unavailable(e.message ?: "the stored passphrase did not authenticate")
|
||||
} finally {
|
||||
StoreSecret.wipe(blob)
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops the ciphertext and the Keystore key. Irreversible. */
|
||||
fun forget() {
|
||||
file.delete()
|
||||
File(file.parentFile, file.name + ".tmp").delete()
|
||||
cipher.deleteKey()
|
||||
}
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@ package com.siriusdevops.onionwire.ui
|
|||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
|
|
@ -11,10 +12,13 @@ import androidx.compose.foundation.rememberScrollState
|
|||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
|
|
@ -28,10 +32,38 @@ import androidx.compose.ui.text.input.KeyboardType
|
|||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.siriusdevops.onionwire.Phase
|
||||
import com.siriusdevops.onionwire.Unlock
|
||||
import com.siriusdevops.onionwire.crypto.KeyBacking
|
||||
|
||||
/**
|
||||
* Lock screen.
|
||||
*
|
||||
* When [Unlock.OneTap] is set, the passphrase is already on disk wrapped by the
|
||||
* Android Keystore key and the user taps once. Otherwise they type it — and
|
||||
* they land here, with [Unlock.TypeIt.notice] explaining why, whenever the
|
||||
* stored blob cannot be read (key invalidated, device reset, corrupt file).
|
||||
*
|
||||
* The typed passphrase lives in a plain `remember` (not `rememberSaveable`) and
|
||||
* is cleared as soon as it is handed to the ViewModel: it never survives a
|
||||
* config change and never gets written to the saved-instance-state bundle.
|
||||
*/
|
||||
@Composable
|
||||
fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) {
|
||||
fun UnlockScreen(
|
||||
phase: Phase,
|
||||
unlock: Unlock,
|
||||
onUnlock: (passphrase: String, remember: Boolean) -> Unit,
|
||||
onUnlockStored: () -> Unit,
|
||||
onForgetStored: () -> Unit,
|
||||
) {
|
||||
var pass by remember { mutableStateOf("") }
|
||||
var storePassphrase by remember { mutableStateOf(true) }
|
||||
// Only meaningful under OneTap: reveal the form without giving up the
|
||||
// stored passphrase.
|
||||
var typeInstead by remember { mutableStateOf(false) }
|
||||
|
||||
val oneTap = unlock as? Unlock.OneTap
|
||||
val failed = phase is Phase.Failed
|
||||
val showForm = oneTap == null || typeInstead || failed
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
|
|
@ -64,38 +96,107 @@ fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) {
|
|||
}
|
||||
|
||||
else -> {
|
||||
Text(
|
||||
"Passphrase",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = pass,
|
||||
onValueChange = { pass = it },
|
||||
singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Password,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
label = { Text("wraps the local message key") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
"Empty is not a bypass — it fails closed. There is no recovery: " +
|
||||
"lose this and the stored chat bodies stay unreadable.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Button(
|
||||
onClick = { onUnlock(pass) },
|
||||
enabled = pass.isNotEmpty(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Open") }
|
||||
if (oneTap != null && !failed) {
|
||||
Text("Passphrase", style = MaterialTheme.typography.titleSmall)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
"Stored on this device, wrapped by an Android Keystore key " +
|
||||
"(${backingLabel(oneTap.backing)}).",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Button(
|
||||
onClick = onUnlockStored,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Unlock") }
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
TextButton(onClick = { typeInstead = true }) {
|
||||
Text("Type it instead")
|
||||
}
|
||||
TextButton(onClick = onForgetStored) {
|
||||
Text("Forget stored passphrase")
|
||||
}
|
||||
}
|
||||
if (showForm) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
HorizontalDivider()
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
if (phase is Phase.Failed) {
|
||||
if (showForm) {
|
||||
if (unlock is Unlock.TypeIt && unlock.notice != null) {
|
||||
Text(
|
||||
unlock.notice,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
|
||||
OutlinedTextField(
|
||||
value = pass,
|
||||
onValueChange = { pass = it },
|
||||
singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Password,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
label = { Text("wraps the local message key") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
"Empty is not a bypass — it fails closed. There is no recovery: " +
|
||||
"lose this and the stored chat bodies stay unreadable.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Checkbox(
|
||||
checked = storePassphrase,
|
||||
onCheckedChange = { storePassphrase = it },
|
||||
)
|
||||
Text(
|
||||
"Remember on this device (wrapped by the Android Keystore, " +
|
||||
"no backup)",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
if (oneTap != null) {
|
||||
Text(
|
||||
"Typing and remembering replaces the stored passphrase.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Button(
|
||||
onClick = {
|
||||
val typed = pass
|
||||
// Drop the plaintext from Compose state the moment
|
||||
// it is handed over; the ViewModel wipes its copy.
|
||||
pass = ""
|
||||
onUnlock(typed, storePassphrase)
|
||||
},
|
||||
enabled = pass.isNotEmpty(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Open") }
|
||||
}
|
||||
|
||||
if (failed) {
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Text(
|
||||
"Failed to start",
|
||||
|
|
@ -128,3 +229,14 @@ fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) {
|
|||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the Keystore reported, verbatim. Never upgraded into a stronger claim:
|
||||
* a software key says so.
|
||||
*/
|
||||
internal fun backingLabel(backing: KeyBacking): String = when (backing) {
|
||||
KeyBacking.STRONGBOX -> "StrongBox"
|
||||
KeyBacking.HARDWARE -> "TEE-backed"
|
||||
KeyBacking.SOFTWARE -> "software key, NOT hardware-backed"
|
||||
KeyBacking.UNKNOWN -> "backing not reported by this device"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,157 @@
|
|||
package com.siriusdevops.onionwire.crypto
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Test
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
|
||||
/**
|
||||
* Exercises the real envelope code — [StoreSecret] has no `android.*` imports,
|
||||
* so a JVM AES key stands in for the AndroidKeystore key.
|
||||
*
|
||||
* What this does NOT cover (see the PR description): the AndroidKeyStore provider
|
||||
* itself (`KeyGenerator` + `KeyGenParameterSpec`, StrongBox fallback, and
|
||||
* `KeyInfo.isInsideSecureHardware`). Those are device-only APIs; the unit-test
|
||||
* JVM has no such provider.
|
||||
*/
|
||||
class StoreSecretTest {
|
||||
|
||||
private fun aesKey(): SecretKey =
|
||||
KeyGenerator.getInstance("AES").apply { init(StoreSecret.KEY_BITS) }.generateKey()
|
||||
|
||||
private val passphrase = "correct horse battery staple".toCharArray()
|
||||
|
||||
@Test
|
||||
fun seal_open_round_trips() {
|
||||
val key = aesKey()
|
||||
val blob = StoreSecret.seal(key, passphrase)
|
||||
val out = StoreSecret.open(key, blob)
|
||||
try {
|
||||
assertArrayEquals(passphrase, out)
|
||||
} finally {
|
||||
StoreSecret.wipe(out)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun round_trips_non_ascii_and_whitespace() {
|
||||
val key = aesKey()
|
||||
val weird = " ünïcödé 🔑 \n\ttab ".toCharArray()
|
||||
val out = StoreSecret.open(key, StoreSecret.seal(key, weird))
|
||||
try {
|
||||
assertArrayEquals(weird, out)
|
||||
} finally {
|
||||
StoreSecret.wipe(out)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blob_does_not_contain_the_plaintext() {
|
||||
val key = aesKey()
|
||||
val blob = StoreSecret.seal(key, passphrase)
|
||||
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
|
||||
assertFalse(
|
||||
"ciphertext must not contain the passphrase",
|
||||
blob.containsSubsequence(needle),
|
||||
)
|
||||
assertTrue(blob.size > needle.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blob_carries_the_envelope_magic() {
|
||||
val blob = StoreSecret.seal(aesKey(), passphrase)
|
||||
assertEquals("OWSEAL1\n", String(blob.copyOfRange(0, 8), Charsets.US_ASCII))
|
||||
// Magic(8) + IV length(1) + IV(12) + tag(16)
|
||||
assertEquals(8 + 1 + StoreSecret.IV_BYTES + 16, blob.size - String(passphrase).toByteArray(Charsets.UTF_8).size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun each_seal_uses_a_fresh_iv() {
|
||||
val key = aesKey()
|
||||
val a = StoreSecret.seal(key, passphrase)
|
||||
val b = StoreSecret.seal(key, passphrase)
|
||||
assertNotEquals(
|
||||
"identical ciphertext means the IV was reused",
|
||||
a.toList(),
|
||||
b.toList(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wrong_key_fails_closed() {
|
||||
val blob = StoreSecret.seal(aesKey(), passphrase)
|
||||
try {
|
||||
StoreSecret.open(aesKey(), blob)
|
||||
fail("expected SecretUnavailable")
|
||||
} catch (e: SecretUnavailable) {
|
||||
assertTrue(e.message!!.contains("authenticate"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tampered_ciphertext_fails_the_gcm_tag() {
|
||||
val key = aesKey()
|
||||
val blob = StoreSecret.seal(key, passphrase)
|
||||
blob[blob.size - 1] = (blob[blob.size - 1].toInt() xor 0x01).toByte()
|
||||
try {
|
||||
StoreSecret.open(key, blob)
|
||||
fail("expected SecretUnavailable")
|
||||
} catch (_: SecretUnavailable) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun truncated_blob_fails_closed() {
|
||||
val key = aesKey()
|
||||
val blob = StoreSecret.seal(key, passphrase)
|
||||
try {
|
||||
StoreSecret.open(key, blob.copyOfRange(0, 10))
|
||||
fail("expected SecretUnavailable")
|
||||
} catch (_: SecretUnavailable) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun garbage_blob_fails_closed() {
|
||||
try {
|
||||
StoreSecret.open(aesKey(), "not an envelope".toByteArray())
|
||||
fail("expected SecretUnavailable")
|
||||
} catch (e: SecretUnavailable) {
|
||||
assertTrue(e.message!!.contains("truncated") || e.message!!.contains("envelope"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun seal_refuses_an_empty_passphrase() {
|
||||
try {
|
||||
StoreSecret.seal(aesKey(), CharArray(0))
|
||||
fail("expected IllegalArgumentException")
|
||||
} catch (_: IllegalArgumentException) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wipe_zeroes() {
|
||||
val bytes = byteArrayOf(1, 2, 3)
|
||||
StoreSecret.wipe(bytes)
|
||||
assertArrayEquals(ByteArray(3), bytes)
|
||||
|
||||
val chars = charArrayOf('a', 'b')
|
||||
StoreSecret.wipe(chars)
|
||||
assertArrayEquals(CharArray(2), chars)
|
||||
}
|
||||
|
||||
private fun ByteArray.containsSubsequence(needle: ByteArray): Boolean {
|
||||
if (needle.isEmpty() || needle.size > size) return false
|
||||
outer@ for (i in 0..size - needle.size) {
|
||||
for (j in needle.indices) if (this[i + j] != needle[j]) continue@outer
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,167 @@
|
|||
package com.siriusdevops.onionwire.crypto
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
|
||||
/**
|
||||
* File-level behaviour of [StoredPassphraseStore] with the real envelope from
|
||||
* [StoreSecret] and a JVM AES key standing in for the Keystore key.
|
||||
*
|
||||
* The Keystore itself is device-only; what is proven here is that nothing
|
||||
* plaintext reaches the file, that a lost key degrades instead of crashing,
|
||||
* and that a lost key does not delete the user's blob.
|
||||
*/
|
||||
class StoredPassphraseStoreTest {
|
||||
|
||||
@get:Rule
|
||||
val tmp = TemporaryFolder()
|
||||
|
||||
private val passphrase = "correct horse battery staple".toCharArray()
|
||||
|
||||
/** Stands in for the AndroidKeystore key: real AES-GCM, JVM-held key. */
|
||||
private class JvmKeyCipher(private val key: SecretKey) : PassphraseCipher {
|
||||
var deleted = false
|
||||
var backingQueried = 0
|
||||
|
||||
override fun seal(plaintext: CharArray): ByteArray = StoreSecret.seal(key, plaintext)
|
||||
|
||||
override fun open(blob: ByteArray): CharArray {
|
||||
if (deleted) throw SecretUnavailable("the device's Keystore key for OnionWire is gone")
|
||||
return StoreSecret.open(key, blob)
|
||||
}
|
||||
|
||||
override fun keyPresent(): Boolean = !deleted
|
||||
|
||||
override fun backing(): KeyBacking {
|
||||
backingQueried++
|
||||
return KeyBacking.SOFTWARE
|
||||
}
|
||||
|
||||
override fun deleteKey() {
|
||||
deleted = true
|
||||
}
|
||||
}
|
||||
|
||||
private fun jvmKey(): SecretKey =
|
||||
KeyGenerator.getInstance("AES").apply { init(StoreSecret.KEY_BITS) }.generateKey()
|
||||
|
||||
private fun store(cipher: PassphraseCipher) =
|
||||
StoredPassphraseStore(tmp.newFile("store-passphrase.bin").also { it.delete() }, cipher)
|
||||
|
||||
@Test
|
||||
fun save_then_load_round_trips() {
|
||||
val store = store(JvmKeyCipher(jvmKey()))
|
||||
store.save(passphrase)
|
||||
|
||||
val loaded = store.load()
|
||||
assertTrue(loaded is StoredPassphraseStore.Load.Loaded)
|
||||
val out = (loaded as StoredPassphraseStore.Load.Loaded).passphrase
|
||||
try {
|
||||
assertArrayEquals(passphrase, out)
|
||||
} finally {
|
||||
StoreSecret.wipe(out)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun on_disk_blob_is_not_the_plaintext() {
|
||||
val store = store(JvmKeyCipher(jvmKey()))
|
||||
store.save(passphrase)
|
||||
|
||||
val raw = java.io.File(store.path).readBytes()
|
||||
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
|
||||
assertFalse(
|
||||
"the passphrase must not appear in the file",
|
||||
raw.toString(Charsets.ISO_8859_1).contains(String(needle, Charsets.ISO_8859_1)),
|
||||
)
|
||||
assertTrue("expected the OWSEAL envelope", raw.size > needle.size + 20)
|
||||
assertEquals("OWSEAL1\n", String(raw.copyOfRange(0, 8), Charsets.US_ASCII))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun no_temp_file_is_left_behind() {
|
||||
val store = store(JvmKeyCipher(jvmKey()))
|
||||
store.save(passphrase)
|
||||
val dir = requireNotNull(java.io.File(store.path).parentFile)
|
||||
val leftovers = dir.listFiles()!!.filter { it.name.endsWith(".tmp") }
|
||||
assertTrue("temp files left: $leftovers", leftovers.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun save_overwrites_the_previous_blob() {
|
||||
val store = store(JvmKeyCipher(jvmKey()))
|
||||
store.save("first".toCharArray())
|
||||
store.save("second".toCharArray())
|
||||
|
||||
val loaded = store.load() as StoredPassphraseStore.Load.Loaded
|
||||
try {
|
||||
assertArrayEquals("second".toCharArray(), loaded.passphrase)
|
||||
} finally {
|
||||
StoreSecret.wipe(loaded.passphrase)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun absent_when_nothing_was_ever_stored() {
|
||||
val store = store(JvmKeyCipher(jvmKey()))
|
||||
assertFalse(store.exists())
|
||||
assertEquals(StoredPassphraseStore.Load.Absent, store.load())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lost_key_reports_unavailable_and_keeps_the_blob() {
|
||||
val cipher = JvmKeyCipher(jvmKey())
|
||||
val store = store(cipher)
|
||||
store.save(passphrase)
|
||||
|
||||
cipher.deleteKey() // device reset / key invalidated
|
||||
|
||||
val loaded = store.load()
|
||||
assertTrue(loaded is StoredPassphraseStore.Load.Unavailable)
|
||||
assertTrue(
|
||||
(loaded as StoredPassphraseStore.Load.Unavailable).reason.contains("gone"),
|
||||
)
|
||||
assertTrue("a failed read must not delete the blob", store.exists())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun corrupt_blob_reports_unavailable_instead_of_throwing() {
|
||||
val store = store(JvmKeyCipher(jvmKey()))
|
||||
store.save(passphrase)
|
||||
java.io.File(store.path).writeBytes("OWSEAL1\n not really a ciphertext".toByteArray())
|
||||
|
||||
val loaded = store.load()
|
||||
assertTrue(loaded is StoredPassphraseStore.Load.Unavailable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun forget_deletes_the_blob_and_the_key() {
|
||||
val cipher = JvmKeyCipher(jvmKey())
|
||||
val store = store(cipher)
|
||||
store.save(passphrase)
|
||||
assertTrue(store.exists())
|
||||
|
||||
store.forget()
|
||||
|
||||
assertFalse(store.exists())
|
||||
assertFalse(cipher.keyPresent())
|
||||
assertEquals(StoredPassphraseStore.Load.Absent, store.load())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun backing_is_reported_from_the_cipher() {
|
||||
val cipher = JvmKeyCipher(jvmKey())
|
||||
val store = store(cipher)
|
||||
store.save(passphrase)
|
||||
|
||||
assertEquals(KeyBacking.SOFTWARE, store.backing())
|
||||
assertEquals(1, cipher.backingQueried)
|
||||
}
|
||||
}
|
||||
|
|
@ -9,11 +9,15 @@ composeBom = "2025.12.01"
|
|||
jna = "5.19.1"
|
||||
coroutines = "1.11.0"
|
||||
junit = "4.13.2"
|
||||
androidxTestJunit = "1.3.0"
|
||||
androidxTestRunner = "1.7.0"
|
||||
|
||||
[libraries]
|
||||
androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "coreKtx" }
|
||||
jna = { module = "net.java.dev.jna:jna", version.ref = "jna" }
|
||||
junit = { module = "junit:junit", version.ref = "junit" }
|
||||
androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "androidxTestJunit" }
|
||||
androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidxTestRunner" }
|
||||
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
|
||||
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }
|
||||
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" }
|
||||
|
|
|
|||
60
docs/TUI.md
60
docs/TUI.md
|
|
@ -510,3 +510,63 @@ add it on this card. Preferred: depend on `unicode-width` explicitly and assert
|
|||
|
||||
`tests/tui_frames.rs` `chars_count_is_not_terminal_cells` documents the three
|
||||
examples without adding a crate.
|
||||
|
||||
## After frames (spacing / ASCII / wrap / copy)
|
||||
|
||||
Base: `origin/main` after PR #24 (`33beede`). Hierarchy, fail-closed footer,
|
||||
1-line header, roster width, help overlay, and `NO_COLOR` palette are unchanged
|
||||
here. Optional 3-line wordmark at height ≥ 40 was skipped (it fights the 1-line
|
||||
header without buying hierarchy).
|
||||
|
||||
### 80x24 — `draw_share` after (field-boundary wrap)
|
||||
|
||||
Invite lines break on `:`. `sig=` hex that does not fit continues as an
|
||||
all-hex line. Joining those lines (no extra spaces) is the original payload.
|
||||
|
||||
```
|
||||
┌(o) invite────────────────────────────────────────────────────────────────────┐
|
||||
│give this string to a friend; they F3 paste it │
|
||||
│ │
|
||||
│fp ea4a6c63… │
|
||||
│onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion │
|
||||
│ │
|
||||
│onionwire:v1: │
|
||||
│k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: │
|
||||
│o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: │
|
||||
│spk=0101010101010101010101010101010101010101010101010101010101010101: │
|
||||
│sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0│
|
||||
│5401b0af934cefea617f71466f406af4bef956847200a8e915190b │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 80x24 — ASCII switch (`ONIONWIRE_ASCII=1`)
|
||||
|
||||
No non-ASCII byte. Truncation marker is `...`. Borders are `+` `-` `|`.
|
||||
|
||||
```
|
||||
+(o) invite--------------------------------------------------------------------+
|
||||
|give this string to a friend; they F3 paste it |
|
||||
| |
|
||||
|fp ea4a6c63... |
|
||||
|onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion |
|
||||
| |
|
||||
|onionwire:v1: |
|
||||
|k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: |
|
||||
|o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: |
|
||||
|spk=0101010101010101010101010101010101010101010101010101010101010101: |
|
||||
|sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0|
|
||||
|5401b0af934cefea617f71466f406af4bef956847200a8e915190b |
|
||||
+------------------------------------------------------------------------------+
|
||||
```
|
||||
|
||||
### 80x24 / 120x40 — main chrome after
|
||||
|
||||
Same 1-line header, unboxed composer, fail-closed footer as PR #24. Dump:
|
||||
|
||||
```
|
||||
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.
|
||||
|
|
|
|||
122
src/tui.rs
122
src/tui.rs
|
|
@ -5,6 +5,7 @@ use std::time::Duration;
|
|||
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
|
||||
use ratatui::layout::{Constraint, Layout, Rect};
|
||||
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};
|
||||
|
||||
|
|
@ -38,8 +39,90 @@ fn color_mode() -> ColorMode {
|
|||
}
|
||||
}
|
||||
|
||||
/// ASCII chrome when `ONIONWIRE_ASCII` or `NO_COLOR` is set. No extra crate.
|
||||
pub fn ascii_chrome() -> bool {
|
||||
std::env::var_os("ONIONWIRE_ASCII").is_some() || std::env::var_os("NO_COLOR").is_some()
|
||||
}
|
||||
|
||||
const ASCII_BORDERS: border::Set = border::Set {
|
||||
top_left: "+",
|
||||
top_right: "+",
|
||||
bottom_left: "+",
|
||||
bottom_right: "+",
|
||||
vertical_left: "|",
|
||||
vertical_right: "|",
|
||||
horizontal_top: "-",
|
||||
horizontal_bottom: "-",
|
||||
};
|
||||
|
||||
fn ellipsis() -> &'static str {
|
||||
"…"
|
||||
if ascii_chrome() { "..." } else { "…" }
|
||||
}
|
||||
|
||||
/// Truncate or keep an alert so it cannot spill into the roster row.
|
||||
pub fn alert_line(msg: &str, width: u16) -> String {
|
||||
let mut text = msg.to_string();
|
||||
if color_mode() == ColorMode::None && !text.starts_with("! ") {
|
||||
text = format!("! {text}");
|
||||
}
|
||||
truncate_chars(&text, width as usize)
|
||||
}
|
||||
|
||||
/// Wrap an invite at `:` so a mouse-copy cannot lose a mid-hex continuation.
|
||||
/// Joining the lines (no extra spaces) reconstructs `payload`.
|
||||
pub fn wrap_invite(payload: &str, width: usize) -> String {
|
||||
if width == 0 {
|
||||
return String::new();
|
||||
}
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let parts: Vec<&str> = payload.split(':').collect();
|
||||
for (i, part) in parts.iter().enumerate() {
|
||||
let piece = if i + 1 < parts.len() {
|
||||
format!("{part}:")
|
||||
} else {
|
||||
(*part).to_string()
|
||||
};
|
||||
for chunk in char_chunks(&piece, width) {
|
||||
if cur.is_empty() {
|
||||
cur = chunk;
|
||||
} else if char_len(&cur) + char_len(&chunk) <= width {
|
||||
cur.push_str(&chunk);
|
||||
} else {
|
||||
lines.push(std::mem::take(&mut cur));
|
||||
cur = chunk;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !cur.is_empty() {
|
||||
lines.push(cur);
|
||||
}
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
fn char_chunks(s: &str, width: usize) -> Vec<String> {
|
||||
if width == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
if char_len(s) <= width {
|
||||
return vec![s.to_string()];
|
||||
}
|
||||
let chars: Vec<char> = s.chars().collect();
|
||||
chars.chunks(width).map(|c| c.iter().collect()).collect()
|
||||
}
|
||||
|
||||
/// Friend selected, no messages yet.
|
||||
pub fn empty_friend_chat_text() -> &'static str {
|
||||
"no messages\ntype below, Enter sends"
|
||||
}
|
||||
|
||||
/// Paste overlay copy. Error keeps the resubmit hint.
|
||||
pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String {
|
||||
let hint = match err {
|
||||
Some(e) => format!("{e}\nEnter resubmits Esc back"),
|
||||
None => "paste onionwire:v1 payload, Enter to submit".to_string(),
|
||||
};
|
||||
format!("{hint}\n\n{buf}")
|
||||
}
|
||||
|
||||
fn char_len(s: &str) -> usize {
|
||||
|
|
@ -1429,11 +1512,7 @@ impl App {
|
|||
|
||||
f.render_widget(Paragraph::new(header).style(style_accent()), cols[0]);
|
||||
if let Some(msg) = &self.alert {
|
||||
let text = if color_mode() == ColorMode::None && !msg.starts_with("! ") {
|
||||
format!("! {msg}")
|
||||
} else {
|
||||
msg.clone()
|
||||
};
|
||||
let text = alert_line(msg, area.width);
|
||||
f.render_widget(Paragraph::new(text).style(style_alert()), cols[1]);
|
||||
}
|
||||
|
||||
|
|
@ -1559,7 +1638,10 @@ impl App {
|
|||
];
|
||||
};
|
||||
match self.node.list_messages(&friend.pubkey) {
|
||||
Ok(msgs) if msgs.is_empty() => vec!["no messages".into()],
|
||||
Ok(msgs) if msgs.is_empty() => empty_friend_chat_text()
|
||||
.lines()
|
||||
.map(str::to_string)
|
||||
.collect(),
|
||||
Ok(msgs) => msgs
|
||||
.iter()
|
||||
.map(|m| {
|
||||
|
|
@ -1583,8 +1665,7 @@ impl App {
|
|||
} else {
|
||||
style_dim()
|
||||
};
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
apply_chrome_borders(Block::default())
|
||||
.border_style(border)
|
||||
.title(title)
|
||||
.title_style(title_style)
|
||||
|
|
@ -1699,9 +1780,17 @@ fn footer_hints(screen: &Screen) -> &'static str {
|
|||
}
|
||||
}
|
||||
|
||||
fn apply_chrome_borders(block: Block<'_>) -> Block<'_> {
|
||||
let block = block.borders(Borders::ALL);
|
||||
if ascii_chrome() {
|
||||
block.border_set(ASCII_BORDERS)
|
||||
} else {
|
||||
block
|
||||
}
|
||||
}
|
||||
|
||||
fn themed_block(title: &str) -> Block<'_> {
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
apply_chrome_borders(Block::default())
|
||||
.border_style(style_accent())
|
||||
.title(title)
|
||||
.title_style(style_accent().add_modifier(Modifier::BOLD))
|
||||
|
|
@ -1712,8 +1801,10 @@ pub fn draw_share(f: &mut Frame, payload: &str) {
|
|||
Ok(p) => (truncate_fp(&to_hex(&p.pubkey)), p.onion),
|
||||
Err(_) => ("?".into(), "?".into()),
|
||||
};
|
||||
let inner = f.area().width.saturating_sub(2) as usize;
|
||||
let invite = wrap_invite(payload, inner.max(1));
|
||||
let body = format!(
|
||||
"give this string to a friend; they F3 paste it\n\nfp {fp}\nonion {onion}\n\n{payload}"
|
||||
"give this string to a friend; they F3 paste it\n\nfp {fp}\nonion {onion}\n\n{invite}"
|
||||
);
|
||||
f.render_widget(
|
||||
Paragraph::new(body)
|
||||
|
|
@ -1725,10 +1816,9 @@ pub fn draw_share(f: &mut Frame, payload: &str) {
|
|||
}
|
||||
|
||||
fn draw_paste(f: &mut Frame, buf: &str, err: Option<&str>) {
|
||||
let hint = err
|
||||
.unwrap_or("paste onionwire:v1 payload, Enter to submit")
|
||||
.to_string();
|
||||
let body = format!("{hint}\n\n{buf}");
|
||||
let inner = f.area().width.saturating_sub(2) as usize;
|
||||
let shown = wrap_invite(buf, inner.max(1));
|
||||
let body = paste_screen_text(&shown, err);
|
||||
let style = if err.is_some() {
|
||||
style_alert()
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -1,17 +1,21 @@
|
|||
//! Spec implementation tests for docs/TUI.md (this card).
|
||||
//! Does not own `tests/tui_frames.rs` (PR #23).
|
||||
|
||||
use onionwire::qr;
|
||||
use onionwire::tui::{
|
||||
draw_text_overlay, help_overlay_text, main_footer_hints, main_header_line, roster_col_width,
|
||||
status_footer,
|
||||
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,
|
||||
status_footer, wrap_invite,
|
||||
};
|
||||
use ratatui::Frame;
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::TestBackend;
|
||||
use ratatui::layout::{Constraint, Layout};
|
||||
use ratatui::widgets::{Block, Borders, List, ListItem, Paragraph, Wrap};
|
||||
use std::sync::Mutex;
|
||||
|
||||
const FP: &str = "abcdef0123456789deadbeefcafebabe";
|
||||
static ASCII_ENV: Mutex<()> = Mutex::new(());
|
||||
const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion";
|
||||
|
||||
fn screen_from(buf: &ratatui::buffer::Buffer, w: u16, h: u16) -> String {
|
||||
|
|
@ -179,6 +183,8 @@ fn reconstructed_main_keeps_send_failed_on_footer() {
|
|||
|
||||
#[test]
|
||||
fn dump_spec_frames() {
|
||||
let _guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
|
||||
for (w, h) in [(80u16, 24u16), (120, 40)] {
|
||||
let backend = TestBackend::new(w, h);
|
||||
let mut terminal = Terminal::new(backend).expect("terminal");
|
||||
|
|
@ -205,5 +211,168 @@ fn dump_spec_frames() {
|
|||
.expect("draw");
|
||||
println!("===== AFTER help {w}x{h} =====");
|
||||
print!("{}", screen_from(terminal.backend().buffer(), w, h));
|
||||
|
||||
let invite = sample_invite();
|
||||
let backend = TestBackend::new(w, h);
|
||||
let mut terminal = Terminal::new(backend).expect("terminal");
|
||||
terminal.draw(|f| draw_share(f, &invite)).expect("draw");
|
||||
println!("===== AFTER share {w}x{h} =====");
|
||||
print!("{}", screen_from(terminal.backend().buffer(), w, h));
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_invite() -> String {
|
||||
let sk = [7u8; 32];
|
||||
qr::encode(&sk, ONION, &[1u8; 32]).expect("encode")
|
||||
}
|
||||
|
||||
fn invite_line_ok(line: &str) -> bool {
|
||||
let t = line.trim();
|
||||
t.is_empty()
|
||||
|| t.starts_with("onionwire:")
|
||||
|| t.starts_with("k=")
|
||||
|| t.starts_with("o=")
|
||||
|| t.starts_with("spk=")
|
||||
|| t.starts_with("sig=")
|
||||
|| t.chars().all(|c| c.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alert_line_truncates_to_frame_width() {
|
||||
let long = "passphrases do not match and then a lot more context that would collide with the roster on the next row if left unwrapped";
|
||||
let line = alert_line(long, 80);
|
||||
assert!(
|
||||
line.chars().count() <= 80,
|
||||
"alert wider than 80: {} {line:?}",
|
||||
line.chars().count()
|
||||
);
|
||||
assert!(
|
||||
line.contains('…') || line.contains("..."),
|
||||
"long alert was not truncated: {line:?}"
|
||||
);
|
||||
assert!(
|
||||
!line.contains("roster on the next row"),
|
||||
"alert still has overflow tail: {line:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrap_invite_breaks_on_field_boundaries() {
|
||||
let invite = sample_invite();
|
||||
assert!(invite.len() > 78, "fixture too short to wrap: {invite}");
|
||||
let wrapped = wrap_invite(&invite, 78);
|
||||
for line in wrapped.lines() {
|
||||
assert!(
|
||||
line.chars().count() <= 78,
|
||||
"invite line wider than 78: {} {line:?}",
|
||||
line.chars().count()
|
||||
);
|
||||
assert!(
|
||||
invite_line_ok(line),
|
||||
"invite wrapped mid-token: {line:?}\n{wrapped}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
wrapped.contains("onionwire:v1:"),
|
||||
"lost invite prefix:\n{wrapped}"
|
||||
);
|
||||
assert!(wrapped.contains("k="), "lost k= field:\n{wrapped}");
|
||||
assert!(wrapped.contains("spk="), "lost spk= field:\n{wrapped}");
|
||||
let joined: String = wrapped.lines().map(str::trim).collect();
|
||||
assert_eq!(
|
||||
joined, invite,
|
||||
"wrap must be newline-joinable back to payload"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draw_share_invite_does_not_wrap_mid_token() {
|
||||
let invite = sample_invite();
|
||||
let backend = TestBackend::new(80, 24);
|
||||
let mut terminal = Terminal::new(backend).expect("terminal");
|
||||
terminal.draw(|f| draw_share(f, &invite)).expect("draw");
|
||||
let screen = screen_from(terminal.backend().buffer(), 80, 24);
|
||||
assert!(
|
||||
screen.contains("onionwire:v1:"),
|
||||
"missing prefix:\n{screen}"
|
||||
);
|
||||
for raw in screen.lines() {
|
||||
let inner = raw.trim_start_matches(['│', '|', ' ']);
|
||||
let inner = inner.trim_end_matches(['│', '|', ' ']);
|
||||
if inner.starts_with("onionwire:")
|
||||
|| inner.starts_with("k=")
|
||||
|| inner.starts_with("o=")
|
||||
|| inner.starts_with("spk=")
|
||||
|| inner.starts_with("sig=")
|
||||
|| inner.chars().all(|c| c.is_ascii_hexdigit())
|
||||
{
|
||||
assert!(
|
||||
invite_line_ok(inner),
|
||||
"share pane mid-token wrap: {inner:?}\n{screen}"
|
||||
);
|
||||
}
|
||||
if inner.starts_with('c') && inner.contains(":o=") {
|
||||
panic!("share still wraps mid-hex into :o=: {inner:?}\n{screen}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_friend_chat_has_send_hint() {
|
||||
let text = empty_friend_chat_text();
|
||||
assert!(text.contains("no messages"), "{text:?}");
|
||||
assert!(text.contains("type below, Enter sends"), "{text:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_error_keeps_resubmit_hint() {
|
||||
let body = paste_screen_text("", Some("bad invite"));
|
||||
assert!(body.contains("bad invite"), "{body:?}");
|
||||
assert!(body.contains("Enter resubmits"), "{body:?}");
|
||||
assert!(body.contains("Esc back"), "{body:?}");
|
||||
let ok = paste_screen_text("onionwire:v1:k=x", None);
|
||||
assert!(
|
||||
ok.contains("paste onionwire:v1 payload"),
|
||||
"happy-path hint lost: {ok:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ascii_switch_80x24_frame_is_pure_ascii() {
|
||||
let _guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
unsafe { std::env::set_var("ONIONWIRE_ASCII", "1") };
|
||||
assert!(
|
||||
ascii_chrome(),
|
||||
"ONIONWIRE_ASCII set but ascii_chrome() is false"
|
||||
);
|
||||
let footer = status_footer(80, FP, ONION, None, main_footer_hints());
|
||||
assert!(
|
||||
footer.contains("..."),
|
||||
"ASCII truncation marker missing: {footer:?}"
|
||||
);
|
||||
assert!(
|
||||
!footer.contains('…'),
|
||||
"unicode ellipsis still in footer: {footer:?}"
|
||||
);
|
||||
|
||||
let invite = sample_invite();
|
||||
let backend = TestBackend::new(80, 24);
|
||||
let mut terminal = Terminal::new(backend).expect("terminal");
|
||||
terminal.draw(|f| draw_share(f, &invite)).expect("draw");
|
||||
let screen = screen_from(terminal.backend().buffer(), 80, 24);
|
||||
let non_ascii: Vec<char> = screen.chars().filter(|c| !c.is_ascii()).collect();
|
||||
assert!(
|
||||
non_ascii.is_empty(),
|
||||
"ASCII switch ignored, non-ASCII in 80x24 frame: {non_ascii:?}\n{screen}"
|
||||
);
|
||||
assert!(
|
||||
screen.contains("..."),
|
||||
"truncation marker missing from ASCII frame:\n{screen}"
|
||||
);
|
||||
assert!(
|
||||
screen.contains('+') && screen.contains('|') && screen.contains('-'),
|
||||
"ASCII borders missing:\n{screen}"
|
||||
);
|
||||
println!("===== AFTER ascii share 80x24 =====\n{screen}");
|
||||
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue