EntryEditViewModel.kt

18.0 KB · raw

1package com.peachpasswords.ui.vault23import android.content.Context4import com.peachpasswords.shared.PeachClipboard5import androidx.lifecycle.SavedStateHandle6import androidx.lifecycle.ViewModel7import androidx.lifecycle.viewModelScope8import com.peachpasswords.license.LicenseRepository9import com.peachpasswords.vault.PasswordGenerator10import com.peachpasswords.vault.PasswordHistoryItem11import com.peachpasswords.vault.Canary12import com.peachpasswords.vault.VaultEntry13import com.peachpasswords.vault.VaultRepository14import dagger.hilt.android.lifecycle.HiltViewModel15import dagger.hilt.android.qualifiers.ApplicationContext16import kotlinx.coroutines.flow.MutableStateFlow17import kotlinx.coroutines.flow.StateFlow18import kotlinx.coroutines.flow.asStateFlow19import kotlinx.coroutines.flow.update20import kotlinx.coroutines.Dispatchers21import kotlinx.coroutines.launch22import kotlinx.coroutines.withContext23import okhttp3.MediaType.Companion.toMediaType24import okhttp3.OkHttpClient25import okhttp3.Request26import okhttp3.RequestBody.Companion.toRequestBody27import javax.inject.Inject2829data class EditForm(30    val type: String = "login",31    val title: String = "",32    val username: String = "",33    val email: String = "",34    val password: String = "",35    val url: String = "",36    val additionalUrls: List<String> = emptyList(),37    val totp: String = "",38    val notes: String = "",39    val cardNickname: String = "",40    val cardNumber: String = "",41    val cardholderName: String = "",42    val expiry: String = "",        // "MM/YY" or "MM/YYYY"; split into expMonth/expYear on save43    val cvc: String = "",44    val showCvc: Boolean = false,45    val cardNetwork: String = "unknown",46    val tags: List<String> = emptyList(),47    val canary: Canary? = null,48    val canaryMessage: String? = null,49    val canaryTesting: Boolean = false,50    val showPassword: Boolean = false,51    val generatorOpen: Boolean = false,52    val genCopied: Boolean = false,53    val history: List<PasswordHistoryItem> = emptyList(),54    val showHistory: Boolean = false,55    val genLength: Int = BROWSER_ADD_GENERATOR_LENGTH,56    val genUpper: Boolean = true,57    val genLower: Boolean = true,58    val genNumbers: Boolean = true,59    val genSymbols: Boolean = true,60    val saving: Boolean = false,61    val error: String? = null,62    val showTotp: Boolean = false,63    val showNotes: Boolean = false,64)6566@HiltViewModel67class EntryEditViewModel @Inject constructor(68    private val vault: VaultRepository,69    @ApplicationContext private val appContext: Context,70    private val license: LicenseRepository,71    savedStateHandle: SavedStateHandle,72) : ViewModel() {73    private val id: String? = savedStateHandle.get<String>("id")?.takeIf { it.isNotBlank() }74    val isNew: Boolean = id == null75    private val existing: VaultEntry? = id?.let { vault.getEntry(it) }76    val isPro: Boolean = license.isProActive()77    private val canaryClient by lazy { OkHttpClient() }7879    /**80     * A note authored in the browser is HTML; the form edits its markup form and81     * writes the tags back, so editing a login's notes here cannot flatten them.82     */83    private val notesAreHtml: Boolean = isNoteHtml(existing?.notes.orEmpty())8485    private fun notesForStorage(edited: String): String? =86        noteStorageText(edited, notesAreHtml).ifBlank { null }8788    // Prefill values arrive on the EntryEdit route when the user follows the89    // autofill picker's "+ Create new entry" path. Only apply to fresh entries90    // — editing an existing entry must not be silently overwritten.91    private val prefillUrl: String? = savedStateHandle.get<String>("prefillUrl")?.takeIf { it.isNotBlank() }92    private val prefillUsername: String? = savedStateHandle.get<String>("prefillUsername")?.takeIf { it.isNotBlank() }93    private val prefillEmail: String? = savedStateHandle.get<String>("prefillEmail")?.takeIf { it.isNotBlank() }9495    private val _form = MutableStateFlow(96        existing?.let {97            EditForm(98                type = it.type ?: "login",99                title = it.title,100                username = it.username.orEmpty(),101                email = it.email.orEmpty(),102                password = it.password.orEmpty(),103                url = it.url.orEmpty(),104                additionalUrls = it.additionalUrls.orEmpty(),105                totp = it.totp.orEmpty(),106                notes = noteEditorText(it.notes.orEmpty()),107                cardNickname = it.cardNickname.orEmpty(),108                cardNumber = CardFieldUtils.formatPan(it.cardNumber.orEmpty()),109                cardholderName = it.cardholderName.orEmpty(),110                expiry = CardFieldUtils.displayExpiry(it.expMonth, it.expYear),111                cvc = it.cvc.orEmpty(),112                cardNetwork = it.cardNetwork ?: CardFieldUtils.detectNetwork(it.cardNumber.orEmpty()),113                tags = it.tags.orEmpty(),114                canary = it.canary,115                history = it.passwordHistory.orEmpty(),116                showTotp = !it.totp.isNullOrBlank(),117                showNotes = !it.notes.isNullOrBlank(),118            )119        } ?: EditForm(120            password = generateEditPassword(BROWSER_ADD_GENERATOR_LENGTH),121            url = prefillUrl.orEmpty(),122            username = prefillUsername.orEmpty(),123            email = prefillEmail.orEmpty(),124        ),125    )126    val form: StateFlow<EditForm> = _form.asStateFlow()127128    /** Browser AddView parity: field-specific identity suggestions, frequency-sorted. */129    val usernameSuggestions: StateFlow<List<String>> =130        MutableStateFlow(identitySuggestionsFor(vault.getActiveEntries(), IdentityField.Username)).asStateFlow()131132    val emailSuggestions: StateFlow<List<String>> =133        MutableStateFlow(identitySuggestionsFor(vault.getActiveEntries(), IdentityField.Email)).asStateFlow()134135    fun setType(t: String) = _form.update { it.copy(type = t) }136137    fun setTitle(v: String) = _form.update { it.copy(title = v, error = null) }138    fun setUsername(v: String) = _form.update { it.copy(username = v) }139    fun setEmail(v: String) = _form.update { it.copy(email = v) }140    fun setPassword(v: String) = _form.update { it.copy(password = v) }141    fun setUrl(v: String) = _form.update { it.copy(url = v) }142    fun setAdditionalUrl(index: Int, v: String) = _form.update { form ->143        form.copy(additionalUrls = form.additionalUrls.toMutableList().also { it[index] = v })144    }145    fun addAdditionalUrl() = _form.update { form ->146        if (form.additionalUrls.size >= MAX_ADDITIONAL_URLS) form147        else form.copy(additionalUrls = form.additionalUrls + "")148    }149    fun removeAdditionalUrl(index: Int) = _form.update { form ->150        form.copy(additionalUrls = form.additionalUrls.toMutableList().also { it.removeAt(index) })151    }152    fun setTotp(v: String) = _form.update { it.copy(totp = v) }153    fun setNotes(v: String) = _form.update { it.copy(notes = v) }154    fun revealTotp() = _form.update { it.copy(showTotp = true) }155    fun revealNotes() = _form.update { it.copy(showNotes = true) }156    fun setCardNickname(v: String) = _form.update { it.copy(cardNickname = v, error = null) }157    fun setCardNumber(v: String) = _form.update {158        val formatted = CardFieldUtils.formatPan(v)159        it.copy(cardNumber = formatted, cardNetwork = CardFieldUtils.detectNetwork(formatted), error = null)160    }161    fun setCardholderName(v: String) = _form.update { it.copy(cardholderName = v, error = null) }162    fun setExpiry(v: String) = _form.update { it.copy(expiry = CardFieldUtils.formatExpiry(v), error = null) }163    fun setCvc(v: String) = _form.update {164        it.copy(cvc = v.filter { c -> c.isDigit() }.take(CardFieldUtils.cvcMaxDigits(it.cardNetwork)))165    }166    fun toggleShowCvc() = _form.update { it.copy(showCvc = !it.showCvc) }167168    val allTags: List<String> = vault.getDistinctTags()169    fun addTag(raw: String) = _form.update { f ->170        val tag = raw.trim().lowercase().take(32)171        if (tag.isEmpty() || f.tags.size >= 10 || f.tags.any { it == tag }) f172        else f.copy(tags = f.tags + tag)173    }174    fun removeTag(tag: String) = _form.update { it.copy(tags = it.tags - tag) }175176    fun setCanary(enabled: Boolean, webhookUrl: String, label: String) {177        if (enabled && existing?.canary == null && !license.isProActive()) {178            _form.update { it.copy(canaryMessage = "Canary entries require Peach Pro") }179            return180        }181        _form.update { form ->182            form.copy(183                canary = if (enabled) {184                    Canary(185                        webhookUrl = webhookUrl.trim(),186                        label = label.trim().ifBlank { null },187                        lastPinged = form.canary?.lastPinged,188                        pingCount = form.canary?.pingCount,189                    )190                } else {191                    null192                },193                canaryMessage = null,194            )195        }196    }197198    fun testCanary(webhookUrl: String) {199        val url = webhookUrl.trim()200        if (!isAllowedCanaryWebhookUrl(url)) {201            _form.update { it.copy(canaryMessage = "enter a public HTTPS webhook URL") }202            return203        }204        viewModelScope.launch {205            _form.update { it.copy(canaryTesting = true, canaryMessage = null) }206            val result = runCatching {207                withContext(Dispatchers.IO) {208                    val body = """209                        {"event":"peach_canary_test","entry":${canaryJsonString(_form.value.title)},"trigger":"test","timestamp":${canaryJsonString(java.time.Instant.now().toString())},"source":"peach-android"}210                    """.trimIndent().toRequestBody("application/json".toMediaType())211                    val request = Request.Builder().url(url).post(body).build()212                    canaryClient.newCall(request).execute().use { it.isSuccessful }213                }214            }.getOrDefault(false)215            _form.update { it.copy(canaryTesting = false, canaryMessage = if (result) "sent" else "failed - check URL") }216        }217    }218219    fun toggleShowPassword() = _form.update { it.copy(showPassword = !it.showPassword) }220    fun toggleGenerator() = _form.update { form ->221        val opening = !form.generatorOpen222        val next = form.copy(generatorOpen = opening, showHistory = false)223        if (opening && next.password.isBlank()) next.withGeneratedPassword() else next224    }225    fun toggleHistory() = _form.update { it.copy(showHistory = !it.showHistory, generatorOpen = false) }226227    /** Restore a past password into the editor; the save flow records the swap. */228    fun restorePassword(pw: String) =229        _form.update { it.copy(password = pw, showPassword = true, showHistory = false) }230231    /** Copy the current generated/typed password to the clipboard with a drain latch. */232    fun copyGenerated() {233        val pw = _form.value.password234        if (pw.isEmpty()) return235        PeachClipboard.copy(appContext, "peach", pw)236        viewModelScope.launch {237            _form.update { it.copy(genCopied = true) }238            kotlinx.coroutines.delay(1200)239            _form.update { it.copy(genCopied = false) }240        }241    }242243    fun copyHistoryPassword(pw: String) {244        PeachClipboard.copy(appContext, "peach", pw)245    }246    fun setGenLength(n: Int) = _form.update { it.copy(genLength = n.coerceIn(8, 128)).withGeneratedPassword() }247    fun setGenUpper(b: Boolean) = _form.update { it.copy(genUpper = b).withGeneratedPassword() }248    fun setGenLower(b: Boolean) = _form.update { it.copy(genLower = b).withGeneratedPassword() }249    fun setGenNumbers(b: Boolean) = _form.update { it.copy(genNumbers = b).withGeneratedPassword() }250    fun setGenSymbols(b: Boolean) = _form.update { it.copy(genSymbols = b).withGeneratedPassword() }251252    fun generate() {253        _form.update { it.withGeneratedPassword() }254    }255256    fun useGeneratedPassword() = _form.update { it.copy(generatorOpen = false, showPassword = false) }257258    fun save(onDone: () -> Unit) {259        val f = _form.value260        if (f.saving) return261        if (f.title.isBlank()) {262            _form.update { it.copy(error = "title is required") }263            return264        }265        if (f.type == "card" && (f.cardNumber.isBlank() || f.cardholderName.isBlank())) {266            _form.update { it.copy(error = "Cardholder name and card number are required") }267            return268        }269        if (f.canary != null) {270            if (existing?.canary == null && !license.isProActive()) {271                _form.update { it.copy(error = "Canary entries require Peach Pro") }272                return273            }274            if (!isAllowedCanaryWebhookUrl(f.canary.webhookUrl)) {275                _form.update { it.copy(error = "enter a public HTTPS webhook URL") }276                return277            }278        }279        _form.update { it.copy(saving = true, error = null) }280        viewModelScope.launch {281            runCatching {282                if (isNew) {283                    vault.addEntry(284                        VaultEntry(285                            id = "", type = f.type, title = f.title.trim(),286                            username = f.username.ifBlank { null },287                            email = f.email.ifBlank { null },288                            password = f.password.ifBlank { null },289                            url = f.url.ifBlank { null },290                            additionalUrls = f.additionalUrls291                                .map { it.trim() }.filter { it.isNotBlank() }292                                .ifEmpty { null },293                            totp = f.totp.ifBlank { null },294                            notes = notesForStorage(f.notes),295                            cardNickname = f.cardNickname.ifBlank { null },296                            cardNumber = f.cardNumber.filter { it.isDigit() }.ifBlank { null },297                            cardholderName = f.cardholderName.ifBlank { null },298                            expMonth = f.expiry.filter { it.isDigit() }.take(2).ifBlank { null },299                            expYear = f.expiry.filter { it.isDigit() }.drop(2).take(4).ifBlank { null },300                            cvc = f.cvc.ifBlank { null },301                            cardNetwork = f.cardNetwork.takeIf { it != "unknown" },302                            tags = f.tags.ifEmpty { null },303                            canary = f.canary,304                            createdAt = 0, modifiedAt = 0,305                        ),306                    )307                } else {308                    vault.updateEntry(309                        existing!!.copy(310                            type = f.type, title = f.title.trim(),311                            username = f.username.ifBlank { null },312                            email = f.email.ifBlank { null },313                            password = f.password.ifBlank { null },314                            url = f.url.ifBlank { null },315                            additionalUrls = f.additionalUrls316                                .map { it.trim() }.filter { it.isNotBlank() }317                                .ifEmpty { null },318                            totp = f.totp.ifBlank { null },319                            notes = notesForStorage(f.notes),320                            cardNickname = f.cardNickname.ifBlank { null },321                            cardNumber = f.cardNumber.filter { it.isDigit() }.ifBlank { null },322                            cardholderName = f.cardholderName.ifBlank { null },323                            expMonth = f.expiry.filter { it.isDigit() }.take(2).ifBlank { null },324                            expYear = f.expiry.filter { it.isDigit() }.drop(2).take(4).ifBlank { null },325                            cvc = f.cvc.ifBlank { null },326                            cardNetwork = f.cardNetwork.takeIf { it != "unknown" },327                            tags = f.tags.ifEmpty { null },328                            canary = f.canary,329                        ),330                    )331                }332            }.onSuccess { onDone() }333                .onFailure { e -> _form.update { it.copy(saving = false, error = e.message ?: "save failed") } }334        }335    }336}337338private fun canaryJsonString(value: String): String =339    "\"" + value340        .replace("\\", "\\\\")341        .replace("\"", "\\\"")342        .replace("\n", "\\n")343        .replace("\r", "\\r") + "\""344345internal const val BROWSER_ADD_GENERATOR_LENGTH = 64346347private fun EditForm.withGeneratedPassword(): EditForm =348    copy(349        password = generateEditPassword(350            length = genLength,351            upper = genUpper,352            lower = genLower,353            numbers = genNumbers,354            symbols = genSymbols,355        ),356        showPassword = true,357    )358359private fun generateEditPassword(360    length: Int,361    upper: Boolean = true,362    lower: Boolean = true,363    numbers: Boolean = true,364    symbols: Boolean = true,365): String =366    PasswordGenerator.generate(367        PasswordGenerator.Options(368            length = length,369            includeUppercase = upper,370            includeLowercase = lower,371            includeNumbers = numbers,372            includeSymbols = symbols,373        ),374    )375376internal enum class IdentityField { Username, Email }377378data class IdentitySuggestion(val value: String, val count: Int)379380internal fun identitySuggestionsFor(entries: List<VaultEntry>, field: IdentityField): List<String> {381    return identitySuggestionCounts(entries, field).map { it.value }382}383384internal fun identitySuggestionCounts(385    entries: List<VaultEntry>,386    field: IdentityField,387): List<IdentitySuggestion> {388    val buckets = linkedMapOf<String, Pair<String, Int>>()389390    fun add(value: String) {391        val trimmed = value.trim()392        if (trimmed.isEmpty()) return393        val key = trimmed.lowercase()394        val current = buckets[key]395        buckets[key] = (current?.first ?: trimmed) to ((current?.second ?: 0) + 1)396    }397398    entries.filter { it.deletedAt == null }.forEach { entry ->399        listOfNotNull(entry.username, entry.email).forEach { value ->400            val trimmed = value.trim()401            if (trimmed.isNotEmpty() && (trimmed.contains("@") == (field == IdentityField.Email))) add(trimmed)402        }403    }404405    return buckets.values406        .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })407        .map { IdentitySuggestion(it.first, it.second) }408        .take(8)409}