import { beforeEach, describe, expect, it, vi } from "vitest"; import { computeVaultId } from "../shared/sync-identity"; async function dispatch(message: { type: string; payload?: unknown }) { vi.resetModules(); const messages = await import("./messages"); return messages.handleMessage( message as never, { url: chrome.runtime.getURL("popup.html") } as chrome.runtime.MessageSender, ); } describe("CREATE_VAULT_FROM_ROOT_KEY message", () => { beforeEach(() => { vi.stubGlobal("__PEACH_E2E_PASSKEYS__", false); vi.stubGlobal("chrome", { runtime: { id: "ext", getURL: (path = "") => `chrome-extension://ext/${path}`, }, tabs: { query: vi.fn((_query: unknown, callback?: (tabs: Array<{ id?: number }>) => void) => { if (typeof callback === "function") callback([]); return Promise.resolve([]); }), sendMessage: vi.fn(async () => ({ ok: true })), }, storage: { local: { get: vi.fn(async () => ({})), set: vi.fn(), remove: vi.fn(), }, session: { get: vi.fn(async () => ({})), set: vi.fn(), remove: vi.fn() }, }, alarms: { clear: vi.fn(), create: vi.fn(), onAlarm: { addListener: vi.fn() } }, idle: { setDetectionInterval: vi.fn(), onStateChanged: { addListener: vi.fn() } }, }); }); it("T-A06: succeeds with a valid receiver password and root key", async () => { const res = await dispatch({ type: "CREATE_VAULT_FROM_ROOT_KEY", payload: { password: "receiver-local-passphrase-456", rootKeyHex: "44".repeat(32) }, }) as { ok: boolean; vaultId?: string }; expect(res.ok).toBe(true); expect(res.vaultId).toMatch(/^[0-9a-f]{64}$/); }); it("T-A07: fails gracefully for invalid rootKeyHex", async () => { const res = await dispatch({ type: "CREATE_VAULT_FROM_ROOT_KEY", payload: { password: "receiver-local-passphrase-456", rootKeyHex: "nope" }, }) as { ok: boolean; error?: string }; expect(res.ok).toBe(false); expect(res.error).toContain("ADOPT_INVALID_ROOT_KEY"); }); it("T-A08: is vault-less allowed", async () => { const hasBefore = await dispatch({ type: "HAS_VAULT" }) as { ok: boolean; data?: boolean }; expect(hasBefore.data).toBe(false); const create = await dispatch({ type: "CREATE_VAULT_FROM_ROOT_KEY", payload: { password: "receiver-local-passphrase-456", rootKeyHex: "55".repeat(32) }, }) as { ok: boolean }; expect(create.ok).toBe(true); }); it("T-A09: returns the vault id computed from the adopted root key", async () => { const rootKeyHex = "66".repeat(32); const expected = await computeVaultId(new Uint8Array(Buffer.from(rootKeyHex, "hex"))); const res = await dispatch({ type: "CREATE_VAULT_FROM_ROOT_KEY", payload: { password: "receiver-local-passphrase-456", rootKeyHex }, }) as { ok: boolean; vaultId?: string }; expect(res).toEqual({ ok: true, vaultId: expected }); }); });