diff --git a/extension/e2e/fake-host.py b/extension/e2e/fake-host.py index 7ba061eb..45d4feeb 100755 --- a/extension/e2e/fake-host.py +++ b/extension/e2e/fake-host.py @@ -8,7 +8,8 @@ (DEADBOLT_FAKE_LIST_DELAY each list reply), and DEADBOLT_FAKE_SIGNIN adds "Sign in with Google" logins, and DEADBOLT_FAKE_GOOGLE lists three Google logins instead of its own, and -DEADBOLT_FAKE_KEYLOGIN adds a login with no username. Saves +DEADBOLT_FAKE_KEYLOGIN adds a login with no username, and +DEADBOLT_FAKE_ONE_LINE adds an identity with its address on one line. Saves are checked against the spec's title and URL rules. Generated passwords are held per origin, as the daemon holds them: candidates until generate-keep, then pending, and check and save resolve only pending ones. Fields that allow @@ -59,6 +60,12 @@ VISA: {"number": "4242424242424242", "cvv": "123", "expiry": "2028-08", "cardholder": "Alex Mercer", "brand": "Visa"}, } VALUES = {REF1: {"username": "alex@acme.test", "password": "correct horse", "totp": "492039"}, REF2: {"username": "admin", "password": "hunter2"}} +# DEADBOLT_FAKE_ONE_LINE=1 adds "Mailing", an identity that keeps its whole +# address in its first line, as one typed into a single box is saved. +if os.environ.get("DEADBOLT_FAKE_ONE_LINE"): + MAILING = "c" * 64 + ":" + "4" * 32 + IDENTITIES.append({"ref": MAILING, "title": "Mailing", "summary": "Alex Mercer · 123 Main St, Apt 4, Brooklyn, NY, 11201, United States"}) + FORM_VALUES[MAILING] = {"given-name": "Alex", "family-name": "Mercer", "address-line1": "123 Main St, Apt 4, Brooklyn, NY, 11201, United States"} # DEADBOLT_FAKE_USERNAME and DEADBOLT_FAKE_PASSWORD replace the first login's # values (corpus/sweep.ts, on real sites). if os.environ.get("DEADBOLT_FAKE_USERNAME"): diff --git a/extension/e2e/gauntlet/scenarios.ts b/extension/e2e/gauntlet/scenarios.ts index 3e7e1bac..67c284b6 100644 --- a/extension/e2e/gauntlet/scenarios.ts +++ b/extension/e2e/gauntlet/scenarios.ts @@ -4,8 +4,9 @@ // these its helpers. // // The e2e logins are the fake host's: alex@acme.test ("correct horse", with -// a one-time code) and admin ("hunter2"); the identity "Home" and the card -// "Personal Visa". +// a one-time code) and admin ("hunter2"); the identities "Home" and "Work", +// the card "Personal Visa", and for the pages that pick it "Mailing", an +// identity with its whole address on one line. import type { BrowserContext, Frame, Page, Worker } from "playwright-core" import { BACKUP_CODES, EMAIL_CODE, PAGES, SMS_CODE, type Account } from "./site" @@ -20,7 +21,8 @@ export interface Harness { /** http://localhost: */ site: string port: number - launch(options?: { record?: string; scale?: number }): Promise + /** `oneLine`: the vault also lists "Mailing", an identity that keeps its whole address in its first line. */ + launch(options?: { record?: string; scale?: number; oneLine?: boolean }): Promise close(run: R): Promise check(ok: boolean, what: string): boolean settled(menu: Frame): Promise @@ -686,6 +688,43 @@ export function gauntletScenarios(h: Harness): { scena await c.page.click("#submit") c.ok(!!(await wait("saved", async () => (await c.page.locator("#result[data-ok]").count()) > 0)), "and the form submits") }, + "mailing-address-continued": async (c) => { + const FIELDS = ["#first", "#last", "#street", "#street-more", "#city", "#country", "#state", "#zip"] + // Twice: an identity with its address in parts, then one that keeps the whole address in its first line. + for (const [title, how] of [["Home", "an identity with its address in parts"], ["Mailing", "an identity with its whole address on one line"]]) { + await c.page.goto(g("mailing-address-continued")) + c.ok(!(await c.page.isVisible("#street")), "the mailing address is hidden until Paper check is chosen") + await c.page.click("#pay-check") + await c.page.waitForSelector("#street", { state: "visible" }) + c.ok((await c.page.locator("#state option").count()) === 1 && (await value(c.page, "#state")) === "0", "the state list holds only its Select placeholder, value 0") + c.ok(await pickForm(c, "#street", title), `one pick of ${how} fills`) + c.ok(await filledWith(c.page, "#state", "32", 5000), "the state is chosen once the country's states load, by its code in \"NY - New York\"") + const got = await Promise.all(FIELDS.map((s) => value(c.page, s))) + c.ok(JSON.stringify(got) === JSON.stringify(["Alex", "Mercer", "123 Main St", "Apt 4", "Brooklyn", "US", "32", "11201"]), `all eight fields, the unit in the Continued line (${got.join(" | ")})`) + c.ok(got[2].length <= 40 && got[3].length <= 40, `neither street line is over its 40 characters (${got[2].length}, ${got[3].length})`) + await c.page.click("#submit") + const saved = await wait("saved", async () => (await c.page.locator("#result[data-ok], #error").count()) > 0) + c.ok(!!saved && (await c.page.locator("#result[data-ok]").count()) > 0, `and the page takes it (${(await c.page.locator("#error").textContent({ timeout: 500 }).catch(() => "")) || "no error"})`) + } + }, + "address-optional-line": async (c) => { + await c.page.goto(g("address-optional-line")) + const SHIP = ["#ship-street", "#ship-street-b", "#ship-city", "#ship-state", "#ship-zip"] + const BILL = ["#bill-street", "#bill-city", "#bill-state", "#bill-zip"] + const read = (sels: string[]) => Promise.all(sels.map((s) => value(c.page, s))) + c.ok(await pickForm(c, "#ship-street", "Home"), "one pick on the shipping street fills") + let ship = await read(SHIP) + c.ok(JSON.stringify(ship) === JSON.stringify(["123 Main St", "Apt 4", "Brooklyn", "NY", "11201"]), `both street lines and the rest of the shipping address (${ship.join(" | ")})`) + let bill = await read(BILL) + c.ok(bill.every((v) => !v), `the billing address gets 0 bytes (${bill.join(" | ")})`) + c.ok(await pickForm(c, "#bill-street", "Work"), "a pick on the billing street fills") + bill = await read(BILL) + c.ok(JSON.stringify(bill) === JSON.stringify(["1 Market St", "San Francisco", "CA", "94105"]), `the billing address, from another identity (${bill.join(" | ")})`) + ship = await read(SHIP) + c.ok(JSON.stringify(ship) === JSON.stringify(["123 Main St", "Apt 4", "Brooklyn", "NY", "11201"]), `and the shipping address is as it was (${ship.join(" | ")})`) + await c.page.click("#submit") + c.ok(!!(await wait("saved", async () => (await c.page.locator("#result[data-ok]").count()) > 0)), "and the form submits") + }, "spa-shell-save": async (c) => { await c.page.goto(g("spa-shell-save")) await reported(c.run, "/gauntlet/spa-shell-save") @@ -747,7 +786,8 @@ export function gauntletScenarios(h: Harness): { scena const only = process.env.GAUNTLET_PAGES?.split(",").filter(Boolean) const slugs = only ? all.filter((s) => only.includes(s)) : all if (!slugs.length) return - const run = await h.launch(h.video ? { record: h.video, scale: 1 } : {}) + // The one-line identity is listed only for the pages that pick it: every other menu is as it was. + const run = await h.launch({ ...(h.video ? { record: h.video, scale: 1 } : {}), oneLine: slugs.includes("mailing-address-continued") }) try { for (const slug of slugs) { const page = await run.context.newPage() @@ -805,6 +845,6 @@ export function gauntletScenarios(h: Harness): { scena if (missing.length) throw new Error(`gauntlet pages without a scenario: ${missing.join(", ")}`) return { scenarios: Object.fromEntries(Object.entries(units).map(([name, slugs]) => [name, () => runPages(slugs)])), - cost: { gauntletSignIn: 38, gauntletCodes: 80, gauntletIdentity: 19, gauntletDom: 52, gauntletDom2: 50, gauntletFlows: 55, gauntletTraps: 95 }, + cost: { gauntletSignIn: 38, gauntletCodes: 80, gauntletIdentity: 19, gauntletDom: 52, gauntletDom2: 50, gauntletFlows: 55, gauntletTraps: 115 }, } } diff --git a/extension/e2e/gauntlet/traps.ts b/extension/e2e/gauntlet/traps.ts index d5a74680..3682a2bb 100644 --- a/extension/e2e/gauntlet/traps.ts +++ b/extension/e2e/gauntlet/traps.ts @@ -4,7 +4,9 @@ // concealed inputs (the ACSAC 2024 concealment tricks), decoy fields that are // no sign-in at all, a checkout whose fields all sit below the fold, code // boxes that take a code only as a paste, a card form behind a strict mask, -// and a single-page app that signs in without a page load. +// a single-page app that signs in without a page load, a mailing address +// revealed by a radio button whose second line is "… Continued" and whose +// states load after the country, and two street boxes with one label. // Every account, code and answer here is made up. import type { Account, PageInfo } from "./site" @@ -18,6 +20,8 @@ export const TRAP_PAGES: PageInfo[] = [ { slug: "below-fold-checkout", group: "Traps", title: "Checkout below the fold", blurb: "Shipping address and card under a tall summary." }, { slug: "paste-otp-boxes", group: "Traps", title: "Paste-only code boxes", blurb: "Six boxes that turn a written digit down and take the code only as a paste." }, { slug: "masked-card", group: "Traps", title: "Strictly masked card", blurb: "Card number and expiry masks that take a character at a time." }, + { slug: "mailing-address-continued", group: "Traps", title: "Mailing address behind a radio button", blurb: "“Address Continued”, 40 characters a line, states by number after the country." }, + { slug: "address-optional-line", group: "Traps", title: "Two street boxes, one label", blurb: "“Street Address (optional)”, then a billing address in the same form." }, { slug: "spa-shell-save", group: "Traps", title: "Single-page sign-in", blurb: "No page load: the form goes and an avatar menu shows. No Sign out link." }, ] @@ -261,7 +265,72 @@ document.getElementById("f").addEventListener("submit",async(e)=>{e.preventDefau strictMaskScript, ) }, + // A payout form as claims and benefits sites draw one: the mailing + // address shows only once "Paper check" is chosen; its second street + // line is "… Continued" (no number, no autocomplete); both street lines + // take 40 characters at most; and the state list holds only + // until the country is chosen, then + // loads options with the site's own numbers for values. + "mailing-address-continued": async (req, _u, _r, form) => { + const slug = "mailing-address-continued" + const STATES: Record> = { + CA: [[60, "ON - Ontario"], [61, "QC - Quebec"]], + US: [[5, "CA - California"], [32, "NY - New York"], [43, "TX - Texas"], [47, "WA - Washington"]], + } + if (req.method === "POST") { + const f = await form() + const long = ["street", "street_more"].filter((n) => (f[n] ?? "").length > 40) + const missing = ["first", "last", "street", "city", "zip"].filter((n) => !f[n]?.trim()) + const state = (STATES[f.country] ?? []).find(([v]) => String(v) === f.state) + const error = f.method !== "check" ? "Choose Paper check." : long.length ? `${long.join(", ")}: too many characters` : missing.length || !state ? `Required: ${[...missing, ...(state ? [] : ["state"])].join(", ")}` : "" + if (error) return h("Payment method", `

Payment method

Back

`, slug) + const rows = Object.entries({ ...f, state: state![1] }).map(([n, v]) => `${esc(n)}${esc(v)}`).join("") + return h("Saved", `

Saved

${rows}
`, slug) + } + return h( + "Payment method", + `

Payment method

How would you like to be paid?

+ + + +
`, + slug, + `const STATES=${JSON.stringify(STATES)};const c=document.getElementById("country"),s=document.getElementById("state"),m=document.getElementById("mailing") +for(const r of document.querySelectorAll("input[name=method]"))r.addEventListener("change",()=>{m.style.display=document.getElementById("pay-check").checked?"":"none"}) +c.addEventListener("change",()=>{s.innerHTML='';const chosen=c.value;setTimeout(()=>{if(c.value!==chosen)return;s.innerHTML=''+(STATES[chosen]||[]).map(([v,n])=>'').join("")},150)})`, + ) + }, + // Two street boxes one after the other with the same label, the second + // only "(optional)", and a billing address after the shipping one in + // the same form under headings alone: the first two are one address's + // lines, and the billing address is still its own. + "address-optional-line": async (req) => { + const slug = "address-optional-line" + if (req.method === "POST") return k.savedProfile(req, slug) + const block = (p: string, second: boolean) => + ` + ${second ? `` : ""} + +
+
` + return h( + "Checkout", + `

Checkout

+

Shipping address

${block("ship", true)} +

Billing address

${block("bill", false)} +
`, + slug, + ) + }, // Signs in without a page load: a wrong password shows an alert and // clears the box; the right one swaps the form for an app shell whose // only sign of the account is an avatar menu. diff --git a/extension/e2e/run.ts b/extension/e2e/run.ts index ba0a0287..90e91da2 100644 --- a/extension/e2e/run.ts +++ b/extension/e2e/run.ts @@ -1313,6 +1313,8 @@ interface LaunchOptions { keyLogin?: boolean /** "deny": the fake host turns down Touch ID for a card's number. */ touchId?: string + /** The fake host adds "Mailing", an identity with its whole address in its first line. */ + oneLine?: boolean /** http origins the browser treats as secure contexts, which WebAuthn needs. */ secure?: string[] } @@ -1358,6 +1360,7 @@ async function launch(options: LaunchOptions = {}): Promise { DEADBOLT_FAKE_GOOGLE: options.google ? "1" : "", DEADBOLT_FAKE_KEYLOGIN: options.keyLogin ? "1" : "", DEADBOLT_FAKE_TOUCHID: options.touchId ?? "", + DEADBOLT_FAKE_ONE_LINE: options.oneLine ? "1" : "", ...options.realHost, }, }) diff --git a/extension/src/content/formfill.ts b/extension/src/content/formfill.ts index c4430780..45814d52 100644 --- a/extension/src/content/formfill.ts +++ b/extension/src/content/formfill.ts @@ -140,6 +140,14 @@ const approveCheck = (kind: FormKind, ours?: Element | null) => (el: FormControl /** A select with nothing to choose yet: disabled, or only placeholder options (no value). */ const unloaded = (el: FormControl) => el instanceof HTMLSelectElement && (el.disabled || !Array.from(el.options).some((o) => o.value)) +/** + * A state select beside a country that doesn't list the identity's region + * yet: a placeholder with a value of its own (``), + * or another country's regions, until the country chosen loads its own. + */ +const awaitsCountry = (f: FormField, roles: FormRole[], values: FormValues) => + f.el instanceof HTMLSelectElement && f.role === "address-level1" && !!values.region && roles.includes("country") && valueFor(f.role, f.el, values) === undefined + /** Roles a mask often formats as they're typed, turning a whole value written at once down (see typeChars). */ const MASKED = new Set(["cc-number", "cc-exp", "tel", "tel-national"]) @@ -202,6 +210,8 @@ async function fillAll(fields: FormField[], given: FormValues, check: (el: FormC const ok = (group: FormField[]) => (el: FormControl) => group.every(formFieldInPlace) && check(el) const done = new Set() const later: FormField[] = [] + /** Of `later`, the state selects that wait only on a country this fill chose. */ + const onCountry = new Set() for (const f of ordered) { if (done.has(f)) continue if (f.role === "cc-number" && f.split) { @@ -225,6 +235,12 @@ async function fillAll(fields: FormField[], given: FormValues, check: (el: FormC later.push(f) continue } + // So does a state select with no option for the region: the country's change may load it. + if (awaitsCountry(f, roles, values)) { + later.push(f) + onCountry.add(f) + continue + } // A combobox for a country or state is chosen in, not typed in (see combobox.ts). if (isCombobox(f.el) && CHOICE_ROLES.has(f.role)) { const choice = choiceFor(f.role, values) @@ -251,8 +267,10 @@ async function fillAll(fields: FormField[], given: FormValues, check: (el: FormC // option, through the full check. const until = Date.now() + DEPENDENT_WAIT_MS for (const f of filled.length ? later : []) { - let value: string | undefined - while (Date.now() < until && (unloaded(f.el) || (value = valueFor(f.role, f.el, values)) === undefined)) await sleep(100) + // No country chosen, no list to wait for: a state the select doesn't have is left alone at once. + if (onCountry.has(f) && !filled.includes("country")) continue + while ((unloaded(f.el) || valueFor(f.role, f.el, values) === undefined) && Date.now() < until) await sleep(100) + const value = unloaded(f.el) ? undefined : valueFor(f.role, f.el, values) if (!value || !ok([f])(f.el)) continue if (setFormValue(f.el, value, ok([f]))) { filled.push(f.role) diff --git a/extension/src/content/forms.ts b/extension/src/content/forms.ts index 6138a1d3..bf2b0f9d 100644 --- a/extension/src/content/forms.ts +++ b/extension/src/content/forms.ts @@ -63,11 +63,11 @@ export function plain(text: string): string { * Whole words for Latin and Cyrillic text; CJK, which runs words together, * matches anywhere. The patterns below are written `\b(…)\b` for reading. */ -const w = (r: RegExp) => - new RegExp(r.source.replace(/^\\b\(/, "(? + new RegExp(r.source.replace(/^\\b\(/, "(? = ([ ["family-name", /\b(last ?name|surname|family ?name|lname|last|nachname|familienname|nom de famille|nom(?! complet)|apellidos?|cognome|achternaam|sobrenome|фамилия)\b/], ["honorific-prefix", /\b(salutation|honorific|anrede|civilite|tratamiento|prefix)\b/], ["address-line3", /\b(address ?(line)? ?3|address3|addr3|street3)\b/], - ["address-line2", /\b(address ?(line)? ?2|address2|addr2|street2|apt|apartment|suite|unit|flat|floor|building|adresszusatz|complemento|complement( d adresse)?|piso)\b/], + // A second street line by its number, by what it holds (a unit), or by how forms word it: "Address continued", "Additional address", "c/o". + ["address-line2", /\b(address ?(line)? ?(2|two)|address2|addr ?2|street ?(address ?)?(2|two)|line ?(2|two)|second ?(address ?|street ?)?line|(address|addr|street|line) ?(continued|continuation|contd?)|(additional|secondary|extra) (street ?)?address|care of|c ?\/ ?o|apt|apartment|suite|unit|flat|floor|building|adresszusatz|complemento|complement( d adresse)?|piso)\b/], ["address-line1", /\b(address ?(line)? ?1|address1|addr1|street1|street( address)?|address|strasse|stra[sß]e und hausnummer|calle|rue|straat|direccion|adresse|indirizzo|endereco|住所|地址|адрес)\b/], ["postal-code", /\b(zip( ?code)?|postal( ?code)?|post ?code|postcode|plz|postleitzahl|codigo postal|code postal|cep|cap|郵便番号|邮编|индекс)\b/], ["address-level2", /\b(city|town|suburb|locality|ort|stadt|ciudad|ville|citta|localidad|cidade|plaats|市区町村|城市|город)\b/], @@ -112,7 +113,8 @@ const LOGIN_WORDS = w(/\b(user ?name|login|password|passwort|account|benutzernam /** The role text names, if any: a label first, then the id and name. */ function fromText(display: string, code: string): FormRole | null { for (const text of [display, code]) { - if (!text.trim() || NOT_A_FORM_FIELD.test(text) || LOGIN_WORDS.test(text)) continue + if (NOT_A_FORM_FIELD.test(text)) return null + if (!text.trim() || LOGIN_WORDS.test(text)) continue for (const [role, re] of CLUES) { if (!re.test(text)) continue // "Name" next to "card" is the cardholder; plain "card" words never make an address. @@ -246,6 +248,7 @@ export function scanForms(source: ScanSource = openRoots()): FormField[] { // After the selects: an expiry in month and year dropdowns counts. notACard(found, graph) outOfContext(found, graph) + consecutiveAddressLines(found, graph) const fields = sectionsOf(found.filter((c): c is Candidate & { role: FormRole } => c.role !== null)) // One lone box guessed from its text (a newsletter's email, a phone // number on its own) isn't an address form; one the site marked is. @@ -391,6 +394,37 @@ function contextSection(el: Element): string { return "" } +/** Words that say which address a box is for: a box that names one its neighbour doesn't is another address. */ +const ADDRESS_KINDS = w(/\b(home|work|office|business|company|billing|bill to|invoice|shipping|ship to|delivery|deliver to|mailing|postal|physical|residential|permanent|temporary|current|previous|former|prior|old|new|alternate|alternative|other|different|primary|legal|registered|school|campus)\b/, "gu") +const addressKinds = (c: Candidate) => new Set((c.display + c.code).match(ADDRESS_KINDS) ?? []) + +/** + * Street lines one after the other are one address's lines. A box whose + * text only says "address" ("Address (optional)", a second box under one + * "Street address" label) right after an address's first or second line, + * with no other box between them (a field of ours or not), in the same + * form, cluster and fieldset and the same shipping or billing block, is + * that address's next line: left as a first line, it would start a new + * section (see sectionsOf) and cut the address off from its own city, state + * and postal code. Only a role guessed from text is changed, never one the + * site marked by autocomplete, and never a box that names another address + * than the one before ("Home address", then "Work address"). Two address + * blocks have a city or postal code between their streets, and stay two. + */ +function consecutiveAddressLines(found: Candidate[], graph: FormGraph) { + for (let i = 1; i < found.length; i++) { + const prev = found[i - 1] + const c = found[i] + if (c.role !== "address-line1" || (prev.role !== "address-line1" && prev.role !== "address-line2")) continue + if (!(c.el instanceof HTMLInputElement) || autocompleteRole(c.el) !== null) continue + if (formOf(c.el) !== formOf(prev.el) || graph.clusterOf(c.el) !== graph.clusterOf(prev.el) || c.el.closest("fieldset") !== prev.el.closest("fieldset")) continue + if ((tokenSection(c.el) || contextSection(c.el)) !== (tokenSection(prev.el) || contextSection(prev.el))) continue + const before = addressKinds(prev) + if ([...addressKinds(c)].some((kind) => !before.has(kind))) continue + c.role = prev.role === "address-line1" ? "address-line2" : "address-line3" + } +} + /** * Groups fields into sections: per form (or the page, for fields outside * one), then by the autocomplete section words, then by their diff --git a/extension/src/content/transform.ts b/extension/src/content/transform.ts index cdddd542..db0a841a 100644 --- a/extension/src/content/transform.ts +++ b/extension/src/content/transform.ts @@ -93,6 +93,36 @@ export function matchOption(el: HTMLSelectElement, wanted: string[]): string | u return opts.find((o) => wanted.some((w) => w.length > 2 && plain(o.text).trim().startsWith(w)))?.value } +/** Every region name in the tables, plain: "west virginia" holds "virginia" and isn't it. */ +const REGION_NAMES = [...new Set(Object.values(REGIONS).flatMap((table) => Object.values(table).map((name) => plain(name).trim())))] + +/** + * A region in a select whose values are the site's own numbers and whose + * text carries the code beside the name ("NY - New York", "New York (NY)"): + * the option that reads as exactly the two together, else the only option + * that holds the name as whole words ("State of New York") and no longer + * region's name around it ("West Virginia" for Virginia), or, for a region + * known only by its code, the only one that starts or ends with it. Two + * options that could be it give none; an option with no value is a prompt. + */ +function regionOption(el: HTMLSelectElement, forms: string[]): string | undefined { + const opts = Array.from(el.options) + .filter((o) => !o.disabled && o.value) + .map((o) => ({ value: o.value, text: ` ${plain(o.text).trim()} ` })) + const only = (is: (text: string) => boolean) => { + const found = opts.filter((o) => is(o.text)) + return found.length === 1 ? found[0].value : undefined + } + const whole = (w: string) => { + const longer = REGION_NAMES.filter((name) => name !== w && ` ${name} `.includes(` ${w} `)) + return only((text) => text.includes(` ${w} `) && !longer.some((name) => text.includes(` ${name} `))) + } + const [code, name] = forms + if (name) return only((text) => text === ` ${code} ${name} ` || text === ` ${name} ${code} `) ?? whole(name) + if (!code) return undefined + return code.length <= 3 ? only((text) => text.startsWith(` ${code} `) || text.endsWith(` ${code} `)) : whole(code) +} + // ---- Values per role ------------------------------------------------------------- /** A full name's given and family names: all but the last word, and the last. */ @@ -219,7 +249,7 @@ export function valueFor(role: FormRole, el: FormControl, v: FormValues): string case "address-level1": { if (!v.region) return undefined const forms = regionForms(v.region, v.country ?? "") - if (select) return matchOption(select, forms) + if (select) return matchOption(select, forms) ?? regionOption(select, forms) // A two- or three-letter box takes the code. const len = maxLen(el) return len > 0 && len <= 3 && forms[0].length <= len ? forms[0].toUpperCase() : v.region diff --git a/extension/test/detect.test.ts b/extension/test/detect.test.ts index 24bb9413..7f49c966 100644 --- a/extension/test/detect.test.ts +++ b/extension/test/detect.test.ts @@ -540,6 +540,104 @@ describe("identity and payment forms", () => { expect(c.section).not.toBe(a.section) }) + test("a second street line by its wording, not only its number", () => { + // Between a city and a postal code, so only its own words can say what it is. + const roleOf = (label: string) => { + page(`
`, "/checkout") + return scanForms().find((f) => f.el.id === "b")?.role + } + const second = ["Current Address Continued", "Address (cont.)", "Address cont'd", "Street Address 2", "Address Line Two", "Second address line", "Line 2", "Mailing address 2", "Additional address information", "Secondary address", "Extra address details", "Care of", "C/O"] + expect(second.map((label) => [label, roleOf(label)])).toEqual(second.map((label) => [label, "address-line2"])) + // "Contact" and "Continue" aren't "cont."; an address that's merely somebody's is still a first line. + const first = ["Contact address", "Address to continue with", "Street address"] + expect(first.map((label) => [label, roleOf(label)])).toEqual(first.map((label) => [label, "address-line1"])) + }) + + // A payout form's mailing address: its second line is "… Continued", with no number anywhere and no autocomplete. + test("an address and its continued line are one section with their city, country, state and postal code", () => { + page(`
+ + + + + + +
`, "/payment") + const fields = scanForms() + expect(fields.map((f) => f.role)).toEqual(["given-name", "family-name", "address-line1", "address-line2", "address-level2", "country", "address-level1", "postal-code"]) + expect(new Set(fields.map((f) => f.section)).size).toBe(1) + }) + + test("street boxes one after the other are one address's lines", () => { + page(`
+ + +
`, "/checkout") + let fields = scanForms() + expect(fields.map((f) => f.role)).toEqual(["address-line1", "address-line2", "address-level2", "postal-code"]) + expect(new Set(fields.map((f) => f.section)).size).toBe(1) + // Three of them, the first marked by the site: the two guessed after it follow on. + page(`
`, "/checkout") + fields = scanForms() + expect(fields.map((f) => f.role)).toEqual(["address-line1", "address-line2", "address-line3", "address-level2"]) + expect(new Set(fields.map((f) => f.section)).size).toBe(1) + }) + + test("two addresses in one form, each with its city and postal code, are still two sections", () => { + const block = (p: string, second: boolean) => + `${second ? `` : ""} + ` + page(`

Shipping address

${block("s", true)}

Billing address

${block("b", false)}
`, "/checkout") + const fields = scanForms() + expect(fields.map((f) => f.role)).toEqual(["address-line1", "address-line2", "address-level2", "address-level1", "postal-code", "address-line1", "address-level2", "address-level1", "postal-code"]) + const sections = [...new Set(fields.map((f) => f.section))] + expect(sections.length).toBe(2) + expect(fields.map((f) => sections.indexOf(f.section))).toEqual([0, 0, 0, 0, 0, 1, 1, 1, 1]) + }) + + test("a street box that names another address, or that the site marked, is no second line", () => { + // Each address on one line: "Work address" isn't the home address's second line. + page(`
`, "/profile") + expect(scanForms().map((f) => [f.el.id, f.role])).toEqual([["n", "name"], ["a", "address-line1"]]) + page(`
`, "/checkout") + expect(formRoles()).toEqual(["address-line1", "address-line1"]) + page(`
`, "/checkout") + const [a, b] = scanForms() + expect([a.role, b.role]).toEqual(["address-line1", "address-line1"]) + expect(a.section).not.toBe(b.section) + }) + + test("an address box in another fieldset, another part of the page, or that says it's a different one, is no second line", () => { + const second = () => scanForms().find((f) => f.el.id === "b")?.role + // Two fieldsets, each with one "Address" box: the legends name the addresses, the boxes don't. + const sets = (work: string) => + `
Home address
${work}
` + page(sets(`
Work address
`), "/profile") + expect(second()).not.toBe("address-line2") + // One fieldset around both boxes is still one address. + page(`
Home address
`, "/profile") + expect(second()).toBe("address-line2") + // No form: two sections of the page are two clusters. + page(`

Home

Work

`, "/profile") + expect(second()).toBe("address-line1") + page(`
`, "/profile") + expect(second()).not.toBe("address-line2") + page(`
`, "/profile") + expect(second()).not.toBe("address-line2") + }) + + test("a box between two street boxes parts them, whether or not it's a field of ours", () => { + const fields = (label: string, name = "") => { + page(`
`, "/apply") + return scanForms().map((f) => [f.el.id, f.role]) + } + const two = [["n", "name"], ["a", "address-line1"], ["b", "address-line1"], ["c", "address-level2"]] + // How long somebody has lived there is no line of the address, for all that it says "address", and its name does too. + expect(fields("Years at address", "address_years")).toEqual(two) + expect(fields("How long have you lived at this address?", "address_duration")).toEqual(two) + expect(fields("Monthly rent")).toEqual(two) + }) + test("a card: number, expiry as one box, code, name on card", () => { page(`
diff --git a/extension/test/fill.test.ts b/extension/test/fill.test.ts index 71884ff0..57ec550b 100644 --- a/extension/test/fill.test.ts +++ b/extension/test/fill.test.ts @@ -476,6 +476,31 @@ describe("form values", () => { expect(valueFor("address-level1", el(``), { ...alex, region: "New York" })).toBe("NY") }) + test("a region in a select with the site's own numbers for values and the code beside the name", () => { + const states = (...texts: string[]) => el(``) + expect(valueFor("address-level1", states("NJ - New Jersey", "NY - New York", "VA - Virginia", "WV - West Virginia"), alex)).toBe("2") + expect(valueFor("address-level1", states("NJ - New Jersey", "NY - New York", "VA - Virginia", "WV - West Virginia"), { ...alex, region: "Virginia" })).toBe("3") + expect(valueFor("address-level1", states("AR - Arkansas", "KS - Kansas"), { ...alex, region: "Kansas" })).toBe("2") + expect(valueFor("address-level1", states("New Jersey (NJ)", "New York (NY)"), alex)).toBe("2") + expect(valueFor("address-level1", states("State of New Jersey", "State of New York"), alex)).toBe("2") + // "West Virginia" holds "Virginia" and isn't it, alone or beside the real one. + expect(valueFor("address-level1", states("WV - West Virginia"), { ...alex, region: "VA" })).toBeUndefined() + expect(valueFor("address-level1", states("WV - West Virginia"), { ...alex, region: "Virginia" })).toBeUndefined() + expect(valueFor("address-level1", states("State of Virginia", "WV - West Virginia"), { ...alex, region: "VA" })).toBe("1") + expect(valueFor("address-level1", states("West Virginia (WV)", "Commonwealth of Virginia"), { ...alex, region: "West Virginia" })).toBe("1") + // An option with no value is a prompt, whatever it says. + const prompted = (...texts: string[]) => el(``) + expect(valueFor("address-level1", prompted("NJ - New Jersey"), alex)).toBeUndefined() + expect(valueFor("address-level1", prompted("State of New Jersey", "State of New York"), alex)).toBe("2") + // Two options that could be it, another region's code, or only the placeholder: none. + expect(valueFor("address-level1", states("Upstate New York", "Downstate New York"), alex)).toBeUndefined() + expect(valueFor("address-level1", states("AR - Arkansas"), { ...alex, region: "KS" })).toBeUndefined() + expect(valueFor("address-level1", states("NYC - New York City borough"), { ...alex, region: "NV" })).toBeUndefined() + expect(valueFor("address-level1", states(), alex)).toBeUndefined() + // A region known only by its code, in a country with no table here. + expect(valueFor("address-level1", states("BE - Berlin", "BY - Bayern"), { ...alex, country: "DE", region: "BY" })).toBe("2") + }) + test("birthday whole and in parts", () => { expect(valueFor("bday", el(``), alex)).toBe("1990-07-04") expect(valueFor("bday", el(``), alex)).toBe("07/04/1990") diff --git a/extension/test/formfill.test.ts b/extension/test/formfill.test.ts index e19b3b53..fad787c7 100644 --- a/extension/test/formfill.test.ts +++ b/extension/test/formfill.test.ts @@ -1,6 +1,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test" import { approveForms, fillCheck, fillForm, offScreen, takeApproved, type FormsState } from "../src/content/formfill" import { formFieldInPlace, scanForms } from "../src/content/forms" +import type { FormRole } from "../src/messages" // happy-dom does no layout: each element sits where its data-y says on a // page 800 px tall in view, scrolled by "scrolled"; data-x, data-w and data-h @@ -251,3 +252,88 @@ describe("fields in a shadow root under the page's form", () => { expect(formFieldInPlace(f)).toBe(false) }) }) + +// A payout form's mailing address, as claims and benefits sites draw it: +// "… Continued" for the second street line, 40 characters a line, and a +// state list that holds only until the +// country is chosen, then loads options whose values are the site's own numbers. +describe("a mailing address with a continued line and states that load after the country", () => { + const STATES: Record = { US: ``, CA: `` } + function mailing(countries = ``) { + document.body.innerHTML = ` + + + + + + + ` + const country = $("country") as unknown as HTMLSelectElement + const state = $("state") as unknown as HTMLSelectElement + country.addEventListener("change", () => { + state.innerHTML = `` + const chosen = country.value + setTimeout(() => chosen === country.value && (state.innerHTML = `${STATES[chosen] ?? ""}`), 150) + }) + } + const all = () => ["first", "last", "street", "more", "city", "country", "state", "zip"].map((id) => $(id).value) + const ROLES: FormRole[] = ["given-name", "family-name", "address-line1", "address-line2", "address-level2", "country", "address-level1", "postal-code"] + const alex = { "given-name": "Alex", "family-name": "Mercer" } + + test("an identity with its whole address on one line fills every part, the street within its 40 characters", async () => { + mailing() + const line = "123 Main St, San Francisco, CA, 94117, United States" + expect(line.length).toBeGreaterThan(40) + const { filled } = await fillForm(scanForms(), { ...alex, "address-line1": line }, () => true) + expect(all()).toEqual(["Alex", "Mercer", "123 Main St", "", "San Francisco", "US", "5", "94117"]) + expect(filled.sort()).toEqual(ROLES.filter((r) => r !== "address-line2").sort()) + expect(($("state") as unknown as HTMLSelectElement).selectedOptions[0].text).toBe("CA - California") + }) + + test("a unit in the line goes into the continued box", async () => { + mailing() + await fillForm(scanForms(), { ...alex, "address-line1": "123 Main St, Apt 4, Brooklyn, NY, 11201, United States" }, () => true) + expect(all()).toEqual(["Alex", "Mercer", "123 Main St", "Apt 4", "Brooklyn", "US", "32", "11201"]) + }) + + test("an identity with its address in parts: the state is chosen once the country's states load", async () => { + mailing() + const { filled } = await fillForm(scanForms(), { ...alex, "address-line1": "123 Main St", "address-line2": "Apt 4", city: "Brooklyn", region: "NY", "postal-code": "11201", country: "US" }, () => true) + expect(all()).toEqual(["Alex", "Mercer", "123 Main St", "Apt 4", "Brooklyn", "US", "32", "11201"]) + expect(filled.sort()).toEqual([...ROLES].sort()) + expect(($("state") as unknown as HTMLSelectElement).selectedOptions[0].text).toBe("NY - New York") + }) + + test("with no country chosen there's no list to wait for: the state is left at once", async () => { + mailing(``) + const start = Date.now() + const { filled } = await fillForm(scanForms(), { ...alex, "address-line1": "123 Main St", city: "Brooklyn", region: "NY", "postal-code": "11201", country: "US" }, () => true) + expect(Date.now() - start).toBeLessThan(1500) + expect(filled).not.toContain("address-level1") + expect([$("country").value, $("state").value]).toEqual(["0", "0"]) + }) + + // The wait is one for all of them: a list that loaded while an earlier one used the wait up is still chosen from. + test("a list that loaded while an earlier one never did is still chosen from", async () => { + document.body.innerHTML = `
+ + + +
` + const fields = scanForms() + expect(fields.map((f) => f.role)).toEqual(["given-name", "honorific-prefix", "country"]) + const now = Date.now + // The country's list arrives, and then the wait is over while the salutation, first in line, is still waiting. + setTimeout(() => { + $("country").innerHTML = `` + Date.now = () => now() + 60_000 + }, 150) + try { + const { filled } = await fillForm(fields, { ...alex, honorific: "Dr", country: "US" }, () => true) + expect([$("country").value, $("salutation").value]).toEqual(["US", ""]) + expect(filled.sort()).toEqual(["country", "given-name"]) + } finally { + Date.now = now + } + }) +})