contracts.test.tsx

69.8 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 { LockView } from "./Lock";10import { ExportView } from "./Export";11import { SettingsView } from "./Settings";12import { DEFAULT_BINDINGS } from "../../shared/shortcuts";13import { EntryView } from "./Entry";14import { ImportView } from "./Import";15import { AddView } from "./Add";16import { NotesEditor } from "./NotesEditor";17import { RecoveryWordEntryView } from "./RecoveryWordEntry";18import { RecoveryWordDisplayView } from "./RecoveryWordDisplay";19import { VaultView } from "./Vault";20import { changeSelect, flushView, inputText, pressEnter, renderView } from "./view-test-utils";2122const sendMessageMock = vi.fn<(msg: unknown) => Promise<unknown>>();23const triggerRingMock = vi.fn();24const triggerPipPulseMock = vi.fn();25const parseImportSourceMock = vi.fn<(raw: string, password?: string) => Promise<ImportParseResult>>();26const zxcvbnMock = vi.fn((value: string) => ({ score: value.length >= 16 ? 3 : 1 }));2728vi.mock("../App", () => ({29  sendMessage: (msg: unknown) => sendMessageMock(msg),30  triggerRing: () => triggerRingMock(),31  triggerPipPulse: () => triggerPipPulseMock(),32}));3334vi.mock("../../shared/bridge", () => ({35  sendMessage: (msg: unknown) => sendMessageMock(msg),36}));3738vi.mock("../../shared/import", () => ({39  parseImportSource: (...args: [string, string | undefined]) => parseImportSourceMock(...args),40}));4142vi.mock("../../shared/favicon", async (importOriginal) => {43  const actual = await importOriginal<typeof import("../../shared/favicon")>();44  return { ...actual, faviconUrl: () => null };45});4647vi.mock("../../crypto/totp", () => ({48  generateTOTP: () => ({ code: "123 456", remaining: 24 }),49  parseOtpauthURI: (value: string) =>50    value.startsWith("otpauth://")51      ? { secret: "NB2W45DFOIZA====", algorithm: "SHA1" as const }52      : null,53}));5455vi.mock("../components/GeneratorDrawer", () => ({56  GeneratorDrawer: () => null,57}));5859vi.mock("../components/RuneCanvas", () => ({ RuneCanvas: () => null }));6061vi.mock("../components/RuneBackground", () => ({62  RuneBackground: () => null,63}));6465vi.mock("@zxcvbn-ts/core", () => ({66  zxcvbn: (value: string) => zxcvbnMock(value),67  zxcvbnOptions: { setOptions: vi.fn() },68}));69vi.mock("@zxcvbn-ts/language-common", () => ({70  adjacencyGraphs: {},71  dictionary: {},72}));73vi.mock("@zxcvbn-ts/language-en", () => ({74  translations: {},75  dictionary: {},76}));7778describe("popup contract tests", () => {79  const disposers: Array<() => void> = [];8081  beforeEach(() => {82    document.body.innerHTML = "";83    sendMessageMock.mockReset();84    triggerRingMock.mockReset();85    triggerPipPulseMock.mockReset();86    parseImportSourceMock.mockReset();87    zxcvbnMock.mockReset();88    zxcvbnMock.mockImplementation((value: string) => ({ score: value.length >= 16 ? 3 : 1 }));89    parseImportSourceMock.mockResolvedValue({90      format: "unknown",91      label: "Unknown format",92      entries: [],93      totalItems: 0,94      skippedItems: 0,95    });9697    vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {98      return window.setTimeout(() => cb(0), 0) as unknown as number;99    });100    vi.stubGlobal("cancelAnimationFrame", (id: number) => window.clearTimeout(id));101    vi.stubGlobal("URL", {102      createObjectURL: vi.fn(() => "blob:peach-test"),103      revokeObjectURL: vi.fn(),104    });105    vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});106107    (globalThis as { chrome?: typeof chrome }).chrome = {108      runtime: {109        getManifest: () => ({ version: "1.4.47" }),110        onMessage: { addListener: vi.fn() },111      },112    } as unknown as typeof chrome;113  });114115  afterEach(() => {116    while (disposers.length > 0) {117      disposers.pop()?.();118    }119    vi.restoreAllMocks();120    vi.unstubAllGlobals();121  });122123  function mount(view: JSX.Element | (() => JSX.Element)) {124    const mounted = renderView(view);125    disposers.push(mounted.dispose);126    return mounted.container;127  }128129  function sampleEntry(overrides: Partial<VaultEntry> = {}): VaultEntry {130    return {131      id: "entry-1",132      type: "login",133      title: "GitHub",134      username: "june",135      password: "secret123",136      url: "https://github.com",137      totp: "JBSWY3DPEHPK3PXP",138      canary: {139        webhookUrl: "https://example.com/hook",140      },141      createdAt: 1,142      modifiedAt: 1,143      ...overrides,144    };145  }146147  function sampleImportResult(148    overrides: Partial<ImportParseResult> = {}149  ): ImportParseResult {150    return {151      format: "csv",152      label: "CSV import",153      entries: [154        {155          type: "login",156          title: "Imported site",157          username: "imported-user",158          password: "imported-pass",159          url: "https://imported.test",160        },161      ],162      totalItems: 1,163      skippedItems: 0,164      ...overrides,165    };166  }167168  function settingsProps(overrides: Partial<Parameters<typeof SettingsView>[0]> = {}) {169    return {170      entriesCount: 1,171      breachMonitoring: true,172      lockOnClose: true,173      autoLockMinutes: 5,174      lockedSyncRequiresUnlock: false,175      trashRetentionDays: 30,176      theme: "dark" as const,177      accentColor: "peach" as const,178      textSize: "medium" as const,179      reduceMotion: false,180      onBreachMonitoringChange: vi.fn(),181      onLockOnCloseChange: vi.fn(),182      onAutoLockMinutesChange: vi.fn(),183      onTrashRetentionChange: vi.fn(),184      onLockedSyncRequiresUnlockChange: vi.fn(),185      onThemeChange: vi.fn(),186      onAccentChange: vi.fn(),187      onTextSizeChange: vi.fn(),188      onReduceMotionChange: vi.fn(),189      shortcuts: DEFAULT_BINDINGS,190      onShortcutsChange: vi.fn(),191      onBack: vi.fn(),192      onImport: vi.fn(),193      onExport: vi.fn(),194      onBreachCheckDone: vi.fn(),195      ...overrides,196    };197  }198199  async function selectImportFile(200    container: HTMLElement,201    contents = '{"export":"test"}'202  ) {203    // The Import view now opens onto a menu — click into the file subview204    // before locating the file input. Idempotent: a second click won't re-fire205    // because the menu unmounts once the subview renders.206    const fileCard = findButton(container, "Choose file →");207    if (fileCard) {208      fileCard.click();209      await flushView();210    }211    const input = container.querySelector('input[type="file"]') as HTMLInputElement;212    const file = new File([contents], "import.json", { type: "application/json" });213    Object.defineProperty(input, "files", {214      configurable: true,215      value: [file],216    });217    input.dispatchEvent(new Event("change", { bubbles: true }));218    await flushView();219    await flushView();220  }221222  function findButton(container: HTMLElement, text: string): HTMLButtonElement {223    return Array.from(container.querySelectorAll("button")).find(224      (candidate) => candidate.textContent?.trim() === text225    ) as HTMLButtonElement;226  }227228  it("Lock sends UNLOCK with the entered passphrase", async () => {229    sendMessageMock.mockResolvedValue({ ok: true });230    const onUnlock = vi.fn(async () => undefined);231    const container = mount(<LockView hasVault={true} ready={true} onUnlock={onUnlock} />);232233    const password = container.querySelector("#unlock-password") as HTMLInputElement;234    inputText(password, "correct horse battery staple");235    (container.querySelector(".peach-lock-submit") as HTMLButtonElement).click();236    await flushView();237238    expect(sendMessageMock).toHaveBeenCalledWith({239      type: "UNLOCK",240      payload: { password: "correct horse battery staple" },241    });242    expect(onUnlock).toHaveBeenCalled();243  });244245  it("Lock uses a configured preferred PIN and keeps the password fallback available", async () => {246    sendMessageMock.mockImplementation(async (msg: unknown) => {247      const type = (msg as { type: string }).type;248      if (type === "GET_PIN_STATUS") {249        return { ok: true, data: { configured: true, available: true, attemptsRemaining: 3 } };250      }251      return type === "GET_SETTINGS"252        ? { ok: true, data: { pinEnabled: true, pinPreferred: true } }253        : { ok: true };254    });255    const onUnlock = vi.fn(async () => undefined);256    const container = mount(<LockView hasVault={true} ready={true} onUnlock={onUnlock} />);257    await flushView();258259    inputText(container.querySelector("#unlock-pin") as HTMLInputElement, "1234");260    (container.querySelector(".peach-lock-submit") as HTMLButtonElement).click();261    await flushView();262263    expect(sendMessageMock).toHaveBeenCalledWith({264      type: "UNLOCK_WITH_PIN",265      payload: { pin: "1234" },266    });267    expect(onUnlock).toHaveBeenCalled();268    expect(container.textContent).toContain("use master password");269  });270271  it("places the PIN method switch below the unlock button", async () => {272    sendMessageMock.mockImplementation(async (msg: unknown) => {273      const type = (msg as { type: string }).type;274      if (type === "GET_PIN_STATUS") {275        return { ok: true, data: { configured: true, available: true, attemptsRemaining: 3 } };276      }277      return type === "GET_SETTINGS"278        ? { ok: true, data: { pinEnabled: true, pinPreferred: false } }279        : { ok: true };280    });281    const container = mount(<LockView hasVault={true} ready={true} onUnlock={vi.fn()} />);282    await flushView();283284    const buttons = Array.from(container.querySelectorAll("button"));285    const unlockIndex = buttons.findIndex((button) => button.textContent?.trim() === "unlock");286    const pinIndex = buttons.findIndex((button) => button.textContent?.trim() === "use PIN");287    expect(pinIndex).toBeGreaterThan(unlockIndex);288  });289290  it("keeps standalone note creation in Notes mode", async () => {291    const chromeApi = globalThis.chrome as unknown as {292      tabs?: { query: (queryInfo: object, callback: (tabs: unknown[]) => void) => void };293    };294    chromeApi.tabs = { query: vi.fn((_queryInfo, callback) => callback([])) };295296    const addContainer = mount(<AddView onBack={vi.fn()} onSave={vi.fn()} />);297    await flushView();298299    expect(Array.from(addContainer.querySelectorAll(".peach-new-type-btn")).map((button) => button.textContent?.trim()))300      .toEqual(["login", "card"]);301    expect(addContainer.querySelector(".peach-note-editor-body--inline")).toBeNull();302  });303304  it("gives Notes mode the full note-formatting toolbar", async () => {305    const container = mount(306      <NotesEditor307        note={null}308        onBack={vi.fn()}309        onSaved={vi.fn()}310        onDelete={vi.fn()}311      />312    );313    await flushView();314315    expect(container.querySelector('[title="Strikethrough"]')).toBeTruthy();316    expect(container.querySelector('[title="Divider"]')).toBeTruthy();317    expect(container.querySelector('[title="Quote"]')).toBeTruthy();318    expect(container.querySelectorAll(".peach-note-toolbar-desktop-inline button")).toHaveLength(9);319    expect(container.querySelectorAll(".peach-note-toolbar-desktop-inline button svg")).toHaveLength(9);320    expect(container.querySelector(".peach-notes-header-title")?.textContent).toBe("notes.");321  });322323  it("saves formatting applied by the Notes toolbar before leaving", async () => {324    const savedNote = {325      id: "note-1",326      type: "note" as const,327      title: "Untitled",328      notes: "<b>formatted</b>",329      createdAt: 1,330      modifiedAt: 2,331    };332    sendMessageMock.mockResolvedValue({ ok: true, data: savedNote });333    const originalExecCommand = document.execCommand;334    const execCommandMock = vi.fn(() => {335      const body = document.querySelector<HTMLDivElement>(".peach-note-body-field");336      if (body) body.innerHTML = "<b>formatted</b>";337      return true;338    });339    Object.defineProperty(document, "execCommand", { configurable: true, value: execCommandMock });340341    try {342      const container = mount(343        <NotesEditor344          note={null}345          onBack={vi.fn()}346          onSaved={vi.fn()}347          onDelete={vi.fn()}348        />349      );350      await flushView();351      container.querySelector<HTMLButtonElement>('[title="Bold"]')?.dispatchEvent(352        new MouseEvent("mousedown", { bubbles: true, cancelable: true })353      );354      expect(execCommandMock).toHaveBeenCalledWith("bold", false, undefined);355      container.querySelector<HTMLButtonElement>('[aria-label="Back to notes list"]')?.click();356      await flushView();357358      expect(sendMessageMock).toHaveBeenCalledWith({359        type: "SAVE_NOTE",360        payload: { id: undefined, title: "Untitled", body: "<b>formatted</b>" },361      });362    } finally {363      Object.defineProperty(document, "execCommand", { configurable: true, value: originalExecCommand });364    }365  });366367  it("Lock keeps create-vault disabled for short passwords and weak passphrases", async () => {368    const container = mount(<LockView hasVault={false} ready={true} onUnlock={vi.fn()} />);369    const createButton = container.querySelector(".peach-lock-submit") as HTMLButtonElement;370    const password = container.querySelector("#master-password") as HTMLInputElement;371    const confirm = container.querySelector("#confirm-password") as HTMLInputElement;372373    inputText(password, "short");374    inputText(confirm, "short");375    await flushView();376    expect(createButton.disabled).toBe(true);377378    zxcvbnMock.mockImplementation(() => ({ score: 1 }));379    inputText(password, "weakweakweak");380    inputText(confirm, "weakweakweak");381    await flushView();382    expect(createButton.disabled).toBe(true);383  });384385  it("Lock create-vault header pins the wordmark left with back on the right", async () => {386    const container = mount(387      <LockView388        hasVault={false}389        ready={true}390        onUnlock={vi.fn()}391        onBackToOnboarding={() => {}}392      />393    );394    const header = container.querySelector(".peach-newvault-header") as HTMLElement;395    const wordmark = header.querySelector(".peach-wordmark-stack");396    const back = header.querySelector(".peach-newvault-back");397    expect(wordmark).toBeTruthy();398    expect(back).toBeTruthy();399    // Wordmark first so it never shifts between onboarding screens; back400    // takes the opposite corner instead of displacing it.401    expect(header.firstElementChild).toBe(wordmark);402    expect(header.lastElementChild).toBe(back);403    await flushView();404  });405406  it("Lock sends CREATE_VAULT when the onboarding passphrase is strong enough", async () => {407    // Sequence: CREATE_VAULT → show recovery words → GET_RECOVERY_WORDS → user confirms → onUnlock408    sendMessageMock.mockImplementation(409      async (msg: unknown) => {410        const m = msg as { type: string; payload?: { password?: string } };411        if (m.type === "CREATE_VAULT") return { ok: true };412        if (m.type === "GET_RECOVERY_WORDS") {413          // Return 12 fake words — must pass findInvalidWords414          return {415            ok: true,416            data: [417              "abandon", "ability", "able", "about", "above", "absent",418              "absorb", "abstract", "absurd", "abuse", "access", "accident",419            ],420          };421        }422        return { ok: true };423      }424    );425    zxcvbnMock.mockImplementation(() => ({ score: 3 }));426    const onUnlock = vi.fn(async () => undefined);427    const container = mount(<LockView hasVault={false} ready={true} onUnlock={onUnlock} />);428429    const password = container.querySelector("#master-password") as HTMLInputElement;430    const confirm = container.querySelector("#confirm-password") as HTMLInputElement;431    const createButton = container.querySelector(".peach-lock-submit") as HTMLButtonElement;432433    inputText(password, "correct horse battery staple");434    inputText(confirm, "correct horse battery staple");435    await flushView();436    expect(createButton.disabled).toBe(false);437438    pressEnter(confirm);439    await flushView();440441    expect(sendMessageMock).toHaveBeenCalledWith({442      type: "CREATE_VAULT",443      payload: { password: "correct horse battery staple" },444    });445    // After CREATE_VAULT success, the recovery word display is shown.446    // onUnlock is NOT called yet — user must first confirm their recovery words.447    expect(onUnlock).not.toHaveBeenCalled();448  });449450  it("Lock reports saved-but-locked creation before requesting recovery words", async () => {451    sendMessageMock.mockResolvedValue({ ok: true, data: { committed: true, unlocked: false } });452    zxcvbnMock.mockImplementation(() => ({ score: 3 }));453    const container = mount(<LockView hasVault={false} ready={true} onUnlock={vi.fn()} />);454    inputText(container.querySelector<HTMLInputElement>("#master-password")!, "correct horse battery staple");455    inputText(container.querySelector<HTMLInputElement>("#confirm-password")!, "correct horse battery staple");456    await flushView();457    pressEnter(container.querySelector<HTMLInputElement>("#confirm-password")!);458    await flushView();459    expect(container.textContent).toContain("Your new vault and password were saved");460    expect(sendMessageMock).not.toHaveBeenCalledWith({ type: "SET_RECOVERY_CONFIRM_PENDING" });461  });462463  it("Lock CSV restore stops when creation saved a locked vault", async () => {464    parseImportSourceMock.mockResolvedValue(sampleImportResult());465    sendMessageMock.mockResolvedValue({ ok: true, data: { committed: true, unlocked: false } });466    const container = mount(<LockView hasVault={false} ready={true} initialRestore={true} initialRestoreSource="csv" onUnlock={vi.fn()} />);467    await flushView();468    inputText(container.querySelector<HTMLInputElement>("#restore-csv-pass")!, "new-master-password");469    inputText(container.querySelector<HTMLInputElement>("#restore-csv-confirm")!, "new-master-password");470    const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;471    Object.defineProperty(input, "files", { configurable: true, value: [new File(["csv"], "backup.csv")] });472    input.dispatchEvent(new Event("change", { bubbles: true }));473    await flushView();474    expect(container.textContent).toContain("Your new vault and password were saved");475    expect(sendMessageMock.mock.calls.some(([msg]) => (msg as { type: string }).type === "BATCH_ADD_ENTRIES")).toBe(false);476  });477478  it("Lock PeachScript restore stops when creation saved a locked vault", async () => {479    const script = await import("../../crypto/peachScript");480    const payload = await import("../../crypto/peachPayload");481    vi.spyOn(script, "isPeachScript").mockImplementation((value) => value === "backup");482    vi.spyOn(script, "decodePeachScript").mockReturnValue(new Uint8Array());483    vi.spyOn(payload, "parsePayload").mockResolvedValue({ entries: [sampleEntry()], settings: {} });484    sendMessageMock.mockResolvedValue({ ok: true, data: { committed: true, unlocked: false } });485    const container = mount(<LockView hasVault={false} ready={true} initialRestore={true} initialRestoreSource="symbols" onUnlock={vi.fn()} />);486    await flushView();487    inputText(container.querySelector<HTMLTextAreaElement>(".peach-restore-script")!, "backup");488    inputText(container.querySelector<HTMLInputElement>("#restore-backup-pass")!, "new-master-password");489    container.querySelector<HTMLButtonElement>(".peach-restore-submit")!.click();490    await flushView();491    expect(container.textContent).toContain("Your new vault and password were saved");492    expect(sendMessageMock.mock.calls.some(([msg]) => (msg as { type: string }).type === "RESTORE_ENTRIES")).toBe(false);493  });494495  it("recovery display asks for three distinct randomized word positions and confirms", async () => {496    const words12 = [497      "abandon", "ability", "able", "about", "above", "absent",498      "absorb", "abstract", "absurd", "abuse", "access", "accident",499    ];500    sendMessageMock.mockImplementation(async (msg: unknown) => {501      const type = (msg as { type?: string }).type;502      if (type === "GET_RECOVERY_WORDS") return { ok: true, data: words12 };503      return { ok: true };504    });505506    vi.useFakeTimers();507    const onDone = vi.fn();508    try {509      const container = mount(<RecoveryWordDisplayView onDone={onDone} />);510      // onMount fires GET_RECOVERY_WORDS; let the resolved promise + render settle511      await vi.advanceTimersByTimeAsync(0);512513      const prompts = Array.from(514        container.querySelectorAll(".peach-recovery-confirm-num")515      ).map((el) => Number.parseInt((el.textContent ?? "").replace(/\D+/g, ""), 10));516      expect(prompts).toHaveLength(3);517      expect(new Set(prompts).size).toBe(3);518      for (const p of prompts) {519        expect(p).toBeGreaterThanOrEqual(1);520        expect(p).toBeLessThanOrEqual(12);521      }522523      // Inputs stay disabled until the 5s countdown expires524      const inputs = Array.from(525        container.querySelectorAll(".peach-recovery-confirm-input")526      ) as HTMLInputElement[];527      expect(inputs).toHaveLength(3);528      expect(inputs[0]!.disabled).toBe(true);529      await vi.advanceTimersByTimeAsync(5000);530      expect(inputs[0]!.disabled).toBe(false);531532      prompts.forEach((pos, i) => {533        inputText(inputs[i]!, words12[pos - 1]!);534      });535536      const confirmBtn = container.querySelector(".peach-recovery-confirm-btn") as HTMLButtonElement;537      expect(confirmBtn.disabled).toBe(false);538      confirmBtn.click();539      await vi.advanceTimersByTimeAsync(700); // success pause before onDone540541      expect(onDone).toHaveBeenCalledTimes(1);542    } finally {543      vi.useRealTimers();544    }545  });546547  it.each([true, false])("Recovery words flow reports whether the saved password unlocked the vault (%s)", async (unlocked) => {548    sendMessageMock.mockImplementation(async (msg: unknown) => {549      const type = (msg as { type?: string }).type;550      if (type === "VALIDATE_RECOVERY_WORDS") {551        return { ok: true, data: { valid: true, invalid: [] } };552      }553      if (type === "RECOVER_WITH_WORDS") return { ok: true, data: { committed: true, unlocked } };554      return { ok: true };555    });556    const canvasContext = {557      clearRect: vi.fn(),558      fillText: vi.fn(),559      beginPath: vi.fn(),560      closePath: vi.fn(),561      arc: vi.fn(),562      fill: vi.fn(),563      stroke: vi.fn(),564      save: vi.fn(),565      restore: vi.fn(),566      translate: vi.fn(),567      rotate: vi.fn(),568      scale: vi.fn(),569      drawImage: vi.fn(),570      measureText: vi.fn(() => ({ width: 0 })),571      setTransform: vi.fn(),572      fillRect: vi.fn(),573      strokeRect: vi.fn(),574    } as unknown as CanvasRenderingContext2D;575    vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(() => canvasContext);576577    const onRecoveryComplete = vi.fn(async () => undefined);578    const onCancel = vi.fn();579    const container = mount(580      <RecoveryWordEntryView581        onCancel={onCancel}582        onRecoveryComplete={onRecoveryComplete}583      />584    );585586    const recoveryWords = WORD_LIST.slice(0, 12);587    for (let i = 0; i < recoveryWords.length; i++) {588      const input = container.querySelector(`#recovery-word-${i}`) as HTMLInputElement;589      inputText(input, recoveryWords[i]!);590    }591    await flushView();592593    findButton(container, "verify words").click();594    await flushView();595596    expect(container.textContent).toContain("new master password");597598    const newPassword = container.querySelector("#recovery-new-password") as HTMLInputElement;599    const confirmPassword = container.querySelector("#recovery-confirm-password") as HTMLInputElement;600    inputText(newPassword, "fresh-recovery-password");601    inputText(confirmPassword, "fresh-recovery-password");602    await flushView();603604    findButton(container, "recover vault").click();605    await flushView();606607    expect(sendMessageMock).toHaveBeenCalledWith({608      type: "RECOVER_WITH_WORDS",609      payload: {610        words: recoveryWords,611        newPassword: "fresh-recovery-password",612      },613    });614    if (unlocked) expect(onRecoveryComplete).toHaveBeenCalled();615    else {616      expect(onRecoveryComplete).not.toHaveBeenCalled();617      expect(container.textContent).toContain("your new password is saved");618      expect(container.textContent).toContain("use your new password to unlock your vault");619      expect(container.textContent).not.toContain("recovery failed");620      findButton(container, "back to unlock").click();621      expect(onCancel).toHaveBeenCalledOnce();622    }623  });624625  it("Export menu surfaces both backup formats", async () => {626    const container = mount(<ExportView onBack={vi.fn()} />);627    await flushView();628629    expect(container.textContent).toContain("PeachScript");630    expect(container.textContent).toContain("CSV");631  });632633  it("Lock can open directly on backup restore from onboarding", async () => {634    const container = mount(() => (635      <LockView636        hasVault={false}637        ready={true}638        onUnlock={vi.fn()}639        initialRestore={true}640      />641    ));642    await flushView();643644    expect(container.textContent).toContain("PeachScript");645    expect(container.textContent).toContain("Codex");646    expect(container.textContent).toContain("CSV");647    expect(container.querySelector("#master-password")).toBeNull();648  });649650  it("Lock restore back returns to onboarding, not the create-vault screen", async () => {651    const onBackToOnboarding = vi.fn();652    const container = mount(() => (653      <LockView654        hasVault={false}655        ready={true}656        onUnlock={vi.fn()}657        initialRestore={true}658        onBackToOnboarding={onBackToOnboarding}659      />660    ));661    await flushView();662663    (container.querySelector(".peach-restore-back") as HTMLButtonElement).click();664    await flushView();665    expect(onBackToOnboarding).toHaveBeenCalledTimes(1);666  });667668  it("Lock restore resumes on the picked PeachScript source, not the picker", async () => {669    const container = mount(() => (670      <LockView671        hasVault={false}672        ready={true}673        onUnlock={vi.fn()}674        initialRestore={true}675        initialRestoreSource="symbols"676      />677    ));678    await flushView();679680    expect(container.querySelector(".peach-restore-script")).toBeTruthy();681    expect(container.querySelector("#restore-backup-pass")).toBeTruthy();682    expect(container.querySelector(".peach-restore-sources")).toBeNull();683  });684685  it("Lock restore resumes on the picked CSV source, not the picker", async () => {686    const container = mount(() => (687      <LockView688        hasVault={false}689        ready={true}690        onUnlock={vi.fn()}691        initialRestore={true}692        initialRestoreSource="csv"693      />694    ));695    await flushView();696697    expect(container.querySelector("#restore-csv-pass")).toBeTruthy();698    expect(container.querySelector("#restore-csv-confirm")).toBeTruthy();699    expect(container.querySelector(".peach-restore-sources")).toBeNull();700  });701702  it("Lock restore PeachScript form loads a dropped .peach file", async () => {703    const container = mount(() => (704      <LockView705        hasVault={false}706        ready={true}707        onUnlock={vi.fn()}708        initialRestore={true}709        initialRestoreSource="symbols"710      />711    ));712    await flushView();713714    const form = container.querySelector(".peach-restore-form") as HTMLElement;715    expect(form).toBeTruthy();716717    // The OS file picker dismisses the action popup, so drag-and-drop is the718    // file path that survives; a drop must land the file in the script field.719    const file = new File(["dropped-peach-backup"], "vault.peach", { type: "text/plain" });720    const drop = new Event("drop", { bubbles: true, cancelable: true }) as Event & {721      dataTransfer?: { files: File[] };722    };723    drop.dataTransfer = { files: [file] };724    form.dispatchEvent(drop);725    await flushView();726727    const script = container.querySelector(".peach-restore-script") as HTMLTextAreaElement;728    expect(script.value).toBe("dropped-peach-backup");729  });730731  it("HOLE 4: removing a device discloses that recovery words survive revocation", async () => {732    const device = {733      deviceId: "phone-1",734      deviceName: "June's Phone",735      deviceType: "android" as const,736      longTermPublicKeyHex: "a".repeat(64),737      signingPublicKeyHex: "b".repeat(64),738      pairedAt: 1,739      trustSource: "direct" as const,740    };741    sendMessageMock.mockImplementation(async (msg: unknown) => {742      const m = msg as { type: string };743      if (m.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [device] } };744      return { ok: true, data: null };745    });746747    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);748    for (let i = 0; i < 30; i++) await Promise.resolve();749750    const openSync = Array.from(container.querySelectorAll("button")).find((b) =>751      /sync/i.test(b.textContent ?? ""),752    );753    openSync?.click();754    for (let i = 0; i < 30; i++) await Promise.resolve();755756    const remove = Array.from(container.querySelectorAll("button")).find(757      (b) => (b.textContent ?? "").trim() === "remove",758    );759    expect(remove).toBeTruthy();760761    // Guard against a vacuous pass: the disclosure must not already be on762    // screen before the user asks to remove anything.763    expect(container.querySelector(".peach-unpair-confirm-note")).toBeNull();764765    remove!.click();766    for (let i = 0; i < 10; i++) await Promise.resolve();767768    // Revocation must never be presented as securing the vault against the769    // removed device — recovery words survive it and restore everything.770    const note = container.querySelector(".peach-unpair-confirm-note");771    expect(note).toBeTruthy();772    const text = note!.textContent ?? "";773    expect(text).toContain("master password");774    expect(text).toContain("recovery words");775    expect(text).toContain("future changes");776  });777778  it("PB-26-709: pending device approval identifies the key, time, provenance, and vault scope", async () => {779    sendMessageMock.mockImplementation(async (msg: unknown) => {780      const m = msg as { type: string };781      if (m.type === "GET_PENDING_VOUCHED_DEVICES") {782        return {783          ok: true,784          data: [{785            deviceId: "phone-source-id",786            deviceName: "June's Phone",787            deviceType: "android",788            longTermPublicKeyHex: "a1b2c3d4e5f6" + "0".repeat(52),789            signingPublicKeyHex: "b".repeat(64),790            pairedAt: Date.UTC(2026, 8, 5),791            receivedAt: Date.UTC(2026, 8, 6, 20, 15),792            vouchedByDeviceId: "trusted-browser-id",793          }],794        };795      }796      if (m.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [] } };797      return { ok: true, data: null };798    });799800    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);801    for (let i = 0; i < 30; i++) await Promise.resolve();802    Array.from(container.querySelectorAll("button"))803      .find((button) => /sync/i.test(button.textContent ?? ""))804      ?.click();805    for (let i = 0; i < 30; i++) await Promise.resolve();806807    expect(container.textContent).toContain("a1b2 c3d4 e5f6");808    expect(container.textContent).toContain("trusted-browser-id");809    expect(container.textContent).toContain("2026-09-06");810    expect(container.textContent).toContain("existing vault contents");811  });812813  it("Settings keeps the paired-device list and revokes through UNPAIR_DEVICE", async () => {814    const device = {815      deviceId: "phone-1",816      deviceName: "June's Phone",817      deviceType: "android" as const,818      longTermPublicKeyHex: "a".repeat(64),819      signingPublicKeyHex: "b".repeat(64),820      pairedAt: 1,821      trustSource: "direct" as const,822    };823    let paired: typeof device[] = [device];824    sendMessageMock.mockImplementation(async (msg: any) => {825      if (msg?.type === "LIST_PAIRED_DEVICES") {826        return { ok: true, data: { devices: [...paired] } };827      }828      if (msg?.type === "UNPAIR_DEVICE") {829        // Mirror the real handler: UNPAIR_DEVICE drops the row from the830        // registry. The next LIST_PAIRED_DEVICES must not see it.831        paired = paired.filter((d) => d.deviceId !== msg.payload?.deviceId);832        return { ok: true };833      }834      if (msg?.type === "RENAME_PAIRED_DEVICE") {835        paired = paired.map((d) =>836          d.deviceId === msg.payload?.deviceId ? { ...d, localAlias: msg.payload.name } : d,837        );838        return { ok: true };839      }840      return { ok: true, data: null };841    });842843    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);844    for (let i = 0; i < 30; i++) await Promise.resolve();845    Array.from(container.querySelectorAll("button"))846      .find((b) => /sync/i.test(b.textContent ?? ""))847      ?.click();848    for (let i = 0; i < 30; i++) await Promise.resolve();849850    // The list itself: extracting the relay selector must not take the hub with it.851    expect(container.textContent).toContain("PAIRED DEVICES");852    expect(container.textContent).toContain("June's Phone");853    expect(container.textContent).toContain("Android");854    Array.from(container.querySelectorAll("button"))855      .find((b) => (b.textContent ?? "").trim() === "rename")!856      .click();857    const renameInput = container.querySelector<HTMLInputElement>('input[aria-label="Rename June\'s Phone"]')!;858    renameInput.value = "Travel phone";859    renameInput.dispatchEvent(new InputEvent("input", { bubbles: true }));860    Array.from(container.querySelectorAll("button"))861      .find((b) => (b.textContent ?? "").trim() === "save")!862      .click();863    for (let i = 0; i < 30; i++) await Promise.resolve();864    expect(sendMessageMock).toHaveBeenCalledWith({865      type: "RENAME_PAIRED_DEVICE",866      payload: { deviceId: "phone-1", name: "Travel phone" },867    });868    expect(container.textContent).toContain("Travel phone");869    const syncNowButton = container.querySelector<HTMLButtonElement>(870      'button[aria-label="Sync this vault now"]',871    )!;872    const syncStatusRow = syncNowButton.closest(".peach-settings-row--meta");873    const syncCard = syncNowButton.closest('[data-settings-card-id="sync"]');874    expect(syncStatusRow).not.toBeNull();875    expect(syncStatusRow?.contains(syncNowButton)).toBe(true);876    expect(syncCard?.querySelectorAll(".peach-settings-row--meta")).toHaveLength(1);877    const labels = Array.from(container.querySelectorAll(".peach-settings-sub-label"));878    const addDeviceLabel = labels.find((label) => label.textContent?.includes("ADD A DEVICE"))!;879    const pairedDevicesLabel = labels.find((label) => label.textContent?.includes("PAIRED DEVICES"))!;880    expect(881      syncNowButton.compareDocumentPosition(addDeviceLabel) & Node.DOCUMENT_POSITION_FOLLOWING,882    ).toBeTruthy();883    expect(884      syncNowButton.compareDocumentPosition(pairedDevicesLabel) & Node.DOCUMENT_POSITION_FOLLOWING,885    ).toBeTruthy();886887    Array.from(container.querySelectorAll("button"))888      .find((b) => (b.textContent ?? "").trim() === "remove")!889      .click();890    for (let i = 0; i < 10; i++) await Promise.resolve();891    const confirm = Array.from(892      container.querySelectorAll<HTMLButtonElement>(".peach-unpair-confirm button"),893    ).find((b) => (b.textContent ?? "").trim() === "remove");894    confirm!.click();895    for (let i = 0; i < 30; i++) await Promise.resolve();896897    expect(sendMessageMock).toHaveBeenCalledWith({898      type: "UNPAIR_DEVICE",899      payload: { deviceId: "phone-1" },900    });901    // The list must be refreshed and the device must be gone. The regression902    // we're guarding against: a Settings view that calls UNPAIR_DEVICE but903    // never refreshes LIST_PAIRED_DEVICES, so the row stays in the UI.904    expect(container.textContent).not.toContain("June's Phone");905    expect(container.textContent).not.toContain("PAIRED DEVICES");906  });907  it("Settings keeps the confirmation and shows revoke failures", async () => {908    const device = {909      deviceId: "phone-1",910      deviceName: "June's Phone",911      deviceType: "android" as const,912      longTermPublicKeyHex: "a".repeat(64),913      signingPublicKeyHex: "b".repeat(64),914      pairedAt: 1,915      trustSource: "direct" as const,916    };917    sendMessageMock.mockImplementation(async (msg: unknown) => {918      const message = msg as { type?: string; payload?: { deviceId?: string } };919      if (message.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [device] } };920      if (message.type === "UNPAIR_DEVICE") return { ok: false, error: "trust_data_corrupted" };921      return { ok: true, data: null };922    });923924    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);925    for (let i = 0; i < 30; i++) await Promise.resolve();926    for (let i = 0; i < 30; i++) await Promise.resolve();927    Array.from(container.querySelectorAll("button")).find((b) => /sync/i.test(b.textContent ?? ""))?.click();928    for (let i = 0; i < 30; i++) await Promise.resolve();929    Array.from(container.querySelectorAll("button")).find((b) => (b.textContent ?? "").trim() === "remove")?.click();930    for (let i = 0; i < 10; i++) await Promise.resolve();931    Array.from(container.querySelectorAll<HTMLButtonElement>(".peach-unpair-confirm button")).find((b) => (b.textContent ?? "").trim() === "remove")?.click();932    for (let i = 0; i < 30; i++) await Promise.resolve();933934    expect(container.textContent).toContain("trust_data_corrupted");935    expect(container.textContent).toContain("June's Phone");936  });937938  it("Settings drops the secure-reset panel once the device is on the settled generation", async () => {939    const openSyncCard = async (state: "V2_ACTIVE" | "V2_ANCHOR" | "LEGACY_ACTIVE") => {940      sendMessageMock.mockImplementation(async (msg: unknown) => {941        const message = msg as { type?: string };942        if (message.type === "GET_SYNC_GENERATION") {943          return { ok: true, data: { schemaVersion: 1, generation: 2, state, createdAt: 1 } };944        }945        return { ok: true, data: null };946      });947      const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);948      for (let i = 0; i < 30; i++) await Promise.resolve();949      Array.from(container.querySelectorAll("button")).find((b) => /sync/i.test(b.textContent ?? ""))?.click();950      for (let i = 0; i < 30; i++) await Promise.resolve();951      return container;952    };953954    // Settled: the migration is over, so the panel must not linger as a label.955    const settled = await openSyncCard("V2_ACTIVE");956    expect(settled.textContent).not.toContain("SECURE SYNC RESET");957    expect(settled.textContent).toContain("ADD A DEVICE");958959    // Still actionable states keep the panel and its explanation.960    const anchored = await openSyncCard("V2_ANCHOR");961    expect(anchored.textContent).toContain("SECURE SYNC RESET");962    expect(anchored.textContent).toContain("Not re-paired");963964    const legacy = await openSyncCard("LEGACY_ACTIVE");965    expect(legacy.textContent).toContain("SECURE SYNC RESET");966    expect(legacy.textContent).toContain("Legacy Sync generation");967  });968969  it("Settings keeps connection and recovery details collapsed until requested", async () => {970    sendMessageMock.mockImplementation(async (msg: any) => {971      if (msg?.type === "LIST_PAIRED_DEVICES") {972        return { ok: true, data: { devices: [] } };973      }974      return { ok: true, data: null };975    });976977    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);978    for (let i = 0; i < 30; i++) await Promise.resolve();979    Array.from(container.querySelectorAll("button"))980      .find((button) => /sync/i.test(button.textContent ?? ""))981      ?.click();982    for (let i = 0; i < 20; i++) await Promise.resolve();983984    expect(container.textContent).toContain("SYNC STATUS");985    expect(container.textContent).toContain("ADD A DEVICE");986    expect(container.textContent).not.toContain("Public relay");987    expect(container.textContent).not.toContain("Rotate sync identity");988989    const connection = Array.from(container.querySelectorAll("button"))990      .find((button) => button.textContent?.includes("CONNECTION"));991    connection?.click();992    await Promise.resolve();993    expect(container.textContent).toContain("Public relay");994995    const recovery = Array.from(container.querySelectorAll("button"))996      .find((button) => button.textContent?.includes("RECOVERY & SECURITY"));997    recovery?.click();998    await Promise.resolve();999    expect(container.textContent).toContain("Rotate sync identity");1000  });10011002  it("Settings requires current, new, and confirm passwords before enabling save", async () => {1003    sendMessageMock.mockResolvedValue({ ok: true, data: null });1004    const container = mount(1005      <SettingsView1006        entriesCount={1}1007        breachMonitoring={true}1008        lockOnClose={true}1009        lockedSyncRequiresUnlock={false}1010        autoLockMinutes={5}1011        trashRetentionDays={30}1012        theme="dark"1013        accentColor="peach"1014        textSize="medium"1015        reduceMotion={false}1016        onBreachMonitoringChange={vi.fn()}1017        onLockedSyncRequiresUnlockChange={vi.fn()}1018        onLockOnCloseChange={vi.fn()}1019        onAutoLockMinutesChange={vi.fn()}1020        onTrashRetentionChange={vi.fn()}1021        onThemeChange={vi.fn()}1022        onAccentChange={vi.fn()}1023        onTextSizeChange={vi.fn()}1024        onReduceMotionChange={vi.fn()}1025        shortcuts={DEFAULT_BINDINGS}1026        onShortcutsChange={vi.fn()}1027        onBack={vi.fn()}1028        onImport={vi.fn()}1029        onExport={vi.fn()}1030        onBreachCheckDone={vi.fn()}1031      />1032    );1033    await flushView();10341035    expect(container.querySelectorAll(".stk-card").length).toBe(7);1036    // Settings now opens to card I (Peach Pro) — see koh save [f7a2710b3f67]1037    // "open settings to card I (Peach Pro) instead of card II (Protection)".1038    expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Peach Pro");10391040    const changeButton = Array.from(container.querySelectorAll("button")).find(1041      (candidate) => candidate.textContent?.trim() === "change"1042    ) as HTMLButtonElement;1043    changeButton.click();1044    await flushView();10451046    const saveButton = Array.from(container.querySelectorAll("button")).find(1047      (candidate) => candidate.textContent?.trim() === "save new password"1048    ) as HTMLButtonElement;1049    expect(saveButton.disabled).toBe(true);10501051    const inputs = container.querySelectorAll('input[type="password"]');1052    inputText(inputs[0] as HTMLInputElement, "current-pass");1053    inputText(inputs[1] as HTMLInputElement, "new-pass-12345");1054    await flushView();1055    expect(saveButton.disabled).toBe(true);10561057    inputText(inputs[2] as HTMLInputElement, "new-pass-12345");1058    await flushView();1059    expect(saveButton.disabled).toBe(false);1060  });10611062  it("Settings feedback highlights the selected category and hides the form after submit", async () => {1063    sendMessageMock.mockResolvedValue({ ok: true, data: null });1064    const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => ({1065      ok: true,1066      json: async () => ({ success: true }),1067    }));1068    vi.stubGlobal("fetch", fetchMock);10691070    const container = mount(1071      <SettingsView1072        entriesCount={1}1073        breachMonitoring={true}1074        lockOnClose={true}1075        lockedSyncRequiresUnlock={false}1076        autoLockMinutes={5}1077        trashRetentionDays={30}1078        theme="dark"1079        accentColor="peach"1080        textSize="medium"1081        reduceMotion={false}1082        initialSection="feedback"1083        onLockedSyncRequiresUnlockChange={vi.fn()}1084        onBreachMonitoringChange={vi.fn()}1085        onLockOnCloseChange={vi.fn()}1086        onAutoLockMinutesChange={vi.fn()}1087        onTrashRetentionChange={vi.fn()}1088        onThemeChange={vi.fn()}1089        onAccentChange={vi.fn()}1090        onTextSizeChange={vi.fn()}1091        onReduceMotionChange={vi.fn()}1092        shortcuts={DEFAULT_BINDINGS}1093        onShortcutsChange={vi.fn()}1094        onBack={vi.fn()}1095        onImport={vi.fn()}1096        onExport={vi.fn()}1097        onBreachCheckDone={vi.fn()}1098      />1099    );1100    await flushView();11011102    const feedbackCard = container.querySelector('[data-settings-card-id="feedback"]') as HTMLElement;1103    expect(feedbackCard.classList.contains("is-active")).toBe(true);11041105    const categoryButtons = Array.from(container.querySelectorAll(".peach-feedback-chip")) as HTMLButtonElement[];1106    const bugButton = categoryButtons.find((button) => button.textContent?.trim() === "Bug report")!;1107    const featureButton = categoryButtons.find((button) => button.textContent?.trim() === "Feature request")!;1108    expect(bugButton.getAttribute("aria-pressed")).toBe("true");1109    expect(featureButton.getAttribute("aria-pressed")).toBe("false");11101111    featureButton.click();1112    await flushView();11131114    expect(bugButton.getAttribute("aria-pressed")).toBe("false");1115    expect(featureButton.getAttribute("aria-pressed")).toBe("true");1116    expect(featureButton.classList.contains("is-active")).toBe(true);11171118    inputText(1119      container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,1120      '<script>alert("xss")</script> Please make this easier to see & safer.'1121    );1122    const sendButton = Array.from(container.querySelectorAll("button")).find(1123      (candidate) => candidate.textContent?.trim() === "Send"1124    ) as HTMLButtonElement;1125    sendButton.click();11261127    await vi.waitFor(() => {1128      expect(container.textContent).toContain("Thank you");1129    });11301131    const requestBody = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));1132    expect(requestBody.subject).toContain("Feature request");1133    expect(requestBody.message).toBe(1134      "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt; Please make this easier to see &amp; safer."1135    );1136    expect(requestBody.message).not.toContain("<script>");1137    expect(container.textContent).toContain("Someone will process it soon");1138    expect(container.querySelector(".peach-feedback-textarea")).toBeNull();1139    expect(container.querySelector(".peach-feedback-submit")).toBeNull();1140  });11411142  it("Settings keeps license activation on the full-screen celebration path", async () => {1143    const onLicenseChange = vi.fn(async () => undefined);1144    sendMessageMock.mockImplementation(async (msg: unknown) => {1145      const type = (msg as { type?: string }).type;1146      if (type === "GET_LICENSE") return { ok: true, data: { valid: false, plan: "free" } };1147      if (type === "ACTIVATE_LICENSE") {1148        return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };1149      }1150      if (type === "GET_ENTRIES") return { ok: true, data: [] };1151      return { ok: true, data: null };1152    });11531154    const container = mount(<SettingsView {...settingsProps({ isPro: false, onLicenseChange })} />);1155    await flushView();11561157    inputText(1158      container.querySelector(".peach-pro-key-inline-input") as HTMLInputElement,1159      "PEACH-TEST-KEY",1160    );1161    const apply = container.querySelector(".peach-pro-key-apply") as HTMLButtonElement;1162    apply.click();11631164    await vi.waitFor(() => expect(onLicenseChange).toHaveBeenCalledTimes(1));1165    expect(container.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(false);1166    expect(container.textContent).not.toContain("thank you ✦");1167  });11681169  it("Settings Pro star and peach clicks use the same in-card replay path", async () => {1170    sendMessageMock.mockImplementation(async (msg: unknown) => {1171      const type = (msg as { type?: string }).type;1172      if (type === "GET_LICENSE") return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };1173      if (type === "GET_LICENSE_KEY") return { ok: true, data: "PEACH-TEST-KEY" };1174      if (type === "GET_ENTRIES") return { ok: true, data: [] };1175      return { ok: true, data: null };1176    });11771178    const onLicenseChangeFromStar = vi.fn();1179    const starContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromStar })} />);1180    await flushView();1181    (starContainer.querySelector(".stk-card-icon--btn") as HTMLButtonElement).click();1182    expect(starContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);1183    expect(onLicenseChangeFromStar).not.toHaveBeenCalled();11841185    const onLicenseChangeFromPeach = vi.fn();1186    const peachContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromPeach })} />);1187    await flushView();1188    (peachContainer.querySelector(".peach-pro-active-mark-wrap") as HTMLButtonElement).click();1189    expect(peachContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);1190    expect(onLicenseChangeFromPeach).not.toHaveBeenCalled();1191  });11921193  it("Settings feedback sends even if Firefox reports no data-collection consent — a user-initiated send is its own consent", async () => {1194    sendMessageMock.mockResolvedValue({ ok: true, data: null });1195    const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => ({1196      ok: true,1197      json: async () => ({ success: true }),1198    }));1199    vi.stubGlobal("fetch", fetchMock);1200    // Firefox-style permissions API reporting the optional consent as absent.1201    // The old code gated send behind this and silently returned to idle, which1202    // read as a dead Send button. The gate is gone: Send must always send.1203    vi.stubGlobal("browser", {1204      permissions: {1205        getAll: vi.fn(async () => ({ data_collection: [] })),1206        request: vi.fn(async () => false),1207      },1208    });12091210    const container = mount(1211      <SettingsView1212        entriesCount={1}1213        breachMonitoring={true}1214        lockOnClose={true}1215        lockedSyncRequiresUnlock={false}1216        autoLockMinutes={5}1217        trashRetentionDays={30}1218        theme="dark"1219        accentColor="peach"1220        textSize="medium"1221        reduceMotion={false}1222        initialSection="feedback"1223        onLockedSyncRequiresUnlockChange={vi.fn()}1224        onBreachMonitoringChange={vi.fn()}1225        onLockOnCloseChange={vi.fn()}1226        onAutoLockMinutesChange={vi.fn()}1227        onTrashRetentionChange={vi.fn()}1228        onThemeChange={vi.fn()}1229        onAccentChange={vi.fn()}1230        onTextSizeChange={vi.fn()}1231        onReduceMotionChange={vi.fn()}1232        shortcuts={DEFAULT_BINDINGS}1233        onShortcutsChange={vi.fn()}1234        onBack={vi.fn()}1235        onImport={vi.fn()}1236        onExport={vi.fn()}1237        onBreachCheckDone={vi.fn()}1238      />1239    );1240    await flushView();12411242    inputText(1243      container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,1244      "Please improve the feedback flow."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(fetchMock).toHaveBeenCalledTimes(1);1253    });1254    await vi.waitFor(() => {1255      expect(container.textContent).toContain("Thank you");1256    });1257    expect(container.querySelector(".peach-feedback-textarea")).toBeNull();1258  });12591260  it("Settings sends CHANGE_PASSWORD and forwards auto-lock/theme changes through callbacks", async () => {1261    sendMessageMock.mockImplementation(async (msg: unknown) => {1262      const m = msg as { type: string };1263      if (m.type === "GET_RECOVERY_WORDS") {1264        return {1265          ok: true,1266          data: [1267            "abandon", "ability", "able", "about", "above", "absent",1268            "absorb", "abstract", "absurd", "abuse", "access", "accident",1269          ],1270        };1271      }1272      return { ok: true, data: null };1273    });1274    const onAutoLockMinutesChange = vi.fn();1275    const onLockedSyncRequiresUnlockChange = vi.fn();1276    const onThemeChange = vi.fn();1277    const container = mount(1278      <SettingsView1279        entriesCount={1}1280        breachMonitoring={true}1281        lockOnClose={true}1282        lockedSyncRequiresUnlock={false}1283        autoLockMinutes={5}1284        trashRetentionDays={30}1285        theme="dark"1286        accentColor="peach"1287        textSize="medium"1288        reduceMotion={false}1289        onBreachMonitoringChange={vi.fn()}1290        onLockedSyncRequiresUnlockChange={onLockedSyncRequiresUnlockChange}1291        onLockOnCloseChange={vi.fn()}1292        onAutoLockMinutesChange={onAutoLockMinutesChange}1293        onTrashRetentionChange={vi.fn()}1294        onThemeChange={onThemeChange}1295        onAccentChange={vi.fn()}1296        onTextSizeChange={vi.fn()}1297        onReduceMotionChange={vi.fn()}1298        shortcuts={DEFAULT_BINDINGS}1299        onShortcutsChange={vi.fn()}1300        onBack={vi.fn()}1301        onImport={vi.fn()}1302        onExport={vi.fn()}1303        onBreachCheckDone={vi.fn()}1304      />1305    );1306    await flushView();1307    sendMessageMock.mockClear();13081309    // ── Auto-lock + theme changes (before password change) ─────────────1310    const selects = container.querySelectorAll("select");1311    changeSelect(selects[0] as HTMLSelectElement, "15");1312    expect(onAutoLockMinutesChange).toHaveBeenCalledWith(15);13131314    const appearanceCard = container.querySelector('[data-settings-card-id="appearance"]') as HTMLElement;1315    appearanceCard.click();1316    await flushView();1317    expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Appearance");1318    const themeButton = Array.from(container.querySelectorAll("button")).find(1319      (candidate) => candidate.textContent?.trim() === "Switch to light"1320    ) as HTMLButtonElement;1321    themeButton.click();1322    expect(onThemeChange).toHaveBeenCalledWith("light");13231324    // ── Locked Sync custody toggle ──────────────────────────────────────1325    const protectionCard = container.querySelector('[data-settings-card-id="protection"]') as HTMLElement;1326    protectionCard.click();1327    await flushView();1328    const custodyToggle = container.querySelector<HTMLButtonElement>(1329      'button[aria-label="Toggle unlock requirement for locked Sync after restart"]',1330    );1331    expect(custodyToggle).not.toBeNull();1332    custodyToggle!.click();1333    expect(onLockedSyncRequiresUnlockChange).toHaveBeenCalledWith(true);13341335    const changeButton = Array.from(container.querySelectorAll("button")).find(1336      (candidate) => candidate.textContent?.trim() === "change"1337    ) as HTMLButtonElement;1338    changeButton.click();1339    await flushView();13401341    const inputs = container.querySelectorAll('input[type="password"]');1342    inputText(inputs[0] as HTMLInputElement, "current-pass");1343    inputText(inputs[1] as HTMLInputElement, "new-password-123");1344    inputText(inputs[2] as HTMLInputElement, "new-password-123");1345    await flushView();13461347    const saveButton = Array.from(container.querySelectorAll("button")).find(1348      (candidate) => candidate.textContent?.trim() === "save new password"1349    ) as HTMLButtonElement;1350    saveButton.click();1351    await flushView();13521353    expect(sendMessageMock).toHaveBeenCalledWith({1354      type: "CHANGE_PASSWORD",1355      payload: {1356        currentPassword: "current-pass",1357        newPassword: "new-password-123",1358      },1359    });13601361    // After a successful password change the recovery word display replaces settings.1362    expect(container.textContent).toContain("save your recovery words");1363    expect(sendMessageMock).toHaveBeenCalledWith({ type: "GET_RECOVERY_WORDS" });1364  });13651366  it("Entry copy actions send COPY and canary ping messages for password and username", async () => {1367    sendMessageMock.mockResolvedValue({ ok: true });1368    const container = mount(1369      <EntryView1370        entry={sampleEntry()}1371        onDelete={vi.fn()}1372        onFieldSaved={vi.fn(async () => undefined)}1373      />1374    );13751376    const passwordButton = container.querySelector('button[aria-label="Copy password"]') as HTMLButtonElement;1377    passwordButton.click();1378    await flushView();13791380    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1381      type: "COPY",1382      payload: { text: "secret123", label: "password", alreadyWritten: false },1383    });1384    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {1385      type: "FIRE_CANARY_PING",1386      payload: {1387        webhookUrl: "https://example.com/hook",1388        entryTitle: "GitHub",1389        trigger: "password_copied",1390      },1391    });13921393    sendMessageMock.mockClear();1394    const usernameButton = container.querySelector('button[aria-label="Copy username"]') as HTMLButtonElement;1395    usernameButton.click();1396    await flushView();13971398    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1399      type: "COPY",1400      payload: { text: "june", label: "username", alreadyWritten: false },1401    });1402    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {1403      type: "FIRE_CANARY_PING",1404      payload: {1405        webhookUrl: "https://example.com/hook",1406        entryTitle: "GitHub",1407        trigger: "username_copied",1408      },1409    });1410  });14111412  it("Entry keyboard password copy reports its canary after COPY", async () => {1413    sendMessageMock.mockResolvedValue({ ok: true });1414    mount(1415      <EntryView1416        entry={sampleEntry()}1417        onDelete={vi.fn()}1418        onFieldSaved={vi.fn(async () => undefined)}1419      />1420    );14211422    window.dispatchEvent(new KeyboardEvent("keydown", { key: "c", bubbles: true }));1423    await flushView();14241425    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1426      type: "COPY",1427      payload: { text: "secret123", label: "password", alreadyWritten: false },1428    });1429    await flushView();1430    expect(sendMessageMock.mock.calls).toContainEqual([{1431      type: "FIRE_CANARY_PING",1432      payload: {1433        webhookUrl: "https://example.com/hook",1434        entryTitle: "GitHub",1435        trigger: "password_copied",1436      },1437    }]);1438  });1439  it("Entry Cmd+C leaves the native clipboard shortcut untouched", async () => {1440    sendMessageMock.mockResolvedValue({ ok: true });1441    mount(1442      <EntryView1443        entry={sampleEntry()}1444        onDelete={vi.fn()}1445        onFieldSaved={vi.fn(async () => undefined)}1446      />1447    );14481449    window.dispatchEvent(new KeyboardEvent("keydown", { key: "c", metaKey: true, bubbles: true }));1450    await flushView();14511452    expect(sendMessageMock).not.toHaveBeenCalledWith(expect.objectContaining({ type: "COPY" }));1453  });14541455  it("Vault password swipe copy reports its canary after COPY", async () => {1456    sendMessageMock.mockResolvedValue({ ok: true });1457    const container = mount(1458      <VaultView1459        entries={[sampleEntry()]}1460        sortOrder="url-first"1461        onSelectEntry={vi.fn()}1462        onSortOrderChange={vi.fn()}1463        onAdd={vi.fn()}1464        onClose={vi.fn()}1465      />1466    );1467    const row = container.querySelector(".peach-entry-row") as HTMLButtonElement;1468    row.dispatchEvent(new TouchEvent("touchstart", {1469      bubbles: true,1470      touches: [{ clientX: 0, clientY: 0 } as Touch],1471    }));1472    row.dispatchEvent(new TouchEvent("touchend", {1473      bubbles: true,1474      changedTouches: [{ clientX: 100, clientY: 0 } as Touch],1475    }));1476    await flushView();14771478    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {1479      type: "COPY",1480      payload: { text: "secret123", label: "password", alreadyWritten: false },1481    });1482    await flushView();1483    expect(sendMessageMock.mock.calls).toContainEqual([{1484      type: "FIRE_CANARY_PING",1485      payload: {1486        webhookUrl: "https://example.com/hook",1487        entryTitle: "GitHub",1488        trigger: "password_copied",1489      },1490    }]);1491  });14921493  it("Entry shows Advanced for passkey-bearing credential entries", async () => {1494    const container = mount(1495      <EntryView1496        entry={sampleEntry({1497          type: "passkey",1498          username: undefined,1499          password: undefined,1500          totp: undefined,1501          canary: undefined,1502          passkey: {1503            rpId: "vercel.com",1504            rpName: "Vercel",1505            credentialId: "cred-1",1506            publicKeyCose: "cose",1507            userHandle: "handle",1508            userName: "june",1509            userDisplayName: "June",1510            algorithm: -7,1511            signCount: 0,1512            aaguid: "",1513            backupEligible: false,1514            backupState: false,1515            createdAt: 1,1516          },1517        })}1518        onDelete={vi.fn()}1519        onFieldSaved={vi.fn(async () => undefined)}1520      />1521    );15221523    const advanced = Array.from(container.querySelectorAll(".peach-entry-add-link")).find(1524      (button) => button.textContent?.includes("Advanced")1525    ) as HTMLButtonElement | undefined;1526    expect(advanced).toBeDefined();1527    expect(advanced?.textContent).toContain("+ Advanced");15281529    advanced!.click();1530    await flushView();15311532    expect(container.textContent).toContain("passkey · vercel.com");1533  });15341535  it("Entry refuses to send an empty password update and copies TOTP through COPY", async () => {1536    sendMessageMock.mockResolvedValue({ ok: true });1537    const onFieldSaved = vi.fn(async () => undefined);1538    const container = mount(1539      <EntryView1540        entry={sampleEntry()}1541        onDelete={vi.fn()}1542        onFieldSaved={onFieldSaved}1543      />1544    );15451546    const passwordValue = container.querySelector(".peach-password-value") as HTMLSpanElement;1547    passwordValue.click();1548    await flushView();15491550    const passwordInput = container.querySelector('input[placeholder="paste or type a password"]') as HTMLInputElement;1551    inputText(passwordInput, "");1552    await flushView();15531554    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;1555    saveButton.click();1556    await flushView();15571558    expect(sendMessageMock).not.toHaveBeenCalledWith(1559      expect.objectContaining({ type: "UPDATE_ENTRY" })1560    );1561    expect(onFieldSaved).not.toHaveBeenCalled();15621563    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;1564    totpMain.click();15651566    await vi.waitFor(() => {1567      expect(sendMessageMock).toHaveBeenLastCalledWith({1568        type: "COPY",1569        payload: { text: "123456", label: "totp", alreadyWritten: false },1570      });1571    }, { timeout: 500 });1572  });15731574  it("Entry closes an unchanged inline editor when focus leaves it", async () => {1575    sendMessageMock.mockResolvedValue({ ok: true });1576    const container = mount(1577      <EntryView1578        entry={sampleEntry()}1579        onDelete={vi.fn()}1580        onFieldSaved={vi.fn(async () => undefined)}1581      />1582    );15831584    const usernameValue = container.querySelector(".peach-field-value.peach-inline-clickable") as HTMLSpanElement;1585    usernameValue.click();1586    await flushView();15871588    const usernameInput = container.querySelector(".peach-inline-input[autocomplete=\"off\"]") as HTMLInputElement;1589    usernameInput.blur();1590    await flushView();15911592    expect(container.querySelector(".peach-inline-input[autocomplete=\"off\"]")).toBeNull();1593    expect(sendMessageMock).not.toHaveBeenCalledWith(1594      expect.objectContaining({ type: "UPDATE_ENTRY" })1595    );1596  });15971598  it("Entry keeps the full used-email list available while editing an email", async () => {1599    const container = mount(1600      <EntryView1601        entry={sampleEntry({ email: "[email protected]" })}1602        entries={[1603          sampleEntry({ email: "[email protected]" }),1604          sampleEntry({ id: "entry-2", email: "[email protected]" }),1605          sampleEntry({ id: "entry-3", username: "duckuccino" }),1606        ]}1607        onDelete={vi.fn()}1608        onFieldSaved={vi.fn(async () => undefined)}1609      />1610    );16111612    const emailValue = Array.from(container.querySelectorAll(".peach-field-card")).find(1613      (card) => card.querySelector(".peach-label")?.textContent === "email"1614    )?.querySelector(".peach-inline-clickable") as HTMLSpanElement;1615    emailValue.click();1616    await flushView();16171618    const suggestions = Array.from(container.querySelectorAll(".peach-identity-suggestion-value"))1619      .map((element) => element.textContent);1620    expect(suggestions).toEqual(["[email protected]", "[email protected]"]);1621  });16221623  it("Entry lets TOTP secrets be edited inline", async () => {1624    sendMessageMock.mockResolvedValue({ ok: true });1625    const onFieldSaved = vi.fn(async () => undefined);1626    const container = mount(1627      <EntryView1628        entry={sampleEntry()}1629        onDelete={vi.fn()}1630        onFieldSaved={onFieldSaved}1631      />1632    );16331634    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;1635    totpMain.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));1636    await flushView();16371638    const totpInput = container.querySelector('input[placeholder="otpauth://... or base32 secret"]') as HTMLInputElement;1639    inputText(totpInput, "otpauth://totp/Example?secret=NB2W45DFOIZA====&issuer=Peach");1640    await flushView();16411642    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;1643    saveButton.click();1644    await flushView();16451646    expect(sendMessageMock).toHaveBeenCalledWith({1647      type: "UPDATE_ENTRY",1648      payload: {1649        id: "entry-1",1650        patch: { totp: "NB2W45DFOIZA====" },1651      },1652    });1653    expect(onFieldSaved).toHaveBeenCalled();1654  });16551656  it("Vault seeds and focuses search when a search seed is provided", async () => {1657    const container = mount(1658      <VaultView1659        entries={[sampleEntry(), sampleEntry({ id: "entry-2", title: "GitLab" })]}1660        sortOrder="url-first"1661        searchSeed="g"1662        searchSeedNonce={1}1663        onSelectEntry={vi.fn()}1664        onSortOrderChange={vi.fn()}1665        onAdd={vi.fn()}1666        onClose={vi.fn()}1667      />1668    );16691670    await flushView();16711672    const search = container.querySelector(".peach-list-top .peach-search-input") as HTMLInputElement;1673    expect(search.value).toBe("g");1674    expect(document.activeElement).toBe(search);1675  });16761677  it("Import existing-vault add mode parses a file and batches entries into the vault", async () => {1678    parseImportSourceMock.mockResolvedValue(1679      sampleImportResult({1680        entries: [1681          {1682            type: "login",1683            title: "Imported site",1684            username: "imported-user",1685            password: "imported-pass",1686            url: "https://imported.test",1687          },1688        ],1689      })1690    );1691    sendMessageMock.mockImplementation(async (msg: unknown) => {1692      const type = (msg as { type?: string }).type;1693      if (type === "GET_ENTRIES") {1694        return {1695          ok: true,1696          data: [1697            sampleEntry({1698              id: "existing-1",1699              title: "Imported site",1700              username: "imported-user",1701              url: "https://imported.test",1702            }),1703          ],1704        };1705      }1706      if (type === "BATCH_ADD_ENTRIES") {1707        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1708      }1709      return { ok: true };1710    });1711    const onImport = vi.fn(async () => undefined);1712    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1713    await flushView();1714    sendMessageMock.mockClear();17151716    await selectImportFile(container);1717    findButton(container, "Import 1").click();1718    await flushView();17191720    expect(parseImportSourceMock).toHaveBeenCalledWith('{"export":"test"}');1721    expect(sendMessageMock).toHaveBeenCalledWith({1722      type: "BATCH_ADD_ENTRIES",1723      payload: {1724        entries: [1725          expect.objectContaining({1726            title: "Imported site",1727            username: "imported-user",1728            password: "imported-pass",1729            url: "https://imported.test",1730          }),1731        ],1732      },1733    });1734    expect(onImport).toHaveBeenCalled();1735    expect(container.textContent).toContain("1 entry appears to be duplicates");1736  });17371738  it("Import replace mode requires confirmation before clearing and replacing the vault", async () => {1739    parseImportSourceMock.mockResolvedValue(sampleImportResult());1740    sendMessageMock.mockImplementation(async (msg: unknown) => {1741      const type = (msg as { type?: string }).type;1742      if (type === "GET_ENTRIES") {1743        return { ok: true, data: [sampleEntry({ id: "existing-1" })] };1744      }1745      if (type === "CLEAR_VAULT_ENTRIES") {1746        return { ok: true };1747      }1748      if (type === "BATCH_ADD_ENTRIES") {1749        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1750      }1751      return { ok: true };1752    });1753    const onImport = vi.fn(async () => undefined);1754    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1755    await flushView();1756    sendMessageMock.mockClear();17571758    await selectImportFile(container);1759    (container.querySelector('input[value="replace"]') as HTMLInputElement).click();1760    await flushView();17611762    findButton(container, "Replace vault with 1").click();1763    await flushView();17641765    expect(sendMessageMock).not.toHaveBeenCalledWith(1766      expect.objectContaining({ type: "CLEAR_VAULT_ENTRIES" })1767    );1768    expect(container.textContent).toContain("Replace forever? This cannot be undone.");17691770    findButton(container, "Yes, replace forever").click();1771    await flushView();17721773    expect(sendMessageMock).toHaveBeenCalledWith({ type: "CLEAR_VAULT_ENTRIES" });1774    expect(sendMessageMock).toHaveBeenCalledWith({1775      type: "BATCH_ADD_ENTRIES",1776      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1777    });1778    expect(onImport).toHaveBeenCalled();1779  });17801781  it.each([true, false])("Import onboarding mode creates only after matching passwords (replacement %s)", async (replacesExistingVault) => {1782    parseImportSourceMock.mockResolvedValue(sampleImportResult());1783    sendMessageMock.mockImplementation(async (msg: unknown) => {1784      const type = (msg as { type?: string }).type;1785      if (type === "CREATE_VAULT") return { ok: true };1786      if (type === "BATCH_ADD_ENTRIES") {1787        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1788      }1789      return { ok: true };1790    });1791    const onImport = vi.fn(async () => undefined);1792    const container = mount(1793      <ImportView1794        mode="onboarding"1795        replacesExistingVault={replacesExistingVault}1796        onBack={vi.fn()}1797        onImport={onImport}1798      />1799    );18001801    await selectImportFile(container);18021803    const createButton = findButton(container, "Create vault + import 1");1804    expect(createButton.disabled).toBe(true);1805    expect(container.textContent?.includes("Restoring now replaces the locked local vault")).toBe(replacesExistingVault);1806    expect(container.textContent).toContain("Use at least 8 characters");18071808    const masterInput = container.querySelector(1809      'input[placeholder="new master password"]'1810    ) as HTMLInputElement;1811    const confirmInput = container.querySelector(1812      'input[placeholder="confirm master password"]'1813    ) as HTMLInputElement;1814    const revealButton = container.querySelector(1815      'button[aria-label="Show passwords"]'1816    ) as HTMLButtonElement;1817    expect(revealButton).toBeTruthy();1818    revealButton.click();1819    await flushView();1820    expect(masterInput.type).toBe("text");1821    expect(confirmInput.type).toBe("text");18221823    inputText(masterInput, "fresh-master-password");1824    inputText(confirmInput, "fresh-master-password");1825    await flushView();18261827    expect(createButton.disabled).toBe(false);1828    createButton.click();1829    await flushView();18301831    expect(sendMessageMock).toHaveBeenCalledWith({1832      type: "CREATE_VAULT",1833      payload: { password: "fresh-master-password", ...(replacesExistingVault ? { replacement: "warned-import" } : {}) },1834    });1835    expect(sendMessageMock).toHaveBeenCalledWith({1836      type: "BATCH_ADD_ENTRIES",1837      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1838    });1839    expect(onImport).toHaveBeenCalled();1840  });18411842});