1package com.peachpasswords.ui.lock23import android.content.Context4import androidx.biometric.BiometricPrompt5import androidx.fragment.app.FragmentActivity6import androidx.lifecycle.ViewModel7import androidx.lifecycle.viewModelScope8import com.peachpasswords.license.LicenseRepository9import com.peachpasswords.sync.ForegroundSyncCoordinator10import com.peachpasswords.sync.SyncFreshStartResetter11import com.peachpasswords.ui.PeachNav12import com.peachpasswords.ui.vault.entryTapDestination13import com.peachpasswords.vault.CreateVaultResult14import com.peachpasswords.ui.security.scorePassword15import com.peachpasswords.vault.DuressAction16import com.peachpasswords.vault.DuressConfigStore17import com.peachpasswords.vault.LastViewedEntryStore18import com.peachpasswords.vault.UnlockResult19import com.peachpasswords.vault.VaultCrypto20import com.peachpasswords.vault.VaultEntry21import com.peachpasswords.vault.VaultLockTimer22import com.peachpasswords.vault.VaultRepository23import dagger.hilt.android.lifecycle.HiltViewModel24import dagger.hilt.android.qualifiers.ApplicationContext25import kotlinx.coroutines.Dispatchers26import kotlinx.coroutines.async27import kotlinx.coroutines.flow.MutableStateFlow28import kotlinx.coroutines.flow.StateFlow29import kotlinx.coroutines.flow.asStateFlow30import kotlinx.coroutines.flow.update31import kotlinx.coroutines.launch32import kotlinx.coroutines.withContext33import javax.inject.Inject3435data class LockUiState(36 val hasVault: Boolean = false,37 val pinEnabled: Boolean = false,38 val pinPreferred: Boolean = false,39 val isPro: Boolean = false,40 val loading: Boolean = false,41 val error: String? = null,42 val unlocked: Boolean = false,43 44 val created: Boolean = false,45 46 val shakeNonce: Int = 0,47 48 val duressDestroyed: Boolean = false,49)5051const val MIN_PASSWORD_LENGTH = 12525354const val MIN_CREATE_STRENGTH = 255565758596061internal fun createValidationError(password: String, confirm: String, score: Int): String? = when {62 password.length < MIN_PASSWORD_LENGTH -> "password must be at least $MIN_PASSWORD_LENGTH characters"63 score < MIN_CREATE_STRENGTH -> "Password too weak — try a longer or more varied password"64 password != confirm -> "passwords do not match"65 else -> null66}676869internal fun canSubmitCreateVault(password: String, confirm: String, score: Int): Boolean =70 createValidationError(password, confirm, score) == null717273747576777879internal fun postUnlockDestination(80 lastViewedId: String?,81 resolve: (String) -> VaultEntry?,82 firstActive: VaultEntry?,83): PeachNav {84 val target = lastViewedId?.let(resolve) ?: firstActive ?: return PeachNav.VaultList85 return entryTapDestination(target)86}8788@HiltViewModel89class LockViewModel @Inject constructor(90 private val vault: VaultRepository,91 license: LicenseRepository,92 private val duress: DuressConfigStore,93 private val lockTimer: VaultLockTimer,94 private val lastViewed: LastViewedEntryStore,95 private val foregroundSync: ForegroundSyncCoordinator,96 private val syncFreshStart: SyncFreshStartResetter,97 private val pinUnlock: com.peachpasswords.vault.PinUnlockStore,98 @ApplicationContext private val appContext: Context,99) : ViewModel() {100 private val _state = MutableStateFlow(101 LockUiState(102 hasVault = vault.hasVault(),103 pinEnabled = pinUnlock.isConfigured(),104 pinPreferred = pinUnlock.isPinPreferred(),105 isPro = license.isProActive(),106 ),107 )108 val state: StateFlow<LockUiState> = _state.asStateFlow()109110 111 fun postUnlockDestination(): PeachNav =112 postUnlockDestination(lastViewed.get(), vault::getEntry, vault.getActiveEntries().firstOrNull())113114 115116117118119120121122123 private class UnlockCandidates(private val vault: VaultRepository) : AutoCloseable {124 private val lock = Any()125 private var closed = false126 private var slotA: VaultRepository.SlotAUnlock? = null127 private var duress: VaultRepository.DuressUnlock? = null128129 fun registerSlotA(candidate: VaultRepository.SlotAUnlock) {130 val discard = synchronized(lock) {131 if (closed) true else {132 slotA?.let(vault::discardSlotAUnlock)133 slotA = candidate134 false135 }136 }137 if (discard) vault.discardSlotAUnlock(candidate)138 }139140 fun registerDuress(candidate: VaultRepository.DuressUnlock) {141 val discard = synchronized(lock) {142 if (closed) true else {143 duress?.let(vault::discardDuressUnlock)144 duress = candidate145 false146 }147 }148 if (discard) vault.discardDuressUnlock(candidate)149 }150151 fun takeSlotA(): VaultRepository.SlotAUnlock? = synchronized(lock) {152 slotA.also { slotA = null }153 }154155 fun takeDuress(): VaultRepository.DuressUnlock? = synchronized(lock) {156 duress.also { duress = null }157 }158159 override fun close() {160 val candidates = synchronized(lock) {161 if (closed) return162 closed = true163 val result = slotA to duress164 slotA = null165 duress = null166 result167 }168 candidates.first?.let(vault::discardSlotAUnlock)169 candidates.second?.let(vault::discardDuressUnlock)170 }171 }172173 fun unlock(password: String) {174 if (password.isBlank() || _state.value.loading) return175 _state.update { it.copy(loading = true, error = null) }176 viewModelScope.launch {177 val candidates = UnlockCandidates(vault)178 try {179 180 181 182 withContext(Dispatchers.Default) {183 kotlinx.coroutines.coroutineScope {184 val duressDeferred = async {185 if (duress.isConfigured()) {186 vault.tryUnlockDuress(password)?.also(candidates::registerDuress)187 } else null188 }189 val slotADeferred = async {190 vault.tryUnlockSlotA(password)?.also(candidates::registerSlotA)191 }192 193 194 duressDeferred.await()195 slotADeferred.await()196 }197 }198199 when (val duressUnlock = candidates.takeDuress()) {200 201 202 null -> when (val slotAUnlock = candidates.takeSlotA()) {203 null -> _state.update {204 it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)205 }206 else -> try {207 when (val result = vault.commitSlotAUnlock(slotAUnlock)) {208 is UnlockResult.Success -> {209 lockTimer.start()210 vault.clearUiGate()211 foregroundSync.triggerForegroundSync()212 pinUnlock.markPasswordUsed()213 pinUnlock.replenishAttemptGates()214 _state.update { it.copy(loading = false, unlocked = true, pinPreferred = false) }215 }216 is UnlockResult.Error -> _state.update {217 it.copy(loading = false, error = result.reason, shakeNonce = it.shakeNonce + 1)218 }219 is UnlockResult.WrongPassword -> _state.update {220 it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)221 }222 }223 } finally {224 225 226 227 vault.discardSlotAUnlock(slotAUnlock)228 }229 }230 else -> {231 candidates.takeSlotA()?.let(vault::discardSlotAUnlock)232 try {233 handleDuress(duressUnlock)234 } finally {235 vault.discardDuressUnlock(duressUnlock)236 }237 }238 }239 } finally {240 241 242 243 candidates.close()244 }245 }246 }247248 fun unlockWithPin(pin: String) {249 if (pin.isBlank() || _state.value.loading) return250 _state.update { it.copy(loading = true, error = null) }251 viewModelScope.launch {252 val key = withContext(Dispatchers.Default) {253 pinUnlock.unlockVaultKey(pin)254 }255 if (key == null) {256 _state.update {257 it.copy(258 loading = false,259 error = if (pinUnlock.areAttemptsExhausted()) {260 "PIN locked — use master password"261 } else {262 "incorrect PIN"263 },264 shakeNonce = it.shakeNonce + 1,265 )266 }267 return@launch268 }269 try {270 when (val result = vault.unlockWithKey(key)) {271 is UnlockResult.Success -> {272 lockTimer.start()273 vault.clearUiGate()274 foregroundSync.triggerForegroundSync()275 pinUnlock.markPinUsed()276 _state.update { it.copy(loading = false, unlocked = true, pinPreferred = true) }277 }278 else -> _state.update {279 it.copy(loading = false, error = "incorrect PIN", shakeNonce = it.shakeNonce + 1)280 }281 }282 } finally {283 VaultCrypto.zero(key)284 }285 }286 }287288 289290291292293 private suspend fun handleDuress(duressUnlock: VaultRepository.DuressUnlock) {294 when (duress.action()) {295 DuressAction.DECOY -> when (vault.commitDuressUnlock(duressUnlock)) {296 is UnlockResult.Success -> { lockTimer.start(); vault.clearUiGate(); _state.update { it.copy(loading = false, unlocked = true) } }297 else -> _state.update {298 it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)299 }300 }301 DuressAction.DESTROY -> {302 vault.discardDuressUnlock(duressUnlock)303 vault.destroyVault()304 syncFreshStart.reset()305 duress.clear()306 _state.update { it.copy(loading = false, hasVault = false, duressDestroyed = true) }307 }308 }309 }310311 fun create(password: String, confirm: String) {312 if (_state.value.loading) return313 createValidationError(password, confirm, scorePassword(password))?.let { msg ->314 return _state.update { it.copy(error = msg) }315 }316 _state.update { it.copy(loading = true, error = null) }317 viewModelScope.launch {318 when (val r = vault.createVault(password)) {319 is CreateVaultResult.Success -> { lockTimer.start(); _state.update { it.copy(loading = false, unlocked = true, created = true) } }320 is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) }321 }322 }323 }324325 fun clearError() = _state.update { it.copy(error = null) }326327 328329330331332 fun canTryBiometric(): Boolean =333 vault.hasVault() &&334 Biometrics.strongAvailable(appContext) &&335 BiometricKeyStore.hasWrappedKey(appContext)336337 338339340341342 fun biometricUnlock(activity: FragmentActivity) {343 if (_state.value.loading) return344 345 if (vault.isUnlocked.value) {346 Biometrics.authenticate(347 activity = activity,348 title = "Unlock Peach",349 subtitle = "Confirm your identity to access your vault",350 onSuccess = {351 vault.clearUiGate()352 lockTimer.poke()353 foregroundSync.triggerForegroundSync()354 _state.update { it.copy(unlocked = true) }355 },356 )357 return358 }359 val cipher = BiometricKeyStore.decryptCipher(appContext) ?: return360 Biometrics.authenticateCrypto(361 activity = activity,362 title = "Unlock Peach",363 subtitle = "Use your biometric to unlock your vault",364 crypto = BiometricPrompt.CryptoObject(cipher),365 onSuccess = { result ->366 val used = result.cryptoObject?.cipher ?: return@authenticateCrypto367 viewModelScope.launch {368 369 370 371 var key: ByteArray? = null372 val r = try {373 key = BiometricKeyStore.unwrap(appContext, used)374 if (key == null) return@launch375 vault.unlockWithKey(key!!)376 } finally {377 key?.let(VaultCrypto::zero)378 }379 when (r) {380 is UnlockResult.Success -> {381 lockTimer.start()382 vault.clearUiGate()383 foregroundSync.triggerForegroundSync()384 _state.update { it.copy(unlocked = true) }385 }386 else -> _state.update { it.copy(error = "biometric unlock failed", shakeNonce = it.shakeNonce + 1) }387 }388 }389 },390 )391 }392}