contracts.test.tsx

43.4 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    sendMessageMock.mockImplementation(async (msg: unknown) => {467      const m = msg as { type: string };468      if (m.type === "LIST_PAIRED_DEVICES") return { ok: true, data: { devices: [device] } };469      return { ok: true, data: null };470    });471472    const container = mount(<SettingsView {...settingsProps({ isPro: true })} />);473    for (let i = 0; i < 30; i++) await Promise.resolve();474    Array.from(container.querySelectorAll("button"))475      .find((b) => /sync/i.test(b.textContent ?? ""))476      ?.click();477    for (let i = 0; i < 30; i++) await Promise.resolve();478479    // The list itself: extracting the relay selector must not take the hub with it.480    expect(container.textContent).toContain("PAIRED DEVICES");481    expect(container.textContent).toContain("June's Phone");482    expect(container.textContent).toContain("Android");483484    Array.from(container.querySelectorAll("button"))485      .find((b) => (b.textContent ?? "").trim() === "remove")!486      .click();487    for (let i = 0; i < 10; i++) await Promise.resolve();488    const confirm = Array.from(489      container.querySelectorAll<HTMLButtonElement>(".peach-unpair-confirm button"),490    ).find((b) => (b.textContent ?? "").trim() === "remove");491    confirm!.click();492    for (let i = 0; i < 20; i++) await Promise.resolve();493494    expect(sendMessageMock).toHaveBeenCalledWith({495      type: "UNPAIR_DEVICE",496      payload: { deviceId: "phone-1" },497    });498  });499500  it("Settings requires current, new, and confirm passwords before enabling save", async () => {501    sendMessageMock.mockResolvedValue({ ok: true, data: null });502    const container = mount(503      <SettingsView504        entriesCount={1}505        breachMonitoring={true}506        lockOnClose={true}507        autoLockMinutes={5}508        trashRetentionDays={30}509        theme="dark"510        accentColor="peach"511        textSize="medium"512        reduceMotion={false}513        onBreachMonitoringChange={vi.fn()}514        onLockOnCloseChange={vi.fn()}515        onAutoLockMinutesChange={vi.fn()}516        onTrashRetentionChange={vi.fn()}517        onThemeChange={vi.fn()}518        onAccentChange={vi.fn()}519        onTextSizeChange={vi.fn()}520        onReduceMotionChange={vi.fn()}521        shortcuts={DEFAULT_BINDINGS}522        onShortcutsChange={vi.fn()}523        onBack={vi.fn()}524        onImport={vi.fn()}525        onExport={vi.fn()}526        onBreachCheckDone={vi.fn()}527      />528    );529    await flushView();530531    expect(container.querySelectorAll(".stk-card").length).toBe(7);532    // Settings now opens to card I (Peach Pro) — see koh save [f7a2710b3f67]533    // "open settings to card I (Peach Pro) instead of card II (Protection)".534    expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Peach Pro");535536    const changeButton = Array.from(container.querySelectorAll("button")).find(537      (candidate) => candidate.textContent?.trim() === "change"538    ) as HTMLButtonElement;539    changeButton.click();540    await flushView();541542    const saveButton = Array.from(container.querySelectorAll("button")).find(543      (candidate) => candidate.textContent?.trim() === "save new password"544    ) as HTMLButtonElement;545    expect(saveButton.disabled).toBe(true);546547    const inputs = container.querySelectorAll('input[type="password"]');548    inputText(inputs[0] as HTMLInputElement, "current-pass");549    inputText(inputs[1] as HTMLInputElement, "new-pass-12345");550    await flushView();551    expect(saveButton.disabled).toBe(true);552553    inputText(inputs[2] as HTMLInputElement, "new-pass-12345");554    await flushView();555    expect(saveButton.disabled).toBe(false);556  });557558  it("Settings feedback highlights the selected category and hides the form after submit", async () => {559    sendMessageMock.mockResolvedValue({ ok: true, data: null });560    const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => ({561      ok: true,562      json: async () => ({ success: true }),563    }));564    vi.stubGlobal("fetch", fetchMock);565566    const container = mount(567      <SettingsView568        entriesCount={1}569        breachMonitoring={true}570        lockOnClose={true}571        autoLockMinutes={5}572        trashRetentionDays={30}573        theme="dark"574        accentColor="peach"575        textSize="medium"576        reduceMotion={false}577        initialSection="feedback"578        onBreachMonitoringChange={vi.fn()}579        onLockOnCloseChange={vi.fn()}580        onAutoLockMinutesChange={vi.fn()}581        onTrashRetentionChange={vi.fn()}582        onThemeChange={vi.fn()}583        onAccentChange={vi.fn()}584        onTextSizeChange={vi.fn()}585        onReduceMotionChange={vi.fn()}586        shortcuts={DEFAULT_BINDINGS}587        onShortcutsChange={vi.fn()}588        onBack={vi.fn()}589        onImport={vi.fn()}590        onExport={vi.fn()}591        onBreachCheckDone={vi.fn()}592      />593    );594    await flushView();595596    const feedbackCard = container.querySelector('[data-settings-card-id="feedback"]') as HTMLElement;597    expect(feedbackCard.classList.contains("is-active")).toBe(true);598599    const categoryButtons = Array.from(container.querySelectorAll(".peach-feedback-chip")) as HTMLButtonElement[];600    const bugButton = categoryButtons.find((button) => button.textContent?.trim() === "Bug report")!;601    const featureButton = categoryButtons.find((button) => button.textContent?.trim() === "Feature request")!;602    expect(bugButton.getAttribute("aria-pressed")).toBe("true");603    expect(featureButton.getAttribute("aria-pressed")).toBe("false");604605    featureButton.click();606    await flushView();607608    expect(bugButton.getAttribute("aria-pressed")).toBe("false");609    expect(featureButton.getAttribute("aria-pressed")).toBe("true");610    expect(featureButton.classList.contains("is-active")).toBe(true);611612    inputText(613      container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,614      '<script>alert("xss")</script> Please make this easier to see & safer.'615    );616    const sendButton = Array.from(container.querySelectorAll("button")).find(617      (candidate) => candidate.textContent?.trim() === "Send"618    ) as HTMLButtonElement;619    sendButton.click();620621    await vi.waitFor(() => {622      expect(container.textContent).toContain("Thank you");623    });624625    const requestBody = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));626    expect(requestBody.subject).toContain("Feature request");627    expect(requestBody.message).toBe(628      "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt; Please make this easier to see &amp; safer."629    );630    expect(requestBody.message).not.toContain("<script>");631    expect(container.textContent).toContain("Someone will process it soon");632    expect(container.querySelector(".peach-feedback-textarea")).toBeNull();633    expect(container.querySelector(".peach-feedback-submit")).toBeNull();634  });635636  it("Settings keeps license activation on the full-screen celebration path", async () => {637    const onLicenseChange = vi.fn(async () => undefined);638    sendMessageMock.mockImplementation(async (msg: unknown) => {639      const type = (msg as { type?: string }).type;640      if (type === "GET_LICENSE") return { ok: true, data: { valid: false, plan: "free" } };641      if (type === "ACTIVATE_LICENSE") {642        return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };643      }644      if (type === "GET_ENTRIES") return { ok: true, data: [] };645      return { ok: true, data: null };646    });647648    const container = mount(<SettingsView {...settingsProps({ isPro: false, onLicenseChange })} />);649    await flushView();650651    inputText(652      container.querySelector(".peach-pro-key-inline-input") as HTMLInputElement,653      "PEACH-TEST-KEY",654    );655    const apply = container.querySelector(".peach-pro-key-apply") as HTMLButtonElement;656    apply.click();657658    await vi.waitFor(() => expect(onLicenseChange).toHaveBeenCalledTimes(1));659    expect(container.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(false);660    expect(container.textContent).not.toContain("thank you ✦");661  });662663  it("Settings Pro star and peach clicks use the same in-card replay path", async () => {664    sendMessageMock.mockImplementation(async (msg: unknown) => {665      const type = (msg as { type?: string }).type;666      if (type === "GET_LICENSE") return { ok: true, data: { valid: true, plan: "pro", issued: "2026-05-21" } };667      if (type === "GET_LICENSE_KEY") return { ok: true, data: "PEACH-TEST-KEY" };668      if (type === "GET_ENTRIES") return { ok: true, data: [] };669      return { ok: true, data: null };670    });671672    const onLicenseChangeFromStar = vi.fn();673    const starContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromStar })} />);674    await flushView();675    (starContainer.querySelector(".stk-card-icon--btn") as HTMLButtonElement).click();676    expect(starContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);677    expect(onLicenseChangeFromStar).not.toHaveBeenCalled();678679    const onLicenseChangeFromPeach = vi.fn();680    const peachContainer = mount(<SettingsView {...settingsProps({ isPro: true, onLicenseChange: onLicenseChangeFromPeach })} />);681    await flushView();682    (peachContainer.querySelector(".peach-pro-active-mark-wrap") as HTMLButtonElement).click();683    expect(peachContainer.querySelector(".stk-deck")?.classList.contains("is-fanning")).toBe(true);684    expect(onLicenseChangeFromPeach).not.toHaveBeenCalled();685  });686687  it("Settings feedback does not transmit when Firefox data consent is denied", async () => {688    sendMessageMock.mockResolvedValue({ ok: true, data: null });689    const fetchMock = vi.fn();690    const requestMock = vi.fn(async () => false);691    vi.stubGlobal("fetch", fetchMock);692    vi.stubGlobal("browser", {693      permissions: {694        getAll: vi.fn(async () => ({ data_collection: [] })),695        request: requestMock,696      },697    });698699    const container = mount(700      <SettingsView701        entriesCount={1}702        breachMonitoring={true}703        lockOnClose={true}704        autoLockMinutes={5}705        trashRetentionDays={30}706        theme="dark"707        accentColor="peach"708        textSize="medium"709        reduceMotion={false}710        initialSection="feedback"711        onBreachMonitoringChange={vi.fn()}712        onLockOnCloseChange={vi.fn()}713        onAutoLockMinutesChange={vi.fn()}714        onTrashRetentionChange={vi.fn()}715        onThemeChange={vi.fn()}716        onAccentChange={vi.fn()}717        onTextSizeChange={vi.fn()}718        onReduceMotionChange={vi.fn()}719        shortcuts={DEFAULT_BINDINGS}720        onShortcutsChange={vi.fn()}721        onBack={vi.fn()}722        onImport={vi.fn()}723        onExport={vi.fn()}724        onBreachCheckDone={vi.fn()}725      />726    );727    await flushView();728729    inputText(730      container.querySelector(".peach-feedback-textarea") as HTMLTextAreaElement,731      "Please improve the feedback flow."732    );733    const sendButton = Array.from(container.querySelectorAll("button")).find(734      (candidate) => candidate.textContent?.trim() === "Send"735    ) as HTMLButtonElement;736    sendButton.click();737738    await vi.waitFor(() => {739      expect(requestMock).toHaveBeenCalledWith({ data_collection: ["technicalAndInteraction"] });740    });741    expect(fetchMock).not.toHaveBeenCalled();742    expect(container.querySelector(".peach-feedback-textarea")).not.toBeNull();743  });744745  it("Settings sends CHANGE_PASSWORD and forwards auto-lock/theme changes through callbacks", async () => {746    sendMessageMock.mockImplementation(async (msg: unknown) => {747      const m = msg as { type: string };748      if (m.type === "GET_RECOVERY_WORDS") {749        return {750          ok: true,751          data: [752            "abandon", "ability", "able", "about", "above", "absent",753            "absorb", "abstract", "absurd", "abuse", "access", "accident",754          ],755        };756      }757      return { ok: true, data: null };758    });759    const onAutoLockMinutesChange = vi.fn();760    const onThemeChange = vi.fn();761    const container = mount(762      <SettingsView763        entriesCount={1}764        breachMonitoring={true}765        lockOnClose={true}766        autoLockMinutes={5}767        trashRetentionDays={30}768        theme="dark"769        accentColor="peach"770        textSize="medium"771        reduceMotion={false}772        onBreachMonitoringChange={vi.fn()}773        onLockOnCloseChange={vi.fn()}774        onAutoLockMinutesChange={onAutoLockMinutesChange}775        onTrashRetentionChange={vi.fn()}776        onThemeChange={onThemeChange}777        onAccentChange={vi.fn()}778        onTextSizeChange={vi.fn()}779        onReduceMotionChange={vi.fn()}780        shortcuts={DEFAULT_BINDINGS}781        onShortcutsChange={vi.fn()}782        onBack={vi.fn()}783        onImport={vi.fn()}784        onExport={vi.fn()}785        onBreachCheckDone={vi.fn()}786      />787    );788    await flushView();789    sendMessageMock.mockClear();790791    // ── Auto-lock + theme changes (before password change) ─────────────792    const selects = container.querySelectorAll("select");793    changeSelect(selects[0] as HTMLSelectElement, "15");794    expect(onAutoLockMinutesChange).toHaveBeenCalledWith(15);795796    const appearanceCard = container.querySelector('[data-settings-card-id="appearance"]') as HTMLElement;797    appearanceCard.click();798    await flushView();799    expect(container.querySelector(".stk-card.is-active")?.textContent).toContain("Appearance");800    const themeButton = Array.from(container.querySelectorAll("button")).find(801      (candidate) => candidate.textContent?.trim() === "Switch to light"802    ) as HTMLButtonElement;803    themeButton.click();804    expect(onThemeChange).toHaveBeenCalledWith("light");805806    // ── Password change → recovery words display ────────────────────────807    const protectionCard = container.querySelector('[data-settings-card-id="protection"]') as HTMLElement;808    protectionCard.click();809    await flushView();810811    const changeButton = Array.from(container.querySelectorAll("button")).find(812      (candidate) => candidate.textContent?.trim() === "change"813    ) as HTMLButtonElement;814    changeButton.click();815    await flushView();816817    const inputs = container.querySelectorAll('input[type="password"]');818    inputText(inputs[0] as HTMLInputElement, "current-pass");819    inputText(inputs[1] as HTMLInputElement, "new-password-123");820    inputText(inputs[2] as HTMLInputElement, "new-password-123");821    await flushView();822823    const saveButton = Array.from(container.querySelectorAll("button")).find(824      (candidate) => candidate.textContent?.trim() === "save new password"825    ) as HTMLButtonElement;826    saveButton.click();827    await flushView();828829    expect(sendMessageMock).toHaveBeenCalledWith({830      type: "CHANGE_PASSWORD",831      payload: {832        currentPassword: "current-pass",833        newPassword: "new-password-123",834      },835    });836837    // After a successful password change the recovery word display replaces settings.838    expect(container.textContent).toContain("save your recovery words");839    expect(sendMessageMock).toHaveBeenCalledWith({ type: "GET_RECOVERY_WORDS" });840  });841842  it("Entry copy actions send COPY and canary ping messages for password and username", async () => {843    sendMessageMock.mockResolvedValue({ ok: true });844    const container = mount(845      <EntryView846        entry={sampleEntry()}847        onDelete={vi.fn()}848        onFieldSaved={vi.fn(async () => undefined)}849      />850    );851852    const passwordButton = container.querySelector('button[aria-label="Copy password"]') as HTMLButtonElement;853    passwordButton.click();854    await flushView();855856    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {857      type: "COPY",858      payload: { text: "secret123", label: "password", alreadyWritten: false },859    });860    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {861      type: "FIRE_CANARY_PING",862      payload: {863        webhookUrl: "https://example.com/hook",864        entryTitle: "GitHub",865        trigger: "password_copied",866      },867    });868869    sendMessageMock.mockClear();870    const usernameButton = container.querySelector('button[aria-label="Copy username"]') as HTMLButtonElement;871    usernameButton.click();872    await flushView();873874    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {875      type: "COPY",876      payload: { text: "june", label: "username", alreadyWritten: false },877    });878    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {879      type: "FIRE_CANARY_PING",880      payload: {881        webhookUrl: "https://example.com/hook",882        entryTitle: "GitHub",883        trigger: "username_copied",884      },885    });886  });887888  it("Entry refuses to send an empty password update and copies TOTP through COPY", async () => {889    sendMessageMock.mockResolvedValue({ ok: true });890    const onFieldSaved = vi.fn(async () => undefined);891    const container = mount(892      <EntryView893        entry={sampleEntry()}894        onDelete={vi.fn()}895        onFieldSaved={onFieldSaved}896      />897    );898899    const passwordValue = container.querySelector(".peach-password-value") as HTMLSpanElement;900    passwordValue.click();901    await flushView();902903    const passwordInput = container.querySelector('input[placeholder="paste or type a password"]') as HTMLInputElement;904    inputText(passwordInput, "");905    await flushView();906907    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;908    saveButton.click();909    await flushView();910911    expect(sendMessageMock).not.toHaveBeenCalledWith(912      expect.objectContaining({ type: "UPDATE_ENTRY" })913    );914    expect(onFieldSaved).not.toHaveBeenCalled();915916    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;917    totpMain.click();918919    await vi.waitFor(() => {920      expect(sendMessageMock).toHaveBeenLastCalledWith({921        type: "COPY",922        payload: { text: "123456", label: "totp", alreadyWritten: false },923      });924    }, { timeout: 500 });925  });926927  it("Entry closes an unchanged inline editor when focus leaves it", async () => {928    sendMessageMock.mockResolvedValue({ ok: true });929    const container = mount(930      <EntryView931        entry={sampleEntry()}932        onDelete={vi.fn()}933        onFieldSaved={vi.fn(async () => undefined)}934      />935    );936937    const usernameValue = container.querySelector(".peach-field-value.peach-inline-clickable") as HTMLSpanElement;938    usernameValue.click();939    await flushView();940941    const usernameInput = container.querySelector(".peach-inline-input[autocomplete=\"off\"]") as HTMLInputElement;942    usernameInput.blur();943    await flushView();944945    expect(container.querySelector(".peach-inline-input[autocomplete=\"off\"]")).toBeNull();946    expect(sendMessageMock).not.toHaveBeenCalledWith(947      expect.objectContaining({ type: "UPDATE_ENTRY" })948    );949  });950951  it("Entry lets TOTP secrets be edited inline", async () => {952    sendMessageMock.mockResolvedValue({ ok: true });953    const onFieldSaved = vi.fn(async () => undefined);954    const container = mount(955      <EntryView956        entry={sampleEntry()}957        onDelete={vi.fn()}958        onFieldSaved={onFieldSaved}959      />960    );961962    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;963    totpMain.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));964    await flushView();965966    const totpInput = container.querySelector('input[placeholder="otpauth://... or base32 secret"]') as HTMLInputElement;967    inputText(totpInput, "otpauth://totp/Example?secret=NB2W45DFOIZA====&issuer=Peach");968    await flushView();969970    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;971    saveButton.click();972    await flushView();973974    expect(sendMessageMock).toHaveBeenCalledWith({975      type: "UPDATE_ENTRY",976      payload: {977        id: "entry-1",978        patch: { totp: "NB2W45DFOIZA====" },979      },980    });981    expect(onFieldSaved).toHaveBeenCalled();982  });983984  it("Vault seeds and focuses search when a search seed is provided", async () => {985    const container = mount(986      <VaultView987        entries={[sampleEntry(), sampleEntry({ id: "entry-2", title: "GitLab" })]}988        sortOrder="url-first"989        searchSeed="g"990        searchSeedNonce={1}991        onSelectEntry={vi.fn()}992        onSortOrderChange={vi.fn()}993        onAdd={vi.fn()}994        onClose={vi.fn()}995      />996    );997998    await flushView();9991000    const search = container.querySelector(".peach-list-top .peach-search-input") as HTMLInputElement;1001    expect(search.value).toBe("g");1002    expect(document.activeElement).toBe(search);1003  });10041005  it("Import existing-vault add mode parses a file and batches entries into the vault", async () => {1006    parseImportSourceMock.mockResolvedValue(1007      sampleImportResult({1008        entries: [1009          {1010            type: "login",1011            title: "Imported site",1012            username: "imported-user",1013            password: "imported-pass",1014            url: "https://imported.test",1015          },1016        ],1017      })1018    );1019    sendMessageMock.mockImplementation(async (msg: unknown) => {1020      const type = (msg as { type?: string }).type;1021      if (type === "GET_ENTRIES") {1022        return {1023          ok: true,1024          data: [1025            sampleEntry({1026              id: "existing-1",1027              title: "Imported site",1028              username: "imported-user",1029              url: "https://imported.test",1030            }),1031          ],1032        };1033      }1034      if (type === "BATCH_ADD_ENTRIES") {1035        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1036      }1037      return { ok: true };1038    });1039    const onImport = vi.fn(async () => undefined);1040    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1041    await flushView();1042    sendMessageMock.mockClear();10431044    await selectImportFile(container);1045    findButton(container, "Import 1").click();1046    await flushView();10471048    expect(parseImportSourceMock).toHaveBeenCalledWith('{"export":"test"}', undefined);1049    expect(sendMessageMock).toHaveBeenCalledWith({1050      type: "BATCH_ADD_ENTRIES",1051      payload: {1052        entries: [1053          expect.objectContaining({1054            title: "Imported site",1055            username: "imported-user",1056            password: "imported-pass",1057            url: "https://imported.test",1058          }),1059        ],1060      },1061    });1062    expect(onImport).toHaveBeenCalled();1063    expect(container.textContent).toContain("1 entry appears to be duplicates");1064  });10651066  it("Import replace mode requires confirmation before clearing and replacing the vault", async () => {1067    parseImportSourceMock.mockResolvedValue(sampleImportResult());1068    sendMessageMock.mockImplementation(async (msg: unknown) => {1069      const type = (msg as { type?: string }).type;1070      if (type === "GET_ENTRIES") {1071        return { ok: true, data: [sampleEntry({ id: "existing-1" })] };1072      }1073      if (type === "CLEAR_VAULT_ENTRIES") {1074        return { ok: true };1075      }1076      if (type === "BATCH_ADD_ENTRIES") {1077        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1078      }1079      return { ok: true };1080    });1081    const onImport = vi.fn(async () => undefined);1082    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1083    await flushView();1084    sendMessageMock.mockClear();10851086    await selectImportFile(container);1087    (container.querySelector('input[value="replace"]') as HTMLInputElement).click();1088    await flushView();10891090    findButton(container, "Replace vault with 1").click();1091    await flushView();10921093    expect(sendMessageMock).not.toHaveBeenCalledWith(1094      expect.objectContaining({ type: "CLEAR_VAULT_ENTRIES" })1095    );1096    expect(container.textContent).toContain("Replace forever? This cannot be undone.");10971098    findButton(container, "Yes, replace forever").click();1099    await flushView();11001101    expect(sendMessageMock).toHaveBeenCalledWith({ type: "CLEAR_VAULT_ENTRIES" });1102    expect(sendMessageMock).toHaveBeenCalledWith({1103      type: "BATCH_ADD_ENTRIES",1104      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1105    });1106    expect(onImport).toHaveBeenCalled();1107  });11081109  it("Import onboarding mode waits for a matching master password before creating a vault", async () => {1110    parseImportSourceMock.mockResolvedValue(sampleImportResult());1111    sendMessageMock.mockImplementation(async (msg: unknown) => {1112      const type = (msg as { type?: string }).type;1113      if (type === "CREATE_VAULT") return { ok: true };1114      if (type === "BATCH_ADD_ENTRIES") {1115        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1116      }1117      return { ok: true };1118    });1119    const onImport = vi.fn(async () => undefined);1120    const container = mount(1121      <ImportView1122        mode="onboarding"1123        replacesExistingVault={true}1124        onBack={vi.fn()}1125        onImport={onImport}1126      />1127    );11281129    await selectImportFile(container);11301131    const createButton = findButton(container, "Create vault + import 1");1132    expect(createButton.disabled).toBe(true);1133    expect(container.textContent).toContain("Restoring now replaces the locked local vault");1134    expect(container.textContent).toContain("Use at least 8 characters");11351136    const masterInput = container.querySelector(1137      'input[placeholder="new master password"]'1138    ) as HTMLInputElement;1139    const confirmInput = container.querySelector(1140      'input[placeholder="confirm master password"]'1141    ) as HTMLInputElement;1142    const revealButton = container.querySelector(1143      'button[aria-label="Show passwords"]'1144    ) as HTMLButtonElement;1145    expect(revealButton).toBeTruthy();1146    revealButton.click();1147    await flushView();1148    expect(masterInput.type).toBe("text");1149    expect(confirmInput.type).toBe("text");11501151    inputText(masterInput, "fresh-master-password");1152    inputText(confirmInput, "fresh-master-password");1153    await flushView();11541155    expect(createButton.disabled).toBe(false);1156    createButton.click();1157    await flushView();11581159    expect(sendMessageMock).toHaveBeenCalledWith({1160      type: "CREATE_VAULT",1161      payload: { password: "fresh-master-password" },1162    });1163    expect(sendMessageMock).toHaveBeenCalledWith({1164      type: "BATCH_ADD_ENTRIES",1165      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1166    });1167    expect(onImport).toHaveBeenCalled();1168  });11691170  it("Import encrypted backups reparse with the backup password before import", async () => {1171    parseImportSourceMock1172      .mockResolvedValueOnce(1173        sampleImportResult({1174          format: "peach-json",1175          label: "Peach encrypted backup",1176          entries: [],1177          totalItems: 0,1178          requiresPassword: true,1179        })1180      )1181      .mockResolvedValueOnce(1182        sampleImportResult({1183          format: "peach-json",1184          label: "Peach encrypted backup",1185        })1186      );1187    sendMessageMock.mockImplementation(async (msg: unknown) => {1188      const type = (msg as { type?: string }).type;1189      if (type === "GET_ENTRIES") return { ok: true, data: [] };1190      if (type === "BATCH_ADD_ENTRIES") {1191        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };1192      }1193      return { ok: true };1194    });1195    const onImport = vi.fn(async () => undefined);1196    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);1197    await flushView();1198    sendMessageMock.mockClear();11991200    await selectImportFile(container, '{"type":"peach-export"}');1201    const password = container.querySelector('input[placeholder="backup password"]') as HTMLInputElement;1202    inputText(password, "backup-passphrase");1203    pressEnter(password);1204    await flushView();1205    await flushView();12061207    expect(parseImportSourceMock).toHaveBeenNthCalledWith(1, '{"type":"peach-export"}', undefined);1208    expect(parseImportSourceMock).toHaveBeenNthCalledWith(2, '{"type":"peach-export"}', "backup-passphrase");12091210    findButton(container, "Import 1").click();1211    await flushView();12121213    expect(sendMessageMock).toHaveBeenCalledWith({1214      type: "BATCH_ADD_ENTRIES",1215      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },1216    });1217    expect(onImport).toHaveBeenCalled();1218  });1219});