AssistStructureParser.kt

9.8 KB · raw

1package com.peachpasswords.autofill23import android.app.assist.AssistStructure4import android.text.InputType5import android.view.View6import android.view.autofill.AutofillId78/**9* The autofillable fields discovered in one [AssistStructure], plus the origin10* Android authenticated for ranking vault entries.11 *12 * Origin verification was removed (queue #3, June 2026-08-02): matches are13 * ranked by [originDomains] (the page domain, or a native app's app-link14 * domains) and [appTitle] (a native app's display label), with no caller-trust15 * gate. [originDomains]/[appTitle] are populated by the service, not the parser.16*/17data class ParsedStructure(18    val usernameId: AutofillId? = null,19    val emailId: AutofillId? = null,20    val passwordId: AutofillId? = null,21    val otpId: AutofillId? = null,22    val usernameValue: String? = null,23    val emailValue: String? = null,24    val passwordValue: String? = null,25    val otpValue: String? = null,26    val passwordPolicy: PasswordPolicy? = null,27    val isNewPassword: Boolean = false,28    val webDomain: String? = null,29    val packageName: String? = null,30    val appTitle: String? = null,31    val originDomains: List<String> = emptyList(),32    val cardNumberId: AutofillId? = null,33    val cardExpMonthId: AutofillId? = null,34    val cardExpYearId: AutofillId? = null,35    val cardExpDateId: AutofillId? = null,36    val cardCvcId: AutofillId? = null,37    val cardNameId: AutofillId? = null,38) {39    /** The id we put the account identifier into — email preferred, else username. */40    val identityId: AutofillId? get() = emailId ?: usernameId41    val hasUsableField: Boolean get() = passwordId != null || identityId != null || otpId != null || hasCardField42    val hasCardField: Boolean get() = cardNumberId != null || cardExpMonthId != null ||43        cardExpYearId != null || cardExpDateId != null || cardCvcId != null || cardNameId != null44    /** Best label to rank entries against. */45    val origin: String? get() = webDomain ?: packageName46}4748/**49 * Walks an [AssistStructure] to classify username/email/password/OTP/card fields.50 * Mirrors the browser content-script's field detection: trust explicit autofill51 * hints first, then fall back to input-type and id/hint keyword heuristics so52 * unannotated login forms still work.53 */54object AssistStructureParser {5556    fun parse(structure: AssistStructure): ParsedStructure {57        // View-node package ids are supplied by the foreground app; the framework-owned58        // activity component is the authenticated caller identity.59        var result = ParsedStructure(60            packageName = authenticatedPackageName(structure.activityComponent?.packageName),61        )62        val windows = structure.windowNodeCount63        for (i in 0 until windows) {64            val root = structure.getWindowNodeAt(i).rootViewNode65            result = traverse(root, result)66        }67        return result68    }6970    private fun traverse(node: AssistStructure.ViewNode, acc: ParsedStructure): ParsedStructure {71        var result = acc72        if (result.webDomain == null && !node.webDomain.isNullOrBlank()) {73            result = result.copy(webDomain = node.webDomain)74        }7576        val id = node.autofillId77        if (id != null && isFillable(node)) {78            val value = node.autofillValue?.takeIf { it.isText }?.textValue?.toString()79                ?: node.text?.toString()80            result = when (classify(node)) {81                FieldKind.PASSWORD -> if (result.passwordId == null) {82                    val attrs = htmlAttributes(node)83                    result.copy(84                        passwordId = id,85                        passwordValue = value,86                        passwordPolicy = PasswordPolicy.fromHtmlAttributes(attrs)87                            .takeIf { it.minLength != null || it.maxLength != null },88                        isNewPassword = attrs["autocomplete"]89                            ?.contains("new-password", ignoreCase = true) == true,90                    )91                } else result92                FieldKind.USERNAME -> if (result.usernameId == null) result.copy(usernameId = id, usernameValue = value) else result93                FieldKind.EMAIL -> if (result.emailId == null) result.copy(emailId = id, emailValue = value) else result94                FieldKind.OTP -> if (result.otpId == null) result.copy(otpId = id, otpValue = value) else result95                FieldKind.CARD_NUMBER -> if (result.cardNumberId == null) result.copy(cardNumberId = id) else result96                FieldKind.CARD_EXP_MONTH -> if (result.cardExpMonthId == null) result.copy(cardExpMonthId = id) else result97                FieldKind.CARD_EXP_YEAR -> if (result.cardExpYearId == null) result.copy(cardExpYearId = id) else result98                FieldKind.CARD_EXP_DATE -> if (result.cardExpDateId == null) result.copy(cardExpDateId = id) else result99                FieldKind.CARD_CVC -> if (result.cardCvcId == null) result.copy(cardCvcId = id) else result100                FieldKind.CARD_NAME -> if (result.cardNameId == null) result.copy(cardNameId = id) else result101                FieldKind.NONE -> result102            }103        }104105        for (i in 0 until node.childCount) {106            result = traverse(node.getChildAt(i), result)107        }108        return result109    }110111    private fun isFillable(node: AssistStructure.ViewNode): Boolean =112        node.autofillType == View.AUTOFILL_TYPE_TEXT &&113            node.visibility == View.VISIBLE114115    /**116     * A web field's HTML attributes (minlength/maxlength/pattern/autocomplete…),117     * lower-cased by key. Empty for native views — [ViewNode.getHtmlInfo] is only118     * populated for web content, so policy detection degrades to "no constraint".119     */120    private fun htmlAttributes(node: AssistStructure.ViewNode): Map<String, String> {121        val info = node.htmlInfo ?: return emptyMap()122        val out = mutableMapOf<String, String>()123        for (attr in info.attributes.orEmpty()) {124            val key = attr.first?.lowercase() ?: continue125            val value = attr.second ?: continue126            out[key] = value127        }128        return out129    }130131    private enum class FieldKind { USERNAME, EMAIL, PASSWORD, OTP, CARD_NUMBER, CARD_EXP_MONTH, CARD_EXP_YEAR, CARD_EXP_DATE, CARD_CVC, CARD_NAME, NONE }132133    private fun classify(node: AssistStructure.ViewNode): FieldKind {134        node.autofillHints?.forEach { hint ->135            when (hint.lowercase()) {136                View.AUTOFILL_HINT_PASSWORD, "password" -> return FieldKind.PASSWORD137                View.AUTOFILL_HINT_USERNAME, "username" -> return FieldKind.USERNAME138                View.AUTOFILL_HINT_EMAIL_ADDRESS, "email", "emailaddress" -> return FieldKind.EMAIL139                "otp", "smsotpcode", "2facode" -> return FieldKind.OTP140                View.AUTOFILL_HINT_CREDIT_CARD_NUMBER, "creditcardnumber", "ccnumber" -> return FieldKind.CARD_NUMBER141                View.AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH, "creditcardexpirationmonth" -> return FieldKind.CARD_EXP_MONTH142                View.AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR, "creditcardexpirationyear" -> return FieldKind.CARD_EXP_YEAR143                View.AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE, "creditcardexpirationdate" -> return FieldKind.CARD_EXP_DATE144                View.AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE, "creditcardsecuritycode", "ccsecuritycode" -> return FieldKind.CARD_CVC145            }146        }147148        val type = node.inputType149        val isPasswordType = type and InputType.TYPE_MASK_VARIATION == InputType.TYPE_TEXT_VARIATION_PASSWORD ||150            type and InputType.TYPE_MASK_VARIATION == InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD ||151            type and InputType.TYPE_MASK_VARIATION == InputType.TYPE_NUMBER_VARIATION_PASSWORD152        if (isPasswordType) return FieldKind.PASSWORD153154        val haystack = listOfNotNull(node.idEntry, node.hint, node.text?.toString())155            .joinToString(" ").lowercase()156        return when {157            haystack.isBlank() -> FieldKind.NONE158            Regex("\\b(otp|2fa|mfa|one[- ]?time|verification code|auth code)\\b").containsMatchIn(haystack) -> FieldKind.OTP159            haystack.contains("password") || haystack.contains("passwd") || haystack.contains("pwd") -> FieldKind.PASSWORD160            haystack.contains("email") || haystack.contains("e-mail") -> FieldKind.EMAIL161            haystack.contains("user") || haystack.contains("login") || haystack.contains("account") -> FieldKind.USERNAME162            CARD_NUMBER_RX.containsMatchIn(haystack) -> FieldKind.CARD_NUMBER163            CARD_EXP_MONTH_RX.containsMatchIn(haystack) -> FieldKind.CARD_EXP_MONTH164            CARD_EXP_YEAR_RX.containsMatchIn(haystack) -> FieldKind.CARD_EXP_YEAR165            CARD_EXP_DATE_RX.containsMatchIn(haystack) -> FieldKind.CARD_EXP_DATE166            CARD_CVC_RX.containsMatchIn(haystack) -> FieldKind.CARD_CVC167            CARD_NAME_RX.containsMatchIn(haystack) -> FieldKind.CARD_NAME168            else -> FieldKind.NONE169        }170    }171172    private val CARD_NUMBER_RX = Regex("\\b(card\\s*number|credit\\s*card|card\\s*no|pan|cc\\s*num)\\b")173    private val CARD_EXP_MONTH_RX = Regex("\\b(exp\\s*month|expiration\\s*month|expiry\\s*month)\\b")174    private val CARD_EXP_YEAR_RX = Regex("\\b(exp\\s*year|expiration\\s*year|expiry\\s*year)\\b")175    private val CARD_EXP_DATE_RX = Regex("\\b(exp\\s*date|expiration\\s*date|expiry\\s*date|exp\\b)")176    private val CARD_CVC_RX = Regex("\\b(cvc|cvv|security\\s*code|card\\s*code)\\b")177    private val CARD_NAME_RX = Regex("\\b(cardholder|card\\s*holder|name\\s*on\\s*card|card\\s*name)\\b")178}179180/**181 * The framework-owned activity component is the caller identity. Never infer182 * the package from a view node or an autofill hint: those are host-controlled183 * form metadata and cannot authenticate an origin.184 */185internal fun authenticatedPackageName(packageName: String?): String? =186    packageName?.takeIf { it.isNotBlank() }