LockViewModel.kt

5.1 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.UnlockResult11import com.peachpasswords.vault.VaultCrypto12import com.peachpasswords.vault.VaultRepository13import dagger.hilt.android.lifecycle.HiltViewModel14import dagger.hilt.android.qualifiers.ApplicationContext15import kotlinx.coroutines.flow.MutableStateFlow16import kotlinx.coroutines.flow.StateFlow17import kotlinx.coroutines.flow.asStateFlow18import kotlinx.coroutines.flow.update19import kotlinx.coroutines.launch20import javax.inject.Inject2122data class LockUiState(23    val hasVault: Boolean = false,24    val loading: Boolean = false,25    val error: String? = null,26    val unlocked: Boolean = false,27    /** True when this session just created a new vault (routes through recovery-word setup). */28    val created: Boolean = false,29    /** Increments on each failed unlock so the screen can fire its shake animation. */30    val shakeNonce: Int = 0,31)3233const val MIN_PASSWORD_LENGTH = 123435/** CreateVault is blocked below "fair" (zxcvbn-style score 2). */36const val MIN_CREATE_STRENGTH = 23738@HiltViewModel39class LockViewModel @Inject constructor(40    private val vault: VaultRepository,41    @ApplicationContext private val appContext: Context,42) : ViewModel() {43    private val _state = MutableStateFlow(LockUiState(hasVault = vault.hasVault()))44    val state: StateFlow<LockUiState> = _state.asStateFlow()4546    fun unlock(password: String) {47        if (password.isBlank() || _state.value.loading) return48        _state.update { it.copy(loading = true, error = null) }49        viewModelScope.launch {50            when (val r = vault.unlock(password)) {51                is UnlockResult.Success -> _state.update { it.copy(loading = false, unlocked = true) }52                is UnlockResult.WrongPassword -> _state.update {53                    it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)54                }55                is UnlockResult.Error -> _state.update {56                    it.copy(loading = false, error = r.reason, shakeNonce = it.shakeNonce + 1)57                }58            }59        }60    }6162    fun create(password: String, confirm: String) {63        if (_state.value.loading) return64        when {65            password.length < MIN_PASSWORD_LENGTH ->66                return _state.update { it.copy(error = "password must be at least $MIN_PASSWORD_LENGTH characters") }67            scorePassword(password) < MIN_CREATE_STRENGTH ->68                return _state.update { it.copy(error = "Password too weak — try a longer or more varied password") }69            password != confirm ->70                return _state.update { it.copy(error = "passwords do not match") }71        }72        _state.update { it.copy(loading = true, error = null) }73        viewModelScope.launch {74            when (val r = vault.createVault(password)) {75                is CreateVaultResult.Success -> _state.update { it.copy(loading = false, unlocked = true, created = true) }76                is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) }77            }78        }79    }8081    fun clearError() = _state.update { it.copy(error = null) }8283    /**84     * True when an existing vault can be unlocked by biometrics: strong biometrics85     * available AND a key was escrowed on enable. (A wrapped key existing implies86     * the user enabled biometrics — no need to also read the locked settings blob.)87     */88    fun canTryBiometric(): Boolean =89        vault.hasVault() &&90            Biometrics.strongAvailable(appContext) &&91            BiometricKeyStore.hasWrappedKey(appContext)9293    /**94     * Run the biometric unlock: prompt with the DECRYPT cipher, unwrap the escrowed95     * vault key, and unlock with it. Failure/cancel is silent so the password input96     * remains usable.97     */98    fun biometricUnlock(activity: FragmentActivity) {99        if (_state.value.loading) return100        val cipher = BiometricKeyStore.decryptCipher(appContext) ?: return101        Biometrics.authenticateCrypto(102            activity = activity,103            title = "Unlock Peach",104            subtitle = "Use your biometric to unlock your vault",105            crypto = BiometricPrompt.CryptoObject(cipher),106            onSuccess = { result ->107                val used = result.cryptoObject?.cipher ?: return@authenticateCrypto108                val key = BiometricKeyStore.unwrap(appContext, used) ?: return@authenticateCrypto109                viewModelScope.launch {110                    val r = vault.unlockWithKey(key)111                    VaultCrypto.zero(key)112                    when (r) {113                        is UnlockResult.Success -> _state.update { it.copy(unlocked = true) }114                        else -> _state.update { it.copy(error = "biometric unlock failed", shakeNonce = it.shakeNonce + 1) }115                    }116                }117            },118        )119    }120}