// @vitest-environment jsdom import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; // PCH-01-007: the three document-level keydown handlers inside the inline // selector must ignore page-synthesised KeyboardEvents (isTrusted === false), // so a host page cannot script selection + fill without a real keypress. describe("PCH-01-007 — inject keydown handlers gate on e.isTrusted", () => { let showAutofillSelector: typeof import("./inject").showAutofillSelector; let cleanup: (() => void) | null = null; beforeEach(async () => { vi.resetModules(); (globalThis as unknown as { chrome: unknown }).chrome = { runtime: { sendMessage: vi.fn(), getURL: (p: string) => p }, }; class NoopObserver { observe() {} unobserve() {} disconnect() {} } (globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = NoopObserver; (globalThis as unknown as { IntersectionObserver: unknown }).IntersectionObserver = NoopObserver; ({ showAutofillSelector } = await import("./inject")); }); afterEach(() => { cleanup?.(); cleanup = null; document.body.innerHTML = ""; }); it("ignores untrusted ArrowDown/Enter — no fill without user intent", () => { const input = document.createElement("input"); document.body.appendChild(input); const onSelect = vi.fn(); cleanup = showAutofillSelector( input, [ { id: "1", title: "GitHub", username: "june", url: "https://github.com" }, { id: "2", title: "GitLab", username: "june", url: "https://gitlab.com" }, ], onSelect, { domain: "github.com" }, ); // Synthetic events have isTrusted === false in jsdom → handlers no-op. document.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); document.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); expect(onSelect).not.toHaveBeenCalled(); }); it("ignores untrusted single-character keys (type-to-search handlers no-op)", () => { const input = document.createElement("input"); document.body.appendChild(input); const onSelect = vi.fn(); cleanup = showAutofillSelector( input, [{ id: "1", title: "GitHub", username: "june", url: "https://github.com" }], onSelect, { domain: "github.com" }, ); // A page-dispatched printable key must not drive selection/fill. document.dispatchEvent(new KeyboardEvent("keydown", { key: "a", bubbles: true })); expect(onSelect).not.toHaveBeenCalled(); }); });