messages.test.ts

68.7 KB · raw

1import { beforeEach, describe, expect, it, vi } from "vitest";23import { base64urlEncode, generatePasskeyKeypair } from "./passkey-crypto";4import type { Message, MessageResponse } from "../shared/types";56type StorageShape = Record<string, unknown>;78function deferred(): { promise: Promise<void>; resolve: () => void } {9  let resolve!: () => void;10  const promise = new Promise<void>((done) => {11    resolve = done;12  });13  return { promise, resolve };14}15type MessageListener = (16  msg: unknown,17  sender: chrome.runtime.MessageSender,18  sendResponse: (response: MessageResponse) => void19) => boolean;2021describe("background messages", () => {22  let storage: StorageShape;23  let sessionStorage: StorageShape;24  let listener: MessageListener;25  let fetchMock: ReturnType<typeof vi.fn>;2627  beforeEach(async () => {28    vi.resetModules();29    vi.useRealTimers();30    storage = {31      peach_settings: { breachMonitoring: false },32    };33    sessionStorage = {};3435    fetchMock = vi.fn(async () => ({36      ok: true,37      status: 200,38      text: async () => "",39    }));40    vi.stubGlobal("fetch", fetchMock);41    vi.stubGlobal("__PEACH_E2E_PASSKEYS__", false);4243    const tabs = [{ id: 1 }];44    const chromeMock = {45      runtime: {46        id: "peach-extension",47        getURL: (p: string) => `chrome-extension://peach-extension/${p}`,48        onMessage: {49          addListener: vi.fn((fn: MessageListener) => {50            listener = fn;51          }),52        },53        sendMessage: vi.fn(async () => ({ ok: true })),54      },55      tabs: {56        query: vi.fn((_query: unknown, callback?: (tabs: Array<{ id?: number }>) => void) => {57          if (typeof callback === "function") {58            callback(tabs);59            return;60          }61          return Promise.resolve(tabs);62        }),63        sendMessage: vi.fn(async () => ({ ok: true })),64      },65      storage: {66        local: {67          get: vi.fn(async (key?: string | string[]) => {68            if (!key) return storage;69            if (typeof key === "string") {70              return { [key]: storage[key] };71            }7273            return key.reduce<Record<string, unknown>>((result, entry) => {74              result[entry] = storage[entry];75              return result;76            }, {});77          }),78          set: vi.fn(async (next: Record<string, unknown>) => {79            Object.assign(storage, next);80          }),81          remove: vi.fn(async (keys: string | string[]) => {82            const list = Array.isArray(keys) ? keys : [keys];83            for (const key of list) {84              delete storage[key];85            }86          }),87          clear: vi.fn(async () => {88            for (const key of Object.keys(storage)) delete storage[key];89          }),90        },91        session: {92          get: vi.fn(async (key?: string | string[]) => {93            if (!key) return sessionStorage;94            if (typeof key === "string") {95              return { [key]: sessionStorage[key] };96            }97            return key.reduce<Record<string, unknown>>((result, entry) => {98              result[entry] = sessionStorage[entry];99              return result;100            }, {});101          }),102          set: vi.fn(async (next: Record<string, unknown>) => {103            Object.assign(sessionStorage, next);104          }),105          remove: vi.fn(async (keys: string | string[]) => {106            const list = Array.isArray(keys) ? keys : [keys];107            for (const key of list) {108              delete sessionStorage[key];109            }110          }),111          clear: vi.fn(async () => {112            for (const key of Object.keys(sessionStorage)) delete sessionStorage[key];113          }),114        },115        sync: {116          get: vi.fn(async (_key?: string | string[]) => ({})),117          set: vi.fn(async (_values: Record<string, unknown>) => undefined),118          remove: vi.fn(async (_keys: string | string[]) => undefined),119          clear: vi.fn(async () => undefined),120        },121      },122      alarms: {123        clear: vi.fn(),124        create: vi.fn(),125        onAlarm: { addListener: vi.fn() },126      },127      idle: {128        setDetectionInterval: vi.fn(),129        onStateChanged: { addListener: vi.fn() },130      },131      scripting: {132        executeScript: vi.fn(async () => []),133      },134    } as unknown as typeof chrome;135136    (globalThis as { chrome?: typeof chrome }).chrome = chromeMock;137138    const messages = await import("./messages");139    messages.setupMessageHandler();140    const vault = await import("./vault");141    await vault.ensureSettingsLoaded();142  });143144  async function dispatch(145    message: Message,146    sender: chrome.runtime.MessageSender = {147      id: "peach-extension",148      url: "chrome-extension://peach-extension/popup.html",149    }150  ): Promise<MessageResponse> {151    return await new Promise<MessageResponse>((resolve) => {152      const keepChannelOpen = listener(message, sender, (response) => resolve(response));153      expect(keepChannelOpen).toBe(true);154    });155  }156157  it("PB-26-303: page GET_SETTINGS returns only theme, accent, and its own summon record", async () => {158    storage.peach_settings = {159      theme: "dark",160      accentColor: "peach",161      autoLockMinutes: 5,162      pinEnabled: true,163      manualSummonDomains: {164        "example.com": { firstSummonedAt: 1, summonCount: 2, lastSummonedAt: 3 },165        "other.example": { firstSummonedAt: 4, summonCount: 5, lastSummonedAt: 6 },166      },167    };168    const response = await dispatch(169      { type: "GET_SETTINGS" },170      {171        id: "peach-extension",172        url: "https://login.example.com/form",173        tab: { id: 1 },174        frameId: 0,175      } as chrome.runtime.MessageSender,176    );177178    expect(response).toEqual({179      ok: true,180      data: {181        theme: "dark",182        accentColor: "peach",183        manualSummonDomains: {184          "example.com": { firstSummonedAt: 1, summonCount: 2, lastSummonedAt: 3 },185        },186      },187    });188    await expect(dispatch({ type: "GET_SETTINGS" })).resolves.toMatchObject({189      ok: true,190      data: {191        autoLockMinutes: 5,192        pinEnabled: true,193        manualSummonDomains: {194          "example.com": expect.anything(),195          "other.example": expect.anything(),196        },197      },198    });199  });200201  it("RECORD_MANUAL_SUMMON binds and bounds the sender domain", async () => {202    const sender = {203      id: "peach-extension",204      url: "https://login.example.com/form",205      origin: "https://login.example.com",206      tab: { id: 1 },207      frameId: 0,208    } as chrome.runtime.MessageSender;209210    await expect(dispatch({211      type: "RECORD_MANUAL_SUMMON",212      payload: { domain: "evil.example" },213    }, sender)).resolves.toEqual({ ok: false, error: "invalid_domain" });214    await expect(dispatch({215      type: "RECORD_MANUAL_SUMMON",216      payload: { domain: "example.com" },217    }, sender)).resolves.toEqual({ ok: true });218    await expect(dispatch({219      type: "RECORD_MANUAL_SUMMON",220      payload: { domain: "a".repeat(254) },221    }, { ...sender, origin: "https://a.com", url: "https://a.com/form" })).resolves.toEqual({222      ok: false,223      error: "invalid_domain",224    });225  });226227  it("GET_ENTRIES when unlocked returns the entry array", async () => {228    const vault = await import("./vault");229    await vault.createVault("correct-pass-12345");230    await vault.addEntry({231      title: "GitHub",232      username: "june",233      password: "secret123",234      url: "https://github.com",235    });236237    await expect(dispatch({ type: "GET_ENTRIES" })).resolves.toMatchObject({238      ok: true,239      data: [240        expect.objectContaining({241          title: "GitHub",242          username: "june",243        }),244      ],245    });246  });247248  it("GET_ENTRIES when locked returns a vault locked error", async () => {249    const vault = await import("./vault");250    await vault.createVault("correct-pass-12345");251    vault.lock();252253    await expect(dispatch({ type: "GET_ENTRIES" })).resolves.toMatchObject({254      ok: false,255      error: "vault_locked",256    });257  });258259  it("ADD_ENTRY with a valid payload returns the created entry", async () => {260    const vault = await import("./vault");261    await vault.createVault("correct-pass-12345");262263    const response = await dispatch({264      type: "ADD_ENTRY",265      payload: {266        title: "GitHub",267        username: "june",268        password: "secret123",269        url: "https://github.com",270      },271    });272273    expect(response).toMatchObject({274      ok: true,275      data: expect.objectContaining({276        id: expect.any(String),277        title: "GitHub",278      }),279    });280    expect(vault.getEntries()).toHaveLength(1);281  });282283  it("ADD_ENTRY when locked returns a vault locked error", async () => {284    const vault = await import("./vault");285    await vault.createVault("correct-pass-12345");286    vault.lock();287288    await expect(289      dispatch({290        type: "ADD_ENTRY",291        payload: {292          title: "GitHub",293          username: "june",294          password: "secret123",295          url: "https://github.com",296        },297      })298    ).resolves.toMatchObject({ ok: false, error: "vault_locked" });299  });300301  it("ADD_ENTRY with no password succeeds for email-only accounts", async () => {302    const vault = await import("./vault");303    await vault.createVault("correct-pass-12345");304305    await expect(306      dispatch({307        type: "ADD_ENTRY",308        payload: {309          title: "GitHub",310          username: "june",311          password: "",312          url: "https://github.com",313        },314      })315    ).resolves.toMatchObject({ ok: true });316  });317318  it("UPDATE_ENTRY updates an existing entry and returns ok", async () => {319    const vault = await import("./vault");320    await vault.createVault("correct-pass-12345");321    const entry = await vault.addEntry({322      title: "GitHub",323      username: "june",324      password: "secret123",325      url: "https://github.com",326    });327328    await expect(329      dispatch({330        type: "UPDATE_ENTRY",331        payload: { id: entry.id, patch: { password: "new-secret" } },332      })333    ).resolves.toMatchObject({ ok: true });334335    expect(vault.getEntryById(entry.id)?.password).toBe("new-secret");336  });337338  it("UPDATE_ENTRY with an empty password clears it for email-only accounts", async () => {339    const vault = await import("./vault");340    await vault.createVault("correct-pass-12345");341    const entry = await vault.addEntry({342      title: "GitHub",343      username: "june",344      password: "secret123",345      url: "https://github.com",346    });347348    await expect(349      dispatch({350        type: "UPDATE_ENTRY",351        payload: { id: entry.id, patch: { password: "" } },352      })353    ).resolves.toMatchObject({ ok: true });354355    expect(vault.getEntryById(entry.id)?.password).toBeUndefined();356  });357358  it("DELETE_ENTRY soft-deletes the target entry", async () => {359    const vault = await import("./vault");360    await vault.createVault("correct-pass-12345");361    const entry = await vault.addEntry({362      title: "GitHub",363      username: "june",364      password: "secret123",365      url: "https://github.com",366    });367368    await expect(369      dispatch({370        type: "DELETE_ENTRY",371        payload: { id: entry.id },372      })373    ).resolves.toMatchObject({ ok: true });374375    expect(vault.getEntries()).toEqual([]);376    expect(vault.getDeletedEntries()).toHaveLength(1);377  });378379  it("DELETE_ENTRY of a missing id returns an error", async () => {380    const vault = await import("./vault");381    await vault.createVault("correct-pass-12345");382383    await expect(384      dispatch({385        type: "DELETE_ENTRY",386        payload: { id: "missing" },387      })388    ).resolves.toMatchObject({ ok: false, error: "entry_not_found" });389  });390391  it("GET_ENTRY_FOR_FILL returns a safe login entry without privateKeyJwk", async () => {392    const vault = await import("./vault");393    await vault.createVault("correct-pass-12345");394    const entry = await vault.addEntry({395      title: "GitHub",396      username: "june",397      password: "secret123",398      url: "https://github.com",399    });400401    const response = await dispatch(402      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },403      { id: "peach-extension", url: "https://github.com/login" },404    );405406    expect(response).toMatchObject({407      ok: true,408      data: expect.objectContaining({409        id: entry.id,410        username: "june",411        password: "secret123",412      }),413    });414    expect((response.data as Record<string, unknown>).privateKeyJwk).toBeUndefined();415  });416417  it("GET_ENTRY_FOR_FILL when locked returns an error", async () => {418    const vault = await import("./vault");419    await vault.createVault("correct-pass-12345");420    vault.lock();421422    await expect(423      dispatch({424        type: "GET_ENTRY_FOR_FILL",425        payload: { id: "missing" },426      })427    ).resolves.toMatchObject({ ok: false, error: "vault_locked" });428  });429430  it("GET_ENTRY_FOR_FILL rejects passkey-only entries", async () => {431    const vault = await import("./vault");432    await vault.createVault("correct-pass-12345");433    const generated = await generatePasskeyKeypair(-7);434    const entry = await vault.addEntry({435      type: "login",436      title: "WebAuthn.io",437      passkey: {438        rpId: "webauthn.io",439        rpName: "WebAuthn.io",440        credentialId: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),441        publicKeyCose: base64urlEncode(generated.publicKeyCose),442        privateKeyJwk: generated.privateKeyJwk,443        userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),444        userName: "june",445        userDisplayName: "June",446        algorithm: -7,447        signCount: 0,448        aaguid: "AAAAAAAAAAAAAAAAAAAAAA",449        backupEligible: true,450        backupState: false,451        createdAt: Date.now(),452      },453    });454455    await expect(456      dispatch({457        type: "GET_ENTRY_FOR_FILL",458        payload: { id: entry.id },459      })460    ).resolves.toMatchObject({ ok: false, error: "passkey_not_fillable" });461  });462463  it("AUTOFILL_QUERY returns matched domain metadata without secrets", async () => {464    const vault = await import("./vault");465    await vault.createVault("correct-pass-12345");466    await vault.addEntry({467      title: "GitHub",468      username: "june",469      password: "secret123",470      url: "https://github.com",471      totp: "JBSWY3DPEHPK3PXP",472    });473474    const response = await dispatch({475      type: "AUTOFILL_QUERY",476      payload: { domain: "github.com" },477    });478479    expect(response).toMatchObject({480      ok: true,481      data: [482        {483          id: expect.any(String),484          title: "GitHub",485          username: "june",486          url: "https://github.com",487          hasTotp: true,488        },489      ],490    });491    expect((response.data as Array<Record<string, unknown>>)[0].password).toBeUndefined();492    expect((response.data as Array<Record<string, unknown>>)[0].totp).toBeUndefined();493  });494495  it("AUTOFILL_QUERY includeAll returns search-ready summaries for non-note, non-passkey entries", async () => {496    const vault = await import("./vault");497    await vault.createVault("correct-pass-12345");498    await vault.addEntry({499      title: "GitHub",500      username: "june",501      password: "secret123",502      url: "https://github.com",503    });504    await vault.addEntry({505      type: "note",506      title: "Secure note",507      notes: "hello",508    });509510    const response = await dispatch({511      type: "AUTOFILL_QUERY",512      payload: { domain: "github.com", includeAll: true },513    });514515    expect(response).toMatchObject({516      ok: true,517      data: [518        {519          id: expect.any(String),520          title: "GitHub",521          username: "june",522          url: "https://github.com",523          hasPasskey: false,524        },525      ],526    });527    const data = response.data as Array<Record<string, unknown>>;528    expect(data).toHaveLength(1);529    // No secrets cross the boundary.530    expect(data[0]).not.toHaveProperty("password");531    expect(data[0]).not.toHaveProperty("totp");532  });533534  it("AUTOFILL_QUERY kind=totp returns only matching entries with 2FA summaries", async () => {535    const vault = await import("./vault");536    await vault.createVault("correct-pass-12345");537    await vault.addEntry({538      title: "GitHub",539      username: "june",540      password: "secret123",541      url: "https://github.com",542      totp: "JBSWY3DPEHPK3PXP",543    });544    await vault.addEntry({545      title: "No 2FA",546      username: "person",547      password: "secret123",548      url: "https://github.com",549    });550551    const response = await dispatch({552      type: "AUTOFILL_QUERY",553      payload: { domain: "github.com", kind: "totp" },554    });555556    expect(response).toMatchObject({557      ok: true,558      data: [559        {560          id: expect.any(String),561          title: "GitHub",562          username: "june",563          url: "https://github.com",564          hasTotp: true,565        },566      ],567    });568    expect((response.data as Array<Record<string, unknown>>)[0].totp).toBeUndefined();569    expect(response.data).toHaveLength(1);570  });571572  it("RESTORE_ENTRIES replace mode restores the provided entries", async () => {573    const vault = await import("./vault");574    await vault.createVault("correct-pass-12345");575    await vault.addEntry({ title: "A", username: "", password: "one", url: "" });576577    const response = await dispatch({578      type: "RESTORE_ENTRIES",579      payload: {580        mode: "replace",581        entries: [582          {583            id: "restored-1",584            type: "login",585            title: "B",586            username: "june",587            password: "two",588            url: "https://b.test",589            createdAt: 1,590            modifiedAt: 1,591          },592        ],593      },594    });595596    expect(response).toMatchObject({ ok: true, data: { added: 1, updated: 0, skipped: 0 } });597    expect(vault.getEntries().map((entry) => entry.id)).toEqual(["restored-1"]);598  });599600  it("RESTORE_ENTRIES replace mode with an empty array returns an error", async () => {601    const vault = await import("./vault");602    await vault.createVault("correct-pass-12345");603604    await expect(605      dispatch({606        type: "RESTORE_ENTRIES",607        payload: { mode: "replace", entries: [] },608      })609    ).resolves.toMatchObject({ ok: false, error: "refuse to replace with empty entry set" });610  });611612  it("CHANGE_PASSWORD responds true for the happy path and false for a wrong current password", async () => {613    const vault = await import("./vault");614    await vault.createVault("correct-pass-12345");615616    await expect(617      dispatch({618        type: "CHANGE_PASSWORD",619        payload: {620          currentPassword: "correct-pass-12345",621          newPassword: "new-pass-67890",622        },623      })624    ).resolves.toMatchObject({ ok: true });625626    vault.lock();627    expect(await vault.unlock("new-pass-67890")).toBe(true);628629    await expect(630      dispatch({631        type: "CHANGE_PASSWORD",632        payload: {633          currentPassword: "wrong-pass",634          newPassword: "another-pass",635        },636      })637    ).resolves.toMatchObject({ ok: false, error: "incorrect_current_password" });638  });639640  it("UPDATE_SETTINGS reschedules auto-lock using the new minutes value", async () => {641    const vault = await import("./vault");642    await vault.createVault("correct-pass-12345");643644    (645      chrome.alarms.create as unknown as ReturnType<typeof vi.fn>646    ).mockClear();647    (648      chrome.idle.setDetectionInterval as unknown as ReturnType<typeof vi.fn>649    ).mockClear();650651    await expect(652      dispatch({653        type: "UPDATE_SETTINGS",654        payload: { autoLockMinutes: 30 },655      })656    ).resolves.toMatchObject({ ok: true });657658    expect(vault.getSettings().autoLockMinutes).toBe(30);659    expect(chrome.idle.setDetectionInterval).toHaveBeenLastCalledWith(1800);660    expect(chrome.alarms.create).toHaveBeenLastCalledWith("autolock", {661      delayInMinutes: 30,662    });663  });664665  it("CHECK_ALL_BREACHES updates matching entries without corrupting the vault", async () => {666    vi.useFakeTimers();667    const vault = await import("./vault");668    await vault.createVault("correct-pass-12345");669    const entry = await vault.addEntry({670      title: "GitHub",671      username: "june",672      password: "secret123",673      url: "https://github.com",674    });675    const breachSpy = vi.spyOn(vault, "checkBreach").mockResolvedValue(7);676677    const responsePromise = dispatch({ type: "CHECK_ALL_BREACHES" });678    await vi.runAllTimersAsync();679    const response = await responsePromise;680681    expect(response).toMatchObject({ ok: true, data: { [entry.id]: 7 } });682    expect(vault.getEntryById(entry.id)?.breach).toBe(7);683    breachSpy.mockRestore();684  });685686  it("rejects passkey approval from a different tab than the ceremony", async () => {687    sessionStorage.passkey_pending_301 = {688      requestId: 301,689      type: "get",690      rpId: "example.com",691      rpName: "Example",692      userName: "[email protected]",693      tabId: 7,694      origin: "https://example.com",695    };696697    await expect(698      dispatch(699        { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 301, approved: true } },700        { id: "peach-extension", tab: { id: 8 }, url: "https://example.com/login" } as chrome.runtime.MessageSender,701      ),702    ).resolves.toMatchObject({ ok: false, error: "invalid_passkey_approval_sender" });703  });704705  it("messages from foreign or URL-less senders are rejected", async () => {706    const vault = await import("./vault");707    await vault.createVault("correct-pass-12345");708709    await expect(dispatch({ type: "GET_ENTRIES" }, { id: "other-extension" })).resolves.toMatchObject({710      ok: false,711      error: "invalid_sender",712    });713714    await expect(dispatch({ type: "GET_ENTRIES" }, {})).resolves.toMatchObject({715      ok: false,716      error: "invalid_sender",717    });718  });719720  it("LOCK and UNLOCK messages update vault state correctly", async () => {721    const vault = await import("./vault");722723    await expect(724      dispatch({ type: "CREATE_VAULT", payload: { password: "correct-pass-12345" } })725    ).resolves.toMatchObject({ ok: true });726    expect(vault.isUnlocked()).toBe(true);727728    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });729    expect(vault.isUnlocked()).toBe(false);730731    await expect(732      dispatch({ type: "UNLOCK", payload: { password: "wrong-pass" } })733    ).resolves.toMatchObject({ ok: false });734    expect(vault.isUnlocked()).toBe(false);735736    await expect(737      dispatch({ type: "UNLOCK", payload: { password: "correct-pass-12345" } })738    ).resolves.toMatchObject({ ok: true });739    expect(vault.isUnlocked()).toBe(true);740  });741742  it("does not acknowledge LOCK until session cleanup finishes", async () => {743    await expect(744      dispatch({ type: "CREATE_VAULT", payload: { password: "correct-pass-12345" } })745    ).resolves.toMatchObject({ ok: true });746747    const removalStarted = deferred();748    const releaseRemoval = deferred();749    const remove = chrome.storage.session.remove as unknown as ReturnType<typeof vi.fn>;750    remove.mockImplementation(async (keys: string | string[]) => {751      removalStarted.resolve();752      await releaseRemoval.promise;753      for (const key of Array.isArray(keys) ? keys : [keys]) delete sessionStorage[key];754    });755756    let responded = false;757    const response = dispatch({ type: "LOCK" }).then((result) => {758      responded = true;759      return result;760    });761    await removalStarted.promise;762763    try {764      await Promise.resolve();765      expect(responded).toBe(false);766    } finally {767      releaseRemoval.resolve();768    }769770    await expect(response).resolves.toMatchObject({ ok: true });771  });772773  it("remembers the last successful unlock method", async () => {774    const vault = await import("./vault");775    const password = "correct-pass-12345";776    const popupSender = {777      id: "peach-extension",778      url: "chrome-extension://peach-extension/src/popup/index.html",779    } as chrome.runtime.MessageSender;780781    await vault.createVault(password);782    expect(await vault.setupPinUnlock(password, "1234")).toBe(true);783    vault.lock();784785    await expect(786      dispatch({ type: "UNLOCK_WITH_PIN", payload: { pin: "1234" } }, popupSender),787    ).resolves.toMatchObject({ ok: true });788    expect((await vault.ensureSettingsLoaded()).pinPreferred).toBe(true);789790    vault.lock();791    await expect(792      dispatch({ type: "UNLOCK", payload: { password } }, popupSender),793    ).resolves.toMatchObject({ ok: true });794    expect((await vault.ensureSettingsLoaded()).pinPreferred).toBe(false);795  });796797  it("FIRE_CANARY_PING sends a minimal payload to allowed HTTPS webhooks", async () => {798    const response = await dispatch({799      type: "FIRE_CANARY_PING",800      payload: {801        webhookUrl: "https://example.com/hook",802        entryTitle: "GitHub",803        trigger: "password_copied",804      },805    });806807    expect(response).toMatchObject({ ok: true });808    expect(fetchMock).toHaveBeenCalledWith(809      "https://example.com/hook",810      expect.objectContaining({811        method: "POST",812        headers: { "Content-Type": "application/json" },813        body: expect.any(String),814      })815    );816    const body = JSON.parse(fetchMock.mock.calls[0][1].body as string) as Record<string, unknown>;817    expect(body).toMatchObject({818      entry: "GitHub",819      trigger: "password_copied",820      source: "peach-extension",821    });822  });823824  it("LV-3: debounces a repeat non-test ping for the same webhook+entry", async () => {825    const payload = {826      webhookUrl: "https://example.com/hook",827      entryTitle: "GitHub",828      trigger: "autofilled" as const,829    };830    const first = await dispatch({ type: "FIRE_CANARY_PING", payload });831    expect(first).toMatchObject({ ok: true });832    expect(fetchMock).toHaveBeenCalledTimes(1);833834    const second = await dispatch({ type: "FIRE_CANARY_PING", payload });835    expect(second).toMatchObject({ ok: true, data: { rateLimited: true } });836    expect(fetchMock).toHaveBeenCalledTimes(1); // not fired again837  });838839  it("LV-3: debounce is per-entry — a different entry on the same webhook still fires", async () => {840    await dispatch({841      type: "FIRE_CANARY_PING",842      payload: { webhookUrl: "https://example.com/hook", entryTitle: "GitHub", trigger: "autofilled" },843    });844    await dispatch({845      type: "FIRE_CANARY_PING",846      payload: { webhookUrl: "https://example.com/hook", entryTitle: "GitLab", trigger: "autofilled" },847    });848    expect(fetchMock).toHaveBeenCalledTimes(2);849  });850851  it("LV-3: test pings are exempt from the debounce", async () => {852    const payload = {853      webhookUrl: "https://example.com/hook",854      entryTitle: "GitHub",855      trigger: "test" as const,856    };857    await dispatch({ type: "FIRE_CANARY_PING", payload });858    await dispatch({ type: "FIRE_CANARY_PING", payload });859    expect(fetchMock).toHaveBeenCalledTimes(2);860  });861862  it("rejects test pings from content scripts before contacting the webhook", async () => {863    const response = await dispatch(864      {865        type: "FIRE_CANARY_PING",866        payload: {867          webhookUrl: "https://example.com/hook",868          entryTitle: "GitHub",869          trigger: "test",870        },871      },872      {873        id: "peach-extension",874        url: "https://example.com/login",875        tab: { id: 7 },876      } as chrome.runtime.MessageSender,877    );878879    expect(response).toMatchObject({ ok: false, error: "invalid_sender" });880    expect(fetchMock).not.toHaveBeenCalled();881  });882883  it("FIRE_CANARY_PING rejects insecure webhook urls", async () => {884    await expect(885      dispatch({886        type: "FIRE_CANARY_PING",887        payload: {888          webhookUrl: "http://example.com/hook",889          entryTitle: "GitHub",890          trigger: "password_copied",891        },892      })893    ).resolves.toMatchObject({ ok: false, error: "invalid_webhook_url" });894895    expect(fetchMock).not.toHaveBeenCalled();896  });897898  it("F3: FIRE_CANARY_PING rejects IPv4-mapped IPv6 webhooks pointing at private ranges (Codex Security 2026-08-04)", async () => {899    for (const webhookUrl of [900      "https://[::ffff:192.168.0.1]/hook",901      "https://[::ffff:c0a8:1]/hook",902      "https://[::ffff:10.0.0.1]/hook",903      "https://[::ffff:127.0.0.1]/hook",904      "https://[::ffff:169.254.1.1]/hook",905      "https://[::ffff:172.16.0.1]/hook",906    ]) {907      await expect(908        dispatch({909          type: "FIRE_CANARY_PING",910          payload: { webhookUrl, entryTitle: "GitHub", trigger: "password_copied" },911        })912      ).resolves.toMatchObject({ ok: false, error: "invalid_webhook_url" });913    }914915    expect(fetchMock).not.toHaveBeenCalled();916  });917918  it("GET_IDENTITIES when locked returns vault locked error", async () => {919    const vault = await import("./vault");920    await vault.createVault("correct-pass-12345");921    vault.lock();922    await expect(dispatch({ type: "GET_IDENTITIES" })).resolves.toMatchObject({923      ok: false,924      error: "vault_locked",925    });926  });927928  it("GET_IDENTITIES returns emails and usernames derived from login entries", async () => {929    const vault = await import("./vault");930    await vault.createVault("correct-pass-12345");931    await vault.addEntry({ title: "Gmail", username: "[email protected]", password: "pw1", url: "https://gmail.com" });932    await vault.addEntry({ title: "GitHub", username: "[email protected]", password: "pw2", url: "https://github.com" });933    await vault.addEntry({ title: "Slack", username: "juni_patel", password: "pw3", url: "https://slack.com" });934935    const resp = await dispatch({ type: "GET_IDENTITIES" }) as { ok: boolean; data: unknown[] };936    expect(resp.ok).toBe(true);937    const data = resp.data as Array<{ value: string; type: string; useCount: number }>;938    expect(data.find((d) => d.value === "[email protected]")).toMatchObject({939      type: "email",940      useCount: 2,941    });942    expect(data.find((d) => d.value === "juni_patel")).toMatchObject({943      type: "username",944      useCount: 1,945    });946    // emails appear before usernames947    const emailIdx = data.findIndex((d) => d.value === "[email protected]");948    const userIdx = data.findIndex((d) => d.value === "juni_patel");949    expect(emailIdx).toBeLessThan(userIdx);950  });951952  it("GET_IDENTITIES deduplicates correctly — same email across 3 entries appears once with useCount 3", async () => {953    const vault = await import("./vault");954    await vault.createVault("correct-pass-12345");955    for (let i = 0; i < 3; i++) {956      await vault.addEntry({ title: `Site${i}`, username: "[email protected]", password: "pw", url: `https://site${i}.com` });957    }958959    const resp = await dispatch({ type: "GET_IDENTITIES" }) as { ok: boolean; data: unknown[] };960    const data = resp.data as Array<{ value: string; useCount: number }>;961    const hits = data.filter((d) => d.value === "[email protected]");962    expect(hits).toHaveLength(1);963    expect(hits[0]!.useCount).toBe(3);964  });965966  it("GET_IDENTITIES rejects content-script and page-relay senders", async () => {967    const vault = await import("./vault");968    await vault.createVault("correct-pass-12345");969    await vault.addEntry({970      title: "Private identity",971      username: "[email protected]",972      password: "pw",973      url: "https://private.example",974    });975976    const senders = [977      {978        id: "peach-extension",979        url: "https://private.example/signup",980        tab: { id: 1 } as chrome.tabs.Tab,981      },982      { id: "peach-extension", url: "https://private.example/signup" },983    ] satisfies chrome.runtime.MessageSender[];984    for (const sender of senders) {985      await expect(dispatch({ type: "GET_IDENTITIES" }, sender)).resolves.toMatchObject({986        ok: false,987        error: "invalid_sender",988      });989    }990  });991992  it("IS_CARD_DECLINED does not refresh the auto-lock timer", async () => {993    const vault = await import("./vault");994    await vault.createVault("correct-pass-12345");995    const alarmsCreate = chrome.alarms.create as unknown as ReturnType<typeof vi.fn>;996997    // Sanity: a non-excluded message (GET_ENTRIES) DOES refresh the timer998    alarmsCreate.mockClear();999    await dispatch({ type: "GET_ENTRIES" });1000    expect(alarmsCreate).toHaveBeenCalled();10011002    // Passive queries are in the exclusion list and must not re-arm1003    alarmsCreate.mockClear();1004    await dispatch({ type: "IS_CARD_DECLINED", payload: { origin: "https://example.com" } });1005    expect(alarmsCreate).not.toHaveBeenCalled();1006  });10071008  it("DESTROY_VAULT preserves the Pro license and celebration flag", async () => {1009    const vault = await import("./vault");1010    await vault.createVault("correct-pass-12345");1011    await vault.addEntry({ title: "Gmail", username: "june", password: "s", url: "https://mail.google.com" });10121013    // Simulate an activated Pro license + already-celebrated marker.1014    storage.peach_license = "PEACH-PRO-TEST-KEY";1015    storage.peach_pro_celebrated = true;10161017    const res = await dispatch({ type: "DESTROY_VAULT" }, { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" });1018    expect(res).toMatchObject({ ok: true });10191020    // Vault data is gone…1021    expect(storage.peach_vault_a).toBeUndefined();1022    // …but the paid license and celebration flag survive the wipe.1023    expect(storage.peach_license).toBe("PEACH-PRO-TEST-KEY");1024    expect(storage.peach_pro_celebrated).toBe(true);1025  });10261027  it("handleMessage waits for the restore gate before serving (cold-start: no premature onboarding/lock)", async () => {1028    const messages = await import("./messages");1029    const vault = await import("./vault");10301031    let resolveGate: () => void = () => {};1032    messages.setRestoreReady(new Promise<void>((r) => { resolveGate = r; }));10331034    let settled = false;1035    const pending = dispatch({ type: "HAS_VAULT" }).then((r) => { settled = true; return r; });10361037    // While restore is in flight the handler must NOT have answered yet —1038    // this is the window where the old code returned "no vault" → onboarding.1039    await new Promise((r) => setTimeout(r, 20));1040    expect(settled).toBe(false);10411042    // Restore completes (the vault becomes available), gate opens.1043    await vault.createVault("correct-pass-12345");1044    resolveGate();10451046    await expect(pending).resolves.toMatchObject({ ok: true, data: true });1047  });10481049  it("CREATE_VAULT rejects an empty master password (audit HIGH — no empty-key vault)", async () => {1050    const res = await dispatch({ type: "CREATE_VAULT", payload: { password: "" } });1051    expect(res.ok).toBe(false);1052    // Nothing was written — no vault exists.1053    const has = await dispatch({ type: "HAS_VAULT" });1054    expect((has as { data?: boolean }).data).toBe(false);1055  });10561057  it("GET_ENTRY_FOR_FILL sends a 6-digit TOTP code, never the seed (SEV-3-C)", async () => {1058    const vault = await import("./vault");1059    await vault.createVault("correct-pass-12345");1060    const e = await vault.addEntry({1061      title: "Mail",1062      username: "june",1063      password: "pw",1064      url: "https://mail.test",1065      totp: "JBSWY3DPEHPK3PXP",1066    });10671068    const res = await dispatch(1069      { type: "GET_ENTRY_FOR_FILL", payload: { id: e.id } },1070      { id: "peach-extension", url: "https://mail.test/login" },1071    );1072    expect(res.ok).toBe(true);1073    const data = res.data as { totp?: string; totpCode?: string; totpRemaining?: number };1074    expect(data.totp).toBeUndefined();1075    expect(data.totpCode).toMatch(/^\d{6}$/);1076    expect(data.totpRemaining).toBeGreaterThan(0);1077    expect(data.totpRemaining).toBeLessThanOrEqual(30);1078  });10791080  it("GET_ENTRY_FOR_FILL strips passwordHistory; GET_ENTRY_FOR_EDIT keeps it", async () => {1081    const vault = await import("./vault");1082    await vault.createVault("correct-pass-12345");1083    const e = await vault.addEntry({1084      title: "Bank",1085      username: "june",1086      password: "old-pw",1087      url: "https://bank.test",1088    });1089    await vault.updateEntry(e.id, { password: "new-pw" });10901091    const fill = await dispatch(1092      { type: "GET_ENTRY_FOR_FILL", payload: { id: e.id } },1093      { id: "peach-extension", url: "https://bank.test/login" },1094    );1095    expect(fill.ok).toBe(true);1096    // Passive autofill never receives prior passwords (blast-radius containment).1097    expect((fill.data as Record<string, unknown>).passwordHistory).toBeUndefined();10981099    const edit = await dispatch({ type: "GET_ENTRY_FOR_EDIT", payload: { id: e.id } });1100    expect(edit.ok).toBe(true);1101    const editHist = (edit.data as { passwordHistory?: Array<{ password: string }> }).passwordHistory ?? [];1102    expect(editHist.map((h) => h.password)).toEqual(["old-pw"]);1103  });11041105  it("GET_ENTRY_FOR_EDIT returns the raw TOTP seed for the trusted edit form", async () => {1106    const vault = await import("./vault");1107    await vault.createVault("correct-pass-12345");1108    const e = await vault.addEntry({1109      title: "Mail",1110      username: "june",1111      password: "pw",1112      url: "https://mail.test",1113      totp: "JBSWY3DPEHPK3PXP",1114    });11151116    const res = await dispatch({ type: "GET_ENTRY_FOR_EDIT", payload: { id: e.id } });1117    expect(res.ok).toBe(true);1118    const data = res.data as { totp?: string };1119    expect(data.totp).toBe("JBSWY3DPEHPK3PXP");1120  });11211122  it("DESTROY_VAULT with no license clears storage without resurrecting keys", async () => {1123    const vault = await import("./vault");1124    await vault.createVault("correct-pass-12345");11251126    const res = await dispatch({ type: "DESTROY_VAULT" }, { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" });1127    expect(res).toMatchObject({ ok: true });11281129    expect(storage.peach_vault_a).toBeUndefined();1130    expect(storage.peach_license).toBeUndefined();1131    expect(storage.peach_pro_celebrated).toBeUndefined();1132  });11331134  // --- MV-1: GET_ENTRY_FOR_FILL re-validates the requesting tab's origin ---11351136  function tabSender(url: string, tabId = 1, frameId = 0): chrome.runtime.MessageSender {1137    return { id: "peach-extension", tab: { id: tabId, url } as chrome.tabs.Tab, url, frameId };1138  }11391140  async function addPasskeyOnlyEntry(title: string, url: string) {1141    const vault = await import("./vault");1142    const generated = await generatePasskeyKeypair(-7);1143    return vault.addEntry({1144      type: "login",1145      title,1146      url,1147      passkey: {1148        rpId: new URL(url).hostname,1149        rpName: title,1150        credentialId: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1151        publicKeyCose: base64urlEncode(generated.publicKeyCose),1152        privateKeyJwk: generated.privateKeyJwk,1153        userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1154        userName: "june",1155        userDisplayName: "June",1156        algorithm: -7,1157        signCount: 0,1158        aaguid: "AAAAAAAAAAAAAAAAAAAAAA",1159        backupEligible: true,1160        backupState: false,1161        createdAt: Date.now(),1162      },1163    });1164  }11651166  it("PB-26-201: normal inventory ignores forged domain and gesture booleans", async () => {1167    const vault = await import("./vault");1168    await vault.createVault("correct-pass-12345");1169    await vault.addEntry({ title: "GitHub", username: "victim", password: "secret", url: "https://github.com" });1170    await vault.addEntry({ title: "Evil", username: "attacker", password: "known", url: "https://evil.example.com" });11711172    const result = await dispatch(1173      {1174        type: "AUTOFILL_QUERY",1175        payload: {1176          domain: "github.com",1177          includeAll: true,1178          userGesture: true,1179          explicitSummon: true,1180        },1181      },1182      tabSender("https://evil.example.com/phish"),1183    );11841185    expect(result).toMatchObject({ ok: true });1186    expect((result.data as Array<{ title: string }>).map((entry) => entry.title)).toEqual(["Evil"]);1187  });11881189  it("PB-26-201: normal TOTP inventory is scoped to the attested frame origin", async () => {1190    const vault = await import("./vault");1191    await vault.createVault("correct-pass-12345");1192    await vault.addEntry({ title: "GitHub 2FA", password: "secret", url: "https://github.com", totp: "JBSWY3DPEHPK3PXP" });1193    await vault.addEntry({ title: "Evil 2FA", password: "known", url: "https://evil.example.com", totp: "JBSWY3DPEHPK3PXP" });11941195    const result = await dispatch(1196      { type: "AUTOFILL_QUERY", payload: { domain: "github.com", kind: "totp" } },1197      tabSender("https://evil.example.com/verify"),1198    );11991200    expect((result.data as Array<{ title: string }>).map((entry) => entry.title)).toEqual(["Evil 2FA"]);1201  });12021203  it("PB-26-201: summon capability is one-shot after inventory authorization", async () => {1204    const vault = await import("./vault");1205    const messages = await import("./messages");1206    await vault.createVault("correct-pass-12345");1207    const entry = await vault.addEntry({ title: "GitHub", username: "june", password: "secret123", url: "https://github.com" });1208    const sender = tabSender("https://evil.example.com/phish");1209    const token = messages.createSummonCapability(1, "https://evil.example.com");12101211    const inventory = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1212    expect(inventory).toMatchObject({ ok: true, data: [{ id: entry.id }] });12131214    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1215    expect(firstFill).toMatchObject({ ok: true, data: { id: entry.id } });1216    const replay = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1217    expect(replay).toMatchObject({ ok: false, error: "entry_not_found" });1218  });12191220  it("PB-26-201: summon capability is consumed by a same-domain fill", async () => {1221    const vault = await import("./vault");1222    const messages = await import("./messages");1223    await vault.createVault("correct-pass-12345");1224    const entry = await vault.addEntry({ title: "GitHub", password: "secret123", url: "https://evil.example.com" });1225    const sender = tabSender("https://evil.example.com/login");1226    const token = messages.createSummonCapability(1, "https://evil.example.com");12271228    const inventory = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1229    expect(inventory).toMatchObject({ ok: true, data: [{ id: entry.id }] });1230    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1231    expect(firstFill).toMatchObject({ ok: true, data: { id: entry.id } });12321233    const offDomainReplay = await dispatch(1234      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1235      tabSender("https://github.com/login"),1236    );1237    expect(offDomainReplay).toMatchObject({ ok: false, error: "entry_not_found" });1238  });12391240  it("PB-26-201: summon capability cannot fill a different entry", async () => {1241    const vault = await import("./vault");1242    const messages = await import("./messages");1243    await vault.createVault("correct-pass-12345");1244    const first = await vault.addEntry({ title: "First", password: "one", url: "https://first.example" });1245    const second = await vault.addEntry({ title: "Second", password: "two", url: "https://second.example" });1246    const sender = tabSender("https://evil.example.com/phish");1247    const token = messages.createSummonCapability(1, "https://evil.example.com");1248    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1249    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: first.id, capability: token } }, sender);1250    expect(firstFill).toMatchObject({ ok: true, data: { id: first.id } });1251    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: second.id, capability: token } }, sender);1252    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1253    expect(first.id).not.toBe(second.id);1254  });12551256  it("PB-26-201: fill before inventory is rejected without an entry oracle", async () => {1257    const vault = await import("./vault");1258    const messages = await import("./messages");1259    await vault.createVault("correct-pass-12345");1260    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1261    const token = messages.createSummonCapability(1, "https://evil.example.com");1262    const result = await dispatch(1263      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1264      tabSender("https://evil.example.com/phish"),1265    );1266    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1267  });12681269  it("PB-26-201: an unused summon capability does not block a normal same-origin fill", async () => {1270    const vault = await import("./vault");1271    const messages = await import("./messages");1272    await vault.createVault("correct-pass-12345");1273    const entry = await vault.addEntry({1274      title: "Evil",1275      password: "known",1276      url: "https://evil.example.com",1277    });1278    const sender = tabSender("https://evil.example.com/login");1279    const token = messages.createSummonCapability(1, "https://evil.example.com");12801281    const result = await dispatch(1282      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1283      sender,1284    );12851286    expect(result).toMatchObject({ ok: true, data: { id: entry.id } });1287  });12881289  it("PB-26-201: expired fill capability is rejected before entry-specific errors", async () => {1290    vi.useFakeTimers();1291    vi.setSystemTime(new Date("2026-09-02T12:00:00Z"));1292    const vault = await import("./vault");1293    const messages = await import("./messages");1294    await vault.createVault("correct-pass-12345");1295    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1296    const sender = tabSender("https://evil.example.com/phish");1297    const token = messages.createSummonCapability(1, "https://evil.example.com");1298    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1299    vi.advanceTimersByTime(30_001);13001301    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1302    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1303  });13041305  it("PB-26-201: wrong-tab fill capability is rejected before entry-specific errors", async () => {1306    const vault = await import("./vault");1307    const messages = await import("./messages");1308    await vault.createVault("correct-pass-12345");1309    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1310    const token = messages.createSummonCapability(1, "https://evil.example.com");1311    await dispatch(1312      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1313      tabSender("https://evil.example.com/phish"),1314    );13151316    const result = await dispatch(1317      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1318      tabSender("https://evil.example.com/phish", 2),1319    );1320    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1321  });13221323  it("PB-26-201: wrong-frame fill capability is rejected before entry-specific errors", async () => {1324    const vault = await import("./vault");1325    const messages = await import("./messages");1326    await vault.createVault("correct-pass-12345");1327    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1328    const token = messages.createSummonCapability(1, "https://evil.example.com", 3);1329    await dispatch(1330      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1331      tabSender("https://evil.example.com/phish", 1, 3),1332    );13331334    const result = await dispatch(1335      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1336      tabSender("https://evil.example.com/phish", 1, 4),1337    );1338    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1339  });13401341  it("PB-26-201: wrong-origin fill capability is rejected before entry-specific errors", async () => {1342    const vault = await import("./vault");1343    const messages = await import("./messages");1344    await vault.createVault("correct-pass-12345");1345    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1346    const token = messages.createSummonCapability(1, "https://evil.example.com");1347    await dispatch(1348      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1349      tabSender("https://evil.example.com/phish"),1350    );13511352    const result = await dispatch(1353      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1354      tabSender("https://other.example.com/phish"),1355    );1356    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1357  });13581359  it("PB-26-201: selecting a missing id consumes the one-shot capability without an oracle", async () => {1360    const vault = await import("./vault");1361    const messages = await import("./messages");1362    await vault.createVault("correct-pass-12345");1363    const existing = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1364    const sender = tabSender("https://evil.example.com/phish");1365    const token = messages.createSummonCapability(1, "https://evil.example.com");1366    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);13671368    const missing = await dispatch(1369      { type: "GET_ENTRY_FOR_FILL", payload: { id: "missing", capability: token } },1370      sender,1371    );1372    const existingReplay = await dispatch(1373      { type: "GET_ENTRY_FOR_FILL", payload: { id: existing.id, capability: token } },1374      sender,1375    );1376    expect(missing).toMatchObject({ ok: false, error: "entry_not_found" });1377    expect(existingReplay).toEqual(missing);1378  });13791380  it("PB-26-201: inventory capability cannot be reused for a second inventory", async () => {1381    const vault = await import("./vault");1382    const messages = await import("./messages");1383    await vault.createVault("correct-pass-12345");1384    await vault.addEntry({ title: "GitHub", password: "secret", url: "https://github.com" });1385    const sender = tabSender("https://evil.example.com/phish");1386    const token = messages.createSummonCapability(1, "https://evil.example.com");1387    const first = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1388    const second = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);13891390    expect(first).toMatchObject({ ok: true, data: [{ title: "GitHub" }] });1391    expect(second).toMatchObject({ ok: false, error: "entry_not_found" });1392  });13931394  it("PB-26-201: cards require a capability and consume it on the selected fill", async () => {1395    const vault = await import("./vault");1396    const messages = await import("./messages");1397    await vault.createVault("correct-pass-12345");1398    const card = await vault.addEntry({1399      type: "card",1400      title: "Personal Visa",1401      cardholderName: "June Peach",1402      cardNumber: "4111111111111111",1403      cvc: "123",1404      expMonth: "12",1405      expYear: "2030",1406    });1407    const sender = tabSender("https://shop.example.com/checkout");1408    const passive = await dispatch(1409      { type: "AUTOFILL_QUERY", payload: { domain: "shop.example.com", kind: "card" } },1410      sender,1411    );1412    expect(passive).toMatchObject({ ok: true, data: [] });14131414    const token = messages.createSummonCapability(1, "https://shop.example.com");1415    const inventory = await dispatch(1416      { type: "AUTOFILL_QUERY", payload: { domain: "forged.example", kind: "card", capability: token } },1417      sender,1418    );1419    expect(inventory).toMatchObject({ ok: true, data: [{ id: card.id, title: "Personal Visa" }] });1420    expect((inventory.data as Array<Record<string, unknown>>)[0]).not.toHaveProperty("cardNumber");14211422    const fill = await dispatch(1423      { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1424      sender,1425    );1426    expect(fill).toMatchObject({ ok: true, data: { id: card.id, cardNumber: "4111111111111111" } });1427    const replay = await dispatch(1428      { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1429      sender,1430    );1431    expect(replay).toMatchObject({ ok: false, error: "entry_not_found" });1432  });14331434  it("PB-26-201: inline edit popup request stores only the selected entry id", async () => {1435    const result = await dispatch(1436      { type: "OPEN_POPUP", payload: { entryId: "entry-123" } },1437      tabSender("https://example.com/login"),1438    );14391440    expect(result).toMatchObject({ ok: true });1441    expect(sessionStorage.peach_open_entry).toBe("entry-123");1442    expect(sessionStorage.peach_inline_unlock).toBeUndefined();1443  });14441445  it("MV-1: tab request with a matching domain returns the entry", async () => {1446    const vault = await import("./vault");1447    await vault.createVault("correct-pass-12345");1448    const entry = await vault.addEntry({1449      title: "GitHub",1450      username: "june",1451      password: "secret123",1452      url: "https://github.com",1453    });14541455    const res = await dispatch(1456      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1457      tabSender("https://github.com/login"),1458    );1459    expect(res).toMatchObject({ ok: true, data: { id: entry.id } });1460  });14611462  it("MV-1: tab request with a mismatched domain and no explicitSummon is refused as entry_not_found", async () => {1463    const vault = await import("./vault");1464    await vault.createVault("correct-pass-12345");1465    const entry = await vault.addEntry({1466      title: "GitHub",1467      username: "june",1468      password: "secret123",1469      url: "https://github.com",1470    });14711472    const res = await dispatch(1473      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1474      tabSender("https://evil.example.com/phish"),1475    );1476    // Refused with the same error as a missing id — no cross-domain oracle.1477    expect(res).toMatchObject({ ok: false, error: "entry_not_found" });1478  });14791480  it("PB-26-201: explicitSummon cannot authorize off-domain fill", async () => {1481    const vault = await import("./vault");1482    await vault.createVault("correct-pass-12345");1483    const entry = await vault.addEntry({1484      title: "GitHub",1485      username: "june",1486      password: "secret123",1487      url: "https://github.com",1488    });14891490    const res = await dispatch(1491      {1492        type: "GET_ENTRY_FOR_FILL",1493        payload: { id: entry.id, explicitSummon: true },1494      },1495      tabSender("https://evil.example.com/phish"),1496    );1497    expect(res).toMatchObject({ ok: false, error: "entry_not_found" });1498  });14991500  it("MV-1: tab context with an unparseable URL is refused as origin_unverified", async () => {1501    const vault = await import("./vault");1502    await vault.createVault("correct-pass-12345");1503    const entry = await vault.addEntry({1504      title: "GitHub",1505      username: "june",1506      password: "secret123",1507      url: "https://github.com",1508    });15091510    const res = await dispatch(1511      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1512      tabSender("not a url"),1513    );1514    expect(res).toMatchObject({ ok: false, error: "origin_unverified" });1515  });15161517  // --- MV-2: vault-wide inventory only ships on an explicit user gesture ---15181519  async function seedTwoDomainVault() {1520    const vault = await import("./vault");1521    await vault.createVault("correct-pass-12345");1522    await vault.addEntry({1523      title: "GitHub",1524      username: "june",1525      password: "gh",1526      url: "https://github.com",1527    });1528    await vault.addEntry({1529      title: "Example",1530      username: "june",1531      password: "ex",1532      url: "https://example.com",1533    });1534  }15351536  it("MV-2: AUTOFILL_QUERY with includeAll but no userGesture returns only the domain-scoped list", async () => {1537    await seedTwoDomainVault();15381539    const res = await dispatch({1540      type: "AUTOFILL_QUERY",1541      payload: { domain: "github.com", includeAll: true },1542    });1543    expect(res.ok).toBe(true);1544    const data = res.data as Array<{ title: string }>;1545    // includeAll was stripped — only the github.com match comes back.1546    expect(data).toHaveLength(1);1547    expect(data[0].title).toBe("GitHub");1548  });15491550  it("PB-26-201: userGesture cannot authorize vault-wide inventory", async () => {1551    await seedTwoDomainVault();15521553    const res = await dispatch({1554      type: "AUTOFILL_QUERY",1555      payload: { domain: "github.com", includeAll: true, userGesture: true },1556    });1557    expect(res.ok).toBe(true);1558    const data = res.data as Array<{ title: string }>;1559    expect(data.map((d) => d.title)).toEqual(["GitHub"]);1560  });15611562  // --- MV-7: vouched device confirmation handlers ---15631564  async function seedPendingVouched(deviceId: string) {1565    await chrome.storage.local.set({1566      peach_pending_vouched_devices_v1: [{1567        deviceId,1568        deviceName: "New Pixel",1569        deviceType: "android",1570        longTermPublicKeyHex: "e".repeat(64),1571        signingPublicKeyHex: "a".repeat(64),1572        wsPort: 51234,1573        pairedAt: 1_700_000_000_020,1574        receivedAt: 1_700_000_000_050,1575        vouchedByDeviceId: "extension-issuer",1576      }],1577    });1578  }15791580  it("MV-7: CONFIRM_VOUCHED_DEVICE moves a pending device into the paired registry as vouched", async () => {1581    const vault = await import("./vault");1582    await vault.createVault("correct-pass-12345");1583    await seedPendingVouched("android-new");1584    const { findPairedDeviceById } = await import("./paired-devices");1585    const { listPendingVouchedDevices } = await import(1586      "./pending-vouched-devices"1587    );15881589    const res = await dispatch({1590      type: "CONFIRM_VOUCHED_DEVICE",1591      payload: { deviceId: "android-new" },1592    });1593    expect(res).toMatchObject({ ok: true });15941595    expect(await findPairedDeviceById("android-new")).toMatchObject({1596      deviceName: "New Pixel",1597      trustSource: "vouched",1598      longTermPublicKeyHex: "e".repeat(64),1599    });1600    expect(await listPendingVouchedDevices()).toHaveLength(0);1601  });16021603  it("S1: CONFIRM_VOUCHED_DEVICE refuses a pending device whose key is revoked", async () => {1604    const vault = await import("./vault");1605    await vault.createVault("correct-pass-12345");1606    await seedPendingVouched("android-relabelled");1607    const { findPairedDeviceById, revokeDeviceById, upsertPairedDevice } =1608      await import("./paired-devices");1609    const { listPendingVouchedDevices } = await import(1610      "./pending-vouched-devices"1611    );16121613    // The queue entry predates the revocation, and it carries a fresh id, so1614    // sweeping the queue by id at revocation time would not have caught it.1615    await upsertPairedDevice({1616      deviceId: "android-old",1617      deviceName: "New Pixel",1618      deviceType: "android",1619      longTermPublicKeyHex: "e".repeat(64),1620      signingPublicKeyHex: "a".repeat(64),1621      pairedAt: 1_700_000_000_000,1622      trustSource: "vouched",1623    });1624    await revokeDeviceById("android-old", "self");16251626    const res = await dispatch({1627      type: "CONFIRM_VOUCHED_DEVICE",1628      payload: { deviceId: "android-relabelled" },1629    });1630    expect(res).toMatchObject({ ok: false, error: "device_revoked" });1631    expect(await findPairedDeviceById("android-relabelled")).toBeNull();1632    expect(await listPendingVouchedDevices()).toHaveLength(0);1633  });16341635  it("MV-7: REJECT_VOUCHED_DEVICE clears the pending entry and never pairs it", async () => {1636    const vault = await import("./vault");1637    await vault.createVault("correct-pass-12345");1638    await seedPendingVouched("android-new");1639    const { findPairedDeviceById } = await import("./paired-devices");1640    const { listPendingVouchedDevices } = await import(1641      "./pending-vouched-devices"1642    );16431644    const res = await dispatch({1645      type: "REJECT_VOUCHED_DEVICE",1646      payload: { deviceId: "android-new" },1647    });1648    expect(res).toMatchObject({ ok: true });16491650    expect(await findPairedDeviceById("android-new")).toBeNull();1651    expect(await listPendingVouchedDevices()).toHaveLength(0);1652  });16531654  // --- unpair: UNPAIR_DEVICE revokes the device and drops it from the registry ---16551656  it("UNPAIR_DEVICE revokes a paired device, drops the row, and lists the revocation", async () => {1657    const vault = await import("./vault");1658    await vault.createVault("correct-pass-12345");1659    const { findPairedDeviceById, isDeviceRevoked, listDeviceRevocations, upsertPairedDevice } =1660      await import("./paired-devices");16611662    await upsertPairedDevice({1663      deviceId: "phone-1",1664      deviceName: "June's Phone",1665      deviceType: "android",1666      longTermPublicKeyHex: "a".repeat(64),1667      signingPublicKeyHex: "b".repeat(64),1668      pairedAt: 1_700_000_000_000,1669      trustSource: "direct",1670    });16711672    const res = await dispatch({1673      type: "UNPAIR_DEVICE",1674      payload: { deviceId: "phone-1" },1675    });1676    expect(res).toMatchObject({ ok: true });16771678    // The row is gone locally — re-listing must not surface it.1679    expect(await findPairedDeviceById("phone-1")).toBeNull();1680    // The revocation is recorded so a future manifest from a peer cannot1681    // resurrect this device under either the same id or the same key (MV-7 + S1).1682    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);1683    const records = await listDeviceRevocations();1684    expect(records).toHaveLength(1);1685    expect(records[0]).toMatchObject({1686      deviceId: "phone-1",1687      longTermPublicKeyHex: "a".repeat(64),1688      revokedByDeviceId: expect.any(String),1689    });1690  });16911692  it("UNPAIR_DEVICE on an unknown id is a no-op (ok) and writes no revocation", async () => {1693    const vault = await import("./vault");1694    await vault.createVault("correct-pass-12345");1695    const { listDeviceRevocations } = await import("./paired-devices");16961697    const res = await dispatch({1698      type: "UNPAIR_DEVICE",1699      payload: { deviceId: "never-paired" },1700    });1701    expect(res).toMatchObject({ ok: true });1702    // A revocation with the all-zero key sentinel is still written — the1703    // contract is that the user-intent is recorded even when the registry had1704    // no row. This is what blocks a peer from later vouched-adopting the same1705    // fresh id back in.1706    const records = await listDeviceRevocations();1707    expect(records).toHaveLength(1);1708    expect(records[0]).toMatchObject({1709      deviceId: "never-paired",1710      longTermPublicKeyHex: "0".repeat(64),1711    });1712  });17131714  it("UNPAIR_DEVICE refuses an empty payload with invalid_payload", async () => {1715    const res = await dispatch({1716      type: "UNPAIR_DEVICE",1717      payload: { deviceId: "" },1718    });1719    expect(res).toMatchObject({ ok: false, error: "invalid_payload" });1720  });17211722  // The old "fresh direct re-pair clears the old revocation" test dispatched1723  // COMPLETE_PAIRING, a handler deleted on 2026-08-04 (no legitimate senders;1724  // adoption runs in-background via relay-adoption-bg.ts). The live1725  // revocation-overlap repair is pinned in paired-devices.test.ts1726  // (repairPairedRevocationOverlaps, runs at service-worker boot).1727  it("F1: privileged handlers reject content-script senders but keep extension-page senders (Codex Security 2026-08-04)", async () => {1728    const vault = await import("./vault");1729    await vault.createVault("correct-pass-12345");1730    const contentScriptSender = {1731      id: "peach-extension",1732      url: "https://evil.example/page",1733    };1734    const extensionPageSender = {1735      id: "peach-extension",1736      url: "chrome-extension://peach-extension/popup.html",1737    };1738    const completion = { requestId: 1, rpId: "evil.example" };17391740    // Content-script senders must never reach the gated passkey-store handler.1741    await expect(1742      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, contentScriptSender)1743    ).resolves.toMatchObject({ ok: false, error: "invalid_sender" });17441745    // Extension-page senders still reach it — refused by the pending-ceremony1746    // binding, not by the sender gate.1747    await expect(1748      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)1749    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });1750  });17511752  it("F2: COMPLETE_FIREFOX_PASSKEY_CREATE must match the pending ceremony (Codex Security 2026-08-04)", async () => {1753    const vault = await import("./vault");1754    await vault.createVault("correct-pass-12345");1755    const extensionPageSender = {1756      id: "peach-extension",1757      url: "chrome-extension://peach-extension/popup.html",1758    };1759    const completion = {1760      requestId: 123,1761      rpId: "example.com",1762      rpName: "Example",1763      userName: "june",1764      userHandle: "BBBB",1765      credentialId: "cred-1",1766      publicKeyCose: "c3BraQ",1767      algorithm: -7 as const,1768    };17691770    // No pending ceremony at all -> refuse.1771    await expect(1772      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)1773    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });17741775    // Seed a background-minted pending ceremony.1776    sessionStorage.passkey_pending_firefox = {1777      requestId: 123,1778      type: "create",1779      rpId: "example.com",1780      rpName: "Example",1781      userName: "june",1782      browser: "firefox",1783      challenge: "AAAA",1784      userHandle: "BBBB",1785    };17861787    // Mismatched userHandle (attacker-forged completion) -> refuse.1788    await expect(1789      dispatch(1790        { type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: { ...completion, userHandle: "CCCC" } },1791        extensionPageSender1792      )1793    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });17941795    // Matching completion -> stored.1796    await expect(1797      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)1798    ).resolves.toMatchObject({ ok: true });1799    const entries = await dispatch({ type: "GET_ENTRIES" });1800    expect(entries).toMatchObject({ ok: true });1801    const stored = (entries as { data: Array<{ passkey?: { credentialId?: string } }> }).data;1802    expect(stored.some((entry) => entry.passkey?.credentialId === "cred-1")).toBe(true);1803  });18041805  it("F2: INITIATE_FIREFOX_PASSKEY_CREATE rejects an rpId the caller origin does not own (Codex Security 2026-08-04)", async () => {1806    await expect(1807      dispatch(1808        {1809          type: "INITIATE_FIREFOX_PASSKEY_CREATE",1810          payload: { rpId: "bank.example", rpName: "Bank", userName: "june" },1811        },1812        { id: "peach-extension", url: "https://evil.example/page" }1813      )1814    ).resolves.toMatchObject({ ok: false, error: "rpid_origin_mismatch" });1815  });18161817  it("after UNPAIR_DEVICE, a fresh id carrying the same revoked key is also refused (S1)", async () => {1818    // The cross-manifest refusal is exercised end-to-end in sync-vault-adapter.test.ts;1819    // here we just pin the storage-level invariant the UNPAIR_DEVICE call1820    // establishes, since the rest of the testbed's revoke coverage rides on1821    // this state.1822    const vault = await import("./vault");1823    await vault.createVault("correct-pass-12345");1824    const { isDeviceRevoked, revokeDeviceById, upsertPairedDevice } = await import(1825      "./paired-devices"1826    );18271828    await upsertPairedDevice({1829      deviceId: "phone-1",1830      deviceName: "June's Phone",1831      deviceType: "android",1832      longTermPublicKeyHex: "a".repeat(64),1833      signingPublicKeyHex: "b".repeat(64),1834      pairedAt: 1_700_000_000_000,1835      trustSource: "direct",1836    });18371838    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(false);1839    await revokeDeviceById("phone-1", "self");1840    // The key check is what blocks a re-vouch under a fresh id.1841    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);1842    expect(await isDeviceRevoked("fresh-id", "a".repeat(64))).toBe(true);1843  });18441845  // --- LV-4: GET_RECOVERY_WORDS requires a fresh password proof ---18461847  it("LV-4: GET_RECOVERY_WORDS without a password returns password_required", async () => {1848    const vault = await import("./vault");1849    await vault.createVault("correct-pass-12345");18501851    const res = await dispatch({ type: "GET_RECOVERY_WORDS", payload: {} });1852    expect(res).toMatchObject({ ok: false, error: "password_required" });1853  });18541855  it("LV-4: GET_RECOVERY_WORDS with a wrong password returns wrong_password and no words", async () => {1856    const vault = await import("./vault");1857    await vault.createVault("correct-pass-12345");18581859    const res = await dispatch({1860      type: "GET_RECOVERY_WORDS",1861      payload: { password: "not-the-password" },1862    });1863    expect(res).toMatchObject({ ok: false, error: "wrong_password" });1864    expect(res.data).toBeUndefined();1865  });18661867  it("LV-4: GET_RECOVERY_WORDS with the correct password returns 12 words", async () => {1868    const vault = await import("./vault");1869    await vault.createVault("correct-pass-12345");18701871    const res = await dispatch({1872      type: "GET_RECOVERY_WORDS",1873      payload: { password: "correct-pass-12345" },1874    });1875    expect(res.ok).toBe(true);1876    expect((res.data as string[]).length).toBe(12);1877  });18781879  it("PB-26-311: cleartext export requires a fresh master-password proof", async () => {1880    const vault = await import("./vault");1881    await vault.createVault("correct-pass-12345");18821883    await expect(1884      dispatch({ type: "EXPORT_ENTRIES" as never, payload: {} }),1885    ).resolves.toMatchObject({ ok: false, error: "password_required" });1886    await expect(1887      dispatch({1888        type: "EXPORT_ENTRIES" as never,1889        payload: { password: "not-the-password" },1890      }),1891    ).resolves.toMatchObject({ ok: false, error: "wrong_password" });1892    await expect(1893      dispatch({1894        type: "EXPORT_ENTRIES" as never,1895        payload: { password: "correct-pass-12345" },1896      }),1897    ).resolves.toMatchObject({ ok: true, data: [] });1898  });18991900  it("GET_PIN_STATUS reports only a session-available PIN wrapper", async () => {1901    const vault = await import("./vault");1902    const password = "correct-pass-12345";1903    const popupSender = {1904      id: "peach-extension",1905      url: "chrome-extension://peach-extension/src/popup/index.html",1906    } as chrome.runtime.MessageSender;19071908    await vault.createVault(password);1909    await vault.setupPinUnlock(password, "1234");1910    await vault.lock();19111912    await expect(dispatch({ type: "GET_PIN_STATUS" }, popupSender)).resolves.toMatchObject({1913      ok: true,1914      data: { configured: true, available: true, attemptsRemaining: 3 },1915    });1916  });1917});