feat(android): wrap the store passphrase in the Android Keystore

Typing the passphrase on every launch was the v1 posture. It stays the
fallback, but it is no longer required: on first unlock the passphrase can be
remembered (checkbox, on by default) and is stored as an AES-256-GCM blob
wrapped by a key that never leaves the Android Keystore.

- crypto/StoreSecret.kt: the OWSEAL1 envelope (magic + IV + ciphertext + GCM
  tag) and the wipe helpers. No android.* imports, so the code that runs on a
  device is the code the unit tests exercise, with a JVM AES key standing in
  for the Keystore key.
- crypto/KeystorePassphraseCipher.kt: AES-256-GCM key under alias
  `onionwire.store`, StrongBox requested first (API 28+) with a graceful
  fallback on ProviderException (StrongBoxUnavailableException is one), and an
  honest KeyInfo-backed report of where the key actually lives.
  setUserAuthenticationRequired(false) stays the default on purpose.
- crypto/StoredPassphraseStore.kt: ciphertext only, at
  filesDir/secrets/store-passphrase.bin, written tmp+rename. A failed decrypt
  reports Unavailable and does NOT delete the blob.
- WireViewModel: unlock(passphrase, remember), unlockStored(),
  forgetStoredPassphrase(); the secret CharArray is zeroed in `finally`; the
  Keystore probe runs off the main thread at ViewModel construction.
- UnlockScreen: one-tap when a stored blob exists, the typed passphrase is
  dropped from Compose state as soon as it is handed over and is never put in
  saved instance state; "Forget stored passphrase" deletes blob and key.
- androidTest: the device-only half (AndroidKeyStore, StrongBox, KeyInfo),
  which cannot run in the unit-test JVM.

Verified: ./gradlew :app:assembleDebug and :app:testDebugUnitTest green,
25 tests / 0 failures (11 new StoreSecretTest, 9 new StoredPassphraseStoreTest).
This commit is contained in:
Sirius DevOps 2026-09-12 13:01:25 -04:00
commit 2fd640e230
No known key found for this signature in database
13 changed files with 1245 additions and 43 deletions

View file

@ -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,
)
}
}

View file

@ -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() {

View file

@ -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"
}
}

View file

@ -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,
}

View file

@ -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)

View file

@ -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()
}
}

View file

@ -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"
}