contracts.test.tsx

41.6 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 requires current, new, and confirm passwords before enabling save", async () => {457    sendMessageMock.mockResolvedValue({ ok: true, data: null });458    const container = mount(459      <SettingsView460        entriesCount={1}461        breachMonitoring={true}462        lockOnClose={true}463        autoLockMinutes={5}464        trashRetentionDays={30}465        theme="dark"466        accentColor="peach"467        textSize="medium"468        reduceMotion={false}469        onBreachMonitoringChange={vi.fn()}470        onLockOnCloseChange={vi.fn()}471        onAutoLockMinutesChange={vi.fn()}472        onTrashRetentionChange={vi.fn()}473        onThemeChange={vi.fn()}474        onAccentChange={vi.fn()}475        onTextSizeChange={vi.fn()}476        onReduceMotionChange={vi.fn()}477        shortcuts={DEFAULT_BINDINGS}478        onShortcutsChange={vi.fn()}479        onBack={vi.fn()}480        onImport={vi.fn()}481        onExport={vi.fn()}482        onBreachCheckDone={vi.fn()}483      />484    );485    await flushView();486487    expect(container.querySelectorAll(".stk-card").length).toBe(7);488    // Settings now opens to card I (Peach Pro) — see koh save [f7a2710b3f67]489    // "open settings to card I (Peach Pro) instead of card II (Protection)".490    expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Peach Pro");491492    const changeButton = Array.from(container.querySelectorAll("button")).find(493      (candidate) => candidate.textContent?.trim() === "change"494    ) as HTMLButtonElement;495    changeButton.click();496    await flushView();497498    const saveButton = Array.from(container.querySelectorAll("button")).find(499      (candidate) => candidate.textContent?.trim() === "save new password"500    ) as HTMLButtonElement;501    expect(saveButton.disabled).toBe(true);502503    const inputs = container.querySelectorAll('input[type="password"]');504    inputText(inputs[0] as HTMLInputElement, "current-pass");505    inputText(inputs[1] as HTMLInputElement, "new-pass-12345");506    await flushView();507    expect(saveButton.disabled).toBe(true);508509    inputText(inputs[2] as HTMLInputElement, "new-pass-12345");510    await flushView();511    expect(saveButton.disabled).toBe(false);512  });513514  it("Settings feedback highlights the selected category and hides the form after submit", async () => {515    sendMessageMock.mockResolvedValue({ ok: true, data: null });516    const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => ({517      ok: true,518      json: async () => ({ success: true }),519    }));520    vi.stubGlobal("fetch", fetchMock);521522    const container = mount(523      <SettingsView524        entriesCount={1}525        breachMonitoring={true}526        lockOnClose={true}527        autoLockMinutes={5}528        trashRetentionDays={30}529        theme="dark"530        accentColor="peach"531        textSize="medium"532        reduceMotion={false}533        initialSection="feedback"534        onBreachMonitoringChange={vi.fn()}535        onLockOnCloseChange={vi.fn()}536        onAutoLockMinutesChange={vi.fn()}537        onTrashRetentionChange={vi.fn()}538        onThemeChange={vi.fn()}539        onAccentChange={vi.fn()}540        onTextSizeChange={vi.fn()}541        onReduceMotionChange={vi.fn()}542        shortcuts={DEFAULT_BINDINGS}543        onShortcutsChange={vi.fn()}544        onBack={vi.fn()}545        onImport={vi.fn()}546        onExport={vi.fn()}547        onBreachCheckDone={vi.fn()}548      />549    );550    await flushView();551552    const feedbackCard = container.querySelector('[data-settings-card-id="feedback"]') as HTMLElement;553    expect(feedbackCard.classList.contains("is-active")).toBe(true);554555    const categoryButtons = Array.from(container.querySelectorAll(".peach-feedback-chip")) as HTMLButtonElement[];556    const bugButton = categoryButtons.find((button) => button.textContent?.trim() === "Bug report")!;557    const featureButton = categoryButtons.find((button) => button.textContent?.trim() === "Feature request")!;558    expect(bugButton.getAttribute("aria-pressed")).toBe("true");559    expect(featureButton.getAttribute("aria-pressed")).toBe("false");560561    featureButton.click();562    await flushView();563564    expect(bugButton.getAttribute("aria-pressed")).toBe("false");565    expect(featureButton.getAttribute("aria-pressed")).toBe("true");566    expect(featureButton.classList.contains("is-active")).toBe(true);567568    inputText(569      container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,570      '<script>alert("xss")</script> Please make this easier to see & safer.'571    );572    const sendButton = Array.from(container.querySelectorAll("button")).find(573      (candidate) => candidate.textContent?.trim() === "Send"574    ) as HTMLButtonElement;575    sendButton.click();576577    await vi.waitFor(() => {578      expect(container.textContent).toContain("Thank you");579    });580581    const requestBody = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));582    expect(requestBody.subject).toContain("Feature request");583    expect(requestBody.message).toBe(584      "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt; Please make this easier to see &amp; safer."585    );586    expect(requestBody.message).not.toContain("<script>");587    expect(container.textContent).toContain("Someone will process it soon");588    expect(container.querySelector(".peach-feedback-textarea")).toBeNull();589    expect(container.querySelector(".peach-feedback-submit")).toBeNull();590  });591592  it("Settings keeps license activation on the full-screen celebration path", async () => {593    const onLicenseChange = vi.fn(async () => undefined);594    sendMessageMock.mockImplementation(async (msg: unknown) => {595      const type = (msg as { type?: string }).type;596      if (type === "GET_LICENSE") return { ok: true, data: { valid: false, plan: "free" } };597      if (type === "ACTIVATE_LICENSE") {598        return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };599      }600      if (type === "GET_ENTRIES") return { ok: true, data: [] };601      return { ok: true, data: null };602    });603604    const container = mount(<SettingsView {...settingsProps({ isPro: false, onLicenseChange })} />);605    await flushView();606607    inputText(608      container.querySelector(".peach-pro-key-inline-input") as HTMLInputElement,609      "PEACH-TEST-KEY",610    );611    const apply = container.querySelector(".peach-pro-key-apply") as HTMLButtonElement;612    apply.click();613614    await vi.waitFor(() => expect(onLicenseChange).toHaveBeenCalledTimes(1));615    expect(container.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(false);616    expect(container.textContent).not.toContain("thank you ✦");617  });618619  it("Settings Pro star and peach clicks use the same in-card replay path", async () => {620    sendMessageMock.mockImplementation(async (msg: unknown) => {621      const type = (msg as { type?: string }).type;622      if (type === "GET_LICENSE") return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };623      if (type === "GET_LICENSE_KEY") return { ok: true, data: "PEACH-TEST-KEY" };624      if (type === "GET_ENTRIES") return { ok: true, data: [] };625      return { ok: true, data: null };626    });627628    const onLicenseChangeFromStar = vi.fn();629    const starContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromStar })} />);630    await flushView();631    (starContainer.querySelector(".stk-card-icon--btn") as HTMLButtonElement).click();632    expect(starContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);633    expect(onLicenseChangeFromStar).not.toHaveBeenCalled();634635    const onLicenseChangeFromPeach = vi.fn();636    const peachContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromPeach })} />);637    await flushView();638    (peachContainer.querySelector(".peach-pro-active-mark-wrap") as HTMLButtonElement).click();639    expect(peachContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);640    expect(onLicenseChangeFromPeach).not.toHaveBeenCalled();641  });642643  it("Settings feedback does not transmit when Firefox data consent is denied", async () => {644    sendMessageMock.mockResolvedValue({ ok: true, data: null });645    const fetchMock = vi.fn();646    const requestMock = vi.fn(async () => false);647    vi.stubGlobal("fetch", fetchMock);648    vi.stubGlobal("browser", {649      permissions: {650        getAll: vi.fn(async () => ({ data_collection: [] })),651        request: requestMock,652      },653    });654655    const container = mount(656      <SettingsView657        entriesCount={1}658        breachMonitoring={true}659        lockOnClose={true}660        autoLockMinutes={5}661        trashRetentionDays={30}662        theme="dark"663        accentColor="peach"664        textSize="medium"665        reduceMotion={false}666        initialSection="feedback"667        onBreachMonitoringChange={vi.fn()}668        onLockOnCloseChange={vi.fn()}669        onAutoLockMinutesChange={vi.fn()}670        onTrashRetentionChange={vi.fn()}671        onThemeChange={vi.fn()}672        onAccentChange={vi.fn()}673        onTextSizeChange={vi.fn()}674        onReduceMotionChange={vi.fn()}675        shortcuts={DEFAULT_BINDINGS}676        onShortcutsChange={vi.fn()}677        onBack={vi.fn()}678        onImport={vi.fn()}679        onExport={vi.fn()}680        onBreachCheckDone={vi.fn()}681      />682    );683    await flushView();684685    inputText(686      container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,687      "Please improve the feedback flow."688    );689    const sendButton = Array.from(container.querySelectorAll("button")).find(690      (candidate) => candidate.textContent?.trim() === "Send"691    ) as HTMLButtonElement;692    sendButton.click();693694    await vi.waitFor(() => {695      expect(requestMock).toHaveBeenCalledWith({ data_collection: ["technicalAndInteraction"] });696    });697    expect(fetchMock).not.toHaveBeenCalled();698    expect(container.querySelector(".peach-feedback-textarea")).not.toBeNull();699  });700701  it("Settings sends CHANGE_PASSWORD and forwards auto-lock/theme changes through callbacks", async () => {702    sendMessageMock.mockImplementation(async (msg: unknown) => {703      const m = msg as { type: string };704      if (m.type === "GET_RECOVERY_WORDS") {705        return {706          ok: true,707          data: [708            "abandon", "ability", "able", "about", "above", "absent",709            "absorb", "abstract", "absurd", "abuse", "access", "accident",710          ],711        };712      }713      return { ok: true, data: null };714    });715    const onAutoLockMinutesChange = vi.fn();716    const onThemeChange = vi.fn();717    const container = mount(718      <SettingsView719        entriesCount={1}720        breachMonitoring={true}721        lockOnClose={true}722        autoLockMinutes={5}723        trashRetentionDays={30}724        theme="dark"725        accentColor="peach"726        textSize="medium"727        reduceMotion={false}728        onBreachMonitoringChange={vi.fn()}729        onLockOnCloseChange={vi.fn()}730        onAutoLockMinutesChange={onAutoLockMinutesChange}731        onTrashRetentionChange={vi.fn()}732        onThemeChange={onThemeChange}733        onAccentChange={vi.fn()}734        onTextSizeChange={vi.fn()}735        onReduceMotionChange={vi.fn()}736        shortcuts={DEFAULT_BINDINGS}737        onShortcutsChange={vi.fn()}738        onBack={vi.fn()}739        onImport={vi.fn()}740        onExport={vi.fn()}741        onBreachCheckDone={vi.fn()}742      />743    );744    await flushView();745    sendMessageMock.mockClear();746747    // ── Auto-lock + theme changes (before password change) ─────────────748    const selects = container.querySelectorAll("select");749    changeSelect(selects[0] as HTMLSelectElement, "15");750    expect(onAutoLockMinutesChange).toHaveBeenCalledWith(15);751752    const appearanceCard = container.querySelector('[data-settings-card-id="appearance"]') as HTMLElement;753    appearanceCard.click();754    await flushView();755    expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Appearance");756    const themeButton = Array.from(container.querySelectorAll("button")).find(757      (candidate) => candidate.textContent?.trim() === "Switch to light"758    ) as HTMLButtonElement;759    themeButton.click();760    expect(onThemeChange).toHaveBeenCalledWith("light");761762    // ── Password change → recovery words display ────────────────────────763    const protectionCard = container.querySelector('[data-settings-card-id="protection"]') as HTMLElement;764    protectionCard.click();765    await flushView();766767    const changeButton = Array.from(container.querySelectorAll("button")).find(768      (candidate) => candidate.textContent?.trim() === "change"769    ) as HTMLButtonElement;770    changeButton.click();771    await flushView();772773    const inputs = container.querySelectorAll('input[type="password"]');774    inputText(inputs[0] as HTMLInputElement, "current-pass");775    inputText(inputs[1] as HTMLInputElement, "new-password-123");776    inputText(inputs[2] as HTMLInputElement, "new-password-123");777    await flushView();778779    const saveButton = Array.from(container.querySelectorAll("button")).find(780      (candidate) => candidate.textContent?.trim() === "save new password"781    ) as HTMLButtonElement;782    saveButton.click();783    await flushView();784785    expect(sendMessageMock).toHaveBeenCalledWith({786      type: "CHANGE_PASSWORD",787      payload: {788        currentPassword: "current-pass",789        newPassword: "new-password-123",790      },791    });792793    // After a successful password change the recovery word display replaces settings.794    expect(container.textContent).toContain("save your recovery words");795    expect(sendMessageMock).toHaveBeenCalledWith({ type: "GET_RECOVERY_WORDS" });796  });797798  it("Entry copy actions send COPY and canary ping messages for password and username", async () => {799    sendMessageMock.mockResolvedValue({ ok: true });800    const container = mount(801      <EntryView802        entry={sampleEntry()}803        onDelete={vi.fn()}804        onFieldSaved={vi.fn(async () => undefined)}805      />806    );807808    const passwordButton = container.querySelector('button[aria-label="Copy password"]') as HTMLButtonElement;809    passwordButton.click();810    await flushView();811812    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {813      type: "COPY",814      payload: { text: "secret123", label: "password", alreadyWritten: false },815    });816    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {817      type: "FIRE_CANARY_PING",818      payload: {819        webhookUrl: "https://example.com/hook",820        entryTitle: "GitHub",821        trigger: "password_copied",822      },823    });824825    sendMessageMock.mockClear();826    const usernameButton = container.querySelector('button[aria-label="Copy username"]') as HTMLButtonElement;827    usernameButton.click();828    await flushView();829830    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {831      type: "COPY",832      payload: { text: "june", label: "username", alreadyWritten: false },833    });834    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {835      type: "FIRE_CANARY_PING",836      payload: {837        webhookUrl: "https://example.com/hook",838        entryTitle: "GitHub",839        trigger: "username_copied",840      },841    });842  });843844  it("Entry refuses to send an empty password update and copies TOTP through COPY", async () => {845    sendMessageMock.mockResolvedValue({ ok: true });846    const onFieldSaved = vi.fn(async () => undefined);847    const container = mount(848      <EntryView849        entry={sampleEntry()}850        onDelete={vi.fn()}851        onFieldSaved={onFieldSaved}852      />853    );854855    const passwordValue = container.querySelector(".peach-password-value") as HTMLSpanElement;856    passwordValue.click();857    await flushView();858859    const passwordInput = container.querySelector('input[placeholder="paste or type a password"]') as HTMLInputElement;860    inputText(passwordInput, "");861    await flushView();862863    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;864    saveButton.click();865    await flushView();866867    expect(sendMessageMock).not.toHaveBeenCalledWith(868      expect.objectContaining({ type: "UPDATE_ENTRY" })869    );870    expect(onFieldSaved).not.toHaveBeenCalled();871872    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;873    totpMain.click();874875    await vi.waitFor(() => {876      expect(sendMessageMock).toHaveBeenLastCalledWith({877        type: "COPY",878        payload: { text: "123456", label: "totp", alreadyWritten: false },879      });880    }, { timeout: 500 });881  });882883  it("Entry closes an unchanged inline editor when focus leaves it", async () => {884    sendMessageMock.mockResolvedValue({ ok: true });885    const container = mount(886      <EntryView887        entry={sampleEntry()}888        onDelete={vi.fn()}889        onFieldSaved={vi.fn(async () => undefined)}890      />891    );892893    const usernameValue = container.querySelector(".peach-field-value.peach-inline-clickable") as HTMLSpanElement;894    usernameValue.click();895    await flushView();896897    const usernameInput = container.querySelector(".peach-inline-input[autocomplete=\"off\"]") as HTMLInputElement;898    usernameInput.blur();899    await flushView();900901    expect(container.querySelector(".peach-inline-input[autocomplete=\"off\"]")).toBeNull();902    expect(sendMessageMock).not.toHaveBeenCalledWith(903      expect.objectContaining({ type: "UPDATE_ENTRY" })904    );905  });906907  it("Entry lets TOTP secrets be edited inline", async () => {908    sendMessageMock.mockResolvedValue({ ok: true });909    const onFieldSaved = vi.fn(async () => undefined);910    const container = mount(911      <EntryView912        entry={sampleEntry()}913        onDelete={vi.fn()}914        onFieldSaved={onFieldSaved}915      />916    );917918    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;919    totpMain.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));920    await flushView();921922    const totpInput = container.querySelector('input[placeholder="otpauth://... or base32 secret"]') as HTMLInputElement;923    inputText(totpInput, "otpauth://totp/Example?secret=NB2W45DFOIZA====&issuer=Peach");924    await flushView();925926    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;927    saveButton.click();928    await flushView();929930    expect(sendMessageMock).toHaveBeenCalledWith({931      type: "UPDATE_ENTRY",932      payload: {933        id: "entry-1",934        patch: { totp: "NB2W45DFOIZA====" },935      },936    });937    expect(onFieldSaved).toHaveBeenCalled();938  });939940  it("Vault seeds and focuses search when a search seed is provided", async () => {941    const container = mount(942      <VaultView943        entries={[sampleEntry(), sampleEntry({ id: "entry-2", title: "GitLab" })]}944        sortOrder="url-first"945        searchSeed="g"946        searchSeedNonce={1}947        onSelectEntry={vi.fn()}948        onSortOrderChange={vi.fn()}949        onAdd={vi.fn()}950        onClose={vi.fn()}951      />952    );953954    await flushView();955956    const search = container.querySelector(".peach-list-top .peach-search-input") as HTMLInputElement;957    expect(search.value).toBe("g");958    expect(document.activeElement).toBe(search);959  });960961  it("Import existing-vault add mode parses a file and batches entries into the vault", async () => {962    parseImportSourceMock.mockResolvedValue(963      sampleImportResult({964        entries: [965          {966            type: "login",967            title: "Imported site",968            username: "imported-user",969            password: "imported-pass",970            url: "https://imported.test",971          },972        ],973      })974    );975    sendMessageMock.mockImplementation(async (msg: unknown) => {976      const type = (msg as { type?: string }).type;977      if (type === "GET_ENTRIES") {978        return {979          ok: true,980          data: [981            sampleEntry({982              id: "existing-1",983              title: "Imported site",984              username: "imported-user",985              url: "https://imported.test",986            }),987          ],988        };989      }990      if (type === "BATCH_ADD_ENTRIES") {991        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };992      }993      return { ok: true };994    });995    const onImport = vi.fn(async () => undefined);996    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);997    await flushView();998    sendMessageMock.mockClear();9991000    await selectImportFile(container);1001    findButton(container, "Import 1").click();1002    await flushView();10031004    expect(parseImportSourceMock).toHaveBeenCalledWith('{"export":"test"}', undefined);1005    expect(sendMessageMock).toHaveBeenCalledWith({1006      type: "BATCH_ADD_ENTRIES",1007      payload: {1008        entries: [1009          expect.objectContaining({1010            title: "Imported site",1011            username: "imported-user",1012            password: "imported-pass",1013            url: "https://imported.test",1014          }),1015        ],1016      },1017    });1018    expect(onImport).toHaveBeenCalled();1019    expect(container.textContent).toContain("1 entry appears to be duplicates");1020  });10211022  it("Import replace mode requires confirmation before clearing and replacing the vault", async () => {1023    parseImportSourceMock.mockResolvedValue(sampleImportResult());1024    sendMessageMock.mockImplementation(async (msg: unknown) => {1025      const type = (msg as { type?: string }).type;1026      if (type === "GET_ENTRIES") {1027        return { ok: true, data: [sampleEntry({ id: "existing-1" })] };1028      }1029      if (type === "CLEAR_VAULT_ENTRIES") {1030        return { ok: true };1031      }1032      if (type === "BATCH_ADD_ENTRIES") {1033        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1034      }1035      return { ok: true };1036    });1037    const onImport = vi.fn(async () => undefined);1038    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1039    await flushView();1040    sendMessageMock.mockClear();10411042    await selectImportFile(container);1043    (container.querySelector('input[value="replace"]') as HTMLInputElement).click();1044    await flushView();10451046    findButton(container, "Replace vault with 1").click();1047    await flushView();10481049    expect(sendMessageMock).not.toHaveBeenCalledWith(1050      expect.objectContaining({ type: "CLEAR_VAULT_ENTRIES" })1051    );1052    expect(container.textContent).toContain("Replace forever? This cannot be undone.");10531054    findButton(container, "Yes, replace forever").click();1055    await flushView();10561057    expect(sendMessageMock).toHaveBeenCalledWith({ type: "CLEAR_VAULT_ENTRIES" });1058    expect(sendMessageMock).toHaveBeenCalledWith({1059      type: "BATCH_ADD_ENTRIES",1060      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1061    });1062    expect(onImport).toHaveBeenCalled();1063  });10641065  it("Import onboarding mode waits for a matching master password before creating a vault", async () => {1066    parseImportSourceMock.mockResolvedValue(sampleImportResult());1067    sendMessageMock.mockImplementation(async (msg: unknown) => {1068      const type = (msg as { type?: string }).type;1069      if (type === "CREATE_VAULT") return { ok: true };1070      if (type === "BATCH_ADD_ENTRIES") {1071        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1072      }1073      return { ok: true };1074    });1075    const onImport = vi.fn(async () => undefined);1076    const container = mount(1077      <ImportView1078        mode="onboarding"1079        replacesExistingVault={true}1080        onBack={vi.fn()}1081        onImport={onImport}1082      />1083    );10841085    await selectImportFile(container);10861087    const createButton = findButton(container, "Create vault + import 1");1088    expect(createButton.disabled).toBe(true);1089    expect(container.textContent).toContain("Restoring now replaces the locked local vault");1090    expect(container.textContent).toContain("Use at least 8 characters");10911092    const masterInput = container.querySelector(1093      'input[placeholder="new master password"]'1094    ) as HTMLInputElement;1095    const confirmInput = container.querySelector(1096      'input[placeholder="confirm master password"]'1097    ) as HTMLInputElement;1098    const revealButton = container.querySelector(1099      'button[aria-label="Show passwords"]'1100    ) as HTMLButtonElement;1101    expect(revealButton).toBeTruthy();1102    revealButton.click();1103    await flushView();1104    expect(masterInput.type).toBe("text");1105    expect(confirmInput.type).toBe("text");11061107    inputText(masterInput, "fresh-master-password");1108    inputText(confirmInput, "fresh-master-password");1109    await flushView();11101111    expect(createButton.disabled).toBe(false);1112    createButton.click();1113    await flushView();11141115    expect(sendMessageMock).toHaveBeenCalledWith({1116      type: "CREATE_VAULT",1117      payload: { password: "fresh-master-password" },1118    });1119    expect(sendMessageMock).toHaveBeenCalledWith({1120      type: "BATCH_ADD_ENTRIES",1121      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1122    });1123    expect(onImport).toHaveBeenCalled();1124  });11251126  it("Import encrypted backups reparse with the backup password before import", async () => {1127    parseImportSourceMock1128      .mockResolvedValueOnce(1129        sampleImportResult({1130          format: "peach-json",1131          label: "Peach encrypted backup",1132          entries: [],1133          totalItems: 0,1134          requiresPassword: true,1135        })1136      )1137      .mockResolvedValueOnce(1138        sampleImportResult({1139          format: "peach-json",1140          label: "Peach encrypted backup",1141        })1142      );1143    sendMessageMock.mockImplementation(async (msg: unknown) => {1144      const type = (msg as { type?: string }).type;1145      if (type === "GET_ENTRIES") return { ok: true, data: [] };1146      if (type === "BATCH_ADD_ENTRIES") {1147        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1148      }1149      return { ok: true };1150    });1151    const onImport = vi.fn(async () => undefined);1152    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1153    await flushView();1154    sendMessageMock.mockClear();11551156    await selectImportFile(container, '{"type":"peach-export"}');1157    const password = container.querySelector('input[placeholder="backup password"]') as HTMLInputElement;1158    inputText(password, "backup-passphrase");1159    pressEnter(password);1160    await flushView();1161    await flushView();11621163    expect(parseImportSourceMock).toHaveBeenNthCalledWith(1, '{"type":"peach-export"}', undefined);1164    expect(parseImportSourceMock).toHaveBeenNthCalledWith(2, '{"type":"peach-export"}', "backup-passphrase");11651166    findButton(container, "Import 1").click();1167    await flushView();11681169    expect(sendMessageMock).toHaveBeenCalledWith({1170      type: "BATCH_ADD_ENTRIES",1171      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1172    });1173    expect(onImport).toHaveBeenCalled();1174  });1175});