LockViewModel.kt

4.8 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.vault.UnlockResult10import com.peachpasswords.vault.VaultCrypto11import com.peachpasswords.vault.VaultRepository12import dagger.hilt.android.lifecycle.HiltViewModel13import dagger.hilt.android.qualifiers.ApplicationContext14import kotlinx.coroutines.flow.MutableStateFlow15import kotlinx.coroutines.flow.StateFlow16import kotlinx.coroutines.flow.asStateFlow17import kotlinx.coroutines.flow.update18import kotlinx.coroutines.launch19import javax.inject.Inject2021data class LockUiState(22    val hasVault: Boolean = false,23    val loading: Boolean = false,24    val error: String? = null,25    val unlocked: Boolean = false,26    /** True when this session just created a new vault (routes through recovery-word setup). */27    val created: Boolean = false,28    /** Increments on each failed unlock so the screen can fire its shake animation. */29    val shakeNonce: Int = 0,30)3132const val MIN_PASSWORD_LENGTH = 123334@HiltViewModel35class LockViewModel @Inject constructor(36    private val vault: VaultRepository,37    @ApplicationContext private val appContext: Context,38) : ViewModel() {39    private val _state = MutableStateFlow(LockUiState(hasVault = vault.hasVault()))40    val state: StateFlow<LockUiState> = _state.asStateFlow()4142    fun unlock(password: String) {43        if (password.isBlank() || _state.value.loading) return44        _state.update { it.copy(loading = true, error = null) }45        viewModelScope.launch {46            when (val r = vault.unlock(password)) {47                is UnlockResult.Success -> _state.update { it.copy(loading = false, unlocked = true) }48                is UnlockResult.WrongPassword -> _state.update {49                    it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)50                }51                is UnlockResult.Error -> _state.update {52                    it.copy(loading = false, error = r.reason, shakeNonce = it.shakeNonce + 1)53                }54            }55        }56    }5758    fun create(password: String, confirm: String) {59        if (_state.value.loading) return60        when {61            password.length < MIN_PASSWORD_LENGTH ->62                return _state.update { it.copy(error = "password must be at least $MIN_PASSWORD_LENGTH characters") }63            password != confirm ->64                return _state.update { it.copy(error = "passwords do not match") }65        }66        _state.update { it.copy(loading = true, error = null) }67        viewModelScope.launch {68            when (val r = vault.createVault(password)) {69                is CreateVaultResult.Success -> _state.update { it.copy(loading = false, unlocked = true, created = true) }70                is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) }71            }72        }73    }7475    fun clearError() = _state.update { it.copy(error = null) }7677    /**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)8687    /**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    }114}