SettingsViewModel.kt

6.0 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.license.LicenseRepository9import com.peachpasswords.ui.lock.BiometricKeyStore10import com.peachpasswords.ui.lock.Biometrics11import com.peachpasswords.vault.VaultCrypto12import com.peachpasswords.vault.VaultRepository13import com.peachpasswords.vault.VaultSettings14import dagger.hilt.android.lifecycle.HiltViewModel15import dagger.hilt.android.qualifiers.ApplicationContext16import kotlinx.coroutines.flow.MutableStateFlow17import kotlinx.coroutines.flow.StateFlow18import kotlinx.coroutines.flow.asStateFlow19import kotlinx.coroutines.launch20import javax.inject.Inject2122@HiltViewModel23class SettingsViewModel @Inject constructor(24    private val vault: VaultRepository,25    private val license: LicenseRepository,26    @ApplicationContext private val appContext: Context,27) : ViewModel() {28    val entries: StateFlow<List<com.peachpasswords.vault.VaultEntry>> = vault.entries29    val settings: StateFlow<VaultSettings> = vault.settings3031    /** Live Pro entitlement, seeded from the stored (locally Ed25519-validated) license. */32    private val _isPro = MutableStateFlow(license.isProActive())33    val isPro: StateFlow<Boolean> = _isPro.asStateFlow()3435    private val _activating = MutableStateFlow(false)36    val activating: StateFlow<Boolean> = _activating.asStateFlow()3738    private val _activationError = MutableStateFlow<String?>(null)39    val activationError: StateFlow<String?> = _activationError.asStateFlow()4041    /** Set true after a fresh activation so the screen can fire ProCelebration once. */42    private val _showCelebration = MutableStateFlow(false)43    val showCelebration: StateFlow<Boolean> = _showCelebration.asStateFlow()4445    /**46     * Validate a license key locally (offline Ed25519 — there is no activation server)47     * and, on success, persist it and flip Pro on. Surfaces only outcomes that can48     * actually occur offline.49     */50    fun activateLicense(rawKey: String) {51        if (_activating.value) return52        _activating.value = true53        _activationError.value = null54        viewModelScope.launch {55            val key = rawKey.trim()56            if (license.validateLicense(key)) {57                license.storeLicense(key)58                _isPro.value = true59                _showCelebration.value = true60            } else {61                _activationError.value = "Invalid license key"62            }63            _activating.value = false64        }65    }6667    fun clearActivationError() { _activationError.value = null }6869    fun dismissCelebration() {70        license.markProCelebrated()71        _showCelebration.value = false72    }7374    fun deactivate() {75        license.clearLicense()76        _isPro.value = false77    }7879    private fun mutate(block: (VaultSettings) -> VaultSettings) {80        viewModelScope.launch { vault.updateSettings(block(vault.settings.value)) }81    }8283    fun setTheme(theme: String) = mutate { it.copy(theme = theme) }84    fun setAccent(name: String) = mutate { it.copy(accentColor = name) }85    fun setTextSize(size: String) = mutate { it.copy(textSize = size) }86    fun setReduceMotion(on: Boolean) = mutate { it.copy(reduceMotion = on) }87    fun setBreachMonitoring(on: Boolean) = mutate { it.copy(breachMonitoring = on) }88    fun setBiometrics(on: Boolean) = mutate { it.copy(biometricsEnabled = on) }8990    /**91     * Enable biometric unlock: prompt to wrap the live vault key under a hardware92     * KeyStore key and persist the escrow, then flip the setting on. Requires the93     * vault to be unlocked (it is, inside Settings). A failed/cancelled prompt94     * leaves biometrics off.95     */96    fun enableBiometrics(activity: FragmentActivity) {97        val key = vault.currentVaultKey() ?: return98        val cipher = try {99            BiometricKeyStore.encryptCipher()100        } catch (_: Exception) {101            VaultCrypto.zero(key); return102        }103        Biometrics.authenticateCrypto(104            activity = activity,105            title = "Enable biometric unlock",106            subtitle = "Confirm to secure your vault key",107            crypto = BiometricPrompt.CryptoObject(cipher),108            onSuccess = { result ->109                val used = result.cryptoObject?.cipher110                if (used != null) {111                    runCatching { BiometricKeyStore.wrapAndStore(appContext, used, key) }112                        .onSuccess { mutate { it.copy(biometricsEnabled = true) } }113                }114                VaultCrypto.zero(key)115            },116            onFail = { VaultCrypto.zero(key) },117        )118    }119120    /** Disable biometric unlock: drop the escrowed key + KeyStore entry, flip the setting off. */121    fun disableBiometrics() {122        BiometricKeyStore.clear(appContext)123        mutate { it.copy(biometricsEnabled = false) }124    }125    fun setAutoLockMinutes(min: Int?) = mutate { it.copy(autoLockMinutes = min) }126    fun setTrashRetentionDays(days: Int?) = mutate { it.copy(trashRetentionDays = days) }127128    suspend fun changePassword(current: String, next: String): Boolean =129        vault.changePassword(current, next)130131    /** One-line summary shown under each card title; mirrors the browser ledes. */132    fun lede(id: CardId, entriesCount: Int, s: VaultSettings): String = when (id) {133        CardId.Pro -> if (_isPro.value) "active · paid once, yours forever" else "$39 once · yours forever"134        CardId.Protection ->135            "${if (s.breachMonitoring) "breaches watched" else "breach watch off"} · manual lock"136        CardId.Vault ->137            "$entriesCount ${if (entriesCount == 1) "entry" else "entries"} · backups, history, cleanup"138        CardId.Sync -> if (_isPro.value) "pair by chirp, keep in step" else "Pro · encrypted device pairing"139        CardId.Appearance -> "${s.theme} · ${s.accentColor} · ${s.textSize}"140        CardId.Shortcuts -> "bindings · what your fingers know"141        CardId.Feedback -> "tell us what would make it better"142    }143}