AutofillResponseBuilder.kt

23.0 KB · raw

1package com.peachpasswords.autofill23import android.annotation.SuppressLint4import android.app.PendingIntent5import android.content.Context6import android.os.Build7import android.service.autofill.Dataset8import android.service.autofill.InlinePresentation9import android.view.autofill.AutofillId10import android.view.autofill.AutofillValue11import android.widget.RemoteViews12import androidx.annotation.RequiresApi13import android.graphics.Bitmap14import android.graphics.Canvas15import android.graphics.Paint16import android.graphics.drawable.Icon17import android.util.LruCache18import androidx.autofill.inline.v1.InlineSuggestionUi19import androidx.autofill.inline.UiVersions20import com.peachpasswords.R21import com.peachpasswords.shared.extractDomain22import com.peachpasswords.vault.PasswordGenerator23import com.peachpasswords.vault.TOTPGenerator24import com.peachpasswords.vault.VaultEntry25import com.peachpasswords.vault.isCard2627/**28 * Turns parsed form fields + vault entries into autofill [Dataset]s — the menu29 * RemoteViews row, the inline keyboard chip, and the actual field values.30 * TOTP is filled as a freshly-generated code; the seed never leaves the vault.31 */32object AutofillResponseBuilder {3334    /**35     * Registrable-domain matching. Missing, malformed, local, and IP origins36     * return no entries (there is nothing to rank against).37     */38    data class MatchResult(val hits: List<VaultEntry>, val rest: List<VaultEntry>) {39        val all: List<VaultEntry> get() = hits + rest40    }4142    fun matchEntries(entries: List<VaultEntry>, origin: String?): MatchResult {43        val originDomain = origin?.let(::extractDomain)44            ?: return MatchResult(emptyList(), emptyList())45        return matchDomains(entries, setOf(originDomain))46    }4748    /**49     * Rank entries for the already-resolved origin. The service verifies web50     * caller identity before populating web domains. Native callers match on51     * their verified app-link domains plus an explicit package-name52     * association — never on their display label, which any app can choose53     * freely (PAI-2026-001). Blank origins match nothing.54     */55    fun matchEntries(entries: List<VaultEntry>, parsed: ParsedStructure): MatchResult {56        val byDomain = matchDomains(entries, parsed.originDomains.mapNotNull(::extractDomain).toSet()).hits57        val byPackage = nativePackageMatches(entries, parsed)58        return MatchResult((byDomain + byPackage).distinctBy { it.id }, emptyList())59    }6061    /**62     * An entry the user associated with this exact package — the save paths63     * store the calling package as the entry's url. Exact match, not domain64     * matching: two packages can share a registrable domain under the public65     * suffix list (com.a.example.app and com.b.example.app both reduce to66     * example.app), so anything weaker would re-open the confusion the label67     * match had.68     */69    private fun nativePackageMatches(entries: List<VaultEntry>, parsed: ParsedStructure): List<VaultEntry> {70        val packageName = parsed.packageName?.takeIf { it.isNotBlank() } ?: return emptyList()71        if (parsed.webDomain != null) return emptyList()72        val signerDigests = parsed.nativeSignerDigests73        if (signerDigests.isNullOrEmpty()) return emptyList()74        return entries.filter { entry ->75            (entry.url == packageName || entry.additionalUrls.orEmpty().any { it == packageName }) &&76                entry.nativeSignerDigests.orEmpty().any { it in signerDigests }77        }78    }7980    private fun matchDomains(entries: List<VaultEntry>, domains: Set<String>): MatchResult =81        MatchResult(82            hits = entries.filter { entry ->83                domains.any { domain -> entry.matchesOriginDomain(domain) }84            },85            rest = emptyList(),86        )8788    /** Distribute a TOTP code character-by-character over [boxCount] split boxes. */89    internal fun otpDigitsFor(boxCount: Int, code: String): List<String> =90        code.filter { !it.isWhitespace() }.take(boxCount).map { it.toString() }9192    private fun VaultEntry.matchesOriginDomain(originDomain: String): Boolean =93        sequenceOf(url)94            .plus(additionalUrls.orEmpty().asSequence())95            .filterNotNull()96            .mapNotNull(::extractDomain)97            .any { it == originDomain }9899    /**100     * What a suggestion row or keyboard chip shows about an entry.101     * [iconSource] seeds the chip monogram; null keeps the Peach mark102     * (always the case in privacy mode — initials would leak titles too).103     */104    enum class FillMode { LOGIN, OTP_FILL }105106    data class PreviewLabels(107        val title: String,108        val subtitle: String,109        val iconSource: String?,110        val fillMode: FillMode = FillMode.LOGIN,111        val endIcon: Icon? = null,112    )113114    /**115     * Privacy previews: with [privatePreview] the rows and chips render only116     * the Peach brand and the caller's domain — no entry titles or usernames117     * in the IME's suggestion strip. The values still fill on tap.118     */119    /**120     * Chunk a TOTP code for chip readability: "482901" -> "482 901". Alphanumeric121     * codes (Steam-style base32: "JBSWY3DPEHPK3PXP") and codes longer than 6 digits122     * pass through unchanged — a 7-digit code is rarely grouped, and stripping123     * letters to chunk the digits would mutilate the code. The autofilled value124     * stays the raw code so the form receives what its regex expects.125     */126    internal fun chunkOtpForDisplay(code: String): String {127        if (code.length != 6 || !code.all { it.isDigit() }) return code128        return code.chunked(3).joinToString(" ")129    }130131    /**132     * Build the chip labels for an entry's fill. Pass [FillMode.OTP_FILL] when133     * the dataset fills ONLY an OTP field (no identity/password) so the chip134     * surfaces the actual TOTP code as the title and the literal "2FA" in the135     * subtitle. The entry's favicon/initial on the left already conveys the136     * entry, so a duplicate-name subtitle invites the user to misread the137     * digits as their password. Private preview always wins: digits are never138     * leaked into the chip strip even in this mode.139     */140    fun previewLabels(141        privatePreview: Boolean,142        entry: VaultEntry,143        originDomain: String?,144        fillMode: FillMode = FillMode.LOGIN,145        otpCode: String? = null,146        secondsRemaining: Int? = null,147    ): PreviewLabels = when {148        privatePreview -> PreviewLabels("Peach", originDomain ?: "", null, fillMode)149        fillMode == FillMode.OTP_FILL -> {150            val code = requireNotNull(otpCode) { "otpCode required for OTP_FILL mode" }151            // Subtitle reads "2FA" instead of the entry title so the user can152            // tell a TOTP chip from a password chip at a glance — the entry's153            // favicon/initial on the left already conveys the entry, so a154            // duplicate-name subtitle invites the user to misread the digits155            // as their password. When [secondsRemaining] is known we156            // append the TOTP window countdown (the chip itself is static;157            // a fresh chip with a fresh code is rebuilt on every focus-change158            // FillRequest, so the user only needs to tap off and back into159            // the field to get the next code).160            val subtitle = when {161                secondsRemaining == null -> "2FA"162                secondsRemaining <= 0 -> "2FA · expired"163                else -> "2FA · ${secondsRemaining}s"164            }165            val endIcon = secondsRemaining?.let { OtpCountdownDot.icon(it) }166            PreviewLabels(167                title = chunkOtpForDisplay(code),168                subtitle = subtitle,169                iconSource = entry.title,170                fillMode = FillMode.OTP_FILL,171                endIcon = endIcon,172            )173        }174        else -> PreviewLabels(175            entry.title,176            entry.username ?: entry.email ?: entry.url?.let(::extractDomain) ?: "",177            entry.title,178            FillMode.LOGIN,179        )180    }181182    fun rowFor(context: Context, labels: PreviewLabels): RemoteViews =183        RemoteViews(context.packageName, R.layout.autofill_row).apply {184            setTextViewText(R.id.autofill_row_title, labels.title)185            setTextViewText(R.id.autofill_row_subtitle, labels.subtitle)186        }187188    fun simpleRow(context: Context, title: String, subtitle: String): RemoteViews =189        RemoteViews(context.packageName, R.layout.autofill_row).apply {190            setTextViewText(R.id.autofill_row_title, title)191            setTextViewText(R.id.autofill_row_subtitle, subtitle)192        }193194    /**195     * Build a dataset filling the parsed fields from [entry]. Attaches the inline196     * chip when the IME offered a spec (API 30+); otherwise menu-only.197     */198    fun datasetFor(199        context: Context,200        parsed: ParsedStructure,201        entry: VaultEntry,202        inlineSpec: android.widget.inline.InlinePresentationSpec?,203        privatePreview: Boolean,204    ): Dataset? {205        // Generate the TOTP code once and route it to BOTH the chip title (when206        // the dataset fills ONLY an OTP field) and the fill value (always).207        // The FillMode.OTP_FILL chip surfaces the actual digits in the208        // keyboard strip so the user can confirm what they're about to type.209        val otp = entry.totp?.let { TOTPGenerator.generate(it) }210        val otpCode = otp?.code211        val fillingOnlyOtp = parsed.identityId == null &&212            parsed.passwordId == null &&213            parsed.otpId != null &&214            otpCode != null215        val fillMode = if (fillingOnlyOtp) FillMode.OTP_FILL else FillMode.LOGIN216        val labels = previewLabels(217            privatePreview,218            entry,219            parsed.origin?.let(::extractDomain),220            fillMode = fillMode,221            otpCode = if (fillingOnlyOtp) otpCode else null,222            secondsRemaining = otp?.remaining,223        )224        val menu = rowFor(context, labels)225        val inline = if (Build.VERSION.SDK_INT >= 30 && inlineSpec != null) {226            buildInline(context, labels, inlineSpec)227        } else {228            null229        }230231        val builder = Dataset.Builder()232        var filledAny = false233        fun put(id: AutofillId?, value: String?) {234            if (id == null || value.isNullOrEmpty()) return235            val av = AutofillValue.forText(value)236            if (inline != null && Build.VERSION.SDK_INT >= 30) {237                builder.setValue(id, av, menu, inline)238            } else {239                builder.setValue(id, av, menu)240            }241            filledAny = true242        }243        put(parsed.identityId, entry.username ?: entry.email)244        put(parsed.passwordId, entry.password)245        // OTP fill on a multi-field form is handled by [otpDatasetFor] -- a246        // separate dataset with its own chip on the 2FA field. The LOGIN chip247        // intentionally does NOT fill otp here, so the user can verify the248        // code before it lands: "tap github fills email and password, then249        // automatically surfaces the next chip with 2FA code" (continuity250        // 2026-08-05). On an OTP-only form (fillingOnlyOtp) we keep filling251        // from the LOGIN path -- there's no separate chip to defer to.252        if (fillingOnlyOtp) put(parsed.otpId, otpCode)253        // A6: split single-character OTP boxes — one character per box254        // (browser's fillOTPDigitBoxes). Only when no full-code field exists.255        if (parsed.otpId == null && otpCode != null && parsed.otpDigitBoxIds.isNotEmpty()) {256            otpDigitsFor(parsed.otpDigitBoxIds.size, otpCode).forEachIndexed { index, digit ->257                builder.setValue(parsed.otpDigitBoxIds[index], AutofillValue.forText(digit), menu)258            }259            filledAny = true260        }261262        return if (filledAny) builder.build() else null263    }264265    /**266     * A second inline dataset for the 2FA chip: fills ONLY the detected OTP267     * field with a freshly generated TOTP code and renders its chip in268     * [FillMode.OTP_FILL] (title = chunked code, subtitle = "2FA"). The user269     * wanted the LOGIN chip and the 2FA chip as separate affordances:270     * "tap 'github' it fills email and password, then automatically surfaces271     * the next chip with 2FA code" (continuity 2026-08-05). The chip lands on272     * the spec whose autofillId matches [parsed.otpId]; if no spec matches273     * (the framework only offered a single spec on a focused 2FA field, say),274     * the dataset still surfaces in the system menu.275     */276    fun otpDatasetFor(277        context: Context,278        parsed: ParsedStructure,279        entry: VaultEntry,280        inlineSpec: android.widget.inline.InlinePresentationSpec?,281        privatePreview: Boolean,282    ): Dataset? {283        val otpId = parsed.otpId ?: return null284        val otp = entry.totp?.let { TOTPGenerator.generate(it) } ?: return null285        val otpCode = otp.code286        val labels = previewLabels(287            privatePreview = privatePreview,288            entry = entry,289            originDomain = parsed.origin?.let(::extractDomain),290            fillMode = FillMode.OTP_FILL,291            otpCode = otpCode,292            secondsRemaining = otp.remaining,293        )294        val menu = rowFor(context, labels)295        val inline = if (Build.VERSION.SDK_INT >= 30 && inlineSpec != null) {296            buildInline(context, labels, inlineSpec)297        } else {298            null299        }300        val builder = Dataset.Builder()301        val av = AutofillValue.forText(otpCode)302        if (inline != null && Build.VERSION.SDK_INT >= 30) {303            builder.setValue(otpId, av, menu, inline)304        } else {305            builder.setValue(otpId, av, menu)306        }307        return builder.build()308    }309310    /**311     * Build a dataset filling detected card fields from a card [entry].312     * Cards are not domain-matched — any detected card form offers all cards.313     */314    fun cardDatasetFor(315        context: Context,316        parsed: ParsedStructure,317        entry: VaultEntry,318        inlineSpec: android.widget.inline.InlinePresentationSpec?,319        privatePreview: Boolean,320    ): Dataset? {321        if (!entry.isCard()) return null322        val labels = previewLabels(privatePreview, entry, parsed.origin?.let(::extractDomain))323        val menu = rowFor(context, labels)324        val inline = if (Build.VERSION.SDK_INT >= 30 && inlineSpec != null) {325            buildInline(context, labels, inlineSpec)326        } else {327            null328        }329330        val builder = Dataset.Builder()331        var filledAny = false332        fun put(id: AutofillId?, value: String?) {333            if (id == null || value.isNullOrEmpty()) return334            val av = AutofillValue.forText(value)335            if (inline != null && Build.VERSION.SDK_INT >= 30) {336                builder.setValue(id, av, menu, inline)337            } else {338                builder.setValue(id, av, menu)339            }340            filledAny = true341        }342343        val digits = entry.cardNumber?.filter { it.isDigit() }344        put(parsed.cardNumberId, digits)345        put(parsed.cardExpMonthId, entry.expMonth)346        put(parsed.cardExpYearId, entry.expYear)347        if (parsed.cardExpDateId != null && !entry.expMonth.isNullOrEmpty() && !entry.expYear.isNullOrEmpty()) {348            val yy = entry.expYear.takeLast(2)349            put(parsed.cardExpDateId, "${entry.expMonth.padStart(2, '0')}/$yy")350        }351        put(parsed.cardCvcId, entry.cvc)352        put(parsed.cardNameId, entry.cardholderName)353354        return if (filledAny) builder.build() else null355    }356357    /**358     * A "generate strong password" dataset for signup / no-match forms. Fills the359     * detected password field with a freshly generated password sized to the360     * site's [PasswordPolicy] (A3). The standard save flow captures whatever ends361     * up in the password field, so the generated value is offered for save like362     * any other fill. Menu-only (no inline chip) — there is no vault entry to363     * render. Parity for the browser's inline generator on create forms.364     */365    fun generateDatasetFor(context: Context, parsed: ParsedStructure): Dataset? {366        val passwordId = parsed.passwordId ?: return null367        val policy = parsed.passwordPolicy368        val length = policy?.generationLength() ?: PasswordPolicy.DEFAULT_LENGTH369        val password = PasswordGenerator.generate(PasswordGenerator.Options(length = length))370        val note = policy?.constraintNote(length).orEmpty()371        val menu = simpleRow(context, "Generate strong password", note.ifEmpty { "Peach" })372        return Dataset.Builder()373            .setValue(passwordId, AutofillValue.forText(password), menu)374            .build()375    }376377    /**378     * A4 identity helper: a dataset filling ONLY the signup identity field.379     * Email identities prefer the email field, usernames the username field;380     * each falls back to the other when its preferred field is absent.381     */382    fun identityDatasetFor(383        context: Context,384        parsed: ParsedStructure,385        identity: SavedIdentity,386    ): Dataset? {387        val targetId = when (identity.type) {388            IdentityType.EMAIL -> parsed.emailId ?: parsed.usernameId389            IdentityType.USERNAME -> parsed.usernameId ?: parsed.emailId390        } ?: return null391        val subtitle = if (identity.type == IdentityType.EMAIL) "email" else "username"392        val menu = simpleRow(context, identity.value, subtitle)393        return Dataset.Builder()394            .setValue(targetId, AutofillValue.forText(identity.value), menu)395            .build()396    }397398    /**399     * The "Search Peach…" / "Unlock Peach" / "No saved logins for this site"400     * picker chip. The inline chip carries a [PendingIntent] that opens the401     * picker activity directly on tap (system menu row uses [setAuthentication]402     * via [PeachAutofillService.searchPeachDataset (via AutofillResponseBuilder)] for the same effect).403     *404     * Without an attached [InlinePresentation] the dataset would render only405     * in the drop-down menu — the keyboard-row strip would never show the406     * picker, which was the v2.14.1 regression June hit.407     */408    fun searchPeachDataset(409        context: Context,410        parsed: ParsedStructure,411        inlineSpec: android.widget.inline.InlinePresentationSpec?,412        unlocked: Boolean,413        hasMatches: Boolean,414        requestId: Int,415    ): Dataset {416        val labels = if (unlocked) {417            PreviewLabels("Search Peach…", parsed.origin.orEmpty(), null)418        } else {419            PreviewLabels("Unlock Peach", parsed.origin.orEmpty(), null)420        }421        val menu = simpleRow(context, labels.title, labels.subtitle)422        val inline = if (Build.VERSION.SDK_INT >= 30 && inlineSpec != null) {423            buildInline(context, labels, inlineSpec, AutofillIntents.pickerChipPendingIntent(context, parsed, requestId))424        } else {425            null426        }427        val builder = Dataset.Builder(menu)428        val fieldIds = listOfNotNull(429            parsed.identityId, parsed.passwordId, parsed.otpId,430            parsed.cardNumberId, parsed.cardExpMonthId, parsed.cardExpYearId,431            parsed.cardExpDateId, parsed.cardCvcId, parsed.cardNameId,432        ) + parsed.otpDigitBoxIds433        if (inline != null && Build.VERSION.SDK_INT >= 30) {434            // Samsung's inline renderer drops authenticated datasets whose only435            // field values are null. Bind the chip to one credential field with436            // an empty value; authentication still supplies the real dataset.437            fieldIds.firstOrNull()?.let { id ->438                builder.setValue(id, AutofillValue.forText(""), menu, inline)439            }440            fieldIds.drop(1).forEach { id -> builder.setValue(id, null, menu) }441        } else {442            fieldIds.forEach { id -> builder.setValue(id, null, menu) }443        }444        builder.setAuthentication(AutofillIntents.pickerIntentSender(context, parsed, requestId))445        return builder.build()446    }447448    // InlineSuggestionUi.Content.getSlice is @RestrictedApi to androidx, but449    // reading the slice to build an InlinePresentation is the documented usage.450    @SuppressLint("RestrictedApi")451    @RequiresApi(30)452    private fun buildInline(453        context: Context,454        labels: PreviewLabels,455        spec: android.widget.inline.InlinePresentationSpec,456        chipPending: PendingIntent = AutofillIntents.noopChipIntent(context, 0),457    ): InlinePresentation? = try {458        val style = spec.style459        if (!UiVersions.getVersions(style).contains(UiVersions.INLINE_UI_VERSION_1)) {460            null461        } else {462            val startIcon = labels.iconSource?.let { ChipMonogramIcon.icon(it) }463                ?: android.graphics.drawable.Icon.createWithResource(context, R.drawable.ic_peach_mark)464            val slice = InlineSuggestionUi.newContentBuilder(chipPending)465                .setTitle(labels.title)466                .apply { if (labels.subtitle.isNotBlank()) setSubtitle(labels.subtitle) }467                .setStartIcon(startIcon)468                .apply { if (labels.endIcon != null) setEndIcon(labels.endIcon) }469                .build()470                .slice471            InlinePresentation(slice, spec, false)472        }473    } catch (_: Throwable) {474        // A non-conforming IME spec must never crash the fill — degrade to menu.475        null476    }477478    /**479     * Small colored dot rendered as the inline chip's end icon when the 2FA480     * chip is in [FillMode.OTP_FILL] with a known [secondsRemaining].481     *482     * Colors match the urgency: green (>= 10s), amber (5..9s), red (<= 4s483     * or already expired). The chip itself is a static RemoteViews render484     * — once built, no live animation runs; a fresh chip with a fresh485     * code is returned on the next focus-change FillRequest, so the486     * user only needs to tap off the keyboard and back into the 2FA487     * field to get the next code. Cached by color so per-fill alloc is488     * constant.489     */490    private object OtpCountdownDot {491        private const val SIZE_PX = 32492        private const val GREEN = 0xFF6FB07F.toInt()493        private const val AMBER = 0xFFE0A857.toInt()494        private const val RED = 0xFFD8534B.toInt()495        private val cache = LruCache<Int, Icon>(8)496497        fun icon(secondsRemaining: Int): Icon? {498            val color = when {499                secondsRemaining <= 4 -> RED500                secondsRemaining <= 9 -> AMBER501                else -> GREEN502            }503            cache.get(color)?.let { return it }504            // Bitmap creation is a no-op on the JVM test runtime (the505            // android.jar stubs return null for createBitmap). Fail-soft506            // there — the chip still gets the seconds-left text; the507            // colored dot only matters on a real device where the dot508            // is also the glanceable expiry signal the user asked for.509            val icon = runCatching {510                val bm = Bitmap.createBitmap(SIZE_PX, SIZE_PX, Bitmap.Config.ARGB_8888)511                val canvas = Canvas(bm)512                val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color }513                canvas.drawCircle(SIZE_PX / 2f, SIZE_PX / 2f, SIZE_PX / 2f - 2f, paint)514                Icon.createWithBitmap(bm)515            }.getOrNull() ?: return null516            cache.put(color, icon)517            return icon518        }519    }520}