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 _state.update { it.copy(loading = false, unlocked = true, pinPreferred = false) }214 }215 is UnlockResult.Error -> _state.update {216 it.copy(loading = false, error = result.reason, shakeNonce = it.shakeNonce + 1)217 }218 is UnlockResult.WrongPassword -> _state.update {219 it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)220 }221 }222 } finally {223 224 225 226 vault.discardSlotAUnlock(slotAUnlock)227 }228 }229 else -> {230 candidates.takeSlotA()?.let(vault::discardSlotAUnlock)231 try {232 handleDuress(duressUnlock)233 } finally {234 vault.discardDuressUnlock(duressUnlock)235 }236 }237 }238 } finally {239 240 241 242 candidates.close()243 }244 }245 }246247 fun unlockWithPin(pin: String) {248 if (pin.isBlank() || _state.value.loading) return249 _state.update { it.copy(loading = true, error = null) }250 viewModelScope.launch {251 val key = withContext(Dispatchers.Default) {252 pinUnlock.unlockVaultKey(pin)253 }254 if (key == null) {255 _state.update { it.copy(loading = false, error = "incorrect PIN", shakeNonce = it.shakeNonce + 1) }256 return@launch257 }258 try {259 when (val result = vault.unlockWithKey(key)) {260 is UnlockResult.Success -> {261 lockTimer.start()262 vault.clearUiGate()263 foregroundSync.triggerForegroundSync()264 pinUnlock.markPinUsed()265 _state.update { it.copy(loading = false, unlocked = true, pinPreferred = true) }266 }267 else -> _state.update {268 it.copy(loading = false, error = "incorrect PIN", shakeNonce = it.shakeNonce + 1)269 }270 }271 } finally {272 VaultCrypto.zero(key)273 }274 }275 }276277 278279280281282 private suspend fun handleDuress(duressUnlock: VaultRepository.DuressUnlock) {283 when (duress.action()) {284 DuressAction.DECOY -> when (vault.commitDuressUnlock(duressUnlock)) {285 is UnlockResult.Success -> { lockTimer.start(); vault.clearUiGate(); _state.update { it.copy(loading = false, unlocked = true) } }286 else -> _state.update {287 it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)288 }289 }290 DuressAction.DESTROY -> {291 vault.discardDuressUnlock(duressUnlock)292 vault.destroyVault()293 syncFreshStart.reset()294 duress.clear()295 _state.update { it.copy(loading = false, hasVault = false, duressDestroyed = true) }296 }297 }298 }299300 fun create(password: String, confirm: String) {301 if (_state.value.loading) return302 createValidationError(password, confirm, scorePassword(password))?.let { msg ->303 return _state.update { it.copy(error = msg) }304 }305 _state.update { it.copy(loading = true, error = null) }306 viewModelScope.launch {307 when (val r = vault.createVault(password)) {308 is CreateVaultResult.Success -> { lockTimer.start(); _state.update { it.copy(loading = false, unlocked = true, created = true) } }309 is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) }310 }311 }312 }313314 fun clearError() = _state.update { it.copy(error = null) }315316 317318319320321 fun canTryBiometric(): Boolean =322 vault.hasVault() &&323 Biometrics.strongAvailable(appContext) &&324 BiometricKeyStore.hasWrappedKey(appContext)325326 327328329330331 fun biometricUnlock(activity: FragmentActivity) {332 if (_state.value.loading) return333 334 if (vault.isUnlocked.value) {335 Biometrics.authenticate(336 activity = activity,337 title = "Unlock Peach",338 subtitle = "Confirm your identity to access your vault",339 onSuccess = {340 vault.clearUiGate()341 lockTimer.poke()342 foregroundSync.triggerForegroundSync()343 _state.update { it.copy(unlocked = true) }344 },345 )346 return347 }348 val cipher = BiometricKeyStore.decryptCipher(appContext) ?: return349 Biometrics.authenticateCrypto(350 activity = activity,351 title = "Unlock Peach",352 subtitle = "Use your biometric to unlock your vault",353 crypto = BiometricPrompt.CryptoObject(cipher),354 onSuccess = { result ->355 val used = result.cryptoObject?.cipher ?: return@authenticateCrypto356 viewModelScope.launch {357 358 359 360 var key: ByteArray? = null361 val r = try {362 key = BiometricKeyStore.unwrap(appContext, used)363 if (key == null) return@launch364 vault.unlockWithKey(key!!)365 } finally {366 key?.let(VaultCrypto::zero)367 }368 when (r) {369 is UnlockResult.Success -> {370 lockTimer.start()371 vault.clearUiGate()372 foregroundSync.triggerForegroundSync()373 _state.update { it.copy(unlocked = true) }374 }375 else -> _state.update { it.copy(error = "biometric unlock failed", shakeNonce = it.shakeNonce + 1) }376 }377 }378 },379 )380 }381}