package com.peachpasswords.ui.lock import android.content.Context import androidx.biometric.BiometricPrompt import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.peachpasswords.vault.CreateVaultResult import com.peachpasswords.ui.security.scorePassword import com.peachpasswords.vault.DuressAction import com.peachpasswords.vault.DuressConfigStore import com.peachpasswords.vault.DuressMatch import com.peachpasswords.vault.UnlockResult import com.peachpasswords.vault.VaultCrypto import com.peachpasswords.vault.VaultRepository import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject data class LockUiState( val hasVault: Boolean = false, val loading: Boolean = false, val error: String? = null, val unlocked: Boolean = false, /** True when this session just created a new vault (routes through recovery-word setup). */ val created: Boolean = false, /** Increments on each failed unlock so the screen can fire its shake animation. */ val shakeNonce: Int = 0, /** Real vault was wiped by a destroy-duress unlock → screen drops to CreateVault. */ val duressDestroyed: Boolean = false, ) const val MIN_PASSWORD_LENGTH = 12 /** CreateVault is blocked below "fair" (zxcvbn-style score 2). */ const val MIN_CREATE_STRENGTH = 2 @HiltViewModel class LockViewModel @Inject constructor( private val vault: VaultRepository, private val duress: DuressConfigStore, @ApplicationContext private val appContext: Context, ) : ViewModel() { private val _state = MutableStateFlow(LockUiState(hasVault = vault.hasVault())) val state: StateFlow = _state.asStateFlow() fun unlock(password: String) { if (password.isBlank() || _state.value.loading) return _state.update { it.copy(loading = true, error = null) } viewModelScope.launch { // Duress check first: a matching duress password never reaches the real vault. when (val d = duress.verify(password)) { is DuressMatch.Match -> { handleDuress(d.action); return@launch } DuressMatch.None -> Unit } when (val r = vault.unlock(password)) { is UnlockResult.Success -> _state.update { it.copy(loading = false, unlocked = true) } is UnlockResult.WrongPassword -> _state.update { it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1) } is UnlockResult.Error -> _state.update { it.copy(loading = false, error = r.reason, shakeNonce = it.shakeNonce + 1) } } } } /** * Carry out the configured duress action. Both paths look like an ordinary * successful (decoy) or fresh-install (destroy) unlock to a coercer — no error. */ private suspend fun handleDuress(action: DuressAction) { when (action) { DuressAction.DECOY -> when (vault.unlockDecoy()) { is UnlockResult.Success -> _state.update { it.copy(loading = false, unlocked = true) } else -> _state.update { it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1) } } DuressAction.DESTROY -> { vault.destroyVault() duress.clear() _state.update { it.copy(loading = false, hasVault = false, duressDestroyed = true) } } } } fun create(password: String, confirm: String) { if (_state.value.loading) return when { password.length < MIN_PASSWORD_LENGTH -> return _state.update { it.copy(error = "password must be at least $MIN_PASSWORD_LENGTH characters") } scorePassword(password) < MIN_CREATE_STRENGTH -> return _state.update { it.copy(error = "Password too weak — try a longer or more varied password") } password != confirm -> return _state.update { it.copy(error = "passwords do not match") } } _state.update { it.copy(loading = true, error = null) } viewModelScope.launch { when (val r = vault.createVault(password)) { is CreateVaultResult.Success -> _state.update { it.copy(loading = false, unlocked = true, created = true) } is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) } } } } fun clearError() = _state.update { it.copy(error = null) } /** * True when an existing vault can be unlocked by biometrics: strong biometrics * available AND a key was escrowed on enable. (A wrapped key existing implies * the user enabled biometrics — no need to also read the locked settings blob.) */ fun canTryBiometric(): Boolean = vault.hasVault() && Biometrics.strongAvailable(appContext) && BiometricKeyStore.hasWrappedKey(appContext) /** * Run the biometric unlock: prompt with the DECRYPT cipher, unwrap the escrowed * vault key, and unlock with it. Failure/cancel is silent so the password input * remains usable. */ fun biometricUnlock(activity: FragmentActivity) { if (_state.value.loading) return val cipher = BiometricKeyStore.decryptCipher(appContext) ?: return Biometrics.authenticateCrypto( activity = activity, title = "Unlock Peach", subtitle = "Use your biometric to unlock your vault", crypto = BiometricPrompt.CryptoObject(cipher), onSuccess = { result -> val used = result.cryptoObject?.cipher ?: return@authenticateCrypto val key = BiometricKeyStore.unwrap(appContext, used) ?: return@authenticateCrypto viewModelScope.launch { val r = vault.unlockWithKey(key) VaultCrypto.zero(key) when (r) { is UnlockResult.Success -> _state.update { it.copy(unlocked = true) } else -> _state.update { it.copy(error = "biometric unlock failed", shakeNonce = it.shakeNonce + 1) } } } }, ) } }