messages-CREATE_VAULT_FROM_ROOT_KEY.test.ts

2.7 KB · raw

1// DRAFT DESTINATION: src/background/messages.create-vault-from-root-key.test.ts2// T-A06..T-A09: message handler contract.34import { beforeEach, describe, expect, it, vi } from "vitest";5import { computeVaultId } from "../shared/sync-identity";67async function dispatch(message: { type: string; payload?: unknown }) {8  vi.resetModules();9  const messages = await import("./messages");10  return messages.handleMessage(message, { url: chrome.runtime.getURL("popup.html") } as chrome.runtime.MessageSender);11}1213describe("CREATE_VAULT_FROM_ROOT_KEY message", () => {14  beforeEach(() => {15    vi.stubGlobal("chrome", {16      runtime: { id: "ext", getURL: (path = "") => `chrome-extension://ext/${path}` },17      storage: {18        local: { get: vi.fn(async () => ({})), set: vi.fn(), remove: vi.fn() },19        session: { get: vi.fn(async () => ({})), set: vi.fn(), remove: vi.fn() },20      },21      alarms: { clear: vi.fn(), create: vi.fn(), onAlarm: { addListener: vi.fn() } },22      idle: { setDetectionInterval: vi.fn(), onStateChanged: { addListener: vi.fn() } },23    });24  });2526  it("T-A06: succeeds with a valid receiver password and root key", async () => {27    const res = await dispatch({28      type: "CREATE_VAULT_FROM_ROOT_KEY",29      payload: { password: "receiver-local-passphrase-456", rootKeyHex: "44".repeat(32) },30    }) as { ok: boolean; vaultId?: string };3132    expect(res.ok).toBe(true);33    expect(res.vaultId).toMatch(/^[0-9a-f]{64}$/);34  });3536  it("T-A07: fails gracefully for invalid rootKeyHex", async () => {37    const res = await dispatch({38      type: "CREATE_VAULT_FROM_ROOT_KEY",39      payload: { password: "receiver-local-passphrase-456", rootKeyHex: "nope" },40    }) as { ok: boolean; error?: string };4142    expect(res.ok).toBe(false);43    expect(res.error).toContain("ADOPT_INVALID_ROOT_KEY");44  });4546  it("T-A08: is vault-less allowed", async () => {47    const hasBefore = await dispatch({ type: "HAS_VAULT" }) as { ok: boolean; data?: boolean };48    expect(hasBefore.data).toBe(false);4950    const create = await dispatch({51      type: "CREATE_VAULT_FROM_ROOT_KEY",52      payload: { password: "receiver-local-passphrase-456", rootKeyHex: "55".repeat(32) },53    }) as { ok: boolean };5455    expect(create.ok).toBe(true);56  });5758  it("T-A09: returns the vault id computed from the adopted root key", async () => {59    const rootKeyHex = "66".repeat(32);60    const expected = await computeVaultId(new Uint8Array(Buffer.from(rootKeyHex, "hex")));61    const res = await dispatch({62      type: "CREATE_VAULT_FROM_ROOT_KEY",63      payload: { password: "receiver-local-passphrase-456", rootKeyHex },64    }) as { ok: boolean; vaultId?: string };6566    expect(res).toEqual({ ok: true, vaultId: expected });67  });68});69