contracts.test.tsx

76.5 KB · raw

1// @vitest-environment jsdom23import type { JSX } from "solid-js";4import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";56import type { ImportParseResult } from "../../shared/import";7import type { VaultEntry } from "../../shared/types";8import { WORD_LIST } from "../../shared/recovery-word-list";9import { PasskeyToast } from "../../content/passkey-toast/PasskeyToast";10import { PasskeyApprovalView } from "./PasskeyApproval";11import { LockView } from "./Lock";12import { ExportView } from "./Export";13import { SettingsView } from "./Settings";14import { DEFAULT_BINDINGS } from "../../shared/shortcuts";15import { EntryView } from "./Entry";16import { ImportView } from "./Import";17import { AddView } from "./Add";18import { NotesEditor } from "./NotesEditor";19import { RecoveryWordEntryView } from "./RecoveryWordEntry";20import { RecoveryWordDisplayView } from "./RecoveryWordDisplay";21import { VaultView } from "./Vault";22import { changeSelect, flushView, inputText, pressEnter, renderView } from "./view-test-utils";2324const sendMessageMock = vi.fn<(msg: unknown) => Promise<unknown>>();25const triggerRingMock = vi.fn();26const triggerPipPulseMock = vi.fn();27const parseImportSourceMock = vi.fn<(raw: string, password?: string) => Promise<ImportParseResult>>();28const zxcvbnMock = vi.fn((value: string) => ({ score: value.length >= 16 ? 3 : 1 }));2930vi.mock("../App", () => ({31  sendMessage: (msg: unknown) => sendMessageMock(msg),32  triggerRing: () => triggerRingMock(),33  triggerPipPulse: () => triggerPipPulseMock(),34}));3536vi.mock("../../shared/bridge", () => ({37  sendMessage: (msg: unknown) => sendMessageMock(msg),38}));3940vi.mock("../../shared/import", () => ({41  parseImportSource: (...args: [string, string | undefined]) => parseImportSourceMock(...args),42}));4344vi.mock("../../shared/favicon", async (importOriginal) => {45  const actual = await importOriginal<typeof import("../../shared/favicon")>();46  return { ...actual, faviconUrl: () => null };47});4849vi.mock("../../crypto/totp", () => ({50  generateTOTP: () => ({ code: "123 456", remaining: 24 }),51  parseOtpauthURI: (value: string) =>52    value.startsWith("otpauth://")53      ? { secret: "NB2W45DFOIZA====", algorithm: "SHA1" as const }54      : null,55}));5657vi.mock("../components/GeneratorDrawer", () => ({58  GeneratorDrawer: () => null,59}));6061vi.mock("../components/RuneCanvas", () => ({ RuneCanvas: () => null }));6263vi.mock("../components/RuneBackground", () => ({64  RuneBackground: () => null,65}));6667vi.mock("@zxcvbn-ts/core", () => ({68  zxcvbn: (value: string) => zxcvbnMock(value),69  zxcvbnOptions: { setOptions: vi.fn() },70}));71vi.mock("@zxcvbn-ts/language-common", () => ({72  adjacencyGraphs: {},73  dictionary: {},74}));75vi.mock("@zxcvbn-ts/language-en", () => ({76  translations: {},77  dictionary: {},78}));7980describe("popup contract tests", () => {81  const disposers: Array<() => void> = [];8283  beforeEach(() => {84    document.body.innerHTML = "";85    sendMessageMock.mockReset();86    triggerRingMock.mockReset();87    triggerPipPulseMock.mockReset();88    parseImportSourceMock.mockReset();89    zxcvbnMock.mockReset();90    zxcvbnMock.mockImplementation((value: string) => ({ score: value.length >= 16 ? 3 : 1 }));91    parseImportSourceMock.mockResolvedValue({92      format: "unknown",93      label: "Unknown format",94      entries: [],95      totalItems: 0,96      skippedItems: 0,97    });9899    vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {100      return window.setTimeout(() => cb(0), 0) as unknown as number;101    });102    vi.stubGlobal("cancelAnimationFrame", (id: number) => window.clearTimeout(id));103    vi.stubGlobal("URL", {104      createObjectURL: vi.fn(() => "blob:peach-test"),105      revokeObjectURL: vi.fn(),106    });107    vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});108109    (globalThis as { chrome?: typeof chrome }).chrome = {110      runtime: {111        getManifest: () => ({ version: "1.4.47" }),112        onMessage: { addListener: vi.fn() },113      },114    } as unknown as typeof chrome;115  });116117  afterEach(() => {118    while (disposers.length > 0) {119      disposers.pop()?.();120    }121    vi.restoreAllMocks();122    vi.unstubAllGlobals();123  });124125  function mount(view: JSX.Element | (() => JSX.Element)) {126    const mounted = renderView(view);127    disposers.push(mounted.dispose);128    return mounted.container;129  }130131  function sampleEntry(overrides: Partial<VaultEntry> = {}): VaultEntry {132    return {133      id: "entry-1",134      type: "login",135      title: "GitHub",136      username: "june",137      password: "secret123",138      url: "https://github.com",139      totp: "JBSWY3DPEHPK3PXP",140      canary: {141        webhookUrl: "https://example.com/hook",142      },143      createdAt: 1,144      modifiedAt: 1,145      ...overrides,146    };147  }148149  function sampleImportResult(150    overrides: Partial<ImportParseResult> = {}151  ): ImportParseResult {152    return {153      format: "csv",154      label: "CSV import",155      entries: [156        {157          type: "login",158          title: "Imported site",159          username: "imported-user",160          password: "imported-pass",161          url: "https://imported.test",162        },163      ],164      totalItems: 1,165      skippedItems: 0,166      ...overrides,167    };168  }169170  function settingsProps(overrides: Partial<Parameters<typeof SettingsView>[0]> = {}) {171    return {172      entriesCount: 1,173      breachMonitoring: true,174      lockOnClose: true,175      autoLockMinutes: 5,176      lockedSyncRequiresUnlock: false,177      trashRetentionDays: 30,178      theme: "dark" as const,179      accentColor: "peach" as const,180      textSize: "medium" as const,181      reduceMotion: false,182      onBreachMonitoringChange: vi.fn(),183      onLockOnCloseChange: vi.fn(),184      onAutoLockMinutesChange: vi.fn(),185      onTrashRetentionChange: vi.fn(),186      onLockedSyncRequiresUnlockChange: vi.fn(),187      onThemeChange: vi.fn(),188      onAccentChange: vi.fn(),189      onTextSizeChange: vi.fn(),190      onReduceMotionChange: vi.fn(),191      shortcuts: DEFAULT_BINDINGS,192      onShortcutsChange: vi.fn(),193      onBack: vi.fn(),194      onImport: vi.fn(),195      onExport: vi.fn(),196      onBreachCheckDone: vi.fn(),197      ...overrides,198    };199  }200201  async function selectImportFile(202    container: HTMLElement,203    contents = '{"export":"test"}'204  ) {205    // The Import view now opens onto a menu — click into the file subview206    // before locating the file input. Idempotent: a second click won't re-fire207    // because the menu unmounts once the subview renders.208    const fileCard = findButton(container, "Choose file →");209    if (fileCard) {210      fileCard.click();211      await flushView();212    }213    const input = container.querySelector('input[type="file"]') as HTMLInputElement;214    const file = new File([contents], "import.json", { type: "application/json" });215    Object.defineProperty(input, "files", {216      configurable: true,217      value: [file],218    });219    input.dispatchEvent(new Event("change", { bubbles: true }));220    await flushView();221    await flushView();222  }223224  function findButton(container: HTMLElement, text: string): HTMLButtonElement {225    return Array.from(container.querySelectorAll("button")).find(226      (candidate) => candidate.textContent?.trim() === text227    ) as HTMLButtonElement;228  }229230  it("Passkey toast shows the caller origin separately from the RP", async () => {231    const container = mount(() => <PasskeyToast site="example.com" origin="https://login.other.example:8443"232      displayName="June" username="june" requestId="1" onSignIn={() => {}} onDeny={() => {}} />);233    await flushView();234    expect(container.textContent).toContain("sign in to example.com?");235    expect(container.textContent).toContain("Request from https://login.other.example:8443");236  });237238  it("Passkey approval identifies the caller origin and embedded request", async () => {239    const container = mount(() => <PasskeyApprovalView type="get" rpId="example.com" rpName="Example"240      userName="june" origin="https://login.other.example:8443" crossOrigin={true} onApprove={() => {}} onDeny={() => {}} />);241    await flushView();242    expect(container.textContent).toContain("https://login.other.example:8443");243    expect(container.textContent).toContain("embedded in another site");244  });245246  it("Lock sends UNLOCK with the entered passphrase", async () => {247    sendMessageMock.mockResolvedValue({ ok: true });248    const onUnlock = vi.fn(async () => undefined);249    const container = mount(<LockView hasVault={true} ready={true} onUnlock={onUnlock} />);250251    const password = container.querySelector("#unlock-password") as HTMLInputElement;252    inputText(password, "correct horse battery staple");253    (container.querySelector(".peach-lock-submit") as HTMLButtonElement).click();254    await flushView();255256    expect(sendMessageMock).toHaveBeenCalledWith({257      type: "UNLOCK",258      payload: { password: "correct horse battery staple" },259    });260    expect(onUnlock).toHaveBeenCalled();261  });262263  it("Lock uses a configured preferred PIN and keeps the password fallback available", async () => {264    sendMessageMock.mockImplementation(async (msg: unknown) => {265      const type = (msg as { type: string }).type;266      if (type === "GET_PIN_STATUS") {267        return { ok: true, data: { configured: true, available: true, attemptsRemaining: 3 } };268      }269      return type === "GET_SETTINGS"270        ? { ok: true, data: { pinEnabled: true, pinPreferred: true } }271        : { ok: true };272    });273    const onUnlock = vi.fn(async () => undefined);274    const container = mount(<LockView hasVault={true} ready={true} onUnlock={onUnlock} />);275    await flushView();276277    inputText(container.querySelector("#unlock-pin") as HTMLInputElement, "1234");278    (container.querySelector(".peach-lock-submit") as HTMLButtonElement).click();279    await flushView();280281    expect(sendMessageMock).toHaveBeenCalledWith({282      type: "UNLOCK_WITH_PIN",283      payload: { pin: "1234" },284    });285    expect(onUnlock).toHaveBeenCalled();286    expect(container.textContent).toContain("use master password");287  });288289  it("places the PIN method switch below the unlock button", async () => {290    sendMessageMock.mockImplementation(async (msg: unknown) => {291      const type = (msg as { type: string }).type;292      if (type === "GET_PIN_STATUS") {293        return { ok: true, data: { configured: true, available: true, attemptsRemaining: 3 } };294      }295      return type === "GET_SETTINGS"296        ? { ok: true, data: { pinEnabled: true, pinPreferred: false } }297        : { ok: true };298    });299    const container = mount(<LockView hasVault={true} ready={true} onUnlock={vi.fn()} />);300    await flushView();301302    const buttons = Array.from(container.querySelectorAll("button"));303    const unlockIndex = buttons.findIndex((button) => button.textContent?.trim() === "unlock");304    const pinIndex = buttons.findIndex((button) => button.textContent?.trim() === "use PIN");305    expect(pinIndex).toBeGreaterThan(unlockIndex);306  });307308  it("keeps standalone note creation in Notes mode", async () => {309    const chromeApi = globalThis.chrome as unknown as {310      tabs?: { query: (queryInfo: object, callback: (tabs: unknown[]) => void) => void };311    };312    chromeApi.tabs = { query: vi.fn((_queryInfo, callback) => callback([])) };313314    const addContainer = mount(<AddView onBack={vi.fn()} onSave={vi.fn()} />);315    await flushView();316317    expect(Array.from(addContainer.querySelectorAll(".peach-new-type-btn")).map((button) => button.textContent?.trim()))318      .toEqual(["login", "card"]);319    expect(addContainer.querySelector(".peach-note-editor-body--inline")).toBeNull();320  });321322  it("gives Notes mode the full note-formatting toolbar", async () => {323    const container = mount(324      <NotesEditor325        note={null}326        onBack={vi.fn()}327        onSaved={vi.fn()}328        onDelete={vi.fn()}329      />330    );331    await flushView();332333    expect(container.querySelector('[title="Strikethrough"]')).toBeTruthy();334    expect(container.querySelector('[title="Divider"]')).toBeTruthy();335    expect(container.querySelector('[title="Quote"]')).toBeTruthy();336    expect(container.querySelectorAll(".peach-note-toolbar-desktop-inline button")).toHaveLength(9);337    expect(container.querySelectorAll(".peach-note-toolbar-desktop-inline button svg")).toHaveLength(9);338    expect(container.querySelector(".peach-notes-header-title")?.textContent).toBe("notes.");339  });340341  it("saves formatting applied by the Notes toolbar before leaving", async () => {342    const savedNote = {343      id: "note-1",344      type: "note" as const,345      title: "Untitled",346      notes: "<b>formatted</b>",347      createdAt: 1,348      modifiedAt: 2,349    };350    sendMessageMock.mockResolvedValue({ ok: true, data: savedNote });351    const originalExecCommand = document.execCommand;352    const execCommandMock = vi.fn(() => {353      const body = document.querySelector<HTMLDivElement>(".peach-note-body-field");354      if (body) body.innerHTML = "<b>formatted</b>";355      return true;356    });357    Object.defineProperty(document, "execCommand", { configurable: true, value: execCommandMock });358359    try {360      const container = mount(361        <NotesEditor362          note={null}363          onBack={vi.fn()}364          onSaved={vi.fn()}365          onDelete={vi.fn()}366        />367      );368      await flushView();369      container.querySelector<HTMLButtonElement>('[title="Bold"]')?.dispatchEvent(370        new MouseEvent("mousedown", { bubbles: true, cancelable: true })371      );372      expect(execCommandMock).toHaveBeenCalledWith("bold", false, undefined);373      container.querySelector<HTMLButtonElement>('[aria-label="Back to notes list"]')?.click();374      await flushView();375376      expect(sendMessageMock).toHaveBeenCalledWith({377        type: "SAVE_NOTE",378        payload: { id: undefined, title: "Untitled", body: "<b>formatted</b>" },379      });380    } finally {381      Object.defineProperty(document, "execCommand", { configurable: true, value: originalExecCommand });382    }383  });384385  it("Lock keeps create-vault disabled for short passwords and weak passphrases", async () => {386    const container = mount(<LockView hasVault={false} ready={true} onUnlock={vi.fn()} />);387    const createButton = container.querySelector(".peach-lock-submit") as HTMLButtonElement;388    const password = container.querySelector("#master-password") as HTMLInputElement;389    const confirm = container.querySelector("#confirm-password") as HTMLInputElement;390391    inputText(password, "short");392    inputText(confirm, "short");393    await flushView();394    expect(createButton.disabled).toBe(true);395396    zxcvbnMock.mockImplementation(() => ({ score: 1 }));397    inputText(password, "weakweakweak");398    inputText(confirm, "weakweakweak");399    await flushView();400    expect(createButton.disabled).toBe(true);401  });402403  it("Lock create-vault header pins the wordmark left with back on the right", async () => {404    const container = mount(405      <LockView406        hasVault={false}407        ready={true}408        onUnlock={vi.fn()}409        onBackToOnboarding={() => {}}410      />411    );412    const header = container.querySelector(".peach-newvault-header") as HTMLElement;413    const wordmark = header.querySelector(".peach-wordmark-stack");414    const back = header.querySelector(".peach-newvault-back");415    expect(wordmark).toBeTruthy();416    expect(back).toBeTruthy();417    // Wordmark first so it never shifts between onboarding screens; back418    // takes the opposite corner instead of displacing it.419    expect(header.firstElementChild).toBe(wordmark);420    expect(header.lastElementChild).toBe(back);421    await flushView();422  });423424  it("Lock sends CREATE_VAULT when the onboarding passphrase is strong enough", async () => {425    // Sequence: CREATE_VAULT → show recovery words → GET_RECOVERY_WORDS → user confirms → onUnlock426    sendMessageMock.mockImplementation(427      async (msg: unknown) => {428        const m = msg as { type: string; payload?: { password?: string } };429        if (m.type === "CREATE_VAULT") return { ok: true };430        if (m.type === "GET_RECOVERY_WORDS") {431          // Return 12 fake words — must pass findInvalidWords432          return {433            ok: true,434            data: [435              "abandon", "ability", "able", "about", "above", "absent",436              "absorb", "abstract", "absurd", "abuse", "access", "accident",437            ],438          };439        }440        return { ok: true };441      }442    );443    zxcvbnMock.mockImplementation(() => ({ score: 3 }));444    const onUnlock = vi.fn(async () => undefined);445    const container = mount(<LockView hasVault={false} ready={true} onUnlock={onUnlock} />);446447    const password = container.querySelector("#master-password") as HTMLInputElement;448    const confirm = container.querySelector("#confirm-password") as HTMLInputElement;449    const createButton = container.querySelector(".peach-lock-submit") as HTMLButtonElement;450451    inputText(password, "correct horse battery staple");452    inputText(confirm, "correct horse battery staple");453    await flushView();454    expect(createButton.disabled).toBe(false);455456    pressEnter(confirm);457    await flushView();458459    expect(sendMessageMock).toHaveBeenCalledWith({460      type: "CREATE_VAULT",461      payload: { password: "correct horse battery staple", purpose: "onboarding" },462    });463    // After CREATE_VAULT success, the recovery word display is shown.464    // onUnlock is NOT called yet — user must first confirm their recovery words.465    expect(onUnlock).not.toHaveBeenCalled();466  });467468  it("Lock reports saved-but-locked creation before requesting recovery words", async () => {469    sendMessageMock.mockResolvedValue({ ok: true, data: { committed: true, unlocked: false } });470    zxcvbnMock.mockImplementation(() => ({ score: 3 }));471    const container = mount(<LockView hasVault={false} ready={true} onUnlock={vi.fn()} />);472    inputText(container.querySelector<HTMLInputElement>("#master-password")!, "correct horse battery staple");473    inputText(container.querySelector<HTMLInputElement>("#confirm-password")!, "correct horse battery staple");474    await flushView();475    pressEnter(container.querySelector<HTMLInputElement>("#confirm-password")!);476    await flushView();477    expect(container.textContent).toContain("Your new vault and password were saved");478    expect(sendMessageMock).not.toHaveBeenCalledWith({ type: "SET_RECOVERY_CONFIRM_PENDING" });479  });480481  it("Lock CSV restore stops when creation saved a locked vault", async () => {482    parseImportSourceMock.mockResolvedValue(sampleImportResult());483    sendMessageMock.mockResolvedValue({ ok: true, data: { committed: true, unlocked: false } });484    const container = mount(<LockView hasVault={false} ready={true} initialRestore={true} initialRestoreSource="csv" onUnlock={vi.fn()} />);485    await flushView();486    inputText(container.querySelector<HTMLInputElement>("#restore-csv-pass")!, "new-master-password");487    inputText(container.querySelector<HTMLInputElement>("#restore-csv-confirm")!, "new-master-password");488    const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;489    Object.defineProperty(input, "files", { configurable: true, value: [new File(["csv"], "backup.csv")] });490    input.dispatchEvent(new Event("change", { bubbles: true }));491    await flushView();492    expect(container.textContent).toContain("Your new vault and password were saved");493    expect(sendMessageMock.mock.calls.some(([msg]) => (msg as { type: string }).type === "BATCH_ADD_ENTRIES")).toBe(false);494  });495496  it("Lock PeachScript restore stops when creation saved a locked vault", async () => {497    const script = await import("../../crypto/peachScript");498    const payload = await import("../../crypto/peachPayload");499    vi.spyOn(script, "isPeachScript").mockImplementation((value) => value === "backup");500    vi.spyOn(script, "decodePeachScript").mockReturnValue(new Uint8Array());501    vi.spyOn(payload, "parsePayload").mockResolvedValue({ entries: [sampleEntry()], settings: {} });502    sendMessageMock.mockResolvedValue({ ok: true, data: { committed: true, unlocked: false } });503    const container = mount(<LockView hasVault={false} ready={true} initialRestore={true} initialRestoreSource="symbols" onUnlock={vi.fn()} />);504    await flushView();505    inputText(container.querySelector<HTMLTextAreaElement>(".peach-restore-script")!, "backup");506    inputText(container.querySelector<HTMLInputElement>("#restore-backup-pass")!, "new-master-password");507    container.querySelector<HTMLButtonElement>(".peach-restore-submit")!.click();508    await flushView();509    expect(container.textContent).toContain("Your new vault and password were saved");510    expect(sendMessageMock.mock.calls.some(([msg]) => (msg as { type: string }).type === "RESTORE_ENTRIES")).toBe(false);511  });512513  it("recovery display requests password proof after its initial reveal was consumed", async () => {514    sendMessageMock.mockImplementation(async (msg: unknown) => {515      const request = msg as { type: string; payload?: { password?: string } };516      if (request.type === "GET_RECOVERY_WORDS") {517        if (!request.payload?.password) return { ok: false, error: "password_required" };518        if (request.payload.password !== "fresh-password") return { ok: false, error: "wrong_password" };519        return { ok: true, data: WORD_LIST.slice(0, 12) };520      }521      return { ok: true };522    });523    const container = mount(<RecoveryWordDisplayView onDone={vi.fn()} />);524    await flushView();525    const password = container.querySelector<HTMLInputElement>('#recovery-reveal-password');526    expect(password).not.toBeNull();527    inputText(password!, "incorrect-password");528    container.querySelector<HTMLButtonElement>('.peach-recovery-reveal-btn')!.click();529    await flushView();530    expect(container.textContent).toContain("incorrect password");531    inputText(password!, "fresh-password");532    container.querySelector<HTMLButtonElement>('.peach-recovery-reveal-btn')!.click();533    await flushView();534    expect(container.querySelectorAll('.peach-recovery-word-item')).toHaveLength(12);535    expect(password!.value).toBe("");536    expect(sendMessageMock).not.toHaveBeenCalledWith({ type: "SET_RECOVERY_CONFIRM_PENDING" });537  });538539  it("recovery display discards replies arriving after the view hides", async () => {540    let deliver!: (value: unknown) => void;541    sendMessageMock.mockReturnValueOnce(new Promise((resolve) => { deliver = resolve; }));542    const visibility = vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");543    const container = mount(<RecoveryWordDisplayView onDone={vi.fn()} />);544    await flushView();545    visibility.mockReturnValue("hidden");546    document.dispatchEvent(new Event("visibilitychange"));547    deliver({ ok: true, data: WORD_LIST.slice(0, 12) });548    await flushView();549    expect(container.querySelectorAll('.peach-recovery-word-item')).toHaveLength(0);550    visibility.mockReturnValue("visible");551    sendMessageMock.mockResolvedValueOnce({ ok: false, error: "password_required" });552    document.dispatchEvent(new Event("visibilitychange"));553    await flushView();554    expect(container.querySelector('#recovery-reveal-password')).not.toBeNull();555  });556557  it("recovery display clears visible secrets and late replies on vault lock", async () => {558    sendMessageMock.mockResolvedValue({ ok: true, data: WORD_LIST.slice(0, 12) });559    const container = mount(<RecoveryWordDisplayView onDone={vi.fn()} />);560    await flushView();561    expect(container.querySelectorAll('.peach-recovery-word-item')).toHaveLength(12);562    inputText(container.querySelector<HTMLInputElement>('.peach-recovery-confirm-input')!, "abandon");563    const addListener = chrome.runtime.onMessage.addListener as ReturnType<typeof vi.fn>;564    const listener = addListener.mock.calls[0]![0] as (message: { type: string }) => void;565    listener({ type: "VAULT_LOCKED" });566    await flushView();567    expect(container.querySelectorAll('.peach-recovery-word-item')).toHaveLength(0);568    expect(container.querySelector('#recovery-reveal-password')).not.toBeNull();569    sendMessageMock.mockResolvedValueOnce({ ok: false, error: "vault_locked" });570    sendMessageMock.mockResolvedValueOnce({ ok: true });571    sendMessageMock.mockResolvedValueOnce({ ok: true, data: WORD_LIST.slice(0, 12) });572    inputText(container.querySelector<HTMLInputElement>('#recovery-reveal-password')!, "fresh-password");573    container.querySelector<HTMLButtonElement>('.peach-recovery-reveal-btn')!.click();574    await flushView();575    expect(sendMessageMock).toHaveBeenCalledWith({ type: "UNLOCK", payload: { password: "fresh-password" } });576    expect(container.querySelectorAll('.peach-recovery-word-item')).toHaveLength(12);577    expect([...container.querySelectorAll<HTMLInputElement>('.peach-recovery-confirm-input')].every((input) => input.value === "")).toBe(true);578  });579580  it("recovery display asks for three distinct randomized word positions and confirms", async () => {581    const words12 = [582      "abandon", "ability", "able", "about", "above", "absent",583      "absorb", "abstract", "absurd", "abuse", "access", "accident",584    ];585    sendMessageMock.mockImplementation(async (msg: unknown) => {586      const type = (msg as { type?: string }).type;587      if (type === "GET_RECOVERY_WORDS") return { ok: true, data: words12 };588      return { ok: true };589    });590591    vi.useFakeTimers();592    const onDone = vi.fn();593    try {594      const container = mount(<RecoveryWordDisplayView onDone={onDone} />);595      // onMount fires GET_RECOVERY_WORDS; let the resolved promise + render settle596      await vi.advanceTimersByTimeAsync(0);597598      const prompts = Array.from(599        container.querySelectorAll(".peach-recovery-confirm-num")600      ).map((el) => Number.parseInt((el.textContent ?? "").replace(/\D+/g, ""), 10));601      expect(prompts).toHaveLength(3);602      expect(new Set(prompts).size).toBe(3);603      for (const p of prompts) {604        expect(p).toBeGreaterThanOrEqual(1);605        expect(p).toBeLessThanOrEqual(12);606      }607608      // Inputs stay disabled until the 5s countdown expires609      const inputs = Array.from(610        container.querySelectorAll(".peach-recovery-confirm-input")611      ) as HTMLInputElement[];612      expect(inputs).toHaveLength(3);613      expect(inputs[0]!.disabled).toBe(true);614      await vi.advanceTimersByTimeAsync(5000);615      expect(inputs[0]!.disabled).toBe(false);616617      prompts.forEach((pos, i) => {618        inputText(inputs[i]!, words12[pos - 1]!);619      });620621      const confirmBtn = container.querySelector(".peach-recovery-confirm-btn") as HTMLButtonElement;622      expect(confirmBtn.disabled).toBe(false);623      confirmBtn.click();624      await vi.advanceTimersByTimeAsync(700); // success pause before onDone625626      expect(onDone).toHaveBeenCalledTimes(1);627    } finally {628      vi.useRealTimers();629    }630  });631632  it.each([true, false])("Recovery words flow reports whether the saved password unlocked the vault (%s)", async (unlocked) => {633    sendMessageMock.mockImplementation(async (msg: unknown) => {634      const type = (msg as { type?: string }).type;635      if (type === "VALIDATE_RECOVERY_WORDS") {636        return { ok: true, data: { valid: true, invalid: [] } };637      }638      if (type === "RECOVER_WITH_WORDS") return { ok: true, data: { committed: true, unlocked } };639      return { ok: true };640    });641    const canvasContext = {642      clearRect: vi.fn(),643      fillText: vi.fn(),644      beginPath: vi.fn(),645      closePath: vi.fn(),646      arc: vi.fn(),647      fill: vi.fn(),648      stroke: vi.fn(),649      save: vi.fn(),650      restore: vi.fn(),651      translate: vi.fn(),652      rotate: vi.fn(),653      scale: vi.fn(),654      drawImage: vi.fn(),655      measureText: vi.fn(() => ({ width: 0 })),656      setTransform: vi.fn(),657      fillRect: vi.fn(),658      strokeRect: vi.fn(),659    } as unknown as CanvasRenderingContext2D;660    vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(() => canvasContext);661662    const onRecoveryComplete = vi.fn(async () => undefined);663    const onCancel = vi.fn();664    const container = mount(665      <RecoveryWordEntryView666        onCancel={onCancel}667        onRecoveryComplete={onRecoveryComplete}668      />669    );670671    const recoveryWords = WORD_LIST.slice(0, 12);672    for (let i = 0; i < recoveryWords.length; i++) {673      const input = container.querySelector(`#recovery-word-${i}`) as HTMLInputElement;674      inputText(input, recoveryWords[i]!);675    }676    await flushView();677678    findButton(container, "verify words").click();679    await flushView();680681    expect(container.textContent).toContain("new master password");682683    const newPassword = container.querySelector("#recovery-new-password") as HTMLInputElement;684    const confirmPassword = container.querySelector("#recovery-confirm-password") as HTMLInputElement;685    inputText(newPassword, "fresh-recovery-password");686    inputText(confirmPassword, "fresh-recovery-password");687    await flushView();688689    findButton(container, "recover vault").click();690    await flushView();691692    expect(sendMessageMock).toHaveBeenCalledWith({693      type: "RECOVER_WITH_WORDS",694      payload: {695        words: recoveryWords,696        newPassword: "fresh-recovery-password",697      },698    });699    if (unlocked) expect(onRecoveryComplete).toHaveBeenCalled();700    else {701      expect(onRecoveryComplete).not.toHaveBeenCalled();702      expect(container.textContent).toContain("your new password is saved");703      expect(container.textContent).toContain("use your new password to unlock your vault");704      expect(container.textContent).not.toContain("recovery failed");705      findButton(container, "back to unlock").click();706      expect(onCancel).toHaveBeenCalledOnce();707    }708  });709710  it("Export menu surfaces both backup formats", async () => {711    const container = mount(<ExportView onBack={vi.fn()} />);712    await flushView();713714    expect(container.textContent).toContain("PeachScript");715    expect(container.textContent).toContain("CSV");716  });717718  it("Lock can open directly on backup restore from onboarding", async () => {719    const container = mount(() => (720      <LockView721        hasVault={false}722        ready={true}723        onUnlock={vi.fn()}724        initialRestore={true}725      />726    ));727    await flushView();728729    expect(container.textContent).toContain("PeachScript");730    expect(container.textContent).toContain("Codex");731    expect(container.textContent).toContain("CSV");732    expect(container.querySelector("#master-password")).toBeNull();733  });734735  it("Lock restore back returns to onboarding, not the create-vault screen", async () => {736    const onBackToOnboarding = vi.fn();737    const container = mount(() => (738      <LockView739        hasVault={false}740        ready={true}741        onUnlock={vi.fn()}742        initialRestore={true}743        onBackToOnboarding={onBackToOnboarding}744      />745    ));746    await flushView();747748    (container.querySelector(".peach-restore-back") as HTMLButtonElement).click();749    await flushView();750    expect(onBackToOnboarding).toHaveBeenCalledTimes(1);751  });752753  it("Lock restore resumes on the picked PeachScript source, not the picker", async () => {754    const container = mount(() => (755      <LockView756        hasVault={false}757        ready={true}758        onUnlock={vi.fn()}759        initialRestore={true}760        initialRestoreSource="symbols"761      />762    ));763    await flushView();764765    expect(container.querySelector(".peach-restore-script")).toBeTruthy();766    expect(container.querySelector("#restore-backup-pass")).toBeTruthy();767    expect(container.querySelector(".peach-restore-sources")).toBeNull();768  });769770  it("Lock restore resumes on the picked CSV source, not the picker", async () => {771    const container = mount(() => (772      <LockView773        hasVault={false}774        ready={true}775        onUnlock={vi.fn()}776        initialRestore={true}777        initialRestoreSource="csv"778      />779    ));780    await flushView();781782    expect(container.querySelector("#restore-csv-pass")).toBeTruthy();783    expect(container.querySelector("#restore-csv-confirm")).toBeTruthy();784    expect(container.querySelector(".peach-restore-sources")).toBeNull();785  });786787  it("Lock restore PeachScript form loads a dropped .peach file", async () => {788    const container = mount(() => (789      <LockView790        hasVault={false}791        ready={true}792        onUnlock={vi.fn()}793        initialRestore={true}794        initialRestoreSource="symbols"795      />796    ));797    await flushView();798799    const form = container.querySelector(".peach-restore-form") as HTMLElement;800    expect(form).toBeTruthy();801802    // The OS file picker dismisses the action popup, so drag-and-drop is the803    // file path that survives; a drop must land the file in the script field.804    const file = new File(["dropped-peach-backup"], "vault.peach", { type: "text/plain" });805    const drop = new Event("drop", { bubbles: true, cancelable: true }) as Event & {806      dataTransfer?: { files: File[] };807    };808    drop.dataTransfer = { files: [file] };809    form.dispatchEvent(drop);810    await flushView();811812    const script = container.querySelector(".peach-restore-script") as HTMLTextAreaElement;813    expect(script.value).toBe("dropped-peach-backup");814  });815816  it("HOLE 4: removing a device discloses that recovery words survive revocation", async () => {817    const device = {818      deviceId: "phone-1",819      deviceName: "June's Phone",820      deviceType: "android" as const,821      longTermPublicKeyHex: "a".repeat(64),822      signingPublicKeyHex: "b".repeat(64),823      pairedAt: 1,824      trustSource: "direct" as const,825    };826    sendMessageMock.mockImplementation(async (msg: unknown) => {827      const m = msg as { type: string };828      if (m.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [device] } };829      return { ok: true, data: null };830    });831832    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);833    for (let i = 0; i < 30; i++) await Promise.resolve();834835    const openSync = Array.from(container.querySelectorAll("button")).find((b) =>836      /sync/i.test(b.textContent ?? ""),837    );838    openSync?.click();839    for (let i = 0; i < 30; i++) await Promise.resolve();840841    const remove = Array.from(container.querySelectorAll("button")).find(842      (b) => (b.textContent ?? "").trim() === "remove",843    );844    expect(remove).toBeTruthy();845846    // Guard against a vacuous pass: the disclosure must not already be on847    // screen before the user asks to remove anything.848    expect(container.querySelector(".peach-unpair-confirm-note")).toBeNull();849850    remove!.click();851    for (let i = 0; i < 10; i++) await Promise.resolve();852853    // Revocation must never be presented as securing the vault against the854    // removed device — recovery words survive it and restore everything.855    const note = container.querySelector(".peach-unpair-confirm-note");856    expect(note).toBeTruthy();857    const text = note!.textContent ?? "";858    expect(text).toContain("master password");859    expect(text).toContain("recovery words");860    expect(text).toContain("future changes");861  });862863  it("PB-26-709: pending device approval identifies the key, time, provenance, and vault scope", async () => {864    sendMessageMock.mockImplementation(async (msg: unknown) => {865      const m = msg as { type: string };866      if (m.type === "GET_PENDING_VOUCHED_DEVICES") {867        return {868          ok: true,869          data: [{870            deviceId: "phone-source-id",871            deviceName: "June's Phone",872            deviceType: "android",873            longTermPublicKeyHex: "a1b2c3d4e5f6" + "0".repeat(52),874            signingPublicKeyHex: "b".repeat(64),875            pairedAt: Date.UTC(2026, 8, 5),876            receivedAt: Date.UTC(2026, 8, 6, 20, 15),877            vouchedByDeviceId: "trusted-browser-id",878          }],879        };880      }881      if (m.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [] } };882      return { ok: true, data: null };883    });884885    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);886    for (let i = 0; i < 30; i++) await Promise.resolve();887    Array.from(container.querySelectorAll("button"))888      .find((button) => /sync/i.test(button.textContent ?? ""))889      ?.click();890    for (let i = 0; i < 30; i++) await Promise.resolve();891892    expect(container.textContent).toContain("a1b2 c3d4 e5f6");893    expect(container.textContent).toContain("trusted-browser-id");894    expect(container.textContent).toContain("2026-09-06");895    expect(container.textContent).toContain("existing vault contents");896  });897898  it("Settings keeps the paired-device list and revokes through UNPAIR_DEVICE", async () => {899    const device = {900      deviceId: "phone-1",901      deviceName: "June's Phone",902      deviceType: "android" as const,903      longTermPublicKeyHex: "a".repeat(64),904      signingPublicKeyHex: "b".repeat(64),905      pairedAt: 1,906      trustSource: "direct" as const,907    };908    let paired: typeof device[] = [device];909    sendMessageMock.mockImplementation(async (msg: any) => {910      if (msg?.type === "LIST_PAIRED_DEVICES") {911        return { ok: true, data: { devices: [...paired] } };912      }913      if (msg?.type === "UNPAIR_DEVICE") {914        // Mirror the real handler: UNPAIR_DEVICE drops the row from the915        // registry. The next LIST_PAIRED_DEVICES must not see it.916        paired = paired.filter((d) => d.deviceId !== msg.payload?.deviceId);917        return { ok: true };918      }919      if (msg?.type === "RENAME_PAIRED_DEVICE") {920        paired = paired.map((d) =>921          d.deviceId === msg.payload?.deviceId ? { ...d, localAlias: msg.payload.name } : d,922        );923        return { ok: true };924      }925      return { ok: true, data: null };926    });927928    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);929    for (let i = 0; i < 30; i++) await Promise.resolve();930    Array.from(container.querySelectorAll("button"))931      .find((b) => /sync/i.test(b.textContent ?? ""))932      ?.click();933    for (let i = 0; i < 30; i++) await Promise.resolve();934935    // The list itself: extracting the relay selector must not take the hub with it.936    expect(container.textContent).toContain("PAIRED DEVICES");937    expect(container.textContent).toContain("June's Phone");938    expect(container.textContent).toContain("Android");939    Array.from(container.querySelectorAll("button"))940      .find((b) => (b.textContent ?? "").trim() === "rename")!941      .click();942    const renameInput = container.querySelector<HTMLInputElement>('input[aria-label="Rename June\'s Phone"]')!;943    renameInput.value = "Travel phone";944    renameInput.dispatchEvent(new InputEvent("input", { bubbles: true }));945    Array.from(container.querySelectorAll("button"))946      .find((b) => (b.textContent ?? "").trim() === "save")!947      .click();948    for (let i = 0; i < 30; i++) await Promise.resolve();949    expect(sendMessageMock).toHaveBeenCalledWith({950      type: "RENAME_PAIRED_DEVICE",951      payload: { deviceId: "phone-1", name: "Travel phone" },952    });953    expect(container.textContent).toContain("Travel phone");954    const syncNowButton = container.querySelector<HTMLButtonElement>(955      'button[aria-label="Sync this vault now"]',956    )!;957    const syncStatusRow = syncNowButton.closest(".peach-settings-row--meta");958    const syncCard = syncNowButton.closest('[data-settings-card-id="sync"]');959    expect(syncStatusRow).not.toBeNull();960    expect(syncStatusRow?.contains(syncNowButton)).toBe(true);961    expect(syncCard?.querySelectorAll(".peach-settings-row--meta")).toHaveLength(1);962    const labels = Array.from(container.querySelectorAll(".peach-settings-sub-label"));963    const addDeviceLabel = labels.find((label) => label.textContent?.includes("ADD A DEVICE"))!;964    const pairedDevicesLabel = labels.find((label) => label.textContent?.includes("PAIRED DEVICES"))!;965    expect(966      syncNowButton.compareDocumentPosition(addDeviceLabel) & Node.DOCUMENT_POSITION_FOLLOWING,967    ).toBeTruthy();968    expect(969      syncNowButton.compareDocumentPosition(pairedDevicesLabel) & Node.DOCUMENT_POSITION_FOLLOWING,970    ).toBeTruthy();971972    Array.from(container.querySelectorAll("button"))973      .find((b) => (b.textContent ?? "").trim() === "remove")!974      .click();975    for (let i = 0; i < 10; i++) await Promise.resolve();976    const confirm = Array.from(977      container.querySelectorAll<HTMLButtonElement>(".peach-unpair-confirm button"),978    ).find((b) => (b.textContent ?? "").trim() === "remove");979    confirm!.click();980    for (let i = 0; i < 30; i++) await Promise.resolve();981982    expect(sendMessageMock).toHaveBeenCalledWith({983      type: "UNPAIR_DEVICE",984      payload: { deviceId: "phone-1" },985    });986    // The list must be refreshed and the device must be gone. The regression987    // we're guarding against: a Settings view that calls UNPAIR_DEVICE but988    // never refreshes LIST_PAIRED_DEVICES, so the row stays in the UI.989    expect(container.textContent).not.toContain("June's Phone");990    expect(container.textContent).not.toContain("PAIRED DEVICES");991  });992  it("Settings keeps the confirmation and shows revoke failures", async () => {993    const device = {994      deviceId: "phone-1",995      deviceName: "June's Phone",996      deviceType: "android" as const,997      longTermPublicKeyHex: "a".repeat(64),998      signingPublicKeyHex: "b".repeat(64),999      pairedAt: 1,1000      trustSource: "direct" as const,1001    };1002    sendMessageMock.mockImplementation(async (msg: unknown) => {1003      const message = msg as { type?: string; payload?: { deviceId?: string } };1004      if (message.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [device] } };1005      if (message.type === "UNPAIR_DEVICE") return { ok: false, error: "trust_data_corrupted" };1006      return { ok: true, data: null };1007    });10081009    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);1010    for (let i = 0; i < 30; i++) await Promise.resolve();1011    for (let i = 0; i < 30; i++) await Promise.resolve();1012    Array.from(container.querySelectorAll("button")).find((b) => /sync/i.test(b.textContent ?? ""))?.click();1013    for (let i = 0; i < 30; i++) await Promise.resolve();1014    Array.from(container.querySelectorAll("button")).find((b) => (b.textContent ?? "").trim() === "remove")?.click();1015    for (let i = 0; i < 10; i++) await Promise.resolve();1016    Array.from(container.querySelectorAll<HTMLButtonElement>(".peach-unpair-confirm button")).find((b) => (b.textContent ?? "").trim() === "remove")?.click();1017    for (let i = 0; i < 30; i++) await Promise.resolve();10181019    expect(container.textContent).toContain("trust_data_corrupted");1020    expect(container.textContent).toContain("June's Phone");1021  });10221023  it("Settings drops the secure-reset panel once the device is on the settled generation", async () => {1024    const openSyncCard = async (state: "V2_ACTIVE" | "V2_ANCHOR" | "LEGACY_ACTIVE") => {1025      sendMessageMock.mockImplementation(async (msg: unknown) => {1026        const message = msg as { type?: string };1027        if (message.type === "GET_SYNC_GENERATION") {1028          return { ok: true, data: { schemaVersion: 1, generation: 2, state, createdAt: 1 } };1029        }1030        return { ok: true, data: null };1031      });1032      const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);1033      for (let i = 0; i < 30; i++) await Promise.resolve();1034      Array.from(container.querySelectorAll("button")).find((b) => /sync/i.test(b.textContent ?? ""))?.click();1035      for (let i = 0; i < 30; i++) await Promise.resolve();1036      return container;1037    };10381039    // Settled: the migration is over, so the panel must not linger as a label.1040    const settled = await openSyncCard("V2_ACTIVE");1041    expect(settled.textContent).not.toContain("SECURE SYNC RESET");1042    expect(settled.textContent).toContain("ADD A DEVICE");10431044    // Still actionable states keep the panel and its explanation.1045    const anchored = await openSyncCard("V2_ANCHOR");1046    expect(anchored.textContent).toContain("SECURE SYNC RESET");1047    expect(anchored.textContent).toContain("Not re-paired");10481049    const legacy = await openSyncCard("LEGACY_ACTIVE");1050    expect(legacy.textContent).toContain("SECURE SYNC RESET");1051    expect(legacy.textContent).toContain("Legacy Sync generation");1052  });10531054  it("Settings keeps connection and recovery details collapsed until requested", async () => {1055    sendMessageMock.mockImplementation(async (msg: any) => {1056      if (msg?.type === "LIST_PAIRED_DEVICES") {1057        return { ok: true, data: { devices: [] } };1058      }1059      return { ok: true, data: null };1060    });10611062    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);1063    for (let i = 0; i < 30; i++) await Promise.resolve();1064    Array.from(container.querySelectorAll("button"))1065      .find((button) => /sync/i.test(button.textContent ?? ""))1066      ?.click();1067    for (let i = 0; i < 20; i++) await Promise.resolve();10681069    expect(container.textContent).toContain("SYNC STATUS");1070    expect(container.textContent).toContain("ADD A DEVICE");1071    expect(container.textContent).not.toContain("Public relay");1072    expect(container.textContent).not.toContain("Rotate sync identity");10731074    const connection = Array.from(container.querySelectorAll("button"))1075      .find((button) => button.textContent?.includes("CONNECTION"));1076    connection?.click();1077    await Promise.resolve();1078    expect(container.textContent).toContain("Public relay");10791080    const recovery = Array.from(container.querySelectorAll("button"))1081      .find((button) => button.textContent?.includes("RECOVERY & SECURITY"));1082    recovery?.click();1083    await Promise.resolve();1084    expect(container.textContent).toContain("Rotate sync identity");1085  });10861087  it("Settings sends fresh master-password proof with sync rotation", async () => {1088    sendMessageMock.mockImplementation(async (msg: unknown) => {1089      const request = msg as { type: string };1090      if (request.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [] } };1091      if (request.type === "ROTATE_SYNC_IDENTITY") return { ok: false, error: "wrong_password" };1092      return { ok: true, data: null };1093    });1094    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);1095    await flushView();1096    container.querySelector<HTMLElement>('[data-settings-card-id="sync"]')!.click();1097    await flushView();1098    Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.includes("RECOVERY & SECURITY"))!.click();1099    await flushView();1100    Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.trim() === "rotate")!.click();1101    await flushView();1102    const confirm = Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.trim() === "Rotate sync identity")!;1103    expect(confirm.disabled).toBe(true);1104    const password = container.querySelector<HTMLInputElement>('#rotate-master-password');1105    expect(password).not.toBeNull();1106    inputText(password!, "current-master-password");1107    confirm.click();1108    await flushView();1109    expect(sendMessageMock).toHaveBeenCalledWith({ type: "ROTATE_SYNC_IDENTITY", payload: { password: "current-master-password" } });1110    expect(password!.value).toBe("");1111    expect(container.textContent).toContain("incorrect password");1112  });11131114  it("Settings requires current, new, and confirm passwords before enabling save", async () => {1115    sendMessageMock.mockResolvedValue({ ok: true, data: null });1116    const container = mount(1117      <SettingsView1118        entriesCount={1}1119        breachMonitoring={true}1120        lockOnClose={true}1121        lockedSyncRequiresUnlock={false}1122        autoLockMinutes={5}1123        trashRetentionDays={30}1124        theme="dark"1125        accentColor="peach"1126        textSize="medium"1127        reduceMotion={false}1128        onBreachMonitoringChange={vi.fn()}1129        onLockedSyncRequiresUnlockChange={vi.fn()}1130        onLockOnCloseChange={vi.fn()}1131        onAutoLockMinutesChange={vi.fn()}1132        onTrashRetentionChange={vi.fn()}1133        onThemeChange={vi.fn()}1134        onAccentChange={vi.fn()}1135        onTextSizeChange={vi.fn()}1136        onReduceMotionChange={vi.fn()}1137        shortcuts={DEFAULT_BINDINGS}1138        onShortcutsChange={vi.fn()}1139        onBack={vi.fn()}1140        onImport={vi.fn()}1141        onExport={vi.fn()}1142        onBreachCheckDone={vi.fn()}1143      />1144    );1145    await flushView();11461147    expect(container.querySelectorAll(".stk-card").length).toBe(7);1148    // Settings now opens to card I (Peach Pro) — see koh save [f7a2710b3f67]1149    // "open settings to card I (Peach Pro) instead of card II (Protection)".1150    expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Peach Pro");11511152    const changeButton = Array.from(container.querySelectorAll("button")).find(1153      (candidate) => candidate.textContent?.trim() === "change"1154    ) as HTMLButtonElement;1155    changeButton.click();1156    await flushView();11571158    const saveButton = Array.from(container.querySelectorAll("button")).find(1159      (candidate) => candidate.textContent?.trim() === "save new password"1160    ) as HTMLButtonElement;1161    expect(saveButton.disabled).toBe(true);11621163    const inputs = container.querySelectorAll('input[type="password"]');1164    inputText(inputs[0] as HTMLInputElement, "current-pass");1165    inputText(inputs[1] as HTMLInputElement, "new-pass-12345");1166    await flushView();1167    expect(saveButton.disabled).toBe(true);11681169    inputText(inputs[2] as HTMLInputElement, "new-pass-12345");1170    await flushView();1171    expect(saveButton.disabled).toBe(false);1172  });11731174  it("Settings feedback highlights the selected category and hides the form after submit", async () => {1175    sendMessageMock.mockResolvedValue({ ok: true, data: null });1176    const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => ({1177      ok: true,1178      json: async () => ({ success: true }),1179    }));1180    vi.stubGlobal("fetch", fetchMock);11811182    const container = mount(1183      <SettingsView1184        entriesCount={1}1185        breachMonitoring={true}1186        lockOnClose={true}1187        lockedSyncRequiresUnlock={false}1188        autoLockMinutes={5}1189        trashRetentionDays={30}1190        theme="dark"1191        accentColor="peach"1192        textSize="medium"1193        reduceMotion={false}1194        initialSection="feedback"1195        onLockedSyncRequiresUnlockChange={vi.fn()}1196        onBreachMonitoringChange={vi.fn()}1197        onLockOnCloseChange={vi.fn()}1198        onAutoLockMinutesChange={vi.fn()}1199        onTrashRetentionChange={vi.fn()}1200        onThemeChange={vi.fn()}1201        onAccentChange={vi.fn()}1202        onTextSizeChange={vi.fn()}1203        onReduceMotionChange={vi.fn()}1204        shortcuts={DEFAULT_BINDINGS}1205        onShortcutsChange={vi.fn()}1206        onBack={vi.fn()}1207        onImport={vi.fn()}1208        onExport={vi.fn()}1209        onBreachCheckDone={vi.fn()}1210      />1211    );1212    await flushView();12131214    const feedbackCard = container.querySelector('[data-settings-card-id="feedback"]') as HTMLElement;1215    expect(feedbackCard.classList.contains("is-active")).toBe(true);12161217    const categoryButtons = Array.from(container.querySelectorAll(".peach-feedback-chip")) as HTMLButtonElement[];1218    const bugButton = categoryButtons.find((button) => button.textContent?.trim() === "Bug report")!;1219    const featureButton = categoryButtons.find((button) => button.textContent?.trim() === "Feature request")!;1220    expect(bugButton.getAttribute("aria-pressed")).toBe("true");1221    expect(featureButton.getAttribute("aria-pressed")).toBe("false");12221223    featureButton.click();1224    await flushView();12251226    expect(bugButton.getAttribute("aria-pressed")).toBe("false");1227    expect(featureButton.getAttribute("aria-pressed")).toBe("true");1228    expect(featureButton.classList.contains("is-active")).toBe(true);12291230    inputText(1231      container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,1232      '<script>alert("xss")</script> Please make this easier to see & safer.'1233    );1234    const sendButton = Array.from(container.querySelectorAll("button")).find(1235      (candidate) => candidate.textContent?.trim() === "Send"1236    ) as HTMLButtonElement;1237    sendButton.click();12381239    await vi.waitFor(() => {1240      expect(container.textContent).toContain("Thank you");1241    });12421243    const requestBody = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));1244    expect(requestBody.subject).toContain("Feature request");1245    expect(requestBody.message).toBe(1246      "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt; Please make this easier to see &amp; safer."1247    );1248    expect(requestBody.message).not.toContain("<script>");1249    expect(container.textContent).toContain("Someone will process it soon");1250    expect(container.querySelector(".peach-feedback-textarea")).toBeNull();1251    expect(container.querySelector(".peach-feedback-submit")).toBeNull();1252  });12531254  it("Settings keeps license activation on the full-screen celebration path", async () => {1255    const onLicenseChange = vi.fn(async () => undefined);1256    sendMessageMock.mockImplementation(async (msg: unknown) => {1257      const type = (msg as { type?: string }).type;1258      if (type === "GET_LICENSE") return { ok: true, data: { valid: false, plan: "free" } };1259      if (type === "ACTIVATE_LICENSE") {1260        return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };1261      }1262      if (type === "GET_ENTRIES") return { ok: true, data: [] };1263      return { ok: true, data: null };1264    });12651266    const container = mount(<SettingsView {...settingsProps({ isPro: false, onLicenseChange })} />);1267    await flushView();12681269    inputText(1270      container.querySelector(".peach-pro-key-inline-input") as HTMLInputElement,1271      "PEACH-TEST-KEY",1272    );1273    const apply = container.querySelector(".peach-pro-key-apply") as HTMLButtonElement;1274    apply.click();12751276    await vi.waitFor(() => expect(onLicenseChange).toHaveBeenCalledTimes(1));1277    expect(container.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(false);1278    expect(container.textContent).not.toContain("thank you ✦");1279  });12801281  it("Settings Pro star and peach clicks use the same in-card replay path", async () => {1282    sendMessageMock.mockImplementation(async (msg: unknown) => {1283      const type = (msg as { type?: string }).type;1284      if (type === "GET_LICENSE") return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };1285      if (type === "GET_LICENSE_KEY") return { ok: true, data: "PEACH-TEST-KEY" };1286      if (type === "GET_ENTRIES") return { ok: true, data: [] };1287      return { ok: true, data: null };1288    });12891290    const onLicenseChangeFromStar = vi.fn();1291    const starContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromStar })} />);1292    await flushView();1293    (starContainer.querySelector(".stk-card-icon--btn") as HTMLButtonElement).click();1294    expect(starContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);1295    expect(onLicenseChangeFromStar).not.toHaveBeenCalled();12961297    const onLicenseChangeFromPeach = vi.fn();1298    const peachContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromPeach })} />);1299    await flushView();1300    (peachContainer.querySelector(".peach-pro-active-mark-wrap") as HTMLButtonElement).click();1301    expect(peachContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);1302    expect(onLicenseChangeFromPeach).not.toHaveBeenCalled();1303  });13041305  it("Settings feedback sends even if Firefox reports no data-collection consent — a user-initiated send is its own consent", async () => {1306    sendMessageMock.mockResolvedValue({ ok: true, data: null });1307    const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => ({1308      ok: true,1309      json: async () => ({ success: true }),1310    }));1311    vi.stubGlobal("fetch", fetchMock);1312    // Firefox-style permissions API reporting the optional consent as absent.1313    // The old code gated send behind this and silently returned to idle, which1314    // read as a dead Send button. The gate is gone: Send must always send.1315    vi.stubGlobal("browser", {1316      permissions: {1317        getAll: vi.fn(async () => ({ data_collection: [] })),1318        request: vi.fn(async () => false),1319      },1320    });13211322    const container = mount(1323      <SettingsView1324        entriesCount={1}1325        breachMonitoring={true}1326        lockOnClose={true}1327        lockedSyncRequiresUnlock={false}1328        autoLockMinutes={5}1329        trashRetentionDays={30}1330        theme="dark"1331        accentColor="peach"1332        textSize="medium"1333        reduceMotion={false}1334        initialSection="feedback"1335        onLockedSyncRequiresUnlockChange={vi.fn()}1336        onBreachMonitoringChange={vi.fn()}1337        onLockOnCloseChange={vi.fn()}1338        onAutoLockMinutesChange={vi.fn()}1339        onTrashRetentionChange={vi.fn()}1340        onThemeChange={vi.fn()}1341        onAccentChange={vi.fn()}1342        onTextSizeChange={vi.fn()}1343        onReduceMotionChange={vi.fn()}1344        shortcuts={DEFAULT_BINDINGS}1345        onShortcutsChange={vi.fn()}1346        onBack={vi.fn()}1347        onImport={vi.fn()}1348        onExport={vi.fn()}1349        onBreachCheckDone={vi.fn()}1350      />1351    );1352    await flushView();13531354    inputText(1355      container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,1356      "Please improve the feedback flow."1357    );1358    const sendButton = Array.from(container.querySelectorAll("button")).find(1359      (candidate) => candidate.textContent?.trim() === "Send"1360    ) as HTMLButtonElement;1361    sendButton.click();13621363    await vi.waitFor(() => {1364      expect(fetchMock).toHaveBeenCalledTimes(1);1365    });1366    await vi.waitFor(() => {1367      expect(container.textContent).toContain("Thank you");1368    });1369    expect(container.querySelector(".peach-feedback-textarea")).toBeNull();1370  });13711372  it("Settings sends CHANGE_PASSWORD and forwards auto-lock/theme changes through callbacks", async () => {1373    sendMessageMock.mockImplementation(async (msg: unknown) => {1374      const m = msg as { type: string };1375      if (m.type === "GET_RECOVERY_WORDS") {1376        return {1377          ok: true,1378          data: [1379            "abandon", "ability", "able", "about", "above", "absent",1380            "absorb", "abstract", "absurd", "abuse", "access", "accident",1381          ],1382        };1383      }1384      return { ok: true, data: null };1385    });1386    const onAutoLockMinutesChange = vi.fn();1387    const onLockedSyncRequiresUnlockChange = vi.fn();1388    const onThemeChange = vi.fn();1389    const container = mount(1390      <SettingsView1391        entriesCount={1}1392        breachMonitoring={true}1393        lockOnClose={true}1394        lockedSyncRequiresUnlock={false}1395        autoLockMinutes={5}1396        trashRetentionDays={30}1397        theme="dark"1398        accentColor="peach"1399        textSize="medium"1400        reduceMotion={false}1401        onBreachMonitoringChange={vi.fn()}1402        onLockedSyncRequiresUnlockChange={onLockedSyncRequiresUnlockChange}1403        onLockOnCloseChange={vi.fn()}1404        onAutoLockMinutesChange={onAutoLockMinutesChange}1405        onTrashRetentionChange={vi.fn()}1406        onThemeChange={onThemeChange}1407        onAccentChange={vi.fn()}1408        onTextSizeChange={vi.fn()}1409        onReduceMotionChange={vi.fn()}1410        shortcuts={DEFAULT_BINDINGS}1411        onShortcutsChange={vi.fn()}1412        onBack={vi.fn()}1413        onImport={vi.fn()}1414        onExport={vi.fn()}1415        onBreachCheckDone={vi.fn()}1416      />1417    );1418    await flushView();1419    sendMessageMock.mockClear();14201421    // ── Auto-lock + theme changes (before password change) ─────────────1422    const selects = container.querySelectorAll("select");1423    changeSelect(selects[0] as HTMLSelectElement, "15");1424    expect(onAutoLockMinutesChange).toHaveBeenCalledWith(15);14251426    const appearanceCard = container.querySelector('[data-settings-card-id="appearance"]') as HTMLElement;1427    appearanceCard.click();1428    await flushView();1429    expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Appearance");1430    const themeButton = Array.from(container.querySelectorAll("button")).find(1431      (candidate) => candidate.textContent?.trim() === "Switch to light"1432    ) as HTMLButtonElement;1433    themeButton.click();1434    expect(onThemeChange).toHaveBeenCalledWith("light");14351436    // ── Locked Sync custody toggle ──────────────────────────────────────1437    const protectionCard = container.querySelector('[data-settings-card-id="protection"]') as HTMLElement;1438    protectionCard.click();1439    await flushView();1440    const custodyToggle = container.querySelector<HTMLButtonElement>(1441      'button[aria-label="Toggle unlock requirement for locked Sync after restart"]',1442    );1443    expect(custodyToggle).not.toBeNull();1444    custodyToggle!.click();1445    expect(onLockedSyncRequiresUnlockChange).toHaveBeenCalledWith(true);14461447    const changeButton = Array.from(container.querySelectorAll("button")).find(1448      (candidate) => candidate.textContent?.trim() === "change"1449    ) as HTMLButtonElement;1450    changeButton.click();1451    await flushView();14521453    const inputs = container.querySelectorAll('input[type="password"]');1454    inputText(inputs[0] as HTMLInputElement, "current-pass");1455    inputText(inputs[1] as HTMLInputElement, "new-password-123");1456    inputText(inputs[2] as HTMLInputElement, "new-password-123");1457    await flushView();14581459    const saveButton = Array.from(container.querySelectorAll("button")).find(1460      (candidate) => candidate.textContent?.trim() === "save new password"1461    ) as HTMLButtonElement;1462    saveButton.click();1463    await flushView();14641465    expect(sendMessageMock).toHaveBeenCalledWith({1466      type: "CHANGE_PASSWORD",1467      payload: {1468        currentPassword: "current-pass",1469        newPassword: "new-password-123",1470      },1471    });14721473    expect(sendMessageMock).not.toHaveBeenCalledWith({ type: "SET_RECOVERY_CONFIRM_PENDING" });1474    // After a successful password change the recovery word display replaces settings.1475    expect(container.textContent).toContain("save your recovery words");1476    expect(sendMessageMock).toHaveBeenCalledWith({ type: "GET_RECOVERY_WORDS" });1477  });14781479  it("Entry copy actions send COPY and canary ping messages for password and username", async () => {1480    sendMessageMock.mockResolvedValue({ ok: true });1481    const container = mount(1482      <EntryView1483        entry={sampleEntry()}1484        onDelete={vi.fn()}1485        onFieldSaved={vi.fn(async () => undefined)}1486      />1487    );14881489    const passwordButton = container.querySelector('button[aria-label="Copy password"]') as HTMLButtonElement;1490    passwordButton.click();1491    await flushView();14921493    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1494      type: "COPY",1495      payload: { text: "secret123", label: "password", alreadyWritten: false },1496    });1497    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {1498      type: "FIRE_CANARY_PING",1499      payload: {1500        webhookUrl: "https://example.com/hook",1501        entryTitle: "GitHub",1502        trigger: "password_copied",1503      },1504    });15051506    sendMessageMock.mockClear();1507    const usernameButton = container.querySelector('button[aria-label="Copy username"]') as HTMLButtonElement;1508    usernameButton.click();1509    await flushView();15101511    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1512      type: "COPY",1513      payload: { text: "june", label: "username", alreadyWritten: false },1514    });1515    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {1516      type: "FIRE_CANARY_PING",1517      payload: {1518        webhookUrl: "https://example.com/hook",1519        entryTitle: "GitHub",1520        trigger: "username_copied",1521      },1522    });1523  });15241525  it("Entry keyboard password copy reports its canary after COPY", async () => {1526    sendMessageMock.mockResolvedValue({ ok: true });1527    mount(1528      <EntryView1529        entry={sampleEntry()}1530        onDelete={vi.fn()}1531        onFieldSaved={vi.fn(async () => undefined)}1532      />1533    );15341535    window.dispatchEvent(new KeyboardEvent("keydown", { key: "c", bubbles: true }));1536    await flushView();15371538    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1539      type: "COPY",1540      payload: { text: "secret123", label: "password", alreadyWritten: false },1541    });1542    await flushView();1543    expect(sendMessageMock.mock.calls).toContainEqual([{1544      type: "FIRE_CANARY_PING",1545      payload: {1546        webhookUrl: "https://example.com/hook",1547        entryTitle: "GitHub",1548        trigger: "password_copied",1549      },1550    }]);1551  });1552  it("Entry Cmd+C leaves the native clipboard shortcut untouched", async () => {1553    sendMessageMock.mockResolvedValue({ ok: true });1554    mount(1555      <EntryView1556        entry={sampleEntry()}1557        onDelete={vi.fn()}1558        onFieldSaved={vi.fn(async () => undefined)}1559      />1560    );15611562    window.dispatchEvent(new KeyboardEvent("keydown", { key: "c", metaKey: true, bubbles: true }));1563    await flushView();15641565    expect(sendMessageMock).not.toHaveBeenCalledWith(expect.objectContaining({ type: "COPY" }));1566  });15671568  it("Vault password swipe copy reports its canary after COPY", async () => {1569    sendMessageMock.mockResolvedValue({ ok: true });1570    const container = mount(1571      <VaultView1572        entries={[sampleEntry()]}1573        sortOrder="url-first"1574        onSelectEntry={vi.fn()}1575        onSortOrderChange={vi.fn()}1576        onAdd={vi.fn()}1577        onClose={vi.fn()}1578      />1579    );1580    const row = container.querySelector(".peach-entry-row") as HTMLButtonElement;1581    row.dispatchEvent(new TouchEvent("touchstart", {1582      bubbles: true,1583      touches: [{ clientX: 0, clientY: 0 } as Touch],1584    }));1585    row.dispatchEvent(new TouchEvent("touchend", {1586      bubbles: true,1587      changedTouches: [{ clientX: 100, clientY: 0 } as Touch],1588    }));1589    await flushView();15901591    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1592      type: "COPY",1593      payload: { text: "secret123", label: "password", alreadyWritten: false },1594    });1595    await flushView();1596    expect(sendMessageMock.mock.calls).toContainEqual([{1597      type: "FIRE_CANARY_PING",1598      payload: {1599        webhookUrl: "https://example.com/hook",1600        entryTitle: "GitHub",1601        trigger: "password_copied",1602      },1603    }]);1604  });16051606  it("Entry shows Advanced for passkey-bearing credential entries", async () => {1607    const container = mount(1608      <EntryView1609        entry={sampleEntry({1610          type: "passkey",1611          username: undefined,1612          password: undefined,1613          totp: undefined,1614          canary: undefined,1615          passkey: {1616            rpId: "vercel.com",1617            rpName: "Vercel",1618            credentialId: "cred-1",1619            publicKeyCose: "cose",1620            userHandle: "handle",1621            userName: "june",1622            userDisplayName: "June",1623            algorithm: -7,1624            signCount: 0,1625            aaguid: "",1626            backupEligible: false,1627            backupState: false,1628            createdAt: 1,1629          },1630        })}1631        onDelete={vi.fn()}1632        onFieldSaved={vi.fn(async () => undefined)}1633      />1634    );16351636    const advanced = Array.from(container.querySelectorAll(".peach-entry-add-link")).find(1637      (button) => button.textContent?.includes("Advanced")1638    ) as HTMLButtonElement | undefined;1639    expect(advanced).toBeDefined();1640    expect(advanced?.textContent).toContain("+ Advanced");16411642    advanced!.click();1643    await flushView();16441645    expect(container.textContent).toContain("passkey · vercel.com");1646  });16471648  it("Entry refuses to send an empty password update and copies TOTP through COPY", async () => {1649    sendMessageMock.mockResolvedValue({ ok: true });1650    const onFieldSaved = vi.fn(async () => undefined);1651    const container = mount(1652      <EntryView1653        entry={sampleEntry()}1654        onDelete={vi.fn()}1655        onFieldSaved={onFieldSaved}1656      />1657    );16581659    const passwordValue = container.querySelector(".peach-password-value") as HTMLSpanElement;1660    passwordValue.click();1661    await flushView();16621663    const passwordInput = container.querySelector('input[placeholder="paste or type a password"]') as HTMLInputElement;1664    inputText(passwordInput, "");1665    await flushView();16661667    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;1668    saveButton.click();1669    await flushView();16701671    expect(sendMessageMock).not.toHaveBeenCalledWith(1672      expect.objectContaining({ type: "UPDATE_ENTRY" })1673    );1674    expect(onFieldSaved).not.toHaveBeenCalled();16751676    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;1677    totpMain.click();16781679    await vi.waitFor(() => {1680      expect(sendMessageMock).toHaveBeenLastCalledWith({1681        type: "COPY",1682        payload: { text: "123456", label: "totp", alreadyWritten: false },1683      });1684    }, { timeout: 500 });1685  });16861687  it("Entry closes an unchanged inline editor when focus leaves it", async () => {1688    sendMessageMock.mockResolvedValue({ ok: true });1689    const container = mount(1690      <EntryView1691        entry={sampleEntry()}1692        onDelete={vi.fn()}1693        onFieldSaved={vi.fn(async () => undefined)}1694      />1695    );16961697    const usernameValue = container.querySelector(".peach-field-value.peach-inline-clickable") as HTMLSpanElement;1698    usernameValue.click();1699    await flushView();17001701    const usernameInput = container.querySelector(".peach-inline-input[autocomplete=\"off\"]") as HTMLInputElement;1702    usernameInput.blur();1703    await flushView();17041705    expect(container.querySelector(".peach-inline-input[autocomplete=\"off\"]")).toBeNull();1706    expect(sendMessageMock).not.toHaveBeenCalledWith(1707      expect.objectContaining({ type: "UPDATE_ENTRY" })1708    );1709  });17101711  it("Entry keeps the full used-email list available while editing an email", async () => {1712    const container = mount(1713      <EntryView1714        entry={sampleEntry({ email: "[email protected]" })}1715        entries={[1716          sampleEntry({ email: "[email protected]" }),1717          sampleEntry({ id: "entry-2", email: "[email protected]" }),1718          sampleEntry({ id: "entry-3", username: "duckuccino" }),1719        ]}1720        onDelete={vi.fn()}1721        onFieldSaved={vi.fn(async () => undefined)}1722      />1723    );17241725    const emailValue = Array.from(container.querySelectorAll(".peach-field-card")).find(1726      (card) => card.querySelector(".peach-label")?.textContent === "email"1727    )?.querySelector(".peach-inline-clickable") as HTMLSpanElement;1728    emailValue.click();1729    await flushView();17301731    const suggestions = Array.from(container.querySelectorAll(".peach-identity-suggestion-value"))1732      .map((element) => element.textContent);1733    expect(suggestions).toEqual(["[email protected]", "[email protected]"]);1734  });17351736  it("Entry lets TOTP secrets be edited inline", async () => {1737    sendMessageMock.mockResolvedValue({ ok: true });1738    const onFieldSaved = vi.fn(async () => undefined);1739    const container = mount(1740      <EntryView1741        entry={sampleEntry()}1742        onDelete={vi.fn()}1743        onFieldSaved={onFieldSaved}1744      />1745    );17461747    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;1748    totpMain.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));1749    await flushView();17501751    const totpInput = container.querySelector('input[placeholder="otpauth://... or base32 secret"]') as HTMLInputElement;1752    inputText(totpInput, "otpauth://totp/Example?secret=NB2W45DFOIZA====&issuer=Peach");1753    await flushView();17541755    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;1756    saveButton.click();1757    await flushView();17581759    expect(sendMessageMock).toHaveBeenCalledWith({1760      type: "UPDATE_ENTRY",1761      payload: {1762        id: "entry-1",1763        patch: { totp: "NB2W45DFOIZA====" },1764      },1765    });1766    expect(onFieldSaved).toHaveBeenCalled();1767  });17681769  it("Vault seeds and focuses search when a search seed is provided", async () => {1770    const container = mount(1771      <VaultView1772        entries={[sampleEntry(), sampleEntry({ id: "entry-2", title: "GitLab" })]}1773        sortOrder="url-first"1774        searchSeed="g"1775        searchSeedNonce={1}1776        onSelectEntry={vi.fn()}1777        onSortOrderChange={vi.fn()}1778        onAdd={vi.fn()}1779        onClose={vi.fn()}1780      />1781    );17821783    await flushView();17841785    const search = container.querySelector(".peach-list-top .peach-search-input") as HTMLInputElement;1786    expect(search.value).toBe("g");1787    expect(document.activeElement).toBe(search);1788  });17891790  it("Import existing-vault add mode parses a file and batches entries into the vault", async () => {1791    parseImportSourceMock.mockResolvedValue(1792      sampleImportResult({1793        entries: [1794          {1795            type: "login",1796            title: "Imported site",1797            username: "imported-user",1798            password: "imported-pass",1799            url: "https://imported.test",1800          },1801        ],1802      })1803    );1804    sendMessageMock.mockImplementation(async (msg: unknown) => {1805      const type = (msg as { type?: string }).type;1806      if (type === "GET_ENTRIES") {1807        return {1808          ok: true,1809          data: [1810            sampleEntry({1811              id: "existing-1",1812              title: "Imported site",1813              username: "imported-user",1814              url: "https://imported.test",1815            }),1816          ],1817        };1818      }1819      if (type === "BATCH_ADD_ENTRIES") {1820        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1821      }1822      return { ok: true };1823    });1824    const onImport = vi.fn(async () => undefined);1825    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1826    await flushView();1827    sendMessageMock.mockClear();18281829    await selectImportFile(container);1830    findButton(container, "Import 1").click();1831    await flushView();18321833    expect(parseImportSourceMock).toHaveBeenCalledWith('{"export":"test"}');1834    expect(sendMessageMock).toHaveBeenCalledWith({1835      type: "BATCH_ADD_ENTRIES",1836      payload: {1837        entries: [1838          expect.objectContaining({1839            title: "Imported site",1840            username: "imported-user",1841            password: "imported-pass",1842            url: "https://imported.test",1843          }),1844        ],1845      },1846    });1847    expect(onImport).toHaveBeenCalled();1848    expect(container.textContent).toContain("1 entry appears to be duplicates");1849  });18501851  it("Import replace mode requires confirmation before clearing and replacing the vault", async () => {1852    parseImportSourceMock.mockResolvedValue(sampleImportResult());1853    sendMessageMock.mockImplementation(async (msg: unknown) => {1854      const type = (msg as { type?: string }).type;1855      if (type === "GET_ENTRIES") {1856        return { ok: true, data: [sampleEntry({ id: "existing-1" })] };1857      }1858      if (type === "CLEAR_VAULT_ENTRIES") {1859        return { ok: true };1860      }1861      if (type === "BATCH_ADD_ENTRIES") {1862        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1863      }1864      return { ok: true };1865    });1866    const onImport = vi.fn(async () => undefined);1867    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1868    await flushView();1869    sendMessageMock.mockClear();18701871    await selectImportFile(container);1872    (container.querySelector('input[value="replace"]') as HTMLInputElement).click();1873    await flushView();18741875    findButton(container, "Replace vault with 1").click();1876    await flushView();18771878    expect(sendMessageMock).not.toHaveBeenCalledWith(1879      expect.objectContaining({ type: "CLEAR_VAULT_ENTRIES" })1880    );1881    expect(container.textContent).toContain("Replace forever? This cannot be undone.");18821883    findButton(container, "Yes, replace forever").click();1884    await flushView();18851886    expect(sendMessageMock).toHaveBeenCalledWith({ type: "CLEAR_VAULT_ENTRIES" });1887    expect(sendMessageMock).toHaveBeenCalledWith({1888      type: "BATCH_ADD_ENTRIES",1889      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1890    });1891    expect(onImport).toHaveBeenCalled();1892  });18931894  it.each([true, false])("Import onboarding mode creates only after matching passwords (replacement %s)", async (replacesExistingVault) => {1895    parseImportSourceMock.mockResolvedValue(sampleImportResult());1896    sendMessageMock.mockImplementation(async (msg: unknown) => {1897      const type = (msg as { type?: string }).type;1898      if (type === "CREATE_VAULT") return { ok: true };1899      if (type === "BATCH_ADD_ENTRIES") {1900        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1901      }1902      return { ok: true };1903    });1904    const onImport = vi.fn(async () => undefined);1905    const container = mount(1906      <ImportView1907        mode="onboarding"1908        replacesExistingVault={replacesExistingVault}1909        onBack={vi.fn()}1910        onImport={onImport}1911      />1912    );19131914    await selectImportFile(container);19151916    const createButton = findButton(container, "Create vault + import 1");1917    expect(createButton.disabled).toBe(true);1918    expect(container.textContent?.includes("Restoring now replaces the locked local vault")).toBe(replacesExistingVault);1919    expect(container.textContent).toContain("Use at least 8 characters");19201921    const masterInput = container.querySelector(1922      'input[placeholder="new master password"]'1923    ) as HTMLInputElement;1924    const confirmInput = container.querySelector(1925      'input[placeholder="confirm master password"]'1926    ) as HTMLInputElement;1927    const revealButton = container.querySelector(1928      'button[aria-label="Show passwords"]'1929    ) as HTMLButtonElement;1930    expect(revealButton).toBeTruthy();1931    revealButton.click();1932    await flushView();1933    expect(masterInput.type).toBe("text");1934    expect(confirmInput.type).toBe("text");19351936    inputText(masterInput, "fresh-master-password");1937    inputText(confirmInput, "fresh-master-password");1938    await flushView();19391940    expect(createButton.disabled).toBe(false);1941    createButton.click();1942    await flushView();19431944    expect(sendMessageMock).toHaveBeenCalledWith({1945      type: "CREATE_VAULT",1946      payload: { password: "fresh-master-password", ...(replacesExistingVault ? { replacement: "warned-import" } : {}) },1947    });1948    expect(sendMessageMock).toHaveBeenCalledWith({1949      type: "BATCH_ADD_ENTRIES",1950      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1951    });1952    expect(onImport).toHaveBeenCalled();1953  });19541955});