675504ae8d75
feat: C6 biometric unlock — BiometricKeyStore wraps vault key under hardware KeyStore key (auth-required, invalidated-on-reenroll); Biometrics.authenticateCrypto CryptoObject flow; enable/disable in Protection settings (prompt→wrap / clear); LockScreen real canTryBiometric + 300ms auto-trigger + 'Use biometrics' button → unlockWithKey; VaultRepository.currentVaultKey() (v2.1.29)
- time
- 2026-06-09 03:51 UTC · 5 months ago
- machine
- koh2
- agent
- claude-opus-4-8
- session
- peach gap implementation
- parent
- 30882ab0d494
↓ peach-android-675504ae.tar.gzatlas at this save
files changed8 files
app/build.gradle+2 −2app/src/main/java/com/peachpasswords/ui/lock/BiometricKeyStore.kt+119 −0app/src/main/java/com/peachpasswords/ui/lock/Biometrics.kt+35 −0app/src/main/java/com/peachpasswords/ui/lock/LockScreen.kt+27 −0app/src/main/java/com/peachpasswords/ui/lock/LockViewModel.kt+43 −2app/src/main/java/com/peachpasswords/ui/settings/SettingsCardBodies.kt+4 −1app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt+44 −0app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+7 −0app/build.gradle+2 −2
@@ -16,8 +16,8 @@1616 applicationId "com.peachpasswords"1717 minSdk 261818 targetSdk 3519- versionCode 20102820- versionName "2.1.28"19+ versionCode 20102920+ versionName "2.1.29"2121 2222 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"2323 vectorDrawables {app/src/main/java/com/peachpasswords/ui/lock/BiometricKeyStore.kt+119 −0
@@ -0,0 +1,119 @@1+package com.peachpasswords.ui.lock2+3+import android.content.Context4+import android.os.Build5+import android.security.keystore.KeyGenParameterSpec6+import android.security.keystore.KeyPermanentlyInvalidatedException7+import android.security.keystore.KeyProperties8+import java.security.KeyStore9+import java.util.Base6410+import javax.crypto.Cipher11+import javax.crypto.KeyGenerator12+import javax.crypto.SecretKey13+import javax.crypto.spec.GCMParameterSpec14+15+/**16+ * Stores the vault's AES key wrapped under a hardware-backed, biometric-gated17+ * Android KeyStore key, so the lock screen can unlock without the master password.18+ *19+ * The KeyStore key requires user (biometric) authentication for every use, so both20+ * wrapping (on enable) and unwrapping (on unlock) must happen inside a21+ * [androidx.biometric.BiometricPrompt] `CryptoObject`. The wrapped blob + IV are22+ * kept in plain prefs — they are AES-256-GCM ciphertext under a key that never23+ * leaves the secure hardware, so the prefs themselves carry no secret.24+ *25+ * Enrolling a new biometric invalidates the key ([setInvalidatedByBiometricEnrollment]);26+ * the resulting [KeyPermanentlyInvalidatedException] is caught and the escrow cleared,27+ * so the user simply falls back to the master password.28+ */29+object BiometricKeyStore {30+ private const val KEY_ALIAS = "peach_bio_vault_key"31+ private const val KEYSTORE = "AndroidKeyStore"32+ private const val TRANSFORM = "AES/GCM/NoPadding"33+ private const val PREFS = "peach_bio_prefs"34+ private const val K_WRAPPED = "wrapped"35+ private const val K_IV = "iv"36+ private const val GCM_TAG_BITS = 12837+38+ private fun prefs(context: Context) =39+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)40+41+ fun hasWrappedKey(context: Context): Boolean =42+ prefs(context).contains(K_WRAPPED) && prefs(context).contains(K_IV)43+44+ fun clear(context: Context) {45+ prefs(context).edit().remove(K_WRAPPED).remove(K_IV).apply()46+ runCatching {47+ KeyStore.getInstance(KEYSTORE).apply { load(null) }.deleteEntry(KEY_ALIAS)48+ }49+ }50+51+ /** Cipher to wrap the vault key on enable (fresh random IV). Drive via CryptoObject. */52+ fun encryptCipher(): Cipher {53+ val key = getOrCreateKey()54+ return Cipher.getInstance(TRANSFORM).apply { init(Cipher.ENCRYPT_MODE, key) }55+ }56+57+ /**58+ * Cipher to unwrap on unlock, initialised with the stored IV. Returns null when59+ * no escrow exists or the key was invalidated by a new biometric enrolment (the60+ * escrow is cleared in that case so the caller falls back to the password).61+ */62+ fun decryptCipher(context: Context): Cipher? {63+ val iv = loadIv(context) ?: return null64+ return try {65+ val key = existingKey() ?: return null66+ Cipher.getInstance(TRANSFORM).apply { init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(GCM_TAG_BITS, iv)) }67+ } catch (_: KeyPermanentlyInvalidatedException) {68+ clear(context)69+ null70+ } catch (_: Exception) {71+ null72+ }73+ }74+75+ /** Wrap [vaultKey] with the authenticated [cipher] and persist it. */76+ fun wrapAndStore(context: Context, cipher: Cipher, vaultKey: ByteArray) {77+ val wrapped = cipher.doFinal(vaultKey)78+ prefs(context).edit()79+ .putString(K_WRAPPED, b64(wrapped))80+ .putString(K_IV, b64(cipher.iv))81+ .apply()82+ }83+84+ /** Unwrap the stored vault key with the authenticated [cipher]. */85+ fun unwrap(context: Context, cipher: Cipher): ByteArray? {86+ val wrapped = prefs(context).getString(K_WRAPPED, null)?.let(::unb64) ?: return null87+ return runCatching { cipher.doFinal(wrapped) }.getOrNull()88+ }89+90+ private fun loadIv(context: Context): ByteArray? =91+ prefs(context).getString(K_IV, null)?.let(::unb64)92+93+ private fun existingKey(): SecretKey? {94+ val ks = KeyStore.getInstance(KEYSTORE).apply { load(null) }95+ return (ks.getEntry(KEY_ALIAS, null) as? KeyStore.SecretKeyEntry)?.secretKey96+ }97+98+ private fun getOrCreateKey(): SecretKey {99+ existingKey()?.let { return it }100+ val builder = KeyGenParameterSpec.Builder(101+ KEY_ALIAS,102+ KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,103+ )104+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)105+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)106+ .setKeySize(256)107+ .setUserAuthenticationRequired(true)108+ .setInvalidatedByBiometricEnrollment(true)109+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {110+ builder.setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG)111+ }112+ val gen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE)113+ gen.init(builder.build())114+ return gen.generateKey()115+ }116+117+ private fun b64(b: ByteArray) = Base64.getEncoder().encodeToString(b)118+ private fun unb64(s: String) = Base64.getDecoder().decode(s)119+}app/src/main/java/com/peachpasswords/ui/lock/Biometrics.kt+35 −0
@@ -15,6 +15,10 @@1515 fun isAvailable(context: Context): Boolean =1616 BiometricManager.from(context).canAuthenticate(AUTHENTICATORS) == BiometricManager.BIOMETRIC_SUCCESS1717 18+ /** Strong (Class-3) biometrics specifically — required for CryptoObject key gating. */19+ fun strongAvailable(context: Context): Boolean =20+ BiometricManager.from(context).canAuthenticate(BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS21+1822 /** A user-facing reason biometrics can't be used right now, or null when available. */1923 fun statusMessage(context: Context): String? =2024 when (BiometricManager.from(context).canAuthenticate(BIOMETRIC_STRONG)) {@@ -47,5 +51,36 @@4751 .setAllowedAuthenticators(AUTHENTICATORS)4852 .build()4953 prompt.authenticate(info)54+ }55+56+ /**57+ * Authenticate with a [BiometricPrompt.CryptoObject] (key-gated). Uses58+ * BIOMETRIC_STRONG only — device credential is not permitted alongside a59+ * CryptoObject. [onSuccess] receives the authenticated result so the caller60+ * can use `result.cryptoObject?.cipher`.61+ */62+ fun authenticateCrypto(63+ activity: FragmentActivity,64+ title: String,65+ subtitle: String,66+ crypto: BiometricPrompt.CryptoObject,67+ onSuccess: (BiometricPrompt.AuthenticationResult) -> Unit,68+ onFail: () -> Unit = {},69+ ) {70+ val prompt = BiometricPrompt(71+ activity,72+ ContextCompat.getMainExecutor(activity),73+ object : BiometricPrompt.AuthenticationCallback() {74+ override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) = onSuccess(result)75+ override fun onAuthenticationError(errorCode: Int, errString: CharSequence) = onFail()76+ },77+ )78+ val info = BiometricPrompt.PromptInfo.Builder()79+ .setTitle(title)80+ .setSubtitle(subtitle)81+ .setNegativeButtonText("Use password")82+ .setAllowedAuthenticators(BIOMETRIC_STRONG)83+ .build()84+ prompt.authenticate(info, crypto)5085 }5186 }app/src/main/java/com/peachpasswords/ui/lock/LockScreen.kt+27 −0
@@ -49,6 +49,8 @@4949 import androidx.compose.ui.unit.sp5050 import androidx.hilt.navigation.compose.hiltViewModel5151 import androidx.compose.runtime.collectAsState52+import androidx.compose.ui.platform.LocalContext53+import androidx.fragment.app.FragmentActivity5254 import com.peachpasswords.ui.PeachNav5355 import com.peachpasswords.ui.components.LockRuneString5456 import com.peachpasswords.ui.components.PeachMark@@ -65,6 +67,9 @@6567 ) {6668 val state by vm.state.collectAsState()6769 val accent = LocalPeachAccent.current70+ val context = LocalContext.current71+ val activity = context as? FragmentActivity72+ val canBiometric = remember(state.hasVault) { vm.canTryBiometric() }6873 6974 var password by remember { mutableStateOf("") }7075 var confirm by remember { mutableStateOf("") }@@ -76,6 +81,14 @@7681 }7782 }7883 84+ // Auto-offer biometric unlock shortly after the lock screen appears.85+ LaunchedEffect(canBiometric) {86+ if (canBiometric && activity != null && !state.unlocked) {87+ kotlinx.coroutines.delay(300)88+ vm.biometricUnlock(activity)89+ }90+ }91+7992 // Shake the panel on each failed unlock (brief Phase 4: 0→−12→10→−8→6→0 over ~400ms).8093 val shake = remember { Animatable(0f) }8194 LaunchedEffect(state.shakeNonce) {@@ -169,6 +182,20 @@169182 enabled = !state.loading,170183 onClick = { if (state.hasVault) vm.unlock(password) else vm.create(password, confirm) },171184 )185+186+ if (state.hasVault && canBiometric && activity != null) {187+ Spacer(Modifier.height(12.dp))188+ Text(189+ text = "Use biometrics",190+ color = accent,191+ style = PeachType.labelMono.copy(letterSpacing = 0.08.em),192+ textAlign = TextAlign.Center,193+ modifier = Modifier.fillMaxWidth()194+ .clip(RoundedCornerShape(8.dp))195+ .clickable { vm.biometricUnlock(activity) }196+ .padding(vertical = 8.dp),197+ )198+ }172199 }173200 174201 if (!state.hasVault) {app/src/main/java/com/peachpasswords/ui/lock/LockViewModel.kt+43 −2
@@ -1,11 +1,16 @@11 package com.peachpasswords.ui.lock22 3+import android.content.Context4+import androidx.biometric.BiometricPrompt5+import androidx.fragment.app.FragmentActivity36 import androidx.lifecycle.ViewModel47 import androidx.lifecycle.viewModelScope58 import com.peachpasswords.vault.CreateVaultResult69 import com.peachpasswords.vault.UnlockResult10+import com.peachpasswords.vault.VaultCrypto711 import com.peachpasswords.vault.VaultRepository812 import dagger.hilt.android.lifecycle.HiltViewModel13+import dagger.hilt.android.qualifiers.ApplicationContext914 import kotlinx.coroutines.flow.MutableStateFlow1015 import kotlinx.coroutines.flow.StateFlow1116 import kotlinx.coroutines.flow.asStateFlow@@ -29,6 +34,7 @@2934 @HiltViewModel3035 class LockViewModel @Inject constructor(3136 private val vault: VaultRepository,37+ @ApplicationContext private val appContext: Context,3238 ) : ViewModel() {3339 private val _state = MutableStateFlow(LockUiState(hasVault = vault.hasVault()))3440 val state: StateFlow<LockUiState> = _state.asStateFlow()@@ -68,6 +74,41 @@6874 6975 fun clearError() = _state.update { it.copy(error = null) }7076 71- /** Dormant until biometric enrollment lands with Protection settings. */72- fun canTryBiometric(): Boolean = false77+ /**78+ * True when an existing vault can be unlocked by biometrics: strong biometrics79+ * available AND a key was escrowed on enable. (A wrapped key existing implies80+ * the user enabled biometrics — no need to also read the locked settings blob.)81+ */82+ fun canTryBiometric(): Boolean =83+ vault.hasVault() &&84+ Biometrics.strongAvailable(appContext) &&85+ BiometricKeyStore.hasWrappedKey(appContext)86+87+ /**88+ * Run the biometric unlock: prompt with the DECRYPT cipher, unwrap the escrowed89+ * vault key, and unlock with it. Failure/cancel is silent so the password input90+ * remains usable.91+ */92+ fun biometricUnlock(activity: FragmentActivity) {93+ if (_state.value.loading) return94+ val cipher = BiometricKeyStore.decryptCipher(appContext) ?: return95+ Biometrics.authenticateCrypto(96+ activity = activity,97+ title = "Unlock Peach",98+ subtitle = "Use your biometric to unlock your vault",99+ crypto = BiometricPrompt.CryptoObject(cipher),100+ onSuccess = { result ->101+ val used = result.cryptoObject?.cipher ?: return@authenticateCrypto102+ val key = BiometricKeyStore.unwrap(appContext, used) ?: return@authenticateCrypto103+ viewModelScope.launch {104+ val r = vault.unlockWithKey(key)105+ VaultCrypto.zero(key)106+ when (r) {107+ is UnlockResult.Success -> _state.update { it.copy(unlocked = true) }108+ else -> _state.update { it.copy(error = "biometric unlock failed", shakeNonce = it.shakeNonce + 1) }109+ }110+ }111+ },112+ )113+ }73114 }app/src/main/java/com/peachpasswords/ui/settings/SettingsCardBodies.kt+4 −1
@@ -239,9 +239,12 @@239239 }240240 }241241 SubLabel("BIOMETRICS", fg)242+ val bioActivity = LocalContext.current as? androidx.fragment.app.FragmentActivity242243 RowLine(fg) {243244 Name("Unlock with biometrics", fg)244- Toggle(s.biometricsEnabled, fg) { vm.setBiometrics(it) }245+ Toggle(s.biometricsEnabled, fg) { on ->246+ if (on && bioActivity != null) vm.enableBiometrics(bioActivity) else vm.disableBiometrics()247+ }245248 }246249 val bioError = com.peachpasswords.ui.lock.Biometrics.statusMessage(LocalContext.current)247250 if (bioError != null) {app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt+44 −0
@@ -1,11 +1,18 @@11 package com.peachpasswords.ui.settings22 3+import android.content.Context4+import androidx.biometric.BiometricPrompt5+import androidx.fragment.app.FragmentActivity36 import androidx.lifecycle.ViewModel47 import androidx.lifecycle.viewModelScope58 import com.peachpasswords.license.LicenseRepository9+import com.peachpasswords.ui.lock.BiometricKeyStore10+import com.peachpasswords.ui.lock.Biometrics11+import com.peachpasswords.vault.VaultCrypto612 import com.peachpasswords.vault.VaultRepository713 import com.peachpasswords.vault.VaultSettings814 import dagger.hilt.android.lifecycle.HiltViewModel15+import dagger.hilt.android.qualifiers.ApplicationContext916 import kotlinx.coroutines.flow.MutableStateFlow1017 import kotlinx.coroutines.flow.StateFlow1118 import kotlinx.coroutines.flow.asStateFlow@@ -16,6 +23,7 @@1623 class SettingsViewModel @Inject constructor(1724 private val vault: VaultRepository,1825 private val license: LicenseRepository,26+ @ApplicationContext private val appContext: Context,1927 ) : ViewModel() {2028 val entries: StateFlow<List<com.peachpasswords.vault.VaultEntry>> = vault.entries2129 val settings: StateFlow<VaultSettings> = vault.settings@@ -78,6 +86,42 @@7886 fun setReduceMotion(on: Boolean) = mutate { it.copy(reduceMotion = on) }7987 fun setBreachMonitoring(on: Boolean) = mutate { it.copy(breachMonitoring = on) }8088 fun setBiometrics(on: Boolean) = mutate { it.copy(biometricsEnabled = on) }89+90+ /**91+ * Enable biometric unlock: prompt to wrap the live vault key under a hardware92+ * KeyStore key and persist the escrow, then flip the setting on. Requires the93+ * vault to be unlocked (it is, inside Settings). A failed/cancelled prompt94+ * leaves biometrics off.95+ */96+ fun enableBiometrics(activity: FragmentActivity) {97+ val key = vault.currentVaultKey() ?: return98+ val cipher = try {99+ BiometricKeyStore.encryptCipher()100+ } catch (_: Exception) {101+ VaultCrypto.zero(key); return102+ }103+ Biometrics.authenticateCrypto(104+ activity = activity,105+ title = "Enable biometric unlock",106+ subtitle = "Confirm to secure your vault key",107+ crypto = BiometricPrompt.CryptoObject(cipher),108+ onSuccess = { result ->109+ val used = result.cryptoObject?.cipher110+ if (used != null) {111+ runCatching { BiometricKeyStore.wrapAndStore(appContext, used, key) }112+ .onSuccess { mutate { it.copy(biometricsEnabled = true) } }113+ }114+ VaultCrypto.zero(key)115+ },116+ onFail = { VaultCrypto.zero(key) },117+ )118+ }119+120+ /** Disable biometric unlock: drop the escrowed key + KeyStore entry, flip the setting off. */121+ fun disableBiometrics() {122+ BiometricKeyStore.clear(appContext)123+ mutate { it.copy(biometricsEnabled = false) }124+ }81125 fun setAutoLockMinutes(min: Int?) = mutate { it.copy(autoLockMinutes = min) }82126 fun setTrashRetentionDays(days: Int?) = mutate { it.copy(trashRetentionDays = days) }83127 app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+7 −0
@@ -200,6 +200,13 @@200200 /** Stable per-vault id two paired devices must share to sync. Null when locked. */201201 fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }202202 203+ /**204+ * A copy of the live Argon2id-derived vault key, for biometric escrow only205+ * (wrapped under a hardware KeyStore key on biometric enable). Null when206+ * locked. Caller must [VaultCrypto.zero] it after use.207+ */208+ fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()209+203210 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {204211 val slotA = store.loadSlotA() ?: return false205212 return try {