LockViewModel.kt

7.5 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.DuressMatch13import com.peachpasswords.vault.UnlockResult14import com.peachpasswords.vault.VaultCrypto15import com.peachpasswords.vault.VaultLockTimer16import com.peachpasswords.vault.VaultRepository17import dagger.hilt.android.lifecycle.HiltViewModel18import dagger.hilt.android.qualifiers.ApplicationContext19import kotlinx.coroutines.Dispatchers20import kotlinx.coroutines.async21import kotlinx.coroutines.flow.MutableStateFlow22import kotlinx.coroutines.flow.StateFlow23import kotlinx.coroutines.flow.asStateFlow24import kotlinx.coroutines.flow.update25import kotlinx.coroutines.launch26import kotlinx.coroutines.withContext27import javax.inject.Inject2829data class LockUiState(30    val hasVault: Boolean = false,31    val loading: Boolean = false,32    val error: String? = null,33    val unlocked: Boolean = false,34    /** True when this session just created a new vault (routes through recovery-word setup). */35    val created: Boolean = false,36    /** Increments on each failed unlock so the screen can fire its shake animation. */37    val shakeNonce: Int = 0,38    /** Real vault was wiped by a destroy-duress unlock → screen drops to CreateVault. */39    val duressDestroyed: Boolean = false,40)4142const val MIN_PASSWORD_LENGTH = 124344/** CreateVault is blocked below "fair" (zxcvbn-style score 2). */45const val MIN_CREATE_STRENGTH = 24647@HiltViewModel48class LockViewModel @Inject constructor(49    private val vault: VaultRepository,50    private val duress: DuressConfigStore,51    private val lockTimer: VaultLockTimer,52    @ApplicationContext private val appContext: Context,53) : ViewModel() {54    private val _state = MutableStateFlow(LockUiState(hasVault = vault.hasVault()))55    val state: StateFlow<LockUiState> = _state.asStateFlow()5657    fun unlock(password: String) {58        if (password.isBlank() || _state.value.loading) return59        _state.update { it.copy(loading = true, error = null) }60        viewModelScope.launch {61            // Derive the duress hash and slot A CONCURRENTLY so the wall-clock time to62            // reject/accept does not reveal whether the entered password was the real63            // password, the duress password, or simply wrong (MF-5, mirrors browser64            // DUR-002). Both Argon2id derivations always run to completion; the branch65            // happens only after both finish. The slot-A derivation is non-committing66            // (no mutex, no session mutation) so it is safe to discard when duress wins.67            val (duressMatch, slotA) = withContext(Dispatchers.Default) {68                val duressDeferred = async { duress.verify(password) }69                val slotADeferred = async { vault.tryUnlockSlotA(password) }70                duressDeferred.await() to slotADeferred.await()71            }72            when {73                // Duress takes precedence: a matching duress password never reaches the real vault.74                duressMatch is DuressMatch.Match -> {75                    slotA?.let(vault::discardSlotAUnlock)76                    handleDuress(duressMatch.action)77                }78                slotA != null -> {79                    vault.commitSlotAUnlock(slotA)80                    lockTimer.start()81                    _state.update { it.copy(loading = false, unlocked = true) }82                }83                else -> _state.update {84                    it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)85                }86            }87        }88    }8990    /**91     * Carry out the configured duress action. Both paths look like an ordinary92     * successful (decoy) or fresh-install (destroy) unlock to a coercer — no error.93     */94    private suspend fun handleDuress(action: DuressAction) {95        when (action) {96            DuressAction.DECOY -> when (vault.unlockDecoy()) {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.destroyVault()104                duress.clear()105                _state.update { it.copy(loading = false, hasVault = false, duressDestroyed = true) }106            }107        }108    }109110    fun create(password: String, confirm: String) {111        if (_state.value.loading) return112        when {113            password.length < MIN_PASSWORD_LENGTH ->114                return _state.update { it.copy(error = "password must be at least $MIN_PASSWORD_LENGTH characters") }115            scorePassword(password) < MIN_CREATE_STRENGTH ->116                return _state.update { it.copy(error = "Password too weak — try a longer or more varied password") }117            password != confirm ->118                return _state.update { it.copy(error = "passwords do not match") }119        }120        _state.update { it.copy(loading = true, error = null) }121        viewModelScope.launch {122            when (val r = vault.createVault(password)) {123                is CreateVaultResult.Success -> { lockTimer.start(); _state.update { it.copy(loading = false, unlocked = true, created = true) } }124                is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) }125            }126        }127    }128129    fun clearError() = _state.update { it.copy(error = null) }130131    /**132     * True when an existing vault can be unlocked by biometrics: strong biometrics133     * available AND a key was escrowed on enable. (A wrapped key existing implies134     * the user enabled biometrics — no need to also read the locked settings blob.)135     */136    fun canTryBiometric(): Boolean =137        vault.hasVault() &&138            Biometrics.strongAvailable(appContext) &&139            BiometricKeyStore.hasWrappedKey(appContext)140141    /**142     * Run the biometric unlock: prompt with the DECRYPT cipher, unwrap the escrowed143     * vault key, and unlock with it. Failure/cancel is silent so the password input144     * remains usable.145     */146    fun biometricUnlock(activity: FragmentActivity) {147        if (_state.value.loading) return148        val cipher = BiometricKeyStore.decryptCipher(appContext) ?: return149        Biometrics.authenticateCrypto(150            activity = activity,151            title = "Unlock Peach",152            subtitle = "Use your biometric to unlock your vault",153            crypto = BiometricPrompt.CryptoObject(cipher),154            onSuccess = { result ->155                val used = result.cryptoObject?.cipher ?: return@authenticateCrypto156                val key = BiometricKeyStore.unwrap(appContext, used) ?: return@authenticateCrypto157                viewModelScope.launch {158                    val r = vault.unlockWithKey(key)159                    VaultCrypto.zero(key)160                    when (r) {161                        is UnlockResult.Success -> { lockTimer.start(); _state.update { it.copy(unlocked = true) } }162                        else -> _state.update { it.copy(error = "biometric unlock failed", shakeNonce = it.shakeNonce + 1) }163                    }164                }165            },166        )167    }168}