contracts.test.tsx

44.0 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 { RecoveryWordEntryView } from "./RecoveryWordEntry";16import { VaultView } from "./Vault";17import { changeSelect, flushView, inputText, pressEnter, renderView } from "./view-test-utils";1819const sendMessageMock = vi.fn<(msg: unknown) => Promise<unknown>>();20const triggerRingMock = vi.fn();21const triggerPipPulseMock = vi.fn();22const parseImportSourceMock = vi.fn<(raw: string, password?: string) => Promise<ImportParseResult>>();23const zxcvbnMock = vi.fn((value: string) => ({ score: value.length >= 16 ? 3 : 1 }));2425vi.mock("../App", () => ({26  sendMessage: (msg: unknown) => sendMessageMock(msg),27  triggerRing: () => triggerRingMock(),28  triggerPipPulse: () => triggerPipPulseMock(),29}));3031vi.mock("../../shared/import", () => ({32  parseImportSource: (...args: [string, string | undefined]) => parseImportSourceMock(...args),33}));3435vi.mock("../../shared/favicon", async (importOriginal) => {36  const actual = await importOriginal<typeof import("../../shared/favicon")>();37  return { ...actual, faviconUrl: () => null };38});3940vi.mock("../../crypto/totp", () => ({41  generateTOTP: () => ({ code: "123 456", remaining: 24 }),42  parseOtpauthURI: (value: string) =>43    value.startsWith("otpauth://")44      ? { secret: "NB2W45DFOIZA====", algorithm: "SHA1" as const }45      : null,46}));4748vi.mock("../components/GeneratorDrawer", () => ({49  GeneratorDrawer: () => null,50}));5152vi.mock("@zxcvbn-ts/core", () => ({53  zxcvbn: (value: string) => zxcvbnMock(value),54  zxcvbnOptions: { setOptions: vi.fn() },55}));56vi.mock("@zxcvbn-ts/language-common", () => ({57  adjacencyGraphs: {},58  dictionary: {},59}));60vi.mock("@zxcvbn-ts/language-en", () => ({61  translations: {},62  dictionary: {},63}));6465describe("popup contract tests", () => {66  const disposers: Array<() => void> = [];6768  beforeEach(() => {69    document.body.innerHTML = "";70    sendMessageMock.mockReset();71    triggerRingMock.mockReset();72    triggerPipPulseMock.mockReset();73    parseImportSourceMock.mockReset();74    zxcvbnMock.mockReset();75    zxcvbnMock.mockImplementation((value: string) => ({ score: value.length >= 16 ? 3 : 1 }));76    parseImportSourceMock.mockResolvedValue({77      format: "unknown",78      label: "Unknown format",79      entries: [],80      totalItems: 0,81      skippedItems: 0,82      requiresPassword: false,83    });8485    vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {86      return window.setTimeout(() => cb(0), 0) as unknown as number;87    });88    vi.stubGlobal("cancelAnimationFrame", (id: number) => window.clearTimeout(id));89    vi.stubGlobal("URL", {90      createObjectURL: vi.fn(() => "blob:peach-test"),91      revokeObjectURL: vi.fn(),92    });93    vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});9495    (globalThis as { chrome?: typeof chrome }).chrome = {96      runtime: {97        getManifest: () => ({ version: "1.4.47" }),98        onMessage: { addListener: vi.fn() },99      },100    } as unknown as typeof chrome;101  });102103  afterEach(() => {104    while (disposers.length > 0) {105      disposers.pop()?.();106    }107    vi.restoreAllMocks();108    vi.unstubAllGlobals();109  });110111  function mount(view: JSX.Element) {112    const mounted = renderView(view);113    disposers.push(mounted.dispose);114    return mounted.container;115  }116117  function sampleEntry(overrides: Partial<VaultEntry> = {}): VaultEntry {118    return {119      id: "entry-1",120      type: "login",121      title: "GitHub",122      username: "june",123      password: "secret123",124      url: "https://github.com",125      totp: "JBSWY3DPEHPK3PXP",126      canary: {127        webhookUrl: "https://example.com/hook",128      },129      createdAt: 1,130      modifiedAt: 1,131      ...overrides,132    };133  }134135  function sampleImportResult(136    overrides: Partial<ImportParseResult> = {}137  ): ImportParseResult {138    return {139      format: "csv",140      label: "CSV import",141      entries: [142        {143          type: "login",144          title: "Imported site",145          username: "imported-user",146          password: "imported-pass",147          url: "https://imported.test",148        },149      ],150      totalItems: 1,151      skippedItems: 0,152      requiresPassword: false,153      ...overrides,154    };155  }156157  function settingsProps(overrides: Partial<Parameters<typeof SettingsView>[0]> = {}) {158    return {159      entriesCount: 1,160      breachMonitoring: true,161      lockOnClose: true,162      autoLockMinutes: 5,163      trashRetentionDays: 30,164      theme: "dark" as const,165      accentColor: "peach" as const,166      textSize: "medium" as const,167      reduceMotion: false,168      onBreachMonitoringChange: vi.fn(),169      onLockOnCloseChange: vi.fn(),170      onAutoLockMinutesChange: vi.fn(),171      onTrashRetentionChange: vi.fn(),172      onThemeChange: vi.fn(),173      onAccentChange: vi.fn(),174      onTextSizeChange: vi.fn(),175      onReduceMotionChange: vi.fn(),176      shortcuts: DEFAULT_BINDINGS,177      onShortcutsChange: vi.fn(),178      onBack: vi.fn(),179      onImport: vi.fn(),180      onExport: vi.fn(),181      onBreachCheckDone: vi.fn(),182      ...overrides,183    };184  }185186  async function selectImportFile(187    container: HTMLElement,188    contents = '{"export":"test"}'189  ) {190    // The Import view now opens onto a menu — click into the file subview191    // before locating the file input. Idempotent: a second click won't re-fire192    // because the menu unmounts once the subview renders.193    const fileCard = findButton(container, "Choose file →");194    if (fileCard) {195      fileCard.click();196      await flushView();197    }198    const input = container.querySelector('input[type="file"]') as HTMLInputElement;199    const file = new File([contents], "import.json", { type: "application/json" });200    Object.defineProperty(input, "files", {201      configurable: true,202      value: [file],203    });204    input.dispatchEvent(new Event("change", { bubbles: true }));205    await flushView();206    await flushView();207  }208209  function findButton(container: HTMLElement, text: string): HTMLButtonElement {210    return Array.from(container.querySelectorAll("button")).find(211      (candidate) => candidate.textContent?.trim() === text212    ) as HTMLButtonElement;213  }214215  it("Lock sends UNLOCK with the entered passphrase", async () => {216    sendMessageMock.mockResolvedValue({ ok: true });217    const onUnlock = vi.fn(async () => undefined);218    const container = mount(<LockView hasVault={true} ready={true} onUnlock={onUnlock} />);219220    const password = container.querySelector("#unlock-password") as HTMLInputElement;221    inputText(password, "correct horse battery staple");222    (container.querySelector(".peach-lock-submit") as HTMLButtonElement).click();223    await flushView();224225    expect(sendMessageMock).toHaveBeenCalledWith({226      type: "UNLOCK",227      payload: { password: "correct horse battery staple" },228    });229    expect(onUnlock).toHaveBeenCalled();230  });231232  it("Lock keeps create-vault disabled for short passwords and weak passphrases", async () => {233    const container = mount(<LockView hasVault={false} ready={true} onUnlock={vi.fn()} />);234    const createButton = container.querySelector(".peach-lock-submit") as HTMLButtonElement;235    const password = container.querySelector("#master-password") as HTMLInputElement;236    const confirm = container.querySelector("#confirm-password") as HTMLInputElement;237238    inputText(password, "short");239    inputText(confirm, "short");240    await flushView();241    expect(createButton.disabled).toBe(true);242243    zxcvbnMock.mockImplementation(() => ({ score: 1 }));244    inputText(password, "weakweakweak");245    inputText(confirm, "weakweakweak");246    await flushView();247    expect(createButton.disabled).toBe(true);248  });249250  it("Lock sends CREATE_VAULT when the onboarding passphrase is strong enough", async () => {251    // Sequence: CREATE_VAULT → show recovery words → GET_RECOVERY_WORDS → user confirms → onUnlock252    sendMessageMock.mockImplementation(253      async (msg: unknown) => {254        const m = msg as { type: string; payload?: { password?: string } };255        if (m.type === "CREATE_VAULT") return { ok: true };256        if (m.type === "GET_RECOVERY_WORDS") {257          // Return 12 fake words — must pass findInvalidWords258          return {259            ok: true,260            data: [261              "abandon", "ability", "able", "about", "above", "absent",262              "absorb", "abstract", "absurd", "abuse", "access", "accident",263            ],264          };265        }266        return { ok: true };267      }268    );269    zxcvbnMock.mockImplementation(() => ({ score: 3 }));270    const onUnlock = vi.fn(async () => undefined);271    const container = mount(<LockView hasVault={false} ready={true} onUnlock={onUnlock} />);272273    const password = container.querySelector("#master-password") as HTMLInputElement;274    const confirm = container.querySelector("#confirm-password") as HTMLInputElement;275    const createButton = container.querySelector(".peach-lock-submit") as HTMLButtonElement;276277    inputText(password, "correct horse battery staple");278    inputText(confirm, "correct horse battery staple");279    await flushView();280    expect(createButton.disabled).toBe(false);281282    pressEnter(confirm);283    await flushView();284285    expect(sendMessageMock).toHaveBeenCalledWith({286      type: "CREATE_VAULT",287      payload: { password: "correct horse battery staple" },288    });289    // After CREATE_VAULT success, the recovery word display is shown.290    // onUnlock is NOT called yet — user must first confirm their recovery words.291    expect(onUnlock).not.toHaveBeenCalled();292  });293294  it("Recovery words flow submits the new master password and completes", async () => {295    sendMessageMock.mockImplementation(async (msg: unknown) => {296      const type = (msg as { type?: string }).type;297      if (type === "VALIDATE_RECOVERY_WORDS") {298        return { ok: true, data: { valid: true, invalid: [] } };299      }300      if (type === "RECOVER_WITH_WORDS") return { ok: true };301      return { ok: true };302    });303    const canvasContext = {304      clearRect: vi.fn(),305      fillText: vi.fn(),306      beginPath: vi.fn(),307      closePath: vi.fn(),308      arc: vi.fn(),309      fill: vi.fn(),310      stroke: vi.fn(),311      save: vi.fn(),312      restore: vi.fn(),313      translate: vi.fn(),314      rotate: vi.fn(),315      scale: vi.fn(),316      drawImage: vi.fn(),317      measureText: vi.fn(() => ({ width: 0 })),318      setTransform: vi.fn(),319      fillRect: vi.fn(),320      strokeRect: vi.fn(),321    } as unknown as CanvasRenderingContext2D;322    vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(() => canvasContext);323324    const onRecoveryComplete = vi.fn(async () => undefined);325    const container = mount(326      <RecoveryWordEntryView327        onCancel={vi.fn()}328        onRecoveryComplete={onRecoveryComplete}329      />330    );331332    const recoveryWords = WORD_LIST.slice(0, 12);333    for (let i = 0; i < recoveryWords.length; i++) {334      const input = container.querySelector(`#recovery-word-${i}`) as HTMLInputElement;335      inputText(input, recoveryWords[i]!);336    }337    await flushView();338339    findButton(container, "verify words").click();340    await flushView();341342    expect(container.textContent).toContain("new master password");343344    const newPassword = container.querySelector("#recovery-new-password") as HTMLInputElement;345    const confirmPassword = container.querySelector("#recovery-confirm-password") as HTMLInputElement;346    inputText(newPassword, "fresh-recovery-password");347    inputText(confirmPassword, "fresh-recovery-password");348    await flushView();349350    findButton(container, "recover vault").click();351    await flushView();352353    expect(sendMessageMock).toHaveBeenCalledWith({354      type: "RECOVER_WITH_WORDS",355      payload: {356        words: recoveryWords,357        newPassword: "fresh-recovery-password",358      },359    });360    expect(onRecoveryComplete).toHaveBeenCalled();361  });362363  it("Export menu surfaces both backup formats", async () => {364    const container = mount(<ExportView onBack={vi.fn()} />);365    await flushView();366367    expect(container.textContent).toContain("PeachScript");368    expect(container.textContent).toContain("CSV");369  });370371  it("Lock onboarding restore options include Peach Codex", async () => {372    const onOpenCodexRestore = vi.fn();373    const container = mount(374      <LockView375        hasVault={false}376        ready={true}377        onUnlock={vi.fn()}378        onOpenCodexRestore={onOpenCodexRestore}379      />380    );381382    const restoreButton = Array.from(container.querySelectorAll("button")).find(383      (candidate) => candidate.textContent?.includes("restore from backup")384    ) as HTMLButtonElement;385    restoreButton.click();386    await flushView();387388    expect(container.textContent).toContain("PeachScript");389    expect(container.textContent).toContain("Codex");390    expect(container.textContent).toContain("CSV");391392    const codexTab = Array.from(container.querySelectorAll("button")).find(393      (candidate) => candidate.textContent?.trim() === "Codex"394    ) as HTMLButtonElement;395    codexTab.click();396    await flushView();397398    expect(container.textContent).toContain("Restore from Peach Codex");399    expect(container.textContent).toContain("Scan printed Codex pages");400401    const openCodexButton = Array.from(container.querySelectorAll("button")).find(402      (candidate) => candidate.textContent?.trim() === "open Codex restore →"403    ) as HTMLButtonElement;404    openCodexButton.click();405406    expect(onOpenCodexRestore).toHaveBeenCalledTimes(1);407  });408409  it("HOLE 4: removing a device discloses that recovery words survive revocation", async () => {410    const device = {411      deviceId: "phone-1",412      deviceName: "June's Phone",413      deviceType: "android" as const,414      longTermPublicKeyHex: "a".repeat(64),415      signingPublicKeyHex: "b".repeat(64),416      pairedAt: 1,417      trustSource: "direct" as const,418    };419    sendMessageMock.mockImplementation(async (msg: unknown) => {420      const m = msg as { type: string };421      if (m.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [device] } };422      return { ok: true, data: null };423    });424425    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);426    for (let i = 0; i < 30; i++) await Promise.resolve();427428    const openSync = Array.from(container.querySelectorAll("button")).find((b) =>429      /sync/i.test(b.textContent ?? ""),430    );431    openSync?.click();432    for (let i = 0; i < 30; i++) await Promise.resolve();433434    const remove = Array.from(container.querySelectorAll("button")).find(435      (b) => (b.textContent ?? "").trim() === "remove",436    );437    expect(remove).toBeTruthy();438439    // Guard against a vacuous pass: the disclosure must not already be on440    // screen before the user asks to remove anything.441    expect(container.querySelector(".peach-unpair-confirm-note")).toBeNull();442443    remove!.click();444    for (let i = 0; i < 10; i++) await Promise.resolve();445446    // Revocation must never be presented as securing the vault against the447    // removed device — recovery words survive it and restore everything.448    const note = container.querySelector(".peach-unpair-confirm-note");449    expect(note).toBeTruthy();450    const text = note!.textContent ?? "";451    expect(text).toContain("master password");452    expect(text).toContain("recovery words");453    expect(text).toContain("future changes");454  });455456  it("Settings keeps the paired-device list and revokes through UNPAIR_DEVICE", async () => {457    const device = {458      deviceId: "phone-1",459      deviceName: "June's Phone",460      deviceType: "android" as const,461      longTermPublicKeyHex: "a".repeat(64),462      signingPublicKeyHex: "b".repeat(64),463      pairedAt: 1,464      trustSource: "direct" as const,465    };466    let paired: typeof device[] = [device];467    sendMessageMock.mockImplementation(async (msg: any) => {468      if (msg?.type === "LIST_PAIRED_DEVICES") {469        return { ok: true, data: { devices: [...paired] } };470      }471      if (msg?.type === "UNPAIR_DEVICE") {472        // Mirror the real handler: UNPAIR_DEVICE drops the row from the473        // registry. The next LIST_PAIRED_DEVICES must not see it.474        paired = paired.filter((d) => d.deviceId !== msg.payload?.deviceId);475        return { ok: true };476      }477      return { ok: true, data: null };478    });479480    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);481    for (let i = 0; i < 30; i++) await Promise.resolve();482    Array.from(container.querySelectorAll("button"))483      .find((b) => /sync/i.test(b.textContent ?? ""))484      ?.click();485    for (let i = 0; i < 30; i++) await Promise.resolve();486487    // The list itself: extracting the relay selector must not take the hub with it.488    expect(container.textContent).toContain("PAIRED DEVICES");489    expect(container.textContent).toContain("June's Phone");490    expect(container.textContent).toContain("Android");491492    Array.from(container.querySelectorAll("button"))493      .find((b) => (b.textContent ?? "").trim() === "remove")!494      .click();495    for (let i = 0; i < 10; i++) await Promise.resolve();496    const confirm = Array.from(497      container.querySelectorAll<HTMLButtonElement>(".peach-unpair-confirm button"),498    ).find((b) => (b.textContent ?? "").trim() === "remove");499    confirm!.click();500    for (let i = 0; i < 30; i++) await Promise.resolve();501502    expect(sendMessageMock).toHaveBeenCalledWith({503      type: "UNPAIR_DEVICE",504      payload: { deviceId: "phone-1" },505    });506    // The list must be refreshed and the device must be gone. The regression507    // we're guarding against: a Settings view that calls UNPAIR_DEVICE but508    // never refreshes LIST_PAIRED_DEVICES, so the row stays in the UI.509    expect(container.textContent).not.toContain("June's Phone");510    expect(container.textContent).not.toContain("PAIRED DEVICES");511  });512513  it("Settings requires current, new, and confirm passwords before enabling save", async () => {514    sendMessageMock.mockResolvedValue({ ok: true, data: null });515    const container = mount(516      <SettingsView517        entriesCount={1}518        breachMonitoring={true}519        lockOnClose={true}520        autoLockMinutes={5}521        trashRetentionDays={30}522        theme="dark"523        accentColor="peach"524        textSize="medium"525        reduceMotion={false}526        onBreachMonitoringChange={vi.fn()}527        onLockOnCloseChange={vi.fn()}528        onAutoLockMinutesChange={vi.fn()}529        onTrashRetentionChange={vi.fn()}530        onThemeChange={vi.fn()}531        onAccentChange={vi.fn()}532        onTextSizeChange={vi.fn()}533        onReduceMotionChange={vi.fn()}534        shortcuts={DEFAULT_BINDINGS}535        onShortcutsChange={vi.fn()}536        onBack={vi.fn()}537        onImport={vi.fn()}538        onExport={vi.fn()}539        onBreachCheckDone={vi.fn()}540      />541    );542    await flushView();543544    expect(container.querySelectorAll(".stk-card").length).toBe(7);545    // Settings now opens to card I (Peach Pro) — see koh save [f7a2710b3f67]546    // "open settings to card I (Peach Pro) instead of card II (Protection)".547    expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Peach Pro");548549    const changeButton = Array.from(container.querySelectorAll("button")).find(550      (candidate) => candidate.textContent?.trim() === "change"551    ) as HTMLButtonElement;552    changeButton.click();553    await flushView();554555    const saveButton = Array.from(container.querySelectorAll("button")).find(556      (candidate) => candidate.textContent?.trim() === "save new password"557    ) as HTMLButtonElement;558    expect(saveButton.disabled).toBe(true);559560    const inputs = container.querySelectorAll('input[type="password"]');561    inputText(inputs[0] as HTMLInputElement, "current-pass");562    inputText(inputs[1] as HTMLInputElement, "new-pass-12345");563    await flushView();564    expect(saveButton.disabled).toBe(true);565566    inputText(inputs[2] as HTMLInputElement, "new-pass-12345");567    await flushView();568    expect(saveButton.disabled).toBe(false);569  });570571  it("Settings feedback highlights the selected category and hides the form after submit", async () => {572    sendMessageMock.mockResolvedValue({ ok: true, data: null });573    const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => ({574      ok: true,575      json: async () => ({ success: true }),576    }));577    vi.stubGlobal("fetch", fetchMock);578579    const container = mount(580      <SettingsView581        entriesCount={1}582        breachMonitoring={true}583        lockOnClose={true}584        autoLockMinutes={5}585        trashRetentionDays={30}586        theme="dark"587        accentColor="peach"588        textSize="medium"589        reduceMotion={false}590        initialSection="feedback"591        onBreachMonitoringChange={vi.fn()}592        onLockOnCloseChange={vi.fn()}593        onAutoLockMinutesChange={vi.fn()}594        onTrashRetentionChange={vi.fn()}595        onThemeChange={vi.fn()}596        onAccentChange={vi.fn()}597        onTextSizeChange={vi.fn()}598        onReduceMotionChange={vi.fn()}599        shortcuts={DEFAULT_BINDINGS}600        onShortcutsChange={vi.fn()}601        onBack={vi.fn()}602        onImport={vi.fn()}603        onExport={vi.fn()}604        onBreachCheckDone={vi.fn()}605      />606    );607    await flushView();608609    const feedbackCard = container.querySelector('[data-settings-card-id="feedback"]') as HTMLElement;610    expect(feedbackCard.classList.contains("is-active")).toBe(true);611612    const categoryButtons = Array.from(container.querySelectorAll(".peach-feedback-chip")) as HTMLButtonElement[];613    const bugButton = categoryButtons.find((button) => button.textContent?.trim() === "Bug report")!;614    const featureButton = categoryButtons.find((button) => button.textContent?.trim() === "Feature request")!;615    expect(bugButton.getAttribute("aria-pressed")).toBe("true");616    expect(featureButton.getAttribute("aria-pressed")).toBe("false");617618    featureButton.click();619    await flushView();620621    expect(bugButton.getAttribute("aria-pressed")).toBe("false");622    expect(featureButton.getAttribute("aria-pressed")).toBe("true");623    expect(featureButton.classList.contains("is-active")).toBe(true);624625    inputText(626      container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,627      '<script>alert("xss")</script> Please make this easier to see & safer.'628    );629    const sendButton = Array.from(container.querySelectorAll("button")).find(630      (candidate) => candidate.textContent?.trim() === "Send"631    ) as HTMLButtonElement;632    sendButton.click();633634    await vi.waitFor(() => {635      expect(container.textContent).toContain("Thank you");636    });637638    const requestBody = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));639    expect(requestBody.subject).toContain("Feature request");640    expect(requestBody.message).toBe(641      "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt; Please make this easier to see &amp; safer."642    );643    expect(requestBody.message).not.toContain("<script>");644    expect(container.textContent).toContain("Someone will process it soon");645    expect(container.querySelector(".peach-feedback-textarea")).toBeNull();646    expect(container.querySelector(".peach-feedback-submit")).toBeNull();647  });648649  it("Settings keeps license activation on the full-screen celebration path", async () => {650    const onLicenseChange = vi.fn(async () => undefined);651    sendMessageMock.mockImplementation(async (msg: unknown) => {652      const type = (msg as { type?: string }).type;653      if (type === "GET_LICENSE") return { ok: true, data: { valid: false, plan: "free" } };654      if (type === "ACTIVATE_LICENSE") {655        return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };656      }657      if (type === "GET_ENTRIES") return { ok: true, data: [] };658      return { ok: true, data: null };659    });660661    const container = mount(<SettingsView {...settingsProps({ isPro: false, onLicenseChange })} />);662    await flushView();663664    inputText(665      container.querySelector(".peach-pro-key-inline-input") as HTMLInputElement,666      "PEACH-TEST-KEY",667    );668    const apply = container.querySelector(".peach-pro-key-apply") as HTMLButtonElement;669    apply.click();670671    await vi.waitFor(() => expect(onLicenseChange).toHaveBeenCalledTimes(1));672    expect(container.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(false);673    expect(container.textContent).not.toContain("thank you ✦");674  });675676  it("Settings Pro star and peach clicks use the same in-card replay path", async () => {677    sendMessageMock.mockImplementation(async (msg: unknown) => {678      const type = (msg as { type?: string }).type;679      if (type === "GET_LICENSE") return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };680      if (type === "GET_LICENSE_KEY") return { ok: true, data: "PEACH-TEST-KEY" };681      if (type === "GET_ENTRIES") return { ok: true, data: [] };682      return { ok: true, data: null };683    });684685    const onLicenseChangeFromStar = vi.fn();686    const starContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromStar })} />);687    await flushView();688    (starContainer.querySelector(".stk-card-icon--btn") as HTMLButtonElement).click();689    expect(starContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);690    expect(onLicenseChangeFromStar).not.toHaveBeenCalled();691692    const onLicenseChangeFromPeach = vi.fn();693    const peachContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromPeach })} />);694    await flushView();695    (peachContainer.querySelector(".peach-pro-active-mark-wrap") as HTMLButtonElement).click();696    expect(peachContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);697    expect(onLicenseChangeFromPeach).not.toHaveBeenCalled();698  });699700  it("Settings feedback does not transmit when Firefox data consent is denied", async () => {701    sendMessageMock.mockResolvedValue({ ok: true, data: null });702    const fetchMock = vi.fn();703    const requestMock = vi.fn(async () => false);704    vi.stubGlobal("fetch", fetchMock);705    vi.stubGlobal("browser", {706      permissions: {707        getAll: vi.fn(async () => ({ data_collection: [] })),708        request: requestMock,709      },710    });711712    const container = mount(713      <SettingsView714        entriesCount={1}715        breachMonitoring={true}716        lockOnClose={true}717        autoLockMinutes={5}718        trashRetentionDays={30}719        theme="dark"720        accentColor="peach"721        textSize="medium"722        reduceMotion={false}723        initialSection="feedback"724        onBreachMonitoringChange={vi.fn()}725        onLockOnCloseChange={vi.fn()}726        onAutoLockMinutesChange={vi.fn()}727        onTrashRetentionChange={vi.fn()}728        onThemeChange={vi.fn()}729        onAccentChange={vi.fn()}730        onTextSizeChange={vi.fn()}731        onReduceMotionChange={vi.fn()}732        shortcuts={DEFAULT_BINDINGS}733        onShortcutsChange={vi.fn()}734        onBack={vi.fn()}735        onImport={vi.fn()}736        onExport={vi.fn()}737        onBreachCheckDone={vi.fn()}738      />739    );740    await flushView();741742    inputText(743      container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,744      "Please improve the feedback flow."745    );746    const sendButton = Array.from(container.querySelectorAll("button")).find(747      (candidate) => candidate.textContent?.trim() === "Send"748    ) as HTMLButtonElement;749    sendButton.click();750751    await vi.waitFor(() => {752      expect(requestMock).toHaveBeenCalledWith({ data_collection: ["technicalAndInteraction"] });753    });754    expect(fetchMock).not.toHaveBeenCalled();755    expect(container.querySelector(".peach-feedback-textarea")).not.toBeNull();756  });757758  it("Settings sends CHANGE_PASSWORD and forwards auto-lock/theme changes through callbacks", async () => {759    sendMessageMock.mockImplementation(async (msg: unknown) => {760      const m = msg as { type: string };761      if (m.type === "GET_RECOVERY_WORDS") {762        return {763          ok: true,764          data: [765            "abandon", "ability", "able", "about", "above", "absent",766            "absorb", "abstract", "absurd", "abuse", "access", "accident",767          ],768        };769      }770      return { ok: true, data: null };771    });772    const onAutoLockMinutesChange = vi.fn();773    const onThemeChange = vi.fn();774    const container = mount(775      <SettingsView776        entriesCount={1}777        breachMonitoring={true}778        lockOnClose={true}779        autoLockMinutes={5}780        trashRetentionDays={30}781        theme="dark"782        accentColor="peach"783        textSize="medium"784        reduceMotion={false}785        onBreachMonitoringChange={vi.fn()}786        onLockOnCloseChange={vi.fn()}787        onAutoLockMinutesChange={onAutoLockMinutesChange}788        onTrashRetentionChange={vi.fn()}789        onThemeChange={onThemeChange}790        onAccentChange={vi.fn()}791        onTextSizeChange={vi.fn()}792        onReduceMotionChange={vi.fn()}793        shortcuts={DEFAULT_BINDINGS}794        onShortcutsChange={vi.fn()}795        onBack={vi.fn()}796        onImport={vi.fn()}797        onExport={vi.fn()}798        onBreachCheckDone={vi.fn()}799      />800    );801    await flushView();802    sendMessageMock.mockClear();803804    // ── Auto-lock + theme changes (before password change) ─────────────805    const selects = container.querySelectorAll("select");806    changeSelect(selects[0] as HTMLSelectElement, "15");807    expect(onAutoLockMinutesChange).toHaveBeenCalledWith(15);808809    const appearanceCard = container.querySelector('[data-settings-card-id="appearance"]') as HTMLElement;810    appearanceCard.click();811    await flushView();812    expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Appearance");813    const themeButton = Array.from(container.querySelectorAll("button")).find(814      (candidate) => candidate.textContent?.trim() === "Switch to light"815    ) as HTMLButtonElement;816    themeButton.click();817    expect(onThemeChange).toHaveBeenCalledWith("light");818819    // ── Password change → recovery words display ────────────────────────820    const protectionCard = container.querySelector('[data-settings-card-id="protection"]') as HTMLElement;821    protectionCard.click();822    await flushView();823824    const changeButton = Array.from(container.querySelectorAll("button")).find(825      (candidate) => candidate.textContent?.trim() === "change"826    ) as HTMLButtonElement;827    changeButton.click();828    await flushView();829830    const inputs = container.querySelectorAll('input[type="password"]');831    inputText(inputs[0] as HTMLInputElement, "current-pass");832    inputText(inputs[1] as HTMLInputElement, "new-password-123");833    inputText(inputs[2] as HTMLInputElement, "new-password-123");834    await flushView();835836    const saveButton = Array.from(container.querySelectorAll("button")).find(837      (candidate) => candidate.textContent?.trim() === "save new password"838    ) as HTMLButtonElement;839    saveButton.click();840    await flushView();841842    expect(sendMessageMock).toHaveBeenCalledWith({843      type: "CHANGE_PASSWORD",844      payload: {845        currentPassword: "current-pass",846        newPassword: "new-password-123",847      },848    });849850    // After a successful password change the recovery word display replaces settings.851    expect(container.textContent).toContain("save your recovery words");852    expect(sendMessageMock).toHaveBeenCalledWith({ type: "GET_RECOVERY_WORDS" });853  });854855  it("Entry copy actions send COPY and canary ping messages for password and username", async () => {856    sendMessageMock.mockResolvedValue({ ok: true });857    const container = mount(858      <EntryView859        entry={sampleEntry()}860        onDelete={vi.fn()}861        onFieldSaved={vi.fn(async () => undefined)}862      />863    );864865    const passwordButton = container.querySelector('button[aria-label="Copy password"]') as HTMLButtonElement;866    passwordButton.click();867    await flushView();868869    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {870      type: "COPY",871      payload: { text: "secret123", label: "password", alreadyWritten: false },872    });873    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {874      type: "FIRE_CANARY_PING",875      payload: {876        webhookUrl: "https://example.com/hook",877        entryTitle: "GitHub",878        trigger: "password_copied",879      },880    });881882    sendMessageMock.mockClear();883    const usernameButton = container.querySelector('button[aria-label="Copy username"]') as HTMLButtonElement;884    usernameButton.click();885    await flushView();886887    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {888      type: "COPY",889      payload: { text: "june", label: "username", alreadyWritten: false },890    });891    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {892      type: "FIRE_CANARY_PING",893      payload: {894        webhookUrl: "https://example.com/hook",895        entryTitle: "GitHub",896        trigger: "username_copied",897      },898    });899  });900901  it("Entry refuses to send an empty password update and copies TOTP through COPY", async () => {902    sendMessageMock.mockResolvedValue({ ok: true });903    const onFieldSaved = vi.fn(async () => undefined);904    const container = mount(905      <EntryView906        entry={sampleEntry()}907        onDelete={vi.fn()}908        onFieldSaved={onFieldSaved}909      />910    );911912    const passwordValue = container.querySelector(".peach-password-value") as HTMLSpanElement;913    passwordValue.click();914    await flushView();915916    const passwordInput = container.querySelector('input[placeholder="paste or type a password"]') as HTMLInputElement;917    inputText(passwordInput, "");918    await flushView();919920    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;921    saveButton.click();922    await flushView();923924    expect(sendMessageMock).not.toHaveBeenCalledWith(925      expect.objectContaining({ type: "UPDATE_ENTRY" })926    );927    expect(onFieldSaved).not.toHaveBeenCalled();928929    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;930    totpMain.click();931932    await vi.waitFor(() => {933      expect(sendMessageMock).toHaveBeenLastCalledWith({934        type: "COPY",935        payload: { text: "123456", label: "totp", alreadyWritten: false },936      });937    }, { timeout: 500 });938  });939940  it("Entry closes an unchanged inline editor when focus leaves it", async () => {941    sendMessageMock.mockResolvedValue({ ok: true });942    const container = mount(943      <EntryView944        entry={sampleEntry()}945        onDelete={vi.fn()}946        onFieldSaved={vi.fn(async () => undefined)}947      />948    );949950    const usernameValue = container.querySelector(".peach-field-value.peach-inline-clickable") as HTMLSpanElement;951    usernameValue.click();952    await flushView();953954    const usernameInput = container.querySelector(".peach-inline-input[autocomplete=\"off\"]") as HTMLInputElement;955    usernameInput.blur();956    await flushView();957958    expect(container.querySelector(".peach-inline-input[autocomplete=\"off\"]")).toBeNull();959    expect(sendMessageMock).not.toHaveBeenCalledWith(960      expect.objectContaining({ type: "UPDATE_ENTRY" })961    );962  });963964  it("Entry lets TOTP secrets be edited inline", async () => {965    sendMessageMock.mockResolvedValue({ ok: true });966    const onFieldSaved = vi.fn(async () => undefined);967    const container = mount(968      <EntryView969        entry={sampleEntry()}970        onDelete={vi.fn()}971        onFieldSaved={onFieldSaved}972      />973    );974975    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;976    totpMain.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));977    await flushView();978979    const totpInput = container.querySelector('input[placeholder="otpauth://... or base32 secret"]') as HTMLInputElement;980    inputText(totpInput, "otpauth://totp/Example?secret=NB2W45DFOIZA====&issuer=Peach");981    await flushView();982983    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;984    saveButton.click();985    await flushView();986987    expect(sendMessageMock).toHaveBeenCalledWith({988      type: "UPDATE_ENTRY",989      payload: {990        id: "entry-1",991        patch: { totp: "NB2W45DFOIZA====" },992      },993    });994    expect(onFieldSaved).toHaveBeenCalled();995  });996997  it("Vault seeds and focuses search when a search seed is provided", async () => {998    const container = mount(999      <VaultView1000        entries={[sampleEntry(), sampleEntry({ id: "entry-2", title: "GitLab" })]}1001        sortOrder="url-first"1002        searchSeed="g"1003        searchSeedNonce={1}1004        onSelectEntry={vi.fn()}1005        onSortOrderChange={vi.fn()}1006        onAdd={vi.fn()}1007        onClose={vi.fn()}1008      />1009    );10101011    await flushView();10121013    const search = container.querySelector(".peach-list-top .peach-search-input") as HTMLInputElement;1014    expect(search.value).toBe("g");1015    expect(document.activeElement).toBe(search);1016  });10171018  it("Import existing-vault add mode parses a file and batches entries into the vault", async () => {1019    parseImportSourceMock.mockResolvedValue(1020      sampleImportResult({1021        entries: [1022          {1023            type: "login",1024            title: "Imported site",1025            username: "imported-user",1026            password: "imported-pass",1027            url: "https://imported.test",1028          },1029        ],1030      })1031    );1032    sendMessageMock.mockImplementation(async (msg: unknown) => {1033      const type = (msg as { type?: string }).type;1034      if (type === "GET_ENTRIES") {1035        return {1036          ok: true,1037          data: [1038            sampleEntry({1039              id: "existing-1",1040              title: "Imported site",1041              username: "imported-user",1042              url: "https://imported.test",1043            }),1044          ],1045        };1046      }1047      if (type === "BATCH_ADD_ENTRIES") {1048        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1049      }1050      return { ok: true };1051    });1052    const onImport = vi.fn(async () => undefined);1053    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1054    await flushView();1055    sendMessageMock.mockClear();10561057    await selectImportFile(container);1058    findButton(container, "Import 1").click();1059    await flushView();10601061    expect(parseImportSourceMock).toHaveBeenCalledWith('{"export":"test"}', undefined);1062    expect(sendMessageMock).toHaveBeenCalledWith({1063      type: "BATCH_ADD_ENTRIES",1064      payload: {1065        entries: [1066          expect.objectContaining({1067            title: "Imported site",1068            username: "imported-user",1069            password: "imported-pass",1070            url: "https://imported.test",1071          }),1072        ],1073      },1074    });1075    expect(onImport).toHaveBeenCalled();1076    expect(container.textContent).toContain("1 entry appears to be duplicates");1077  });10781079  it("Import replace mode requires confirmation before clearing and replacing the vault", async () => {1080    parseImportSourceMock.mockResolvedValue(sampleImportResult());1081    sendMessageMock.mockImplementation(async (msg: unknown) => {1082      const type = (msg as { type?: string }).type;1083      if (type === "GET_ENTRIES") {1084        return { ok: true, data: [sampleEntry({ id: "existing-1" })] };1085      }1086      if (type === "CLEAR_VAULT_ENTRIES") {1087        return { ok: true };1088      }1089      if (type === "BATCH_ADD_ENTRIES") {1090        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1091      }1092      return { ok: true };1093    });1094    const onImport = vi.fn(async () => undefined);1095    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1096    await flushView();1097    sendMessageMock.mockClear();10981099    await selectImportFile(container);1100    (container.querySelector('input[value="replace"]') as HTMLInputElement).click();1101    await flushView();11021103    findButton(container, "Replace vault with 1").click();1104    await flushView();11051106    expect(sendMessageMock).not.toHaveBeenCalledWith(1107      expect.objectContaining({ type: "CLEAR_VAULT_ENTRIES" })1108    );1109    expect(container.textContent).toContain("Replace forever? This cannot be undone.");11101111    findButton(container, "Yes, replace forever").click();1112    await flushView();11131114    expect(sendMessageMock).toHaveBeenCalledWith({ type: "CLEAR_VAULT_ENTRIES" });1115    expect(sendMessageMock).toHaveBeenCalledWith({1116      type: "BATCH_ADD_ENTRIES",1117      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1118    });1119    expect(onImport).toHaveBeenCalled();1120  });11211122  it("Import onboarding mode waits for a matching master password before creating a vault", async () => {1123    parseImportSourceMock.mockResolvedValue(sampleImportResult());1124    sendMessageMock.mockImplementation(async (msg: unknown) => {1125      const type = (msg as { type?: string }).type;1126      if (type === "CREATE_VAULT") return { ok: true };1127      if (type === "BATCH_ADD_ENTRIES") {1128        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1129      }1130      return { ok: true };1131    });1132    const onImport = vi.fn(async () => undefined);1133    const container = mount(1134      <ImportView1135        mode="onboarding"1136        replacesExistingVault={true}1137        onBack={vi.fn()}1138        onImport={onImport}1139      />1140    );11411142    await selectImportFile(container);11431144    const createButton = findButton(container, "Create vault + import 1");1145    expect(createButton.disabled).toBe(true);1146    expect(container.textContent).toContain("Restoring now replaces the locked local vault");1147    expect(container.textContent).toContain("Use at least 8 characters");11481149    const masterInput = container.querySelector(1150      'input[placeholder="new master password"]'1151    ) as HTMLInputElement;1152    const confirmInput = container.querySelector(1153      'input[placeholder="confirm master password"]'1154    ) as HTMLInputElement;1155    const revealButton = container.querySelector(1156      'button[aria-label="Show passwords"]'1157    ) as HTMLButtonElement;1158    expect(revealButton).toBeTruthy();1159    revealButton.click();1160    await flushView();1161    expect(masterInput.type).toBe("text");1162    expect(confirmInput.type).toBe("text");11631164    inputText(masterInput, "fresh-master-password");1165    inputText(confirmInput, "fresh-master-password");1166    await flushView();11671168    expect(createButton.disabled).toBe(false);1169    createButton.click();1170    await flushView();11711172    expect(sendMessageMock).toHaveBeenCalledWith({1173      type: "CREATE_VAULT",1174      payload: { password: "fresh-master-password" },1175    });1176    expect(sendMessageMock).toHaveBeenCalledWith({1177      type: "BATCH_ADD_ENTRIES",1178      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1179    });1180    expect(onImport).toHaveBeenCalled();1181  });11821183  it("Import encrypted backups reparse with the backup password before import", async () => {1184    parseImportSourceMock1185      .mockResolvedValueOnce(1186        sampleImportResult({1187          format: "peach-json",1188          label: "Peach encrypted backup",1189          entries: [],1190          totalItems: 0,1191          requiresPassword: true,1192        })1193      )1194      .mockResolvedValueOnce(1195        sampleImportResult({1196          format: "peach-json",1197          label: "Peach encrypted backup",1198        })1199      );1200    sendMessageMock.mockImplementation(async (msg: unknown) => {1201      const type = (msg as { type?: string }).type;1202      if (type === "GET_ENTRIES") return { ok: true, data: [] };1203      if (type === "BATCH_ADD_ENTRIES") {1204        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1205      }1206      return { ok: true };1207    });1208    const onImport = vi.fn(async () => undefined);1209    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1210    await flushView();1211    sendMessageMock.mockClear();12121213    await selectImportFile(container, '{"type":"peach-export"}');1214    const password = container.querySelector('input[placeholder="backup password"]') as HTMLInputElement;1215    inputText(password, "backup-passphrase");1216    pressEnter(password);1217    await flushView();1218    await flushView();12191220    expect(parseImportSourceMock).toHaveBeenNthCalledWith(1, '{"type":"peach-export"}', undefined);1221    expect(parseImportSourceMock).toHaveBeenNthCalledWith(2, '{"type":"peach-export"}', "backup-passphrase");12221223    findButton(container, "Import 1").click();1224    await flushView();12251226    expect(sendMessageMock).toHaveBeenCalledWith({1227      type: "BATCH_ADD_ENTRIES",1228      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1229    });1230    expect(onImport).toHaveBeenCalled();1231  });1232});