content.selector-ui.test.ts

15.3 KB · raw

1// @vitest-environment jsdom2//3// Test File 5 — inject.ts showAutofillSelector (T-I01–T-I16).4//5// IMPORTANT ARCHITECTURE NOTE: showAutofillSelector mounts its UI inside a6// CLOSED shadow root (host.attachShadow({ mode: "closed" })). Everything the7// brief wants to assert about the selector's interior — the entry list, arrow/8// Enter/Escape keyboard navigation, the search filter, the lazy GET_ENTRY load,9// the TOTP chip, focus-trapping, above/below placement, isTrusted gating — lives10// behind that closed boundary and is, by design, unreachable from any external11// script (including this test and even a page-context Playwright script).12//13// So this file asserts the externally-observable contract: the selector mounts14// a host into the document and the returned dismiss function tears it down.15// Browser-level behavior is covered through observable effects rather than by16// adding a test-only seam into the closed shadow root.1718import "./_setup"; // chrome mock + ResizeObserver polyfill19import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";20import { showAutofillSelector, showCardSelector } from "./inject";21import { makeInput, resetChromeMock, sentMessages, setMessageResponder } from "./_setup";2223const ENTRIES = [24  { id: "e1", title: "Acme", username: "[email protected]" },25  { id: "e2", title: "Acme Admin", username: "[email protected]" },26];2728// The host is a position:fixed div with the max z-index; closed shadow means we29// can only see the host, never its contents.30function selectorHost(): HTMLElement | null {31  return document.body.querySelector<HTMLElement>('div[style*="2147483647"]');32}3334beforeEach(() => {35  document.body.innerHTML = "";36  resetChromeMock();37});38afterEach(() => {39  document.body.innerHTML = "";40});4142describe("T-I01: mount + dismiss (the observable contract)", () => {43  it("PB-26-707: shows the full security origin instead of the registrable domain", () => {44    const originalAttachShadow = Element.prototype.attachShadow;45    const attachSpy = vi.spyOn(Element.prototype, "attachShadow").mockImplementation(function (this: Element) {46      return originalAttachShadow.call(this, { mode: "open" });47    });48    const anchor = makeInput({ type: "password" });4950    try {51      const dismiss = showAutofillSelector(anchor, ENTRIES, vi.fn(), {52        domain: "example.com",53        securityOrigin: "https://login.accounts.example.com:8443",54      });55      expect(selectorHost()?.shadowRoot?.querySelector(".domain-name")?.textContent)56        .toBe("https://login.accounts.example.com:8443");57      dismiss();58    } finally {59      attachSpy.mockRestore();60    }61  });6263  // T-I01: opening the selector mounts a host into the document and returns a64  // dismiss function.65  it("T-I01: showAutofillSelector mounts a host and returns a dismiss fn", () => {66    const anchor = makeInput({ type: "password" });67    const dismiss = showAutofillSelector(anchor, ENTRIES, vi.fn());68    expect(typeof dismiss).toBe("function");69    expect(selectorHost()).not.toBeNull();70    dismiss();71  });7273  // Dismiss tears the host back down — the closed shadow goes with it. Teardown74  // is animated: dismiss() schedules host.remove() ~130ms later, so we wait it75  // out rather than asserting synchronously.76  it("T-I05/T-I06 (teardown half): the returned dismiss removes the host", async () => {77    const anchor = makeInput({ type: "password" });78    const dismiss = showAutofillSelector(anchor, ENTRIES, vi.fn());79    expect(selectorHost()).not.toBeNull();80    dismiss();81    await new Promise((r) => setTimeout(r, 180));82    expect(selectorHost()).toBeNull();83  });8485  // The host mounts even in locked mode (the unlock prompt is also closed-shadow).86  it("T-I01b: locked-mode open also mounts a host", () => {87    const anchor = makeInput({ type: "password" });88    const dismiss = showAutofillSelector(anchor, [], vi.fn(), { locked: true });89    expect(selectorHost()).not.toBeNull();90    dismiss();91  });9293  // Re-opening dismisses any previous host the caller forgot — but the caller94  // (index.ts) owns currentDismiss, so here we just confirm two opens leave two95  // hosts unless dismissed, proving each open is independent.96  it("T-I01c: each open creates its own host (caller owns single-instance policy)", () => {97    const anchor = makeInput({ type: "password" });98    const d1 = showAutofillSelector(anchor, ENTRIES, vi.fn());99    const d2 = showAutofillSelector(anchor, ENTRIES, vi.fn());100    expect(document.body.querySelectorAll('div[style*="2147483647"]').length).toBe(2);101    d1();102    d2();103  });104});105106describe("PB-26-201: content-safe privileged actions", () => {107  it("opens new-entry creation inline without rechecking an already-unlocked selector", async () => {108    const originalAttachShadow = Element.prototype.attachShadow;109    const attachSpy = vi.spyOn(Element.prototype, "attachShadow").mockImplementation(function (this: Element) {110      return originalAttachShadow.call(this, { mode: "open" });111    });112    const anchor = makeInput({ type: "password" });113    setMessageResponder((message) =>114      message.type === "GET_VAULT_STATUS"115        ? { ok: true, unlocked: false }116        : { ok: true, data: null },117    );118119    try {120      const dismiss = showAutofillSelector(anchor, [ENTRIES[0]!], vi.fn(), { domain: "example.com" });121      const host = selectorHost();122      host?.shadowRoot?.querySelector<HTMLButtonElement>(".domain-add-btn")?.click();123124      await vi.waitFor(() => {125        expect(host?.shadowRoot?.querySelector(".create-form-wrap")).not.toBeNull();126      });127      expect(host?.shadowRoot?.querySelector(".locked-wrap")).toBeNull();128      expect(sentMessages.some((message) => message.type === "GET_VAULT_STATUS")).toBe(false);129      dismiss();130    } finally {131      attachSpy.mockRestore();132    }133  });134135  it("uses a command capability for exactly one login-with-TOTP secret fetch", async () => {136    const originalAttachShadow = Element.prototype.attachShadow;137    const attachSpy = vi.spyOn(Element.prototype, "attachShadow").mockImplementation(function (this: Element) {138      return originalAttachShadow.call(this, { mode: "open" });139    });140    const anchor = makeInput({ type: "password" });141    const onSelect = vi.fn(async (id: string) => {142      await chrome.runtime.sendMessage({143        type: "GET_ENTRY_FOR_FILL",144        payload: { id, capability: "login-capability" },145      });146    });147    setMessageResponder((message) =>148      message.type === "GET_ENTRY_FOR_FILL"149        ? { ok: true, data: { password: "secret", totpCode: "123456" } }150        : { ok: true, data: null },151    );152153    try {154      const dismiss = showAutofillSelector(155        anchor,156        [{ id: "e1", title: "Acme", username: "alice", hasTotp: true }],157        onSelect,158        { domain: "example.com", capability: "login-capability" },159      );160      const host = selectorHost();161      expect(sentMessages.some((message) => message.type === "GET_ENTRY_FOR_FILL")).toBe(false);162      host?.shadowRoot?.querySelector<HTMLButtonElement>(".sp-fill-btn")?.click();163164      await vi.waitFor(() => expect(onSelect).toHaveBeenCalledWith("e1"));165      expect(sentMessages.filter((message) => message.type === "GET_ENTRY_FOR_FILL")).toHaveLength(1);166      dismiss();167    } finally {168      attachSpy.mockRestore();169    }170  });171172  it("passes the command capability into a selected password copy", async () => {173    const originalAttachShadow = Element.prototype.attachShadow;174    const attachSpy = vi.spyOn(Element.prototype, "attachShadow").mockImplementation(function (this: Element) {175      return originalAttachShadow.call(this, { mode: "open" });176    });177    const anchor = makeInput({ type: "password" });178    setMessageResponder((message) =>179      message.type === "GET_ENTRY_FOR_FILL"180        ? { ok: true, data: { password: "correct horse battery staple" } }181        : { ok: true, data: null },182    );183184    try {185      const dismiss = showAutofillSelector(anchor, [ENTRIES[0]!], vi.fn(), {186        domain: "example.com",187        capability: "login-capability",188      } as Parameters<typeof showAutofillSelector>[3]);189      const host = selectorHost();190      host?.shadowRoot?.querySelector<HTMLButtonElement>('button[title="Copy password"]')?.click();191192      await vi.waitFor(() => {193        expect(sentMessages.find((message) => message.type === "GET_ENTRY_FOR_FILL")).toMatchObject({194          payload: { id: "e1", capability: "login-capability" },195        });196      });197      dismiss();198    } finally {199      attachSpy.mockRestore();200    }201  });202203  it("opens the selected entry editor inside the inline helper", async () => {204    const originalAttachShadow = Element.prototype.attachShadow;205    const attachSpy = vi.spyOn(Element.prototype, "attachShadow").mockImplementation(function (this: Element) {206      return originalAttachShadow.call(this, { mode: "open" });207    });208    const anchor = makeInput({ type: "password" });209    setMessageResponder((message) =>210      message.type === "GET_ENTRY_FOR_FILL"211        ? {212            ok: true,213            data: {214              title: "Acme",215              username: "[email protected]",216              password: "current-password",217              url: "https://example.com",218            },219          }220        : { ok: true, data: null },221    );222223    try {224      const dismiss = showAutofillSelector(anchor, [ENTRIES[0]!], vi.fn(), { domain: "example.com" });225      const host = selectorHost();226      const edit = host?.shadowRoot?.querySelector<HTMLButtonElement>(".sp-action-edit");227      expect(edit).not.toBeNull();228      edit?.click();229230      await vi.waitFor(() => {231        expect(host?.shadowRoot?.querySelector<HTMLInputElement>('.create-form-wrap input[type="password"]')?.value)232          .toBe("current-password");233      });234      expect(sentMessages).toContainEqual({235        type: "GET_ENTRY_FOR_FILL",236        payload: { id: "e1", capability: undefined },237      });238      expect(sentMessages.some((message) => message.type === "OPEN_POPUP")).toBe(false);239      expect(sentMessages.some((message) => message.type === "GET_ENTRY_FOR_EDIT")).toBe(false);240      expect(host?.shadowRoot?.querySelector(".create-form-wrap textarea")).toBeNull();241242      const title = host?.shadowRoot?.querySelector<HTMLInputElement>('.create-form-wrap input[type="text"]');243      if (title) title.value = "Acme Updated";244      const url = host?.shadowRoot?.querySelectorAll<HTMLInputElement>('.create-form-wrap input[type="text"]')[1];245      if (url) url.value = "https://example.com/updated";246      host?.shadowRoot?.querySelector<HTMLButtonElement>(".create-form-wrap .save-btn")?.click();247      await vi.waitFor(() => {248        expect(sentMessages.find((message) => message.type === "UPDATE_ENTRY")).toMatchObject({249          payload: {250            id: "e1",251            patch: { title: "Acme Updated", url: "https://example.com/updated", password: "current-password" },252          },253        });254      });255      const patch = sentMessages.find((message) => message.type === "UPDATE_ENTRY")?.payload?.patch;256      expect(patch).not.toHaveProperty("totp");257      expect(patch).not.toHaveProperty("passwordHistory");258      expect(patch).not.toHaveProperty("notes");259      dismiss();260    } finally {261      attachSpy.mockRestore();262    }263  });264265  it.each(["example.com", ""])("PB-26-944: inline edits omit an unchanged legacy primary URL: %j", async (url) => {266    const originalAttachShadow = Element.prototype.attachShadow;267    const attachSpy = vi.spyOn(Element.prototype, "attachShadow").mockImplementation(function (this: Element) {268      return originalAttachShadow.call(this, { mode: "open" });269    });270    const anchor = makeInput({ type: "password" });271    setMessageResponder((message) => message.type === "GET_ENTRY_FOR_FILL"272      ? { ok: true, data: { title: "Legacy", username: "alice", password: "old-password", url } }273      : { ok: true });274    try {275      const dismiss = showAutofillSelector(anchor, [ENTRIES[0]!], vi.fn(), { domain: "example.com" });276      const host = selectorHost();277      host?.shadowRoot?.querySelector<HTMLButtonElement>(".sp-action-edit")?.click();278      await vi.waitFor(() => expect(host?.shadowRoot?.querySelector<HTMLInputElement>('.create-form-wrap input[type="password"]')?.value).toBe("old-password"));279      const password = host?.shadowRoot?.querySelector<HTMLInputElement>('.create-form-wrap input[type="password"]');280      if (password) password.value = "new-password";281      host?.shadowRoot?.querySelector<HTMLButtonElement>(".create-form-wrap .save-btn")?.click();282      await vi.waitFor(() => expect(sentMessages.find((message) => message.type === "UPDATE_ENTRY"))283        .toMatchObject({ payload: { patch: { password: "new-password" } } }));284      expect(sentMessages.find((message) => message.type === "UPDATE_ENTRY")?.payload?.patch).not.toHaveProperty("url");285      dismiss();286    } finally {287      attachSpy.mockRestore();288    }289  });290291  it("passes the card command capability into the selected card fill", async () => {292    const originalAttachShadow = Element.prototype.attachShadow;293    const attachSpy = vi.spyOn(Element.prototype, "attachShadow").mockImplementation(function (this: Element) {294      return originalAttachShadow.call(this, { mode: "open" });295    });296    const anchor = makeInput({ type: "text", autocomplete: "cc-number" });297    const onFill = vi.fn();298    setMessageResponder((message) =>299      message.type === "GET_ENTRY_FOR_FILL"300        ? { ok: true, data: { id: "card-1", type: "card", title: "Personal Visa", cardNumber: "4111111111111111" } }301        : { ok: true, data: null },302    );303304    try {305      const dismiss = showCardSelector(306        anchor,307        [{ id: "card-1", title: "Personal Visa", last4: "1111" }],308        { domain: "shop.example", capability: "card-capability", onFill } as Parameters<typeof showCardSelector>[2],309      );310      const host = selectorHost();311      host?.shadowRoot?.querySelector<HTMLButtonElement>(".sp-fill-btn")?.click();312313      await vi.waitFor(() => {314        expect(sentMessages.find((message) => message.type === "GET_ENTRY_FOR_FILL")).toMatchObject({315          payload: { id: "card-1", capability: "card-capability" },316        });317      });318      dismiss();319    } finally {320      attachSpy.mockRestore();321    }322  });323324  it("allows only one card secret action per command capability", async () => {325    const originalAttachShadow = Element.prototype.attachShadow;326    const attachSpy = vi.spyOn(Element.prototype, "attachShadow").mockImplementation(function (this: Element) {327      return originalAttachShadow.call(this, { mode: "open" });328    });329    const anchor = makeInput({ type: "text", autocomplete: "cc-number" });330    setMessageResponder((message) =>331      message.type === "GET_ENTRY_FOR_FILL"332        ? { ok: true, data: { id: "card-1", type: "card", cardNumber: "4111111111111111", cvc: "123" } }333        : { ok: true, data: null },334    );335336    try {337      const dismiss = showCardSelector(338        anchor,339        [{ id: "card-1", title: "Personal Visa", last4: "1111" }],340        { domain: "shop.example", capability: "card-capability", onFill: vi.fn() },341      );342      const host = selectorHost();343      const copyNumber = host?.shadowRoot?.querySelector<HTMLButtonElement>('button[title="Copy card number"]');344      const fill = host?.shadowRoot?.querySelector<HTMLButtonElement>(".sp-fill-btn");345      copyNumber?.click();346      fill?.click();347348      await vi.waitFor(() => {349        expect(sentMessages.filter((message) => message.type === "GET_ENTRY_FOR_FILL")).toHaveLength(1);350      });351      dismiss();352    } finally {353      attachSpy.mockRestore();354    }355  });356});