contracts.test.tsx

79.3 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 shows unavailable breach results after reconnect", async () => {1115    sendMessageMock.mockImplementation(async (raw) => {1116      const msg = raw as { type: string };1117      if (msg.type === "GET_BREACH_SCAN_STATUS") return { ok: true, data: { id: "scan", state: "complete", total: 2, scanned: 1, unknown: 1, unapplied: 0, breached: 0, cancelled: 0 } };1118      return { ok: true, data: null };1119    });1120    const container = mount(<SettingsView {...settingsProps()} />);1121    await flushView();1122    expect(container.textContent).toContain("1 unavailable");1123    expect(container.textContent).not.toContain("All passwords clean");1124  });11251126  it("Settings requires current, new, and confirm passwords before enabling save", async () => {1127    sendMessageMock.mockResolvedValue({ ok: true, data: null });1128    const container = mount(1129      <SettingsView1130        entriesCount={1}1131        breachMonitoring={true}1132        lockOnClose={true}1133        lockedSyncRequiresUnlock={false}1134        autoLockMinutes={5}1135        trashRetentionDays={30}1136        theme="dark"1137        accentColor="peach"1138        textSize="medium"1139        reduceMotion={false}1140        onBreachMonitoringChange={vi.fn()}1141        onLockedSyncRequiresUnlockChange={vi.fn()}1142        onLockOnCloseChange={vi.fn()}1143        onAutoLockMinutesChange={vi.fn()}1144        onTrashRetentionChange={vi.fn()}1145        onThemeChange={vi.fn()}1146        onAccentChange={vi.fn()}1147        onTextSizeChange={vi.fn()}1148        onReduceMotionChange={vi.fn()}1149        shortcuts={DEFAULT_BINDINGS}1150        onShortcutsChange={vi.fn()}1151        onBack={vi.fn()}1152        onImport={vi.fn()}1153        onExport={vi.fn()}1154        onBreachCheckDone={vi.fn()}1155      />1156    );1157    await flushView();11581159    expect(container.querySelectorAll(".stk-card").length).toBe(7);1160    // Settings now opens to card I (Peach Pro) — see koh save [f7a2710b3f67]1161    // "open settings to card I (Peach Pro) instead of card II (Protection)".1162    expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Peach Pro");11631164    const changeButton = Array.from(container.querySelectorAll("button")).find(1165      (candidate) => candidate.textContent?.trim() === "change"1166    ) as HTMLButtonElement;1167    changeButton.click();1168    await flushView();11691170    const saveButton = Array.from(container.querySelectorAll("button")).find(1171      (candidate) => candidate.textContent?.trim() === "save new password"1172    ) as HTMLButtonElement;1173    expect(saveButton.disabled).toBe(true);11741175    const inputs = container.querySelectorAll('input[type="password"]');1176    inputText(inputs[0] as HTMLInputElement, "current-pass");1177    inputText(inputs[1] as HTMLInputElement, "new-pass-12345");1178    await flushView();1179    expect(saveButton.disabled).toBe(true);11801181    inputText(inputs[2] as HTMLInputElement, "new-pass-12345");1182    await flushView();1183    expect(saveButton.disabled).toBe(false);1184  });11851186  it("Settings feedback highlights the selected category and hides the form after submit", async () => {1187    sendMessageMock.mockResolvedValue({ ok: true, data: null });1188    const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => ({1189      ok: true,1190      json: async () => ({ success: true }),1191    }));1192    vi.stubGlobal("fetch", fetchMock);11931194    const container = mount(1195      <SettingsView1196        entriesCount={1}1197        breachMonitoring={true}1198        lockOnClose={true}1199        lockedSyncRequiresUnlock={false}1200        autoLockMinutes={5}1201        trashRetentionDays={30}1202        theme="dark"1203        accentColor="peach"1204        textSize="medium"1205        reduceMotion={false}1206        initialSection="feedback"1207        onLockedSyncRequiresUnlockChange={vi.fn()}1208        onBreachMonitoringChange={vi.fn()}1209        onLockOnCloseChange={vi.fn()}1210        onAutoLockMinutesChange={vi.fn()}1211        onTrashRetentionChange={vi.fn()}1212        onThemeChange={vi.fn()}1213        onAccentChange={vi.fn()}1214        onTextSizeChange={vi.fn()}1215        onReduceMotionChange={vi.fn()}1216        shortcuts={DEFAULT_BINDINGS}1217        onShortcutsChange={vi.fn()}1218        onBack={vi.fn()}1219        onImport={vi.fn()}1220        onExport={vi.fn()}1221        onBreachCheckDone={vi.fn()}1222      />1223    );1224    await flushView();12251226    const feedbackCard = container.querySelector('[data-settings-card-id="feedback"]') as HTMLElement;1227    expect(feedbackCard.classList.contains("is-active")).toBe(true);12281229    const categoryButtons = Array.from(container.querySelectorAll(".peach-feedback-chip")) as HTMLButtonElement[];1230    const bugButton = categoryButtons.find((button) => button.textContent?.trim() === "Bug report")!;1231    const featureButton = categoryButtons.find((button) => button.textContent?.trim() === "Feature request")!;1232    expect(bugButton.getAttribute("aria-pressed")).toBe("true");1233    expect(featureButton.getAttribute("aria-pressed")).toBe("false");12341235    featureButton.click();1236    await flushView();12371238    expect(bugButton.getAttribute("aria-pressed")).toBe("false");1239    expect(featureButton.getAttribute("aria-pressed")).toBe("true");1240    expect(featureButton.classList.contains("is-active")).toBe(true);12411242    inputText(1243      container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,1244      '<script>alert("xss")</script> Please make this easier to see & safer.'1245    );1246    const sendButton = Array.from(container.querySelectorAll("button")).find(1247      (candidate) => candidate.textContent?.trim() === "Send"1248    ) as HTMLButtonElement;1249    sendButton.click();12501251    await vi.waitFor(() => {1252      expect(container.textContent).toContain("Thank you");1253    });12541255    const requestBody = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));1256    expect(requestBody.subject).toContain("Feature request");1257    expect(requestBody.message).toBe(1258      "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt; Please make this easier to see &amp; safer."1259    );1260    expect(requestBody.message).not.toContain("<script>");1261    expect(container.textContent).toContain("Someone will process it soon");1262    expect(container.querySelector(".peach-feedback-textarea")).toBeNull();1263    expect(container.querySelector(".peach-feedback-submit")).toBeNull();1264  });12651266  it("Settings keeps license activation on the full-screen celebration path", async () => {1267    const onLicenseChange = vi.fn(async () => undefined);1268    sendMessageMock.mockImplementation(async (msg: unknown) => {1269      const type = (msg as { type?: string }).type;1270      if (type === "GET_LICENSE") return { ok: true, data: { valid: false, plan: "free" } };1271      if (type === "ACTIVATE_LICENSE") {1272        return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };1273      }1274      if (type === "GET_ENTRIES") return { ok: true, data: [] };1275      return { ok: true, data: null };1276    });12771278    const container = mount(<SettingsView {...settingsProps({ isPro: false, onLicenseChange })} />);1279    await flushView();12801281    inputText(1282      container.querySelector(".peach-pro-key-inline-input") as HTMLInputElement,1283      "PEACH-TEST-KEY",1284    );1285    const apply = container.querySelector(".peach-pro-key-apply") as HTMLButtonElement;1286    apply.click();12871288    await vi.waitFor(() => expect(onLicenseChange).toHaveBeenCalledTimes(1));1289    expect(container.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(false);1290    expect(container.textContent).not.toContain("thank you ✦");1291  });12921293  it("Settings Pro star and peach clicks use the same in-card replay path", async () => {1294    sendMessageMock.mockImplementation(async (msg: unknown) => {1295      const type = (msg as { type?: string }).type;1296      if (type === "GET_LICENSE") return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };1297      if (type === "GET_LICENSE_KEY") return { ok: true, data: "PEACH-TEST-KEY" };1298      if (type === "GET_ENTRIES") return { ok: true, data: [] };1299      return { ok: true, data: null };1300    });13011302    const onLicenseChangeFromStar = vi.fn();1303    const starContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromStar })} />);1304    await flushView();1305    (starContainer.querySelector(".stk-card-icon--btn") as HTMLButtonElement).click();1306    expect(starContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);1307    expect(onLicenseChangeFromStar).not.toHaveBeenCalled();13081309    const onLicenseChangeFromPeach = vi.fn();1310    const peachContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromPeach })} />);1311    await flushView();1312    (peachContainer.querySelector(".peach-pro-active-mark-wrap") as HTMLButtonElement).click();1313    expect(peachContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);1314    expect(onLicenseChangeFromPeach).not.toHaveBeenCalled();1315  });13161317  it("Settings feedback sends even if Firefox reports no data-collection consent — a user-initiated send is its own consent", async () => {1318    sendMessageMock.mockResolvedValue({ ok: true, data: null });1319    const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => ({1320      ok: true,1321      json: async () => ({ success: true }),1322    }));1323    vi.stubGlobal("fetch", fetchMock);1324    // Firefox-style permissions API reporting the optional consent as absent.1325    // The old code gated send behind this and silently returned to idle, which1326    // read as a dead Send button. The gate is gone: Send must always send.1327    vi.stubGlobal("browser", {1328      permissions: {1329        getAll: vi.fn(async () => ({ data_collection: [] })),1330        request: vi.fn(async () => false),1331      },1332    });13331334    const container = mount(1335      <SettingsView1336        entriesCount={1}1337        breachMonitoring={true}1338        lockOnClose={true}1339        lockedSyncRequiresUnlock={false}1340        autoLockMinutes={5}1341        trashRetentionDays={30}1342        theme="dark"1343        accentColor="peach"1344        textSize="medium"1345        reduceMotion={false}1346        initialSection="feedback"1347        onLockedSyncRequiresUnlockChange={vi.fn()}1348        onBreachMonitoringChange={vi.fn()}1349        onLockOnCloseChange={vi.fn()}1350        onAutoLockMinutesChange={vi.fn()}1351        onTrashRetentionChange={vi.fn()}1352        onThemeChange={vi.fn()}1353        onAccentChange={vi.fn()}1354        onTextSizeChange={vi.fn()}1355        onReduceMotionChange={vi.fn()}1356        shortcuts={DEFAULT_BINDINGS}1357        onShortcutsChange={vi.fn()}1358        onBack={vi.fn()}1359        onImport={vi.fn()}1360        onExport={vi.fn()}1361        onBreachCheckDone={vi.fn()}1362      />1363    );1364    await flushView();13651366    inputText(1367      container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,1368      "Please improve the feedback flow."1369    );1370    const sendButton = Array.from(container.querySelectorAll("button")).find(1371      (candidate) => candidate.textContent?.trim() === "Send"1372    ) as HTMLButtonElement;1373    sendButton.click();13741375    await vi.waitFor(() => {1376      expect(fetchMock).toHaveBeenCalledTimes(1);1377    });1378    await vi.waitFor(() => {1379      expect(container.textContent).toContain("Thank you");1380    });1381    expect(container.querySelector(".peach-feedback-textarea")).toBeNull();1382  });13831384  it("Settings sends CHANGE_PASSWORD and forwards auto-lock/theme changes through callbacks", async () => {1385    sendMessageMock.mockImplementation(async (msg: unknown) => {1386      const m = msg as { type: string };1387      if (m.type === "GET_RECOVERY_WORDS") {1388        return {1389          ok: true,1390          data: [1391            "abandon", "ability", "able", "about", "above", "absent",1392            "absorb", "abstract", "absurd", "abuse", "access", "accident",1393          ],1394        };1395      }1396      return { ok: true, data: null };1397    });1398    const onAutoLockMinutesChange = vi.fn();1399    const onLockedSyncRequiresUnlockChange = vi.fn();1400    const onThemeChange = vi.fn();1401    const container = mount(1402      <SettingsView1403        entriesCount={1}1404        breachMonitoring={true}1405        lockOnClose={true}1406        lockedSyncRequiresUnlock={false}1407        autoLockMinutes={5}1408        trashRetentionDays={30}1409        theme="dark"1410        accentColor="peach"1411        textSize="medium"1412        reduceMotion={false}1413        onBreachMonitoringChange={vi.fn()}1414        onLockedSyncRequiresUnlockChange={onLockedSyncRequiresUnlockChange}1415        onLockOnCloseChange={vi.fn()}1416        onAutoLockMinutesChange={onAutoLockMinutesChange}1417        onTrashRetentionChange={vi.fn()}1418        onThemeChange={onThemeChange}1419        onAccentChange={vi.fn()}1420        onTextSizeChange={vi.fn()}1421        onReduceMotionChange={vi.fn()}1422        shortcuts={DEFAULT_BINDINGS}1423        onShortcutsChange={vi.fn()}1424        onBack={vi.fn()}1425        onImport={vi.fn()}1426        onExport={vi.fn()}1427        onBreachCheckDone={vi.fn()}1428      />1429    );1430    await flushView();1431    sendMessageMock.mockClear();14321433    // ── Auto-lock + theme changes (before password change) ─────────────1434    const selects = container.querySelectorAll("select");1435    changeSelect(selects[0] as HTMLSelectElement, "15");1436    expect(onAutoLockMinutesChange).toHaveBeenCalledWith(15);14371438    const appearanceCard = container.querySelector('[data-settings-card-id="appearance"]') as HTMLElement;1439    appearanceCard.click();1440    await flushView();1441    expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Appearance");1442    const themeButton = Array.from(container.querySelectorAll("button")).find(1443      (candidate) => candidate.textContent?.trim() === "Switch to light"1444    ) as HTMLButtonElement;1445    themeButton.click();1446    expect(onThemeChange).toHaveBeenCalledWith("light");14471448    // ── Locked Sync custody toggle ──────────────────────────────────────1449    const protectionCard = container.querySelector('[data-settings-card-id="protection"]') as HTMLElement;1450    protectionCard.click();1451    await flushView();1452    const custodyToggle = container.querySelector<HTMLButtonElement>(1453      'button[aria-label="Toggle unlock requirement for locked Sync after restart"]',1454    );1455    expect(custodyToggle).not.toBeNull();1456    custodyToggle!.click();1457    expect(onLockedSyncRequiresUnlockChange).toHaveBeenCalledWith(true);14581459    const changeButton = Array.from(container.querySelectorAll("button")).find(1460      (candidate) => candidate.textContent?.trim() === "change"1461    ) as HTMLButtonElement;1462    changeButton.click();1463    await flushView();14641465    const inputs = container.querySelectorAll('input[type="password"]');1466    inputText(inputs[0] as HTMLInputElement, "current-pass");1467    inputText(inputs[1] as HTMLInputElement, "new-password-123");1468    inputText(inputs[2] as HTMLInputElement, "new-password-123");1469    await flushView();14701471    const saveButton = Array.from(container.querySelectorAll("button")).find(1472      (candidate) => candidate.textContent?.trim() === "save new password"1473    ) as HTMLButtonElement;1474    saveButton.click();1475    await flushView();14761477    expect(sendMessageMock).toHaveBeenCalledWith({1478      type: "CHANGE_PASSWORD",1479      payload: {1480        currentPassword: "current-pass",1481        newPassword: "new-password-123",1482      },1483    });14841485    expect(sendMessageMock).not.toHaveBeenCalledWith({ type: "SET_RECOVERY_CONFIRM_PENDING" });1486    // After a successful password change the recovery word display replaces settings.1487    expect(container.textContent).toContain("save your recovery words");1488    expect(sendMessageMock).toHaveBeenCalledWith({ type: "GET_RECOVERY_WORDS" });1489  });14901491  it("shows rejected canary saves and only refreshes after success", async () => {1492    sendMessageMock.mockResolvedValue({ ok: false, error: "invalid_webhook_url" });1493    const onSaved = vi.fn(async () => undefined);1494    const container = mount(<EntryView entry={sampleEntry()} onDelete={vi.fn()} onFieldSaved={onSaved} />);1495    const advanced = Array.from(container.querySelectorAll("button")).find(button => button.textContent?.includes("Advanced"))!;1496    advanced.click(); await flushView();1497    const webhook = container.querySelector('input[placeholder="https://hooks.zapier.com/..."]') as HTMLInputElement;1498    inputText(webhook, "https://100.64.1.2/hook");1499    webhook.dispatchEvent(new FocusEvent("blur", { bubbles: true })); await flushView();1500    expect(container.textContent).toContain("Use a public HTTPS webhook URL without a username or password.");1501    expect(onSaved).not.toHaveBeenCalled();1502    sendMessageMock.mockResolvedValue({ ok: true });1503    inputText(webhook, "https://example.com/updated");1504    webhook.dispatchEvent(new FocusEvent("blur", { bubbles: true })); await flushView();1505    expect(onSaved).toHaveBeenCalledTimes(1);1506    expect(container.querySelector('[role="alert"]')).toBeNull();1507    expect(sendMessageMock).toHaveBeenLastCalledWith({ type: "UPDATE_ENTRY", payload: { id: "entry-1", patch: { canary: { webhookUrl: "https://example.com/updated", label: undefined } } } });1508  });15091510  it("Entry copy actions send COPY and canary ping messages for password and username", async () => {1511    sendMessageMock.mockResolvedValue({ ok: true });1512    const container = mount(1513      <EntryView1514        entry={sampleEntry()}1515        onDelete={vi.fn()}1516        onFieldSaved={vi.fn(async () => undefined)}1517      />1518    );15191520    const passwordButton = container.querySelector('button[aria-label="Copy password"]') as HTMLButtonElement;1521    passwordButton.click();1522    await flushView();15231524    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1525      type: "COPY",1526      payload: { text: "secret123", label: "password", alreadyWritten: false },1527    });1528    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {1529      type: "FIRE_CANARY_PING",1530      payload: {1531        id: "entry-1",1532        trigger: "password_copied",1533      },1534    });15351536    sendMessageMock.mockClear();1537    const usernameButton = container.querySelector('button[aria-label="Copy username"]') as HTMLButtonElement;1538    usernameButton.click();1539    await flushView();15401541    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1542      type: "COPY",1543      payload: { text: "june", label: "username", alreadyWritten: false },1544    });1545    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {1546      type: "FIRE_CANARY_PING",1547      payload: {1548        id: "entry-1",1549        trigger: "username_copied",1550      },1551    });1552  });15531554  it("Entry keyboard password copy reports its canary after COPY", async () => {1555    sendMessageMock.mockResolvedValue({ ok: true });1556    mount(1557      <EntryView1558        entry={sampleEntry()}1559        onDelete={vi.fn()}1560        onFieldSaved={vi.fn(async () => undefined)}1561      />1562    );15631564    window.dispatchEvent(new KeyboardEvent("keydown", { key: "c", bubbles: true }));1565    await flushView();15661567    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1568      type: "COPY",1569      payload: { text: "secret123", label: "password", alreadyWritten: false },1570    });1571    await flushView();1572    expect(sendMessageMock.mock.calls).toContainEqual([{1573      type: "FIRE_CANARY_PING",1574      payload: {1575        id: "entry-1",1576        trigger: "password_copied",1577      },1578    }]);1579  });1580  it("Entry Cmd+C leaves the native clipboard shortcut untouched", async () => {1581    sendMessageMock.mockResolvedValue({ ok: true });1582    mount(1583      <EntryView1584        entry={sampleEntry()}1585        onDelete={vi.fn()}1586        onFieldSaved={vi.fn(async () => undefined)}1587      />1588    );15891590    window.dispatchEvent(new KeyboardEvent("keydown", { key: "c", metaKey: true, bubbles: true }));1591    await flushView();15921593    expect(sendMessageMock).not.toHaveBeenCalledWith(expect.objectContaining({ type: "COPY" }));1594  });15951596  it("Vault password swipe copy reports its canary after COPY", async () => {1597    sendMessageMock.mockResolvedValue({ ok: true });1598    const container = mount(1599      <VaultView1600        entries={[sampleEntry()]}1601        sortOrder="url-first"1602        onSelectEntry={vi.fn()}1603        onSortOrderChange={vi.fn()}1604        onAdd={vi.fn()}1605        onClose={vi.fn()}1606      />1607    );1608    const row = container.querySelector(".peach-entry-row") as HTMLButtonElement;1609    row.dispatchEvent(new TouchEvent("touchstart", {1610      bubbles: true,1611      touches: [{ clientX: 0, clientY: 0 } as Touch],1612    }));1613    row.dispatchEvent(new TouchEvent("touchend", {1614      bubbles: true,1615      changedTouches: [{ clientX: 100, clientY: 0 } as Touch],1616    }));1617    await flushView();16181619    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1620      type: "COPY",1621      payload: { text: "secret123", label: "password", alreadyWritten: false },1622    });1623    await flushView();1624    expect(sendMessageMock.mock.calls).toContainEqual([{1625      type: "FIRE_CANARY_PING",1626      payload: {1627        id: "entry-1",1628        trigger: "password_copied",1629      },1630    }]);1631  });16321633  it("Vault context-menu copies report only the stored entry ID", async () => {1634    sendMessageMock.mockResolvedValue({ ok: true });1635    const container = mount(<VaultView entries={[sampleEntry()]} sortOrder="url-first" onSelectEntry={vi.fn()} onSortOrderChange={vi.fn()} onAdd={vi.fn()} onClose={vi.fn()} />);1636    for (const label of ["Copy username", "Copy password"]) {1637      const row = container.querySelector(".peach-entry-row") as HTMLButtonElement;1638      row.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }));1639      await flushView();1640      const action = Array.from(container.querySelectorAll<HTMLButtonElement>('button[role="menuitem"]')).find(button => button.textContent?.trim() === label)!;1641      action.click(); await flushView();1642      expect(sendMessageMock.mock.calls).toContainEqual([{ type: "FIRE_CANARY_PING", payload: { id: "entry-1", trigger: label === "Copy password" ? "password_copied" : "username_copied" } }]);1643      sendMessageMock.mockClear();1644    }1645  });16461647  it("Entry shows Advanced for passkey-bearing credential entries", async () => {1648    const container = mount(1649      <EntryView1650        entry={sampleEntry({1651          type: "passkey",1652          username: undefined,1653          password: undefined,1654          totp: undefined,1655          canary: undefined,1656          passkey: {1657            rpId: "vercel.com",1658            rpName: "Vercel",1659            credentialId: "cred-1",1660            publicKeyCose: "cose",1661            userHandle: "handle",1662            userName: "june",1663            userDisplayName: "June",1664            algorithm: -7,1665            signCount: 0,1666            aaguid: "",1667            backupEligible: false,1668            backupState: false,1669            createdAt: 1,1670          },1671        })}1672        onDelete={vi.fn()}1673        onFieldSaved={vi.fn(async () => undefined)}1674      />1675    );16761677    const advanced = Array.from(container.querySelectorAll(".peach-entry-add-link")).find(1678      (button) => button.textContent?.includes("Advanced")1679    ) as HTMLButtonElement | undefined;1680    expect(advanced).toBeDefined();1681    expect(advanced?.textContent).toContain("+ Advanced");16821683    advanced!.click();1684    await flushView();16851686    expect(container.textContent).toContain("passkey · vercel.com");1687  });16881689  it("Entry refuses to send an empty password update and copies TOTP through COPY", async () => {1690    sendMessageMock.mockResolvedValue({ ok: true });1691    const onFieldSaved = vi.fn(async () => undefined);1692    const container = mount(1693      <EntryView1694        entry={sampleEntry()}1695        onDelete={vi.fn()}1696        onFieldSaved={onFieldSaved}1697      />1698    );16991700    const passwordValue = container.querySelector(".peach-password-value") as HTMLSpanElement;1701    passwordValue.click();1702    await flushView();17031704    const passwordInput = container.querySelector('input[placeholder="paste or type a password"]') as HTMLInputElement;1705    inputText(passwordInput, "");1706    await flushView();17071708    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;1709    saveButton.click();1710    await flushView();17111712    expect(sendMessageMock).not.toHaveBeenCalledWith(1713      expect.objectContaining({ type: "UPDATE_ENTRY" })1714    );1715    expect(onFieldSaved).not.toHaveBeenCalled();17161717    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;1718    totpMain.click();17191720    await vi.waitFor(() => {1721      expect(sendMessageMock).toHaveBeenLastCalledWith({1722        type: "COPY",1723        payload: { text: "123456", label: "totp", alreadyWritten: false },1724      });1725    }, { timeout: 500 });1726  });17271728  it("Entry closes an unchanged inline editor when focus leaves it", async () => {1729    sendMessageMock.mockResolvedValue({ ok: true });1730    const container = mount(1731      <EntryView1732        entry={sampleEntry()}1733        onDelete={vi.fn()}1734        onFieldSaved={vi.fn(async () => undefined)}1735      />1736    );17371738    const usernameValue = container.querySelector(".peach-field-value.peach-inline-clickable") as HTMLSpanElement;1739    usernameValue.click();1740    await flushView();17411742    const usernameInput = container.querySelector(".peach-inline-input[autocomplete=\"off\"]") as HTMLInputElement;1743    usernameInput.blur();1744    await flushView();17451746    expect(container.querySelector(".peach-inline-input[autocomplete=\"off\"]")).toBeNull();1747    expect(sendMessageMock).not.toHaveBeenCalledWith(1748      expect.objectContaining({ type: "UPDATE_ENTRY" })1749    );1750  });17511752  it("Entry keeps the full used-email list available while editing an email", async () => {1753    const container = mount(1754      <EntryView1755        entry={sampleEntry({ email: "[email protected]" })}1756        entries={[1757          sampleEntry({ email: "[email protected]" }),1758          sampleEntry({ id: "entry-2", email: "[email protected]" }),1759          sampleEntry({ id: "entry-3", username: "duckuccino" }),1760        ]}1761        onDelete={vi.fn()}1762        onFieldSaved={vi.fn(async () => undefined)}1763      />1764    );17651766    const emailValue = Array.from(container.querySelectorAll(".peach-field-card")).find(1767      (card) => card.querySelector(".peach-label")?.textContent === "email"1768    )?.querySelector(".peach-inline-clickable") as HTMLSpanElement;1769    emailValue.click();1770    await flushView();17711772    const suggestions = Array.from(container.querySelectorAll(".peach-identity-suggestion-value"))1773      .map((element) => element.textContent);1774    expect(suggestions).toEqual(["[email protected]", "[email protected]"]);1775  });17761777  it("Entry lets TOTP secrets be edited inline", async () => {1778    sendMessageMock.mockResolvedValue({ ok: true });1779    const onFieldSaved = vi.fn(async () => undefined);1780    const container = mount(1781      <EntryView1782        entry={sampleEntry()}1783        onDelete={vi.fn()}1784        onFieldSaved={onFieldSaved}1785      />1786    );17871788    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;1789    totpMain.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));1790    await flushView();17911792    const totpInput = container.querySelector('input[placeholder="otpauth://... or base32 secret"]') as HTMLInputElement;1793    inputText(totpInput, "otpauth://totp/Example?secret=NB2W45DFOIZA====&issuer=Peach");1794    await flushView();17951796    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;1797    saveButton.click();1798    await flushView();17991800    expect(sendMessageMock).toHaveBeenCalledWith({1801      type: "UPDATE_ENTRY",1802      payload: {1803        id: "entry-1",1804        patch: { totp: "NB2W45DFOIZA====" },1805      },1806    });1807    expect(onFieldSaved).toHaveBeenCalled();1808  });18091810  it("Vault seeds and focuses search when a search seed is provided", async () => {1811    const container = mount(1812      <VaultView1813        entries={[sampleEntry(), sampleEntry({ id: "entry-2", title: "GitLab" })]}1814        sortOrder="url-first"1815        searchSeed="g"1816        searchSeedNonce={1}1817        onSelectEntry={vi.fn()}1818        onSortOrderChange={vi.fn()}1819        onAdd={vi.fn()}1820        onClose={vi.fn()}1821      />1822    );18231824    await flushView();18251826    const search = container.querySelector(".peach-list-top .peach-search-input") as HTMLInputElement;1827    expect(search.value).toBe("g");1828    expect(document.activeElement).toBe(search);1829  });18301831  it("Import existing-vault add mode parses a file and batches entries into the vault", async () => {1832    parseImportSourceMock.mockResolvedValue(1833      sampleImportResult({1834        entries: [1835          {1836            type: "login",1837            title: "Imported site",1838            username: "imported-user",1839            password: "imported-pass",1840            url: "https://imported.test",1841          },1842        ],1843      })1844    );1845    sendMessageMock.mockImplementation(async (msg: unknown) => {1846      const type = (msg as { type?: string }).type;1847      if (type === "GET_ENTRIES") {1848        return {1849          ok: true,1850          data: [1851            sampleEntry({1852              id: "existing-1",1853              title: "Imported site",1854              username: "imported-user",1855              url: "https://imported.test",1856            }),1857          ],1858        };1859      }1860      if (type === "BATCH_ADD_ENTRIES") {1861        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1862      }1863      return { ok: true };1864    });1865    const onImport = vi.fn(async () => undefined);1866    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1867    await flushView();1868    sendMessageMock.mockClear();18691870    await selectImportFile(container);1871    findButton(container, "Import 1").click();1872    await flushView();18731874    expect(parseImportSourceMock).toHaveBeenCalledWith('{"export":"test"}');1875    expect(sendMessageMock).toHaveBeenCalledWith({1876      type: "BATCH_ADD_ENTRIES",1877      payload: {1878        entries: [1879          expect.objectContaining({1880            title: "Imported site",1881            username: "imported-user",1882            password: "imported-pass",1883            url: "https://imported.test",1884          }),1885        ],1886      },1887    });1888    expect(onImport).toHaveBeenCalled();1889    expect(container.textContent).toContain("1 entry appears to be duplicates");1890  });18911892  it("Import replace mode requires confirmation before clearing and replacing the vault", async () => {1893    parseImportSourceMock.mockResolvedValue(sampleImportResult());1894    sendMessageMock.mockImplementation(async (msg: unknown) => {1895      const type = (msg as { type?: string }).type;1896      if (type === "GET_ENTRIES") {1897        return { ok: true, data: [sampleEntry({ id: "existing-1" })] };1898      }1899      if (type === "CLEAR_VAULT_ENTRIES") {1900        return { ok: true };1901      }1902      if (type === "BATCH_ADD_ENTRIES") {1903        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1904      }1905      return { ok: true };1906    });1907    const onImport = vi.fn(async () => undefined);1908    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1909    await flushView();1910    sendMessageMock.mockClear();19111912    await selectImportFile(container);1913    (container.querySelector('input[value="replace"]') as HTMLInputElement).click();1914    await flushView();19151916    findButton(container, "Replace vault with 1").click();1917    await flushView();19181919    expect(sendMessageMock).not.toHaveBeenCalledWith(1920      expect.objectContaining({ type: "CLEAR_VAULT_ENTRIES" })1921    );1922    expect(container.textContent).toContain("Replace forever? This cannot be undone.");19231924    findButton(container, "Yes, replace forever").click();1925    await flushView();19261927    expect(sendMessageMock).toHaveBeenCalledWith({ type: "CLEAR_VAULT_ENTRIES" });1928    expect(sendMessageMock).toHaveBeenCalledWith({1929      type: "BATCH_ADD_ENTRIES",1930      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1931    });1932    expect(onImport).toHaveBeenCalled();1933  });19341935  it.each([true, false])("Import onboarding mode creates only after matching passwords (replacement %s)", async (replacesExistingVault) => {1936    parseImportSourceMock.mockResolvedValue(sampleImportResult());1937    sendMessageMock.mockImplementation(async (msg: unknown) => {1938      const type = (msg as { type?: string }).type;1939      if (type === "CREATE_VAULT") return { ok: true };1940      if (type === "BATCH_ADD_ENTRIES") {1941        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1942      }1943      return { ok: true };1944    });1945    const onImport = vi.fn(async () => undefined);1946    const container = mount(1947      <ImportView1948        mode="onboarding"1949        replacesExistingVault={replacesExistingVault}1950        onBack={vi.fn()}1951        onImport={onImport}1952      />1953    );19541955    await selectImportFile(container);19561957    const createButton = findButton(container, "Create vault + import 1");1958    expect(createButton.disabled).toBe(true);1959    expect(container.textContent?.includes("Restoring now replaces the locked local vault")).toBe(replacesExistingVault);1960    expect(container.textContent).toContain("Use at least 8 characters");19611962    const masterInput = container.querySelector(1963      'input[placeholder="new master password"]'1964    ) as HTMLInputElement;1965    const confirmInput = container.querySelector(1966      'input[placeholder="confirm master password"]'1967    ) as HTMLInputElement;1968    const revealButton = container.querySelector(1969      'button[aria-label="Show passwords"]'1970    ) as HTMLButtonElement;1971    expect(revealButton).toBeTruthy();1972    revealButton.click();1973    await flushView();1974    expect(masterInput.type).toBe("text");1975    expect(confirmInput.type).toBe("text");19761977    inputText(masterInput, "fresh-master-password");1978    inputText(confirmInput, "fresh-master-password");1979    await flushView();19801981    expect(createButton.disabled).toBe(false);1982    createButton.click();1983    await flushView();19841985    expect(sendMessageMock).toHaveBeenCalledWith({1986      type: "CREATE_VAULT",1987      payload: { password: "fresh-master-password", ...(replacesExistingVault ? { replacement: "warned-import" } : {}) },1988    });1989    expect(sendMessageMock).toHaveBeenCalledWith({1990      type: "BATCH_ADD_ENTRIES",1991      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1992    });1993    expect(onImport).toHaveBeenCalled();1994  });19951996});