SettingsViewModel.kt

7.8 KB · raw

1package com.peachpasswords.ui.settings23import android.content.Context4import androidx.biometric.BiometricPrompt5import androidx.fragment.app.FragmentActivity6import androidx.lifecycle.ViewModel7import androidx.lifecycle.viewModelScope8import com.peachpasswords.feedback.FeedbackRepository9import com.peachpasswords.feedback.FeedbackState10import com.peachpasswords.license.LicenseRepository11import com.peachpasswords.ui.lock.BiometricKeyStore12import com.peachpasswords.ui.lock.Biometrics13import com.peachpasswords.vault.VaultCrypto14import com.peachpasswords.vault.VaultRepository15import com.peachpasswords.vault.VaultSettings16import dagger.hilt.android.lifecycle.HiltViewModel17import dagger.hilt.android.qualifiers.ApplicationContext18import kotlinx.coroutines.flow.MutableStateFlow19import kotlinx.coroutines.flow.StateFlow20import kotlinx.coroutines.flow.asStateFlow21import kotlinx.coroutines.launch22import javax.inject.Inject2324@HiltViewModel25class SettingsViewModel @Inject constructor(26    private val vault: VaultRepository,27    private val license: LicenseRepository,28    private val feedback: FeedbackRepository,29    private val duress: com.peachpasswords.vault.DuressConfigStore,30    @ApplicationContext private val appContext: Context,31) : ViewModel() {3233    private val _duressConfigured = MutableStateFlow(duress.isConfigured())34    val duressConfigured: StateFlow<Boolean> = _duressConfigured.asStateFlow()3536    /**37     * MF-6: seal a decoy vault (slot B) under the duress passphrase, then record the38     * action policy. The passphrase keys slot B directly and is never stored as a hash.39     */40    suspend fun saveDuress(password: String, action: com.peachpasswords.vault.DuressAction): Boolean {41        if (!vault.setDuressPassphrase(password)) return false42        val ok = duress.enable(action)43        if (ok) _duressConfigured.value = true44        return ok45    }4647    fun disableDuress() {48        viewModelScope.launch { vault.clearDuress() }49        duress.clear()50        _duressConfigured.value = false51    }5253    private val _feedbackState = MutableStateFlow<FeedbackState>(FeedbackState.Idle)54    val feedbackState: StateFlow<FeedbackState> = _feedbackState.asStateFlow()5556    fun sendFeedback(type: String, message: String) {57        if (_feedbackState.value is FeedbackState.Sending) return58        _feedbackState.value = FeedbackState.Sending59        viewModelScope.launch {60            _feedbackState.value = try {61                feedback.submit(type, message)62                FeedbackState.Sent63            } catch (e: Exception) {64                FeedbackState.Error("Couldn't send feedback — check your connection")65            }66        }67    }6869    /** Reset to Idle when the Feedback card leaves the screen. */70    fun resetFeedback() {71        _feedbackState.value = FeedbackState.Idle72    }73    val entries: StateFlow<List<com.peachpasswords.vault.VaultEntry>> = vault.entries74    val settings: StateFlow<VaultSettings> = vault.settings7576    /** Live Pro entitlement, seeded from the stored (locally Ed25519-validated) license. */77    private val _isPro = MutableStateFlow(license.isProActive())78    val isPro: StateFlow<Boolean> = _isPro.asStateFlow()7980    private val _activating = MutableStateFlow(false)81    val activating: StateFlow<Boolean> = _activating.asStateFlow()8283    private val _activationError = MutableStateFlow<String?>(null)84    val activationError: StateFlow<String?> = _activationError.asStateFlow()8586    /** Set true after a fresh activation so the screen can fire ProCelebration once. */87    private val _showCelebration = MutableStateFlow(false)88    val showCelebration: StateFlow<Boolean> = _showCelebration.asStateFlow()8990    /**91     * Validate a license key locally (offline Ed25519 — there is no activation server)92     * and, on success, persist it and flip Pro on. Surfaces only outcomes that can93     * actually occur offline.94     */95    fun activateLicense(rawKey: String) {96        if (_activating.value) return97        _activating.value = true98        _activationError.value = null99        viewModelScope.launch {100            val key = rawKey.trim()101            if (license.validateLicense(key)) {102                license.storeLicense(key)103                _isPro.value = true104                _showCelebration.value = true105            } else {106                _activationError.value = "Invalid license key"107            }108            _activating.value = false109        }110    }111112    fun clearActivationError() { _activationError.value = null }113114    fun dismissCelebration() {115        license.markProCelebrated()116        _showCelebration.value = false117    }118119    fun deactivate() {120        license.clearLicense()121        _isPro.value = false122    }123124    private fun mutate(block: (VaultSettings) -> VaultSettings) {125        viewModelScope.launch { vault.updateSettings(block(vault.settings.value)) }126    }127128    fun setTheme(theme: String) = mutate { it.copy(theme = theme) }129    fun setAccent(name: String) = mutate { it.copy(accentColor = name) }130    fun setTextSize(size: String) = mutate { it.copy(textSize = size) }131    fun setReduceMotion(on: Boolean) = mutate { it.copy(reduceMotion = on) }132    fun setBreachMonitoring(on: Boolean) = mutate { it.copy(breachMonitoring = on) }133    fun setBiometrics(on: Boolean) = mutate { it.copy(biometricsEnabled = on) }134135    /**136     * Enable biometric unlock: prompt to wrap the live vault key under a hardware137     * KeyStore key and persist the escrow, then flip the setting on. Requires the138     * vault to be unlocked (it is, inside Settings). A failed/cancelled prompt139     * leaves biometrics off.140     */141    fun enableBiometrics(activity: FragmentActivity) {142        val key = vault.currentVaultKey() ?: return143        val cipher = try {144            BiometricKeyStore.encryptCipher()145        } catch (_: Exception) {146            VaultCrypto.zero(key); return147        }148        Biometrics.authenticateCrypto(149            activity = activity,150            title = "Enable biometric unlock",151            subtitle = "Confirm to secure your vault key",152            crypto = BiometricPrompt.CryptoObject(cipher),153            onSuccess = { result ->154                val used = result.cryptoObject?.cipher155                if (used != null) {156                    runCatching { BiometricKeyStore.wrapAndStore(appContext, used, key) }157                        .onSuccess { mutate { it.copy(biometricsEnabled = true) } }158                }159                VaultCrypto.zero(key)160            },161            onFail = { VaultCrypto.zero(key) },162        )163    }164165    /** Disable biometric unlock: drop the escrowed key + KeyStore entry, flip the setting off. */166    fun disableBiometrics() {167        BiometricKeyStore.clear(appContext)168        mutate { it.copy(biometricsEnabled = false) }169    }170    fun setAutoLockMinutes(min: Int?) = mutate { it.copy(autoLockMinutes = min) }171    fun setTrashRetentionDays(days: Int?) = mutate { it.copy(trashRetentionDays = days) }172173    suspend fun changePassword(current: String, next: String): Boolean =174        vault.changePassword(current, next)175176    /** One-line summary shown under each card title; mirrors the browser ledes. */177    fun lede(id: CardId, entriesCount: Int, s: VaultSettings): String = when (id) {178        CardId.Pro -> if (_isPro.value) "active · paid once, yours forever" else "$39 once · yours forever"179        CardId.Protection ->180            "${if (s.breachMonitoring) "breaches watched" else "breach watch off"} · manual lock"181        CardId.Vault ->182            "$entriesCount ${if (entriesCount == 1) "entry" else "entries"} · backups, history, cleanup"183        CardId.Sync -> if (_isPro.value) "pair by chirp, keep in step" else "Pro · encrypted device pairing"184        CardId.Appearance -> "${s.theme} · ${s.accentColor} · ${s.textSize}"185        CardId.Shortcuts -> "bindings · what your fingers know"186        CardId.Feedback -> "tell us what would make it better"187    }188}