1package com.peachpasswords.ui.lock23import android.content.Context4import androidx.biometric.BiometricPrompt5import androidx.fragment.app.FragmentActivity6import androidx.lifecycle.ViewModel7import androidx.lifecycle.viewModelScope8import com.peachpasswords.ui.PeachNav9import com.peachpasswords.ui.vault.entryTapDestination10import com.peachpasswords.vault.CreateVaultResult11import com.peachpasswords.ui.security.scorePassword12import com.peachpasswords.vault.DuressAction13import com.peachpasswords.vault.DuressConfigStore14import com.peachpasswords.vault.LastViewedEntryStore15import com.peachpasswords.vault.UnlockResult16import com.peachpasswords.vault.VaultCrypto17import com.peachpasswords.vault.VaultEntry18import com.peachpasswords.vault.VaultLockTimer19import com.peachpasswords.vault.VaultRepository20import dagger.hilt.android.lifecycle.HiltViewModel21import dagger.hilt.android.qualifiers.ApplicationContext22import kotlinx.coroutines.Dispatchers23import kotlinx.coroutines.async24import kotlinx.coroutines.flow.MutableStateFlow25import kotlinx.coroutines.flow.StateFlow26import kotlinx.coroutines.flow.asStateFlow27import kotlinx.coroutines.flow.update28import kotlinx.coroutines.launch29import kotlinx.coroutines.withContext30import javax.inject.Inject3132data class LockUiState(33 val hasVault: Boolean = false,34 val loading: Boolean = false,35 val error: String? = null,36 val unlocked: Boolean = false,37 38 val created: Boolean = false,39 40 val shakeNonce: Int = 0,41 42 val duressDestroyed: Boolean = false,43)4445const val MIN_PASSWORD_LENGTH = 12464748const val MIN_CREATE_STRENGTH = 249505152535455internal fun createValidationError(password: String, confirm: String, score: Int): String? = when {56 password.length < MIN_PASSWORD_LENGTH -> "password must be at least $MIN_PASSWORD_LENGTH characters"57 score < MIN_CREATE_STRENGTH -> "Password too weak — try a longer or more varied password"58 password != confirm -> "passwords do not match"59 else -> null60}616263646566676869internal fun postUnlockDestination(70 lastViewedId: String?,71 resolve: (String) -> VaultEntry?,72 firstActive: VaultEntry?,73): PeachNav {74 val target = lastViewedId?.let(resolve) ?: firstActive ?: return PeachNav.VaultList75 return entryTapDestination(target)76}7778@HiltViewModel79class LockViewModel @Inject constructor(80 private val vault: VaultRepository,81 private val duress: DuressConfigStore,82 private val lockTimer: VaultLockTimer,83 private val lastViewed: LastViewedEntryStore,84 @ApplicationContext private val appContext: Context,85) : ViewModel() {86 private val _state = MutableStateFlow(LockUiState(hasVault = vault.hasVault()))87 val state: StateFlow<LockUiState> = _state.asStateFlow()8889 90 fun postUnlockDestination(): PeachNav =91 postUnlockDestination(lastViewed.get(), vault::getEntry, vault.getActiveEntries().firstOrNull())9293 fun unlock(password: String) {94 if (password.isBlank() || _state.value.loading) return95 _state.update { it.copy(loading = true, error = null) }96 viewModelScope.launch {97 98 99 100 101 102 103 val (duressUnlock, slotA) = withContext(Dispatchers.Default) {104 val duressDeferred = async { if (duress.isConfigured()) vault.tryUnlockDuress(password) else null }105 val slotADeferred = async { vault.tryUnlockSlotA(password) }106 duressDeferred.await() to slotADeferred.await()107 }108 when {109 110 duressUnlock != null -> {111 slotA?.let(vault::discardSlotAUnlock)112 handleDuress(duressUnlock)113 }114 slotA != null -> {115 vault.commitSlotAUnlock(slotA)116 lockTimer.start()117 _state.update { it.copy(loading = false, unlocked = true) }118 }119 else -> _state.update {120 it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)121 }122 }123 }124 }125126 127128129130131 private suspend fun handleDuress(duressUnlock: VaultRepository.DuressUnlock) {132 when (duress.action()) {133 DuressAction.DECOY -> when (vault.commitDuressUnlock(duressUnlock)) {134 is UnlockResult.Success -> { lockTimer.start(); _state.update { it.copy(loading = false, unlocked = true) } }135 else -> _state.update {136 it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)137 }138 }139 DuressAction.DESTROY -> {140 vault.discardDuressUnlock(duressUnlock)141 vault.destroyVault()142 duress.clear()143 _state.update { it.copy(loading = false, hasVault = false, duressDestroyed = true) }144 }145 }146 }147148 fun create(password: String, confirm: String) {149 if (_state.value.loading) return150 createValidationError(password, confirm, scorePassword(password))?.let { msg ->151 return _state.update { it.copy(error = msg) }152 }153 _state.update { it.copy(loading = true, error = null) }154 viewModelScope.launch {155 when (val r = vault.createVault(password)) {156 is CreateVaultResult.Success -> { lockTimer.start(); _state.update { it.copy(loading = false, unlocked = true, created = true) } }157 is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) }158 }159 }160 }161162 fun clearError() = _state.update { it.copy(error = null) }163164 165166167168169 fun canTryBiometric(): Boolean =170 vault.hasVault() &&171 Biometrics.strongAvailable(appContext) &&172 BiometricKeyStore.hasWrappedKey(appContext)173174 175176177178179 fun biometricUnlock(activity: FragmentActivity) {180 if (_state.value.loading) return181 val cipher = BiometricKeyStore.decryptCipher(appContext) ?: return182 Biometrics.authenticateCrypto(183 activity = activity,184 title = "Unlock Peach",185 subtitle = "Use your biometric to unlock your vault",186 crypto = BiometricPrompt.CryptoObject(cipher),187 onSuccess = { result ->188 val used = result.cryptoObject?.cipher ?: return@authenticateCrypto189 val key = BiometricKeyStore.unwrap(appContext, used) ?: return@authenticateCrypto190 viewModelScope.launch {191 val r = vault.unlockWithKey(key)192 VaultCrypto.zero(key)193 when (r) {194 is UnlockResult.Success -> { lockTimer.start(); _state.update { it.copy(unlocked = true) } }195 else -> _state.update { it.copy(error = "biometric unlock failed", shakeNonce = it.shakeNonce + 1) }196 }197 }198 },199 )200 }201}