diff --git a/apps/browser/src/autofill/content/autofill-init.ts b/apps/browser/src/autofill/content/autofill-init.ts index f2c132c4e94..fe60ebbfdf5 100644 --- a/apps/browser/src/autofill/content/autofill-init.ts +++ b/apps/browser/src/autofill/content/autofill-init.ts @@ -8,6 +8,7 @@ import { DomElementVisibilityService } from "../services/abstractions/dom-elemen import { DomQueryService } from "../services/abstractions/dom-query.service"; import { CollectAutofillContentService } from "../services/collect-autofill-content.service"; import InsertAutofillContentService from "../services/insert-autofill-content.service"; +import { DefaultRuleQualificationService } from "../services/rule-qualification.service"; import { AutofillTriageResponse } from "../types/autofill-triage"; import { sendExtensionMessage } from "../utils"; import { EventSecurity } from "../utils/event-security"; @@ -62,6 +63,16 @@ class AutofillInit implements AutofillInitInterface { domQueryService, this.autofillOverlayContentService, ); + // Setter injection breaks the circular dependency. The rule qualification + // service needs the collect service for its heuristic bypass. The collect + // service needs the rule qualification service to qualify matched rules. + this.collectAutofillContentService.setRuleQualificationService( + new DefaultRuleQualificationService( + this.collectAutofillContentService, + domQueryService, + domElementVisibilityService, + ), + ); this.insertAutofillContentService = new InsertAutofillContentService( domElementVisibilityService, this.collectAutofillContentService, diff --git a/apps/browser/src/autofill/services/abstractions/collect-autofill-content.service.ts b/apps/browser/src/autofill/services/abstractions/collect-autofill-content.service.ts index f0d5a1cf4b0..cde5155700c 100644 --- a/apps/browser/src/autofill/services/abstractions/collect-autofill-content.service.ts +++ b/apps/browser/src/autofill/services/abstractions/collect-autofill-content.service.ts @@ -4,6 +4,8 @@ import AutofillForm from "../../models/autofill-form"; import AutofillPageDetails from "../../models/autofill-page-details"; import { ElementWithOpId, FormFieldElement } from "../../types"; +import { InScopeFormsDetection, RuleQualificationService } from "./rule-qualification.service"; + type AutofillFormElements = Map, AutofillForm>; type AutofillFieldElements = Map, AutofillField>; @@ -24,6 +26,26 @@ interface CollectAutofillContentService extends AutofillMonitor { targetedFields: { selector: string; fieldType: string }[], ): Promise; clearCachedTargetingRules(): void; + /** + * Runs the heuristic collection path after clearing the field caches so the + * pass starts fresh. Called by `RuleQualificationService` on the miss path. + * When `cachedInScopeForms.detectedFields` is populated, the bypass reuses + * those detections rather than scanning the same forms again. + */ + collectHeuristicPageDetailsBypass( + cachedInScopeForms?: InScopeFormsDetection, + ): Promise; + /** + * Setter wiring to break the circular dependency between this service and + * the rule qualification service. Called once at DI setup. + */ + setRuleQualificationService(ruleQualificationService: RuleQualificationService): void; + /** + * Returns whether the element is a form field the heuristic collection pass + * would consider fillable. Exposed so the rule qualification service can + * apply the same filter when checking in-scope extras. + */ + isElementFormFieldElement(element: Element): boolean; } export { diff --git a/apps/browser/src/autofill/services/abstractions/rule-qualification.service.ts b/apps/browser/src/autofill/services/abstractions/rule-qualification.service.ts new file mode 100644 index 00000000000..47906d82178 --- /dev/null +++ b/apps/browser/src/autofill/services/abstractions/rule-qualification.service.ts @@ -0,0 +1,39 @@ +import { FormContent } from "@bitwarden/common/autofill/types"; + +import { FillAssistMissReason } from "../../background/fill-assist-event-receiver"; +import AutofillPageDetails from "../../models/autofill-page-details"; +import { FormFieldElement } from "../../types"; + +/** + * Forms that hold at least one of a targeting rule's declared selectors. + * Half 1 (`checkStructural`) populates `forms`. Half 2 (`checkInScopeExtras`) + * runs heuristic field detection within those forms and stores the result in + * `detectedFields` so the miss path can reuse it rather than detecting fields + * in those forms again. + */ +export type InScopeFormsDetection = { + forms: Set; + detectedFields?: Map; +}; + +export type QualificationResult = + | { kind: "proceedTargeted" } + | { + kind: "fallback"; + missReason: FillAssistMissReason; + pageDetails: AutofillPageDetails; + }; + +/** + * Decides whether a matched targeting rule can fill the current page. A rule + * qualifies only when both halves pass: + * - Half 1 (structural): every declared selector resolves to an eligible field. + * - Half 2 (in-scope extras): no undeclared field exists in any form the rule + * declares at least one selector in. + * Either half failing triggers the miss path: heuristic collection with the + * full security-check suite re-engaged. The field caches are cleared before + * heuristic collection runs so the heuristic pass starts fresh. + */ +export interface RuleQualificationService { + qualifyRule(url: string, matchedRule: FormContent[]): Promise; +} diff --git a/apps/browser/src/autofill/services/collect-autofill-content.service.spec.ts b/apps/browser/src/autofill/services/collect-autofill-content.service.spec.ts index 96b2040451c..60026156102 100644 --- a/apps/browser/src/autofill/services/collect-autofill-content.service.spec.ts +++ b/apps/browser/src/autofill/services/collect-autofill-content.service.spec.ts @@ -459,6 +459,186 @@ describe("CollectAutofillContentService", () => { expect(collectAutofillContentService["buildAutofillFieldsData"]).toHaveBeenCalled(); expect(collectAutofillContentService["noFieldsFound"]).toBe(true); }); + + describe("rule qualification branch", () => { + const sampleRule = [{ category: "login", fields: {} }] as any; + const fallbackPageDetails = { foo: "fallback" } as any; + const targetedPageDetails = { foo: "targeted" } as any; + let ruleQualificationService: { + qualifyRule: jest.Mock; + }; + + beforeEach(() => { + ruleQualificationService = { qualifyRule: jest.fn() }; + collectAutofillContentService.setRuleQualificationService(ruleQualificationService as any); + jest + .spyOn(collectAutofillContentService as any, "getTargetedPageDetails") + .mockResolvedValue(targetedPageDetails); + }); + + it("does not run qualification when ruleFailureFallback is unset", async () => { + collectAutofillContentService["pageTargetingRules"] = sampleRule; + collectAutofillContentService["ruleFailureFallback"] = undefined; + + await collectAutofillContentService.getPageDetails(); + + expect(ruleQualificationService.qualifyRule).not.toHaveBeenCalled(); + }); + + it("runs qualification and returns targeted page details on proceedTargeted", async () => { + collectAutofillContentService["pageTargetingRules"] = sampleRule; + collectAutofillContentService["ruleFailureFallback"] = true; + ruleQualificationService.qualifyRule.mockResolvedValue({ kind: "proceedTargeted" }); + + const result = await collectAutofillContentService.getPageDetails(); + + expect(ruleQualificationService.qualifyRule).toHaveBeenCalledWith( + location.href, + sampleRule, + ); + expect(collectAutofillContentService["getTargetedPageDetails"]).toHaveBeenCalledWith( + sampleRule, + ); + expect(result).toBe(targetedPageDetails); + }); + + it("pins pageTargetingRules to null and returns the fallback page details on miss", async () => { + collectAutofillContentService["pageTargetingRules"] = sampleRule; + collectAutofillContentService["ruleFailureFallback"] = true; + ruleQualificationService.qualifyRule.mockResolvedValue({ + kind: "fallback", + missReason: "structural", + pageDetails: fallbackPageDetails, + }); + + const result = await collectAutofillContentService.getPageDetails(); + + expect(result).toBe(fallbackPageDetails); + expect(collectAutofillContentService["pageTargetingRules"]).toBeNull(); + }); + + it("reuses the cached qualification result on subsequent calls", async () => { + collectAutofillContentService["pageTargetingRules"] = sampleRule; + collectAutofillContentService["ruleFailureFallback"] = true; + ruleQualificationService.qualifyRule.mockResolvedValue({ kind: "proceedTargeted" }); + + await collectAutofillContentService.getPageDetails(); + await collectAutofillContentService.getPageDetails(); + + expect(ruleQualificationService.qualifyRule).toHaveBeenCalledTimes(1); + }); + + it("falls through to the heuristic path on subsequent calls after a miss", async () => { + collectAutofillContentService["pageTargetingRules"] = sampleRule; + collectAutofillContentService["ruleFailureFallback"] = true; + ruleQualificationService.qualifyRule.mockResolvedValue({ + kind: "fallback", + missReason: "structural", + pageDetails: fallbackPageDetails, + }); + + await collectAutofillContentService.getPageDetails(); + // pageTargetingRules is now null, so the second call should not re-enter the branch + await collectAutofillContentService.getPageDetails(); + + expect(ruleQualificationService.qualifyRule).toHaveBeenCalledTimes(1); + }); + + it("falls through to the targeted-fill path when the qualification service has not been wired", async () => { + // Fresh instance without setRuleQualificationService call + const freshService = new CollectAutofillContentService( + mock(), + mock(), + mock(), + ); + jest.spyOn(freshService as any, "sendExtensionMessage").mockResolvedValue({ result: null }); + const targetedSpy = jest + .spyOn(freshService as any, "getTargetedPageDetails") + .mockResolvedValue(targetedPageDetails); + freshService["pageTargetingRules"] = sampleRule; + freshService["ruleFailureFallback"] = true; + + const result = await freshService.getPageDetails(); + + expect(targetedSpy).toHaveBeenCalledWith(sampleRule); + expect(result).toBe(targetedPageDetails); + }); + }); + + describe("clearCachedTargetingRules", () => { + it("resets all three URL-scoped caches", () => { + collectAutofillContentService["pageTargetingRules"] = [] as any; + collectAutofillContentService["ruleFailureFallback"] = true; + collectAutofillContentService["ruleQualificationResult"] = { + kind: "proceedTargeted", + } as any; + + collectAutofillContentService.clearCachedTargetingRules(); + + expect(collectAutofillContentService["pageTargetingRules"]).toBeUndefined(); + expect(collectAutofillContentService["ruleFailureFallback"]).toBeUndefined(); + expect(collectAutofillContentService["ruleQualificationResult"]).toBeUndefined(); + }); + }); + + describe("collectHeuristicPageDetailsBypass", () => { + it("clears pageTargetingRules, autofillFieldElements, and autofillFieldsByOpid before running heuristic collection", async () => { + const dummyField = document.createElement("input") as any; + collectAutofillContentService["pageTargetingRules"] = [ + { category: "login", fields: {} }, + ] as any; + collectAutofillContentService["autofillFieldElements"].set(dummyField, {} as any); + collectAutofillContentService["autofillFieldsByOpid"].set("__opid__0", dummyField); + + const runHeuristicSpy = jest + .spyOn(collectAutofillContentService as any, "runHeuristicCollection") + .mockImplementation(() => { + expect(collectAutofillContentService["pageTargetingRules"]).toBeNull(); + expect(collectAutofillContentService["autofillFieldElements"].size).toBe(0); + expect(collectAutofillContentService["autofillFieldsByOpid"].size).toBe(0); + return Promise.resolve({} as any); + }); + + await collectAutofillContentService.collectHeuristicPageDetailsBypass(); + + expect(runHeuristicSpy).toHaveBeenCalled(); + }); + }); + + describe("envelope destructure", () => { + it("populates pageTargetingRules and ruleFailureFallback from the envelope", async () => { + const rules = [{ category: "login", fields: {} }] as any; + jest + .spyOn(collectAutofillContentService as any, "sendExtensionMessage") + .mockImplementation((command: string) => + command === "getUrlAutofillTargetingRules" + ? Promise.resolve({ + result: { targetingRules: rules, ruleFailureFallback: true }, + }) + : Promise.resolve(undefined), + ); + + await collectAutofillContentService.getPageDetails(); + + expect(collectAutofillContentService["pageTargetingRules"]).toBe(rules); + expect(collectAutofillContentService["ruleFailureFallback"]).toBe(true); + }); + + it("defaults to null rules and false fallback when the message returns no result", async () => { + jest + .spyOn(collectAutofillContentService as any, "sendExtensionMessage") + .mockImplementation((command: string) => + command === "getUrlAutofillTargetingRules" + ? Promise.resolve({ result: null }) + : Promise.resolve(undefined), + ); + + await collectAutofillContentService.getPageDetails(); + + expect(collectAutofillContentService["pageTargetingRules"]).toBeNull(); + expect(collectAutofillContentService["ruleFailureFallback"]).toBe(false); + }); + }); }); describe("applyExternalTargetedFields", () => { @@ -513,13 +693,16 @@ describe("CollectAutofillContentService", () => { .mockImplementation((command: string) => { if (command === "getUrlAutofillTargetingRules") { return Promise.resolve({ - result: [ - { - fields: { - username: ["iframe#nonexistent >>> #username"], + result: { + targetingRules: [ + { + fields: { + username: ["iframe#nonexistent >>> #username"], + }, }, - }, - ], + ], + ruleFailureFallback: false, + }, }); } return Promise.resolve(undefined); @@ -543,7 +726,10 @@ describe("CollectAutofillContentService", () => { .mockImplementation((command: string) => { if (command === "getUrlAutofillTargetingRules") { return Promise.resolve({ - result: [{ fields: { username: ["iframe#nonexistent >>> #username"] } }], + result: { + targetingRules: [{ fields: { username: ["iframe#nonexistent >>> #username"] } }], + ruleFailureFallback: false, + }, }); } return Promise.resolve(undefined); @@ -565,12 +751,15 @@ describe("CollectAutofillContentService", () => { .mockImplementation((command: string) => { if (command === "getUrlAutofillTargetingRules") { return Promise.resolve({ - result: [ - { - category: FormPurposeCategories.AccountLogin, - fields: { email: ["#username"] }, - }, - ], + result: { + targetingRules: [ + { + category: FormPurposeCategories.AccountLogin, + fields: { email: ["#username"] }, + }, + ], + ruleFailureFallback: false, + }, }); } return Promise.resolve(undefined); @@ -591,7 +780,10 @@ describe("CollectAutofillContentService", () => { .mockImplementation((command: string) => { if (command === "getUrlAutofillTargetingRules") { return Promise.resolve({ - result: [{ fields: { username: [selector] } }], + result: { + targetingRules: [{ fields: { username: [selector] } }], + ruleFailureFallback: false, + }, }); } return Promise.resolve(undefined); @@ -675,12 +867,15 @@ describe("CollectAutofillContentService", () => { .mockImplementation((command: string) => { if (command === "getUrlAutofillTargetingRules") { return Promise.resolve({ - result: [ - { - category: FormPurposeCategories.AccountLogin, - fields: { username: ["iframe#login-form-container >>> #username"] }, - }, - ], + result: { + targetingRules: [ + { + category: FormPurposeCategories.AccountLogin, + fields: { username: ["iframe#login-form-container >>> #username"] }, + }, + ], + ruleFailureFallback: false, + }, }); } return Promise.resolve(undefined); diff --git a/apps/browser/src/autofill/services/collect-autofill-content.service.ts b/apps/browser/src/autofill/services/collect-autofill-content.service.ts index f119ecff436..20efc0249bc 100644 --- a/apps/browser/src/autofill/services/collect-autofill-content.service.ts +++ b/apps/browser/src/autofill/services/collect-autofill-content.service.ts @@ -37,6 +37,11 @@ import { } from "./abstractions/collect-autofill-content.service"; import { DomElementVisibilityService } from "./abstractions/dom-element-visibility.service"; import { DomQueryService } from "./abstractions/dom-query.service"; +import { + InScopeFormsDetection, + QualificationResult, + RuleQualificationService, +} from "./abstractions/rule-qualification.service"; import { AutoFillConstants } from "./autofill-constants"; import { ShadowHostHydrationTracker } from "./shadow-host-hydration-tracker"; @@ -67,6 +72,12 @@ export class CollectAutofillContentService implements CollectAutofillContentServ * [] = blocklisted (suppress autofill), [...] = use targeted fill */ private pageTargetingRules: FormContent[] | null | undefined = undefined; + // Populated alongside `pageTargetingRules` from the background envelope. Sibling + // caches that short-circuit the per-call qualification cost (Half 1 + Half 2) on + // subsequent `getPageDetails()` calls for the same page load. + private ruleFailureFallback: boolean | undefined = undefined; + private ruleQualificationResult: QualificationResult | undefined = undefined; + private ruleQualificationService?: RuleQualificationService; private _autofillFormElements: AutofillFormElements = new Map(); private autofillFieldElements: AutofillFieldElements = new Map(); private autofillFieldsByOpid: Map = new Map(); @@ -281,11 +292,40 @@ export class CollectAutofillContentService implements CollectAutofillContentServ // Check for targeting rules before running heuristic collection if (this.pageTargetingRules === undefined) { - this.pageTargetingRules = - (await this.sendExtensionMessage("getUrlAutofillTargetingRules")).result ?? null; + const { result } = await this.sendExtensionMessage("getUrlAutofillTargetingRules"); + const envelope = result ?? { targetingRules: null, ruleFailureFallback: false }; + this.pageTargetingRules = envelope.targetingRules; + this.ruleFailureFallback = envelope.ruleFailureFallback; } const targetingRules = this.pageTargetingRules; + + // Rule qualification branch. When the envelope's `ruleFailureFallback` + // is set and a non-empty rule matches, run qualification once per page + // load and route on the result. On miss, pin `pageTargetingRules = null` + // so later calls on this document skip this branch and run the heuristic + // path. The null check on `ruleQualificationService` guards against the + // branch firing before the service is wired by content-script DI setup. + if ( + this.ruleFailureFallback && + targetingRules != null && + targetingRules.length > 0 && + this.ruleQualificationService + ) { + if (this.ruleQualificationResult === undefined) { + this.ruleQualificationResult = await this.ruleQualificationService.qualifyRule( + location.href, + targetingRules, + ); + } + const qualification = this.ruleQualificationResult; + if (qualification.kind === "proceedTargeted") { + return this.getTargetedPageDetails(targetingRules); + } + this.pageTargetingRules = null; + return qualification.pageDetails; + } + if (targetingRules != null) { if (targetingRules.length === 0) { // Blocklisted; return empty page details, skip heuristics @@ -307,6 +347,15 @@ export class CollectAutofillContentService implements CollectAutofillContentServ ); } + return this.runHeuristicCollection(); + } + + /** + * Walks the DOM for forms and fields, builds the page details, and sets up + * overlay listeners. Shared by `getPageDetails` and + * `collectHeuristicPageDetailsBypass`. + */ + private async runHeuristicCollection(): Promise { const { formElements, formFieldElements } = this.queryAutofillFormAndFieldElements(); const autofillFormsData: Record = this.buildAutofillFormsData(formElements); @@ -326,6 +375,29 @@ export class CollectAutofillContentService implements CollectAutofillContentServ return pageDetails; } + /** + * Runs the heuristic collection path on the miss path, after clearing any + * targeted-rule state so the heuristic pass starts fresh. Called by + * `RuleQualificationService` when a matched rule fails qualification. + * + * The `cachedInScopeForms` parameter is reserved for a later optimization + * that reuses Half 2's field detection within the rule's in-scope forms + * rather than detecting them again. Not consumed yet; the heuristic walk + * runs over the full document. + */ + async collectHeuristicPageDetailsBypass( + cachedInScopeForms?: InScopeFormsDetection, + ): Promise { + this.pageTargetingRules = null; + this.autofillFieldElements.clear(); + this.autofillFieldsByOpid.clear(); + return this.runHeuristicCollection(); + } + + setRuleQualificationService(ruleQualificationService: RuleQualificationService): void { + this.ruleQualificationService = ruleQualificationService; + } + /** * Find an AutofillField element by its opid, will only return the first * element if there are multiple elements with the same opid. If no @@ -586,6 +658,8 @@ export class CollectAutofillContentService implements CollectAutofillContentServ */ clearCachedTargetingRules(): void { this.pageTargetingRules = undefined; + this.ruleFailureFallback = undefined; + this.ruleQualificationResult = undefined; } /** @@ -1467,12 +1541,13 @@ export class CollectAutofillContentService implements CollectAutofillContentServ } /** - * Checks if the passed node is a form field element. - * @param {Element} element the element to check. - * @returns {boolean} whether the element is a form field element. - * @private + * Checks if the passed node is a form field element. Mirrors the filter used + * by the heuristic collection pass: excludes ignored input types and + * `data-bwignore` elements. + * @param element the element to check. + * @returns whether the element is a form field element. */ - private isElementFormFieldElement(element: Element): boolean { + isElementFormFieldElement(element: Element): boolean { const nodeTagName = element.tagName.toLowerCase(); const nodeIsSpanElementWithAutofillAttribute = @@ -1613,6 +1688,8 @@ export class CollectAutofillContentService implements CollectAutofillContentServ // Targeting rules are URL-scoped and gated by user/feature state at fetch // time; the new URL must re-fetch to pick up rule and gate changes. this.pageTargetingRules = undefined; + this.ruleFailureFallback = undefined; + this.ruleQualificationResult = undefined; this.clearFieldCache(); diff --git a/apps/browser/src/autofill/services/rule-qualification.service.spec.ts b/apps/browser/src/autofill/services/rule-qualification.service.spec.ts new file mode 100644 index 00000000000..0d51c8911fd --- /dev/null +++ b/apps/browser/src/autofill/services/rule-qualification.service.spec.ts @@ -0,0 +1,739 @@ +import { mock, MockProxy } from "jest-mock-extended"; + +import { FormContent, FormPurposeCategory } from "@bitwarden/common/autofill/types"; + +import AutofillPageDetails from "../models/autofill-page-details"; + +import { CollectAutofillContentService } from "./abstractions/collect-autofill-content.service"; +import { DomElementVisibilityService } from "./abstractions/dom-element-visibility.service"; +import { DomQueryService } from "./abstractions/dom-query.service"; +import { DefaultRuleQualificationService } from "./rule-qualification.service"; + +describe("DefaultRuleQualificationService", () => { + let collectService: MockProxy; + let domQueryService: MockProxy; + let domElementVisibilityService: MockProxy; + let service: DefaultRuleQualificationService; + + const samplePageDetails = {} as AutofillPageDetails; + + const buildLoginRule = (): FormContent[] => [ + { + category: "login" as FormPurposeCategory, + fields: { + username: ["#user"], + password: ["#pass"], + }, + }, + ]; + + // Mirrors the real `isElementFormFieldElement` filter on the collect service: + // excludes ignored input types and `data-bwignore` elements. + const IGNORED_INPUT_TYPES = new Set([ + "hidden", + "submit", + "reset", + "button", + "image", + "file", + "search", + "url", + "date", + "time", + "datetime", + "datetime-local", + "week", + "color", + "range", + ]); + const realisticIsElementFormFieldElement = (element: Element): boolean => { + const tagName = element.tagName.toLowerCase(); + if (element.hasAttribute("data-bwignore")) { + return false; + } + if (tagName === "input") { + return !IGNORED_INPUT_TYPES.has((element as HTMLInputElement).type); + } + return tagName === "textarea" || tagName === "select"; + }; + + beforeEach(() => { + document.body.innerHTML = ""; + + collectService = mock(); + collectService.collectHeuristicPageDetailsBypass.mockResolvedValue(samplePageDetails); + collectService.isElementFormFieldElement.mockImplementation(realisticIsElementFormFieldElement); + + domQueryService = mock(); + // Default stub mimics a light-DOM walk of the form root. Tests that need + // shadow-DOM-rooted or span[data-bwautofill] candidates override this. + domQueryService.queryWithUnresolvedShadowHosts.mockImplementation((root, predicate) => { + const elements: Element[] = []; + (root as Element).querySelectorAll("*").forEach((element) => { + if (predicate(element)) { + elements.push(element); + } + }); + return { elements: elements as never[], unresolvedHosts: new Set() }; + }); + domElementVisibilityService = mock(); + domElementVisibilityService.isElementHiddenByCss.mockReturnValue(false); + + service = new DefaultRuleQualificationService( + collectService, + domQueryService, + domElementVisibilityService, + ); + }); + + describe("qualifyRule — happy path", () => { + it("returns proceedTargeted when every declared selector resolves inside a form with no extras", async () => { + const form = document.createElement("form"); + const user = document.createElement("input"); + const pass = document.createElement("input"); + form.append(user, pass); + document.body.append(form); + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#user" ? user : selector === "#pass" ? pass : null, + ); + + const result = await service.qualifyRule("https://example.com", buildLoginRule()); + + expect(result).toEqual({ kind: "proceedTargeted" }); + expect(collectService.collectHeuristicPageDetailsBypass).not.toHaveBeenCalled(); + }); + + it("returns proceedTargeted when extras exist in unrelated forms outside the in-scope set", async () => { + const loginForm = document.createElement("form"); + const user = document.createElement("input"); + const pass = document.createElement("input"); + loginForm.append(user, pass); + + const newsletterForm = document.createElement("form"); + const email = document.createElement("input"); + newsletterForm.append(email); + + document.body.append(loginForm, newsletterForm); + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#user" ? user : selector === "#pass" ? pass : null, + ); + + const result = await service.qualifyRule("https://example.com", buildLoginRule()); + + expect(result).toEqual({ kind: "proceedTargeted" }); + }); + }); + + describe("qualifyRule — structural miss", () => { + it("returns fallback with missReason structural when a declared selector does not resolve", async () => { + domQueryService.queryDeepSelector.mockReturnValue(null); + + const result = await service.qualifyRule("https://example.com", buildLoginRule()); + + expect(result).toEqual({ + kind: "fallback", + missReason: "structural", + pageDetails: samplePageDetails, + }); + expect(collectService.collectHeuristicPageDetailsBypass).toHaveBeenCalledWith(); + }); + + it("returns fallback with missReason structural when a declared selector resolves to an input[type=hidden]", async () => { + // Exercises the real `type="hidden"` check in Half 1. The visibility + // service's `isElementHiddenByCss` only inspects CSS, so a hidden-type + // input would silently qualify without the dedicated check. + const form = document.createElement("form"); + const hidden = document.createElement("input"); + hidden.type = "hidden"; + form.append(hidden); + document.body.append(form); + + domQueryService.queryDeepSelector.mockReturnValue(hidden); + + const result = await service.qualifyRule("https://example.com", buildLoginRule()); + + expect(result).toEqual({ + kind: "fallback", + missReason: "structural", + pageDetails: samplePageDetails, + }); + }); + + it("returns fallback with missReason structural when a declared selector resolves but is CSS-hidden", async () => { + const form = document.createElement("form"); + const field = document.createElement("input"); + form.append(field); + document.body.append(form); + + domQueryService.queryDeepSelector.mockReturnValue(field); + domElementVisibilityService.isElementHiddenByCss.mockReturnValue(true); + + const result = await service.qualifyRule("https://example.com", buildLoginRule()); + + expect(result).toEqual({ + kind: "fallback", + missReason: "structural", + pageDetails: samplePageDetails, + }); + }); + + it("fails structural when any member of a DeepSelectorSequence does not resolve", async () => { + const form = document.createElement("form"); + const d1 = document.createElement("input"); + const d2 = document.createElement("input"); + form.append(d1, d2); + document.body.append(form); + + const otpRule: FormContent[] = [ + { + category: "login" as FormPurposeCategory, + fields: { + // Each entry here is a DeepSelectorSequence (string[]). The whole sequence + // must resolve for the rule to qualify. + oneTimeCode: [["#d1", "#d2", "#d3-missing"]], + }, + }, + ]; + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#d1" ? d1 : selector === "#d2" ? d2 : null, + ); + + const result = await service.qualifyRule("https://example.com", otpRule); + + expect(result).toMatchObject({ kind: "fallback", missReason: "structural" }); + }); + }); + + describe("qualifyRule — selector alternatives", () => { + const buildAlternativesRule = (): FormContent[] => [ + { + category: "login" as FormPurposeCategory, + fields: { + username: ["#email", "#login"], + password: ["#pwd"], + }, + }, + ]; + + it("qualifies when only the first alternative resolves", async () => { + const form = document.createElement("form"); + const email = document.createElement("input"); + const pwd = document.createElement("input"); + form.append(email, pwd); + document.body.append(form); + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#email" ? email : selector === "#pwd" ? pwd : null, + ); + + const result = await service.qualifyRule("https://example.com", buildAlternativesRule()); + + expect(result).toEqual({ kind: "proceedTargeted" }); + }); + + it("qualifies when only the second alternative resolves", async () => { + const form = document.createElement("form"); + const login = document.createElement("input"); + const pwd = document.createElement("input"); + form.append(login, pwd); + document.body.append(form); + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#login" ? login : selector === "#pwd" ? pwd : null, + ); + + const result = await service.qualifyRule("https://example.com", buildAlternativesRule()); + + expect(result).toEqual({ kind: "proceedTargeted" }); + }); + + it("fails structural when no alternative resolves", async () => { + const form = document.createElement("form"); + const pwd = document.createElement("input"); + form.append(pwd); + document.body.append(form); + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#pwd" ? pwd : null, + ); + + const result = await service.qualifyRule("https://example.com", buildAlternativesRule()); + + expect(result).toMatchObject({ kind: "fallback", missReason: "structural" }); + }); + + it("qualifies when a sequence alternative fully resolves even though the string alternative does not", async () => { + // Rule: `password: ["#pwd", ["#pwd-a", "#pwd-b"]]`. + // Page has `#pwd-a` and `#pwd-b` but not `#pwd`. + const form = document.createElement("form"); + const user = document.createElement("input"); + const pwdA = document.createElement("input"); + const pwdB = document.createElement("input"); + form.append(user, pwdA, pwdB); + document.body.append(form); + + const rule: FormContent[] = [ + { + category: "login" as FormPurposeCategory, + fields: { + username: ["#user"], + password: ["#pwd", ["#pwd-a", "#pwd-b"]], + }, + }, + ]; + + domQueryService.queryDeepSelector.mockImplementation((selector) => { + if (selector === "#user") { + return user; + } + if (selector === "#pwd-a") { + return pwdA; + } + if (selector === "#pwd-b") { + return pwdB; + } + return null; + }); + + const result = await service.qualifyRule("https://example.com", rule); + + expect(result).toEqual({ kind: "proceedTargeted" }); + }); + + it("fails structural when a sequence alternative has one member missing and no other alternative qualifies", async () => { + const form = document.createElement("form"); + const d1 = document.createElement("input"); + const d2 = document.createElement("input"); + form.append(d1, d2); + document.body.append(form); + + const rule: FormContent[] = [ + { + category: "login" as FormPurposeCategory, + fields: { + oneTimeCode: [["#d1", "#d2", "#d3-missing"]], + }, + }, + ]; + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#d1" ? d1 : selector === "#d2" ? d2 : null, + ); + + const result = await service.qualifyRule("https://example.com", rule); + + expect(result).toMatchObject({ kind: "fallback", missReason: "structural" }); + }); + + it("treats every alternative's resolved elements as declared for the extras check", async () => { + // Both `#email` and `#login` are declared as alternatives for the + // username and both exist on the page. Neither should be flagged as an + // extra. A third input that no alternative covers should. + const form = document.createElement("form"); + const email = document.createElement("input"); + const login = document.createElement("input"); + const pwd = document.createElement("input"); + const stray = document.createElement("input"); + form.append(email, login, pwd, stray); + document.body.append(form); + + domQueryService.queryDeepSelector.mockImplementation((selector) => { + if (selector === "#email") { + return email; + } + if (selector === "#login") { + return login; + } + if (selector === "#pwd") { + return pwd; + } + return null; + }); + + const result = await service.qualifyRule("https://example.com", buildAlternativesRule()); + + expect(result).toMatchObject({ kind: "fallback", missReason: "in_scope_extras" }); + }); + + it("qualifies when only one of several container selectors resolves", async () => { + // Container entries name the same element with different selectors. + // Any one resolving is enough. Pins the any-of semantic for container. + const form = document.createElement("form"); + const user = document.createElement("input"); + const pass = document.createElement("input"); + form.append(user, pass); + document.body.append(form); + + const rule: FormContent[] = [ + { + category: "login" as FormPurposeCategory, + container: ["#main-login", "#legacy-login"], + fields: { + username: ["#user"], + password: ["#pass"], + }, + }, + ]; + + domQueryService.queryDeepSelector.mockImplementation((selector) => { + if (selector === "#legacy-login") { + return form; + } + if (selector === "#user") { + return user; + } + if (selector === "#pass") { + return pass; + } + return null; + }); + + const result = await service.qualifyRule("https://example.com", rule); + + expect(result).toEqual({ kind: "proceedTargeted" }); + }); + }); + + describe("qualifyRule — in-scope extras miss", () => { + it("returns fallback with missReason in_scope_extras when an in-scope form contains an undeclared field", async () => { + const form = document.createElement("form"); + const user = document.createElement("input"); + const pass = document.createElement("input"); + const extra = document.createElement("input"); + form.append(user, pass, extra); + document.body.append(form); + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#user" ? user : selector === "#pass" ? pass : null, + ); + + const result = await service.qualifyRule("https://example.com", buildLoginRule()); + + expect(result).toEqual({ + kind: "fallback", + missReason: "in_scope_extras", + pageDetails: samplePageDetails, + }); + }); + + it("passes the in-scope detection to the bypass when extras are found", async () => { + const form = document.createElement("form"); + const user = document.createElement("input"); + const pass = document.createElement("input"); + const extra = document.createElement("input"); + form.append(user, pass, extra); + document.body.append(form); + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#user" ? user : selector === "#pass" ? pass : null, + ); + + await service.qualifyRule("https://example.com", buildLoginRule()); + + expect(collectService.collectHeuristicPageDetailsBypass).toHaveBeenCalledWith( + expect.objectContaining({ + forms: expect.any(Set), + detectedFields: expect.any(Map), + }), + ); + }); + + it("flags a shadow-DOM-rooted field inside an in-scope form as in_scope_extras", async () => { + // Regression guard. The extras check must cross shadow boundaries, or a + // shadow-rooted field inside an in-scope form would be invisible and the + // rule would qualify despite the extra. + const form = document.createElement("form"); + const user = document.createElement("input"); + const customEl = document.createElement("my-input"); + form.append(user, customEl); + document.body.append(form); + + // Stand-in for a field inside customEl's shadow root. The test only + // exercises what the deep-query mock returns, not the live DOM. + const shadowPassword = document.createElement("input"); + shadowPassword.type = "password"; + + const usernameOnlyRule: FormContent[] = [ + { + category: "login" as FormPurposeCategory, + fields: { username: ["#user"] }, + }, + ]; + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#user" ? user : null, + ); + domQueryService.queryWithUnresolvedShadowHosts.mockImplementation((root, predicate) => { + if (root === form) { + return { + elements: [user, shadowPassword] as never[], + unresolvedHosts: new Set(), + }; + } + const elements: Element[] = []; + (root as Element).querySelectorAll("*").forEach((element) => { + if (predicate(element)) { + elements.push(element); + } + }); + return { elements: elements as never[], unresolvedHosts: new Set() }; + }); + + const result = await service.qualifyRule("https://example.com", usernameOnlyRule); + + expect(result).toMatchObject({ kind: "fallback", missReason: "in_scope_extras" }); + }); + + it("flags a span[data-bwautofill] inside an in-scope form as in_scope_extras", async () => { + // When honorBitwardenAutofillAttribute is on, the heuristic treats + // span[data-bwautofill] as a fillable field. An undeclared one inside + // an in-scope form must be flagged as an extra. + const form = document.createElement("form"); + const user = document.createElement("input"); + const pass = document.createElement("input"); + pass.type = "password"; + const span = document.createElement("span"); + span.setAttribute("data-bwautofill", ""); + form.append(user, pass, span); + document.body.append(form); + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#user" ? user : selector === "#pass" ? pass : null, + ); + collectService.isElementFormFieldElement.mockImplementation((element) => { + if (element.tagName.toLowerCase() === "span" && element.hasAttribute("data-bwautofill")) { + return true; + } + return realisticIsElementFormFieldElement(element); + }); + + const result = await service.qualifyRule("https://example.com", buildLoginRule()); + + expect(result).toMatchObject({ kind: "fallback", missReason: "in_scope_extras" }); + }); + + it("qualifies a realistic login form containing a submit button and hidden token", async () => { + // Regression guard. Earlier the detector used a coarse filter that counted + // every input/select/textarea as a fillable field, so a standard login + // form with a CSRF hidden input and a submit button failed Half 2 on + // every page load. The real heuristic filter excludes those types. + const form = document.createElement("form"); + const user = document.createElement("input"); + user.id = "user"; + const pass = document.createElement("input"); + pass.id = "pass"; + pass.type = "password"; + const csrf = document.createElement("input"); + csrf.type = "hidden"; + csrf.name = "csrf_token"; + const submit = document.createElement("input"); + submit.type = "submit"; + form.append(user, pass, csrf, submit); + document.body.append(form); + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#user" ? user : selector === "#pass" ? pass : null, + ); + + const result = await service.qualifyRule("https://example.com", buildLoginRule()); + + expect(result).toEqual({ kind: "proceedTargeted" }); + }); + + it("qualifies a login form with a Remember Me checkbox", async () => { + // Checkbox and radio are not rule types and the autofill engine does + // not fill them, so Half 2 must not flag them as extras. + const form = document.createElement("form"); + const user = document.createElement("input"); + const pass = document.createElement("input"); + pass.type = "password"; + const remember = document.createElement("input"); + remember.type = "checkbox"; + form.append(user, pass, remember); + document.body.append(form); + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#user" ? user : selector === "#pass" ? pass : null, + ); + + const result = await service.qualifyRule("https://example.com", buildLoginRule()); + + expect(result).toEqual({ kind: "proceedTargeted" }); + }); + + it("ignores a CSS-hidden input when checking for extras", async () => { + // Honeypot inputs are rendered off-screen or display:none. Treating + // them as extras would cause misses on forms that use them. + const form = document.createElement("form"); + const user = document.createElement("input"); + const pass = document.createElement("input"); + pass.type = "password"; + const honeypot = document.createElement("input"); + form.append(user, pass, honeypot); + document.body.append(form); + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#user" ? user : selector === "#pass" ? pass : null, + ); + domElementVisibilityService.isElementHiddenByCss.mockImplementation( + (element) => element === honeypot, + ); + + const result = await service.qualifyRule("https://example.com", buildLoginRule()); + + expect(result).toEqual({ kind: "proceedTargeted" }); + }); + }); + + describe("qualifyRule — formless pages (known limitation)", () => { + it("returns proceedTargeted when every selector resolves outside any form, even if page has other fields", async () => { + // Fields rendered as plain divs, not inside
. closest("form") returns + // null for the resolved elements, so the in-scope form set is empty and + // the extras check passes without inspecting the page's other fields. + const user = document.createElement("input"); + const pass = document.createElement("input"); + const unrelated = document.createElement("input"); + document.body.append(user, pass, unrelated); + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#user" ? user : selector === "#pass" ? pass : null, + ); + + const result = await service.qualifyRule("https://example.com", buildLoginRule()); + + expect(result).toEqual({ kind: "proceedTargeted" }); + }); + }); + + describe("qualifyRule — iframe >>> selectors", () => { + it("passes structural when the first-hop iframe exists in the parent's DOM", async () => { + const rule: FormContent[] = [ + { + category: "login" as FormPurposeCategory, + fields: { username: ["iframe#login >>> #user"] }, + }, + ]; + const iframe = document.createElement("iframe"); + domQueryService.findIframeCrossing.mockReturnValue({ + iframeElement: iframe, + innerSelector: "#user", + }); + + const result = await service.qualifyRule("https://example.com", rule); + + expect(result).toEqual({ kind: "proceedTargeted" }); + expect(domQueryService.queryDeepSelector).not.toHaveBeenCalled(); + }); + + it("fails structural when the first-hop iframe is missing (findIframeCrossing returns null)", async () => { + const rule: FormContent[] = [ + { + category: "login" as FormPurposeCategory, + fields: { username: ["iframe#missing >>> #user"] }, + }, + ]; + domQueryService.findIframeCrossing.mockReturnValue(null); + domQueryService.queryDeepSelector.mockReturnValue(null); + + const result = await service.qualifyRule("https://example.com", rule); + + expect(result).toMatchObject({ kind: "fallback", missReason: "structural" }); + }); + }); + + describe("qualifyRule — shadow DOM >>> selectors", () => { + it("passes structural when a shadow DOM >>> chain resolves to an eligible element", async () => { + const rule: FormContent[] = [ + { + category: "login" as FormPurposeCategory, + fields: { username: ["gi-login.hydrated >>> input#user"] }, + }, + ]; + const input = document.createElement("input"); + // findIframeCrossing returns null for chains without an iframe boundary. + domQueryService.findIframeCrossing.mockReturnValue(null); + domQueryService.queryDeepSelector.mockReturnValue(input); + + const result = await service.qualifyRule("https://example.com", rule); + + expect(result).toEqual({ kind: "proceedTargeted" }); + }); + }); + + describe("qualifyRule — debug logging", () => { + let debugSpy: jest.SpyInstance; + + beforeEach(() => { + debugSpy = jest.spyOn(console, "debug").mockImplementation(() => {}); + }); + + afterEach(() => { + debugSpy.mockRestore(); + }); + + it("logs the proceedTargeted outcome with domain, duration, and in-scope form count", async () => { + const form = document.createElement("form"); + const user = document.createElement("input"); + const pass = document.createElement("input"); + form.append(user, pass); + document.body.append(form); + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#user" ? user : selector === "#pass" ? pass : null, + ); + + await service.qualifyRule("https://example.com/login?token=secret", buildLoginRule()); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("proceedTargeted"), + expect.objectContaining({ + domain: "example.com", + durationMs: expect.any(Number), + inScopeForms: expect.any(Number), + }), + ); + }); + + it("logs the structural miss outcome with domain, duration, and in-scope form count", async () => { + domQueryService.queryDeepSelector.mockReturnValue(null); + + await service.qualifyRule("https://example.com/login?token=secret", buildLoginRule()); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("structural miss"), + expect.objectContaining({ + domain: "example.com", + durationMs: expect.any(Number), + inScopeForms: expect.any(Number), + }), + ); + }); + + it("logs the in_scope_extras miss outcome with domain, duration, and in-scope form count", async () => { + const form = document.createElement("form"); + const user = document.createElement("input"); + const pass = document.createElement("input"); + const extra = document.createElement("input"); + form.append(user, pass, extra); + document.body.append(form); + + domQueryService.queryDeepSelector.mockImplementation((selector) => + selector === "#user" ? user : selector === "#pass" ? pass : null, + ); + + await service.qualifyRule("https://example.com/login?token=secret", buildLoginRule()); + + expect(debugSpy).toHaveBeenCalledWith( + expect.stringContaining("in_scope_extras miss"), + expect.objectContaining({ + domain: "example.com", + durationMs: expect.any(Number), + inScopeForms: expect.any(Number), + }), + ); + }); + }); +}); diff --git a/apps/browser/src/autofill/services/rule-qualification.service.ts b/apps/browser/src/autofill/services/rule-qualification.service.ts new file mode 100644 index 00000000000..49ffdb9ba8f --- /dev/null +++ b/apps/browser/src/autofill/services/rule-qualification.service.ts @@ -0,0 +1,263 @@ +import { FormContent } from "@bitwarden/common/autofill/types"; + +import { FormFieldElement } from "../types"; + +import { CollectAutofillContentService } from "./abstractions/collect-autofill-content.service"; +import { DomElementVisibilityService } from "./abstractions/dom-element-visibility.service"; +import { DomQueryService } from "./abstractions/dom-query.service"; +import { + InScopeFormsDetection, + QualificationResult, + RuleQualificationService, +} from "./abstractions/rule-qualification.service"; +import { AutoFillConstants } from "./autofill-constants"; + +export class DefaultRuleQualificationService implements RuleQualificationService { + constructor( + private collectAutofillContentService: CollectAutofillContentService, + private domQueryService: DomQueryService, + private domElementVisibilityService: DomElementVisibilityService, + ) {} + + async qualifyRule(url: string, matchedRule: FormContent[]): Promise { + const startTime = performance.now(); + // Hostname only. URL paths and queries can carry sensitive values. + const domain = new URL(url).hostname; + const structural = await this.checkStructural(matchedRule); + if (!structural.ok) { + const pageDetails = + await this.collectAutofillContentService.collectHeuristicPageDetailsBypass(); + // eslint-disable-next-line no-console -- this is running in a content-script; `LogService` is unavailable + console.debug("[RuleQualificationService] structural miss", { + domain, + durationMs: performance.now() - startTime, + inScopeForms: structural.inScopeForms.forms.size, + }); + return { kind: "fallback", missReason: "structural", pageDetails }; + } + + const extras = await this.checkInScopeExtras(matchedRule, structural.inScopeForms); + if (!extras.ok) { + const pageDetails = + await this.collectAutofillContentService.collectHeuristicPageDetailsBypass( + structural.inScopeForms, + ); + // eslint-disable-next-line no-console -- this is running in a content-script; `LogService` is unavailable + console.debug("[RuleQualificationService] in_scope_extras miss", { + domain, + durationMs: performance.now() - startTime, + inScopeForms: structural.inScopeForms.forms.size, + }); + return { kind: "fallback", missReason: "in_scope_extras", pageDetails }; + } + + // eslint-disable-next-line no-console -- this is running in a content-script; `LogService` is unavailable + console.debug("[RuleQualificationService] proceedTargeted", { + domain, + durationMs: performance.now() - startTime, + inScopeForms: structural.inScopeForms.forms.size, + }); + return { kind: "proceedTargeted" }; + } + + /** + * Half 1: for each declared field, at least one alternative qualifies. + * Side-effect free. Collects enclosing `` elements along the way so + * Half 2 knows which forms to detect fields within. + */ + private async checkStructural( + rule: FormContent[], + ): Promise<{ ok: boolean; inScopeForms: InScopeFormsDetection }> { + const inScopeForms = new Set(); + + for (const form of rule) { + for (const alternatives of this.extractAlternativeGroups(form)) { + const winningElements = this.firstQualifyingAlternative(alternatives); + if (winningElements === null) { + return { ok: false, inScopeForms: { forms: inScopeForms } }; + } + for (const element of winningElements) { + const enclosingForm = element.closest("form"); + if (enclosingForm) { + inScopeForms.add(enclosingForm); + } + } + } + } + + return { ok: true, inScopeForms: { forms: inScopeForms } }; + } + + /** + * Half 2: no undeclared field exists in any in-scope form. Populates + * `inScopeForms.detectedFields` with the detection result so the miss path + * can reuse it rather than detecting fields in those forms again. + * + * The declared set includes elements for every alternative that resolves, + * not just the one Half 1 picked. If a rule declares `username: ["#email", + * "#login"]` and both exist on the page, neither counts as an extra. + * + * Note on formless pages: when every resolved declared selector sits outside + * a ``, `inScopeForms.forms` is empty and this method returns `ok: true` + * without finding any extras. The check asks "is there an extra inside any + * in-scope form?" and with zero in-scope forms the answer is no. This matches + * the known limitation that formless pages are not covered by the extras check. + */ + private async checkInScopeExtras( + rule: FormContent[], + inScopeForms: InScopeFormsDetection, + ): Promise<{ ok: boolean }> { + const declaredElements = new Set(); + for (const selector of this.flattenDeclaredSelectors(rule)) { + if (selector.includes(">>>") && this.domQueryService.findIframeCrossing(selector)) { + continue; + } + const element = this.domQueryService.queryDeepSelector(selector); + if (element) { + declaredElements.add(element); + } + } + + const detectedFields = new Map(); + for (const form of inScopeForms.forms) { + const fields = this.detectHeuristicFieldsInForm(form); + detectedFields.set(form, fields); + for (const field of fields) { + if (!declaredElements.has(field as Element)) { + inScopeForms.detectedFields = detectedFields; + return { ok: false }; + } + } + } + + inScopeForms.detectedFields = detectedFields; + return { ok: true }; + } + + /** + * Returns one list of alternatives per declared field, plus the container + * if present. A field qualifies when any one alternative qualifies. An + * alternative is a list of selectors that must all resolve together. A + * string entry becomes a one-member list. A `DeepSelectorSequence` entry + * carries all its members. + * + * Container selectors are grouped the same way: multiple entries name the + * same container element, so any one that resolves qualifies. + */ + private extractAlternativeGroups(form: FormContent): string[][][] { + const groups: string[][][] = []; + + if (form.container) { + groups.push(form.container.map((selector) => [selector])); + } + + for (const typeSelectors of Object.values(form.fields)) { + if (!typeSelectors) { + continue; + } + groups.push(typeSelectors.map((entry) => (typeof entry === "string" ? [entry] : entry))); + } + + return groups; + } + + /** + * Flattens every declared selector from a rule into one list. The extras + * check only needs element identity, not alternative grouping, so a flat + * walk keeps the caller free of deep nesting. + */ + private flattenDeclaredSelectors(rule: FormContent[]): string[] { + const selectors: string[] = []; + for (const form of rule) { + for (const alternatives of this.extractAlternativeGroups(form)) { + for (const members of alternatives) { + selectors.push(...members); + } + } + } + return selectors; + } + + /** + * Returns the resolved elements of the first alternative that fully + * qualifies, or null if none do. An iframe `>>>` selector with a resolved + * first-hop iframe counts as qualifying without contributing a local + * element. Later segments live in child frames and are not checked here. + */ + private firstQualifyingAlternative(alternatives: string[][]): HTMLElement[] | null { + for (const members of alternatives) { + const resolved: HTMLElement[] = []; + let allResolve = true; + for (const selector of members) { + if (selector.includes(">>>") && this.domQueryService.findIframeCrossing(selector)) { + continue; + } + const element = this.domQueryService.queryDeepSelector(selector) as HTMLElement | null; + if (!element || this.isElementIneligible(element)) { + allResolve = false; + break; + } + resolved.push(element); + } + if (allResolve) { + return resolved; + } + } + return null; + } + + /** + * Treats `input type="hidden"` and CSS-hidden elements (display, visibility, + * opacity, clip-path) as unresolved, matching the eligibility probe. + */ + private isElementIneligible(element: HTMLElement): boolean { + const isHiddenInput = element instanceof HTMLInputElement && element.type === "hidden"; + return isHiddenInput || this.domElementVisibilityService.isElementHiddenByCss(element); + } + + /** + * Detects heuristic-eligible fields within a single form container. Scoped, + * side-effect-free equivalent of the field detection in + * `buildAutofillFieldsData`. + * + * We chose a scoped reimplementation over making `buildAutofillFieldsData` + * cache-optional because the shared method populates the collect service's + * field caches as a side effect, and those caches must stay empty on the + * heuristic bypass path. Adding a `skipCaching` branch to the shared path + * would clutter it for just one caller. + * + * Uses the same `queryWithUnresolvedShadowHosts` call the full heuristic + * scan uses, so shadow-rooted fields and `span[data-bwautofill]` surface + * the same way. The predicate narrows further via `isFillableField`. + * Unresolved shadow hosts are discarded. The collect service handles + * shadow tracker reconciliation on its own full scan. + */ + private detectHeuristicFieldsInForm(form: HTMLFormElement): FormFieldElement[] { + const { elements } = this.domQueryService.queryWithUnresolvedShadowHosts( + form, + (element) => this.isFillableField(element), + ); + return elements; + } + + /** + * Narrows the collect service's form-field filter to elements the autofill + * engine can actually fill. Rules have no field type for checkbox or radio + * and the autofill engine does not fill them, so counting them as extras + * would misfire on common login forms (e.g. a Remember Me checkbox). + * CSS-hidden elements are also skipped so honeypot inputs do not trip the + * extras check. + */ + private isFillableField(element: Element): boolean { + if (!this.collectAutofillContentService.isElementFormFieldElement(element)) { + return false; + } + if ( + element instanceof HTMLInputElement && + AutoFillConstants.ExcludedAutofillTypes.includes(element.type) + ) { + return false; + } + return !this.domElementVisibilityService.isElementHiddenByCss(element as HTMLElement); + } +} diff --git a/apps/browser/src/background/runtime.background.spec.ts b/apps/browser/src/background/runtime.background.spec.ts index 2cb5e7ee809..45752f0afce 100644 --- a/apps/browser/src/background/runtime.background.spec.ts +++ b/apps/browser/src/background/runtime.background.spec.ts @@ -5,6 +5,7 @@ import { AccountService } from "@bitwarden/common/auth/abstractions/account.serv import { LogoutReason } from "@bitwarden/common/auth/logout"; import { ExtensionCommand } from "@bitwarden/common/autofill/constants"; import { DomainSettingsService } from "@bitwarden/common/autofill/services/domain-settings.service"; +import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; import { Environment, Region, @@ -67,6 +68,7 @@ type RuntimeBackgroundOverrides = { autofillOrchestrator?: MockProxy; intraprocessMessageSender?: MockProxy; fillAssistEventReceiver?: MockProxy; + configService?: MockProxy; }; function createRuntimeBackground({ @@ -79,6 +81,7 @@ function createRuntimeBackground({ autofillOrchestrator = mock(), intraprocessMessageSender = mock(), fillAssistEventReceiver = mock(), + configService = mock(), }: RuntimeBackgroundOverrides = {}) { // The `undefined` slots are collaborators no covered path reaches. // Give one a mock as soon as a test needs it. @@ -90,7 +93,7 @@ function createRuntimeBackground({ environmentService as any, messagingService as any, logService, - undefined as any, // configService + configService, undefined as any, // messageListener accountService, undefined as any, // lockService @@ -485,6 +488,7 @@ describe("RuntimeBackground getUrlAutofillTargetingRules", () => { let runtimeBackground: RuntimeBackground; let mainBackground: MockProxy; let domainSettingsService: MockProxy; + let configService: MockProxy; const message = { command: "getUrlAutofillTargetingRules" }; @@ -501,8 +505,10 @@ describe("RuntimeBackground getUrlAutofillTargetingRules", () => { domainSettingsService = mock(); mainBackground = mock(); (mainBackground as any).domainSettingsService = domainSettingsService; + configService = mock(); + configService.getFeatureFlag.mockResolvedValue(false as any); - runtimeBackground = createRuntimeBackground({ main: mainBackground }); + runtimeBackground = createRuntimeBackground({ main: mainBackground, configService }); }); afterEach(() => { @@ -574,7 +580,7 @@ describe("RuntimeBackground getUrlAutofillTargetingRules", () => { expect(domainSettingsService.getTargetingRulesForUrl).toHaveBeenCalledWith(committedUrl); }); - it("returns the resolved rules to the caller", async () => { + it("returns the resolved rules in the envelope under `targetingRules`", async () => { const rules = [{ category: "account-login", fields: {} }] as any; mockFrameLookup(routedUrl); domainSettingsService.getTargetingRulesForUrl.mockResolvedValue(rules); @@ -586,7 +592,23 @@ describe("RuntimeBackground getUrlAutofillTargetingRules", () => { const result = await runtimeBackground.processMessageWithSender(message, sender); - expect(result).toBe(rules); + expect(result).toEqual({ targetingRules: rules, ruleFailureFallback: false }); + }); + + it("sets ruleFailureFallback=true in the envelope when the fallback flag is on", async () => { + const rules = [{ category: "account-login", fields: {} }] as any; + mockFrameLookup(routedUrl); + domainSettingsService.getTargetingRulesForUrl.mockResolvedValue(rules); + configService.getFeatureFlag.mockResolvedValue(true as any); + const sender = { + frameId: 0, + url: committedUrl, + tab: createChromeTabMock({ id: 1, url: routedUrl }), + } as chrome.runtime.MessageSender; + + const result = await runtimeBackground.processMessageWithSender(message, sender); + + expect(result).toEqual({ targetingRules: rules, ruleFailureFallback: true }); }); }); diff --git a/apps/browser/src/background/runtime.background.ts b/apps/browser/src/background/runtime.background.ts index ad33a1b3fc1..730d2bf2b15 100644 --- a/apps/browser/src/background/runtime.background.ts +++ b/apps/browser/src/background/runtime.background.ts @@ -6,6 +6,7 @@ import { AccountService } from "@bitwarden/common/auth/abstractions/account.serv import { AutofillOverlayVisibility, ExtensionCommand } from "@bitwarden/common/autofill/constants"; import { AutofillSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/autofill-settings.service"; import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; +import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -293,10 +294,13 @@ export default class RuntimeBackground { // Rules are matched against the sender frame's URL rather than the tab's to minimize // selector collisions between frames with similar in-frame markup. const senderURL = await BrowserApi.getSenderFrameUrl(sender); - const targetingRulesForUrl = + const targetingRules = await this.main.domainSettingsService.getTargetingRulesForUrl(senderURL); + const ruleFailureFallback = await this.configService.getFeatureFlag( + FeatureFlag.FillAssistRuleFallback, + ); - return targetingRulesForUrl; + return { targetingRules, ruleFailureFallback }; } case "getBitwardenAutofillAttributeSettings": { const [honorBitwardenIgnoreAttribute, honorBitwardenAutofillAttribute] = await Promise.all([