LockViewModel.kt

16.8 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                                    _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                            // If cancellation happens while commit waits on the224                            // repository mutex, this transferred token still owns225                            // its key until this finally discards it.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                // coroutineScope has joined all children before this closes the240                // owner, covering cancellation at either await and cancellation241                // while the winner waits on the repository mutex.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    /**278     * Carry out the configured duress action against an already-derived slot-B unlock.279     * Both paths look like an ordinary successful (decoy) or fresh-install (destroy)280     * unlock to a coercer — no error, no hint that a duress passphrase was used.281     */282    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    /**317     * True when an existing vault can be unlocked by biometrics: strong biometrics318     * available AND a key was escrowed on enable. (A wrapped key existing implies319     * the user enabled biometrics — no need to also read the locked settings blob.)320     */321    fun canTryBiometric(): Boolean =322        vault.hasVault() &&323            Biometrics.strongAvailable(appContext) &&324            BiometricKeyStore.hasWrappedKey(appContext)325326    /**327     * Run the biometric unlock: prompt with the DECRYPT cipher, unwrap the escrowed328     * vault key, and unlock with it. Failure/cancel is silent so the password input329     * remains usable.330     */331    fun biometricUnlock(activity: FragmentActivity) {332        if (_state.value.loading) return333        // Sync-retained mode: vault is warm, just confirm identity.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                    // Allocate/unseal only inside the launched ownership scope:358                    // if viewModelScope is cancelled before execution, no key is359                    // created that could be stranded before finally runs.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}