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.isCard26272829303132object AutofillResponseBuilder {3334 35363738 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 49505152535455 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 6263646566676869 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 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 100101102103104 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 115116117118119 120121122123124125126 internal fun chunkOtpForDisplay(code: String): String {127 if (code.length != 6 || !code.all { it.isDigit() }) return code128 return code.chunked(3).joinToString(" ")129 }130131 132133134135136137138139140 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 152 153 154 155 156 157 158 159 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 195196197198 fun datasetFor(199 context: Context,200 parsed: ParsedStructure,201 entry: VaultEntry,202 inlineSpec: android.widget.inline.InlinePresentationSpec?,203 privatePreview: Boolean,204 ): Dataset? {205 206 207 208 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 246 247 248 249 250 251 252 if (fillingOnlyOtp) put(parsed.otpId, otpCode)253 254 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 266267268269270271272273274275276 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 311312313314 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 358359360361362363364365 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 378379380381382 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 399400401402403404405406407408 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 435 436 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 449 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 475 null476 }477478 479480481482483484485486487488489490 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 505 506 507 508 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}