content.detect.test.ts

18.8 KB · raw

1// @vitest-environment jsdom2//3// Test File 7 — detect.ts field detection (T-DT01–T-DT21).4//5// detect.ts is the foundation of the whole autofill layer: every gate in6// index.ts asks it "is this a login/signup/email-first/card/totp form?". A7// false positive injects an icon onto a search box; a false negative means the8// user's saved login never offers to fill. These tests pin the classification9// boundaries against real HTML structures that production sites emit.1011import { beforeEach, describe, expect, it } from "vitest";1213import {14  detectCardForm,15  detectLoginFields,16  findOTPDigitBoxGroup,17  findOtpSignalingGroup,18  isAnyCredentialForm,19  isEmailFirstForm,20  isLoginForm,21  isSignupForm,22  isTOTPField,23  isVisible,24} from "./detect";25import { makeFieldVisible, makeInput } from "./_setup";2627// These tests assert detection by *membership* (fields.some) and gate "is this28// page fillable?" through isAnyCredentialForm (the exact predicate index.ts29// uses). The precise login-vs-signup classifier contract is exercised on clean,30// hand-built arrays; detect.test.ts covers the end-to-end classification.3132beforeEach(() => {33  document.body.innerHTML = "";34});3536// Build a form, append it, and return it. Children are added via makeInput so37// every field gets a non-zero bounding rect (jsdom defaults to 0×0, which38// detect.ts's isVisible() would reject).39function form(): HTMLFormElement {40  const f = document.createElement("form");41  document.body.appendChild(f);42  return f;43}4445describe("T-DT01–T-DT03, T-DT06: form-shape classification", () => {46  // T-DT01: a text + current-password pair is the canonical login form. If this47  // regresses, saved logins stop offering on the most common form on the web.48  it("T-DT01: text + password → detected as a fillable login form", () => {49    const f = form();50    const u = makeInput({ type: "text", name: "username", autocomplete: "username" }, f);51    const p = makeInput({ type: "password", name: "password", autocomplete: "current-password" }, f);52    const fields = detectLoginFields();53    expect(fields.some((x) => x.el === u && x.type === "username")).toBe(true);54    expect(fields.some((x) => x.el === p && x.type === "password")).toBe(true);55    // The gate index.ts actually consults:56    expect(isAnyCredentialForm(fields)).toBe(true);57    // Classifier contract on a clean field set:58    expect(isLoginForm([{ type: "username", el: u }, { type: "password", el: p }])).toBe(true);59  });6061  // T-DT02: two password fields (password + confirm) is the signature of signup.62  // Misclassifying it as login would offer the saved-password selector on an63  // account-creation form.64  it("T-DT02: text + new-password + confirm → isSignupForm true, isLoginForm false", () => {65    const f = form();66    makeInput({ type: "text", name: "username" }, f);67    makeInput({ type: "password", name: "new-password", autocomplete: "new-password" }, f);68    makeInput({ type: "password", name: "confirm", autocomplete: "new-password" }, f);69    const fields = detectLoginFields();70    expect(isSignupForm(fields)).toBe(true);71    expect(isLoginForm(fields)).toBe(false);72  });7374  // T-DT03: email-only step with an auth-intent submit button is the Google/MS75  // "enter your email first" pattern. Requires an auth signal so newsletter76  // boxes don't match.77  it("T-DT03: email-only form with auth submit → isEmailFirstForm true", () => {78    const f = form();79    makeInput({ type: "email", name: "email", autocomplete: "email" }, f);80    const btn = document.createElement("button");81    btn.type = "submit";82    btn.textContent = "Next";83    f.appendChild(btn);84    const fields = detectLoginFields();85    expect(isEmailFirstForm(fields)).toBe(true);86  });8788  // T-DT06: a search box (single text input, search submit) must NOT read as a89  // login form. False positive here is the classic "icon on the search bar" bug.90  it("T-DT06: search form → isLoginForm false", () => {91    const f = form();92    makeInput({ type: "search", name: "q", placeholder: "Search" }, f);93    const fields = detectLoginFields();94    expect(isLoginForm(fields)).toBe(false);95    expect(isSignupForm(fields)).toBe(false);96  });97});9899describe("T-DT04: TOTP field detection", () => {100  // T-DT04: autocomplete=one-time-code is the unambiguous TOTP marker. The TOTP101  // selector path keys off this; losing it breaks 2FA autofill.102  it("T-DT04: input[autocomplete=one-time-code] → isTotpField true", () => {103    const f = form();104    const otp = makeInput({ type: "text", autocomplete: "one-time-code", name: "code" }, f);105    expect(isTOTPField(otp)).toBe(true);106  });107108  it("T-DT04b: a plain password field is not a TOTP field", () => {109    const f = form();110    const pw = makeInput({ type: "password", name: "password" }, f);111    expect(isTOTPField(pw)).toBe(false);112  });113});114115describe("T-DT05: credit-card form detection", () => {116  // T-DT05: cc-number + cc-exp + cc-csc autocomplete tokens → card form. detect117  // exposes detectCardForm (returns the field set or null), not a boolean.118  it("T-DT05: cardnumber + expiry + cvc → detectCardForm returns the field set", () => {119    const f = form();120    const number = makeInput({ autocomplete: "cc-number", name: "cardnumber" }, f);121    const exp = makeInput({ autocomplete: "cc-exp", name: "exp" }, f);122    const cvc = makeInput({ autocomplete: "cc-csc", name: "cvc" }, f);123    const card = detectCardForm();124    expect(card).not.toBeNull();125    expect(card!.number).toBe(number);126    expect(card!.expiryCombo).toBe(exp);127    expect(card!.cvc).toBe(cvc);128  });129130  it("T-DT05b: a login form is not a card form", () => {131    const f = form();132    makeInput({ type: "text", name: "username" }, f);133    makeInput({ type: "password", name: "password" }, f);134    expect(detectCardForm()).toBeNull();135  });136});137138describe("T-DT07–T-DT09: isVisible branches", () => {139  // isVisible gates every detection path. Each of its three rejection reasons140  // (zero area, display:none, opacity:0) must independently return false, or141  // off-screen/hidden honeypot fields would receive icons.142143  // T-DT07: a zero-area element (jsdom default, models an unrendered field).144  it("T-DT07: zero-size rect → isVisible false", () => {145    const el = makeInput({ type: "text" });146    Object.defineProperty(el, "getBoundingClientRect", {147      configurable: true,148      value: () => ({ width: 0, height: 0, top: 0, left: 0, right: 0, bottom: 0, x: 0, y: 0, toJSON: () => ({}) }),149    });150    expect(isVisible(el)).toBe(false);151  });152153  // T-DT08: display:none.154  it("T-DT08: display:none → isVisible false", () => {155    const el = makeInput({ type: "text" });156    el.style.display = "none";157    expect(isVisible(el)).toBe(false);158  });159160  // T-DT09: opacity:0 (a common "hidden but laid out" honeypot technique).161  it("T-DT09: opacity:0 → isVisible false", () => {162    const el = makeInput({ type: "text" });163    el.style.opacity = "0";164    expect(isVisible(el)).toBe(false);165  });166167  it("T-DT09b: a normally-laid-out field → isVisible true (control)", () => {168    const el = makeInput({ type: "text" });169    expect(isVisible(el)).toBe(true);170  });171});172173describe("T-DT10: deep (shadow DOM) detection", () => {174  // T-DT10: web-component login forms render fields inside a shadow root.175  // detectLoginFields walks shadow roots via querySelectorAllDeep; a regression176  // to a flat querySelectorAll would miss every shadow-DOM login.177  it("T-DT10: login fields inside an open shadow root are detected", () => {178    const host = document.createElement("div");179    document.body.appendChild(host);180    const root = host.attachShadow({ mode: "open" });181    // Real web-component login forms wrap fields in a container element inside182    // the shadow root; querySelectorAllDeep queries each shadow root directly,183    // so both wrapped and direct children surface.184    const wrapper = document.createElement("div");185    root.appendChild(wrapper);186    const user = document.createElement("input");187    user.type = "text";188    user.setAttribute("name", "username");189    user.setAttribute("autocomplete", "username");190    const pass = document.createElement("input");191    pass.type = "password";192    pass.setAttribute("autocomplete", "current-password");193    wrapper.append(user, pass);194    makeFieldVisible(user);195    makeFieldVisible(pass);196197    const fields = detectLoginFields();198    expect(fields.some((f) => f.type === "password")).toBe(true);199    expect(isAnyCredentialForm(fields)).toBe(true);200  });201});202203describe("T-DT11–T-DT12: PCH-01-025 CSS-special-char id resilience", () => {204  // PCH-01-025: ids can contain CSS-special characters. detect.ts escapes them205  // with CSS.escape AND wraps the label lookup in try/catch so a single weird id206  // can never abort detection for the whole page.207  //208  // NOTE on the environment: jsdom's selector engine (nwsapi) actually THROWS on209  // CSS.escape's output for these ids, so the *label-resolution* benefit cannot210  // be observed here — it is verified in the Playwright e2e. What we pin in211  // jsdom is the resilience invariant: a field whose id is hostile to212  // querySelector must not throw out of detectLoginFields, and the other fields213  // on the page must still be found. Reverting the try/catch makes T-DT12b throw.214  it("T-DT11: id='user[email]' does not abort detection; the password is still found", () => {215    const f = form();216    makeInput({ type: "text", id: "user[email]", name: "user[email]" }, f);217    makeInput({ type: "password", autocomplete: "current-password" }, f);218    let fields: ReturnType<typeof detectLoginFields> = [];219    expect(() => { fields = detectLoginFields(); }).not.toThrow();220    expect(fields.some((x) => x.type === "password")).toBe(true);221  });222223  it("T-DT12: id=\"it's-me\" does not abort detection", () => {224    const f = form();225    makeInput({ type: "text", id: "it's-me", name: "identifier" }, f);226    makeInput({ type: "password", autocomplete: "current-password" }, f);227    expect(() => detectLoginFields()).not.toThrow();228  });229230  // T-DT12b: an id containing a double-quote genuinely throws inside a raw231  // `label[for="..."]` selector. Only the try/catch keeps detection alive — this232  // case fails the moment the catch is removed.233  it("T-DT12b: id with an embedded double-quote does not abort detection", () => {234    const f = form();235    makeInput({ type: "text", id: 'a"quote', name: "weird" }, f);236    makeInput({ type: "password", autocomplete: "current-password" }, f);237    let fields: ReturnType<typeof detectLoginFields> = [];238    expect(() => { fields = detectLoginFields(); }).not.toThrow();239    expect(fields.some((x) => x.type === "password")).toBe(true);240  });241});242243describe("T-DT13–T-DT15: label / placeholder / aria-label classification", () => {244  // T-DT13: a <label for=id> with a plain (escape-safe) id classifies an245  // otherwise-unhinted text input as the username field.246  it("T-DT13: label[for] resolves the field as username", () => {247    const f = form();248    const input = makeInput({ type: "text", id: "login_user" }, f);249    const label = document.createElement("label");250    label.setAttribute("for", "login_user");251    label.textContent = "Username";252    // Append AFTER the input so the previous-sibling heuristic cannot match —253    // forcing the for-attribute path to be the one that resolves the label.254    f.appendChild(label);255    makeInput({ type: "password", autocomplete: "current-password" }, f);256    const fields = detectLoginFields();257    expect(fields.find((x) => x.el === input)?.type).toBe("username");258  });259260  // T-DT14: placeholder text is a real-world classification signal.261  it("T-DT14: placeholder='Username' → classified username", () => {262    const f = form();263    const input = makeInput({ type: "text", placeholder: "Username" }, f);264    makeInput({ type: "password", autocomplete: "current-password" }, f);265    const fields = detectLoginFields();266    expect(fields.find((x) => x.el === input)?.type).toBe("username");267  });268269  // T-DT15: aria-label is authoritative for accessibility-first forms.270  it("T-DT15: aria-label='Email address' → classified", () => {271    const f = form();272    const input = makeInput({ type: "text", "aria-label": "Email address" }, f);273    makeInput({ type: "password", autocomplete: "current-password" }, f);274    const fields = detectLoginFields();275    expect(fields.find((x) => x.el === input)?.type).toBe("username");276  });277});278279describe("T-DT16–T-DT17: edge form shapes", () => {280  // T-DT16: many SPA login forms submit via JS and have no submit button. Field281  // classification must not depend on a button existing.282  it("T-DT16: form without a submit button is still a fillable login form", () => {283    const f = form();284    const u = makeInput({ type: "text", name: "username", autocomplete: "username" }, f);285    const p = makeInput({ type: "password", autocomplete: "current-password" }, f);286    const fields = detectLoginFields();287    expect(fields.some((x) => x.el === u)).toBe(true);288    expect(fields.some((x) => x.el === p && x.type === "password")).toBe(true);289    expect(isAnyCredentialForm(fields)).toBe(true);290    expect(isLoginForm([{ type: "username", el: u }, { type: "password", el: p }])).toBe(true);291  });292293  // T-DT17: change-password forms have old + new + confirm. Three password294  // fields must read as signup-shaped (>=2 passwords), never as login.295  it("T-DT17: old + new + confirm passwords → signup-shaped, not login", () => {296    const f = form();297    makeInput({ type: "password", name: "old-password", autocomplete: "current-password" }, f);298    makeInput({ type: "password", name: "new-password", autocomplete: "new-password" }, f);299    makeInput({ type: "password", name: "confirm-password", autocomplete: "new-password" }, f);300    const fields = detectLoginFields();301    expect(isSignupForm(fields)).toBe(true);302    expect(isLoginForm(fields)).toBe(false);303  });304});305306// ── Split-OTP grouping ──────────────────────────────────────────────────────307// The existing detector is findOTPDigitBoxGroup: it returns the ordered set of308// single-character boxes (4–10 of them) or null. index.ts uses it to open ONE309// TOTP selector anchored on the first box instead of icon-spamming all six.310describe("T-DT18–T-DT21 (existing findOTPDigitBoxGroup behavior)", () => {311  // T-DT18: a 6-box numeric group resolves to the full ordered set, anchored so312  // index.ts injects a single icon on box[0] rather than one per box.313  it("T-DT18: 6× maxlength=1 numeric inputs → group of 6 returned, first is box[0]", () => {314    const f = form();315    const boxes: HTMLInputElement[] = [];316    for (let i = 0; i < 6; i++) boxes.push(makeInput({ type: "text", maxlength: "1", inputmode: "numeric" }, f));317    const group = findOTPDigitBoxGroup(boxes[2]!);318    expect(group).not.toBeNull();319    expect(group!.length).toBe(6);320    expect(group![0]).toBe(boxes[0]);321  });322323  // T-DT19: when a real one-time-code field exists, IT is the TOTP target; the324  // single-char boxes elsewhere are a distinct concern. isTOTPField ignores325  // maxlength=1 boxes, so the proper field is the one that classifies as TOTP.326  it("T-DT19: a real one-time-code field classifies as TOTP; maxlength=1 boxes do not", () => {327    const f = form();328    const box = makeInput({ type: "text", maxlength: "1", inputmode: "numeric" }, f);329    const real = makeInput({ type: "text", autocomplete: "one-time-code", name: "otp" }, f);330    expect(isTOTPField(real)).toBe(true);331    expect(isTOTPField(box)).toBe(false);332  });333334  // T-DT21: a group below the 4-box floor is not an OTP group.335  it("T-DT21: only 2 single-char boxes → not an OTP group (null)", () => {336    const f = form();337    const boxes = [338      makeInput({ type: "text", maxlength: "1", inputmode: "numeric" }, f),339      makeInput({ type: "text", maxlength: "1", inputmode: "numeric" }, f),340    ];341    expect(findOTPDigitBoxGroup(boxes[0]!)).toBeNull();342  });343});344345// ── Addendum 2 — OTP-signaling groups without maxlength="1" ──────────────────346// Some sites render split-digit 2FA boxes as plain inputs that carry OTP347// signaling (autocomplete="one-time-code", name="otp", …) but never set348// maxlength="1". isSingleDigitBox / findOTPDigitBoxGroup miss them, so without349// findOtpSignalingGroup each box would get its own injected icon (the "peach350// icon spam in every 2FA box" bug). The group is detected by OTP signaling +351// count, so a phone-form's numeric boxes (no OTP text) are never matched.352describe("T-DT22–T-DT24: findOtpSignalingGroup (split-OTP boxes lacking maxlength)", () => {353  // T-DT22: 6 one-time-code boxes without maxlength → a single group of 6,354  // ordered, anchored on box[0]. Each box still classifies as a TOTP field355  // (the property scanTOTPFields keys on), so without grouping every one of356  // them would be injected.357  it("T-DT22: 6 one-time-code boxes (no maxlength) → group of 6, anchor is box[0]", () => {358    const f = form();359    const boxes: HTMLInputElement[] = [];360    for (let i = 0; i < 6; i++) {361      boxes.push(makeInput({ type: "text", autocomplete: "one-time-code", name: "otp" }, f));362    }363    expect(isTOTPField(boxes[3]!)).toBe(true);364    const group = findOtpSignalingGroup(boxes[3]!);365    expect(group).not.toBeNull();366    expect(group!.length).toBe(6);367    expect(group![0]).toBe(boxes[0]);368    expect(group![5]).toBe(boxes[5]);369  });370371  // T-DT23: a lone one-time-code field is NOT a group — it gets its own icon372  // via the normal lone-TOTP path. findOtpSignalingGroup returns null so the373  // caller injects on the field itself.374  it("T-DT23: a lone one-time-code field → null (not a group)", () => {375    const f = form();376    const lone = makeInput({ type: "text", autocomplete: "one-time-code", name: "code" }, f);377    expect(findOtpSignalingGroup(lone)).toBeNull();378  });379380  // T-DT24: only 3 OTP-signaling boxes is below the 4-box floor → null. Avoids381  // grouping incidental otp-named fields that happen to coexist on a form.382  it("T-DT24: only 3 one-time-code boxes → null (below 4-box floor)", () => {383    const f = form();384    const boxes: HTMLInputElement[] = [];385    for (let i = 0; i < 3; i++) {386      boxes.push(makeInput({ type: "text", autocomplete: "one-time-code", name: "otp" }, f));387    }388    expect(findOtpSignalingGroup(boxes[0]!)).toBeNull();389  });390391  // T-DT25: a maxlength="1" box is rejected by isTOTPField, so it never enters392  // an OTP-signaling group — it is handled exclusively by findOTPDigitBoxGroup.393  // Confirms the two finders don't overlap and maxlength boxes keep their394  // existing (zero-icon + focus-open) behaviour.395  it("T-DT25: a maxlength=1 box is not part of an OTP-signaling group", () => {396    const f = form();397    const boxes: HTMLInputElement[] = [];398    for (let i = 0; i < 6; i++) {399      boxes.push(makeInput({ type: "text", maxlength: "1", inputmode: "numeric", autocomplete: "one-time-code" }, f));400    }401    expect(isTOTPField(boxes[0]!)).toBe(false);402    expect(findOtpSignalingGroup(boxes[0]!)).toBeNull();403    expect(findOTPDigitBoxGroup(boxes[0]!)).not.toBeNull();404  });405});