LockViewModel.kt

7.6 KB · raw

1package com.peachpasswords.ui.lock23import android.content.Context4import androidx.biometric.BiometricPrompt5import androidx.fragment.app.FragmentActivity6import androidx.lifecycle.ViewModel7import androidx.lifecycle.viewModelScope8import com.peachpasswords.vault.CreateVaultResult9import com.peachpasswords.ui.security.scorePassword10import com.peachpasswords.vault.DuressAction11import com.peachpasswords.vault.DuressConfigStore12import com.peachpasswords.vault.UnlockResult13import com.peachpasswords.vault.VaultCrypto14import com.peachpasswords.vault.VaultLockTimer15import com.peachpasswords.vault.VaultRepository16import dagger.hilt.android.lifecycle.HiltViewModel17import dagger.hilt.android.qualifiers.ApplicationContext18import kotlinx.coroutines.Dispatchers19import kotlinx.coroutines.async20import kotlinx.coroutines.flow.MutableStateFlow21import kotlinx.coroutines.flow.StateFlow22import kotlinx.coroutines.flow.asStateFlow23import kotlinx.coroutines.flow.update24import kotlinx.coroutines.launch25import kotlinx.coroutines.withContext26import javax.inject.Inject2728data class LockUiState(29    val hasVault: Boolean = false,30    val loading: Boolean = false,31    val error: String? = null,32    val unlocked: Boolean = false,33    /** True when this session just created a new vault (routes through recovery-word setup). */34    val created: Boolean = false,35    /** Increments on each failed unlock so the screen can fire its shake animation. */36    val shakeNonce: Int = 0,37    /** Real vault was wiped by a destroy-duress unlock → screen drops to CreateVault. */38    val duressDestroyed: Boolean = false,39)4041const val MIN_PASSWORD_LENGTH = 124243/** CreateVault is blocked below "fair" (zxcvbn-style score 2). */44const val MIN_CREATE_STRENGTH = 24546@HiltViewModel47class LockViewModel @Inject constructor(48    private val vault: VaultRepository,49    private val duress: DuressConfigStore,50    private val lockTimer: VaultLockTimer,51    @ApplicationContext private val appContext: Context,52) : ViewModel() {53    private val _state = MutableStateFlow(LockUiState(hasVault = vault.hasVault()))54    val state: StateFlow<LockUiState> = _state.asStateFlow()5556    fun unlock(password: String) {57        if (password.isBlank() || _state.value.loading) return58        _state.update { it.copy(loading = true, error = null) }59        viewModelScope.launch {60            // Derive slot A and the duress slot (slot B) CONCURRENTLY so the wall-clock61            // time to reject/accept never reveals whether the entered password was the62            // real password, the duress passphrase, or simply wrong (MF-5/MF-6, mirrors63            // browser DUR-002). Both Argon2id derivations run to completion; the branch64            // happens only after both finish. Each derivation is non-committing (no65            // mutex, no session mutation) so the loser is simply discarded.66            val (duressUnlock, slotA) = withContext(Dispatchers.Default) {67                val duressDeferred = async { if (duress.isConfigured()) vault.tryUnlockDuress(password) else null }68                val slotADeferred = async { vault.tryUnlockSlotA(password) }69                duressDeferred.await() to slotADeferred.await()70            }71            when {72                // Duress takes precedence: the duress passphrase never reaches the real vault.73                duressUnlock != null -> {74                    slotA?.let(vault::discardSlotAUnlock)75                    handleDuress(duressUnlock)76                }77                slotA != null -> {78                    vault.commitSlotAUnlock(slotA)79                    lockTimer.start()80                    _state.update { it.copy(loading = false, unlocked = true) }81                }82                else -> _state.update {83                    it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)84                }85            }86        }87    }8889    /**90     * Carry out the configured duress action against an already-derived slot-B unlock.91     * Both paths look like an ordinary successful (decoy) or fresh-install (destroy)92     * unlock to a coercer — no error, no hint that a duress passphrase was used.93     */94    private suspend fun handleDuress(duressUnlock: VaultRepository.DuressUnlock) {95        when (duress.action()) {96            DuressAction.DECOY -> when (vault.commitDuressUnlock(duressUnlock)) {97                is UnlockResult.Success -> { lockTimer.start(); _state.update { it.copy(loading = false, unlocked = true) } }98                else -> _state.update {99                    it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)100                }101            }102            DuressAction.DESTROY -> {103                vault.discardDuressUnlock(duressUnlock)104                vault.destroyVault()105                duress.clear()106                _state.update { it.copy(loading = false, hasVault = false, duressDestroyed = true) }107            }108        }109    }110111    fun create(password: String, confirm: String) {112        if (_state.value.loading) return113        when {114            password.length < MIN_PASSWORD_LENGTH ->115                return _state.update { it.copy(error = "password must be at least $MIN_PASSWORD_LENGTH characters") }116            scorePassword(password) < MIN_CREATE_STRENGTH ->117                return _state.update { it.copy(error = "Password too weak — try a longer or more varied password") }118            password != confirm ->119                return _state.update { it.copy(error = "passwords do not match") }120        }121        _state.update { it.copy(loading = true, error = null) }122        viewModelScope.launch {123            when (val r = vault.createVault(password)) {124                is CreateVaultResult.Success -> { lockTimer.start(); _state.update { it.copy(loading = false, unlocked = true, created = true) } }125                is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) }126            }127        }128    }129130    fun clearError() = _state.update { it.copy(error = null) }131132    /**133     * True when an existing vault can be unlocked by biometrics: strong biometrics134     * available AND a key was escrowed on enable. (A wrapped key existing implies135     * the user enabled biometrics — no need to also read the locked settings blob.)136     */137    fun canTryBiometric(): Boolean =138        vault.hasVault() &&139            Biometrics.strongAvailable(appContext) &&140            BiometricKeyStore.hasWrappedKey(appContext)141142    /**143     * Run the biometric unlock: prompt with the DECRYPT cipher, unwrap the escrowed144     * vault key, and unlock with it. Failure/cancel is silent so the password input145     * remains usable.146     */147    fun biometricUnlock(activity: FragmentActivity) {148        if (_state.value.loading) return149        val cipher = BiometricKeyStore.decryptCipher(appContext) ?: return150        Biometrics.authenticateCrypto(151            activity = activity,152            title = "Unlock Peach",153            subtitle = "Use your biometric to unlock your vault",154            crypto = BiometricPrompt.CryptoObject(cipher),155            onSuccess = { result ->156                val used = result.cryptoObject?.cipher ?: return@authenticateCrypto157                val key = BiometricKeyStore.unwrap(appContext, used) ?: return@authenticateCrypto158                viewModelScope.launch {159                    val r = vault.unlockWithKey(key)160                    VaultCrypto.zero(key)161                    when (r) {162                        is UnlockResult.Success -> { lockTimer.start(); _state.update { it.copy(unlocked = true) } }163                        else -> _state.update { it.copy(error = "biometric unlock failed", shakeNonce = it.shakeNonce + 1) }164                    }165                }166            },167        )168    }169}