// @vitest-environment jsdom import type { JSX } from "solid-js"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { VaultEntry } from "../../shared/types"; import { ExportView } from "./Export"; import { flushView, inputText, renderView } from "./view-test-utils"; const sendMessageMock = vi.fn<(message: unknown) => Promise>(); const buildPayloadMock = vi.fn(async (_input: unknown) => new Uint8Array([1, 2, 3])); const encodePeachScriptMock = vi.fn((_bytes: Uint8Array) => "encoded-peachscript"); vi.mock("../App", () => ({ sendMessage: (message: unknown) => sendMessageMock(message), })); vi.mock("../../crypto/peachPayload", () => ({ buildPayload: (input: unknown) => buildPayloadMock(input), })); vi.mock("../../crypto/peachScript", () => ({ encodePeachScript: (bytes: Uint8Array) => encodePeachScriptMock(bytes), })); vi.mock("../components/RuneCanvas", () => ({ RuneCanvas: () => null })); vi.mock("@zxcvbn-ts/core", () => ({ zxcvbn: () => ({ score: 3, feedback: { warning: null, suggestions: [] } }), zxcvbnOptions: { setOptions: vi.fn() }, })); vi.mock("@zxcvbn-ts/language-common", () => ({ adjacencyGraphs: {}, dictionary: {}, })); vi.mock("@zxcvbn-ts/language-en", () => ({ translations: {}, dictionary: {}, })); const mountedViews: Array<() => void> = []; function mount(view: () => JSX.Element): HTMLElement { const mounted = renderView(view); mountedViews.push(mounted.dispose); return mounted.container; } function messageType(message: unknown): string { return (message as { type: string }).type; } function respondWith(entriesReply: unknown, settingsReply: unknown) { sendMessageMock.mockImplementation(async (message: unknown) => { switch (messageType(message)) { case "GET_ENTRIES": return entriesReply; case "GET_SETTINGS": return settingsReply; case "GET_LICENSE": return { ok: true, data: { valid: false, plan: "free" } }; default: throw new Error(`Unexpected message: ${messageType(message)}`); } }); } async function openAndGenerate(container: HTMLElement): Promise { const createButton = Array.from(container.querySelectorAll("button")).find( (button) => button.textContent?.trim() === "Create PeachScript →", ) as HTMLButtonElement; createButton.click(); await flushView(); const inputs = container.querySelectorAll('input[type="password"]'); inputText(inputs[0]!, "correct horse battery staple"); inputText(inputs[1]!, "correct horse battery staple"); const generateButton = Array.from(container.querySelectorAll("button")).find( (button) => button.textContent?.trim() === "Generate PeachScript", ) as HTMLButtonElement; await vi.waitFor(() => expect(generateButton.disabled).toBe(false)); generateButton.click(); await flushView(); return generateButton; } beforeEach(() => { document.body.innerHTML = ""; sendMessageMock.mockReset(); buildPayloadMock.mockClear(); buildPayloadMock.mockResolvedValue(new Uint8Array([1, 2, 3])); encodePeachScriptMock.mockClear(); encodePeachScriptMock.mockReturnValue("encoded-peachscript"); }); afterEach(() => { while (mountedViews.length > 0) mountedViews.pop()?.(); vi.restoreAllMocks(); }); describe("PeachScript export assembly", () => { it.each([ ["failed GET_ENTRIES", { ok: false, error: "vault_locked" }], ["null GET_ENTRIES reply", null], ["GET_ENTRIES without data", { ok: true }], ["GET_ENTRIES with object data", { ok: true, data: {} }], ])("refuses %s", async (_label, entriesReply) => { respondWith(entriesReply, { ok: true, data: {} }); const container = mount(() => ); await openAndGenerate(container); expect(container.textContent).toContain("Couldn't create PeachScript backup."); expect(container.textContent).not.toContain("Copy"); expect(buildPayloadMock).not.toHaveBeenCalled(); }); it.each([ ["failed GET_SETTINGS", { ok: false, error: "vault_locked" }], ["null GET_SETTINGS reply", null], ["GET_SETTINGS without data", { ok: true }], ["GET_SETTINGS with null data", { ok: true, data: null }], ["GET_SETTINGS with array data", { ok: true, data: [] }], ["GET_SETTINGS with primitive data", { ok: true, data: "dark" }], ])("refuses %s", async (_label, settingsReply) => { respondWith({ ok: true, data: [] }, settingsReply); const container = mount(() => ); await openAndGenerate(container); expect(container.textContent).toContain("Couldn't create PeachScript backup."); expect(container.textContent).not.toContain("Copy"); expect(buildPayloadMock).not.toHaveBeenCalled(); }); it("accepts successful empty entries and settings", async () => { respondWith({ ok: true, data: [] }, { ok: true, data: {} }); const container = mount(() => ); await openAndGenerate(container); expect(container.textContent).toContain("0 entries"); expect(container.textContent).toContain("Copy"); expect(buildPayloadMock).toHaveBeenCalledWith( expect.objectContaining({ entries: [], settings: {} }), ); }); it("keeps license data optional when its lookup fails", async () => { sendMessageMock.mockImplementation(async (message: unknown) => { switch (messageType(message)) { case "GET_ENTRIES": return { ok: true, data: [] }; case "GET_SETTINGS": return { ok: true, data: {} }; case "GET_LICENSE": return { ok: false, error: "SERVICE_WORKER_UNAVAILABLE" }; default: throw new Error(`Unexpected message: ${messageType(message)}`); } }); const container = mount(() => ); await openAndGenerate(container); expect(container.textContent).toContain("0 entries"); expect(container.textContent).toContain("Copy"); expect(buildPayloadMock).toHaveBeenCalledWith( expect.objectContaining({ license: undefined }), ); }); it("reports counts from a valid non-empty export", async () => { const entries: VaultEntry[] = [ { id: "login", type: "login", title: "Login", password: "secret", createdAt: 1, modifiedAt: 1 }, { id: "card", type: "card", title: "Card", createdAt: 1, modifiedAt: 1 }, { id: "note", type: "note", title: "Note", createdAt: 1, modifiedAt: 1 }, { id: "passkey", type: "login", title: "Passkey", createdAt: 1, modifiedAt: 1, passkey: { rpId: "example.com", rpName: "Example", credentialId: "credential", publicKeyCose: "public", userHandle: "user", userName: "June", userDisplayName: "June", algorithm: -7, signCount: 0, aaguid: "aaguid", backupEligible: false, backupState: false, createdAt: 1, }, }, ]; respondWith({ ok: true, data: entries }, { ok: true, data: { theme: "dark" } }); const container = mount(() => ); await openAndGenerate(container); expect(container.textContent).toContain("4 entries · 1 card · 1 passkey · 1 note"); expect(buildPayloadMock).toHaveBeenCalledWith( expect.objectContaining({ entries, settings: { theme: "dark" } }), ); }); it("clears an earlier script before a failed new encode attempt finishes", async () => { respondWith({ ok: true, data: [] }, { ok: true, data: {} }); const container = mount(() => ); const generateButton = await openAndGenerate(container); expect(container.textContent).toContain("Copy"); sendMessageMock.mockResolvedValueOnce({ ok: false, error: "SERVICE_WORKER_UNAVAILABLE" }); // Reattach the removed button to guard handleEncode's clear-before-await ordering. generateButton.disabled = false; document.body.appendChild(generateButton); generateButton.click(); expect(container.textContent).not.toContain("Copy"); await flushView(); expect(container.textContent).toContain("Couldn't create PeachScript backup."); expect(container.textContent).not.toContain("Copy"); }); });