content.save.test.ts

6.5 KB · raw

1// @vitest-environment jsdom2//3// Test File 9 — save.ts save-on-submit detection (T-SV01–T-SV10).4//5// setupSaveDetection installs a document submit listener that scrapes the6// submitted username/password, looks up a matching vault entry7// (CHECK_SAVE_CREDENTIAL), and shows a save/update banner unless8// the credentials already match. The banner itself is a CLOSED shadow root, and9// its Save/Update buttons (which send ADD_ENTRY/UPDATE_ENTRY) are unreachable10// from outside — so those acceptance flows are routed to the e2e. What we pin11// here is the decision: does the banner mount, and is the lookup correct?1213import "./_setup";14import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";15import { setupSaveDetection } from "./save";16import { resetChromeMock, setMessageResponder, sentMessages, makeInput } from "./_setup";1718// Mounted save/update banner host (top-right, max z-index, closed shadow).19function bannerHost(): HTMLElement | null {20  return document.body.querySelector<HTMLElement>('div[style*="2147483647"]');21}2223// Build and submit a form with the given fields; returns after the async24// save-detection chain settles.25async function submitForm(fields: { user?: string; pass?: string; type?: string }): Promise<void> {26  const form = document.createElement("form");27  document.body.appendChild(form);28  if (fields.user !== undefined) {29    const u = makeInput({ type: "text", name: "username", autocomplete: "username" }, form);30    u.value = fields.user;31  }32  if (fields.pass !== undefined) {33    const p = makeInput({ type: fields.type ?? "password", name: "password" }, form);34    p.value = fields.pass;35  }36  form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));37  await new Promise((r) => setTimeout(r, 30)); // let the comparison roundtrip settle38}3940beforeAll(() => {41  setupSaveDetection(); // one document submit listener for the whole file42});4344beforeEach(() => {45  document.body.innerHTML = "";46  resetChromeMock();47});48afterEach(() => {49  document.body.innerHTML = "";50  vi.useRealTimers();51});5253describe("T-SV01, T-SV03: banner mounts for new and changed credentials", () => {54  // T-SV01: submitting credentials with no matching vault entry → save banner.55  it("T-SV01: new credentials → save banner mounts", async () => {56    setMessageResponder((msg) => (msg.type === "CHECK_SAVE_CREDENTIAL" ? { ok: true, data: { status: "new" } } : { ok: true, data: null }));57    await submitForm({ user: "alice", pass: "s3cret" });58    expect(bannerHost()).not.toBeNull();59  });6061  // T-SV03: submitting a changed password for an existing entry → update banner.62  it("T-SV03: changed password for an existing entry → banner mounts (update)", async () => {63    setMessageResponder((msg) => {64      if (msg.type === "CHECK_SAVE_CREDENTIAL") return { ok: true, data: { status: "changed", id: "e1" } };65      return { ok: true, data: null };66    });67    await submitForm({ user: "alice", pass: "new-password" });68    expect(bannerHost()).not.toBeNull();69  });70});7172describe("T-SV02, T-SV04, T-SV05: no banner cases", () => {73  // T-SV02: the submitted password already matches the saved entry → no banner.74  it("T-SV02: credentials already saved (password matches) → no banner", async () => {75    setMessageResponder((msg) => {76      if (msg.type === "CHECK_SAVE_CREDENTIAL") return { ok: true, data: { status: "same" } };77      return { ok: true, data: null };78    });79    await submitForm({ user: "alice", pass: "s3cret" });80    expect(bannerHost()).toBeNull();81  });8283  // T-SV04: a search form has no password field — save detection ignores it and84  // never even runs the vault lookup.85  it("T-SV04: search form (no password) → no banner, no vault lookup", async () => {86    setMessageResponder(() => ({ ok: true, data: [] }));87    const form = document.createElement("form");88    document.body.appendChild(form);89    const q = makeInput({ type: "search", name: "q" }, form);90    q.value = "kittens";91    form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));92    await new Promise((r) => setTimeout(r, 30));93    expect(bannerHost()).toBeNull();94    expect(sentMessages.some((m) => m.type === "CHECK_SAVE_CREDENTIAL")).toBe(false);95  });9697  // T-SV05: an empty password short-circuits before any lookup.98  it("T-SV05: empty password → no banner, no vault lookup", async () => {99    setMessageResponder(() => ({ ok: true, data: [] }));100    await submitForm({ user: "alice", pass: "" });101    expect(bannerHost()).toBeNull();102    expect(sentMessages.some((m) => m.type === "CHECK_SAVE_CREDENTIAL")).toBe(false);103  });104});105106describe("background credential comparison", () => {107  it("sends only submitted credentials and never requests a stored entry or canary ping", async () => {108    setMessageResponder(() => ({ ok: true, data: { status: "same" } }));109    await submitForm({ user: "alice", pass: "secret" });110    expect(sentMessages).toContainEqual({ type: "CHECK_SAVE_CREDENTIAL", payload: { username: "alice", password: "secret" } });111    expect(sentMessages.some(message => ["AUTOFILL_QUERY", "GET_ENTRY_FOR_FILL", "FIRE_CANARY_PING", "UPDATE_ENTRY"].includes(message.type))).toBe(false);112    expect(bannerHost()).toBeNull();113  });114115  it.each([undefined, null, { ok: false, error: "vault_locked" }, { ok: true }, { ok: true, data: { status: "ambiguous" } }, { ok: true, data: { status: "changed" } }, { ok: true, data: { status: "unknown" } }, { ok: true, data: { status: "new", id: "unexpected" } }, { ok: true, data: { status: "changed", id: "entry", password: "unexpected" } }])("suppresses the banner for an inconclusive response: %j", async response => {116    setMessageResponder(() => response);117    await submitForm({ user: "alice", pass: "secret" });118    expect(bannerHost()).toBeNull();119  });120121  it("suppresses the banner when the comparison fails", async () => {122    setMessageResponder(() => Promise.reject(new Error("disconnected")));123    await submitForm({ user: "alice", pass: "secret" });124    expect(bannerHost()).toBeNull();125  });126  it("suppresses a timed-out comparison and ignores its late response", async () => {127    vi.useFakeTimers();128    let resolve!: (value: unknown) => void;129    setMessageResponder(() => new Promise(done => { resolve = done; }));130    const submitting = submitForm({ user: "alice", pass: "secret" });131    await vi.advanceTimersByTimeAsync(5_001);132    await submitting;133    expect(bannerHost()).toBeNull();134    resolve({ ok: true, data: { status: "new" } });135    await vi.advanceTimersByTimeAsync(0);136    expect(bannerHost()).toBeNull();137  });138139});