messages.test.ts

78.9 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;2021/**22 * Chrome re-encodes everything it stores: `undefined` is dropped and object23 * keys come back in its own order, so a value read back is deep-equal to what24 * was set but never the same object nor the same JSON text. Storing the value25 * by reference would let an order-sensitive write-verify pass here and fail on26 * a real device — exactly how the secure-reset archive check shipped broken.27 */28function asChromeStores(value: unknown): unknown {29  if (Array.isArray(value)) return value.map(asChromeStores);30  if (value && typeof value === "object") {31    const source = value as StorageShape;32    const clone: StorageShape = {};33    for (const key of Object.keys(source).sort()) clone[key] = asChromeStores(source[key]);34    return clone;35  }36  return value;37}3839function storeWrite(target: StorageShape, next: StorageShape): void {40  for (const [key, value] of Object.entries(next)) {41    if (value === undefined) continue;42    target[key] = asChromeStores(value);43  }44}4546describe("background messages", () => {47  let storage: StorageShape;48  let sessionStorage: StorageShape;49  let listener: MessageListener;50  let fetchMock: ReturnType<typeof vi.fn>;5152  beforeEach(async () => {53    vi.resetModules();54    vi.useRealTimers();55    storage = {56      peach_settings: { breachMonitoring: false },57    };58    sessionStorage = {};59    fetchMock = vi.fn(async () => ({60      ok: true,61      status: 200,62      text: async () => "",63    }));64    vi.stubGlobal("fetch", fetchMock);65    vi.stubGlobal("__PEACH_E2E_PASSKEYS__", false);6667    const tabs = [{ id: 1 }];68    const chromeMock = {69      runtime: {70        id: "peach-extension",71        getURL: (p: string) => `chrome-extension://peach-extension/${p}`,72        onMessage: {73          addListener: vi.fn((fn: MessageListener) => {74            listener = fn;75          }),76        },77        sendMessage: vi.fn(async () => ({ ok: true })),78      },79      tabs: {80        query: vi.fn((_query: unknown, callback?: (tabs: Array<{ id?: number }>) => void) => {81          if (typeof callback === "function") {82            callback(tabs);83            return;84          }85          return Promise.resolve(tabs);86        }),87        sendMessage: vi.fn(async () => ({ ok: true })),88      },89      storage: {90        local: {91          get: vi.fn(async (key?: string | string[]) => {92            if (!key) return storage;93            if (typeof key === "string") {94              return { [key]: storage[key] };95            }9697            return key.reduce<Record<string, unknown>>((result, entry) => {98              result[entry] = storage[entry];99              return result;100            }, {});101          }),102          set: vi.fn(async (next: Record<string, unknown>) => {103            storeWrite(storage, 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 storage[key];109            }110          }),111          clear: vi.fn(async () => {112            for (const key of Object.keys(storage)) delete storage[key];113          }),114        },115        session: {116          get: vi.fn(async (key?: string | string[]) => {117            if (!key) return sessionStorage;118            if (typeof key === "string") {119              return { [key]: sessionStorage[key] };120            }121            return key.reduce<Record<string, unknown>>((result, entry) => {122              result[entry] = sessionStorage[entry];123              return result;124            }, {});125          }),126          set: vi.fn(async (next: Record<string, unknown>) => {127            storeWrite(sessionStorage, next);128          }),129          remove: vi.fn(async (keys: string | string[]) => {130            const list = Array.isArray(keys) ? keys : [keys];131            for (const key of list) {132              delete sessionStorage[key];133            }134          }),135          clear: vi.fn(async () => {136            for (const key of Object.keys(sessionStorage)) delete sessionStorage[key];137          }),138        },139        sync: {140          get: vi.fn(async (_key?: string | string[]) => ({})),141          set: vi.fn(async (_values: Record<string, unknown>) => undefined),142          remove: vi.fn(async (_keys: string | string[]) => undefined),143          clear: vi.fn(async () => undefined),144        },145      },146      alarms: {147        clear: vi.fn(),148        create: vi.fn(),149        onAlarm: { addListener: vi.fn() },150      },151      idle: {152        setDetectionInterval: vi.fn(),153        onStateChanged: { addListener: vi.fn() },154      },155      scripting: {156        executeScript: vi.fn(async () => []),157      },158    } as unknown as typeof chrome;159160    (globalThis as { chrome?: typeof chrome }).chrome = chromeMock;161162    const messages = await import("./messages");163    messages.setupMessageHandler();164    const vault = await import("./vault");165    await vault.ensureSettingsLoaded();166  });167168  async function dispatch(169    message: Message,170    sender: chrome.runtime.MessageSender = {171      id: "peach-extension",172      url: "chrome-extension://peach-extension/popup.html",173    }174  ): Promise<MessageResponse> {175    return await new Promise<MessageResponse>((resolve) => {176      const keepChannelOpen = listener(message, sender, (response) => resolve(response));177      expect(keepChannelOpen).toBe(true);178    });179  }180181  it("PB-26-303: page GET_SETTINGS returns only theme, accent, and its own summon record", async () => {182    storage.peach_settings = {183      theme: "dark",184      accentColor: "peach",185      autoLockMinutes: 5,186      pinEnabled: true,187      manualSummonDomains: {188        "example.com": { firstSummonedAt: 1, summonCount: 2, lastSummonedAt: 3 },189        "other.example": { firstSummonedAt: 4, summonCount: 5, lastSummonedAt: 6 },190      },191    };192    const response = await dispatch(193      { type: "GET_SETTINGS" },194      {195        id: "peach-extension",196        url: "https://login.example.com/form",197        tab: { id: 1 },198        frameId: 0,199      } as chrome.runtime.MessageSender,200    );201202    expect(response).toEqual({203      ok: true,204      data: {205        theme: "dark",206        accentColor: "peach",207        manualSummonDomains: {208          "example.com": { firstSummonedAt: 1, summonCount: 2, lastSummonedAt: 3 },209        },210      },211    });212    await expect(dispatch({ type: "GET_SETTINGS" })).resolves.toMatchObject({213      ok: true,214      data: {215        autoLockMinutes: 5,216        pinEnabled: true,217        manualSummonDomains: {218          "example.com": expect.anything(),219          "other.example": expect.anything(),220        },221      },222    });223  });224225  it("RECORD_MANUAL_SUMMON binds and bounds the sender domain", async () => {226    const sender = {227      id: "peach-extension",228      url: "https://login.example.com/form",229      origin: "https://login.example.com",230      tab: { id: 1 },231      frameId: 0,232    } as chrome.runtime.MessageSender;233234    await expect(dispatch({235      type: "RECORD_MANUAL_SUMMON",236      payload: { domain: "evil.example" },237    }, sender)).resolves.toEqual({ ok: false, error: "invalid_domain" });238    await expect(dispatch({239      type: "RECORD_MANUAL_SUMMON",240      payload: { domain: "example.com" },241    }, sender)).resolves.toEqual({ ok: true });242    await expect(dispatch({243      type: "RECORD_MANUAL_SUMMON",244      payload: { domain: "a".repeat(254) },245    }, { ...sender, origin: "https://a.com", url: "https://a.com/form" })).resolves.toEqual({246      ok: false,247      error: "invalid_domain",248    });249  });250251  it("GET_ENTRIES when unlocked returns the entry array", async () => {252    const vault = await import("./vault");253    await vault.createVault("correct-pass-12345");254    await vault.addEntry({255      title: "GitHub",256      username: "june",257      password: "secret123",258      url: "https://github.com",259    });260261    await expect(dispatch({ type: "GET_ENTRIES" })).resolves.toMatchObject({262      ok: true,263      data: [264        expect.objectContaining({265          title: "GitHub",266          username: "june",267        }),268      ],269    });270  });271272  it("GET_ENTRIES when locked returns a vault locked error", async () => {273    const vault = await import("./vault");274    await vault.createVault("correct-pass-12345");275    vault.lock();276277    await expect(dispatch({ type: "GET_ENTRIES" })).resolves.toMatchObject({278      ok: false,279      error: "vault_locked",280    });281  });282283  it("ADD_ENTRY with a valid payload returns the created entry", async () => {284    const vault = await import("./vault");285    await vault.createVault("correct-pass-12345");286287    const response = await dispatch({288      type: "ADD_ENTRY",289      payload: {290        title: "GitHub",291        username: "june",292        password: "secret123",293        url: "https://github.com",294      },295    });296297    expect(response).toMatchObject({298      ok: true,299      data: expect.objectContaining({300        id: expect.any(String),301        title: "GitHub",302      }),303    });304    expect(vault.getEntries()).toHaveLength(1);305  });306307  it("ADD_ENTRY when locked returns a vault locked error", async () => {308    const vault = await import("./vault");309    await vault.createVault("correct-pass-12345");310    vault.lock();311312    await expect(313      dispatch({314        type: "ADD_ENTRY",315        payload: {316          title: "GitHub",317          username: "june",318          password: "secret123",319          url: "https://github.com",320        },321      })322    ).resolves.toMatchObject({ ok: false, error: "vault_locked" });323  });324325  it("ADD_ENTRY with no password succeeds for email-only accounts", async () => {326    const vault = await import("./vault");327    await vault.createVault("correct-pass-12345");328329    await expect(330      dispatch({331        type: "ADD_ENTRY",332        payload: {333          title: "GitHub",334          username: "june",335          password: "",336          url: "https://github.com",337        },338      })339    ).resolves.toMatchObject({ ok: true });340  });341342  it("UPDATE_ENTRY updates an existing entry and returns ok", async () => {343    const vault = await import("./vault");344    await vault.createVault("correct-pass-12345");345    const entry = await vault.addEntry({346      title: "GitHub",347      username: "june",348      password: "secret123",349      url: "https://github.com",350    });351352    await expect(353      dispatch({354        type: "UPDATE_ENTRY",355        payload: { id: entry.id, patch: { password: "new-secret" } },356      })357    ).resolves.toMatchObject({ ok: true });358359    expect(vault.getEntryById(entry.id)?.password).toBe("new-secret");360  });361362  it("UPDATE_ENTRY with an empty password clears it for email-only accounts", async () => {363    const vault = await import("./vault");364    await vault.createVault("correct-pass-12345");365    const entry = await vault.addEntry({366      title: "GitHub",367      username: "june",368      password: "secret123",369      url: "https://github.com",370    });371372    await expect(373      dispatch({374        type: "UPDATE_ENTRY",375        payload: { id: entry.id, patch: { password: "" } },376      })377    ).resolves.toMatchObject({ ok: true });378379    expect(vault.getEntryById(entry.id)?.password).toBeUndefined();380  });381382  it("DELETE_ENTRY soft-deletes the target entry", async () => {383    const vault = await import("./vault");384    await vault.createVault("correct-pass-12345");385    const entry = await vault.addEntry({386      title: "GitHub",387      username: "june",388      password: "secret123",389      url: "https://github.com",390    });391392    await expect(393      dispatch({394        type: "DELETE_ENTRY",395        payload: { id: entry.id },396      })397    ).resolves.toMatchObject({ ok: true });398399    expect(vault.getEntries()).toEqual([]);400    expect(vault.getDeletedEntries()).toHaveLength(1);401  });402403  it("DELETE_ENTRY of a missing id returns an error", async () => {404    const vault = await import("./vault");405    await vault.createVault("correct-pass-12345");406407    await expect(408      dispatch({409        type: "DELETE_ENTRY",410        payload: { id: "missing" },411      })412    ).resolves.toMatchObject({ ok: false, error: "entry_not_found" });413  });414415  it("GET_ENTRY_FOR_FILL returns a safe login entry without privateKeyJwk", async () => {416    const vault = await import("./vault");417    await vault.createVault("correct-pass-12345");418    const entry = await vault.addEntry({419      title: "GitHub",420      username: "june",421      password: "secret123",422      url: "https://github.com",423    });424425    const response = await dispatch(426      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },427      { id: "peach-extension", url: "https://github.com/login" },428    );429430    expect(response).toMatchObject({431      ok: true,432      data: expect.objectContaining({433        id: entry.id,434        username: "june",435        password: "secret123",436      }),437    });438    expect((response.data as Record<string, unknown>).privateKeyJwk).toBeUndefined();439  });440441  it("GET_ENTRY_FOR_FILL when locked returns an error", async () => {442    const vault = await import("./vault");443    await vault.createVault("correct-pass-12345");444    vault.lock();445446    await expect(447      dispatch({448        type: "GET_ENTRY_FOR_FILL",449        payload: { id: "missing" },450      })451    ).resolves.toMatchObject({ ok: false, error: "vault_locked" });452  });453454  it("GET_ENTRY_FOR_FILL rejects passkey-only entries", async () => {455    const vault = await import("./vault");456    await vault.createVault("correct-pass-12345");457    const generated = await generatePasskeyKeypair(-7);458    const entry = await vault.addEntry({459      type: "login",460      title: "WebAuthn.io",461      passkey: {462        rpId: "webauthn.io",463        rpName: "WebAuthn.io",464        credentialId: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),465        publicKeyCose: base64urlEncode(generated.publicKeyCose),466        privateKeyJwk: generated.privateKeyJwk,467        userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),468        userName: "june",469        userDisplayName: "June",470        algorithm: -7,471        signCount: 0,472        aaguid: "AAAAAAAAAAAAAAAAAAAAAA",473        backupEligible: true,474        backupState: false,475        createdAt: Date.now(),476      },477    });478479    await expect(480      dispatch({481        type: "GET_ENTRY_FOR_FILL",482        payload: { id: entry.id },483      })484    ).resolves.toMatchObject({ ok: false, error: "passkey_not_fillable" });485  });486487  it("AUTOFILL_QUERY returns matched domain metadata without secrets", async () => {488    const vault = await import("./vault");489    await vault.createVault("correct-pass-12345");490    await vault.addEntry({491      title: "GitHub",492      username: "june",493      password: "secret123",494      url: "https://github.com",495      totp: "JBSWY3DPEHPK3PXP",496    });497498    const response = await dispatch({499      type: "AUTOFILL_QUERY",500      payload: { domain: "github.com" },501    });502503    expect(response).toMatchObject({504      ok: true,505      data: [506        {507          id: expect.any(String),508          title: "GitHub",509          username: "june",510          url: "https://github.com",511          hasTotp: true,512        },513      ],514    });515    expect((response.data as Array<Record<string, unknown>>)[0].password).toBeUndefined();516    expect((response.data as Array<Record<string, unknown>>)[0].totp).toBeUndefined();517  });518519  it("AUTOFILL_QUERY includeAll returns search-ready summaries for non-note, non-passkey entries", async () => {520    const vault = await import("./vault");521    await vault.createVault("correct-pass-12345");522    await vault.addEntry({523      title: "GitHub",524      username: "june",525      password: "secret123",526      url: "https://github.com",527    });528    await vault.addEntry({529      type: "note",530      title: "Secure note",531      notes: "hello",532    });533534    const response = await dispatch({535      type: "AUTOFILL_QUERY",536      payload: { domain: "github.com", includeAll: true },537    });538539    expect(response).toMatchObject({540      ok: true,541      data: [542        {543          id: expect.any(String),544          title: "GitHub",545          username: "june",546          url: "https://github.com",547          hasPasskey: false,548        },549      ],550    });551    const data = response.data as Array<Record<string, unknown>>;552    expect(data).toHaveLength(1);553    // No secrets cross the boundary.554    expect(data[0]).not.toHaveProperty("password");555    expect(data[0]).not.toHaveProperty("totp");556  });557558  it("AUTOFILL_QUERY kind=totp returns only matching entries with 2FA summaries", async () => {559    const vault = await import("./vault");560    await vault.createVault("correct-pass-12345");561    await vault.addEntry({562      title: "GitHub",563      username: "june",564      password: "secret123",565      url: "https://github.com",566      totp: "JBSWY3DPEHPK3PXP",567    });568    await vault.addEntry({569      title: "No 2FA",570      username: "person",571      password: "secret123",572      url: "https://github.com",573    });574575    const response = await dispatch({576      type: "AUTOFILL_QUERY",577      payload: { domain: "github.com", kind: "totp" },578    });579580    expect(response).toMatchObject({581      ok: true,582      data: [583        {584          id: expect.any(String),585          title: "GitHub",586          username: "june",587          url: "https://github.com",588          hasTotp: true,589        },590      ],591    });592    expect((response.data as Array<Record<string, unknown>>)[0].totp).toBeUndefined();593    expect(response.data).toHaveLength(1);594  });595596  it("RESTORE_ENTRIES replace mode restores the provided entries", async () => {597    const vault = await import("./vault");598    await vault.createVault("correct-pass-12345");599    await vault.addEntry({ title: "A", username: "", password: "one", url: "" });600601    const response = await dispatch({602      type: "RESTORE_ENTRIES",603      payload: {604        mode: "replace",605        entries: [606          {607            id: "restored-1",608            type: "login",609            title: "B",610            username: "june",611            password: "two",612            url: "https://b.test",613            createdAt: 1,614            modifiedAt: 1,615          },616        ],617      },618    });619620    expect(response).toMatchObject({ ok: true, data: { added: 1, updated: 0, skipped: 0 } });621    expect(vault.getEntries().map((entry) => entry.id)).toEqual(["restored-1"]);622  });623624  it("RESTORE_ENTRIES replace mode with an empty array returns an error", async () => {625    const vault = await import("./vault");626    await vault.createVault("correct-pass-12345");627628    await expect(629      dispatch({630        type: "RESTORE_ENTRIES",631        payload: { mode: "replace", entries: [] },632      })633    ).resolves.toMatchObject({ ok: false, error: "refuse to replace with empty entry set" });634  });635636  it("CHANGE_PASSWORD responds true for the happy path and false for a wrong current password", async () => {637    const vault = await import("./vault");638    await vault.createVault("correct-pass-12345");639640    await expect(641      dispatch({642        type: "CHANGE_PASSWORD",643        payload: {644          currentPassword: "correct-pass-12345",645          newPassword: "new-pass-67890",646        },647      })648    ).resolves.toMatchObject({ ok: true });649650    vault.lock();651    expect(await vault.unlock("new-pass-67890")).toBe(true);652653    await expect(654      dispatch({655        type: "CHANGE_PASSWORD",656        payload: {657          currentPassword: "wrong-pass",658          newPassword: "another-pass",659        },660      })661    ).resolves.toMatchObject({ ok: false, error: "incorrect_current_password" });662  });663664  it("UPDATE_SETTINGS reschedules auto-lock using the new minutes value", async () => {665    const vault = await import("./vault");666    await vault.createVault("correct-pass-12345");667668    (669      chrome.alarms.create as unknown as ReturnType<typeof vi.fn>670    ).mockClear();671    (672      chrome.idle.setDetectionInterval as unknown as ReturnType<typeof vi.fn>673    ).mockClear();674675    await expect(676      dispatch({677        type: "UPDATE_SETTINGS",678        payload: { autoLockMinutes: 30 },679      })680    ).resolves.toMatchObject({ ok: true });681682    expect(vault.getSettings().autoLockMinutes).toBe(30);683    expect(chrome.idle.setDetectionInterval).toHaveBeenLastCalledWith(1800);684    expect(chrome.alarms.create).toHaveBeenLastCalledWith("autolock", {685      delayInMinutes: 30,686    });687  });688689  it("CHECK_ALL_BREACHES updates matching entries without corrupting the vault", async () => {690    vi.useFakeTimers();691    const vault = await import("./vault");692    await vault.createVault("correct-pass-12345");693    const entry = await vault.addEntry({694      title: "GitHub",695      username: "june",696      password: "secret123",697      url: "https://github.com",698    });699    const breachSpy = vi.spyOn(vault, "checkBreach").mockResolvedValue(7);700701    const responsePromise = dispatch({ type: "CHECK_ALL_BREACHES" });702    await vi.runAllTimersAsync();703    const response = await responsePromise;704705    expect(response).toMatchObject({ ok: true, data: { [entry.id]: 7 } });706    expect(vault.getEntryById(entry.id)?.breach).toBe(7);707    breachSpy.mockRestore();708  });709710  it("rejects passkey approval from a different tab than the ceremony", async () => {711    sessionStorage.passkey_pending_301 = {712      requestId: 301,713      type: "get",714      rpId: "example.com",715      rpName: "Example",716      userName: "[email protected]",717      tabId: 7,718      origin: "https://example.com",719    };720721    await expect(722      dispatch(723        { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 301, approved: true } },724        { id: "peach-extension", tab: { id: 8 }, url: "https://example.com/login" } as chrome.runtime.MessageSender,725      ),726    ).resolves.toMatchObject({ ok: false, error: "invalid_passkey_approval_sender" });727  });728729  it("messages from foreign or URL-less senders are rejected", async () => {730    const vault = await import("./vault");731    await vault.createVault("correct-pass-12345");732733    await expect(dispatch({ type: "GET_ENTRIES" }, { id: "other-extension" })).resolves.toMatchObject({734      ok: false,735      error: "invalid_sender",736    });737738    await expect(dispatch({ type: "GET_ENTRIES" }, {})).resolves.toMatchObject({739      ok: false,740      error: "invalid_sender",741    });742  });743744  it("LOCK and UNLOCK messages update vault state correctly", async () => {745    const vault = await import("./vault");746747    await expect(748      dispatch({ type: "CREATE_VAULT", payload: { password: "correct-pass-12345" } })749    ).resolves.toMatchObject({ ok: true });750    expect(vault.isUnlocked()).toBe(true);751752    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });753    expect(vault.isUnlocked()).toBe(false);754755    await expect(756      dispatch({ type: "UNLOCK", payload: { password: "wrong-pass" } })757    ).resolves.toMatchObject({ ok: false });758    expect(vault.isUnlocked()).toBe(false);759760    await expect(761      dispatch({ type: "UNLOCK", payload: { password: "correct-pass-12345" } })762    ).resolves.toMatchObject({ ok: true });763    expect(vault.isUnlocked()).toBe(true);764  });765766  it("does not acknowledge LOCK until session cleanup finishes", async () => {767    await expect(768      dispatch({ type: "CREATE_VAULT", payload: { password: "correct-pass-12345" } })769    ).resolves.toMatchObject({ ok: true });770771    const removalStarted = deferred();772    const releaseRemoval = deferred();773    const remove = chrome.storage.session.remove as unknown as ReturnType<typeof vi.fn>;774    remove.mockImplementation(async (keys: string | string[]) => {775      removalStarted.resolve();776      await releaseRemoval.promise;777      for (const key of Array.isArray(keys) ? keys : [keys]) delete sessionStorage[key];778    });779780    let responded = false;781    const response = dispatch({ type: "LOCK" }).then((result) => {782      responded = true;783      return result;784    });785    await removalStarted.promise;786787    try {788      await Promise.resolve();789      expect(responded).toBe(false);790    } finally {791      releaseRemoval.resolve();792    }793794    await expect(response).resolves.toMatchObject({ ok: true });795  });796797  it("remembers the last successful unlock method", async () => {798    const vault = await import("./vault");799    const password = "correct-pass-12345";800    const popupSender = {801      id: "peach-extension",802      url: "chrome-extension://peach-extension/src/popup/index.html",803    } as chrome.runtime.MessageSender;804805    await vault.createVault(password);806    expect(await vault.setupPinUnlock(password, "1234")).toBe(true);807    vault.lock();808809    await expect(810      dispatch({ type: "UNLOCK_WITH_PIN", payload: { pin: "1234" } }, popupSender),811    ).resolves.toMatchObject({ ok: true });812    expect((await vault.ensureSettingsLoaded()).pinPreferred).toBe(true);813814    vault.lock();815    await expect(816      dispatch({ type: "UNLOCK", payload: { password } }, popupSender),817    ).resolves.toMatchObject({ ok: true });818    expect((await vault.ensureSettingsLoaded()).pinPreferred).toBe(false);819  });820821  it("FIRE_CANARY_PING sends a minimal payload to allowed HTTPS webhooks", async () => {822    const response = await dispatch({823      type: "FIRE_CANARY_PING",824      payload: {825        webhookUrl: "https://example.com/hook",826        entryTitle: "GitHub",827        trigger: "password_copied",828      },829    });830831    expect(response).toMatchObject({ ok: true });832    expect(fetchMock).toHaveBeenCalledWith(833      "https://example.com/hook",834      expect.objectContaining({835        method: "POST",836        headers: { "Content-Type": "application/json" },837        body: expect.any(String),838      })839    );840    const body = JSON.parse(fetchMock.mock.calls[0][1].body as string) as Record<string, unknown>;841    expect(body).toMatchObject({842      entry: "GitHub",843      trigger: "password_copied",844      source: "peach-extension",845    });846  });847848  it("LV-3: debounces a repeat non-test ping for the same webhook+entry", async () => {849    const payload = {850      webhookUrl: "https://example.com/hook",851      entryTitle: "GitHub",852      trigger: "autofilled" as const,853    };854    const first = await dispatch({ type: "FIRE_CANARY_PING", payload });855    expect(first).toMatchObject({ ok: true });856    expect(fetchMock).toHaveBeenCalledTimes(1);857    expect(Object.keys(storage).some((key) => key.includes("GitHub"))).toBe(false);858    expect(Object.keys(storage).some((key) => key.startsWith("canary-last-fetch:"))).toBe(true);859860    const second = await dispatch({ type: "FIRE_CANARY_PING", payload });861    expect(second).toMatchObject({ ok: true, data: { rateLimited: true } });862    expect(fetchMock).toHaveBeenCalledTimes(1); // not fired again863  });864865  it("LV-3: removes legacy plaintext rate-limit keys", async () => {866    const legacyKey = "canary-last-fetch:https://example.com/hook:GitHub";867    storage[legacyKey] = Date.now();868869    await dispatch({870      type: "FIRE_CANARY_PING",871      payload: { webhookUrl: "https://example.com/hook", entryTitle: "GitHub", trigger: "autofilled" },872    });873874    expect(storage[legacyKey]).toBeUndefined();875  });876877  it("LV-3: debounce is per-entry — a different entry on the same webhook still fires", async () => {878    await dispatch({879      type: "FIRE_CANARY_PING",880      payload: { webhookUrl: "https://example.com/hook", entryTitle: "GitHub", trigger: "autofilled" },881    });882    await dispatch({883      type: "FIRE_CANARY_PING",884      payload: { webhookUrl: "https://example.com/hook", entryTitle: "GitLab", trigger: "autofilled" },885    });886    expect(fetchMock).toHaveBeenCalledTimes(2);887  });888889  it("LV-3: test pings are exempt from the debounce", async () => {890    const payload = {891      webhookUrl: "https://example.com/hook",892      entryTitle: "GitHub",893      trigger: "test" as const,894    };895    await dispatch({ type: "FIRE_CANARY_PING", payload });896    await dispatch({ type: "FIRE_CANARY_PING", payload });897    expect(fetchMock).toHaveBeenCalledTimes(2);898  });899900  it("rejects test pings from content scripts before contacting the webhook", async () => {901    const response = await dispatch(902      {903        type: "FIRE_CANARY_PING",904        payload: {905          webhookUrl: "https://example.com/hook",906          entryTitle: "GitHub",907          trigger: "test",908        },909      },910      {911        id: "peach-extension",912        url: "https://example.com/login",913        tab: { id: 7 },914      } as chrome.runtime.MessageSender,915    );916917    expect(response).toMatchObject({ ok: false, error: "invalid_sender" });918    expect(fetchMock).not.toHaveBeenCalled();919  });920921  it("FIRE_CANARY_PING rejects insecure webhook urls", async () => {922    await expect(923      dispatch({924        type: "FIRE_CANARY_PING",925        payload: {926          webhookUrl: "http://example.com/hook",927          entryTitle: "GitHub",928          trigger: "password_copied",929        },930      })931    ).resolves.toMatchObject({ ok: false, error: "invalid_webhook_url" });932933    expect(fetchMock).not.toHaveBeenCalled();934  });935936  it("F3: FIRE_CANARY_PING rejects IPv4-mapped IPv6 webhooks pointing at private ranges (Codex Security 2026-08-04)", async () => {937    for (const webhookUrl of [938      "https://[::ffff:192.168.0.1]/hook",939      "https://[::ffff:c0a8:1]/hook",940      "https://[::ffff:10.0.0.1]/hook",941      "https://[::ffff:127.0.0.1]/hook",942      "https://[::ffff:169.254.1.1]/hook",943      "https://[::ffff:172.16.0.1]/hook",944    ]) {945      await expect(946        dispatch({947          type: "FIRE_CANARY_PING",948          payload: { webhookUrl, entryTitle: "GitHub", trigger: "password_copied" },949        })950      ).resolves.toMatchObject({ ok: false, error: "invalid_webhook_url" });951    }952953    expect(fetchMock).not.toHaveBeenCalled();954  });955956  it("GET_IDENTITIES when locked returns vault locked error", async () => {957    const vault = await import("./vault");958    await vault.createVault("correct-pass-12345");959    vault.lock();960    await expect(dispatch({ type: "GET_IDENTITIES" })).resolves.toMatchObject({961      ok: false,962      error: "vault_locked",963    });964  });965966  it("GET_IDENTITIES returns emails and usernames derived from login entries", async () => {967    const vault = await import("./vault");968    await vault.createVault("correct-pass-12345");969    await vault.addEntry({ title: "Gmail", username: "[email protected]", password: "pw1", url: "https://gmail.com" });970    await vault.addEntry({ title: "GitHub", username: "[email protected]", password: "pw2", url: "https://github.com" });971    await vault.addEntry({ title: "Slack", username: "juni_patel", password: "pw3", url: "https://slack.com" });972973    const resp = await dispatch({ type: "GET_IDENTITIES" }) as { ok: boolean; data: unknown[] };974    expect(resp.ok).toBe(true);975    const data = resp.data as Array<{ value: string; type: string; useCount: number }>;976    expect(data.find((d) => d.value === "[email protected]")).toMatchObject({977      type: "email",978      useCount: 2,979    });980    expect(data.find((d) => d.value === "juni_patel")).toMatchObject({981      type: "username",982      useCount: 1,983    });984    // emails appear before usernames985    const emailIdx = data.findIndex((d) => d.value === "[email protected]");986    const userIdx = data.findIndex((d) => d.value === "juni_patel");987    expect(emailIdx).toBeLessThan(userIdx);988  });989990  it("GET_IDENTITIES deduplicates correctly — same email across 3 entries appears once with useCount 3", async () => {991    const vault = await import("./vault");992    await vault.createVault("correct-pass-12345");993    for (let i = 0; i < 3; i++) {994      await vault.addEntry({ title: `Site${i}`, username: "[email protected]", password: "pw", url: `https://site${i}.com` });995    }996997    const resp = await dispatch({ type: "GET_IDENTITIES" }) as { ok: boolean; data: unknown[] };998    const data = resp.data as Array<{ value: string; useCount: number }>;999    const hits = data.filter((d) => d.value === "[email protected]");1000    expect(hits).toHaveLength(1);1001    expect(hits[0]!.useCount).toBe(3);1002  });10031004  it("GET_IDENTITIES rejects content-script and page-relay senders", async () => {1005    const vault = await import("./vault");1006    await vault.createVault("correct-pass-12345");1007    await vault.addEntry({1008      title: "Private identity",1009      username: "[email protected]",1010      password: "pw",1011      url: "https://private.example",1012    });10131014    const senders = [1015      {1016        id: "peach-extension",1017        url: "https://private.example/signup",1018        tab: { id: 1 } as chrome.tabs.Tab,1019      },1020      { id: "peach-extension", url: "https://private.example/signup" },1021    ] satisfies chrome.runtime.MessageSender[];1022    for (const sender of senders) {1023      await expect(dispatch({ type: "GET_IDENTITIES" }, sender)).resolves.toMatchObject({1024        ok: false,1025        error: "invalid_sender",1026      });1027    }1028  });10291030  it("IS_CARD_DECLINED does not refresh the auto-lock timer", async () => {1031    const vault = await import("./vault");1032    await vault.createVault("correct-pass-12345");1033    const alarmsCreate = chrome.alarms.create as unknown as ReturnType<typeof vi.fn>;10341035    // Sanity: a non-excluded message (GET_ENTRIES) DOES refresh the timer1036    alarmsCreate.mockClear();1037    await dispatch({ type: "GET_ENTRIES" });1038    expect(alarmsCreate).toHaveBeenCalled();10391040    // Passive queries are in the exclusion list and must not re-arm1041    alarmsCreate.mockClear();1042    await dispatch({ type: "IS_CARD_DECLINED", payload: { origin: "https://example.com" } });1043    expect(alarmsCreate).not.toHaveBeenCalled();1044  });10451046  it("DESTROY_VAULT preserves the Pro license and celebration flag", async () => {1047    const vault = await import("./vault");1048    await vault.createVault("correct-pass-12345");1049    await vault.addEntry({ title: "Gmail", username: "june", password: "s", url: "https://mail.google.com" });10501051    // Simulate an activated Pro license + already-celebrated marker.1052    storage.peach_license = "PEACH-PRO-TEST-KEY";1053    storage.peach_pro_celebrated = true;10541055    const res = await dispatch({ type: "DESTROY_VAULT" }, { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" });1056    expect(res).toMatchObject({ ok: true });10571058    // Vault data is gone…1059    expect(storage.peach_vault_a).toBeUndefined();1060    // …but the paid license and celebration flag survive the wipe.1061    expect(storage.peach_license).toBe("PEACH-PRO-TEST-KEY");1062    expect(storage.peach_pro_celebrated).toBe(true);1063  });10641065  it("handleMessage waits for the restore gate before serving (cold-start: no premature onboarding/lock)", async () => {1066    const messages = await import("./messages");1067    const vault = await import("./vault");10681069    let resolveGate: () => void = () => {};1070    messages.setRestoreReady(new Promise<void>((r) => { resolveGate = r; }));10711072    let settled = false;1073    const pending = dispatch({ type: "HAS_VAULT" }).then((r) => { settled = true; return r; });10741075    // While restore is in flight the handler must NOT have answered yet —1076    // this is the window where the old code returned "no vault" → onboarding.1077    await new Promise((r) => setTimeout(r, 20));1078    expect(settled).toBe(false);10791080    // Restore completes (the vault becomes available), gate opens.1081    await vault.createVault("correct-pass-12345");1082    resolveGate();10831084    await expect(pending).resolves.toMatchObject({ ok: true, data: true });1085  });10861087  it.each([null, true, false, 1, {}, "replace", "warned-import "])("CREATE_VAULT rejects malformed replacement intent %j", async (replacement) => {1088    const result = await dispatch({ type: "CREATE_VAULT", payload: { password: "new-password", replacement } });1089    expect(result).toMatchObject({ ok: false, error: "invalid_payload" });1090    expect(storage.peach_vault_a).toBeUndefined();1091  });10921093  it("CREATE_VAULT refuses ordinary replacement of an existing locked vault", async () => {1094    const vault = await import("./vault");1095    await vault.createVault("original-password");1096    await vault.lock();1097    const before = structuredClone(storage);1098    expect(await dispatch({ type: "CREATE_VAULT", payload: { password: "new-password" } })).toMatchObject({ ok: false, error: "vault_already_exists" });1099    expect(storage).toEqual(before);1100    expect(await vault.unlock("original-password")).toBe(true);1101  });11021103  it("CREATE_VAULT rejects an empty master password (audit HIGH — no empty-key vault)", async () => {1104    const res = await dispatch({ type: "CREATE_VAULT", payload: { password: "" } });1105    expect(res.ok).toBe(false);1106    // Nothing was written — no vault exists.1107    const has = await dispatch({ type: "HAS_VAULT" });1108    expect((has as { data?: boolean }).data).toBe(false);1109  });11101111  it("GET_ENTRY_FOR_FILL sends a 6-digit TOTP code, never the seed (SEV-3-C)", async () => {1112    const vault = await import("./vault");1113    await vault.createVault("correct-pass-12345");1114    const e = await vault.addEntry({1115      title: "Mail",1116      username: "june",1117      password: "pw",1118      url: "https://mail.test",1119      totp: "JBSWY3DPEHPK3PXP",1120    });11211122    const res = await dispatch(1123      { type: "GET_ENTRY_FOR_FILL", payload: { id: e.id } },1124      { id: "peach-extension", url: "https://mail.test/login" },1125    );1126    expect(res.ok).toBe(true);1127    const data = res.data as { totp?: string; totpCode?: string; totpRemaining?: number };1128    expect(data.totp).toBeUndefined();1129    expect(data.totpCode).toMatch(/^\d{6}$/);1130    expect(data.totpRemaining).toBeGreaterThan(0);1131    expect(data.totpRemaining).toBeLessThanOrEqual(30);1132  });11331134  it("GET_ENTRY_FOR_FILL strips passwordHistory; GET_ENTRY_FOR_EDIT keeps it", async () => {1135    const vault = await import("./vault");1136    await vault.createVault("correct-pass-12345");1137    const e = await vault.addEntry({1138      title: "Bank",1139      username: "june",1140      password: "old-pw",1141      url: "https://bank.test",1142    });1143    await vault.updateEntry(e.id, { password: "new-pw" });11441145    const fill = await dispatch(1146      { type: "GET_ENTRY_FOR_FILL", payload: { id: e.id } },1147      { id: "peach-extension", url: "https://bank.test/login" },1148    );1149    expect(fill.ok).toBe(true);1150    // Passive autofill never receives prior passwords (blast-radius containment).1151    expect((fill.data as Record<string, unknown>).passwordHistory).toBeUndefined();11521153    const edit = await dispatch({ type: "GET_ENTRY_FOR_EDIT", payload: { id: e.id } });1154    expect(edit.ok).toBe(true);1155    const editHist = (edit.data as { passwordHistory?: Array<{ password: string }> }).passwordHistory ?? [];1156    expect(editHist.map((h) => h.password)).toEqual(["old-pw"]);1157  });11581159  it("GET_ENTRY_FOR_EDIT returns the raw TOTP seed for the trusted edit form", async () => {1160    const vault = await import("./vault");1161    await vault.createVault("correct-pass-12345");1162    const e = await vault.addEntry({1163      title: "Mail",1164      username: "june",1165      password: "pw",1166      url: "https://mail.test",1167      totp: "JBSWY3DPEHPK3PXP",1168    });11691170    const res = await dispatch({ type: "GET_ENTRY_FOR_EDIT", payload: { id: e.id } });1171    expect(res.ok).toBe(true);1172    const data = res.data as { totp?: string };1173    expect(data.totp).toBe("JBSWY3DPEHPK3PXP");1174  });11751176  it("DESTROY_VAULT with no license clears storage without resurrecting keys", async () => {1177    const vault = await import("./vault");1178    await vault.createVault("correct-pass-12345");11791180    const res = await dispatch({ type: "DESTROY_VAULT" }, { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" });1181    expect(res).toMatchObject({ ok: true });11821183    expect(storage.peach_vault_a).toBeUndefined();1184    expect(storage.peach_license).toBeUndefined();1185    expect(storage.peach_pro_celebrated).toBeUndefined();1186  });11871188  // --- MV-1: GET_ENTRY_FOR_FILL re-validates the requesting tab's origin ---11891190  function tabSender(url: string, tabId = 1, frameId = 0): chrome.runtime.MessageSender {1191    return { id: "peach-extension", tab: { id: tabId, url } as chrome.tabs.Tab, url, frameId };1192  }11931194  async function addPasskeyOnlyEntry(title: string, url: string) {1195    const vault = await import("./vault");1196    const generated = await generatePasskeyKeypair(-7);1197    return vault.addEntry({1198      type: "login",1199      title,1200      url,1201      passkey: {1202        rpId: new URL(url).hostname,1203        rpName: title,1204        credentialId: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1205        publicKeyCose: base64urlEncode(generated.publicKeyCose),1206        privateKeyJwk: generated.privateKeyJwk,1207        userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1208        userName: "june",1209        userDisplayName: "June",1210        algorithm: -7,1211        signCount: 0,1212        aaguid: "AAAAAAAAAAAAAAAAAAAAAA",1213        backupEligible: true,1214        backupState: false,1215        createdAt: Date.now(),1216      },1217    });1218  }12191220  it("PB-26-201: normal inventory ignores forged domain and gesture booleans", async () => {1221    const vault = await import("./vault");1222    await vault.createVault("correct-pass-12345");1223    await vault.addEntry({ title: "GitHub", username: "victim", password: "secret", url: "https://github.com" });1224    await vault.addEntry({ title: "Evil", username: "attacker", password: "known", url: "https://evil.example.com" });12251226    const result = await dispatch(1227      {1228        type: "AUTOFILL_QUERY",1229        payload: {1230          domain: "github.com",1231          includeAll: true,1232          userGesture: true,1233          explicitSummon: true,1234        },1235      },1236      tabSender("https://evil.example.com/phish"),1237    );12381239    expect(result).toMatchObject({ ok: true });1240    expect((result.data as Array<{ title: string }>).map((entry) => entry.title)).toEqual(["Evil"]);1241  });12421243  it("PB-26-201: normal TOTP inventory is scoped to the attested frame origin", async () => {1244    const vault = await import("./vault");1245    await vault.createVault("correct-pass-12345");1246    await vault.addEntry({ title: "GitHub 2FA", password: "secret", url: "https://github.com", totp: "JBSWY3DPEHPK3PXP" });1247    await vault.addEntry({ title: "Evil 2FA", password: "known", url: "https://evil.example.com", totp: "JBSWY3DPEHPK3PXP" });12481249    const result = await dispatch(1250      { type: "AUTOFILL_QUERY", payload: { domain: "github.com", kind: "totp" } },1251      tabSender("https://evil.example.com/verify"),1252    );12531254    expect((result.data as Array<{ title: string }>).map((entry) => entry.title)).toEqual(["Evil 2FA"]);1255  });12561257  it("PB-26-201: summon capability is one-shot after inventory authorization", async () => {1258    const vault = await import("./vault");1259    const messages = await import("./messages");1260    await vault.createVault("correct-pass-12345");1261    const entry = await vault.addEntry({ title: "GitHub", username: "june", password: "secret123", url: "https://github.com" });1262    const sender = tabSender("https://evil.example.com/phish");1263    const token = messages.createSummonCapability(1, "https://evil.example.com");12641265    const inventory = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1266    expect(inventory).toMatchObject({ ok: true, data: [{ id: entry.id }] });12671268    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1269    expect(firstFill).toMatchObject({ ok: true, data: { id: entry.id } });1270    const replay = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1271    expect(replay).toMatchObject({ ok: false, error: "entry_not_found" });1272  });12731274  it("PB-26-201: summon capability is consumed by a same-domain fill", async () => {1275    const vault = await import("./vault");1276    const messages = await import("./messages");1277    await vault.createVault("correct-pass-12345");1278    const entry = await vault.addEntry({ title: "GitHub", password: "secret123", url: "https://evil.example.com" });1279    const sender = tabSender("https://evil.example.com/login");1280    const token = messages.createSummonCapability(1, "https://evil.example.com");12811282    const inventory = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1283    expect(inventory).toMatchObject({ ok: true, data: [{ id: entry.id }] });1284    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1285    expect(firstFill).toMatchObject({ ok: true, data: { id: entry.id } });12861287    const offDomainReplay = await dispatch(1288      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1289      tabSender("https://github.com/login"),1290    );1291    expect(offDomainReplay).toMatchObject({ ok: false, error: "entry_not_found" });1292  });12931294  it("PB-26-201: summon capability cannot fill a different entry", async () => {1295    const vault = await import("./vault");1296    const messages = await import("./messages");1297    await vault.createVault("correct-pass-12345");1298    const first = await vault.addEntry({ title: "First", password: "one", url: "https://first.example" });1299    const second = await vault.addEntry({ title: "Second", password: "two", url: "https://second.example" });1300    const sender = tabSender("https://evil.example.com/phish");1301    const token = messages.createSummonCapability(1, "https://evil.example.com");1302    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1303    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: first.id, capability: token } }, sender);1304    expect(firstFill).toMatchObject({ ok: true, data: { id: first.id } });1305    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: second.id, capability: token } }, sender);1306    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1307    expect(first.id).not.toBe(second.id);1308  });13091310  it("PB-26-201: fill before inventory is rejected without an entry oracle", async () => {1311    const vault = await import("./vault");1312    const messages = await import("./messages");1313    await vault.createVault("correct-pass-12345");1314    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1315    const token = messages.createSummonCapability(1, "https://evil.example.com");1316    const result = await dispatch(1317      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1318      tabSender("https://evil.example.com/phish"),1319    );1320    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1321  });13221323  it("PB-26-201: an unused summon capability does not block a normal same-origin fill", async () => {1324    const vault = await import("./vault");1325    const messages = await import("./messages");1326    await vault.createVault("correct-pass-12345");1327    const entry = await vault.addEntry({1328      title: "Evil",1329      password: "known",1330      url: "https://evil.example.com",1331    });1332    const sender = tabSender("https://evil.example.com/login");1333    const token = messages.createSummonCapability(1, "https://evil.example.com");13341335    const result = await dispatch(1336      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1337      sender,1338    );13391340    expect(result).toMatchObject({ ok: true, data: { id: entry.id } });1341  });13421343  it("PB-26-201: expired fill capability is rejected before entry-specific errors", async () => {1344    vi.useFakeTimers();1345    vi.setSystemTime(new Date("2026-09-02T12:00:00Z"));1346    const vault = await import("./vault");1347    const messages = await import("./messages");1348    await vault.createVault("correct-pass-12345");1349    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1350    const sender = tabSender("https://evil.example.com/phish");1351    const token = messages.createSummonCapability(1, "https://evil.example.com");1352    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1353    vi.advanceTimersByTime(30_001);13541355    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1356    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1357  });13581359  it("PB-26-201: wrong-tab fill capability is rejected before entry-specific errors", async () => {1360    const vault = await import("./vault");1361    const messages = await import("./messages");1362    await vault.createVault("correct-pass-12345");1363    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1364    const token = messages.createSummonCapability(1, "https://evil.example.com");1365    await dispatch(1366      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1367      tabSender("https://evil.example.com/phish"),1368    );13691370    const result = await dispatch(1371      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1372      tabSender("https://evil.example.com/phish", 2),1373    );1374    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1375  });13761377  it("PB-26-201: wrong-frame fill capability is rejected before entry-specific errors", async () => {1378    const vault = await import("./vault");1379    const messages = await import("./messages");1380    await vault.createVault("correct-pass-12345");1381    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1382    const token = messages.createSummonCapability(1, "https://evil.example.com", 3);1383    await dispatch(1384      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1385      tabSender("https://evil.example.com/phish", 1, 3),1386    );13871388    const result = await dispatch(1389      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1390      tabSender("https://evil.example.com/phish", 1, 4),1391    );1392    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1393  });13941395  it("PB-26-201: wrong-origin fill capability is rejected before entry-specific errors", async () => {1396    const vault = await import("./vault");1397    const messages = await import("./messages");1398    await vault.createVault("correct-pass-12345");1399    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1400    const token = messages.createSummonCapability(1, "https://evil.example.com");1401    await dispatch(1402      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1403      tabSender("https://evil.example.com/phish"),1404    );14051406    const result = await dispatch(1407      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1408      tabSender("https://other.example.com/phish"),1409    );1410    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1411  });14121413  it("PB-26-201: selecting a missing id consumes the one-shot capability without an oracle", async () => {1414    const vault = await import("./vault");1415    const messages = await import("./messages");1416    await vault.createVault("correct-pass-12345");1417    const existing = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1418    const sender = tabSender("https://evil.example.com/phish");1419    const token = messages.createSummonCapability(1, "https://evil.example.com");1420    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);14211422    const missing = await dispatch(1423      { type: "GET_ENTRY_FOR_FILL", payload: { id: "missing", capability: token } },1424      sender,1425    );1426    const existingReplay = await dispatch(1427      { type: "GET_ENTRY_FOR_FILL", payload: { id: existing.id, capability: token } },1428      sender,1429    );1430    expect(missing).toMatchObject({ ok: false, error: "entry_not_found" });1431    expect(existingReplay).toEqual(missing);1432  });14331434  it("PB-26-201: inventory capability cannot be reused for a second inventory", async () => {1435    const vault = await import("./vault");1436    const messages = await import("./messages");1437    await vault.createVault("correct-pass-12345");1438    await vault.addEntry({ title: "GitHub", password: "secret", url: "https://github.com" });1439    const sender = tabSender("https://evil.example.com/phish");1440    const token = messages.createSummonCapability(1, "https://evil.example.com");1441    const first = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1442    const second = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);14431444    expect(first).toMatchObject({ ok: true, data: [{ title: "GitHub" }] });1445    expect(second).toMatchObject({ ok: false, error: "entry_not_found" });1446  });14471448  it("PB-26-201: cards require a capability and consume it on the selected fill", async () => {1449    const vault = await import("./vault");1450    const messages = await import("./messages");1451    await vault.createVault("correct-pass-12345");1452    const card = await vault.addEntry({1453      type: "card",1454      title: "Personal Visa",1455      cardholderName: "June Peach",1456      cardNumber: "4111111111111111",1457      cvc: "123",1458      expMonth: "12",1459      expYear: "2030",1460    });1461    const sender = tabSender("https://shop.example.com/checkout");1462    const passive = await dispatch(1463      { type: "AUTOFILL_QUERY", payload: { domain: "shop.example.com", kind: "card" } },1464      sender,1465    );1466    expect(passive).toMatchObject({ ok: true, data: [] });14671468    const token = messages.createSummonCapability(1, "https://shop.example.com");1469    const inventory = await dispatch(1470      { type: "AUTOFILL_QUERY", payload: { domain: "forged.example", kind: "card", capability: token } },1471      sender,1472    );1473    expect(inventory).toMatchObject({ ok: true, data: [{ id: card.id, title: "Personal Visa" }] });1474    expect((inventory.data as Array<Record<string, unknown>>)[0]).not.toHaveProperty("cardNumber");14751476    const fill = await dispatch(1477      { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1478      sender,1479    );1480    expect(fill).toMatchObject({ ok: true, data: { id: card.id, cardNumber: "4111111111111111" } });1481    const replay = await dispatch(1482      { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1483      sender,1484    );1485    expect(replay).toMatchObject({ ok: false, error: "entry_not_found" });1486  });14871488  it("PB-26-201: inline edit popup request stores only the selected entry id", async () => {1489    const result = await dispatch(1490      { type: "OPEN_POPUP", payload: { entryId: "entry-123" } },1491      tabSender("https://example.com/login"),1492    );14931494    expect(result).toMatchObject({ ok: true });1495    expect(sessionStorage.peach_open_entry).toBe("entry-123");1496    expect(sessionStorage.peach_inline_unlock).toBeUndefined();1497  });14981499  it("MV-1: tab request with a matching domain returns the entry", async () => {1500    const vault = await import("./vault");1501    await vault.createVault("correct-pass-12345");1502    const entry = await vault.addEntry({1503      title: "GitHub",1504      username: "june",1505      password: "secret123",1506      url: "https://github.com",1507    });15081509    const res = await dispatch(1510      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1511      tabSender("https://github.com/login"),1512    );1513    expect(res).toMatchObject({ ok: true, data: { id: entry.id } });1514  });15151516  it("MV-1: tab request with a mismatched domain and no explicitSummon is refused as entry_not_found", async () => {1517    const vault = await import("./vault");1518    await vault.createVault("correct-pass-12345");1519    const entry = await vault.addEntry({1520      title: "GitHub",1521      username: "june",1522      password: "secret123",1523      url: "https://github.com",1524    });15251526    const res = await dispatch(1527      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1528      tabSender("https://evil.example.com/phish"),1529    );1530    // Refused with the same error as a missing id — no cross-domain oracle.1531    expect(res).toMatchObject({ ok: false, error: "entry_not_found" });1532  });15331534  it("PB-26-201: explicitSummon cannot authorize off-domain fill", async () => {1535    const vault = await import("./vault");1536    await vault.createVault("correct-pass-12345");1537    const entry = await vault.addEntry({1538      title: "GitHub",1539      username: "june",1540      password: "secret123",1541      url: "https://github.com",1542    });15431544    const res = await dispatch(1545      {1546        type: "GET_ENTRY_FOR_FILL",1547        payload: { id: entry.id, explicitSummon: true },1548      },1549      tabSender("https://evil.example.com/phish"),1550    );1551    expect(res).toMatchObject({ ok: false, error: "entry_not_found" });1552  });15531554  it("MV-1: tab context with an unparseable URL is refused as origin_unverified", async () => {1555    const vault = await import("./vault");1556    await vault.createVault("correct-pass-12345");1557    const entry = await vault.addEntry({1558      title: "GitHub",1559      username: "june",1560      password: "secret123",1561      url: "https://github.com",1562    });15631564    const res = await dispatch(1565      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1566      tabSender("not a url"),1567    );1568    expect(res).toMatchObject({ ok: false, error: "origin_unverified" });1569  });15701571  // --- MV-2: vault-wide inventory only ships on an explicit user gesture ---15721573  async function seedTwoDomainVault() {1574    const vault = await import("./vault");1575    await vault.createVault("correct-pass-12345");1576    await vault.addEntry({1577      title: "GitHub",1578      username: "june",1579      password: "gh",1580      url: "https://github.com",1581    });1582    await vault.addEntry({1583      title: "Example",1584      username: "june",1585      password: "ex",1586      url: "https://example.com",1587    });1588  }15891590  it("MV-2: AUTOFILL_QUERY with includeAll but no userGesture returns only the domain-scoped list", async () => {1591    await seedTwoDomainVault();15921593    const res = await dispatch({1594      type: "AUTOFILL_QUERY",1595      payload: { domain: "github.com", includeAll: true },1596    });1597    expect(res.ok).toBe(true);1598    const data = res.data as Array<{ title: string }>;1599    // includeAll was stripped — only the github.com match comes back.1600    expect(data).toHaveLength(1);1601    expect(data[0].title).toBe("GitHub");1602  });16031604  it("PB-26-201: userGesture cannot authorize vault-wide inventory", async () => {1605    await seedTwoDomainVault();16061607    const res = await dispatch({1608      type: "AUTOFILL_QUERY",1609      payload: { domain: "github.com", includeAll: true, userGesture: true },1610    });1611    expect(res.ok).toBe(true);1612    const data = res.data as Array<{ title: string }>;1613    expect(data.map((d) => d.title)).toEqual(["GitHub"]);1614  });16151616  it("PB-26-104: decoy pairing messages hide devices and prior sync outcome", async () => {1617    const vault = await import("./vault");1618    const { listPairedDevices, upsertPairedDevice } = await import("./paired-devices");1619    const { setSyncRunner, triggerSyncIfReachable } = await import("./sync-trigger");1620    await vault.createVault("correct-pass-12345");1621    await vault.setupDuress("decoy-pass-67890");1622    await upsertPairedDevice({1623      deviceId: "android-real",1624      deviceName: "Real Pixel",1625      deviceType: "android",1626      longTermPublicKeyHex: "a".repeat(64),1627      trustSource: "direct",1628      pairedAt: 1_700_000_000_000,1629    });1630    setSyncRunner(async () => ({ ok: true, entriesReceived: 3, entriesSent: 2 }));1631    await triggerSyncIfReachable({ reason: "manual" });16321633    await vault.lock();1634    expect(await vault.unlock("decoy-pass-67890")).toBe(true);1635    await expect(dispatch({ type: "LIST_PAIRED_DEVICES" })).resolves.toEqual({1636      ok: true,1637      data: { devices: [] },1638    });1639    await expect(dispatch({ type: "GET_SYNC_STATE" })).resolves.toEqual({1640      ok: true,1641      data: { status: "idle" },1642    });1643    expect((await listPairedDevices()).map((device) => device.deviceName)).toEqual(["Real Pixel"]);1644  });16451646  it("PB-26-104: real unlocked pairing messages retain the device list", async () => {1647    const vault = await import("./vault");1648    const { upsertPairedDevice } = await import("./paired-devices");1649    await vault.createVault("correct-pass-12345");1650    await upsertPairedDevice({1651      deviceId: "android-real",1652      deviceName: "Real Pixel",1653      deviceType: "android",1654      longTermPublicKeyHex: "a".repeat(64),1655      trustSource: "direct",1656      pairedAt: 1_700_000_000_000,1657    });16581659    await expect(dispatch({ type: "LIST_PAIRED_DEVICES" })).resolves.toMatchObject({1660      ok: true,1661      data: { devices: [{ deviceId: "android-real", deviceName: "Real Pixel" }] },1662    });1663  });16641665  async function seedPendingVouched(deviceId: string) {1666    await chrome.storage.local.set({1667      peach_pending_vouched_devices_v1: [{1668        deviceId,1669        deviceName: "New Pixel",1670        deviceType: "android",1671        longTermPublicKeyHex: "e".repeat(64),1672        signingPublicKeyHex: "a".repeat(64),1673        wsPort: 51234,1674        pairedAt: 1_700_000_000_020,1675        receivedAt: 1_700_000_000_050,1676        vouchedByDeviceId: "extension-issuer",1677      }],1678    });1679  }16801681  it("MV-7: CONFIRM_VOUCHED_DEVICE moves a pending device into the paired registry as vouched", async () => {1682    const vault = await import("./vault");1683    await vault.createVault("correct-pass-12345");1684    await seedPendingVouched("android-new");1685    const { findPairedDeviceById } = await import("./paired-devices");1686    const { listPendingVouchedDevices } = await import(1687      "./pending-vouched-devices"1688    );16891690    const res = await dispatch({1691      type: "CONFIRM_VOUCHED_DEVICE",1692      payload: { deviceId: "android-new" },1693    });1694    expect(res).toMatchObject({ ok: true });16951696    expect(await findPairedDeviceById("android-new")).toMatchObject({1697      deviceName: "New Pixel",1698      trustSource: "vouched",1699      longTermPublicKeyHex: "e".repeat(64),1700    });1701    expect(await listPendingVouchedDevices()).toHaveLength(0);1702  });17031704  it("S1: CONFIRM_VOUCHED_DEVICE refuses a pending device whose key is revoked", async () => {1705    const vault = await import("./vault");1706    await vault.createVault("correct-pass-12345");1707    await seedPendingVouched("android-relabelled");1708    const { findPairedDeviceById, revokeDeviceById, upsertPairedDevice } =1709      await import("./paired-devices");1710    const { listPendingVouchedDevices } = await import(1711      "./pending-vouched-devices"1712    );17131714    // The queue entry predates the revocation, and it carries a fresh id, so1715    // sweeping the queue by id at revocation time would not have caught it.1716    await upsertPairedDevice({1717      deviceId: "android-old",1718      deviceName: "New Pixel",1719      deviceType: "android",1720      longTermPublicKeyHex: "e".repeat(64),1721      signingPublicKeyHex: "a".repeat(64),1722      pairedAt: 1_700_000_000_000,1723      trustSource: "vouched",1724    });1725    await revokeDeviceById("android-old", "self");17261727    const res = await dispatch({1728      type: "CONFIRM_VOUCHED_DEVICE",1729      payload: { deviceId: "android-relabelled" },1730    });1731    expect(res).toMatchObject({ ok: false, error: "device_revoked" });1732    expect(await findPairedDeviceById("android-relabelled")).toBeNull();1733    expect(await listPendingVouchedDevices()).toHaveLength(0);1734  });17351736  it("MV-7: REJECT_VOUCHED_DEVICE clears the pending entry and never pairs it", async () => {1737    const vault = await import("./vault");1738    await vault.createVault("correct-pass-12345");1739    await seedPendingVouched("android-new");1740    const { findPairedDeviceById } = await import("./paired-devices");1741    const { listPendingVouchedDevices } = await import(1742      "./pending-vouched-devices"1743    );17441745    const res = await dispatch({1746      type: "REJECT_VOUCHED_DEVICE",1747      payload: { deviceId: "android-new" },1748    });1749    expect(res).toMatchObject({ ok: true });17501751    expect(await findPairedDeviceById("android-new")).toBeNull();1752    expect(await listPendingVouchedDevices()).toHaveLength(0);1753  });17541755  // --- unpair: UNPAIR_DEVICE revokes the device and drops it from the registry ---17561757  it("UNPAIR_DEVICE revokes a paired device, drops the row, and lists the revocation", async () => {1758    const vault = await import("./vault");1759    await vault.createVault("correct-pass-12345");1760    // Every real install mints its identity with (or before) its vault, so a1761    // fixture that seeds trust state without one is an install §11.5 refuses.1762    const identity = await import("./device-identity");1763    await identity.getOrCreateDeviceId();1764    const { findPairedDeviceById, isDeviceRevoked, listDeviceRevocations, upsertPairedDevice } =1765      await import("./paired-devices");17661767    await upsertPairedDevice({1768      deviceId: "phone-1",1769      deviceName: "June's Phone",1770      deviceType: "android",1771      longTermPublicKeyHex: "a".repeat(64),1772      signingPublicKeyHex: "b".repeat(64),1773      pairedAt: 1_700_000_000_000,1774      trustSource: "direct",1775    });17761777    const res = await dispatch({1778      type: "UNPAIR_DEVICE",1779      payload: { deviceId: "phone-1" },1780    });1781    expect(res).toMatchObject({ ok: true });17821783    // The row is gone locally — re-listing must not surface it.1784    expect(await findPairedDeviceById("phone-1")).toBeNull();1785    // The revocation is recorded so a future manifest from a peer cannot1786    // resurrect this device under either the same id or the same key (MV-7 + S1).1787    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);1788    const records = await listDeviceRevocations();1789    expect(records).toHaveLength(1);1790    expect(records[0]).toMatchObject({1791      deviceId: "phone-1",1792      longTermPublicKeyHex: "a".repeat(64),1793      revokedByDeviceId: expect.any(String),1794    });1795  });1796  it("UNPAIR_DEVICE still evicts a peer when the local identity needs migration", async () => {1797    const vault = await import("./vault");1798    await vault.createVault("correct-pass-12345");1799    const identity = await import("./device-identity");1800    await identity.getOrCreateDeviceId();1801    delete storage.peach_local_identity_v4;1802    delete sessionStorage.peach_local_identity_session;1803    const { findPairedDeviceById, isDeviceRevoked, upsertPairedDevice } = await import("./paired-devices");1804    await upsertPairedDevice({1805      deviceId: "phone-1",1806      deviceName: "June's Phone",1807      deviceType: "android",1808      longTermPublicKeyHex: "a".repeat(64),1809      signingPublicKeyHex: "b".repeat(64),1810      pairedAt: 1_700_000_000_000,1811      trustSource: "direct",1812    });18131814    const response = await dispatch({ type: "UNPAIR_DEVICE", payload: { deviceId: "phone-1" } });18151816    expect(response).toMatchObject({ ok: true });1817    expect(await findPairedDeviceById("phone-1")).toBeNull();1818    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);1819  });18201821  it("UNPAIR_DEVICE on an unknown id is a no-op (ok) and writes no revocation", async () => {1822    const vault = await import("./vault");1823    await vault.createVault("correct-pass-12345");1824    const { listDeviceRevocations } = await import("./paired-devices");18251826    const res = await dispatch({1827      type: "UNPAIR_DEVICE",1828      payload: { deviceId: "never-paired" },1829    });1830    expect(res).toMatchObject({ ok: true });1831    // A revocation with the all-zero key sentinel is still written — the1832    // contract is that the user-intent is recorded even when the registry had1833    // no row. This is what blocks a peer from later vouched-adopting the same1834    // fresh id back in.1835    const records = await listDeviceRevocations();1836    expect(records).toHaveLength(1);1837    expect(records[0]).toMatchObject({1838      deviceId: "never-paired",1839      longTermPublicKeyHex: "0".repeat(64),1840    });1841  });18421843  it("UNPAIR_DEVICE refuses an empty payload with invalid_payload", async () => {1844    const res = await dispatch({1845      type: "UNPAIR_DEVICE",1846      payload: { deviceId: "" },1847    });1848    expect(res).toMatchObject({ ok: false, error: "invalid_payload" });1849  });1850  it("SECURE_RESET archives legacy trust, rotates identity, and reaches the new Sync anchor", async () => {1851    const vault = await import("./vault");1852    await vault.createVault("correct-pass-12345");1853    const identity = await import("./device-identity");1854    const previousDeviceId = await identity.getOrCreateDeviceId();1855    const { upsertPairedDevice } = await import("./paired-devices");1856    await upsertPairedDevice({1857      deviceId: "phone-1",1858      deviceName: "June's Phone",1859      deviceType: "android",1860      longTermPublicKeyHex: "a".repeat(64),1861      signingPublicKeyHex: "b".repeat(64),1862      pairedAt: 1_700_000_000_000,1863      trustSource: "direct",1864    });18651866    const response = await dispatch({1867      type: "SECURE_RESET",1868      payload: { password: "correct-pass-12345" },1869    });18701871    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });1872    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);1873  });1874  it("SECURE_RESET unlocks a locked real vault before rotating identity", async () => {1875    const vault = await import("./vault");1876    await vault.createVault("correct-pass-12345");1877    const identity = await import("./device-identity");1878    const previousDeviceId = await identity.getOrCreateDeviceId();1879    const { upsertPairedDevice } = await import("./paired-devices");1880    await upsertPairedDevice({1881      deviceId: "phone-1",1882      deviceName: "June's Phone",1883      deviceType: "android",1884      longTermPublicKeyHex: "a".repeat(64),1885      signingPublicKeyHex: "b".repeat(64),1886      pairedAt: 1_700_000_000_000,1887      trustSource: "direct",1888    });1889    await vault.lock();1890    expect(vault.isUnlocked()).toBe(false);18911892    const response = await dispatch({1893      type: "SECURE_RESET",1894      payload: { password: "correct-pass-12345" },1895    });18961897    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });1898    expect(vault.isUnlocked()).toBe(true);1899    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);1900  });1901  it("SECURE_RESET completes after fresh unlock when the locked spool hits identity migration", async () => {1902    const vault = await import("./vault");1903    const syncAdapter = await import("./sync-vault-adapter");1904    vault.setLockedSyncHooks({1905      refresh: syncAdapter.refreshLockedSyncSpool,1906      afterUnlock: syncAdapter.drainAndRefreshLockedSyncSpool,1907    });1908    await vault.createVault("correct-pass-12345");1909    const identity = await import("./device-identity");1910    const previousDeviceId = await identity.getOrCreateDeviceId();1911    const { upsertPairedDevice } = await import("./paired-devices");1912    await upsertPairedDevice({1913      deviceId: "phone-1",1914      deviceName: "June's Phone",1915      deviceType: "android",1916      longTermPublicKeyHex: "a".repeat(64),1917      signingPublicKeyHex: "b".repeat(64),1918      pairedAt: 1_700_000_000_000,1919      trustSource: "direct",1920    });1921    await vault.addEntry({ type: "login", title: "spooled", password: "secret" });1922    await syncAdapter.refreshLockedSyncSpool();1923    await vault.lock();1924    const { createLockedSyncVaultAdapter } = await import("./locked-sync-spool");1925    const lockedAdapter = await createLockedSyncVaultAdapter();1926    expect(lockedAdapter).not.toBeNull();1927    await lockedAdapter!.applyEntries({ remote: "AA==" }, { remote: Date.now() + 1 });1928    delete storage.peach_local_identity_v4;1929    delete sessionStorage.peach_local_identity_session;1930    const sessionSet = chrome.storage.session.set as unknown as ReturnType<typeof vi.fn>;1931    sessionSet.mockImplementation(async (next: Record<string, unknown>) => {1932      if (Object.hasOwn(next, "peach_local_identity_session")) {1933        throw new Error("QUOTA_BYTES");1934      }1935      Object.assign(sessionStorage, next);1936    });19371938    const unlocked = await dispatch({1939      type: "UNLOCK",1940      payload: { password: "correct-pass-12345" },1941    });1942    const pairSecrets = await import("./pair-secrets");1943    const root = Uint8Array.from((vault.getRootKeyHex() ?? "").match(/../g)!, (part) => Number.parseInt(part, 16));1944    await pairSecrets.setPairSecret("phone-1", "c".repeat(64), root);1945    root.fill(0);1946    expect(storage.peach_pair_secrets_v1).toBeDefined();1947    expect(sessionStorage.peach_pair_secrets_session).toBeDefined();1948    expect(unlocked).toMatchObject({ ok: true });19491950    const response = await dispatch({1951      type: "SECURE_RESET",1952      payload: { password: "correct-pass-12345" },1953    });19541955    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });1956    expect(storage.peach_local_identity_v4).toBeDefined();1957    expect(storage.peach_paired_devices_v3).toBeUndefined();1958    expect(storage.peach_pair_secrets_v1).toBeUndefined();1959    expect(sessionStorage.peach_pair_secrets_session).toBeUndefined();1960    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);1961  });1962  // The old "fresh direct re-pair clears the old revocation" test dispatched1963  // COMPLETE_PAIRING, a handler deleted on 2026-08-04 (no legitimate senders;1964  // adoption runs in-background via relay-adoption-bg.ts). The live1965  // revocation-overlap repair is pinned in paired-devices.test.ts1966  // (repairPairedRevocationOverlaps, runs at service-worker boot).1967  it("F1: privileged handlers reject content-script senders but keep extension-page senders (Codex Security 2026-08-04)", async () => {1968    const vault = await import("./vault");1969    await vault.createVault("correct-pass-12345");1970    const contentScriptSender = {1971      id: "peach-extension",1972      url: "https://evil.example/page",1973    };1974    const extensionPageSender = {1975      id: "peach-extension",1976      url: "chrome-extension://peach-extension/popup.html",1977    };1978    const completion = { requestId: 1, rpId: "evil.example" };19791980    // Content-script senders must never reach the gated passkey-store handler.1981    await expect(1982      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, contentScriptSender)1983    ).resolves.toMatchObject({ ok: false, error: "invalid_sender" });19841985    // Extension-page senders still reach it — refused by the pending-ceremony1986    // binding, not by the sender gate.1987    await expect(1988      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)1989    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });1990  });19911992  it("F2: COMPLETE_FIREFOX_PASSKEY_CREATE must match the pending ceremony (Codex Security 2026-08-04)", async () => {1993    const vault = await import("./vault");1994    await vault.createVault("correct-pass-12345");1995    const extensionPageSender = {1996      id: "peach-extension",1997      url: "chrome-extension://peach-extension/popup.html",1998    };1999    const completion = {2000      requestId: 123,2001      rpId: "example.com",2002      rpName: "Example",2003      userName: "june",2004      userHandle: "BBBB",2005      credentialId: "cred-1",2006      publicKeyCose: "c3BraQ",2007      algorithm: -7 as const,2008    };20092010    // No pending ceremony at all -> refuse.2011    await expect(2012      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2013    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });20142015    // Seed a background-minted pending ceremony.2016    sessionStorage.passkey_pending_firefox = {2017      requestId: 123,2018      type: "create",2019      rpId: "example.com",2020      rpName: "Example",2021      userName: "june",2022      browser: "firefox",2023      challenge: "AAAA",2024      userHandle: "BBBB",2025    };20262027    // Mismatched userHandle (attacker-forged completion) -> refuse.2028    await expect(2029      dispatch(2030        { type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: { ...completion, userHandle: "CCCC" } },2031        extensionPageSender2032      )2033    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });20342035    // Matching completion -> stored.2036    await expect(2037      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2038    ).resolves.toMatchObject({ ok: true });2039    const entries = await dispatch({ type: "GET_ENTRIES" });2040    expect(entries).toMatchObject({ ok: true });2041    const stored = (entries as { data: Array<{ passkey?: { credentialId?: string } }> }).data;2042    expect(stored.some((entry) => entry.passkey?.credentialId === "cred-1")).toBe(true);2043  });20442045  it("F2: INITIATE_FIREFOX_PASSKEY_CREATE rejects an rpId the caller origin does not own (Codex Security 2026-08-04)", async () => {2046    await expect(2047      dispatch(2048        {2049          type: "INITIATE_FIREFOX_PASSKEY_CREATE",2050          payload: { rpId: "bank.example", rpName: "Bank", userName: "june" },2051        },2052        { id: "peach-extension", url: "https://evil.example/page" }2053      )2054    ).resolves.toMatchObject({ ok: false, error: "rpid_origin_mismatch" });2055  });20562057  it("after UNPAIR_DEVICE, a fresh id carrying the same revoked key is also refused (S1)", async () => {2058    // The cross-manifest refusal is exercised end-to-end in sync-vault-adapter.test.ts;2059    // here we just pin the storage-level invariant the UNPAIR_DEVICE call2060    // establishes, since the rest of the testbed's revoke coverage rides on2061    // this state.2062    const vault = await import("./vault");2063    await vault.createVault("correct-pass-12345");2064    const { isDeviceRevoked, revokeDeviceById, upsertPairedDevice } = await import(2065      "./paired-devices"2066    );20672068    await upsertPairedDevice({2069      deviceId: "phone-1",2070      deviceName: "June's Phone",2071      deviceType: "android",2072      longTermPublicKeyHex: "a".repeat(64),2073      signingPublicKeyHex: "b".repeat(64),2074      pairedAt: 1_700_000_000_000,2075      trustSource: "direct",2076    });20772078    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(false);2079    await revokeDeviceById("phone-1", "self");2080    // The key check is what blocks a re-vouch under a fresh id.2081    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);2082    expect(await isDeviceRevoked("fresh-id", "a".repeat(64))).toBe(true);2083  });20842085  // --- LV-4: GET_RECOVERY_WORDS requires a fresh password proof ---20862087  it("LV-4: GET_RECOVERY_WORDS without a password returns password_required", async () => {2088    const vault = await import("./vault");2089    await vault.createVault("correct-pass-12345");20902091    const res = await dispatch({ type: "GET_RECOVERY_WORDS", payload: {} });2092    expect(res).toMatchObject({ ok: false, error: "password_required" });2093  });20942095  it("LV-4: GET_RECOVERY_WORDS with a wrong password returns wrong_password and no words", async () => {2096    const vault = await import("./vault");2097    await vault.createVault("correct-pass-12345");20982099    const res = await dispatch({2100      type: "GET_RECOVERY_WORDS",2101      payload: { password: "not-the-password" },2102    });2103    expect(res).toMatchObject({ ok: false, error: "wrong_password" });2104    expect(res.data).toBeUndefined();2105  });21062107  it("LV-4: GET_RECOVERY_WORDS with the correct password returns 12 words", async () => {2108    const vault = await import("./vault");2109    await vault.createVault("correct-pass-12345");21102111    const res = await dispatch({2112      type: "GET_RECOVERY_WORDS",2113      payload: { password: "correct-pass-12345" },2114    });2115    expect(res.ok).toBe(true);2116    expect((res.data as string[]).length).toBe(12);2117  });21182119  it("PB-26-311: cleartext export requires a fresh master-password proof", async () => {2120    const vault = await import("./vault");2121    await vault.createVault("correct-pass-12345");21222123    await expect(2124      dispatch({ type: "EXPORT_ENTRIES" as never, payload: {} }),2125    ).resolves.toMatchObject({ ok: false, error: "password_required" });2126    await expect(2127      dispatch({2128        type: "EXPORT_ENTRIES" as never,2129        payload: { password: "not-the-password" },2130      }),2131    ).resolves.toMatchObject({ ok: false, error: "wrong_password" });2132    await expect(2133      dispatch({2134        type: "EXPORT_ENTRIES" as never,2135        payload: { password: "correct-pass-12345" },2136      }),2137    ).resolves.toMatchObject({ ok: true, data: [] });2138  });21392140  it("GET_PIN_STATUS reports only a session-available PIN wrapper", async () => {2141    const vault = await import("./vault");2142    const password = "correct-pass-12345";2143    const popupSender = {2144      id: "peach-extension",2145      url: "chrome-extension://peach-extension/src/popup/index.html",2146    } as chrome.runtime.MessageSender;21472148    await vault.createVault(password);2149    await vault.setupPinUnlock(password, "1234");2150    await vault.lock();21512152    await expect(dispatch({ type: "GET_PIN_STATUS" }, popupSender)).resolves.toMatchObject({2153      ok: true,2154      data: { configured: true, available: true, attemptsRemaining: 3 },2155    });2156  });2157});