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 102103104105106107108109110 private class UnlockCandidates(private val vault: VaultRepository) : AutoCloseable {111 private val lock = Any()112 private var closed = false113 private var slotA: VaultRepository.SlotAUnlock? = null114 private var duress: VaultRepository.DuressUnlock? = null115116 fun registerSlotA(candidate: VaultRepository.SlotAUnlock) {117 val discard = synchronized(lock) {118 if (closed) true else {119 slotA?.let(vault::discardSlotAUnlock)120 slotA = candidate121 false122 }123 }124 if (discard) vault.discardSlotAUnlock(candidate)125 }126127 fun registerDuress(candidate: VaultRepository.DuressUnlock) {128 val discard = synchronized(lock) {129 if (closed) true else {130 duress?.let(vault::discardDuressUnlock)131 duress = candidate132 false133 }134 }135 if (discard) vault.discardDuressUnlock(candidate)136 }137138 fun takeSlotA(): VaultRepository.SlotAUnlock? = synchronized(lock) {139 slotA.also { slotA = null }140 }141142 fun takeDuress(): VaultRepository.DuressUnlock? = synchronized(lock) {143 duress.also { duress = null }144 }145146 override fun close() {147 val candidates = synchronized(lock) {148 if (closed) return149 closed = true150 val result = slotA to duress151 slotA = null152 duress = null153 result154 }155 candidates.first?.let(vault::discardSlotAUnlock)156 candidates.second?.let(vault::discardDuressUnlock)157 }158 }159160 fun unlock(password: String) {161 if (password.isBlank() || _state.value.loading) return162 _state.update { it.copy(loading = true, error = null) }163 viewModelScope.launch {164 val candidates = UnlockCandidates(vault)165 try {166 167 168 169 withContext(Dispatchers.Default) {170 kotlinx.coroutines.coroutineScope {171 val duressDeferred = async {172 if (duress.isConfigured()) {173 vault.tryUnlockDuress(password)?.also(candidates::registerDuress)174 } else null175 }176 val slotADeferred = async {177 vault.tryUnlockSlotA(password)?.also(candidates::registerSlotA)178 }179 180 181 duressDeferred.await()182 slotADeferred.await()183 }184 }185186 when (val duressUnlock = candidates.takeDuress()) {187 188 189 null -> when (val slotAUnlock = candidates.takeSlotA()) {190 null -> _state.update {191 it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)192 }193 else -> try {194 when (val result = vault.commitSlotAUnlock(slotAUnlock)) {195 is UnlockResult.Success -> {196 lockTimer.start()197 foregroundSync.triggerForegroundSync()198 _state.update { it.copy(loading = false, unlocked = true) }199 }200 is UnlockResult.Error -> _state.update {201 it.copy(loading = false, error = result.reason, shakeNonce = it.shakeNonce + 1)202 }203 is UnlockResult.WrongPassword -> _state.update {204 it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)205 }206 }207 } finally {208 209 210 211 vault.discardSlotAUnlock(slotAUnlock)212 }213 }214 else -> {215 candidates.takeSlotA()?.let(vault::discardSlotAUnlock)216 try {217 handleDuress(duressUnlock)218 } finally {219 vault.discardDuressUnlock(duressUnlock)220 }221 }222 }223 } finally {224 225 226 227 candidates.close()228 }229 }230 }231232 233234235236237 private suspend fun handleDuress(duressUnlock: VaultRepository.DuressUnlock) {238 when (duress.action()) {239 DuressAction.DECOY -> when (vault.commitDuressUnlock(duressUnlock)) {240 is UnlockResult.Success -> { lockTimer.start(); _state.update { it.copy(loading = false, unlocked = true) } }241 else -> _state.update {242 it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)243 }244 }245 DuressAction.DESTROY -> {246 vault.discardDuressUnlock(duressUnlock)247 vault.destroyVault()248 syncFreshStart.reset()249 duress.clear()250 _state.update { it.copy(loading = false, hasVault = false, duressDestroyed = true) }251 }252 }253 }254255 fun create(password: String, confirm: String) {256 if (_state.value.loading) return257 createValidationError(password, confirm, scorePassword(password))?.let { msg ->258 return _state.update { it.copy(error = msg) }259 }260 _state.update { it.copy(loading = true, error = null) }261 viewModelScope.launch {262 when (val r = vault.createVault(password)) {263 is CreateVaultResult.Success -> { lockTimer.start(); _state.update { it.copy(loading = false, unlocked = true, created = true) } }264 is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) }265 }266 }267 }268269 fun clearError() = _state.update { it.copy(error = null) }270271 272273274275276 fun canTryBiometric(): Boolean =277 vault.hasVault() &&278 Biometrics.strongAvailable(appContext) &&279 BiometricKeyStore.hasWrappedKey(appContext)280281 282283284285286 fun biometricUnlock(activity: FragmentActivity) {287 if (_state.value.loading) return288 val cipher = BiometricKeyStore.decryptCipher(appContext) ?: return289 Biometrics.authenticateCrypto(290 activity = activity,291 title = "Unlock Peach",292 subtitle = "Use your biometric to unlock your vault",293 crypto = BiometricPrompt.CryptoObject(cipher),294 onSuccess = { result ->295 val used = result.cryptoObject?.cipher ?: return@authenticateCrypto296 viewModelScope.launch {297 298 299 300 var key: ByteArray? = null301 val r = try {302 key = BiometricKeyStore.unwrap(appContext, used)303 if (key == null) return@launch304 vault.unlockWithKey(key!!)305 } finally {306 key?.let(VaultCrypto::zero)307 }308 when (r) {309 is UnlockResult.Success -> {310 lockTimer.start()311 foregroundSync.triggerForegroundSync()312 _state.update { it.copy(unlocked = true) }313 }314 else -> _state.update { it.copy(error = "biometric unlock failed", shakeNonce = it.shakeNonce + 1) }315 }316 }317 },318 )319 }320}