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 35 val created: Boolean = false,36 37 val shakeNonce: Int = 0,38 39 val duressDestroyed: Boolean = false,40)4142const val MIN_PASSWORD_LENGTH = 12434445const 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 62 63 64 65 66 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 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 91929394 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 132133134135136 fun canTryBiometric(): Boolean =137 vault.hasVault() &&138 Biometrics.strongAvailable(appContext) &&139 BiometricKeyStore.hasWrappedKey(appContext)140141 142143144145146 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}