detect.test.ts

11.2 KB · raw

1// @vitest-environment jsdom23import { beforeEach, describe, expect, it, vi } from "vitest";45import {6  detectCardForm,7  detectLoginFields,8  getPageDomain,9  hasPaymentProcessorIframe,10  isLoginForm,11  isSignupForm,12  isTOTPField,13  querySelectorAllDeep,14} from "./detect";1516describe("content detect", () => {17  beforeEach(() => {18    document.body.innerHTML = "";19  });2021  function visibleInput(22    attributes: Record<string, string> = {},23    tagName: "input" = "input"24  ): HTMLInputElement {25    const input = document.createElement(tagName);26    Object.entries(attributes).forEach(([key, value]) => input.setAttribute(key, value));27    Object.defineProperty(input, "getBoundingClientRect", {28      configurable: true,29      value: () => ({30        width: 100,31        height: 20,32        top: 0,33        left: 0,34        right: 100,35        bottom: 20,36        x: 0,37        y: 0,38        toJSON: () => ({}),39      }),40    });41    document.body.appendChild(input);42    return input as HTMLInputElement;43  }4445  it("isLoginForm returns true for a username/password pair", () => {46    const username = visibleInput({ type: "email", name: "email" });47    const password = visibleInput({ type: "password", autocomplete: "current-password" });4849    expect(50      isLoginForm([51        { type: "username", el: username },52        { type: "password", el: password },53      ])54    ).toBe(true);55  });5657  it("isLoginForm returns false for fields without a password", () => {58    const username = visibleInput({ type: "text", name: "username" });5960    expect(isLoginForm([{ type: "username", el: username }])).toBe(false);61  });6263  it("isSignupForm returns true for confirm-password flows", () => {64    const password = visibleInput({ type: "password", name: "password" });65    const confirm = visibleInput({ type: "password", name: "confirmPassword" });6667    expect(68      isSignupForm([69        { type: "password", el: password },70        { type: "password", el: confirm },71      ])72    ).toBe(true);73  });7475  it("isSignupForm returns false for a single current-password field", () => {76    const password = visibleInput({ type: "password", autocomplete: "current-password" });7778    expect(isSignupForm([{ type: "password", el: password }])).toBe(false);79  });8081  it("detectLoginFields matches email and username-style inputs but not tag-name fields", () => {82    const email = visibleInput({ type: "email", name: "email" });83    const username = visibleInput({ type: "text", name: "login-id" });84    const tagName = visibleInput({ type: "text", name: "tag-name" });85    const password = visibleInput({ type: "password", autocomplete: "current-password" });86    const hidden = visibleInput({ type: "hidden", name: "username" });8788    const fields = detectLoginFields(document);8990    expect(fields.some((field) => field.el === email && field.type === "email")).toBe(true);91    expect(fields.some((field) => field.el === username && field.type === "username")).toBe(true);92    expect(fields.some((field) => field.el === password && field.type === "password")).toBe(true);93    expect(fields.some((field) => field.el === tagName)).toBe(false);94    expect(fields.some((field) => field.el === hidden)).toBe(false);95  });9697  it("getPageDomain falls back to the current hostname when no registrable domain exists", () => {98    expect(getPageDomain()).toBe(window.location.hostname);99  });100101  it("isTOTPField detects one-time-code fields without matching generic code words", () => {102    const oneTimeCode = visibleInput({ autocomplete: "one-time-code" });103    const otpName = visibleInput({ name: "otp" });104    const verification = visibleInput({ placeholder: "Verification code" });105    const zipCode = visibleInput({ name: "zipcode" });106107    expect(isTOTPField(oneTimeCode)).toBe(true);108    expect(isTOTPField(otpName)).toBe(true);109    expect(isTOTPField(verification)).toBe(true);110    expect(isTOTPField(zipCode)).toBe(false);111  });112113  it("isTOTPField detects an adjacent 2FA label", () => {114    const label = document.createElement("label");115    label.textContent = "2FA Code";116    document.body.appendChild(label);117    const input = visibleInput({ placeholder: "If enabled" });118119    expect(isTOTPField(input)).toBe(true);120  });121122  // Regression: numeric 2FA boxes are usually type="number", where the maxlength123  // ATTRIBUTE is set to 1 but the .maxLength PROPERTY ignores it and reports a124  // large default. Detection must key on the attribute so each digit box is125  // recognised as a split-OTP box, not a full TOTP field getting its own icon.126  it("isTOTPField ignores type=number split-OTP digit boxes", () => {127    for (let i = 0; i < 6; i++) {128      const box = visibleInput({ type: "number", maxlength: "1", name: "otp" });129      expect(isTOTPField(box)).toBe(false);130    }131  });132133  it("detectLoginFields skips type=number split-OTP digit boxes", () => {134    for (let i = 0; i < 6; i++) {135      visibleInput({ type: "number", maxlength: "1", name: "otp" });136    }137    expect(detectLoginFields(document)).toEqual([]);138  });139140  // PCH-01-025: ids may legally contain CSS-special chars; field detection141  // must not throw a SyntaxError out of the label[for=...] lookup.142  it("field_detection_does_not_throw_on_id_with_css_special_chars", () => {143    const label = document.createElement("label");144    label.setAttribute("for", "user[email]");145    label.textContent = "Email";146    document.body.appendChild(label);147    const email = visibleInput({ type: "email", name: "email", id: "user[email]" });148    visibleInput({ type: "password", autocomplete: "current-password" });149150    let fields: ReturnType<typeof detectLoginFields> = [];151    expect(() => {152      fields = detectLoginFields(document);153    }).not.toThrow();154    expect(fields.some((field) => field.el === email)).toBe(true);155  });156157  it("field_detection_does_not_throw_on_id_with_quotes", () => {158    const email = visibleInput({ type: "email", name: "email", id: "it's-me" });159    visibleInput({ type: "password", autocomplete: "current-password" });160161    let fields: ReturnType<typeof detectLoginFields> = [];162    expect(() => {163      fields = detectLoginFields(document);164    }).not.toThrow();165    expect(fields.some((field) => field.el === email)).toBe(true);166  });167});168169describe("card form detection", () => {170  beforeEach(() => {171    document.body.innerHTML = "";172  });173174  it("detectCardForm — finds number field by autocomplete attribute", () => {175    document.body.innerHTML = '<input autocomplete="cc-number" /><input autocomplete="cc-exp-month" /><input autocomplete="cc-exp-year" /><input autocomplete="cc-csc" />';176    const result = detectCardForm(document);177    expect(result).not.toBeNull();178    expect(result!.number).toBeTruthy();179    expect(result!.expMonth).toBeTruthy();180  });181182  it("detectCardForm — finds fields by name/id heuristics when no autocomplete", () => {183    document.body.innerHTML = '<input name="cardnum" /><input name="expiry" /><input name="cvv" />';184    const result = detectCardForm(document);185    expect(result).not.toBeNull();186    expect(result!.number).toBeTruthy();187  });188189  it("detectCardForm — returns null when no card number field found", () => {190    document.body.innerHTML = '<input type="text" name="username" />';191    expect(detectCardForm(document)).toBeNull();192  });193194  it("hasPaymentProcessorIframe — returns true when Stripe iframe present", () => {195    document.body.innerHTML = '<iframe src="https://js.stripe.com/v3/"></iframe>';196    expect(hasPaymentProcessorIframe()).toBe(true);197  });198199  it("hasPaymentProcessorIframe — returns false on standard checkout page", () => {200    document.body.innerHTML = '<input name="cardnum" />';201    expect(hasPaymentProcessorIframe()).toBe(false);202  });203204  it("querySelectorAllDeep — returns each match once regardless of nesting depth", () => {205    document.body.innerHTML = '<div><div><div><div><form><input name="a" /></form></div></div></div></div>';206    const matches = querySelectorAllDeep<HTMLInputElement>(document, "input");207    expect(matches).toHaveLength(1);208  });209210  it("querySelectorAllDeep — finds a field that is a direct child of a shadow root", () => {211    const host = document.createElement("div");212    document.body.appendChild(host);213    const shadow = host.attachShadow({ mode: "open" });214    const input = document.createElement("input");215    input.name = "shadow-direct";216    shadow.appendChild(input);217218    const matches = querySelectorAllDeep<HTMLInputElement>(document, "input");219    expect(matches).toEqual([input]);220  });221222  it("querySelectorAllDeep — finds a nested shadow tree and keeps light children once", () => {223    const outer = document.createElement("div");224    document.body.appendChild(outer);225    const outerShadow = outer.attachShadow({ mode: "open" });226    const lightInput = document.createElement("input");227    outer.appendChild(lightInput);228    const innerHost = document.createElement("div");229    outerShadow.appendChild(innerHost);230    const innerShadow = innerHost.attachShadow({ mode: "open" });231    const deepInput = document.createElement("input");232    innerShadow.appendChild(deepInput);233234    const matches = querySelectorAllDeep<HTMLInputElement>(document, "input");235    expect(matches).toEqual([lightInput, deepInput]);236  });237238  it("detectLoginFields — a nested username/password form classifies as login, not signup", () => {239    document.body.innerHTML =240      '<div><div><form><input name="username" autocomplete="username" />' +241      '<input type="password" autocomplete="current-password" /></form></div></div>';242    for (const input of Array.from(document.querySelectorAll("input"))) {243      Object.defineProperty(input, "getBoundingClientRect", {244        configurable: true,245        value: () => ({ width: 100, height: 20, top: 0, left: 0, right: 100, bottom: 20 }),246      });247    }248249    const fields = detectLoginFields();250    expect(fields.filter((field) => field.type === "password")).toHaveLength(1);251    expect(isLoginForm(fields)).toBe(true);252    expect(isSignupForm(fields)).toBe(false);253  });254255  it("querySelectorAllDeep — uses a bounded number of queries for a deep chain", () => {256    let markup = '<input name="leaf" />';257    for (let depth = 0; depth < 40; depth++) markup = `<div>${markup}</div>`;258    document.body.innerHTML = markup;259260    const spies = [261      vi.spyOn(Element.prototype, "querySelectorAll"),262      vi.spyOn(Document.prototype, "querySelectorAll"),263      vi.spyOn(DocumentFragment.prototype, "querySelectorAll"),264    ];265    try {266      const matches = querySelectorAllDeep<HTMLInputElement>(document, "input");267      expect(matches).toHaveLength(1);268      const calls = spies.reduce((total, spy) => total + spy.mock.calls.length, 0);269      // One selector query plus one host scan for the single document root. The270      // re-querying form issued one query per visited ancestor (~40 here).271      expect(calls).toBe(2);272    } finally {273      for (const spy of spies) spy.mockRestore();274    }275  });276277  it("querySelectorAllDeep — still finds fields nested inside a shadow root", () => {278    const host = document.createElement("div");279    document.body.appendChild(host);280    const shadow = host.attachShadow({ mode: "open" });281    const wrapper = document.createElement("div");282    const input = document.createElement("input");283    wrapper.appendChild(input);284    shadow.appendChild(wrapper);285286    const matches = querySelectorAllDeep<HTMLInputElement>(document, "input");287    expect(matches).toEqual([input]);288  });289});