LockViewModel.kt

17.2 KB · raw

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    /** True when this session just created a new vault (routes through recovery-word setup). */44    val created: Boolean = false,45    /** Increments on each failed unlock so the screen can fire its shake animation. */46    val shakeNonce: Int = 0,47    /** Real vault was wiped by a destroy-duress unlock → screen drops to CreateVault. */48    val duressDestroyed: Boolean = false,49)5051const val MIN_PASSWORD_LENGTH = 125253/** CreateVault is blocked below "fair" (zxcvbn-style score 2). */54const val MIN_CREATE_STRENGTH = 25556/**57 * Validate a create-vault attempt; returns the user-facing error, or null when the58 * inputs are acceptable. Pure so the create rules (length floor, strength gate,59 * confirm match — in that order) are unit-testable without the ViewModel.60 */61internal 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}6768/** Browser parity: create stays disabled until every create-vault rule passes. */69internal fun canSubmitCreateVault(password: String, confirm: String, score: Int): Boolean =70    createValidationError(password, confirm, score) == null7172/**73 * Where to land after a successful unlock (brief Fix 3): the last-viewed entry if74 * it still exists, else the first active entry, else the vault list when the vault75 * is empty. [resolve] re-validates the stored id against the live vault so a stale76 * pointer (deleted entry) falls back rather than opening a missing detail screen.77 * NOTE entries route to the notes editor via [entryTapDestination], same as a list tap.78 */79internal 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    /** Resolve where a just-unlocked session should land (last-viewed entry → first → list). */111    fun postUnlockDestination(): PeachNav =112        postUnlockDestination(lastViewed.get(), vault::getEntry, vault.getActiveEntries().firstOrNull())113114    /**115     * Owns candidate unlock tokens for the whole concurrent-derivation scope.116     *117     * Argon2id is deliberately not cancellable.  A token can therefore be118     * produced after the caller has been cancelled unless ownership is claimed119     * by the child immediately, before that child completes.  The scope closes120     * only after [coroutineScope] has joined both children, so every registered121     * loser is discarded even when cancellation happens between either await.122     */123    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                // Derive slot A and the duress slot (slot B) CONCURRENTLY so the180                // wall-clock time to reject/accept never reveals which password was181                // entered.  Each child registers its token before it completes.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                        // Await both children before choosing a winner.  The193                        // candidates object, not a post-await local, owns tokens.194                        duressDeferred.await()195                        slotADeferred.await()196                    }197                }198199                when (val duressUnlock = candidates.takeDuress()) {200                    // Duress takes precedence: the duress passphrase never reaches201                    // the real vault.  Taking it transfers ownership to this branch.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                            // If cancellation happens while commit waits on the225                            // repository mutex, this transferred token still owns226                            // its key until this finally discards it.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                // coroutineScope has joined all children before this closes the241                // owner, covering cancellation at either await and cancellation242                // while the winner waits on the repository mutex.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    /**289     * Carry out the configured duress action against an already-derived slot-B unlock.290     * Both paths look like an ordinary successful (decoy) or fresh-install (destroy)291     * unlock to a coercer — no error, no hint that a duress passphrase was used.292     */293    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    /**328     * True when an existing vault can be unlocked by biometrics: strong biometrics329     * available AND a key was escrowed on enable. (A wrapped key existing implies330     * the user enabled biometrics — no need to also read the locked settings blob.)331     */332    fun canTryBiometric(): Boolean =333        vault.hasVault() &&334            Biometrics.strongAvailable(appContext) &&335            BiometricKeyStore.hasWrappedKey(appContext)336337    /**338     * Run the biometric unlock: prompt with the DECRYPT cipher, unwrap the escrowed339     * vault key, and unlock with it. Failure/cancel is silent so the password input340     * remains usable.341     */342    fun biometricUnlock(activity: FragmentActivity) {343        if (_state.value.loading) return344        // Sync-retained mode: vault is warm, just confirm identity.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                    // Allocate/unseal only inside the launched ownership scope:369                    // if viewModelScope is cancelled before execution, no key is370                    // created that could be stranded before finally runs.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}