messages.test.ts

108.8 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 acknowledges then persists its background result", async () => {690    const vault = await import("./vault");691    await vault.createVault("correct-pass-12345");692    await vault.updateSettings({ breachMonitoring: false });693    const entry = await vault.addEntry({ type: "login", title: "GitHub", username: "june", password: "password", url: "https://github.com" });694    fetchMock.mockResolvedValueOnce({ ok: true, text: async () => "1E4C9B93F3F0682250B6CF8331B7EE68FD8:7" });695    const response = await dispatch({ type: "CHECK_ALL_BREACHES" });696    expect(response).toMatchObject({ ok: true, data: { state: "running", total: 1 } });697    await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete"));698    expect(vault.getEntryById(entry.id)?.breach).toBe(7);699    expect(await dispatch({ type: "GET_BREACH_SCAN_STATUS" })).toMatchObject({ ok: true, data: { state: "complete", scanned: 1, breached: 1 } });700  });701702  it("rejects page breach scan status requests", async () => {703    expect(await dispatch({ type: "GET_BREACH_SCAN_STATUS" }, { id: "peach-extension", url: "https://example.com" })).toMatchObject({ ok: false, error: "invalid_sender" });704  });705706  it("rejects passkey approval from a different tab than the ceremony", async () => {707    sessionStorage.passkey_pending_301 = {708      requestId: 301,709      type: "get",710      rpId: "example.com",711      rpName: "Example",712      userName: "[email protected]",713      tabId: 7,714      origin: "https://example.com",715    };716717    await expect(718      dispatch(719        { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 301, approved: true } },720        { id: "peach-extension", tab: { id: 8 }, url: "https://example.com/login" } as chrome.runtime.MessageSender,721      ),722    ).resolves.toMatchObject({ ok: false, error: "invalid_passkey_approval_sender" });723  });724725  it("requires trusted popup approval for embedded passkey requests", async () => {726    sessionStorage.passkey_pending_302 = {727      requestId: 302, type: "get", rpId: "login.example", rpName: "Login",728      userName: "june", origin: "https://login.example", crossOrigin: true,729    };730    for (const origin of ["https://top.example", "https://login.example"]) {731      await expect(dispatch(732        { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 302, approved: true } },733        { id: "peach-extension", tab: { id: 7 }, origin, url: `${origin}/login` } as chrome.runtime.MessageSender,734      )).resolves.toMatchObject({ ok: false, error: "invalid_passkey_approval_sender" });735      expect(sessionStorage.passkey_pending_302).toBeDefined();736    }737    await expect(dispatch({ type: "APPROVE_PASSKEY", payload: { requestId: 302 } })).resolves.toMatchObject({ ok: true });738    expect(sessionStorage.passkey_pending_302).toBeUndefined();739  });740741  it.each([false, true])("rejects content approval without a bound toast (missing pending: %s)", async (missing) => {742    if (!missing) sessionStorage.passkey_pending_303 = {743      requestId: 303, type: "get", rpId: "example.com", rpName: "Example",744      userName: "june", origin: "https://example.com", crossOrigin: false,745    };746    await expect(dispatch(747      { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 303, approved: true } },748      { id: "peach-extension", tab: { id: 7 }, url: "https://example.com/login" } as chrome.runtime.MessageSender,749    )).resolves.toMatchObject({ ok: false, error: "invalid_passkey_approval_sender" });750    if (!missing) expect(sessionStorage.passkey_pending_303).toBeDefined();751  });752753  it.each([true, false])("accepts bound same-origin toast consent: %s", async (approved) => {754    sessionStorage.passkey_pending_304 = {755      requestId: 304, type: "get", rpId: "example.com", rpName: "Example",756      userName: "june", tabId: 7, origin: "https://example.com", crossOrigin: false,757    };758    await expect(dispatch(759      { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 304, approved } },760      { id: "peach-extension", tab: { id: 7 }, url: "https://example.com/login" } as chrome.runtime.MessageSender,761    )).resolves.toMatchObject({ ok: true });762    expect(sessionStorage.passkey_pending_304).toBeUndefined();763  });764765  it("messages from foreign or URL-less senders are rejected", async () => {766    const vault = await import("./vault");767    await vault.createVault("correct-pass-12345");768769    await expect(dispatch({ type: "GET_ENTRIES" }, { id: "other-extension" })).resolves.toMatchObject({770      ok: false,771      error: "invalid_sender",772    });773774    await expect(dispatch({ type: "GET_ENTRIES" }, {})).resolves.toMatchObject({775      ok: false,776      error: "invalid_sender",777    });778  });779780  it("LOCK and UNLOCK messages update vault state correctly", async () => {781    const vault = await import("./vault");782783    await expect(784      dispatch({ type: "CREATE_VAULT", payload: { password: "correct-pass-12345" } })785    ).resolves.toMatchObject({ ok: true });786    expect(vault.isUnlocked()).toBe(true);787788    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });789    expect(vault.isUnlocked()).toBe(false);790791    await expect(792      dispatch({ type: "UNLOCK", payload: { password: "wrong-pass" } })793    ).resolves.toMatchObject({ ok: false });794    expect(vault.isUnlocked()).toBe(false);795796    await expect(797      dispatch({ type: "UNLOCK", payload: { password: "correct-pass-12345" } })798    ).resolves.toMatchObject({ ok: true });799    expect(vault.isUnlocked()).toBe(true);800  });801802  it("does not acknowledge LOCK until session cleanup finishes", async () => {803    await expect(804      dispatch({ type: "CREATE_VAULT", payload: { password: "correct-pass-12345" } })805    ).resolves.toMatchObject({ ok: true });806807    const removalStarted = deferred();808    const releaseRemoval = deferred();809    const remove = chrome.storage.session.remove as unknown as ReturnType<typeof vi.fn>;810    remove.mockImplementation(async (keys: string | string[]) => {811      removalStarted.resolve();812      await releaseRemoval.promise;813      for (const key of Array.isArray(keys) ? keys : [keys]) delete sessionStorage[key];814    });815816    let responded = false;817    const response = dispatch({ type: "LOCK" }).then((result) => {818      responded = true;819      return result;820    });821    await removalStarted.promise;822823    try {824      await Promise.resolve();825      expect(responded).toBe(false);826    } finally {827      releaseRemoval.resolve();828    }829830    await expect(response).resolves.toMatchObject({ ok: true });831  });832833  it("remembers the last successful unlock method", async () => {834    const vault = await import("./vault");835    const password = "correct-pass-12345";836    const popupSender = {837      id: "peach-extension",838      url: "chrome-extension://peach-extension/src/popup/index.html",839    } as chrome.runtime.MessageSender;840841    await vault.createVault(password);842    expect(await vault.setupPinUnlock(password, "1234")).toBe(true);843    vault.lock();844845    await expect(846      dispatch({ type: "UNLOCK_WITH_PIN", payload: { pin: "1234" } }, popupSender),847    ).resolves.toMatchObject({ ok: true });848    expect((await vault.ensureSettingsLoaded()).pinPreferred).toBe(true);849850    vault.lock();851    await expect(852      dispatch({ type: "UNLOCK", payload: { password } }, popupSender),853    ).resolves.toMatchObject({ ok: true });854    expect((await vault.ensureSettingsLoaded()).pinPreferred).toBe(false);855  });856857  describe("credential save comparison", () => {858    const sender = { id: "peach-extension", url: "https://github.com/login", tab: { id: 7 }, frameId: 0 } as chrome.runtime.MessageSender;859    const compare = (username = "june", password = "secret", source = sender) =>860      dispatch({ type: "CHECK_SAVE_CREDENTIAL", payload: { username, password } } as Message, source);861862    it("selects the submitted identity instead of the first domain entry", async () => {863      const vault = await import("./vault");864      await vault.createVault("comparison-password");865      await vault.addEntry({ title: "Other", username: "other", password: "secret", url: "https://github.com" });866      const entry = await vault.addEntry({ title: "June", username: "june", email: "[email protected]", password: "old", url: "https://github.com", notes: "private" });867      expect(await compare(" [email protected] ")).toEqual({ ok: true, data: { status: "changed", id: entry.id } });868      expect(await compare("other")).toEqual({ ok: true, data: { status: "same" } });869      expect(await compare("new")).toEqual({ ok: true, data: { status: "new" } });870    });871872    it("prefers an exact password and refuses ambiguous updates", async () => {873      const vault = await import("./vault");874      await vault.createVault("comparison-password");875      await vault.addEntry({ title: "One", username: "june", password: "one", url: "https://github.com" });876      await vault.addEntry({ title: "Two", username: "june", password: "two", url: "https://github.com" });877      expect(await compare("june", "two")).toEqual({ ok: true, data: { status: "same" } });878      expect(await compare()).toEqual({ ok: true, data: { status: "ambiguous" } });879      expect(fetchMock).not.toHaveBeenCalled();880    });881882    it("recognizes password-only named accounts without selecting them for updates", async () => {883      const vault = await import("./vault");884      await vault.createVault("comparison-password");885      await vault.addEntry({ title: "Named", username: "june", password: "secret", url: "https://github.com" });886      expect(await compare("")).toEqual({ ok: true, data: { status: "same" } });887      expect(await compare("", "different")).toEqual({ ok: true, data: { status: "new" } });888      const entry = await vault.addEntry({ title: "Anonymous", username: "", password: "old", url: "https://github.com" });889      expect(await compare(" ", "different")).toEqual({ ok: true, data: { status: "changed", id: entry.id } });890    });891892    it("excludes foreign, deleted, and non-login entries", async () => {893      const vault = await import("./vault");894      await vault.createVault("comparison-password");895      await vault.addEntry({ title: "Foreign", username: "june", password: "secret", url: "https://other.example" });896      await vault.addEntry({ type: "note", title: "Note", username: "june", password: "secret", url: "https://github.com" });897      const deleted = await vault.addEntry({ title: "Deleted", username: "june", password: "secret", url: "https://github.com" });898      await vault.deleteEntry(deleted.id);899      expect(await compare()).toEqual({ ok: true, data: { status: "new" } });900    });901902    it("rejects malformed payloads, caller domains, nonpage senders, and locked vaults", async () => {903      const vault = await import("./vault");904      await vault.createVault("comparison-password");905      for (const payload of [null, [], {}, { username: 1, password: "secret" }, { username: "june", password: 1 }, { username: "june", password: "secret", domain: "github.com" }]) {906        expect(await dispatch({ type: "CHECK_SAVE_CREDENTIAL", payload } as Message, sender)).toMatchObject({ ok: false });907      }908      expect(await compare("june", "secret", { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" })).toMatchObject({ ok: false });909      expect(await compare("june", "secret", { ...sender, url: "about:blank" })).toMatchObject({ ok: false });910      expect(await compare("june", "secret", { id: "peach-extension", url: "https://github.com/login" })).toMatchObject({ ok: false });911      await vault.lock();912      expect(await compare()).toMatchObject({ ok: false, error: "vault_locked" });913    });914915    it("alerts every exact canary match as submitted without returning entry data", async () => {916      await addCanary("First"); await addCanary("Second");917      expect(await compare("wrong")).toEqual({ ok: true, data: { status: "new" } });918      expect(await compare("june", "wrong")).toEqual({ ok: true, data: { status: "ambiguous" } });919      expect(fetchMock).not.toHaveBeenCalled();920      expect(await compare()).toEqual({ ok: true, data: { status: "same" } });921      expect(fetchMock).toHaveBeenCalledTimes(2);922      for (const call of fetchMock.mock.calls) expect(JSON.parse(call[1].body as string).trigger).toBe("submitted");923    });924925    it("alerts every named canary for an exact password-only submission", async () => {926      await addCanary("First"); const second = await addCanary("Second");927      const vault = await import("./vault");928      await vault.updateEntry(second.id, { username: "other" });929      expect(await compare("", "different")).toEqual({ ok: true, data: { status: "new" } });930      expect(fetchMock).not.toHaveBeenCalled();931      expect(await compare("")).toEqual({ ok: true, data: { status: "same" } });932      expect(fetchMock).toHaveBeenCalledTimes(2);933      for (const call of fetchMock.mock.calls) expect(JSON.parse(call[1].body as string).trigger).toBe("submitted");934    });935936    it("rechecks non-canary exact matches after a sibling canary await", async () => {937      await addCanary(); const vault = await import("./vault");938      const sibling = await vault.addEntry({ title: "Ordinary", username: "june", password: "secret", url: "https://github.com" });939      const held = deferred(); const entered = deferred();940      const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;941      vi.mocked(chrome.storage.local.get).mockImplementation(async key => {942        if (typeof key === "string" && key.startsWith("canary-last-fetch:")) { entered.resolve(); await held.promise; }943        return original(key);944      });945      const pending = compare(); await entered.promise;946      await vault.updateEntry(sibling.id, { password: "changed" });947      held.resolve();948      expect(await pending).toEqual({ ok: false, error: "entry_changed" });949      expect(fetchMock).toHaveBeenCalledTimes(1);950    });951952    it.each(["lock", "domain", "identity", "password"])("refuses stale comparison after an awaited canary %s change", async change => {953      const entry = await addCanary(); const vault = await import("./vault");954      const held = deferred(); const entered = deferred();955      const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;956      vi.mocked(chrome.storage.local.get).mockImplementation(async key => {957        if (typeof key === "string" && key.startsWith("canary-last-fetch:")) { entered.resolve(); await held.promise; }958        return original(key);959      });960      const pending = compare(); await entered.promise;961      if (change === "lock") { await vault.lock(); await vault.unlock("canary-test-password"); }962      else await vault.updateEntry(entry.id, change === "domain" ? { url: "https://other.example" } : change === "identity" ? { username: "other" } : { password: "changed" });963      held.resolve();964      expect(await pending).toMatchObject({ ok: false });965    });966  });967968  async function addCanary(title = "GitHub", webhookUrl = "https://example.com/hook") {969    const vault = await import("./vault");970    if (!vault.isUnlocked()) await vault.createVault("canary-test-password");971    return vault.addEntry({ type: "login", title, username: "june", password: "secret", url: "https://github.com", canary: { webhookUrl } });972  }973974  const canarySender = { id: "peach-extension", url: "https://github.com/login", tab: { id: 7 }, frameId: 0 } as chrome.runtime.MessageSender;975976  it("rejects unsafe canary destinations at trusted writes", async () => {977    const entry = await addCanary();978    for (const webhookUrl of ["https://user:[email protected]/hook", "https://100.64.1.2/hook"]) {979      expect(await dispatch({ type: "UPDATE_ENTRY", payload: { id: entry.id, patch: { canary: { webhookUrl } } } })).toMatchObject({ ok: false, error: "invalid_webhook_url" });980      expect(await dispatch({ type: "ADD_ENTRY", payload: { title: "Bad", canary: { webhookUrl } } })).toMatchObject({ ok: false, error: "invalid_webhook_url" });981    }982  });983984  it("keeps fresh background counters when a stale popup saves a label", async () => {985    const entry = await addCanary(); const vault = await import("./vault");986    await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender);987    expect(await dispatch({ type: "UPDATE_ENTRY", payload: { id: entry.id, patch: { canary: { ...entry.canary!, label: "new label", pingCount: 0, lastPinged: 1 } } } })).toMatchObject({ ok: true });988    expect(vault.getEntryById(entry.id)?.canary).toMatchObject({ label: "new label", pingCount: 1, lastPinged: expect.any(Number) });989    expect(vault.getEntryById(entry.id)?.canary?.lastPinged).not.toBe(1);990  });991992  it("counts a dispatched request even when rate storage fails", async () => {993    const entry = await addCanary(); const vault = await import("./vault");994    const original = vi.mocked(chrome.storage.local.set).getMockImplementation()! as unknown as (values: Record<string, unknown>) => Promise<void>;995    vi.mocked(chrome.storage.local.set).mockImplementation(async values => {996      if (Object.keys(values).some(key => key.startsWith("canary-last-fetch:"))) throw new Error("rate storage failed");997      return original(values);998    });999    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender)).toMatchObject({ ok: false, error: "canary_update_failed" });1000    expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(1);1001    expect(fetchMock).toHaveBeenCalledTimes(1);1002  });10031004  it("expires future persisted timestamps and future in-memory claims", async () => {1005    const entry = await addCanary();1006    const now = Date.now();1007    const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;1008    vi.mocked(chrome.storage.local.get).mockImplementation(async key => typeof key === "string" && key.startsWith("canary-last-fetch:") ? { [key]: now + 3600000 } : original(key));1009    expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender)).ok).toBe(true);1010    expect(fetchMock).toHaveBeenCalledTimes(1);1011    vi.spyOn(Date, "now").mockReturnValue(now - 1000);1012    expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender)).ok).toBe(true);1013    expect(fetchMock).toHaveBeenCalledTimes(2);1014  });10151016  it.each(["rename", "label", "counters", "destination", "delete"])("merges post-dispatch %s edits without losing a counted attempt", async change => {1017    const entry = await addCanary(); const vault = await import("./vault");1018    const held = deferred(); const entered = deferred();1019    const original = vi.mocked(chrome.storage.local.set).getMockImplementation()! as unknown as (values: Record<string, unknown>) => Promise<void>;1020    vi.mocked(chrome.storage.local.set).mockImplementation(async values => {1021      if (Object.keys(values).some(key => key.startsWith("canary-last-fetch:"))) { entered.resolve(); await held.promise; }1022      return original(values);1023    });1024    const pending = dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1025    await entered.promise;1026    if (change === "delete") await vault.deleteEntry(entry.id);1027    else await vault.updateEntry(entry.id, change === "rename" ? { title: "Renamed" } : { canary: { ...entry.canary!, ...(change === "label" ? { label: "fresh" } : change === "counters" ? { pingCount: 7, lastPinged: 1 } : { webhookUrl: "https://new.example/hook" }) } });1028    held.resolve(); const result = await pending;1029    expect(fetchMock).toHaveBeenCalledTimes(1);1030    if (change === "delete" || change === "destination") {1031      expect(result).toMatchObject({ ok: false, error: "entry_changed" });1032      expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBeUndefined();1033    } else {1034      expect(result).toMatchObject({ ok: true, data: { password: "secret" } });1035      expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(change === "counters" ? 8 : 1);1036      if (change === "rename") expect(vault.getEntryById(entry.id)?.title).toBe("Renamed");1037      if (change === "label") expect(vault.getEntryById(entry.id)?.canary?.label).toBe("fresh");1038    }1039  });10401041  it.each(["get", "remove"] as const)("retries an undispatched alert after rate storage %s fails", async operation => {1042    const entry = await addCanary();1043    const original = vi.mocked(chrome.storage.local[operation]).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;1044    let failed = false;1045    vi.mocked(chrome.storage.local[operation]).mockImplementation(async key => {1046      if (!failed && typeof key === "string" && key.startsWith("canary-last-fetch:")) { failed = true; throw new Error("before dispatch"); }1047      return original(key);1048    });1049    expect((await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).ok).toBe(false);1050    expect(fetchMock).not.toHaveBeenCalled();1051    expect((await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).ok).toBe(true);1052    expect(fetchMock).toHaveBeenCalledTimes(1);1053  });10541055  it("fails closed on legacy invalid stored webhooks without dropping their metadata", async () => {1056    const entry = await addCanary("Legacy", "https://100.64.1.2/hook");1057    expect(await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).toMatchObject({ ok: false, error: "invalid_webhook_url" });1058    const vault = await import("./vault");1059    expect(vault.getEntryById(entry.id)?.canary?.webhookUrl).toBe("https://100.64.1.2/hook");1060    expect(fetchMock).not.toHaveBeenCalled();1061  });10621063  it("starts trusted new canaries with clean counters", async () => {1064    await addCanary();1065    const result = await dispatch({ type: "ADD_ENTRY", payload: { title: "New", canary: { webhookUrl: "https://example.com/hook", pingCount: 99, lastPinged: 1 } } });1066    expect(result).toMatchObject({ ok: true });1067    expect((result.data as import("../shared/types").VaultEntry).canary?.pingCount).toBeUndefined();1068    expect((result.data as import("../shared/types").VaultEntry).canary?.lastPinged).toBeUndefined();1069  });10701071  it("resolves canary destination and title from the stored entry", async () => {1072    const entry = await addCanary();1073    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "password_copied" } })).toMatchObject({ ok: true });1074    expect(fetchMock).toHaveBeenCalledWith("https://example.com/hook", expect.objectContaining({ method: "POST", redirect: "error" }));1075    expect(JSON.parse(fetchMock.mock.calls[0][1].body as string)).toMatchObject({ event: "peach_canary_accessed", entry: "GitHub", trigger: "password_copied", source: "peach-extension" });1076    const vault = await import("./vault");1077    expect(vault.getEntryById(entry.id)?.canary).toMatchObject({ pingCount: 1, lastPinged: expect.any(Number) });1078  });10791080  it("refuses caller-selected non-test destinations without fetching", async () => {1081    const entry = await addCanary();1082    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, webhookUrl: "https://attacker.example/", entryTitle: "forged", trigger: "password_copied" } }, canarySender)).toMatchObject({ ok: false, error: "invalid_payload" });1083    expect(fetchMock).not.toHaveBeenCalled();1084  });10851086  it("rejects array and boxed triggers without poisoning a later valid access", async () => {1087    const entry = await addCanary(); const vault = await import("./vault");1088    const malformed: unknown[] = [structuredClone(["accessed"]), Object("accessed") as unknown];1089    for (const trigger of malformed) {1090      expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger } }, canarySender)).toMatchObject({ ok: false, error: "invalid_payload" });1091      expect(fetchMock).not.toHaveBeenCalled();1092      expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBeUndefined();1093      expect(Object.keys(storage).some(key => key.startsWith("canary-last-fetch:"))).toBe(false);1094    }1095    expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender)).ok).toBe(true);1096    expect(fetchMock).toHaveBeenCalledTimes(1);1097    expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(1);1098  });10991100  it("requires unlock and the requesting frame's own domain", async () => {1101    const entry = await addCanary();1102    const payload = { id: entry.id, trigger: "submitted" };1103    expect(await dispatch({ type: "FIRE_CANARY_PING", payload }, { ...canarySender, url: "https://foreign.example/" })).toMatchObject({ ok: false, error: "entry_not_found" });1104    const vault = await import("./vault"); await vault.lock();1105    expect(await dispatch({ type: "FIRE_CANARY_PING", payload }, canarySender)).toMatchObject({ ok: false, error: "vault_locked" });1106    expect(fetchMock).not.toHaveBeenCalled();1107  });11081109  it("dispatches before credential return without waiting for HTTP completion", async () => {1110    const entry = await addCanary();1111    fetchMock.mockImplementation(() => new Promise(() => {}));1112    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1113    expect(result).toMatchObject({ ok: true, data: { password: "secret" } });1114    expect(fetchMock).toHaveBeenCalledTimes(1);1115    expect(JSON.parse(fetchMock.mock.calls[0][1].body as string).trigger).toBe("accessed");1116  });11171118  it("coalesces concurrent accesses and counts one outbound attempt", async () => {1119    const entry = await addCanary();1120    const payload = { id: entry.id, trigger: "autofilled" };1121    const replies = await Promise.all([dispatch({ type: "FIRE_CANARY_PING", payload }, canarySender), dispatch({ type: "FIRE_CANARY_PING", payload }, canarySender)]);1122    expect(replies.every(reply => reply.ok)).toBe(true);1123    expect(fetchMock).toHaveBeenCalledTimes(1);1124    const vault = await import("./vault");1125    expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(1);1126    await vault.updateEntry(entry.id, { title: "Renamed" });1127    expect(await dispatch({ type: "FIRE_CANARY_PING", payload }, canarySender)).toMatchObject({ ok: true, data: { rateLimited: true } });1128    expect(fetchMock).toHaveBeenCalledTimes(1);1129    expect(Object.keys(storage).some(key => key.includes("GitHub"))).toBe(false);1130  });11311132  it("removes the legacy plaintext canary rate key", async () => {1133    const entry = await addCanary(); const legacy = "canary-last-fetch:https://example.com/hook:GitHub";1134    storage[legacy] = Date.now();1135    expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "submitted" } }, canarySender)).ok).toBe(true);1136    expect(storage[legacy]).toBeUndefined();1137  });11381139  it("does not conflate distinct equal-title entries on one webhook", async () => {1140    const first = await addCanary(); const second = await addCanary();1141    for (const entry of [first, second]) await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "submitted" } }, canarySender);1142    expect(fetchMock).toHaveBeenCalledTimes(2);1143  });11441145  it("keeps accepted ID and canonical URL tuples unambiguous", async () => {1146    const base = await addCanary(); const vault = await import("./vault");1147    const first = { ...base, id: "a", canary: { webhookUrl: "https://x/:https://y/" } };1148    const second = { ...base, id: "a:https://x/", canary: { webhookUrl: "https://y/" } };1149    await vault.applyMergedRemoteEntries([first, second], {});1150    expect(vault.getEntryById(second.id)?.id).toBe(second.id);1151    for (const entry of [first, second]) expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "submitted" } }, canarySender)).ok).toBe(true);1152    expect(fetchMock).toHaveBeenCalledTimes(2);1153    expect(Object.keys(storage).filter(key => key.startsWith("canary-last-fetch:")).length).toBe(2);1154  });11551156  it("counts failed network attempts but not trusted test pings", async () => {1157    const entry = await addCanary();1158    fetchMock.mockRejectedValueOnce(new Error("synthetic network failure"));1159    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "password_copied" } })).toMatchObject({ ok: true });1160    for (let i = 0; i < 2; i++) expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { webhookUrl: "https://example.com/hook", entryTitle: "Draft", trigger: "test" } })).toMatchObject({ ok: true });1161    const vault = await import("./vault");1162    expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(1);1163    expect(fetchMock).toHaveBeenCalledTimes(3);1164  });11651166  it("rejects test pings from content scripts", async () => {1167    await addCanary();1168    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { webhookUrl: "https://example.com/hook", entryTitle: "Draft", trigger: "test" } }, canarySender)).toMatchObject({ ok: false, error: "invalid_sender" });1169    expect(fetchMock).not.toHaveBeenCalled();1170  });11711172  it.each(["http://example.com/hook", "https://localhost./", "https://127.1/", "https://0x7f000001/", "https://100.64.0.1/", "https://0.0.0.0/", "https://224.0.0.1/", "https://240.0.0.1/", "https://[::]/", "https://[fe90::1]/", "https://[febf::1]/", "https://[fd00::1]/", "https://[ff02::1]/", "https://[::ffff:192.168.0.1]/", "https://[::ffff:c0a8:1]/", "https://[::ffff:10.0.0.1]/", "https://[::ffff:127.0.0.1]/", "https://[::ffff:169.254.1.1]/", "https://[::ffff:172.16.0.1]/", "https://[3fff::1]/", "https://[100:0:0:1::1]/", "https://[2001:2::1]/"]) ("rejects unsafe canonical webhook %s", async (webhookUrl) => {1173    await addCanary();1174    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { webhookUrl, entryTitle: "Draft", trigger: "test" } })).toMatchObject({ ok: false, error: "invalid_webhook_url" });1175    expect(fetchMock).not.toHaveBeenCalled();1176  });11771178  it.each(["https://fcm.example/hook", "https://fd.example/hook", "https://10.example/hook", "https://8.8.8.8/hook", "https://[2606:4700:4700::1111]/hook"]) ("preserves legitimate webhook %s", async (webhookUrl) => {1179    await addCanary();1180    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { webhookUrl, entryTitle: "Draft", trigger: "test" } })).toMatchObject({ ok: true });1181    expect(fetchMock).toHaveBeenCalledWith(webhookUrl, expect.objectContaining({ redirect: "error" }));1182  });11831184  it("does not release credentials after lock during a new canary await", async () => {1185    const entry = await addCanary(); const held = deferred(); const entered = deferred();1186    const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;1187    vi.spyOn(chrome.storage.local, "get").mockImplementation(async key => {1188      if (typeof key === "string" && key.startsWith("canary-last-fetch:")) { entered.resolve(); await held.promise; }1189      return original(key);1190    });1191    const filling = dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1192    await entered.promise; const vault = await import("./vault"); await vault.lock(); held.resolve();1193    expect(await filling).toMatchObject({ ok: false, error: "vault_locked" });1194    expect(fetchMock).not.toHaveBeenCalled();1195  });11961197  it("never treats an undispatched alert as an already attempted rate claim", async () => {1198    const entry = await addCanary(); const vault = await import("./vault");1199    vi.spyOn(vault, "updateEntry").mockRejectedValueOnce(new Error("synthetic counter persistence failure"));1200    const first = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1201    expect(first.ok).toBe(false);1202    const retry = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1203    if (retry.ok) expect(fetchMock).toHaveBeenCalledTimes(1);1204    expect(fetchMock).toHaveBeenCalledTimes(1);1205  });12061207  it("rechecks canary configuration after an awaited claim read", async () => {1208    const entry = await addCanary(); const held = deferred(); const entered = deferred();1209    const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;1210    vi.spyOn(chrome.storage.local, "get").mockImplementation(async key => {1211      if (typeof key === "string" && key.startsWith("canary-last-fetch:")) { entered.resolve(); await held.promise; }1212      return original(key);1213    });1214    const filling = dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1215    await entered.promise; const vault = await import("./vault");1216    await vault.updateEntry(entry.id, { canary: { webhookUrl: "https://new.example/hook", label: "new" } });1217    held.resolve();1218    expect(await filling).toMatchObject({ ok: false, error: "entry_changed" });1219    expect(fetchMock).not.toHaveBeenCalled();1220    expect(vault.getEntryById(entry.id)?.canary?.webhookUrl).toBe("https://new.example/hook");1221  });12221223  it("rejects a late canary edit between helper completion and credential return", async () => {1224    const entry = await addCanary(); const vault = await import("./vault"); const edited = deferred();1225    const original = vault.getEntryById; let queued = false;1226    vi.spyOn(vault, "getEntryById").mockImplementation(id => {1227      const current = original(id);1228      if (!queued && current?.canary?.pingCount === 1) {1229        queued = true;1230        queueMicrotask(() => { void vault.updateEntry(entry.id, { canary: { webhookUrl: "https://new.example/hook", label: "changed" } }).then(edited.resolve); });1231      }1232      return current;1233    });1234    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1235    await edited.promise;1236    expect(result).toMatchObject({ ok: false, error: "entry_changed" });1237    expect(fetchMock).toHaveBeenCalledTimes(1);1238  });12391240  it("does not cache a post-dispatch persistence error as a permanent access block", async () => {1241    const entry = await addCanary(); const vault = await import("./vault");1242    vi.spyOn(vault, "updateEntry").mockRejectedValueOnce(new Error("synthetic counter failure"));1243    expect((await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).ok).toBe(false);1244    await vault.updateEntry(entry.id, { canary: { ...entry.canary!, label: "corrected" } });1245    expect(await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).toMatchObject({ ok: true, data: { password: "secret" } });1246    expect(fetchMock).toHaveBeenCalledTimes(1);1247  });12481249  it("uses a valid cross-domain capability once for access and notification", async () => {1250    const entry = await addCanary(); const messages = await import("./messages");1251    const sender = { ...canarySender, url: "https://other.example/" };1252    const token = messages.createSummonCapability(7, "https://other.example");1253    expect((await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "other.example", capability: token } }, sender)).ok).toBe(true);1254    expect(await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender)).toMatchObject({ ok: true, data: { password: "secret" } });1255    expect(await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender)).toMatchObject({ ok: false, error: "entry_not_found" });1256    expect(fetchMock).toHaveBeenCalledTimes(1);1257  });12581259  it("a failed counter write cannot restore a superseded canary configuration", async () => {1260    const entry = await addCanary(); const entered = deferred(); const held = deferred();1261    const original = vi.mocked(chrome.storage.local.set).getMockImplementation()! as unknown as (values: Record<string, unknown>) => Promise<void>; let first = true;1262    vi.spyOn(chrome.storage.local, "set").mockImplementation(async values => {1263      if (first && Object.hasOwn(values, "peach_vault_a")) { first = false; entered.resolve(); await held.promise; throw new Error("synthetic failed counter write"); }1264      return original(values);1265    });1266    const vault = await import("./vault");1267    const failed = vault.updateEntry(entry.id, { canary: { ...entry.canary!, pingCount: 1 } }).catch(() => undefined);1268    await entered.promise;1269    await vault.updateEntry(entry.id, { canary: { webhookUrl: "https://new.example/hook", label: "new configuration" } });1270    held.resolve(); await failed;1271    expect(vault.getEntryById(entry.id)?.canary).toMatchObject({ webhookUrl: "https://new.example/hook", label: "new configuration" });1272  });12731274  it("failed counter rollback preserves a successful overlapping deletion", async () => {1275    const entry = await addCanary(); const entered = deferred(); const held = deferred();1276    const original = vi.mocked(chrome.storage.local.set).getMockImplementation()! as unknown as (values: Record<string, unknown>) => Promise<void>; let first = true;1277    vi.spyOn(chrome.storage.local, "set").mockImplementation(async values => {1278      if (first && Object.hasOwn(values, "peach_vault_a")) { first = false; entered.resolve(); await held.promise; throw new Error("synthetic failed counter write"); }1279      return original(values);1280    });1281    const vault = await import("./vault");1282    const failed = vault.updateEntry(entry.id, { canary: { ...entry.canary!, pingCount: 1 } }).catch(() => undefined);1283    await entered.promise; await vault.deleteEntry(entry.id); held.resolve(); await failed;1284    expect(vault.getEntryById(entry.id)).toBeUndefined();1285    await vault.lock(); await vault.unlock("canary-test-password");1286    expect(vault.getEntryById(entry.id)).toBeUndefined();1287  });12881289  it("GET_IDENTITIES when locked returns vault locked error", async () => {1290    const vault = await import("./vault");1291    await vault.createVault("correct-pass-12345");1292    vault.lock();1293    await expect(dispatch({ type: "GET_IDENTITIES" })).resolves.toMatchObject({1294      ok: false,1295      error: "vault_locked",1296    });1297  });12981299  it("GET_IDENTITIES returns emails and usernames derived from login entries", async () => {1300    const vault = await import("./vault");1301    await vault.createVault("correct-pass-12345");1302    await vault.addEntry({ title: "Gmail", username: "[email protected]", password: "pw1", url: "https://gmail.com" });1303    await vault.addEntry({ title: "GitHub", username: "[email protected]", password: "pw2", url: "https://github.com" });1304    await vault.addEntry({ title: "Slack", username: "juni_patel", password: "pw3", url: "https://slack.com" });13051306    const resp = await dispatch({ type: "GET_IDENTITIES" }) as { ok: boolean; data: unknown[] };1307    expect(resp.ok).toBe(true);1308    const data = resp.data as Array<{ value: string; type: string; useCount: number }>;1309    expect(data.find((d) => d.value === "[email protected]")).toMatchObject({1310      type: "email",1311      useCount: 2,1312    });1313    expect(data.find((d) => d.value === "juni_patel")).toMatchObject({1314      type: "username",1315      useCount: 1,1316    });1317    // emails appear before usernames1318    const emailIdx = data.findIndex((d) => d.value === "[email protected]");1319    const userIdx = data.findIndex((d) => d.value === "juni_patel");1320    expect(emailIdx).toBeLessThan(userIdx);1321  });13221323  it("GET_IDENTITIES deduplicates correctly — same email across 3 entries appears once with useCount 3", async () => {1324    const vault = await import("./vault");1325    await vault.createVault("correct-pass-12345");1326    for (let i = 0; i < 3; i++) {1327      await vault.addEntry({ title: `Site${i}`, username: "[email protected]", password: "pw", url: `https://site${i}.com` });1328    }13291330    const resp = await dispatch({ type: "GET_IDENTITIES" }) as { ok: boolean; data: unknown[] };1331    const data = resp.data as Array<{ value: string; useCount: number }>;1332    const hits = data.filter((d) => d.value === "[email protected]");1333    expect(hits).toHaveLength(1);1334    expect(hits[0]!.useCount).toBe(3);1335  });13361337  it("GET_IDENTITIES rejects content-script and page-relay senders", async () => {1338    const vault = await import("./vault");1339    await vault.createVault("correct-pass-12345");1340    await vault.addEntry({1341      title: "Private identity",1342      username: "[email protected]",1343      password: "pw",1344      url: "https://private.example",1345    });13461347    const senders = [1348      {1349        id: "peach-extension",1350        url: "https://private.example/signup",1351        tab: { id: 1 } as chrome.tabs.Tab,1352      },1353      { id: "peach-extension", url: "https://private.example/signup" },1354    ] satisfies chrome.runtime.MessageSender[];1355    for (const sender of senders) {1356      await expect(dispatch({ type: "GET_IDENTITIES" }, sender)).resolves.toMatchObject({1357        ok: false,1358        error: "invalid_sender",1359      });1360    }1361  });13621363  it("IS_CARD_DECLINED does not refresh the auto-lock timer", async () => {1364    const vault = await import("./vault");1365    await vault.createVault("correct-pass-12345");1366    const alarmsCreate = chrome.alarms.create as unknown as ReturnType<typeof vi.fn>;13671368    // Sanity: a non-excluded message (GET_ENTRIES) DOES refresh the timer1369    alarmsCreate.mockClear();1370    await dispatch({ type: "GET_ENTRIES" });1371    expect(alarmsCreate).toHaveBeenCalled();13721373    // Passive queries are in the exclusion list and must not re-arm1374    alarmsCreate.mockClear();1375    await dispatch({ type: "IS_CARD_DECLINED", payload: { origin: "https://example.com" } });1376    expect(alarmsCreate).not.toHaveBeenCalled();1377  });13781379  it("DESTROY_VAULT preserves the Pro license and celebration flag", async () => {1380    const vault = await import("./vault");1381    await vault.createVault("correct-pass-12345");1382    await vault.addEntry({ title: "Gmail", username: "june", password: "s", url: "https://mail.google.com" });13831384    // Simulate an activated Pro license + already-celebrated marker.1385    storage.peach_license = "PEACH-PRO-TEST-KEY";1386    storage.peach_pro_celebrated = true;13871388    const res = await dispatch({ type: "DESTROY_VAULT" }, { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" });1389    expect(res).toMatchObject({ ok: true });13901391    // Vault data is gone…1392    expect(storage.peach_vault_a).toBeUndefined();1393    // …but the paid license and celebration flag survive the wipe.1394    expect(storage.peach_license).toBe("PEACH-PRO-TEST-KEY");1395    expect(storage.peach_pro_celebrated).toBe(true);1396  });13971398  it("handleMessage waits for the restore gate before serving (cold-start: no premature onboarding/lock)", async () => {1399    const messages = await import("./messages");1400    const vault = await import("./vault");14011402    let resolveGate: () => void = () => {};1403    messages.setRestoreReady(new Promise<void>((r) => { resolveGate = r; }));14041405    let settled = false;1406    const pending = dispatch({ type: "HAS_VAULT" }).then((r) => { settled = true; return r; });14071408    // While restore is in flight the handler must NOT have answered yet —1409    // this is the window where the old code returned "no vault" → onboarding.1410    await new Promise((r) => setTimeout(r, 20));1411    expect(settled).toBe(false);14121413    // Restore completes (the vault becomes available), gate opens.1414    await vault.createVault("correct-pass-12345");1415    resolveGate();14161417    await expect(pending).resolves.toMatchObject({ ok: true, data: true });1418  });14191420  it.each([null, true, false, 1, {}, "replace", "warned-import "])("CREATE_VAULT rejects malformed replacement intent %j", async (replacement) => {1421    const result = await dispatch({ type: "CREATE_VAULT", payload: { password: "new-password", replacement } });1422    expect(result).toMatchObject({ ok: false, error: "invalid_payload" });1423    expect(storage.peach_vault_a).toBeUndefined();1424  });14251426  it("CREATE_VAULT refuses ordinary replacement of an existing locked vault", async () => {1427    const vault = await import("./vault");1428    await vault.createVault("original-password");1429    await vault.lock();1430    const before = structuredClone(storage);1431    expect(await dispatch({ type: "CREATE_VAULT", payload: { password: "new-password" } })).toMatchObject({ ok: false, error: "vault_already_exists" });1432    expect(storage).toEqual(before);1433    expect(await vault.unlock("original-password")).toBe(true);1434  });14351436  it("CREATE_VAULT rejects an empty master password (audit HIGH — no empty-key vault)", async () => {1437    const res = await dispatch({ type: "CREATE_VAULT", payload: { password: "" } });1438    expect(res.ok).toBe(false);1439    // Nothing was written — no vault exists.1440    const has = await dispatch({ type: "HAS_VAULT" });1441    expect((has as { data?: boolean }).data).toBe(false);1442  });14431444  it("GET_ENTRY_FOR_FILL sends a 6-digit TOTP code, never the seed (SEV-3-C)", async () => {1445    const vault = await import("./vault");1446    await vault.createVault("correct-pass-12345");1447    const e = await vault.addEntry({1448      title: "Mail",1449      username: "june",1450      password: "pw",1451      url: "https://mail.test",1452      totp: "JBSWY3DPEHPK3PXP",1453    });14541455    const res = await dispatch(1456      { type: "GET_ENTRY_FOR_FILL", payload: { id: e.id } },1457      { id: "peach-extension", url: "https://mail.test/login" },1458    );1459    expect(res.ok).toBe(true);1460    const data = res.data as { totp?: string; totpCode?: string; totpRemaining?: number };1461    expect(data.totp).toBeUndefined();1462    expect(data.totpCode).toMatch(/^\d{6}$/);1463    expect(data.totpRemaining).toBeGreaterThan(0);1464    expect(data.totpRemaining).toBeLessThanOrEqual(30);1465  });14661467  it("GET_ENTRY_FOR_FILL strips passwordHistory; GET_ENTRY_FOR_EDIT keeps it", async () => {1468    const vault = await import("./vault");1469    await vault.createVault("correct-pass-12345");1470    const e = await vault.addEntry({1471      title: "Bank",1472      username: "june",1473      password: "old-pw",1474      url: "https://bank.test",1475    });1476    await vault.updateEntry(e.id, { password: "new-pw" });14771478    const fill = await dispatch(1479      { type: "GET_ENTRY_FOR_FILL", payload: { id: e.id } },1480      { id: "peach-extension", url: "https://bank.test/login" },1481    );1482    expect(fill.ok).toBe(true);1483    // Passive autofill never receives prior passwords (blast-radius containment).1484    expect((fill.data as Record<string, unknown>).passwordHistory).toBeUndefined();14851486    const edit = await dispatch({ type: "GET_ENTRY_FOR_EDIT", payload: { id: e.id } });1487    expect(edit.ok).toBe(true);1488    const editHist = (edit.data as { passwordHistory?: Array<{ password: string }> }).passwordHistory ?? [];1489    expect(editHist.map((h) => h.password)).toEqual(["old-pw"]);1490  });14911492  it("GET_ENTRY_FOR_EDIT returns the raw TOTP seed for the trusted edit form", async () => {1493    const vault = await import("./vault");1494    await vault.createVault("correct-pass-12345");1495    const e = await vault.addEntry({1496      title: "Mail",1497      username: "june",1498      password: "pw",1499      url: "https://mail.test",1500      totp: "JBSWY3DPEHPK3PXP",1501    });15021503    const res = await dispatch({ type: "GET_ENTRY_FOR_EDIT", payload: { id: e.id } });1504    expect(res.ok).toBe(true);1505    const data = res.data as { totp?: string };1506    expect(data.totp).toBe("JBSWY3DPEHPK3PXP");1507  });15081509  it("DESTROY_VAULT with no license clears storage without resurrecting keys", async () => {1510    const vault = await import("./vault");1511    await vault.createVault("correct-pass-12345");15121513    const res = await dispatch({ type: "DESTROY_VAULT" }, { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" });1514    expect(res).toMatchObject({ ok: true });15151516    expect(storage.peach_vault_a).toBeUndefined();1517    expect(storage.peach_license).toBeUndefined();1518    expect(storage.peach_pro_celebrated).toBeUndefined();1519  });15201521  // --- MV-1: GET_ENTRY_FOR_FILL re-validates the requesting tab's origin ---15221523  function tabSender(url: string, tabId = 1, frameId = 0): chrome.runtime.MessageSender {1524    return { id: "peach-extension", tab: { id: tabId, url } as chrome.tabs.Tab, url, frameId };1525  }15261527  async function addPasskeyOnlyEntry(title: string, url: string) {1528    const vault = await import("./vault");1529    const generated = await generatePasskeyKeypair(-7);1530    return vault.addEntry({1531      type: "login",1532      title,1533      url,1534      passkey: {1535        rpId: new URL(url).hostname,1536        rpName: title,1537        credentialId: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1538        publicKeyCose: base64urlEncode(generated.publicKeyCose),1539        privateKeyJwk: generated.privateKeyJwk,1540        userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1541        userName: "june",1542        userDisplayName: "June",1543        algorithm: -7,1544        signCount: 0,1545        aaguid: "AAAAAAAAAAAAAAAAAAAAAA",1546        backupEligible: true,1547        backupState: false,1548        createdAt: Date.now(),1549      },1550    });1551  }15521553  it("PB-26-201: normal inventory ignores forged domain and gesture booleans", async () => {1554    const vault = await import("./vault");1555    await vault.createVault("correct-pass-12345");1556    await vault.addEntry({ title: "GitHub", username: "victim", password: "secret", url: "https://github.com" });1557    await vault.addEntry({ title: "Evil", username: "attacker", password: "known", url: "https://evil.example.com" });15581559    const result = await dispatch(1560      {1561        type: "AUTOFILL_QUERY",1562        payload: {1563          domain: "github.com",1564          includeAll: true,1565          userGesture: true,1566          explicitSummon: true,1567        },1568      },1569      tabSender("https://evil.example.com/phish"),1570    );15711572    expect(result).toMatchObject({ ok: true });1573    expect((result.data as Array<{ title: string }>).map((entry) => entry.title)).toEqual(["Evil"]);1574  });15751576  it("PB-26-201: normal TOTP inventory is scoped to the attested frame origin", async () => {1577    const vault = await import("./vault");1578    await vault.createVault("correct-pass-12345");1579    await vault.addEntry({ title: "GitHub 2FA", password: "secret", url: "https://github.com", totp: "JBSWY3DPEHPK3PXP" });1580    await vault.addEntry({ title: "Evil 2FA", password: "known", url: "https://evil.example.com", totp: "JBSWY3DPEHPK3PXP" });15811582    const result = await dispatch(1583      { type: "AUTOFILL_QUERY", payload: { domain: "github.com", kind: "totp" } },1584      tabSender("https://evil.example.com/verify"),1585    );15861587    expect((result.data as Array<{ title: string }>).map((entry) => entry.title)).toEqual(["Evil 2FA"]);1588  });15891590  it("PB-26-201: summon capability is one-shot after inventory authorization", async () => {1591    const vault = await import("./vault");1592    const messages = await import("./messages");1593    await vault.createVault("correct-pass-12345");1594    const entry = await vault.addEntry({ title: "GitHub", username: "june", password: "secret123", url: "https://github.com" });1595    const sender = tabSender("https://evil.example.com/phish");1596    const token = messages.createSummonCapability(1, "https://evil.example.com");15971598    const inventory = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1599    expect(inventory).toMatchObject({ ok: true, data: [{ id: entry.id }] });16001601    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1602    expect(firstFill).toMatchObject({ ok: true, data: { id: entry.id } });1603    const replay = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1604    expect(replay).toMatchObject({ ok: false, error: "entry_not_found" });1605  });16061607  it("PB-26-201: summon capability is consumed by a same-domain fill", async () => {1608    const vault = await import("./vault");1609    const messages = await import("./messages");1610    await vault.createVault("correct-pass-12345");1611    const entry = await vault.addEntry({ title: "GitHub", password: "secret123", url: "https://evil.example.com" });1612    const sender = tabSender("https://evil.example.com/login");1613    const token = messages.createSummonCapability(1, "https://evil.example.com");16141615    const inventory = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1616    expect(inventory).toMatchObject({ ok: true, data: [{ id: entry.id }] });1617    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1618    expect(firstFill).toMatchObject({ ok: true, data: { id: entry.id } });16191620    const offDomainReplay = await dispatch(1621      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1622      tabSender("https://github.com/login"),1623    );1624    expect(offDomainReplay).toMatchObject({ ok: false, error: "entry_not_found" });1625  });16261627  it("PB-26-201: summon capability cannot fill a different entry", async () => {1628    const vault = await import("./vault");1629    const messages = await import("./messages");1630    await vault.createVault("correct-pass-12345");1631    const first = await vault.addEntry({ title: "First", password: "one", url: "https://first.example" });1632    const second = await vault.addEntry({ title: "Second", password: "two", url: "https://second.example" });1633    const sender = tabSender("https://evil.example.com/phish");1634    const token = messages.createSummonCapability(1, "https://evil.example.com");1635    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1636    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: first.id, capability: token } }, sender);1637    expect(firstFill).toMatchObject({ ok: true, data: { id: first.id } });1638    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: second.id, capability: token } }, sender);1639    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1640    expect(first.id).not.toBe(second.id);1641  });16421643  it("PB-26-201: fill before inventory is rejected without an entry oracle", async () => {1644    const vault = await import("./vault");1645    const messages = await import("./messages");1646    await vault.createVault("correct-pass-12345");1647    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1648    const token = messages.createSummonCapability(1, "https://evil.example.com");1649    const result = await dispatch(1650      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1651      tabSender("https://evil.example.com/phish"),1652    );1653    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1654  });16551656  it("PB-26-201: an unused summon capability does not block a normal same-origin fill", async () => {1657    const vault = await import("./vault");1658    const messages = await import("./messages");1659    await vault.createVault("correct-pass-12345");1660    const entry = await vault.addEntry({1661      title: "Evil",1662      password: "known",1663      url: "https://evil.example.com",1664    });1665    const sender = tabSender("https://evil.example.com/login");1666    const token = messages.createSummonCapability(1, "https://evil.example.com");16671668    const result = await dispatch(1669      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1670      sender,1671    );16721673    expect(result).toMatchObject({ ok: true, data: { id: entry.id } });1674  });16751676  it("PB-26-201: expired fill capability is rejected before entry-specific errors", async () => {1677    vi.useFakeTimers();1678    vi.setSystemTime(new Date("2026-09-02T12:00:00Z"));1679    const vault = await import("./vault");1680    const messages = await import("./messages");1681    await vault.createVault("correct-pass-12345");1682    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1683    const sender = tabSender("https://evil.example.com/phish");1684    const token = messages.createSummonCapability(1, "https://evil.example.com");1685    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1686    vi.advanceTimersByTime(30_001);16871688    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1689    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1690  });16911692  it("PB-26-201: wrong-tab fill capability is rejected before entry-specific errors", async () => {1693    const vault = await import("./vault");1694    const messages = await import("./messages");1695    await vault.createVault("correct-pass-12345");1696    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1697    const token = messages.createSummonCapability(1, "https://evil.example.com");1698    await dispatch(1699      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1700      tabSender("https://evil.example.com/phish"),1701    );17021703    const result = await dispatch(1704      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1705      tabSender("https://evil.example.com/phish", 2),1706    );1707    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1708  });17091710  it("PB-26-201: wrong-frame fill capability is rejected before entry-specific errors", async () => {1711    const vault = await import("./vault");1712    const messages = await import("./messages");1713    await vault.createVault("correct-pass-12345");1714    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1715    const token = messages.createSummonCapability(1, "https://evil.example.com", 3);1716    await dispatch(1717      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1718      tabSender("https://evil.example.com/phish", 1, 3),1719    );17201721    const result = await dispatch(1722      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1723      tabSender("https://evil.example.com/phish", 1, 4),1724    );1725    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1726  });17271728  it("PB-26-201: wrong-origin fill capability is rejected before entry-specific errors", async () => {1729    const vault = await import("./vault");1730    const messages = await import("./messages");1731    await vault.createVault("correct-pass-12345");1732    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1733    const token = messages.createSummonCapability(1, "https://evil.example.com");1734    await dispatch(1735      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1736      tabSender("https://evil.example.com/phish"),1737    );17381739    const result = await dispatch(1740      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1741      tabSender("https://other.example.com/phish"),1742    );1743    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1744  });17451746  it("PB-26-201: selecting a missing id consumes the one-shot capability without an oracle", async () => {1747    const vault = await import("./vault");1748    const messages = await import("./messages");1749    await vault.createVault("correct-pass-12345");1750    const existing = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1751    const sender = tabSender("https://evil.example.com/phish");1752    const token = messages.createSummonCapability(1, "https://evil.example.com");1753    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);17541755    const missing = await dispatch(1756      { type: "GET_ENTRY_FOR_FILL", payload: { id: "missing", capability: token } },1757      sender,1758    );1759    const existingReplay = await dispatch(1760      { type: "GET_ENTRY_FOR_FILL", payload: { id: existing.id, capability: token } },1761      sender,1762    );1763    expect(missing).toMatchObject({ ok: false, error: "entry_not_found" });1764    expect(existingReplay).toEqual(missing);1765  });17661767  it("PB-26-201: inventory capability cannot be reused for a second inventory", async () => {1768    const vault = await import("./vault");1769    const messages = await import("./messages");1770    await vault.createVault("correct-pass-12345");1771    await vault.addEntry({ title: "GitHub", password: "secret", url: "https://github.com" });1772    const sender = tabSender("https://evil.example.com/phish");1773    const token = messages.createSummonCapability(1, "https://evil.example.com");1774    const first = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1775    const second = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);17761777    expect(first).toMatchObject({ ok: true, data: [{ title: "GitHub" }] });1778    expect(second).toMatchObject({ ok: false, error: "entry_not_found" });1779  });17801781  it("PB-26-201: cards require a capability and consume it on the selected fill", async () => {1782    const vault = await import("./vault");1783    const messages = await import("./messages");1784    await vault.createVault("correct-pass-12345");1785    const card = await vault.addEntry({1786      type: "card",1787      title: "Personal Visa",1788      cardholderName: "June Peach",1789      cardNumber: "4111111111111111",1790      cvc: "123",1791      expMonth: "12",1792      expYear: "2030",1793    });1794    const sender = tabSender("https://shop.example.com/checkout");1795    const passive = await dispatch(1796      { type: "AUTOFILL_QUERY", payload: { domain: "shop.example.com", kind: "card" } },1797      sender,1798    );1799    expect(passive).toMatchObject({ ok: true, data: [] });18001801    const token = messages.createSummonCapability(1, "https://shop.example.com");1802    const inventory = await dispatch(1803      { type: "AUTOFILL_QUERY", payload: { domain: "forged.example", kind: "card", capability: token } },1804      sender,1805    );1806    expect(inventory).toMatchObject({ ok: true, data: [{ id: card.id, title: "Personal Visa" }] });1807    expect((inventory.data as Array<Record<string, unknown>>)[0]).not.toHaveProperty("cardNumber");18081809    const fill = await dispatch(1810      { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1811      sender,1812    );1813    expect(fill).toMatchObject({ ok: true, data: { id: card.id, cardNumber: "4111111111111111" } });1814    const replay = await dispatch(1815      { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1816      sender,1817    );1818    expect(replay).toMatchObject({ ok: false, error: "entry_not_found" });1819  });18201821  it("PB-26-201: inline edit popup request stores only the selected entry id", async () => {1822    const result = await dispatch(1823      { type: "OPEN_POPUP", payload: { entryId: "entry-123" } },1824      tabSender("https://example.com/login"),1825    );18261827    expect(result).toMatchObject({ ok: true });1828    expect(sessionStorage.peach_open_entry).toBe("entry-123");1829    expect(sessionStorage.peach_inline_unlock).toBeUndefined();1830  });18311832  it("MV-1: tab request with a matching domain returns the entry", async () => {1833    const vault = await import("./vault");1834    await vault.createVault("correct-pass-12345");1835    const entry = await vault.addEntry({1836      title: "GitHub",1837      username: "june",1838      password: "secret123",1839      url: "https://github.com",1840    });18411842    const res = await dispatch(1843      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1844      tabSender("https://github.com/login"),1845    );1846    expect(res).toMatchObject({ ok: true, data: { id: entry.id } });1847  });18481849  it("MV-1: tab request with a mismatched domain and no explicitSummon is refused as entry_not_found", async () => {1850    const vault = await import("./vault");1851    await vault.createVault("correct-pass-12345");1852    const entry = await vault.addEntry({1853      title: "GitHub",1854      username: "june",1855      password: "secret123",1856      url: "https://github.com",1857    });18581859    const res = await dispatch(1860      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1861      tabSender("https://evil.example.com/phish"),1862    );1863    // Refused with the same error as a missing id — no cross-domain oracle.1864    expect(res).toMatchObject({ ok: false, error: "entry_not_found" });1865  });18661867  it("PB-26-201: explicitSummon cannot authorize off-domain fill", async () => {1868    const vault = await import("./vault");1869    await vault.createVault("correct-pass-12345");1870    const entry = await vault.addEntry({1871      title: "GitHub",1872      username: "june",1873      password: "secret123",1874      url: "https://github.com",1875    });18761877    const res = await dispatch(1878      {1879        type: "GET_ENTRY_FOR_FILL",1880        payload: { id: entry.id, explicitSummon: true },1881      },1882      tabSender("https://evil.example.com/phish"),1883    );1884    expect(res).toMatchObject({ ok: false, error: "entry_not_found" });1885  });18861887  it("MV-1: tab context with an unparseable URL is refused as origin_unverified", async () => {1888    const vault = await import("./vault");1889    await vault.createVault("correct-pass-12345");1890    const entry = await vault.addEntry({1891      title: "GitHub",1892      username: "june",1893      password: "secret123",1894      url: "https://github.com",1895    });18961897    const res = await dispatch(1898      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1899      tabSender("not a url"),1900    );1901    expect(res).toMatchObject({ ok: false, error: "origin_unverified" });1902  });19031904  // --- MV-2: vault-wide inventory only ships on an explicit user gesture ---19051906  async function seedTwoDomainVault() {1907    const vault = await import("./vault");1908    await vault.createVault("correct-pass-12345");1909    await vault.addEntry({1910      title: "GitHub",1911      username: "june",1912      password: "gh",1913      url: "https://github.com",1914    });1915    await vault.addEntry({1916      title: "Example",1917      username: "june",1918      password: "ex",1919      url: "https://example.com",1920    });1921  }19221923  it("MV-2: AUTOFILL_QUERY with includeAll but no userGesture returns only the domain-scoped list", async () => {1924    await seedTwoDomainVault();19251926    const res = await dispatch({1927      type: "AUTOFILL_QUERY",1928      payload: { domain: "github.com", includeAll: true },1929    });1930    expect(res.ok).toBe(true);1931    const data = res.data as Array<{ title: string }>;1932    // includeAll was stripped — only the github.com match comes back.1933    expect(data).toHaveLength(1);1934    expect(data[0].title).toBe("GitHub");1935  });19361937  it("PB-26-201: userGesture cannot authorize vault-wide inventory", async () => {1938    await seedTwoDomainVault();19391940    const res = await dispatch({1941      type: "AUTOFILL_QUERY",1942      payload: { domain: "github.com", includeAll: true, userGesture: true },1943    });1944    expect(res.ok).toBe(true);1945    const data = res.data as Array<{ title: string }>;1946    expect(data.map((d) => d.title)).toEqual(["GitHub"]);1947  });19481949  it("PB-26-104: decoy pairing messages hide devices and prior sync outcome", async () => {1950    const vault = await import("./vault");1951    const { listPairedDevices, upsertPairedDevice } = await import("./paired-devices");1952    const { setSyncRunner, triggerSyncIfReachable } = await import("./sync-trigger");1953    await vault.createVault("correct-pass-12345");1954    await vault.setupDuress("decoy-pass-67890");1955    await upsertPairedDevice({1956      deviceId: "android-real",1957      deviceName: "Real Pixel",1958      deviceType: "android",1959      longTermPublicKeyHex: "a".repeat(64),1960      trustSource: "direct",1961      pairedAt: 1_700_000_000_000,1962    });1963    setSyncRunner(async () => ({ ok: true, entriesReceived: 3, entriesSent: 2 }));1964    await triggerSyncIfReachable({ reason: "manual" });19651966    await vault.lock();1967    expect(await vault.unlock("decoy-pass-67890")).toBe(true);1968    await expect(dispatch({ type: "LIST_PAIRED_DEVICES" })).resolves.toEqual({1969      ok: true,1970      data: { devices: [] },1971    });1972    await expect(dispatch({ type: "GET_SYNC_STATE" })).resolves.toEqual({1973      ok: true,1974      data: { status: "idle" },1975    });1976    expect((await listPairedDevices()).map((device) => device.deviceName)).toEqual(["Real Pixel"]);1977  });19781979  it("PB-26-104: real unlocked pairing messages retain the device list", async () => {1980    const vault = await import("./vault");1981    const { upsertPairedDevice } = await import("./paired-devices");1982    await vault.createVault("correct-pass-12345");1983    await upsertPairedDevice({1984      deviceId: "android-real",1985      deviceName: "Real Pixel",1986      deviceType: "android",1987      longTermPublicKeyHex: "a".repeat(64),1988      trustSource: "direct",1989      pairedAt: 1_700_000_000_000,1990    });19911992    await expect(dispatch({ type: "LIST_PAIRED_DEVICES" })).resolves.toMatchObject({1993      ok: true,1994      data: { devices: [{ deviceId: "android-real", deviceName: "Real Pixel" }] },1995    });1996  });19971998  async function seedPendingVouched(deviceId: string) {1999    await chrome.storage.local.set({2000      peach_pending_vouched_devices_v1: [{2001        deviceId,2002        deviceName: "New Pixel",2003        deviceType: "android",2004        longTermPublicKeyHex: "e".repeat(64),2005        signingPublicKeyHex: "a".repeat(64),2006        wsPort: 51234,2007        pairedAt: 1_700_000_000_020,2008        receivedAt: 1_700_000_000_050,2009        vouchedByDeviceId: "extension-issuer",2010      }],2011    });2012  }20132014  it("MV-7: CONFIRM_VOUCHED_DEVICE moves a pending device into the paired registry as vouched", async () => {2015    const vault = await import("./vault");2016    await vault.createVault("correct-pass-12345");2017    await seedPendingVouched("android-new");2018    const { findPairedDeviceById } = await import("./paired-devices");2019    const { listPendingVouchedDevices } = await import(2020      "./pending-vouched-devices"2021    );20222023    const res = await dispatch({2024      type: "CONFIRM_VOUCHED_DEVICE",2025      payload: { deviceId: "android-new" },2026    });2027    expect(res).toMatchObject({ ok: true });20282029    expect(await findPairedDeviceById("android-new")).toMatchObject({2030      deviceName: "New Pixel",2031      trustSource: "vouched",2032      longTermPublicKeyHex: "e".repeat(64),2033    });2034    expect(await listPendingVouchedDevices()).toHaveLength(0);2035  });20362037  it("S1: CONFIRM_VOUCHED_DEVICE refuses a pending device whose key is revoked", async () => {2038    const vault = await import("./vault");2039    await vault.createVault("correct-pass-12345");2040    await seedPendingVouched("android-relabelled");2041    const { findPairedDeviceById, revokeDeviceById, upsertPairedDevice } =2042      await import("./paired-devices");2043    const { listPendingVouchedDevices } = await import(2044      "./pending-vouched-devices"2045    );20462047    // The queue entry predates the revocation, and it carries a fresh id, so2048    // sweeping the queue by id at revocation time would not have caught it.2049    await upsertPairedDevice({2050      deviceId: "android-old",2051      deviceName: "New Pixel",2052      deviceType: "android",2053      longTermPublicKeyHex: "e".repeat(64),2054      signingPublicKeyHex: "a".repeat(64),2055      pairedAt: 1_700_000_000_000,2056      trustSource: "vouched",2057    });2058    await revokeDeviceById("android-old", "self");20592060    const res = await dispatch({2061      type: "CONFIRM_VOUCHED_DEVICE",2062      payload: { deviceId: "android-relabelled" },2063    });2064    expect(res).toMatchObject({ ok: false, error: "device_revoked" });2065    expect(await findPairedDeviceById("android-relabelled")).toBeNull();2066    expect(await listPendingVouchedDevices()).toHaveLength(0);2067  });20682069  it("MV-7: REJECT_VOUCHED_DEVICE clears the pending entry and never pairs it", async () => {2070    const vault = await import("./vault");2071    await vault.createVault("correct-pass-12345");2072    await seedPendingVouched("android-new");2073    const { findPairedDeviceById } = await import("./paired-devices");2074    const { listPendingVouchedDevices } = await import(2075      "./pending-vouched-devices"2076    );20772078    const res = await dispatch({2079      type: "REJECT_VOUCHED_DEVICE",2080      payload: { deviceId: "android-new" },2081    });2082    expect(res).toMatchObject({ ok: true });20832084    expect(await findPairedDeviceById("android-new")).toBeNull();2085    expect(await listPendingVouchedDevices()).toHaveLength(0);2086  });20872088  // --- unpair: UNPAIR_DEVICE revokes the device and drops it from the registry ---20892090  it("UNPAIR_DEVICE revokes a paired device, drops the row, and lists the revocation", async () => {2091    const vault = await import("./vault");2092    await vault.createVault("correct-pass-12345");2093    // Every real install mints its identity with (or before) its vault, so a2094    // fixture that seeds trust state without one is an install §11.5 refuses.2095    const identity = await import("./device-identity");2096    await identity.getOrCreateDeviceId();2097    const { findPairedDeviceById, isDeviceRevoked, listDeviceRevocations, upsertPairedDevice } =2098      await import("./paired-devices");20992100    await upsertPairedDevice({2101      deviceId: "phone-1",2102      deviceName: "June's Phone",2103      deviceType: "android",2104      longTermPublicKeyHex: "a".repeat(64),2105      signingPublicKeyHex: "b".repeat(64),2106      pairedAt: 1_700_000_000_000,2107      trustSource: "direct",2108    });21092110    const res = await dispatch({2111      type: "UNPAIR_DEVICE",2112      payload: { deviceId: "phone-1" },2113    });2114    expect(res).toMatchObject({ ok: true });21152116    // The row is gone locally — re-listing must not surface it.2117    expect(await findPairedDeviceById("phone-1")).toBeNull();2118    // The revocation is recorded so a future manifest from a peer cannot2119    // resurrect this device under either the same id or the same key (MV-7 + S1).2120    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);2121    const records = await listDeviceRevocations();2122    expect(records).toHaveLength(1);2123    expect(records[0]).toMatchObject({2124      deviceId: "phone-1",2125      longTermPublicKeyHex: "a".repeat(64),2126      revokedByDeviceId: expect.any(String),2127    });2128  });2129  it("UNPAIR_DEVICE resolves its issuer after an already queued adoption rotation", async () => {2130    const vault = await import("./vault");2131    await vault.createVault("correct-pass-12345");2132    const identity = await import("./device-identity");2133    const paired = await import("./paired-devices");2134    const oldId = await identity.getOrCreateDeviceId();2135    const rotation = paired.rotatePairedDeviceIdentity(() => identity.getLocalPairingIdentity({ existingOnly: true }), identity.rotateDeviceId);2136    const removal = dispatch({ type: "UNPAIR_DEVICE", payload: { deviceId: "phone-1" } });2137    await rotation;2138    expect(await removal).toMatchObject({ ok: true });2139    const newId = await identity.getExistingDeviceId();2140    expect(newId).not.toBe(oldId);2141    expect(await paired.listDeviceRevocations()).toMatchObject([{ deviceId: "phone-1", revokedByDeviceId: newId }]);2142  });21432144  it("UNPAIR_DEVICE still evicts a peer when the local identity needs migration", async () => {2145    const vault = await import("./vault");2146    await vault.createVault("correct-pass-12345");2147    const identity = await import("./device-identity");2148    await identity.getOrCreateDeviceId();2149    delete storage.peach_local_identity_v4;2150    delete sessionStorage.peach_local_identity_session;2151    const { findPairedDeviceById, isDeviceRevoked, upsertPairedDevice } = await import("./paired-devices");2152    await upsertPairedDevice({2153      deviceId: "phone-1",2154      deviceName: "June's Phone",2155      deviceType: "android",2156      longTermPublicKeyHex: "a".repeat(64),2157      signingPublicKeyHex: "b".repeat(64),2158      pairedAt: 1_700_000_000_000,2159      trustSource: "direct",2160    });21612162    const response = await dispatch({ type: "UNPAIR_DEVICE", payload: { deviceId: "phone-1" } });21632164    expect(response).toMatchObject({ ok: true });2165    expect(await findPairedDeviceById("phone-1")).toBeNull();2166    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);2167  });21682169  it("UNPAIR_DEVICE on an unknown id is a no-op (ok) and writes no revocation", async () => {2170    const vault = await import("./vault");2171    await vault.createVault("correct-pass-12345");2172    const { listDeviceRevocations } = await import("./paired-devices");21732174    const res = await dispatch({2175      type: "UNPAIR_DEVICE",2176      payload: { deviceId: "never-paired" },2177    });2178    expect(res).toMatchObject({ ok: true });2179    // A revocation with the all-zero key sentinel is still written — the2180    // contract is that the user-intent is recorded even when the registry had2181    // no row. This is what blocks a peer from later vouched-adopting the same2182    // fresh id back in.2183    const records = await listDeviceRevocations();2184    expect(records).toHaveLength(1);2185    expect(records[0]).toMatchObject({2186      deviceId: "never-paired",2187      longTermPublicKeyHex: "0".repeat(64),2188    });2189  });21902191  it("UNPAIR_DEVICE refuses an empty payload with invalid_payload", async () => {2192    const res = await dispatch({2193      type: "UNPAIR_DEVICE",2194      payload: { deviceId: "" },2195    });2196    expect(res).toMatchObject({ ok: false, error: "invalid_payload" });2197  });2198  it("SECURE_RESET reports archive review without clearing trust or a separate RESET_REQUIRED write", async () => {2199    const vault = await import("./vault");2200    await vault.createVault("correct-pass-12345");2201    const archive = { schemaVersion: 1, generation: 1, pairedDevices: ["incomplete"] };2202    storage.peach_sync_archive_g1_v1 = archive;2203    storage.peach_sync_generation_v1 = JSON.stringify({ schemaVersion: 1, active: {2204      schemaVersion: 1, generation: 1, state: "LEGACY_ACTIVE", createdAt: 100,2205    } });2206    const set = vi.mocked(chrome.storage.local.set);2207    set.mockClear();2208    const response = await dispatch({ type: "SECURE_RESET", payload: { password: "correct-pass-12345" } });2209    expect(response).toEqual({ ok: false, error: "The saved Sync trust archive needs review before reset can continue. Peach has kept the archive and current trust unchanged. Contact Peach support before retrying." });2210    expect(storage.peach_sync_archive_g1_v1).toEqual(archive);2211    const states = set.mock.calls.flatMap(([values]) => {2212      const raw = (values as StorageShape).peach_sync_generation_v1;2213      return typeof raw === "string" ? [JSON.parse(raw).active.state] : [];2214    });2215    expect(states).toEqual(["RESET_CONFIRMED"]);2216  });2217  it("SECURE_RESET archives legacy trust, rotates identity, and reaches the new Sync anchor", async () => {2218    const vault = await import("./vault");2219    await vault.createVault("correct-pass-12345");2220    const identity = await import("./device-identity");2221    const previousDeviceId = await identity.getOrCreateDeviceId();2222    const { upsertPairedDevice } = await import("./paired-devices");2223    await upsertPairedDevice({2224      deviceId: "phone-1",2225      deviceName: "June's Phone",2226      deviceType: "android",2227      longTermPublicKeyHex: "a".repeat(64),2228      signingPublicKeyHex: "b".repeat(64),2229      pairedAt: 1_700_000_000_000,2230      trustSource: "direct",2231    });22322233    const response = await dispatch({2234      type: "SECURE_RESET",2235      payload: { password: "correct-pass-12345" },2236    });22372238    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });2239    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);2240  });2241  it("SECURE_RESET unlocks a locked real vault before rotating identity", async () => {2242    const vault = await import("./vault");2243    await vault.createVault("correct-pass-12345");2244    const identity = await import("./device-identity");2245    const previousDeviceId = await identity.getOrCreateDeviceId();2246    const { upsertPairedDevice } = await import("./paired-devices");2247    await upsertPairedDevice({2248      deviceId: "phone-1",2249      deviceName: "June's Phone",2250      deviceType: "android",2251      longTermPublicKeyHex: "a".repeat(64),2252      signingPublicKeyHex: "b".repeat(64),2253      pairedAt: 1_700_000_000_000,2254      trustSource: "direct",2255    });2256    await vault.lock();2257    expect(vault.isUnlocked()).toBe(false);22582259    const response = await dispatch({2260      type: "SECURE_RESET",2261      payload: { password: "correct-pass-12345" },2262    });22632264    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });2265    expect(vault.isUnlocked()).toBe(true);2266    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);2267  });2268  it("SECURE_RESET completes after fresh unlock when the locked spool hits identity migration", async () => {2269    const vault = await import("./vault");2270    const syncAdapter = await import("./sync-vault-adapter");2271    vault.setLockedSyncHooks({2272      refresh: syncAdapter.refreshLockedSyncSpool,2273      afterUnlock: syncAdapter.drainAndRefreshLockedSyncSpool,2274    });2275    await vault.createVault("correct-pass-12345");2276    const identity = await import("./device-identity");2277    const previousDeviceId = await identity.getOrCreateDeviceId();2278    const { upsertPairedDevice } = await import("./paired-devices");2279    await upsertPairedDevice({2280      deviceId: "phone-1",2281      deviceName: "June's Phone",2282      deviceType: "android",2283      longTermPublicKeyHex: "a".repeat(64),2284      signingPublicKeyHex: "b".repeat(64),2285      pairedAt: 1_700_000_000_000,2286      trustSource: "direct",2287    });2288    await vault.addEntry({ type: "login", title: "spooled", password: "secret" });2289    await syncAdapter.refreshLockedSyncSpool();2290    await vault.lock();2291    const { createLockedSyncVaultAdapter } = await import("./locked-sync-spool");2292    const lockedAdapter = await createLockedSyncVaultAdapter();2293    expect(lockedAdapter).not.toBeNull();2294    await lockedAdapter!.applyEntries({ remote: "AA==" }, { remote: Date.now() + 1 });2295    delete storage.peach_local_identity_v4;2296    delete sessionStorage.peach_local_identity_session;2297    const sessionSet = chrome.storage.session.set as unknown as ReturnType<typeof vi.fn>;2298    sessionSet.mockImplementation(async (next: Record<string, unknown>) => {2299      if (Object.hasOwn(next, "peach_local_identity_session")) {2300        throw new Error("QUOTA_BYTES");2301      }2302      Object.assign(sessionStorage, next);2303    });23042305    const unlocked = await dispatch({2306      type: "UNLOCK",2307      payload: { password: "correct-pass-12345" },2308    });2309    const pairSecrets = await import("./pair-secrets");2310    const root = Uint8Array.from((vault.getRootKeyHex() ?? "").match(/../g)!, (part) => Number.parseInt(part, 16));2311    await pairSecrets.setPairSecret("phone-1", "c".repeat(64), root);2312    root.fill(0);2313    expect(storage.peach_pair_secrets_v1).toBeDefined();2314    expect(sessionStorage.peach_pair_secrets_session).toBeDefined();2315    expect(unlocked).toMatchObject({ ok: true });23162317    const response = await dispatch({2318      type: "SECURE_RESET",2319      payload: { password: "correct-pass-12345" },2320    });23212322    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });2323    expect(storage.peach_local_identity_v4).toBeDefined();2324    expect(storage.peach_paired_devices_v3).toBeUndefined();2325    expect(storage.peach_pair_secrets_v1).toBeUndefined();2326    expect(sessionStorage.peach_pair_secrets_session).toBeUndefined();2327    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);2328  });2329  // The old "fresh direct re-pair clears the old revocation" test dispatched2330  // COMPLETE_PAIRING, a handler deleted on 2026-08-04 (no legitimate senders;2331  // adoption runs in-background via relay-adoption-bg.ts). The live2332  // revocation-overlap repair is pinned in paired-devices.test.ts2333  // (repairPairedRevocationOverlaps, runs at service-worker boot).2334  it("F1: privileged handlers reject content-script senders but keep extension-page senders (Codex Security 2026-08-04)", async () => {2335    const vault = await import("./vault");2336    await vault.createVault("correct-pass-12345");2337    const contentScriptSender = {2338      id: "peach-extension",2339      url: "https://evil.example/page",2340    };2341    const extensionPageSender = {2342      id: "peach-extension",2343      url: "chrome-extension://peach-extension/popup.html",2344    };2345    const completion = { requestId: 1, rpId: "evil.example" };23462347    // Content-script senders must never reach the gated passkey-store handler.2348    await expect(2349      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, contentScriptSender)2350    ).resolves.toMatchObject({ ok: false, error: "invalid_sender" });23512352    // Extension-page senders still reach it — refused by the pending-ceremony2353    // binding, not by the sender gate.2354    await expect(2355      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2356    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });2357  });23582359  it("F2: COMPLETE_FIREFOX_PASSKEY_CREATE must match the pending ceremony (Codex Security 2026-08-04)", async () => {2360    const vault = await import("./vault");2361    await vault.createVault("correct-pass-12345");2362    const extensionPageSender = {2363      id: "peach-extension",2364      url: "chrome-extension://peach-extension/popup.html",2365    };2366    const completion = {2367      requestId: 123,2368      rpId: "example.com",2369      rpName: "Example",2370      userName: "june",2371      userHandle: "BBBB",2372      credentialId: "cred-1",2373      publicKeyCose: "c3BraQ",2374      algorithm: -7 as const,2375    };23762377    // No pending ceremony at all -> refuse.2378    await expect(2379      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2380    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });23812382    // Seed a background-minted pending ceremony.2383    sessionStorage.passkey_pending_firefox = {2384      requestId: 123,2385      type: "create",2386      rpId: "example.com",2387      rpName: "Example",2388      userName: "june",2389      browser: "firefox",2390      challenge: "AAAA",2391      userHandle: "BBBB",2392    };23932394    // Mismatched userHandle (attacker-forged completion) -> refuse.2395    await expect(2396      dispatch(2397        { type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: { ...completion, userHandle: "CCCC" } },2398        extensionPageSender2399      )2400    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });24012402    // Matching completion -> stored.2403    await expect(2404      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2405    ).resolves.toMatchObject({ ok: true });2406    const entries = await dispatch({ type: "GET_ENTRIES" });2407    expect(entries).toMatchObject({ ok: true });2408    const stored = (entries as { data: Array<{ passkey?: { credentialId?: string } }> }).data;2409    expect(stored.some((entry) => entry.passkey?.credentialId === "cred-1")).toBe(true);2410  });24112412  it("F2: INITIATE_FIREFOX_PASSKEY_CREATE rejects an rpId the caller origin does not own (Codex Security 2026-08-04)", async () => {2413    await expect(2414      dispatch(2415        {2416          type: "INITIATE_FIREFOX_PASSKEY_CREATE",2417          payload: { rpId: "bank.example", rpName: "Bank", userName: "june" },2418        },2419        { id: "peach-extension", url: "https://evil.example/page" }2420      )2421    ).resolves.toMatchObject({ ok: false, error: "rpid_origin_mismatch" });2422  });24232424  it("after UNPAIR_DEVICE, a fresh id carrying the same revoked key is also refused (S1)", async () => {2425    // The cross-manifest refusal is exercised end-to-end in sync-vault-adapter.test.ts;2426    // here we just pin the storage-level invariant the UNPAIR_DEVICE call2427    // establishes, since the rest of the testbed's revoke coverage rides on2428    // this state.2429    const vault = await import("./vault");2430    await vault.createVault("correct-pass-12345");2431    const { isDeviceRevoked, revokeDeviceById, upsertPairedDevice } = await import(2432      "./paired-devices"2433    );24342435    await upsertPairedDevice({2436      deviceId: "phone-1",2437      deviceName: "June's Phone",2438      deviceType: "android",2439      longTermPublicKeyHex: "a".repeat(64),2440      signingPublicKeyHex: "b".repeat(64),2441      pairedAt: 1_700_000_000_000,2442      trustSource: "direct",2443    });24442445    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(false);2446    await revokeDeviceById("phone-1", "self");2447    // The key check is what blocks a re-vouch under a fresh id.2448    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);2449    expect(await isDeviceRevoked("fresh-id", "a".repeat(64))).toBe(true);2450  });24512452  // --- LV-4: GET_RECOVERY_WORDS requires a fresh password proof ---24532454  it("LV-4: GET_RECOVERY_WORDS without a password returns password_required", async () => {2455    const vault = await import("./vault");2456    await vault.createVault("correct-pass-12345");24572458    const res = await dispatch({ type: "GET_RECOVERY_WORDS", payload: {} });2459    expect(res).toMatchObject({ ok: false, error: "password_required" });2460  });24612462  it("LV-4: GET_RECOVERY_WORDS with a wrong password returns wrong_password and no words", async () => {2463    const vault = await import("./vault");2464    await vault.createVault("correct-pass-12345");24652466    const res = await dispatch({2467      type: "GET_RECOVERY_WORDS",2468      payload: { password: "not-the-password" },2469    });2470    expect(res).toMatchObject({ ok: false, error: "wrong_password" });2471    expect(res.data).toBeUndefined();2472  });24732474  it("LV-4: GET_RECOVERY_WORDS with the correct password returns 12 words", async () => {2475    const vault = await import("./vault");2476    await vault.createVault("correct-pass-12345");24772478    const res = await dispatch({2479      type: "GET_RECOVERY_WORDS",2480      payload: { password: "correct-pass-12345" },2481    });2482    expect(res.ok).toBe(true);2483    expect((res.data as string[]).length).toBe(12);2484  });24852486  it("PB-26-311: cleartext export requires a fresh master-password proof", async () => {2487    const vault = await import("./vault");2488    await vault.createVault("correct-pass-12345");24892490    await expect(2491      dispatch({ type: "EXPORT_ENTRIES" as never, payload: {} }),2492    ).resolves.toMatchObject({ ok: false, error: "password_required" });2493    await expect(2494      dispatch({2495        type: "EXPORT_ENTRIES" as never,2496        payload: { password: "not-the-password" },2497      }),2498    ).resolves.toMatchObject({ ok: false, error: "wrong_password" });2499    await expect(2500      dispatch({2501        type: "EXPORT_ENTRIES" as never,2502        payload: { password: "correct-pass-12345" },2503      }),2504    ).resolves.toMatchObject({ ok: true, data: [] });2505  });25062507  it("GET_PIN_STATUS reports only a session-available PIN wrapper", async () => {2508    const vault = await import("./vault");2509    const password = "correct-pass-12345";2510    const popupSender = {2511      id: "peach-extension",2512      url: "chrome-extension://peach-extension/src/popup/index.html",2513    } as chrome.runtime.MessageSender;25142515    await vault.createVault(password);2516    await vault.setupPinUnlock(password, "1234");2517    await vault.lock();25182519    await expect(dispatch({ type: "GET_PIN_STATUS" }, popupSender)).resolves.toMatchObject({2520      ok: true,2521      data: { configured: true, available: true, attemptsRemaining: 3 },2522    });2523  });2524});