AutofillResponseBuilder.kt

11.2 KB · raw

1package com.peachpasswords.autofill23import android.annotation.SuppressLint4import android.content.Context5import android.os.Build6import android.service.autofill.Dataset7import android.service.autofill.InlinePresentation8import android.view.autofill.AutofillId9import android.view.autofill.AutofillValue10import android.widget.RemoteViews11import androidx.annotation.RequiresApi12import androidx.autofill.inline.v1.InlineSuggestionUi13import androidx.autofill.inline.UiVersions14import com.peachpasswords.R15import com.peachpasswords.shared.extractDomain16import com.peachpasswords.vault.PasswordGenerator17import com.peachpasswords.vault.TOTPGenerator18import com.peachpasswords.vault.VaultEntry19import com.peachpasswords.vault.isCard2021/**22 * Turns parsed form fields + vault entries into autofill [Dataset]s — the menu23 * RemoteViews row, the inline keyboard chip, and the actual field values.24 * TOTP is filled as a freshly-generated code; the seed never leaves the vault.25 */26object AutofillResponseBuilder {2728    /**29     * Registrable-domain matching. Missing, malformed, local, and IP origins30     * return no entries (there is nothing to rank against).31     */32    data class MatchResult(val hits: List<VaultEntry>, val rest: List<VaultEntry>) {33        val all: List<VaultEntry> get() = hits + rest34    }3536    fun matchEntries(entries: List<VaultEntry>, origin: String?): MatchResult {37        val originDomain = origin?.let(::extractDomain)38            ?: return MatchResult(emptyList(), emptyList())39        return matchDomains(entries, setOf(originDomain))40    }4142    /**43     * Rank entries for an origin with no caller-trust gate (origin verification44     * removed, queue #3). Web origins match by the page domain; native apps match45     * by their app-link domains or display title. Blank origins match nothing.46     */47    fun matchEntries(entries: List<VaultEntry>, parsed: ParsedStructure): MatchResult {48        val domains = parsed.originDomains.mapNotNull(::extractDomain).toSet()49        val byDomain = matchDomains(entries, domains).hits50        val appTitle = parsed.appTitle?.trim()51        val byTitle = if (appTitle.isNullOrBlank()) {52            emptyList()53        } else {54            entries.filter { it.title.trim().equals(appTitle, ignoreCase = true) }55        }56        return MatchResult((byDomain + byTitle).distinctBy { it.id }, emptyList())57    }5859    private fun matchDomains(entries: List<VaultEntry>, domains: Set<String>): MatchResult =60        MatchResult(61            hits = entries.filter { entry ->62                domains.any { domain -> entry.matchesOriginDomain(domain) }63            },64            rest = emptyList(),65        )6667    /** Distribute a TOTP code character-by-character over [boxCount] split boxes. */68    internal fun otpDigitsFor(boxCount: Int, code: String): List<String> =69        code.filter { !it.isWhitespace() }.take(boxCount).map { it.toString() }7071    private fun VaultEntry.matchesOriginDomain(originDomain: String): Boolean =72        sequenceOf(url)73            .plus(additionalUrls.orEmpty().asSequence())74            .filterNotNull()75            .mapNotNull(::extractDomain)76            .any { it == originDomain }7778    /** What a suggestion row or keyboard chip shows about an entry. */79    data class PreviewLabels(val title: String, val subtitle: String)8081    /**82     * Privacy previews: with [privatePreview] the rows and chips render only83     * the Peach brand and the caller's domain — no entry titles or usernames84     * in the IME's suggestion strip. The values still fill on tap.85     */86    fun previewLabels(privatePreview: Boolean, entry: VaultEntry, originDomain: String?): PreviewLabels =87        if (privatePreview) {88            PreviewLabels("Peach", originDomain ?: "")89        } else {90            PreviewLabels(entry.title, entry.username ?: entry.email ?: entry.url?.let(::extractDomain) ?: "")91        }9293    fun rowFor(context: Context, labels: PreviewLabels): RemoteViews =94        RemoteViews(context.packageName, R.layout.autofill_row).apply {95            setTextViewText(R.id.autofill_row_title, labels.title)96            setTextViewText(R.id.autofill_row_subtitle, labels.subtitle)97        }9899    fun simpleRow(context: Context, title: String, subtitle: String): RemoteViews =100        RemoteViews(context.packageName, R.layout.autofill_row).apply {101            setTextViewText(R.id.autofill_row_title, title)102            setTextViewText(R.id.autofill_row_subtitle, subtitle)103        }104105    /**106     * Build a dataset filling the parsed fields from [entry]. Attaches the inline107     * chip when the IME offered a spec (API 30+); otherwise menu-only.108     */109    fun datasetFor(110        context: Context,111        parsed: ParsedStructure,112        entry: VaultEntry,113        inlineSpec: android.widget.inline.InlinePresentationSpec?,114        privatePreview: Boolean,115    ): Dataset? {116        val labels = previewLabels(privatePreview, entry, parsed.origin?.let(::extractDomain))117        val menu = rowFor(context, labels)118        val inline = if (Build.VERSION.SDK_INT >= 30 && inlineSpec != null) {119            buildInline(context, labels, inlineSpec)120        } else {121            null122        }123124        val builder = Dataset.Builder()125        var filledAny = false126        fun put(id: AutofillId?, value: String?) {127            if (id == null || value.isNullOrEmpty()) return128            val av = AutofillValue.forText(value)129            if (inline != null && Build.VERSION.SDK_INT >= 30) {130                builder.setValue(id, av, menu, inline)131            } else {132                builder.setValue(id, av, menu)133            }134            filledAny = true135        }136        put(parsed.identityId, entry.username ?: entry.email)137        put(parsed.passwordId, entry.password)138        val otpCode = entry.totp?.let { TOTPGenerator.generateCode(it) }139        put(parsed.otpId, otpCode)140        // A6: split single-character OTP boxes — one character per box141        // (browser's fillOTPDigitBoxes). Only when no full-code field exists.142        if (parsed.otpId == null && otpCode != null && parsed.otpDigitBoxIds.isNotEmpty()) {143            otpDigitsFor(parsed.otpDigitBoxIds.size, otpCode).forEachIndexed { index, digit ->144                builder.setValue(parsed.otpDigitBoxIds[index], AutofillValue.forText(digit), menu)145            }146            filledAny = true147        }148149        return if (filledAny) builder.build() else null150    }151152    /**153     * Build a dataset filling detected card fields from a card [entry].154     * Cards are not domain-matched — any detected card form offers all cards.155     */156    fun cardDatasetFor(157        context: Context,158        parsed: ParsedStructure,159        entry: VaultEntry,160        inlineSpec: android.widget.inline.InlinePresentationSpec?,161        privatePreview: Boolean,162    ): Dataset? {163        if (!entry.isCard()) return null164        val labels = previewLabels(privatePreview, entry, parsed.origin?.let(::extractDomain))165        val menu = rowFor(context, labels)166        val inline = if (Build.VERSION.SDK_INT >= 30 && inlineSpec != null) {167            buildInline(context, labels, inlineSpec)168        } else {169            null170        }171172        val builder = Dataset.Builder()173        var filledAny = false174        fun put(id: AutofillId?, value: String?) {175            if (id == null || value.isNullOrEmpty()) return176            val av = AutofillValue.forText(value)177            if (inline != null && Build.VERSION.SDK_INT >= 30) {178                builder.setValue(id, av, menu, inline)179            } else {180                builder.setValue(id, av, menu)181            }182            filledAny = true183        }184185        val digits = entry.cardNumber?.filter { it.isDigit() }186        put(parsed.cardNumberId, digits)187        put(parsed.cardExpMonthId, entry.expMonth)188        put(parsed.cardExpYearId, entry.expYear)189        if (parsed.cardExpDateId != null && !entry.expMonth.isNullOrEmpty() && !entry.expYear.isNullOrEmpty()) {190            val yy = entry.expYear.takeLast(2)191            put(parsed.cardExpDateId, "${entry.expMonth.padStart(2, '0')}/$yy")192        }193        put(parsed.cardCvcId, entry.cvc)194        put(parsed.cardNameId, entry.cardholderName)195196        return if (filledAny) builder.build() else null197    }198199    /**200     * A "generate strong password" dataset for signup / no-match forms. Fills the201     * detected password field with a freshly generated password sized to the202     * site's [PasswordPolicy] (A3). The standard save flow captures whatever ends203     * up in the password field, so the generated value is offered for save like204     * any other fill. Menu-only (no inline chip) — there is no vault entry to205     * render. Parity for the browser's inline generator on create forms.206     */207    fun generateDatasetFor(context: Context, parsed: ParsedStructure): Dataset? {208        val passwordId = parsed.passwordId ?: return null209        val policy = parsed.passwordPolicy210        val length = policy?.generationLength() ?: PasswordPolicy.DEFAULT_LENGTH211        val password = PasswordGenerator.generate(PasswordGenerator.Options(length = length))212        val note = policy?.constraintNote(length).orEmpty()213        val menu = simpleRow(context, "Generate strong password", note.ifEmpty { "Peach" })214        return Dataset.Builder()215            .setValue(passwordId, AutofillValue.forText(password), menu)216            .build()217    }218219    /**220     * A4 identity helper: a dataset filling ONLY the signup identity field.221     * Email identities prefer the email field, usernames the username field;222     * each falls back to the other when its preferred field is absent.223     */224    fun identityDatasetFor(225        context: Context,226        parsed: ParsedStructure,227        identity: SavedIdentity,228    ): Dataset? {229        val targetId = when (identity.type) {230            IdentityType.EMAIL -> parsed.emailId ?: parsed.usernameId231            IdentityType.USERNAME -> parsed.usernameId ?: parsed.emailId232        } ?: return null233        val subtitle = if (identity.type == IdentityType.EMAIL) "email" else "username"234        val menu = simpleRow(context, identity.value, subtitle)235        return Dataset.Builder()236            .setValue(targetId, AutofillValue.forText(identity.value), menu)237            .build()238    }239240    // InlineSuggestionUi.Content.getSlice is @RestrictedApi to androidx, but241    // reading the slice to build an InlinePresentation is the documented usage.242    @SuppressLint("RestrictedApi")243    @RequiresApi(30)244    private fun buildInline(245        context: Context,246        labels: PreviewLabels,247        spec: android.widget.inline.InlinePresentationSpec,248    ): InlinePresentation? = try {249        val style = spec.style250        if (!UiVersions.getVersions(style).contains(UiVersions.INLINE_UI_VERSION_1)) {251            null252        } else {253            val pending = AutofillIntents.noopChipIntent(context)254            val slice = InlineSuggestionUi.newContentBuilder(pending)255                .setTitle(labels.title)256                .apply { if (labels.subtitle.isNotBlank()) setSubtitle(labels.subtitle) }257                .setStartIcon(android.graphics.drawable.Icon.createWithResource(context, R.drawable.ic_peach_mark))258                .build()259                .slice260            InlinePresentation(slice, spec, false)261        }262    } catch (_: Throwable) {263        // A non-conforming IME spec must never crash the fill — degrade to menu.264        null265    }266}