LockViewModel.kt

8.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.ui.PeachNav9import com.peachpasswords.ui.vault.entryTapDestination10import com.peachpasswords.vault.CreateVaultResult11import com.peachpasswords.ui.security.scorePassword12import com.peachpasswords.vault.DuressAction13import com.peachpasswords.vault.DuressConfigStore14import com.peachpasswords.vault.LastViewedEntryStore15import com.peachpasswords.vault.UnlockResult16import com.peachpasswords.vault.VaultCrypto17import com.peachpasswords.vault.VaultEntry18import com.peachpasswords.vault.VaultLockTimer19import com.peachpasswords.vault.VaultRepository20import dagger.hilt.android.lifecycle.HiltViewModel21import dagger.hilt.android.qualifiers.ApplicationContext22import kotlinx.coroutines.Dispatchers23import kotlinx.coroutines.async24import kotlinx.coroutines.flow.MutableStateFlow25import kotlinx.coroutines.flow.StateFlow26import kotlinx.coroutines.flow.asStateFlow27import kotlinx.coroutines.flow.update28import kotlinx.coroutines.launch29import kotlinx.coroutines.withContext30import javax.inject.Inject3132data class LockUiState(33    val hasVault: Boolean = false,34    val loading: Boolean = false,35    val error: String? = null,36    val unlocked: Boolean = false,37    /** True when this session just created a new vault (routes through recovery-word setup). */38    val created: Boolean = false,39    /** Increments on each failed unlock so the screen can fire its shake animation. */40    val shakeNonce: Int = 0,41    /** Real vault was wiped by a destroy-duress unlock → screen drops to CreateVault. */42    val duressDestroyed: Boolean = false,43)4445const val MIN_PASSWORD_LENGTH = 124647/** CreateVault is blocked below "fair" (zxcvbn-style score 2). */48const val MIN_CREATE_STRENGTH = 24950/**51 * Where to land after a successful unlock (brief Fix 3): the last-viewed entry if52 * it still exists, else the first active entry, else the vault list when the vault53 * is empty. [resolve] re-validates the stored id against the live vault so a stale54 * pointer (deleted entry) falls back rather than opening a missing detail screen.55 * NOTE entries route to the notes editor via [entryTapDestination], same as a list tap.56 */57internal fun postUnlockDestination(58    lastViewedId: String?,59    resolve: (String) -> VaultEntry?,60    firstActive: VaultEntry?,61): PeachNav {62    val target = lastViewedId?.let(resolve) ?: firstActive ?: return PeachNav.VaultList63    return entryTapDestination(target)64}6566@HiltViewModel67class LockViewModel @Inject constructor(68    private val vault: VaultRepository,69    private val duress: DuressConfigStore,70    private val lockTimer: VaultLockTimer,71    private val lastViewed: LastViewedEntryStore,72    @ApplicationContext private val appContext: Context,73) : ViewModel() {74    private val _state = MutableStateFlow(LockUiState(hasVault = vault.hasVault()))75    val state: StateFlow<LockUiState> = _state.asStateFlow()7677    /** Resolve where a just-unlocked session should land (last-viewed entry → first → list). */78    fun postUnlockDestination(): PeachNav =79        postUnlockDestination(lastViewed.get(), vault::getEntry, vault.getActiveEntries().firstOrNull())8081    fun unlock(password: String) {82        if (password.isBlank() || _state.value.loading) return83        _state.update { it.copy(loading = true, error = null) }84        viewModelScope.launch {85            // Derive slot A and the duress slot (slot B) CONCURRENTLY so the wall-clock86            // time to reject/accept never reveals whether the entered password was the87            // real password, the duress passphrase, or simply wrong (MF-5/MF-6, mirrors88            // browser DUR-002). Both Argon2id derivations run to completion; the branch89            // happens only after both finish. Each derivation is non-committing (no90            // mutex, no session mutation) so the loser is simply discarded.91            val (duressUnlock, slotA) = withContext(Dispatchers.Default) {92                val duressDeferred = async { if (duress.isConfigured()) vault.tryUnlockDuress(password) else null }93                val slotADeferred = async { vault.tryUnlockSlotA(password) }94                duressDeferred.await() to slotADeferred.await()95            }96            when {97                // Duress takes precedence: the duress passphrase never reaches the real vault.98                duressUnlock != null -> {99                    slotA?.let(vault::discardSlotAUnlock)100                    handleDuress(duressUnlock)101                }102                slotA != null -> {103                    vault.commitSlotAUnlock(slotA)104                    lockTimer.start()105                    _state.update { it.copy(loading = false, unlocked = true) }106                }107                else -> _state.update {108                    it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)109                }110            }111        }112    }113114    /**115     * Carry out the configured duress action against an already-derived slot-B unlock.116     * Both paths look like an ordinary successful (decoy) or fresh-install (destroy)117     * unlock to a coercer — no error, no hint that a duress passphrase was used.118     */119    private suspend fun handleDuress(duressUnlock: VaultRepository.DuressUnlock) {120        when (duress.action()) {121            DuressAction.DECOY -> when (vault.commitDuressUnlock(duressUnlock)) {122                is UnlockResult.Success -> { lockTimer.start(); _state.update { it.copy(loading = false, unlocked = true) } }123                else -> _state.update {124                    it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)125                }126            }127            DuressAction.DESTROY -> {128                vault.discardDuressUnlock(duressUnlock)129                vault.destroyVault()130                duress.clear()131                _state.update { it.copy(loading = false, hasVault = false, duressDestroyed = true) }132            }133        }134    }135136    fun create(password: String, confirm: String) {137        if (_state.value.loading) return138        when {139            password.length < MIN_PASSWORD_LENGTH ->140                return _state.update { it.copy(error = "password must be at least $MIN_PASSWORD_LENGTH characters") }141            scorePassword(password) < MIN_CREATE_STRENGTH ->142                return _state.update { it.copy(error = "Password too weak — try a longer or more varied password") }143            password != confirm ->144                return _state.update { it.copy(error = "passwords do not match") }145        }146        _state.update { it.copy(loading = true, error = null) }147        viewModelScope.launch {148            when (val r = vault.createVault(password)) {149                is CreateVaultResult.Success -> { lockTimer.start(); _state.update { it.copy(loading = false, unlocked = true, created = true) } }150                is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) }151            }152        }153    }154155    fun clearError() = _state.update { it.copy(error = null) }156157    /**158     * True when an existing vault can be unlocked by biometrics: strong biometrics159     * available AND a key was escrowed on enable. (A wrapped key existing implies160     * the user enabled biometrics — no need to also read the locked settings blob.)161     */162    fun canTryBiometric(): Boolean =163        vault.hasVault() &&164            Biometrics.strongAvailable(appContext) &&165            BiometricKeyStore.hasWrappedKey(appContext)166167    /**168     * Run the biometric unlock: prompt with the DECRYPT cipher, unwrap the escrowed169     * vault key, and unlock with it. Failure/cancel is silent so the password input170     * remains usable.171     */172    fun biometricUnlock(activity: FragmentActivity) {173        if (_state.value.loading) return174        val cipher = BiometricKeyStore.decryptCipher(appContext) ?: return175        Biometrics.authenticateCrypto(176            activity = activity,177            title = "Unlock Peach",178            subtitle = "Use your biometric to unlock your vault",179            crypto = BiometricPrompt.CryptoObject(cipher),180            onSuccess = { result ->181                val used = result.cryptoObject?.cipher ?: return@authenticateCrypto182                val key = BiometricKeyStore.unwrap(appContext, used) ?: return@authenticateCrypto183                viewModelScope.launch {184                    val r = vault.unlockWithKey(key)185                    VaultCrypto.zero(key)186                    when (r) {187                        is UnlockResult.Success -> { lockTimer.start(); _state.update { it.copy(unlocked = true) } }188                        else -> _state.update { it.copy(error = "biometric unlock failed", shakeNonce = it.shakeNonce + 1) }189                    }190                }191            },192        )193    }194}