contracts.test.tsx

27.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 { LockView } from "./Lock";9import { ExportView } from "./Export";10import { SettingsView } from "./Settings";11import { EntryView } from "./Entry";12import { ImportView } from "./Import";13import { VaultView } from "./Vault";14import { changeSelect, flushView, inputText, pressEnter, renderView } from "./view-test-utils";1516const sendMessageMock = vi.fn<(msg: unknown) => Promise<unknown>>();17const triggerRingMock = vi.fn();18const triggerPipPulseMock = vi.fn();19const exportEntriesToPeachJsonMock = vi.fn();20const parseImportSourceMock = vi.fn<(raw: string, password?: string) => Promise<ImportParseResult>>();21const zxcvbnMock = vi.fn((value: string) => ({ score: value.length >= 16 ? 3 : 1 }));2223vi.mock("../App", () => ({24  sendMessage: (msg: unknown) => sendMessageMock(msg),25  triggerRing: () => triggerRingMock(),26  triggerPipPulse: () => triggerPipPulseMock(),27}));2829vi.mock("../../shared/backup", () => ({30  exportEntriesToPeachJson: (...args: unknown[]) => exportEntriesToPeachJsonMock(...args),31}));3233vi.mock("../../shared/import", () => ({34  parseImportSource: (...args: [string, string | undefined]) => parseImportSourceMock(...args),35}));3637vi.mock("../../shared/favicon", () => ({38  faviconUrl: () => null,39}));4041vi.mock("../../crypto/totp", () => ({42  generateTOTP: () => ({ code: "123 456", remaining: 24 }),43  parseOtpauthURI: (value: string) =>44    value.startsWith("otpauth://")45      ? { secret: "NB2W45DFOIZA====", algorithm: "SHA1" as const }46      : null,47}));4849vi.mock("../components/GeneratorDrawer", () => ({50  GeneratorDrawer: () => null,51}));5253vi.mock("./CJKImport", () => ({54  CJKImportView: () => null,55}));5657vi.mock("./CJKExport", () => ({58  CJKExportView: () => null,59}));6061vi.mock("zxcvbn", () => ({62  default: (value: string) => zxcvbnMock(value),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    exportEntriesToPeachJsonMock.mockReset();74    parseImportSourceMock.mockReset();75    zxcvbnMock.mockReset();76    zxcvbnMock.mockImplementation((value: string) => ({ score: value.length >= 16 ? 3 : 1 }));77    parseImportSourceMock.mockResolvedValue({78      format: "unknown",79      label: "Unknown format",80      entries: [],81      totalItems: 0,82      skippedItems: 0,83      requiresPassword: false,84    });8586    vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {87      return window.setTimeout(() => cb(0), 0) as unknown as number;88    });89    vi.stubGlobal("cancelAnimationFrame", (id: number) => window.clearTimeout(id));90    vi.stubGlobal("URL", {91      createObjectURL: vi.fn(() => "blob:peach-test"),92      revokeObjectURL: vi.fn(),93    });94    vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});9596    (globalThis as { chrome?: typeof chrome }).chrome = {97      runtime: {98        getManifest: () => ({ version: "1.4.47" }),99        onMessage: { addListener: vi.fn() },100      },101    } as unknown as typeof chrome;102  });103104  afterEach(() => {105    while (disposers.length > 0) {106      disposers.pop()?.();107    }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  async function selectImportFile(158    container: HTMLElement,159    contents = '{"export":"test"}'160  ) {161    const input = container.querySelector('input[type="file"]') as HTMLInputElement;162    const file = new File([contents], "import.json", { type: "application/json" });163    Object.defineProperty(input, "files", {164      configurable: true,165      value: [file],166    });167    input.dispatchEvent(new Event("change", { bubbles: true }));168    await flushView();169    await flushView();170  }171172  function findButton(container: HTMLElement, text: string): HTMLButtonElement {173    return Array.from(container.querySelectorAll("button")).find(174      (candidate) => candidate.textContent?.trim() === text175    ) as HTMLButtonElement;176  }177178  it("Lock sends UNLOCK with the entered passphrase", async () => {179    sendMessageMock.mockResolvedValue({ ok: true });180    const onUnlock = vi.fn(async () => undefined);181    const container = mount(<LockView hasVault={true} ready={true} onUnlock={onUnlock} />);182183    const password = container.querySelector("#unlock-password") as HTMLInputElement;184    inputText(password, "correct horse battery staple");185    (container.querySelector(".peach-lock-submit") as HTMLButtonElement).click();186    await flushView();187188    expect(sendMessageMock).toHaveBeenCalledWith({189      type: "UNLOCK",190      payload: { password: "correct horse battery staple" },191    });192    expect(onUnlock).toHaveBeenCalled();193  });194195  it("Lock keeps create-vault disabled for short passwords and weak passphrases", async () => {196    const container = mount(<LockView hasVault={false} ready={true} onUnlock={vi.fn()} />);197    const createButton = container.querySelector(".peach-lock-submit") as HTMLButtonElement;198    const password = container.querySelector("#master-password") as HTMLInputElement;199    const confirm = container.querySelector("#confirm-password") as HTMLInputElement;200201    inputText(password, "short");202    inputText(confirm, "short");203    await flushView();204    expect(createButton.disabled).toBe(true);205206    zxcvbnMock.mockImplementation(() => ({ score: 1 }));207    inputText(password, "weakweakweak");208    inputText(confirm, "weakweakweak");209    await flushView();210    expect(createButton.disabled).toBe(true);211  });212213  it("Lock sends CREATE_VAULT when the onboarding passphrase is strong enough", async () => {214    sendMessageMock.mockResolvedValue({ ok: true });215    zxcvbnMock.mockImplementation(() => ({ score: 3 }));216    const onUnlock = vi.fn(async () => undefined);217    const container = mount(<LockView hasVault={false} ready={true} onUnlock={onUnlock} />);218219    const password = container.querySelector("#master-password") as HTMLInputElement;220    const confirm = container.querySelector("#confirm-password") as HTMLInputElement;221    const createButton = container.querySelector(".peach-lock-submit") as HTMLButtonElement;222223    inputText(password, "correct horse battery staple");224    inputText(confirm, "correct horse battery staple");225    await flushView();226    expect(createButton.disabled).toBe(false);227228    pressEnter(confirm);229    await flushView();230231    expect(sendMessageMock).toHaveBeenCalledWith({232      type: "CREATE_VAULT",233      payload: { password: "correct horse battery staple" },234    });235    expect(onUnlock).toHaveBeenCalled();236  });237238  it("Export keeps encrypted export disabled until the password meets the minimum length", async () => {239    const container = mount(<ExportView onBack={vi.fn()} />);240241    const password = container.querySelector('input[placeholder*="backup password"]') as HTMLInputElement;242    const confirm = container.querySelector("#export-confirm-password") as HTMLInputElement;243    const button = Array.from(container.querySelectorAll("button")).find(244      (candidate) => candidate.textContent?.trim() === "Download backup file"245    ) as HTMLButtonElement;246247    inputText(password, "too-short");248    inputText(confirm, "too-short");249    await flushView();250251    expect(button.disabled).toBe(true);252    expect(exportEntriesToPeachJsonMock).not.toHaveBeenCalled();253  });254255  it("Export keeps encrypted export disabled when passwords do not match", async () => {256    const container = mount(<ExportView onBack={vi.fn()} />);257258    const password = container.querySelector('input[placeholder*="backup password"]') as HTMLInputElement;259    const confirm = container.querySelector("#export-confirm-password") as HTMLInputElement;260    const button = Array.from(container.querySelectorAll("button")).find(261      (candidate) => candidate.textContent?.trim() === "Download backup file"262    ) as HTMLButtonElement;263264    inputText(password, "correct horse battery staple");265    inputText(confirm, "different horse battery staple");266    await flushView();267268    expect(button.disabled).toBe(true);269    expect(exportEntriesToPeachJsonMock).not.toHaveBeenCalled();270  });271272  it("Export requests entries and sends the correct payload to the encrypted backup exporter", async () => {273    sendMessageMock.mockResolvedValue({274      ok: true,275      data: [sampleEntry(), sampleEntry({ id: "deleted", deletedAt: 2 })],276    });277    exportEntriesToPeachJsonMock.mockResolvedValue({278      version: 2,279      type: "peach-export",280    });281    const container = mount(<ExportView onBack={vi.fn()} />);282283    const password = container.querySelector('input[placeholder*="backup password"]') as HTMLInputElement;284    const confirm = container.querySelector("#export-confirm-password") as HTMLInputElement;285    const button = Array.from(container.querySelectorAll("button")).find(286      (candidate) => candidate.textContent?.trim() === "Download backup file"287    ) as HTMLButtonElement;288289    inputText(password, "correct horse battery staple");290    inputText(confirm, "correct horse battery staple");291    await flushView();292    button.click();293    await flushView();294295    expect(sendMessageMock).toHaveBeenCalledWith({ type: "GET_ENTRIES" });296    expect(exportEntriesToPeachJsonMock).toHaveBeenCalledWith(297      [298        expect.objectContaining({ id: "entry-1" }),299        expect.objectContaining({ id: "deleted", deletedAt: 2 }),300      ],301      "correct horse battery staple"302    );303  });304305  it("Settings requires current, new, and confirm passwords before enabling save", async () => {306    sendMessageMock.mockResolvedValue({ ok: true, data: null });307    const container = mount(308      <SettingsView309        entriesCount={1}310        breachMonitoring={true}311        lockOnClose={true}312        autoLockMinutes={5}313        trashRetentionDays={30}314        theme="dark"315        accentColor="peach"316        onBreachMonitoringChange={vi.fn()}317        onLockOnCloseChange={vi.fn()}318        onAutoLockMinutesChange={vi.fn()}319        onTrashRetentionChange={vi.fn()}320        onThemeChange={vi.fn()}321        onAccentChange={vi.fn()}322        onBack={vi.fn()}323        onImport={vi.fn()}324        onExport={vi.fn()}325        onBreachCheckDone={vi.fn()}326      />327    );328    await flushView();329330    const securityRow = Array.from(container.querySelectorAll("button.peach-settings-cat-row")).find(331      (b) => b.querySelector(".peach-settings-cat-name")?.textContent?.trim() === "Security"332    ) as HTMLButtonElement;333    securityRow.click();334    await flushView();335336    const changeButton = Array.from(container.querySelectorAll("button")).find(337      (candidate) => candidate.textContent?.trim() === "change"338    ) as HTMLButtonElement;339    changeButton.click();340    await flushView();341342    const saveButton = Array.from(container.querySelectorAll("button")).find(343      (candidate) => candidate.textContent?.trim() === "save new password"344    ) as HTMLButtonElement;345    expect(saveButton.disabled).toBe(true);346347    const inputs = container.querySelectorAll('input[type="password"]');348    inputText(inputs[0] as HTMLInputElement, "current-pass");349    inputText(inputs[1] as HTMLInputElement, "new-pass-12345");350    await flushView();351    expect(saveButton.disabled).toBe(true);352353    inputText(inputs[2] as HTMLInputElement, "new-pass-12345");354    await flushView();355    expect(saveButton.disabled).toBe(false);356  });357358  it("Settings sends CHANGE_PASSWORD and forwards auto-lock/theme changes through callbacks", async () => {359    sendMessageMock.mockResolvedValue({ ok: true, data: null });360    const onAutoLockMinutesChange = vi.fn();361    const onThemeChange = vi.fn();362    const container = mount(363      <SettingsView364        entriesCount={1}365        breachMonitoring={true}366        lockOnClose={true}367        autoLockMinutes={5}368        trashRetentionDays={30}369        theme="dark"370        accentColor="peach"371        onBreachMonitoringChange={vi.fn()}372        onLockOnCloseChange={vi.fn()}373        onAutoLockMinutesChange={onAutoLockMinutesChange}374        onTrashRetentionChange={vi.fn()}375        onThemeChange={onThemeChange}376        onAccentChange={vi.fn()}377        onBack={vi.fn()}378        onImport={vi.fn()}379        onExport={vi.fn()}380        onBreachCheckDone={vi.fn()}381      />382    );383    await flushView();384    sendMessageMock.mockClear();385386    const headerBack = container.querySelector(".peach-overlay-header button") as HTMLButtonElement;387388    const securityRow = Array.from(container.querySelectorAll("button.peach-settings-cat-row")).find(389      (b) => b.querySelector(".peach-settings-cat-name")?.textContent?.trim() === "Security"390    ) as HTMLButtonElement;391    securityRow.click();392    await flushView();393394    const selects = container.querySelectorAll("select");395    changeSelect(selects[0] as HTMLSelectElement, "15");396    expect(onAutoLockMinutesChange).toHaveBeenCalledWith(15);397398    const changeButton = Array.from(container.querySelectorAll("button")).find(399      (candidate) => candidate.textContent?.trim() === "change"400    ) as HTMLButtonElement;401    changeButton.click();402    await flushView();403404    const inputs = container.querySelectorAll('input[type="password"]');405    inputText(inputs[0] as HTMLInputElement, "current-pass");406    inputText(inputs[1] as HTMLInputElement, "new-password-123");407    inputText(inputs[2] as HTMLInputElement, "new-password-123");408    await flushView();409410    const saveButton = Array.from(container.querySelectorAll("button")).find(411      (candidate) => candidate.textContent?.trim() === "save new password"412    ) as HTMLButtonElement;413    saveButton.click();414    await flushView();415416    headerBack.click();417    await flushView();418    const appearanceRow = Array.from(container.querySelectorAll("button.peach-settings-cat-row")).find(419      (b) => b.querySelector(".peach-settings-cat-name")?.textContent?.trim() === "Appearance"420    ) as HTMLButtonElement;421    appearanceRow.click();422    await flushView();423    const themeButton = Array.from(container.querySelectorAll("button")).find(424      (candidate) => candidate.textContent?.trim() === "Switch to light"425    ) as HTMLButtonElement;426    themeButton.click();427    expect(onThemeChange).toHaveBeenCalledWith("light");428429    expect(sendMessageMock).toHaveBeenCalledWith({430      type: "CHANGE_PASSWORD",431      payload: {432        currentPassword: "current-pass",433        newPassword: "new-password-123",434      },435    });436  });437438  it("Entry copy actions send COPY and canary ping messages for password and username", async () => {439    sendMessageMock.mockResolvedValue({ ok: true });440    const container = mount(441      <EntryView442        entry={sampleEntry()}443        onDelete={vi.fn()}444        onFieldSaved={vi.fn(async () => undefined)}445      />446    );447448    const passwordButton = container.querySelector('button[aria-label="Copy password"]') as HTMLButtonElement;449    passwordButton.click();450    await flushView();451452    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {453      type: "COPY",454      payload: { text: "secret123", label: "password", alreadyWritten: false },455    });456    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {457      type: "FIRE_CANARY_PING",458      payload: {459        webhookUrl: "https://example.com/hook",460        entryTitle: "GitHub",461        trigger: "password_copied",462      },463    });464465    sendMessageMock.mockClear();466    const usernameButton = container.querySelector('button[aria-label="Copy username"]') as HTMLButtonElement;467    usernameButton.click();468    await flushView();469470    expect(sendMessageMock).toHaveBeenNthCalledWith(1, {471      type: "COPY",472      payload: { text: "june", label: "username", alreadyWritten: false },473    });474    expect(sendMessageMock).toHaveBeenNthCalledWith(2, {475      type: "FIRE_CANARY_PING",476      payload: {477        webhookUrl: "https://example.com/hook",478        entryTitle: "GitHub",479        trigger: "username_copied",480      },481    });482  });483484  it("Entry refuses to send an empty password update and copies TOTP through COPY", async () => {485    sendMessageMock.mockResolvedValue({ ok: true });486    const onFieldSaved = vi.fn(async () => undefined);487    const container = mount(488      <EntryView489        entry={sampleEntry()}490        onDelete={vi.fn()}491        onFieldSaved={onFieldSaved}492      />493    );494495    const passwordValue = container.querySelector(".peach-password-value") as HTMLSpanElement;496    passwordValue.click();497    await flushView();498499    const passwordInput = container.querySelector('input[placeholder="paste or type a password"]') as HTMLInputElement;500    inputText(passwordInput, "");501    await flushView();502503    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;504    saveButton.click();505    await flushView();506507    expect(sendMessageMock).not.toHaveBeenCalledWith(508      expect.objectContaining({ type: "UPDATE_ENTRY" })509    );510    expect(onFieldSaved).not.toHaveBeenCalled();511512    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;513    totpMain.click();514    await flushView();515516    expect(sendMessageMock).toHaveBeenLastCalledWith({517      type: "COPY",518      payload: { text: "123456", label: "totp", alreadyWritten: false },519    });520  });521522  it("Entry closes an unchanged inline editor when focus leaves it", async () => {523    sendMessageMock.mockResolvedValue({ ok: true });524    const container = mount(525      <EntryView526        entry={sampleEntry()}527        onDelete={vi.fn()}528        onFieldSaved={vi.fn(async () => undefined)}529      />530    );531532    const usernameValue = container.querySelector(".peach-field-value.peach-inline-clickable") as HTMLSpanElement;533    usernameValue.click();534    await flushView();535536    const usernameInput = container.querySelector(".peach-inline-input[autocomplete=\"off\"]") as HTMLInputElement;537    usernameInput.blur();538    await flushView();539540    expect(container.querySelector(".peach-inline-input[autocomplete=\"off\"]")).toBeNull();541    expect(sendMessageMock).not.toHaveBeenCalledWith(542      expect.objectContaining({ type: "UPDATE_ENTRY" })543    );544  });545546  it("Entry lets TOTP secrets be edited inline", async () => {547    sendMessageMock.mockResolvedValue({ ok: true });548    const onFieldSaved = vi.fn(async () => undefined);549    const container = mount(550      <EntryView551        entry={sampleEntry()}552        onDelete={vi.fn()}553        onFieldSaved={onFieldSaved}554      />555    );556557    const totpMain = container.querySelector(".peach-totp-main") as HTMLDivElement;558    totpMain.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));559    await flushView();560561    const totpInput = container.querySelector('input[placeholder="otpauth://... or base32 secret"]') as HTMLInputElement;562    inputText(totpInput, "otpauth://totp/Example?secret=NB2W45DFOIZA====&issuer=Peach");563    await flushView();564565    const saveButton = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement;566    saveButton.click();567    await flushView();568569    expect(sendMessageMock).toHaveBeenCalledWith({570      type: "UPDATE_ENTRY",571      payload: {572        id: "entry-1",573        patch: { totp: "NB2W45DFOIZA====" },574      },575    });576    expect(onFieldSaved).toHaveBeenCalled();577  });578579  it("Vault seeds and focuses search when a search seed is provided", async () => {580    const container = mount(581      <VaultView582        entries={[sampleEntry(), sampleEntry({ id: "entry-2", title: "GitLab" })]}583        sortOrder="url-first"584        searchSeed="g"585        searchSeedNonce={1}586        onSelectEntry={vi.fn()}587        onSortOrderChange={vi.fn()}588        onAdd={vi.fn()}589        onClose={vi.fn()}590      />591    );592593    await flushView();594595    const search = container.querySelector(".peach-list-top .peach-search-input") as HTMLInputElement;596    expect(search.value).toBe("g");597    expect(document.activeElement).toBe(search);598  });599600  it("Import existing-vault add mode parses a file and batches entries into the vault", async () => {601    parseImportSourceMock.mockResolvedValue(602      sampleImportResult({603        entries: [604          {605            type: "login",606            title: "Imported site",607            username: "imported-user",608            password: "imported-pass",609            url: "https://imported.test",610          },611        ],612      })613    );614    sendMessageMock.mockImplementation(async (msg: unknown) => {615      const type = (msg as { type?: string }).type;616      if (type === "GET_ENTRIES") {617        return {618          ok: true,619          data: [620            sampleEntry({621              id: "existing-1",622              title: "Imported site",623              username: "imported-user",624              url: "https://imported.test",625            }),626          ],627        };628      }629      if (type === "BATCH_ADD_ENTRIES") {630        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };631      }632      return { ok: true };633    });634    const onImport = vi.fn(async () => undefined);635    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);636    await flushView();637    sendMessageMock.mockClear();638639    await selectImportFile(container);640    findButton(container, "Import 1").click();641    await flushView();642643    expect(parseImportSourceMock).toHaveBeenCalledWith('{"export":"test"}', undefined);644    expect(sendMessageMock).toHaveBeenCalledWith({645      type: "BATCH_ADD_ENTRIES",646      payload: {647        entries: [648          expect.objectContaining({649            title: "Imported site",650            username: "imported-user",651            password: "imported-pass",652            url: "https://imported.test",653          }),654        ],655      },656    });657    expect(onImport).toHaveBeenCalled();658    expect(container.textContent).toContain("1 entry appears to be duplicates");659  });660661  it("Import replace mode requires confirmation before clearing and replacing the vault", async () => {662    parseImportSourceMock.mockResolvedValue(sampleImportResult());663    sendMessageMock.mockImplementation(async (msg: unknown) => {664      const type = (msg as { type?: string }).type;665      if (type === "GET_ENTRIES") {666        return { ok: true, data: [sampleEntry({ id: "existing-1" })] };667      }668      if (type === "CLEAR_VAULT_ENTRIES") {669        return { ok: true };670      }671      if (type === "BATCH_ADD_ENTRIES") {672        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };673      }674      return { ok: true };675    });676    const onImport = vi.fn(async () => undefined);677    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);678    await flushView();679    sendMessageMock.mockClear();680681    await selectImportFile(container);682    (container.querySelector('input[value="replace"]') as HTMLInputElement).click();683    await flushView();684685    findButton(container, "Replace vault with 1").click();686    await flushView();687688    expect(sendMessageMock).not.toHaveBeenCalledWith(689      expect.objectContaining({ type: "CLEAR_VAULT_ENTRIES" })690    );691    expect(container.textContent).toContain("Replace forever? This cannot be undone.");692693    findButton(container, "Yes, replace forever").click();694    await flushView();695696    expect(sendMessageMock).toHaveBeenCalledWith({ type: "CLEAR_VAULT_ENTRIES" });697    expect(sendMessageMock).toHaveBeenCalledWith({698      type: "BATCH_ADD_ENTRIES",699      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },700    });701    expect(onImport).toHaveBeenCalled();702  });703704  it("Import onboarding mode waits for a matching master password before creating a vault", async () => {705    parseImportSourceMock.mockResolvedValue(sampleImportResult());706    sendMessageMock.mockImplementation(async (msg: unknown) => {707      const type = (msg as { type?: string }).type;708      if (type === "CREATE_VAULT") return { ok: true };709      if (type === "BATCH_ADD_ENTRIES") {710        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };711      }712      return { ok: true };713    });714    const onImport = vi.fn(async () => undefined);715    const container = mount(716      <ImportView717        mode="onboarding"718        replacesExistingVault={true}719        onBack={vi.fn()}720        onImport={onImport}721      />722    );723724    await selectImportFile(container);725726    const createButton = findButton(container, "Create vault + import 1");727    expect(createButton.disabled).toBe(true);728    expect(container.textContent).toContain("Restoring now replaces the locked local vault");729730    const inputs = container.querySelectorAll('input[type="password"]');731    inputText(inputs[0] as HTMLInputElement, "fresh-master-password");732    inputText(inputs[1] as HTMLInputElement, "fresh-master-password");733    await flushView();734735    expect(createButton.disabled).toBe(false);736    createButton.click();737    await flushView();738739    expect(sendMessageMock).toHaveBeenCalledWith({740      type: "CREATE_VAULT",741      payload: { password: "fresh-master-password" },742    });743    expect(sendMessageMock).toHaveBeenCalledWith({744      type: "BATCH_ADD_ENTRIES",745      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },746    });747    expect(onImport).toHaveBeenCalled();748  });749750  it("Import encrypted backups reparse with the backup password before import", async () => {751    parseImportSourceMock752      .mockResolvedValueOnce(753        sampleImportResult({754          format: "peach-json",755          label: "Peach encrypted backup",756          entries: [],757          totalItems: 0,758          requiresPassword: true,759        })760      )761      .mockResolvedValueOnce(762        sampleImportResult({763          format: "peach-json",764          label: "Peach encrypted backup",765        })766      );767    sendMessageMock.mockImplementation(async (msg: unknown) => {768      const type = (msg as { type?: string }).type;769      if (type === "GET_ENTRIES") return { ok: true, data: [] };770      if (type === "BATCH_ADD_ENTRIES") {771        return { ok: true, data: [sampleEntry({ id: "imported-1" })] };772      }773      return { ok: true };774    });775    const onImport = vi.fn(async () => undefined);776    const container = mount(<ImportView onBack={vi.fn()} onImport={onImport} />);777    await flushView();778    sendMessageMock.mockClear();779780    await selectImportFile(container, '{"type":"peach-export"}');781    const password = container.querySelector('input[placeholder="backup password"]') as HTMLInputElement;782    inputText(password, "backup-passphrase");783    pressEnter(password);784    await flushView();785    await flushView();786787    expect(parseImportSourceMock).toHaveBeenNthCalledWith(1, '{"type":"peach-export"}', undefined);788    expect(parseImportSourceMock).toHaveBeenNthCalledWith(2, '{"type":"peach-export"}', "backup-passphrase");789790    findButton(container, "Import 1").click();791    await flushView();792793    expect(sendMessageMock).toHaveBeenCalledWith({794      type: "BATCH_ADD_ENTRIES",795      payload: { entries: [expect.objectContaining({ title: "Imported site" })] },796    });797    expect(onImport).toHaveBeenCalled();798  });799});