content.field-interaction.test.ts

17.5 KB · raw

1// @vitest-environment jsdom2//3// Test File 2 — index.ts handleFieldInteraction core paths (T-F01–T-F12).4//5// handleFieldInteraction is the central decision: ML predict → suppression6// layers → TOTP/OTP branch → vault query → which surface opens. We mock the7// boundary it talks to — ./inject (so we can see WHICH surface opened) and8// ./content-ml-detector (so we can control predict timing) — and drive the REAL9// exported function with controlled DOM + chrome responses. Nothing about the10// decision logic itself is mocked.1112import { vi } from "vitest";1314// Spies shared with the hoisted vi.mock factories must themselves be hoisted.15const { predictBatch, dismissSpy } = vi.hoisted(() => ({16  predictBatch: vi.fn(() => Promise.resolve([] as unknown[])),17  dismissSpy: vi.fn(),18}));1920// Observe which inject surface opens. showAutofillSelector returns a dismiss fn.21vi.mock("./inject", () => ({22  injectFieldIcon: vi.fn(() => vi.fn()),23  showAutofillSelector: vi.fn(() => dismissSpy),24  showTOTPSelector: vi.fn(() => dismissSpy),25  showCardSelector: vi.fn(() => dismissSpy),26  showRememberSiteToast: vi.fn(),27  showPasskeyAvailable: vi.fn(),28  showPasskeyProGate: vi.fn(),29  showPasskeyRegistrationOffer: vi.fn(),30}));3132// Control ML predict timing/result per test.33vi.mock("./content-ml-detector", () => ({34  contentMLDetector: { predictBatch },35}));3637import { afterEach, beforeEach, describe, expect, it } from "vitest";38import "./_setup";39import { setMessageResponder, resetChromeMock, sentMessages, messageListeners, makeInput, createLoginForm, createEmailFirstForm } from "./_setup";40import { handleFieldInteraction } from "./index";41import { showAutofillSelector, showRememberSiteToast, showTOTPSelector } from "./inject";4243const showSelector = showAutofillSelector as unknown as ReturnType<typeof vi.fn>;44const showTOTP = showTOTPSelector as unknown as ReturnType<typeof vi.fn>;45const showRememberToast = showRememberSiteToast as unknown as ReturnType<typeof vi.fn>;4647// Reset module-private suppression state between tests by exercising the public48// surface: a fresh DOM + cleared mocks. handleFieldInteraction reads live DOM49// each call, so a clean body is a clean slate for everything except the global50// dismiss lock — which we never trip in this file (no dismissals here).51beforeEach(() => {52  document.body.innerHTML = "";53  resetChromeMock();54  showSelector.mockClear();55  showTOTP.mockClear();56  predictBatch.mockReset();57  predictBatch.mockReturnValue(Promise.resolve([]));58});5960afterEach(async () => {61  vi.useRealTimers();62  // index.ts installs a url-watcher MutationObserver on document.body that63  // reads location.href. Clearing the DOM each test queues its callback; flush64  // it here so it runs while jsdom's globals still exist, instead of throwing65  // "location is not defined" during environment teardown.66  await new Promise((r) => setTimeout(r, 0));67});6869// Last options object passed to showAutofillSelector (4th arg).70function lastSelectorOptions(): any {71  const calls = showSelector.mock.calls;72  return calls.length ? calls[calls.length - 1]![3] : undefined;73}7475describe("T-F01–T-F02: ML predict timeout race (150ms)", () => {76  // T-F02: when ML resolves IN TIME with a non-credential verdict for a text77  // field, handleFieldInteraction suppresses — the selector must NOT open.78  it("T-F02: ML resolves fast with a suppressing prediction → no selector", async () => {79    const { username } = createLoginForm();80    predictBatch.mockReturnValue(Promise.resolve([{ type: "search", confidence: 0.9 }]));81    await handleFieldInteraction(username); // passive (explicitSummon=false)82    // give any stray microtasks a tick83    await new Promise((r) => setTimeout(r, 20));84    expect(showSelector).not.toHaveBeenCalled();85  });8687  // T-F01: when ML is SLOWER than the 150ms cap, the timeout wins, the88  // prediction is discarded (treated as null), and the heuristic path proceeds —89  // so the very same suppressing verdict no longer blocks the selector. This is90  // the regression that froze autofill on pages with a slow ML worker.91  it("T-F01: ML slower than 150ms → timeout path taken, selector still opens", async () => {92    const { username } = createLoginForm();93    predictBatch.mockReturnValue(94      new Promise((resolve) => setTimeout(() => resolve([{ type: "search", confidence: 0.9 }]), 250))95    );96    setMessageResponder((msg) =>97      msg.type === "AUTOFILL_QUERY" ? { ok: true, data: [{ id: "e1", title: "Acme", username: "alice" }] } : { ok: true, data: null }98    );99    await handleFieldInteraction(username);100    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled(), { timeout: 1000 });101  });102});103104describe("T-F03–T-F05: vault state + form shape", () => {105  // T-F03: a locked vault shows the inline unlock prompt (showAutofillSelector106  // with {locked:true}), never the entry list.107  it("T-F03: locked vault → selector opened in locked mode", async () => {108    const { password } = createLoginForm();109    setMessageResponder((msg) =>110      msg.type === "AUTOFILL_QUERY" ? { ok: false, error: "vault_locked" } : { ok: true, data: null }111    );112    await handleFieldInteraction(password);113    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());114    expect(lastSelectorOptions()?.locked).toBe(true);115  });116117  // T-F04: unlocked vault with no entries for this domain → signup/identity118  // surface (isSignup:true), not a credential list.119  it("T-F04: no domain entries → signup/identity surface", async () => {120    const { password } = createLoginForm();121    setMessageResponder((msg) =>122      msg.type === "AUTOFILL_QUERY" ? { ok: true, data: [] } : { ok: true, data: null }123    );124    await handleFieldInteraction(password);125    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());126    expect(lastSelectorOptions()?.isSignup).toBe(true);127    expect(lastSelectorOptions()?.locked).toBeFalsy();128    expect(sentMessages.some((msg) => msg.type === "GET_IDENTITIES")).toBe(false);129  });130131  // T-F05: an email-first form (no password on this step) still opens on the132  // email field — the path must not bail just because there is no password.133  it("T-F05: email-first form opens on the email field", async () => {134    const { email } = createEmailFirstForm();135    setMessageResponder((msg) =>136      msg.type === "AUTOFILL_QUERY" ? { ok: true, data: [{ id: "e1", title: "Acme", username: "alice" }] } : { ok: true, data: null }137    );138    await handleFieldInteraction(email);139    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());140  });141});142143describe("T-F07: TOTP field path", () => {144  // T-F07: a lone verification-code field (no login form present) routes to the145  // TOTP selector, not the credential selector.146  it("T-F07: standalone one-time-code field → TOTP selector", async () => {147    const totp = makeInput({ type: "text", autocomplete: "one-time-code", name: "otp" });148    setMessageResponder((msg) =>149      msg.type === "AUTOFILL_QUERY" ? { ok: true, data: [{ id: "t1", title: "Acme 2FA" }] } : { ok: true, data: null }150    );151    await handleFieldInteraction(totp);152    await vi.waitFor(() => expect(showTOTP).toHaveBeenCalled());153    expect(showSelector).not.toHaveBeenCalled();154  });155});156157describe("T-F09: Peach respects the user, not the page's autocomplete=off", () => {158  // T-F09: autocomplete="off" on the form must not stop Peach offering — the159  // user installed Peach precisely to override the site's opt-out.160  it("T-F09: form with autocomplete=off still offers", async () => {161    const form = document.createElement("form");162    form.setAttribute("autocomplete", "off");163    document.body.appendChild(form);164    makeInput({ type: "text", name: "username", autocomplete: "username" }, form);165    const password = makeInput({ type: "password", autocomplete: "current-password" }, form);166    setMessageResponder((msg) =>167      msg.type === "AUTOFILL_QUERY" ? { ok: true, data: [{ id: "e1", title: "Acme", username: "alice" }] } : { ok: true, data: null }168    );169    await handleFieldInteraction(password);170    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());171  });172});173174describe("T-F10–T-F12: robustness", () => {175  // T-F10: a field whose ownerDocument is a different (cross-origin-style)176  // context must be handled without crashing. We approximate by anchoring a177  // detached input — the function must abort cleanly, never throw.178  it("T-F10/T-F12: detached field mid-interaction → clean abort, no throw, no selector", async () => {179    const detached = document.createElement("input");180    detached.type = "password"; // never attached → isVisible() false181    await expect(handleFieldInteraction(detached)).resolves.toBeUndefined();182    expect(showSelector).not.toHaveBeenCalled();183  });184185  // T-F11: two concurrent calls for the SAME field (focusin + icon click racing)186  // must not double-open — pendingInteractions debounces the second.187  it("T-F11: concurrent calls for the same field → selector opens at most once", async () => {188    const { password } = createLoginForm();189    setMessageResponder((msg) =>190      msg.type === "AUTOFILL_QUERY" ? { ok: true, data: [{ id: "e1", title: "Acme", username: "alice" }] } : { ok: true, data: null }191    );192    await Promise.all([handleFieldInteraction(password), handleFieldInteraction(password)]);193    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());194    expect(showSelector).toHaveBeenCalledTimes(1);195  });196});197198describe("PB-26-201: browser-command capability propagation", () => {199  it("passes the capability through form inventory and the selected fill", async () => {200    const { password } = createLoginForm();201    setMessageResponder((msg) => {202      if (msg.type === "AUTOFILL_QUERY") {203        return { ok: true, data: [{ id: "foreign-entry", title: "Foreign", username: "alice" }] };204      }205      if (msg.type === "GET_ENTRY_FOR_FILL") {206        return { ok: true, data: { id: "foreign-entry", title: "Foreign", username: "alice", password: "secret" } };207      }208      return { ok: true, data: null };209    });210211    await handleFieldInteraction(password, true, "form-capability");212    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());213214    expect(sentMessages.find((msg) => msg.type === "AUTOFILL_QUERY")).toMatchObject({215      payload: { includeAll: true, capability: "form-capability" },216    });217    const onSelect = showSelector.mock.calls.at(-1)![2] as (id: string) => Promise<void>;218    await onSelect("foreign-entry");219    expect(sentMessages.find((msg) => msg.type === "GET_ENTRY_FOR_FILL")).toMatchObject({220      payload: { id: "foreign-entry", capability: "form-capability" },221    });222  });223224  it("passes the capability through TOTP inventory and the selected fill", async () => {225    const totp = makeInput({ type: "text", autocomplete: "one-time-code", name: "otp" });226    setMessageResponder((msg) => {227      if (msg.type === "AUTOFILL_QUERY") return { ok: true, data: [{ id: "totp-entry", title: "Foreign 2FA" }] };228      if (msg.type === "GET_ENTRY_FOR_FILL") return { ok: true, data: { id: "totp-entry", totpCode: "123456" } };229      return { ok: true, data: null };230    });231232    await handleFieldInteraction(totp, true, "totp-capability");233    await vi.waitFor(() => expect(showTOTP).toHaveBeenCalled());234    expect(sentMessages.find((msg) => msg.type === "AUTOFILL_QUERY")).toMatchObject({235      payload: { kind: "totp", capability: "totp-capability" },236    });237238    const onSelect = showTOTP.mock.calls.at(-1)![2] as (id: string) => Promise<void>;239    await onSelect("totp-entry");240    expect(sentMessages.find((msg) => msg.type === "GET_ENTRY_FOR_FILL")).toMatchObject({241      payload: { id: "totp-entry", capability: "totp-capability" },242    });243  });244});245246// PB-26-949: the background reply is now an explicit field allowlist. These247// assertions are the content half of that contract — the selector's fill path248// must land the credentials using only the allowlisted keys, so the background249// test's key set stays sufficient.250describe("PB-26-949: selector fill consumes only the allowlisted reply", () => {251  it("fills username, password and TOTP from an allowlist-only reply", async () => {252    const { form, username, password } = createLoginForm();253    // Same-origin https action: jsdom's location is http://localhost, and the254    // form-action gate refuses any non-https form.255    form.action = "https://localhost/login";256    const totp = makeInput({ type: "text", autocomplete: "one-time-code", name: "otp" }, form);257    setMessageResponder((msg) => {258      if (msg.type === "AUTOFILL_QUERY") {259        return { ok: true, data: [{ id: "acme", title: "Acme", username: "alice" }] };260      }261      if (msg.type === "GET_ENTRY_FOR_FILL") {262        return {263          ok: true,264          data: {265            id: "acme",266            title: "Acme",267            username: "alice",268            email: "[email protected]",269            password: "s3cret",270            url: "https://acme.test",271            additionalUrls: ["https://login.acme.test"],272            totpCode: "123456",273            totpRemaining: 24,274          },275        };276      }277      return { ok: true, data: null };278    });279280    // Real manual-summon path: the background's browser command clears every281    // suppression layer (including a page-wide fill grace window left by an282    // earlier test in this file) and opens the selector.283    for (const listener of messageListeners) {284      listener({ type: "SUMMON_AUTOFILL", source: "shortcut" }, { id: chrome.runtime.id }, () => {});285    }286    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());287    const onSelect = showSelector.mock.calls.at(-1)![2] as (id: string) => Promise<void>;288    await onSelect("acme");289290    expect(username.value).toBe("alice");291    expect(password.value).toBe("s3cret");292    expect(totp.value).toBe("123456");293  });294295  it("offers to save the same-domain login after a fill", async () => {296    const { form, username, password } = createLoginForm();297    // jsdom's location is http://localhost, and the form-action gate only298    // permits https or same-origin actions.299    form.action = "https://localhost/login";300    showRememberToast.mockClear();301    setMessageResponder((msg) => {302      if (msg.type === "AUTOFILL_QUERY") {303        return { ok: true, data: [{ id: "acme", title: "Acme", username: "alice" }] };304      }305      if (msg.type === "GET_ENTRY_FOR_FILL") {306        return {307          ok: true,308          data: {309            id: "acme",310            title: "Acme",311            username: "alice",312            password: "s3cret",313            url: "http://localhost",314          },315        };316      }317      return { ok: true, data: null };318    });319320    for (const listener of messageListeners) {321      listener({ type: "SUMMON_AUTOFILL", source: "shortcut" }, { id: chrome.runtime.id }, () => {});322    }323    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());324    const onSelect = showSelector.mock.calls.at(-1)![2] as (id: string) => Promise<void>;325    await onSelect("acme");326327    expect(username.value).toBe("alice");328    expect(password.value).toBe("s3cret");329    // `url` is in the fill allowlist only for this consumer: a saved login that330    // already covers the page must not prompt to save again.331    expect(showRememberToast).not.toHaveBeenCalled();332  });333334  it("stays quiet when an additional URL covers the page", async () => {335    const { form, username } = createLoginForm();336    form.action = "https://localhost/login";337    showRememberToast.mockClear();338    setMessageResponder((msg) => {339      if (msg.type === "AUTOFILL_QUERY") {340        return { ok: true, data: [{ id: "acme", title: "Acme", username: "alice" }] };341      }342      if (msg.type === "GET_ENTRY_FOR_FILL") {343        return {344          ok: true,345          data: {346            id: "acme",347            title: "Acme",348            username: "alice",349            password: "s3cret",350            url: "https://elsewhere.test",351            additionalUrls: ["http://localhost:3000/login"],352          },353        };354      }355      return { ok: true, data: null };356    });357358    for (const listener of messageListeners) {359      listener({ type: "SUMMON_AUTOFILL", source: "shortcut" }, { id: chrome.runtime.id }, () => {});360    }361    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());362    const onSelect = showSelector.mock.calls.at(-1)![2] as (id: string) => Promise<void>;363    await onSelect("acme");364365    expect(username.value).toBe("alice");366    // `additionalUrls` is in the fill allowlist only for this consumer.367    expect(showRememberToast).not.toHaveBeenCalled();368  });369370  it("offers to save a login that covers neither URL nor additional URLs", async () => {371    const { form, username } = createLoginForm();372    form.action = "https://localhost/login";373    showRememberToast.mockClear();374    setMessageResponder((msg) => {375      if (msg.type === "AUTOFILL_QUERY") {376        return { ok: true, data: [{ id: "acme", title: "Acme", username: "alice" }] };377      }378      if (msg.type === "GET_ENTRY_FOR_FILL") {379        return {380          ok: true,381          data: {382            id: "acme",383            title: "Acme",384            username: "alice",385            password: "s3cret",386            url: "https://elsewhere.test",387            additionalUrls: ["https://login.elsewhere.test"],388          },389        };390      }391      return { ok: true, data: null };392    });393394    for (const listener of messageListeners) {395      listener({ type: "SUMMON_AUTOFILL", source: "shortcut" }, { id: chrome.runtime.id }, () => {});396    }397    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());398    const onSelect = showSelector.mock.calls.at(-1)![2] as (id: string) => Promise<void>;399    await onSelect("acme");400401    expect(username.value).toBe("alice");402    expect(showRememberToast).toHaveBeenCalledWith("http://localhost:3000", "acme");403  });404});