content.message-routing.test.ts

11.5 KB · raw

1// @vitest-environment jsdom2//3// Test File 4 — index.ts message routing (T-M01–T-M13).4//5// index.ts registers a single chrome.runtime.onMessage listener that routes6// SUMMON_AUTOFILL (keyboard shortcut / toolbar button), VAULT_UNLOCKED (retry7// after unlock), PING, GET_SITE_PASSWORD_POLICY, and the passkey-toast control8// messages. The harness captures every registered listener; we invoke them with9// a spy sendResponse and a same-extension sender, then assert the routed effect.10//11// Where the brief assumed messages that this listener does not own12// (DISMISS_AUTOFILL, FILL_AND_SUBMIT), the cases are documented rather than13// faked.1415import { vi } from "vitest";1617const { predictBatch, dismissSpy } = vi.hoisted(() => ({18  predictBatch: vi.fn(() => Promise.resolve([] as unknown[])),19  dismissSpy: vi.fn(),20}));2122vi.mock("./inject", () => ({23  injectFieldIcon: vi.fn(() => vi.fn()),24  showAutofillSelector: vi.fn(() => dismissSpy),25  showTOTPSelector: vi.fn(() => dismissSpy),26  showCardSelector: vi.fn(() => dismissSpy),27  showRememberSiteToast: vi.fn(),28  showPasskeyAvailable: vi.fn(),29  showPasskeyProGate: vi.fn(),30  showPasskeyRegistrationOffer: vi.fn(),31}));32vi.mock("./content-ml-detector", () => ({33  contentMLDetector: { predictBatch },34}));3536import { afterEach, beforeEach, describe, expect, it } from "vitest";37import "./_setup";38import { resetChromeMock, setMessageResponder, sentMessages, messageListeners, createLoginForm, makeInput } from "./_setup";39import "./index"; // registers the onMessage listener at import time40import * as inject from "./inject";4142const showSelector = inject.showAutofillSelector as unknown as ReturnType<typeof vi.fn>;43const showCardSelector = inject.showCardSelector as unknown as ReturnType<typeof vi.fn>;44const showPasskeyProGate = inject.showPasskeyProGate as unknown as ReturnType<typeof vi.fn>;45const SELF_SENDER = { id: "peach-test-extension-id" };46const ENTRIES = [{ id: "e1", title: "Acme", username: "alice" }];4748// Deliver a message to every registered onMessage listener; return the49// sendResponse spy so the test can assert the reply.50function dispatch(msg: any, sender: any = SELF_SENDER) {51  const sendResponse = vi.fn();52  for (const l of messageListeners) l(msg, sender, sendResponse);53  return sendResponse;54}5556function withEntries(): void {57  setMessageResponder((msg) =>58    msg.type === "AUTOFILL_QUERY" ? { ok: true, data: ENTRIES } : { ok: true, data: null }59  );60}6162let urlCounter = 0;63beforeEach(async () => {64  try { history.pushState({}, "", `/m${++urlCounter}`); } catch { /* ignore */ }65  document.body.innerHTML = "";66  await new Promise((r) => setTimeout(r, 0));67  resetChromeMock();68  showSelector.mockClear();69  showCardSelector.mockClear();70  showPasskeyProGate.mockClear();71  predictBatch.mockReset();72  predictBatch.mockReturnValue(Promise.resolve([]));73});7475afterEach(async () => {76  await new Promise((r) => setTimeout(r, 0));77});7879describe("T-M01–T-M02: SUMMON_AUTOFILL", () => {80  // T-M01: the shortcut on a login form opens the selector for the focused field.81  it("T-M01: SUMMON_AUTOFILL with a focused login field → selector opens", async () => {82    const { password } = createLoginForm();83    password.focus();84    withEntries();85    const send = dispatch({ type: "SUMMON_AUTOFILL", source: "shortcut" });86    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());87    expect(send).toHaveBeenCalled(); // listener acknowledged88  });8990  // T-M02: the shortcut on a page with no login form must not crash and must not91  // open the credential selector (it falls back to the search palette).92  it("T-M02: SUMMON_AUTOFILL with no login form → no crash, no credential selector", () => {93    expect(() => dispatch({ type: "SUMMON_AUTOFILL", source: "shortcut" })).not.toThrow();94    expect(showSelector).not.toHaveBeenCalled();95  });9697  it("PB-26-201: no-form command carries capability from inventory to selected fill", async () => {98    const originalAttachShadow = Element.prototype.attachShadow;99    const attachSpy = vi.spyOn(Element.prototype, "attachShadow").mockImplementation(function (this: Element) {100      return originalAttachShadow.call(this, { mode: "open" });101    });102    setMessageResponder((msg) => {103      if (msg.type === "AUTOFILL_QUERY") return { ok: true, data: ENTRIES };104      if (msg.type === "GET_ENTRY_FOR_FILL") return { ok: true, data: { ...ENTRIES[0], password: "secret" } };105      return { ok: true, data: null };106    });107108    try {109      dispatch({ type: "SUMMON_AUTOFILL", source: "shortcut", capability: "no-form-capability" });110      await vi.waitFor(() => {111        expect(sentMessages.find((msg) => msg.type === "AUTOFILL_QUERY")).toMatchObject({112          payload: { includeAll: true, capability: "no-form-capability" },113        });114      });115      const findRow = () => Array.from(document.body.children)116        .map((host) => host.shadowRoot?.querySelector<HTMLElement>(".e"))117        .find((candidate): candidate is HTMLElement => candidate !== null && candidate !== undefined);118      await vi.waitFor(() => expect(findRow()).toBeDefined());119      const row = findRow();120      row?.click();121      await vi.waitFor(() => {122        expect(sentMessages.find((msg) => msg.type === "GET_ENTRY_FOR_FILL")).toMatchObject({123          payload: { id: "e1", capability: "no-form-capability" },124        });125      });126    } finally {127      attachSpy.mockRestore();128    }129  });130131  it("PB-26-201: card command carries capability into inventory and selector actions", async () => {132    const form = document.createElement("form");133    document.body.appendChild(form);134    const number = makeInput({ type: "text", autocomplete: "cc-number" }, form);135    makeInput({ type: "text", autocomplete: "cc-exp" }, form);136    makeInput({ type: "text", autocomplete: "cc-csc" }, form);137    number.focus();138    setMessageResponder((msg) =>139      msg.type === "AUTOFILL_QUERY"140        ? { ok: true, data: [{ id: "card-1", title: "Personal Visa", last4: "1111" }] }141        : { ok: true, data: null },142    );143144    dispatch({ type: "SUMMON_AUTOFILL", source: "shortcut", capability: "card-capability" });145146    await vi.waitFor(() => expect(showCardSelector).toHaveBeenCalled());147    expect(sentMessages.find((msg) => msg.type === "AUTOFILL_QUERY" && msg.payload?.kind === "card")).toMatchObject({148      payload: { capability: "card-capability" },149    });150    expect(showCardSelector.mock.calls.at(-1)![2]).toMatchObject({ capability: "card-capability" });151  });152});153154describe("T-M03–T-M05: VAULT_UNLOCKED", () => {155  // T-M03: after unlock, the pending field's interaction is retried.156  it("T-M03: VAULT_UNLOCKED with a pending anchor → re-triggers and reopens", async () => {157    const { password } = createLoginForm();158    password.focus();159    withEntries();160    dispatch({ type: "SUMMON_AUTOFILL", source: "shortcut" }); // opens → sets currentAnchorField161    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());162    showSelector.mockClear();163164    dispatch({ type: "VAULT_UNLOCKED" });165    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled()); // reopened at the same field166  });167168  // T-M05: VAULT_UNLOCKED with nothing pending and no focused field is a no-op —169  // it must not throw or open anything.170  it("T-M05: VAULT_UNLOCKED with no pending interaction → no-op, no crash", async () => {171    (document.activeElement as HTMLElement | null)?.blur?.();172    const send = dispatch({ type: "VAULT_UNLOCKED" });173    await new Promise((r) => setTimeout(r, 20));174    expect(send).toHaveBeenCalledWith({ ok: true });175    expect(showSelector).not.toHaveBeenCalled();176  });177178  // T-M04: when a passkey unlock is in flight (passkeySummonActive), VAULT_UNLOCKED179  // must NOT re-trigger autofill — the passkey toast owns the next step. We arm180  // passkeySummonActive via the passkey-unlock summon path, then assert the181  // unlock only dismisses (no fresh credential selector). Ordered last in the182  // group because the VAULT_UNLOCKED it sends also clears the flag.183  it("T-M04: VAULT_UNLOCKED while passkeySummonActive → no re-trigger", async () => {184    // The passkey-unlock branch only fires when there is NO credential form on185    // the page (vault locked mid-passkey-GET); it anchors the locked prompt on186    // whatever element is focused (typically the sign-in button).187    const anchor = makeInput({ type: "text", name: "search-box", placeholder: "Search" });188    anchor.focus();189    dispatch({ type: "SUMMON_AUTOFILL", source: "passkey-unlock" }); // sets passkeySummonActive190    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());191    showSelector.mockClear();192193    dispatch({ type: "VAULT_UNLOCKED" }); // passkey branch: dismiss only, no reopen194    await new Promise((r) => setTimeout(r, 20));195    expect(showSelector).not.toHaveBeenCalled();196  });197});198199describe("PB-26-319: toast close signals require the extension token", () => {200  it("ignores a page-forged toast-closed postMessage", async () => {201    const { password } = createLoginForm();202    password.focus();203    withEntries();204    dispatch({ type: "SHOW_PASSKEY_TOAST", payload: { toastToken: "extension-token" } });205    window.dispatchEvent(new MessageEvent("message", { source: window, data: { source: "peach-passkey-toast", type: "toast-closed", token: "page-token" } }));206    dispatch({ type: "SUMMON_AUTOFILL", source: "shortcut" });207    await new Promise((resolve) => setTimeout(resolve, 0));208    expect(showSelector).not.toHaveBeenCalled();209  });210211  it("accepts the injected toast's token", async () => {212    const { password } = createLoginForm();213    password.focus();214    withEntries();215    dispatch({ type: "SHOW_PASSKEY_TOAST", payload: { toastToken: "extension-token" } });216    window.dispatchEvent(new MessageEvent("message", { source: window, data: { source: "peach-passkey-toast", type: "toast-closed", token: "extension-token" } }));217    await new Promise((resolve) => setTimeout(resolve, 0));218    dispatch({ type: "SUMMON_AUTOFILL", source: "shortcut" });219    await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());220  });221});222223describe("T-M08–T-M10: PING, passkey gate, robustness", () => {224  // PING is the liveness probe the background uses to confirm the content script225  // is injected.226  it("PING → sendResponse({ ok: true })", () => {227    const send = dispatch({ type: "PING" });228    expect(send).toHaveBeenCalledWith({ ok: true });229  });230231  // GET_SITE_PASSWORD_POLICY returns the scraped policy for the generator.232  it("GET_SITE_PASSWORD_POLICY → returns a policy object", () => {233    document.body.innerHTML = '<input type="password" maxlength="32" />';234    const send = dispatch({ type: "GET_SITE_PASSWORD_POLICY" });235    expect(send).toHaveBeenCalledTimes(1);236    const arg = send.mock.calls[0]![0];237    expect(arg.ok).toBe(true);238    expect(arg.data.maxLength).toBe(32);239  });240241  // PASSKEY_PRO_GATE surfaces the upgrade prompt (State 11).242  it("PASSKEY_PRO_GATE → showPasskeyProGate called", () => {243    dispatch({ type: "PASSKEY_PRO_GATE" });244    expect(showPasskeyProGate).toHaveBeenCalled();245  });246247  // T-M09: an unknown message type falls through harmlessly — no throw, no248  // unhandled rejection.249  it("T-M09: unknown message type → handled gracefully", () => {250    expect(() => dispatch({ type: "TOTALLY_UNKNOWN_MESSAGE" })).not.toThrow();251    expect(showSelector).not.toHaveBeenCalled();252  });253254  // T-M10: a foreign-extension sender (sender.id mismatch) is ignored entirely —255  // a security boundary, not just robustness.256  it("T-M10: message from a foreign sender id is ignored", () => {257    const send = dispatch({ type: "PING" }, { id: "some-other-extension" });258    expect(send).not.toHaveBeenCalled();259  });260});