1package com.peachpasswords.ui.lock23import android.content.Context4import androidx.biometric.BiometricPrompt5import androidx.fragment.app.FragmentActivity6import androidx.lifecycle.ViewModel7import androidx.lifecycle.viewModelScope8import com.peachpasswords.sync.ForegroundSyncCoordinator9import com.peachpasswords.sync.SyncFreshStartResetter10import com.peachpasswords.ui.PeachNav11import com.peachpasswords.ui.vault.entryTapDestination12import com.peachpasswords.vault.CreateVaultResult13import com.peachpasswords.ui.security.scorePassword14import com.peachpasswords.vault.DuressAction15import com.peachpasswords.vault.DuressConfigStore16import com.peachpasswords.vault.LastViewedEntryStore17import com.peachpasswords.vault.UnlockResult18import com.peachpasswords.vault.VaultCrypto19import com.peachpasswords.vault.VaultEntry20import com.peachpasswords.vault.VaultLockTimer21import com.peachpasswords.vault.VaultRepository22import dagger.hilt.android.lifecycle.HiltViewModel23import dagger.hilt.android.qualifiers.ApplicationContext24import kotlinx.coroutines.Dispatchers25import kotlinx.coroutines.async26import kotlinx.coroutines.flow.MutableStateFlow27import kotlinx.coroutines.flow.StateFlow28import kotlinx.coroutines.flow.asStateFlow29import kotlinx.coroutines.flow.update30import kotlinx.coroutines.launch31import kotlinx.coroutines.withContext32import javax.inject.Inject3334data class LockUiState(35 val hasVault: Boolean = false,36 val loading: Boolean = false,37 val error: String? = null,38 val unlocked: Boolean = false,39 40 val created: Boolean = false,41 42 val shakeNonce: Int = 0,43 44 val duressDestroyed: Boolean = false,45)4647const val MIN_PASSWORD_LENGTH = 12484950const val MIN_CREATE_STRENGTH = 251525354555657internal fun createValidationError(password: String, confirm: String, score: Int): String? = when {58 password.length < MIN_PASSWORD_LENGTH -> "password must be at least $MIN_PASSWORD_LENGTH characters"59 score < MIN_CREATE_STRENGTH -> "Password too weak — try a longer or more varied password"60 password != confirm -> "passwords do not match"61 else -> null62}636465internal fun canSubmitCreateVault(password: String, confirm: String, score: Int): Boolean =66 createValidationError(password, confirm, score) == null676869707172737475internal fun postUnlockDestination(76 lastViewedId: String?,77 resolve: (String) -> VaultEntry?,78 firstActive: VaultEntry?,79): PeachNav {80 val target = lastViewedId?.let(resolve) ?: firstActive ?: return PeachNav.VaultList81 return entryTapDestination(target)82}8384@HiltViewModel85class LockViewModel @Inject constructor(86 private val vault: VaultRepository,87 private val duress: DuressConfigStore,88 private val lockTimer: VaultLockTimer,89 private val lastViewed: LastViewedEntryStore,90 private val foregroundSync: ForegroundSyncCoordinator,91 private val syncFreshStart: SyncFreshStartResetter,92 @ApplicationContext private val appContext: Context,93) : ViewModel() {94 private val _state = MutableStateFlow(LockUiState(hasVault = vault.hasVault()))95 val state: StateFlow<LockUiState> = _state.asStateFlow()9697 98 fun postUnlockDestination(): PeachNav =99 postUnlockDestination(lastViewed.get(), vault::getEntry, vault.getActiveEntries().firstOrNull())100101 fun unlock(password: String) {102 if (password.isBlank() || _state.value.loading) return103 _state.update { it.copy(loading = true, error = null) }104 viewModelScope.launch {105 106 107 108 109 110 111 val (duressUnlock, slotA) = withContext(Dispatchers.Default) {112 val duressDeferred = async { if (duress.isConfigured()) vault.tryUnlockDuress(password) else null }113 val slotADeferred = async { vault.tryUnlockSlotA(password) }114 duressDeferred.await() to slotADeferred.await()115 }116 when {117 118 duressUnlock != null -> {119 slotA?.let(vault::discardSlotAUnlock)120 handleDuress(duressUnlock)121 }122 slotA != null -> {123 vault.commitSlotAUnlock(slotA)124 lockTimer.start()125 foregroundSync.triggerForegroundSync()126 _state.update { it.copy(loading = false, unlocked = true) }127 }128 else -> _state.update {129 it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)130 }131 }132 }133 }134135 136137138139140 private suspend fun handleDuress(duressUnlock: VaultRepository.DuressUnlock) {141 when (duress.action()) {142 DuressAction.DECOY -> when (vault.commitDuressUnlock(duressUnlock)) {143 is UnlockResult.Success -> { lockTimer.start(); _state.update { it.copy(loading = false, unlocked = true) } }144 else -> _state.update {145 it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)146 }147 }148 DuressAction.DESTROY -> {149 vault.discardDuressUnlock(duressUnlock)150 vault.destroyVault()151 syncFreshStart.reset()152 duress.clear()153 _state.update { it.copy(loading = false, hasVault = false, duressDestroyed = true) }154 }155 }156 }157158 fun create(password: String, confirm: String) {159 if (_state.value.loading) return160 createValidationError(password, confirm, scorePassword(password))?.let { msg ->161 return _state.update { it.copy(error = msg) }162 }163 _state.update { it.copy(loading = true, error = null) }164 viewModelScope.launch {165 when (val r = vault.createVault(password)) {166 is CreateVaultResult.Success -> { lockTimer.start(); _state.update { it.copy(loading = false, unlocked = true, created = true) } }167 is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) }168 }169 }170 }171172 fun clearError() = _state.update { it.copy(error = null) }173174 175176177178179 fun canTryBiometric(): Boolean =180 vault.hasVault() &&181 Biometrics.strongAvailable(appContext) &&182 BiometricKeyStore.hasWrappedKey(appContext)183184 185186187188189 fun biometricUnlock(activity: FragmentActivity) {190 if (_state.value.loading) return191 val cipher = BiometricKeyStore.decryptCipher(appContext) ?: return192 Biometrics.authenticateCrypto(193 activity = activity,194 title = "Unlock Peach",195 subtitle = "Use your biometric to unlock your vault",196 crypto = BiometricPrompt.CryptoObject(cipher),197 onSuccess = { result ->198 val used = result.cryptoObject?.cipher ?: return@authenticateCrypto199 val key = BiometricKeyStore.unwrap(appContext, used) ?: return@authenticateCrypto200 viewModelScope.launch {201 val r = vault.unlockWithKey(key)202 VaultCrypto.zero(key)203 when (r) {204 is UnlockResult.Success -> {205 lockTimer.start()206 foregroundSync.triggerForegroundSync()207 _state.update { it.copy(unlocked = true) }208 }209 else -> _state.update { it.copy(error = "biometric unlock failed", shakeNonce = it.shakeNonce + 1) }210 }211 }212 },213 )214 }215}