messages.test.ts

113.1 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 vault = await import("./vault");227    await vault.createVault("summon-pass-12345");228    const sender = {229      id: "peach-extension",230      url: "https://login.example.com/form",231      origin: "https://login.example.com",232      tab: { id: 1 },233      frameId: 0,234    } as chrome.runtime.MessageSender;235236    await expect(dispatch({237      type: "RECORD_MANUAL_SUMMON",238      payload: { domain: "evil.example" },239    }, sender)).resolves.toEqual({ ok: false, error: "invalid_domain" });240    await expect(dispatch({241      type: "RECORD_MANUAL_SUMMON",242      payload: { domain: "example.com" },243    }, sender)).resolves.toEqual({ ok: true });244    await expect(dispatch({245      type: "RECORD_MANUAL_SUMMON",246      payload: { domain: "a".repeat(254) },247    }, { ...sender, origin: "https://a.com", url: "https://a.com/form" })).resolves.toEqual({248      ok: false,249      error: "invalid_domain",250    });251  });252253  it("GET_ENTRIES when unlocked returns the entry array", async () => {254    const vault = await import("./vault");255    await vault.createVault("correct-pass-12345");256    await vault.addEntry({257      title: "GitHub",258      username: "june",259      password: "secret123",260      url: "https://github.com",261    });262263    await expect(dispatch({ type: "GET_ENTRIES" })).resolves.toMatchObject({264      ok: true,265      data: [266        expect.objectContaining({267          title: "GitHub",268          username: "june",269        }),270      ],271    });272  });273274  it("GET_ENTRIES when locked returns a vault locked error", async () => {275    const vault = await import("./vault");276    await vault.createVault("correct-pass-12345");277    vault.lock();278279    await expect(dispatch({ type: "GET_ENTRIES" })).resolves.toMatchObject({280      ok: false,281      error: "vault_locked",282    });283  });284285  it("ADD_ENTRY with a valid payload returns the created entry", async () => {286    const vault = await import("./vault");287    await vault.createVault("correct-pass-12345");288289    const response = await dispatch({290      type: "ADD_ENTRY",291      payload: {292        title: "GitHub",293        username: "june",294        password: "secret123",295        url: "https://github.com",296      },297    });298299    expect(response).toMatchObject({300      ok: true,301      data: expect.objectContaining({302        id: expect.any(String),303        title: "GitHub",304      }),305    });306    expect(vault.getEntries()).toHaveLength(1);307  });308309  it("ADD_ENTRY when locked returns a vault locked error", async () => {310    const vault = await import("./vault");311    await vault.createVault("correct-pass-12345");312    vault.lock();313314    await expect(315      dispatch({316        type: "ADD_ENTRY",317        payload: {318          title: "GitHub",319          username: "june",320          password: "secret123",321          url: "https://github.com",322        },323      })324    ).resolves.toMatchObject({ ok: false, error: "vault_locked" });325  });326327  it("ADD_ENTRY with no password succeeds for email-only accounts", async () => {328    const vault = await import("./vault");329    await vault.createVault("correct-pass-12345");330331    await expect(332      dispatch({333        type: "ADD_ENTRY",334        payload: {335          title: "GitHub",336          username: "june",337          password: "",338          url: "https://github.com",339        },340      })341    ).resolves.toMatchObject({ ok: true });342  });343344  it("UPDATE_ENTRY updates an existing entry and returns ok", async () => {345    const vault = await import("./vault");346    await vault.createVault("correct-pass-12345");347    const entry = await vault.addEntry({348      title: "GitHub",349      username: "june",350      password: "secret123",351      url: "https://github.com",352    });353354    await expect(355      dispatch({356        type: "UPDATE_ENTRY",357        payload: { id: entry.id, patch: { password: "new-secret" } },358      })359    ).resolves.toMatchObject({ ok: true });360361    expect(vault.getEntryById(entry.id)?.password).toBe("new-secret");362  });363364  it("UPDATE_ENTRY with an empty password clears it for email-only accounts", async () => {365    const vault = await import("./vault");366    await vault.createVault("correct-pass-12345");367    const entry = await vault.addEntry({368      title: "GitHub",369      username: "june",370      password: "secret123",371      url: "https://github.com",372    });373374    await expect(375      dispatch({376        type: "UPDATE_ENTRY",377        payload: { id: entry.id, patch: { password: "" } },378      })379    ).resolves.toMatchObject({ ok: true });380381    expect(vault.getEntryById(entry.id)?.password).toBeUndefined();382  });383384  it("DELETE_ENTRY soft-deletes the target entry", async () => {385    const vault = await import("./vault");386    await vault.createVault("correct-pass-12345");387    const entry = await vault.addEntry({388      title: "GitHub",389      username: "june",390      password: "secret123",391      url: "https://github.com",392    });393394    await expect(395      dispatch({396        type: "DELETE_ENTRY",397        payload: { id: entry.id },398      })399    ).resolves.toMatchObject({ ok: true });400401    expect(vault.getEntries()).toEqual([]);402    expect(vault.getDeletedEntries()).toHaveLength(1);403  });404405  it("DELETE_ENTRY of a missing id returns an error", async () => {406    const vault = await import("./vault");407    await vault.createVault("correct-pass-12345");408409    await expect(410      dispatch({411        type: "DELETE_ENTRY",412        payload: { id: "missing" },413      })414    ).resolves.toMatchObject({ ok: false, error: "entry_not_found" });415  });416417  it("GET_ENTRY_FOR_FILL returns a safe login entry without privateKeyJwk", async () => {418    const vault = await import("./vault");419    await vault.createVault("correct-pass-12345");420    const entry = await vault.addEntry({421      title: "GitHub",422      username: "june",423      password: "secret123",424      url: "https://github.com",425    });426427    const response = await dispatch(428      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },429      { id: "peach-extension", url: "https://github.com/login" },430    );431432    expect(response).toMatchObject({433      ok: true,434      data: expect.objectContaining({435        id: entry.id,436        username: "june",437        password: "secret123",438      }),439    });440    expect((response.data as Record<string, unknown>).privateKeyJwk).toBeUndefined();441  });442443  it("GET_ENTRY_FOR_FILL when locked returns an error", async () => {444    const vault = await import("./vault");445    await vault.createVault("correct-pass-12345");446    vault.lock();447448    await expect(449      dispatch({450        type: "GET_ENTRY_FOR_FILL",451        payload: { id: "missing" },452      })453    ).resolves.toMatchObject({ ok: false, error: "vault_locked" });454  });455456  it("GET_ENTRY_FOR_FILL rejects passkey-only entries", async () => {457    const vault = await import("./vault");458    await vault.createVault("correct-pass-12345");459    const generated = await generatePasskeyKeypair(-7);460    const entry = await vault.addEntry({461      type: "login",462      title: "WebAuthn.io",463      passkey: {464        rpId: "webauthn.io",465        rpName: "WebAuthn.io",466        credentialId: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),467        publicKeyCose: base64urlEncode(generated.publicKeyCose),468        privateKeyJwk: generated.privateKeyJwk,469        userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),470        userName: "june",471        userDisplayName: "June",472        algorithm: -7,473        signCount: 0,474        aaguid: "AAAAAAAAAAAAAAAAAAAAAA",475        backupEligible: true,476        backupState: false,477        createdAt: Date.now(),478      },479    });480481    await expect(482      dispatch({483        type: "GET_ENTRY_FOR_FILL",484        payload: { id: entry.id },485      })486    ).resolves.toMatchObject({ ok: false, error: "passkey_not_fillable" });487  });488489  it("AUTOFILL_QUERY returns matched domain metadata without secrets", async () => {490    const vault = await import("./vault");491    await vault.createVault("correct-pass-12345");492    await vault.addEntry({493      title: "GitHub",494      username: "june",495      password: "secret123",496      url: "https://github.com",497      totp: "JBSWY3DPEHPK3PXP",498    });499500    const response = await dispatch({501      type: "AUTOFILL_QUERY",502      payload: { domain: "github.com" },503    });504505    expect(response).toMatchObject({506      ok: true,507      data: [508        {509          id: expect.any(String),510          title: "GitHub",511          username: "june",512          url: "https://github.com",513          hasTotp: true,514        },515      ],516    });517    expect((response.data as Array<Record<string, unknown>>)[0].password).toBeUndefined();518    expect((response.data as Array<Record<string, unknown>>)[0].totp).toBeUndefined();519  });520521  it("AUTOFILL_QUERY includeAll returns search-ready summaries for non-note, non-passkey entries", async () => {522    const vault = await import("./vault");523    await vault.createVault("correct-pass-12345");524    await vault.addEntry({525      title: "GitHub",526      username: "june",527      password: "secret123",528      url: "https://github.com",529    });530    await vault.addEntry({531      type: "note",532      title: "Secure note",533      notes: "hello",534    });535536    const response = await dispatch({537      type: "AUTOFILL_QUERY",538      payload: { domain: "github.com", includeAll: true },539    });540541    expect(response).toMatchObject({542      ok: true,543      data: [544        {545          id: expect.any(String),546          title: "GitHub",547          username: "june",548          url: "https://github.com",549          hasPasskey: false,550        },551      ],552    });553    const data = response.data as Array<Record<string, unknown>>;554    expect(data).toHaveLength(1);555    // No secrets cross the boundary.556    expect(data[0]).not.toHaveProperty("password");557    expect(data[0]).not.toHaveProperty("totp");558  });559560  it("AUTOFILL_QUERY kind=totp returns only matching entries with 2FA summaries", async () => {561    const vault = await import("./vault");562    await vault.createVault("correct-pass-12345");563    await vault.addEntry({564      title: "GitHub",565      username: "june",566      password: "secret123",567      url: "https://github.com",568      totp: "JBSWY3DPEHPK3PXP",569    });570    await vault.addEntry({571      title: "No 2FA",572      username: "person",573      password: "secret123",574      url: "https://github.com",575    });576577    const response = await dispatch({578      type: "AUTOFILL_QUERY",579      payload: { domain: "github.com", kind: "totp" },580    });581582    expect(response).toMatchObject({583      ok: true,584      data: [585        {586          id: expect.any(String),587          title: "GitHub",588          username: "june",589          url: "https://github.com",590          hasTotp: true,591        },592      ],593    });594    expect((response.data as Array<Record<string, unknown>>)[0].totp).toBeUndefined();595    expect(response.data).toHaveLength(1);596  });597598  it("RESTORE_ENTRIES replace mode restores the provided entries", async () => {599    const vault = await import("./vault");600    await vault.createVault("correct-pass-12345");601    await vault.addEntry({ title: "A", username: "", password: "one", url: "" });602603    const response = await dispatch({604      type: "RESTORE_ENTRIES",605      payload: {606        mode: "replace",607        entries: [608          {609            id: "restored-1",610            type: "login",611            title: "B",612            username: "june",613            password: "two",614            url: "https://b.test",615            createdAt: 1,616            modifiedAt: 1,617          },618        ],619      },620    });621622    expect(response).toMatchObject({ ok: true, data: { added: 1, updated: 0, skipped: 0 } });623    expect(vault.getEntries().map((entry) => entry.id)).toEqual(["restored-1"]);624  });625626  it("RESTORE_ENTRIES replace mode with an empty array returns an error", async () => {627    const vault = await import("./vault");628    await vault.createVault("correct-pass-12345");629630    await expect(631      dispatch({632        type: "RESTORE_ENTRIES",633        payload: { mode: "replace", entries: [] },634      })635    ).resolves.toMatchObject({ ok: false, error: "refuse to replace with empty entry set" });636  });637638  it("CHANGE_PASSWORD responds true for the happy path and false for a wrong current password", async () => {639    const vault = await import("./vault");640    await vault.createVault("correct-pass-12345");641642    await expect(643      dispatch({644        type: "CHANGE_PASSWORD",645        payload: {646          currentPassword: "correct-pass-12345",647          newPassword: "new-pass-67890",648        },649      })650    ).resolves.toMatchObject({ ok: true });651652    vault.lock();653    expect(await vault.unlock("new-pass-67890")).toBe(true);654655    await expect(656      dispatch({657        type: "CHANGE_PASSWORD",658        payload: {659          currentPassword: "wrong-pass",660          newPassword: "another-pass",661        },662      })663    ).resolves.toMatchObject({ ok: false, error: "incorrect_current_password" });664  });665666  it("UPDATE_SETTINGS reschedules auto-lock using the new minutes value", async () => {667    const vault = await import("./vault");668    await vault.createVault("correct-pass-12345");669670    (671      chrome.alarms.create as unknown as ReturnType<typeof vi.fn>672    ).mockClear();673    (674      chrome.idle.setDetectionInterval as unknown as ReturnType<typeof vi.fn>675    ).mockClear();676677    await expect(678      dispatch({679        type: "UPDATE_SETTINGS",680        payload: { autoLockMinutes: 30 },681      })682    ).resolves.toMatchObject({ ok: true });683684    expect(vault.getSettings().autoLockMinutes).toBe(30);685    expect(chrome.idle.setDetectionInterval).toHaveBeenLastCalledWith(1800);686    expect(chrome.alarms.create).toHaveBeenLastCalledWith("autolock", {687      delayInMinutes: 30,688    });689  });690691  it("CHECK_ALL_BREACHES acknowledges then persists its background result", async () => {692    const vault = await import("./vault");693    await vault.createVault("correct-pass-12345");694    await vault.updateSettings({ breachMonitoring: false });695    const entry = await vault.addEntry({ type: "login", title: "GitHub", username: "june", password: "password", url: "https://github.com" });696    fetchMock.mockResolvedValueOnce({ ok: true, text: async () => "1E4C9B93F3F0682250B6CF8331B7EE68FD8:7" });697    const response = await dispatch({ type: "CHECK_ALL_BREACHES" });698    expect(response).toMatchObject({ ok: true, data: { state: "running", total: 1 } });699    await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete"));700    expect(vault.getEntryById(entry.id)?.breach).toBe(7);701    expect(await dispatch({ type: "GET_BREACH_SCAN_STATUS" })).toMatchObject({ ok: true, data: { state: "complete", scanned: 1, breached: 1 } });702  });703704  it("rejects page breach scan status requests", async () => {705    expect(await dispatch({ type: "GET_BREACH_SCAN_STATUS" }, { id: "peach-extension", url: "https://example.com" })).toMatchObject({ ok: false, error: "invalid_sender" });706  });707708  it("rejects passkey approval from a different tab than the ceremony", async () => {709    sessionStorage.passkey_pending_301 = {710      requestId: 301,711      type: "get",712      rpId: "example.com",713      rpName: "Example",714      userName: "[email protected]",715      tabId: 7,716      origin: "https://example.com",717    };718719    await expect(720      dispatch(721        { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 301, approved: true } },722        { id: "peach-extension", tab: { id: 8 }, url: "https://example.com/login" } as chrome.runtime.MessageSender,723      ),724    ).resolves.toMatchObject({ ok: false, error: "invalid_passkey_approval_sender" });725  });726727  it("requires trusted popup approval for embedded passkey requests", async () => {728    sessionStorage.passkey_pending_302 = {729      requestId: 302, type: "get", rpId: "login.example", rpName: "Login",730      userName: "june", origin: "https://login.example", crossOrigin: true,731    };732    for (const origin of ["https://top.example", "https://login.example"]) {733      await expect(dispatch(734        { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 302, approved: true } },735        { id: "peach-extension", tab: { id: 7 }, origin, url: `${origin}/login` } as chrome.runtime.MessageSender,736      )).resolves.toMatchObject({ ok: false, error: "invalid_passkey_approval_sender" });737      expect(sessionStorage.passkey_pending_302).toBeDefined();738    }739    await expect(dispatch({ type: "APPROVE_PASSKEY", payload: { requestId: 302 } })).resolves.toMatchObject({ ok: true });740    expect(sessionStorage.passkey_pending_302).toBeUndefined();741  });742743  it.each([false, true])("rejects content approval without a bound toast (missing pending: %s)", async (missing) => {744    if (!missing) sessionStorage.passkey_pending_303 = {745      requestId: 303, type: "get", rpId: "example.com", rpName: "Example",746      userName: "june", origin: "https://example.com", crossOrigin: false,747    };748    await expect(dispatch(749      { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 303, approved: true } },750      { id: "peach-extension", tab: { id: 7 }, url: "https://example.com/login" } as chrome.runtime.MessageSender,751    )).resolves.toMatchObject({ ok: false, error: "invalid_passkey_approval_sender" });752    if (!missing) expect(sessionStorage.passkey_pending_303).toBeDefined();753  });754755  it.each([true, false])("accepts bound same-origin toast consent: %s", async (approved) => {756    sessionStorage.passkey_pending_304 = {757      requestId: 304, type: "get", rpId: "example.com", rpName: "Example",758      userName: "june", tabId: 7, origin: "https://example.com", crossOrigin: false,759    };760    await expect(dispatch(761      { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 304, approved } },762      { id: "peach-extension", tab: { id: 7 }, url: "https://example.com/login" } as chrome.runtime.MessageSender,763    )).resolves.toMatchObject({ ok: true });764    expect(sessionStorage.passkey_pending_304).toBeUndefined();765  });766767  it("messages from foreign or URL-less senders are rejected", async () => {768    const vault = await import("./vault");769    await vault.createVault("correct-pass-12345");770771    await expect(dispatch({ type: "GET_ENTRIES" }, { id: "other-extension" })).resolves.toMatchObject({772      ok: false,773      error: "invalid_sender",774    });775776    await expect(dispatch({ type: "GET_ENTRIES" }, {})).resolves.toMatchObject({777      ok: false,778      error: "invalid_sender",779    });780  });781782  it("LOCK and UNLOCK messages update vault state correctly", async () => {783    const vault = await import("./vault");784785    await expect(786      dispatch({ type: "CREATE_VAULT", payload: { password: "correct-pass-12345" } })787    ).resolves.toMatchObject({ ok: true });788    expect(vault.isUnlocked()).toBe(true);789790    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });791    expect(vault.isUnlocked()).toBe(false);792793    await expect(794      dispatch({ type: "UNLOCK", payload: { password: "wrong-pass" } })795    ).resolves.toMatchObject({ ok: false });796    expect(vault.isUnlocked()).toBe(false);797798    await expect(799      dispatch({ type: "UNLOCK", payload: { password: "correct-pass-12345" } })800    ).resolves.toMatchObject({ ok: true });801    expect(vault.isUnlocked()).toBe(true);802  });803804  it("does not acknowledge LOCK until session cleanup finishes", async () => {805    await expect(806      dispatch({ type: "CREATE_VAULT", payload: { password: "correct-pass-12345" } })807    ).resolves.toMatchObject({ ok: true });808809    const removalStarted = deferred();810    const releaseRemoval = deferred();811    const remove = chrome.storage.session.remove as unknown as ReturnType<typeof vi.fn>;812    remove.mockImplementation(async (keys: string | string[]) => {813      removalStarted.resolve();814      await releaseRemoval.promise;815      for (const key of Array.isArray(keys) ? keys : [keys]) delete sessionStorage[key];816    });817818    let responded = false;819    const response = dispatch({ type: "LOCK" }).then((result) => {820      responded = true;821      return result;822    });823    await removalStarted.promise;824825    try {826      await Promise.resolve();827      expect(responded).toBe(false);828    } finally {829      releaseRemoval.resolve();830    }831832    await expect(response).resolves.toMatchObject({ ok: true });833  });834835  it("remembers the last successful unlock method", async () => {836    const vault = await import("./vault");837    const password = "correct-pass-12345";838    const popupSender = {839      id: "peach-extension",840      url: "chrome-extension://peach-extension/src/popup/index.html",841    } as chrome.runtime.MessageSender;842843    await vault.createVault(password);844    expect(await vault.setupPinUnlock(password, "1234")).toBe(true);845    vault.lock();846847    await expect(848      dispatch({ type: "UNLOCK_WITH_PIN", payload: { pin: "1234" } }, popupSender),849    ).resolves.toMatchObject({ ok: true });850    expect((await vault.ensureSettingsLoaded()).pinPreferred).toBe(true);851852    vault.lock();853    await expect(854      dispatch({ type: "UNLOCK", payload: { password } }, popupSender),855    ).resolves.toMatchObject({ ok: true });856    expect((await vault.ensureSettingsLoaded()).pinPreferred).toBe(false);857  });858859  describe("credential save comparison", () => {860    const sender = { id: "peach-extension", url: "https://github.com/login", tab: { id: 7 }, frameId: 0 } as chrome.runtime.MessageSender;861    const compare = (username = "june", password = "secret", source = sender) =>862      dispatch({ type: "CHECK_SAVE_CREDENTIAL", payload: { username, password } } as Message, source);863864    it("selects the submitted identity instead of the first domain entry", async () => {865      const vault = await import("./vault");866      await vault.createVault("comparison-password");867      await vault.addEntry({ title: "Other", username: "other", password: "secret", url: "https://github.com" });868      const entry = await vault.addEntry({ title: "June", username: "june", email: "[email protected]", password: "old", url: "https://github.com", notes: "private" });869      expect(await compare(" [email protected] ")).toEqual({ ok: true, data: { status: "changed", id: entry.id } });870      expect(await compare("other")).toEqual({ ok: true, data: { status: "same" } });871      expect(await compare("new")).toEqual({ ok: true, data: { status: "new" } });872    });873874    it("prefers an exact password and refuses ambiguous updates", async () => {875      const vault = await import("./vault");876      await vault.createVault("comparison-password");877      await vault.addEntry({ title: "One", username: "june", password: "one", url: "https://github.com" });878      await vault.addEntry({ title: "Two", username: "june", password: "two", url: "https://github.com" });879      expect(await compare("june", "two")).toEqual({ ok: true, data: { status: "same" } });880      expect(await compare()).toEqual({ ok: true, data: { status: "ambiguous" } });881      expect(fetchMock).not.toHaveBeenCalled();882    });883884    it("recognizes password-only named accounts without selecting them for updates", async () => {885      const vault = await import("./vault");886      await vault.createVault("comparison-password");887      await vault.addEntry({ title: "Named", username: "june", password: "secret", url: "https://github.com" });888      expect(await compare("")).toEqual({ ok: true, data: { status: "same" } });889      expect(await compare("", "different")).toEqual({ ok: true, data: { status: "new" } });890      const entry = await vault.addEntry({ title: "Anonymous", username: "", password: "old", url: "https://github.com" });891      expect(await compare(" ", "different")).toEqual({ ok: true, data: { status: "changed", id: entry.id } });892    });893894    it("excludes foreign, deleted, and non-login entries", async () => {895      const vault = await import("./vault");896      await vault.createVault("comparison-password");897      await vault.addEntry({ title: "Foreign", username: "june", password: "secret", url: "https://other.example" });898      await vault.addEntry({ type: "note", title: "Note", username: "june", password: "secret", url: "https://github.com" });899      const deleted = await vault.addEntry({ title: "Deleted", username: "june", password: "secret", url: "https://github.com" });900      await vault.deleteEntry(deleted.id);901      expect(await compare()).toEqual({ ok: true, data: { status: "new" } });902    });903904    it("rejects malformed payloads, caller domains, nonpage senders, and locked vaults", async () => {905      const vault = await import("./vault");906      await vault.createVault("comparison-password");907      for (const payload of [null, [], {}, { username: 1, password: "secret" }, { username: "june", password: 1 }, { username: "june", password: "secret", domain: "github.com" }]) {908        expect(await dispatch({ type: "CHECK_SAVE_CREDENTIAL", payload } as Message, sender)).toMatchObject({ ok: false });909      }910      expect(await compare("june", "secret", { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" })).toMatchObject({ ok: false });911      expect(await compare("june", "secret", { ...sender, url: "about:blank" })).toMatchObject({ ok: false });912      expect(await compare("june", "secret", { id: "peach-extension", url: "https://github.com/login" })).toMatchObject({ ok: false });913      await vault.lock();914      expect(await compare()).toMatchObject({ ok: false, error: "vault_locked" });915    });916917    it("alerts every exact canary match as submitted without returning entry data", async () => {918      await addCanary("First"); await addCanary("Second");919      expect(await compare("wrong")).toEqual({ ok: true, data: { status: "new" } });920      expect(await compare("june", "wrong")).toEqual({ ok: true, data: { status: "ambiguous" } });921      expect(fetchMock).not.toHaveBeenCalled();922      expect(await compare()).toEqual({ ok: true, data: { status: "same" } });923      expect(fetchMock).toHaveBeenCalledTimes(2);924      for (const call of fetchMock.mock.calls) expect(JSON.parse(call[1].body as string).trigger).toBe("submitted");925    });926927    it("alerts every named canary for an exact password-only submission", async () => {928      await addCanary("First"); const second = await addCanary("Second");929      const vault = await import("./vault");930      await vault.updateEntry(second.id, { username: "other" });931      expect(await compare("", "different")).toEqual({ ok: true, data: { status: "new" } });932      expect(fetchMock).not.toHaveBeenCalled();933      expect(await compare("")).toEqual({ ok: true, data: { status: "same" } });934      expect(fetchMock).toHaveBeenCalledTimes(2);935      for (const call of fetchMock.mock.calls) expect(JSON.parse(call[1].body as string).trigger).toBe("submitted");936    });937938    it("rechecks non-canary exact matches after a sibling canary await", async () => {939      await addCanary(); const vault = await import("./vault");940      const sibling = await vault.addEntry({ title: "Ordinary", username: "june", password: "secret", url: "https://github.com" });941      const held = deferred(); const entered = deferred();942      const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;943      vi.mocked(chrome.storage.local.get).mockImplementation(async key => {944        if (typeof key === "string" && key.startsWith("canary-last-fetch:")) { entered.resolve(); await held.promise; }945        return original(key);946      });947      const pending = compare(); await entered.promise;948      await vault.updateEntry(sibling.id, { password: "changed" });949      held.resolve();950      expect(await pending).toEqual({ ok: false, error: "entry_changed" });951      expect(fetchMock).toHaveBeenCalledTimes(1);952    });953954    it.each(["lock", "domain", "identity", "password"])("refuses stale comparison after an awaited canary %s change", async change => {955      const entry = await addCanary(); const vault = await import("./vault");956      const held = deferred(); const entered = deferred();957      const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;958      vi.mocked(chrome.storage.local.get).mockImplementation(async key => {959        if (typeof key === "string" && key.startsWith("canary-last-fetch:")) { entered.resolve(); await held.promise; }960        return original(key);961      });962      const pending = compare(); await entered.promise;963      if (change === "lock") { await vault.lock(); await vault.unlock("canary-test-password"); }964      else await vault.updateEntry(entry.id, change === "domain" ? { url: "https://other.example" } : change === "identity" ? { username: "other" } : { password: "changed" });965      held.resolve();966      expect(await pending).toMatchObject({ ok: false });967    });968  });969970  async function addCanary(title = "GitHub", webhookUrl = "https://example.com/hook") {971    const vault = await import("./vault");972    if (!vault.isUnlocked()) await vault.createVault("canary-test-password");973    return vault.addEntry({ type: "login", title, username: "june", password: "secret", url: "https://github.com", canary: { webhookUrl } });974  }975976  const canarySender = { id: "peach-extension", url: "https://github.com/login", tab: { id: 7 }, frameId: 0 } as chrome.runtime.MessageSender;977978  it("rejects unsafe canary destinations at trusted writes", async () => {979    const entry = await addCanary();980    for (const webhookUrl of ["https://user:[email protected]/hook", "https://100.64.1.2/hook"]) {981      expect(await dispatch({ type: "UPDATE_ENTRY", payload: { id: entry.id, patch: { canary: { webhookUrl } } } })).toMatchObject({ ok: false, error: "invalid_webhook_url" });982      expect(await dispatch({ type: "ADD_ENTRY", payload: { title: "Bad", canary: { webhookUrl } } })).toMatchObject({ ok: false, error: "invalid_webhook_url" });983    }984  });985986  it("keeps fresh background counters when a stale popup saves a label", async () => {987    const entry = await addCanary(); const vault = await import("./vault");988    await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender);989    expect(await dispatch({ type: "UPDATE_ENTRY", payload: { id: entry.id, patch: { canary: { ...entry.canary!, label: "new label", pingCount: 0, lastPinged: 1 } } } })).toMatchObject({ ok: true });990    expect(vault.getEntryById(entry.id)?.canary).toMatchObject({ label: "new label", pingCount: 1, lastPinged: expect.any(Number) });991    expect(vault.getEntryById(entry.id)?.canary?.lastPinged).not.toBe(1);992  });993994  it("counts a dispatched request even when rate storage fails", async () => {995    const entry = await addCanary(); const vault = await import("./vault");996    const original = vi.mocked(chrome.storage.local.set).getMockImplementation()! as unknown as (values: Record<string, unknown>) => Promise<void>;997    vi.mocked(chrome.storage.local.set).mockImplementation(async values => {998      if (Object.keys(values).some(key => key.startsWith("canary-last-fetch:"))) throw new Error("rate storage failed");999      return original(values);1000    });1001    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender)).toMatchObject({ ok: false, error: "canary_update_failed" });1002    expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(1);1003    expect(fetchMock).toHaveBeenCalledTimes(1);1004  });10051006  it("expires future persisted timestamps and future in-memory claims", async () => {1007    const entry = await addCanary();1008    const now = Date.now();1009    const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;1010    vi.mocked(chrome.storage.local.get).mockImplementation(async key => typeof key === "string" && key.startsWith("canary-last-fetch:") ? { [key]: now + 3600000 } : original(key));1011    expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender)).ok).toBe(true);1012    expect(fetchMock).toHaveBeenCalledTimes(1);1013    vi.spyOn(Date, "now").mockReturnValue(now - 1000);1014    expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender)).ok).toBe(true);1015    expect(fetchMock).toHaveBeenCalledTimes(2);1016  });10171018  it.each(["rename", "label", "counters", "destination", "delete"])("merges post-dispatch %s edits without losing a counted attempt", async change => {1019    const entry = await addCanary(); const vault = await import("./vault");1020    const held = deferred(); const entered = deferred();1021    const original = vi.mocked(chrome.storage.local.set).getMockImplementation()! as unknown as (values: Record<string, unknown>) => Promise<void>;1022    vi.mocked(chrome.storage.local.set).mockImplementation(async values => {1023      if (Object.keys(values).some(key => key.startsWith("canary-last-fetch:"))) { entered.resolve(); await held.promise; }1024      return original(values);1025    });1026    const pending = dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1027    await entered.promise;1028    if (change === "delete") await vault.deleteEntry(entry.id);1029    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" }) } });1030    held.resolve(); const result = await pending;1031    expect(fetchMock).toHaveBeenCalledTimes(1);1032    if (change === "delete" || change === "destination") {1033      expect(result).toMatchObject({ ok: false, error: "entry_changed" });1034      expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBeUndefined();1035    } else {1036      expect(result).toMatchObject({ ok: true, data: { password: "secret" } });1037      expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(change === "counters" ? 8 : 1);1038      if (change === "rename") expect(vault.getEntryById(entry.id)?.title).toBe("Renamed");1039      if (change === "label") expect(vault.getEntryById(entry.id)?.canary?.label).toBe("fresh");1040    }1041  });10421043  it.each(["get", "remove"] as const)("retries an undispatched alert after rate storage %s fails", async operation => {1044    const entry = await addCanary();1045    const original = vi.mocked(chrome.storage.local[operation]).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;1046    let failed = false;1047    vi.mocked(chrome.storage.local[operation]).mockImplementation(async key => {1048      if (!failed && typeof key === "string" && key.startsWith("canary-last-fetch:")) { failed = true; throw new Error("before dispatch"); }1049      return original(key);1050    });1051    expect((await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).ok).toBe(false);1052    expect(fetchMock).not.toHaveBeenCalled();1053    expect((await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).ok).toBe(true);1054    expect(fetchMock).toHaveBeenCalledTimes(1);1055  });10561057  it("fails closed on legacy invalid stored webhooks without dropping their metadata", async () => {1058    const entry = await addCanary("Legacy", "https://100.64.1.2/hook");1059    expect(await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).toMatchObject({ ok: false, error: "invalid_webhook_url" });1060    const vault = await import("./vault");1061    expect(vault.getEntryById(entry.id)?.canary?.webhookUrl).toBe("https://100.64.1.2/hook");1062    expect(fetchMock).not.toHaveBeenCalled();1063  });10641065  it("starts trusted new canaries with clean counters", async () => {1066    await addCanary();1067    const result = await dispatch({ type: "ADD_ENTRY", payload: { title: "New", canary: { webhookUrl: "https://example.com/hook", pingCount: 99, lastPinged: 1 } } });1068    expect(result).toMatchObject({ ok: true });1069    expect((result.data as import("../shared/types").VaultEntry).canary?.pingCount).toBeUndefined();1070    expect((result.data as import("../shared/types").VaultEntry).canary?.lastPinged).toBeUndefined();1071  });10721073  it("resolves canary destination and title from the stored entry", async () => {1074    const entry = await addCanary();1075    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "password_copied" } })).toMatchObject({ ok: true });1076    expect(fetchMock).toHaveBeenCalledWith("https://example.com/hook", expect.objectContaining({ method: "POST", redirect: "error" }));1077    expect(JSON.parse(fetchMock.mock.calls[0][1].body as string)).toMatchObject({ event: "peach_canary_accessed", entry: "GitHub", trigger: "password_copied", source: "peach-extension" });1078    const vault = await import("./vault");1079    expect(vault.getEntryById(entry.id)?.canary).toMatchObject({ pingCount: 1, lastPinged: expect.any(Number) });1080  });10811082  it("refuses caller-selected non-test destinations without fetching", async () => {1083    const entry = await addCanary();1084    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" });1085    expect(fetchMock).not.toHaveBeenCalled();1086  });10871088  it("rejects array and boxed triggers without poisoning a later valid access", async () => {1089    const entry = await addCanary(); const vault = await import("./vault");1090    const malformed: unknown[] = [structuredClone(["accessed"]), Object("accessed") as unknown];1091    for (const trigger of malformed) {1092      expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger } }, canarySender)).toMatchObject({ ok: false, error: "invalid_payload" });1093      expect(fetchMock).not.toHaveBeenCalled();1094      expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBeUndefined();1095      expect(Object.keys(storage).some(key => key.startsWith("canary-last-fetch:"))).toBe(false);1096    }1097    expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender)).ok).toBe(true);1098    expect(fetchMock).toHaveBeenCalledTimes(1);1099    expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(1);1100  });11011102  it("requires unlock and the requesting frame's own domain", async () => {1103    const entry = await addCanary();1104    const payload = { id: entry.id, trigger: "submitted" };1105    expect(await dispatch({ type: "FIRE_CANARY_PING", payload }, { ...canarySender, url: "https://foreign.example/" })).toMatchObject({ ok: false, error: "entry_not_found" });1106    const vault = await import("./vault"); await vault.lock();1107    expect(await dispatch({ type: "FIRE_CANARY_PING", payload }, canarySender)).toMatchObject({ ok: false, error: "vault_locked" });1108    expect(fetchMock).not.toHaveBeenCalled();1109  });11101111  it("dispatches before credential return without waiting for HTTP completion", async () => {1112    const entry = await addCanary();1113    fetchMock.mockImplementation(() => new Promise(() => {}));1114    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1115    expect(result).toMatchObject({ ok: true, data: { password: "secret" } });1116    expect(fetchMock).toHaveBeenCalledTimes(1);1117    expect(JSON.parse(fetchMock.mock.calls[0][1].body as string).trigger).toBe("accessed");1118  });11191120  it("coalesces concurrent accesses and counts one outbound attempt", async () => {1121    const entry = await addCanary();1122    const payload = { id: entry.id, trigger: "autofilled" };1123    const replies = await Promise.all([dispatch({ type: "FIRE_CANARY_PING", payload }, canarySender), dispatch({ type: "FIRE_CANARY_PING", payload }, canarySender)]);1124    expect(replies.every(reply => reply.ok)).toBe(true);1125    expect(fetchMock).toHaveBeenCalledTimes(1);1126    const vault = await import("./vault");1127    expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(1);1128    await vault.updateEntry(entry.id, { title: "Renamed" });1129    expect(await dispatch({ type: "FIRE_CANARY_PING", payload }, canarySender)).toMatchObject({ ok: true, data: { rateLimited: true } });1130    expect(fetchMock).toHaveBeenCalledTimes(1);1131    expect(Object.keys(storage).some(key => key.includes("GitHub"))).toBe(false);1132  });11331134  it("removes the legacy plaintext canary rate key", async () => {1135    const entry = await addCanary(); const legacy = "canary-last-fetch:https://example.com/hook:GitHub";1136    storage[legacy] = Date.now();1137    expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "submitted" } }, canarySender)).ok).toBe(true);1138    expect(storage[legacy]).toBeUndefined();1139  });11401141  it("does not conflate distinct equal-title entries on one webhook", async () => {1142    const first = await addCanary(); const second = await addCanary();1143    for (const entry of [first, second]) await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "submitted" } }, canarySender);1144    expect(fetchMock).toHaveBeenCalledTimes(2);1145  });11461147  it("keeps accepted ID and canonical URL tuples unambiguous", async () => {1148    const base = await addCanary(); const vault = await import("./vault");1149    const first = { ...base, id: "a", canary: { webhookUrl: "https://x/:https://y/" } };1150    const second = { ...base, id: "a:https://x/", canary: { webhookUrl: "https://y/" } };1151    await vault.applyMergedRemoteEntries([first, second], {});1152    expect(vault.getEntryById(second.id)?.id).toBe(second.id);1153    for (const entry of [first, second]) expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "submitted" } }, canarySender)).ok).toBe(true);1154    expect(fetchMock).toHaveBeenCalledTimes(2);1155    expect(Object.keys(storage).filter(key => key.startsWith("canary-last-fetch:")).length).toBe(2);1156  });11571158  it("counts failed network attempts but not trusted test pings", async () => {1159    const entry = await addCanary();1160    fetchMock.mockRejectedValueOnce(new Error("synthetic network failure"));1161    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "password_copied" } })).toMatchObject({ ok: true });1162    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 });1163    const vault = await import("./vault");1164    expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(1);1165    expect(fetchMock).toHaveBeenCalledTimes(3);1166  });11671168  it("rejects test pings from content scripts", async () => {1169    await addCanary();1170    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { webhookUrl: "https://example.com/hook", entryTitle: "Draft", trigger: "test" } }, canarySender)).toMatchObject({ ok: false, error: "invalid_sender" });1171    expect(fetchMock).not.toHaveBeenCalled();1172  });11731174  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) => {1175    await addCanary();1176    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { webhookUrl, entryTitle: "Draft", trigger: "test" } })).toMatchObject({ ok: false, error: "invalid_webhook_url" });1177    expect(fetchMock).not.toHaveBeenCalled();1178  });11791180  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) => {1181    await addCanary();1182    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { webhookUrl, entryTitle: "Draft", trigger: "test" } })).toMatchObject({ ok: true });1183    expect(fetchMock).toHaveBeenCalledWith(webhookUrl, expect.objectContaining({ redirect: "error" }));1184  });11851186  it("does not release credentials after lock during a new canary await", async () => {1187    const entry = await addCanary(); const held = deferred(); const entered = deferred();1188    const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;1189    vi.spyOn(chrome.storage.local, "get").mockImplementation(async key => {1190      if (typeof key === "string" && key.startsWith("canary-last-fetch:")) { entered.resolve(); await held.promise; }1191      return original(key);1192    });1193    const filling = dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1194    await entered.promise; const vault = await import("./vault"); await vault.lock(); held.resolve();1195    expect(await filling).toMatchObject({ ok: false, error: "vault_locked" });1196    expect(fetchMock).not.toHaveBeenCalled();1197  });11981199  it("never treats an undispatched alert as an already attempted rate claim", async () => {1200    const entry = await addCanary(); const vault = await import("./vault");1201    vi.spyOn(vault, "updateEntry").mockRejectedValueOnce(new Error("synthetic counter persistence failure"));1202    const first = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1203    expect(first.ok).toBe(false);1204    const retry = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1205    if (retry.ok) expect(fetchMock).toHaveBeenCalledTimes(1);1206    expect(fetchMock).toHaveBeenCalledTimes(1);1207  });12081209  it("rechecks canary configuration after an awaited claim read", async () => {1210    const entry = await addCanary(); const held = deferred(); const entered = deferred();1211    const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;1212    vi.spyOn(chrome.storage.local, "get").mockImplementation(async key => {1213      if (typeof key === "string" && key.startsWith("canary-last-fetch:")) { entered.resolve(); await held.promise; }1214      return original(key);1215    });1216    const filling = dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1217    await entered.promise; const vault = await import("./vault");1218    await vault.updateEntry(entry.id, { canary: { webhookUrl: "https://new.example/hook", label: "new" } });1219    held.resolve();1220    expect(await filling).toMatchObject({ ok: false, error: "entry_changed" });1221    expect(fetchMock).not.toHaveBeenCalled();1222    expect(vault.getEntryById(entry.id)?.canary?.webhookUrl).toBe("https://new.example/hook");1223  });12241225  it("rejects a late canary edit between helper completion and credential return", async () => {1226    const entry = await addCanary(); const vault = await import("./vault"); const edited = deferred();1227    const original = vault.getEntryById; let queued = false;1228    vi.spyOn(vault, "getEntryById").mockImplementation(id => {1229      const current = original(id);1230      if (!queued && current?.canary?.pingCount === 1) {1231        queued = true;1232        queueMicrotask(() => { void vault.updateEntry(entry.id, { canary: { webhookUrl: "https://new.example/hook", label: "changed" } }).then(edited.resolve); });1233      }1234      return current;1235    });1236    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1237    await edited.promise;1238    expect(result).toMatchObject({ ok: false, error: "entry_changed" });1239    expect(fetchMock).toHaveBeenCalledTimes(1);1240  });12411242  it("does not cache a post-dispatch persistence error as a permanent access block", async () => {1243    const entry = await addCanary(); const vault = await import("./vault");1244    vi.spyOn(vault, "updateEntry").mockRejectedValueOnce(new Error("synthetic counter failure"));1245    expect((await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).ok).toBe(false);1246    await vault.updateEntry(entry.id, { canary: { ...entry.canary!, label: "corrected" } });1247    expect(await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).toMatchObject({ ok: true, data: { password: "secret" } });1248    expect(fetchMock).toHaveBeenCalledTimes(1);1249  });12501251  it("uses a valid cross-domain capability once for access and notification", async () => {1252    const entry = await addCanary(); const messages = await import("./messages");1253    const sender = { ...canarySender, url: "https://other.example/" };1254    const token = messages.createSummonCapability(7, "https://other.example");1255    expect((await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "other.example", capability: token } }, sender)).ok).toBe(true);1256    expect(await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender)).toMatchObject({ ok: true, data: { password: "secret" } });1257    expect(await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender)).toMatchObject({ ok: false, error: "entry_not_found" });1258    expect(fetchMock).toHaveBeenCalledTimes(1);1259  });12601261  it("a failed counter write cannot restore a superseded canary configuration", async () => {1262    const entry = await addCanary(); const entered = deferred(); const held = deferred();1263    const original = vi.mocked(chrome.storage.local.set).getMockImplementation()! as unknown as (values: Record<string, unknown>) => Promise<void>; let first = true;1264    vi.spyOn(chrome.storage.local, "set").mockImplementation(async values => {1265      if (first && Object.hasOwn(values, "peach_vault_a")) { first = false; entered.resolve(); await held.promise; throw new Error("synthetic failed counter write"); }1266      return original(values);1267    });1268    const vault = await import("./vault");1269    const failed = vault.updateEntry(entry.id, { canary: { ...entry.canary!, pingCount: 1 } }).catch(() => undefined);1270    await entered.promise;1271    await vault.updateEntry(entry.id, { canary: { webhookUrl: "https://new.example/hook", label: "new configuration" } });1272    held.resolve(); await failed;1273    expect(vault.getEntryById(entry.id)?.canary).toMatchObject({ webhookUrl: "https://new.example/hook", label: "new configuration" });1274  });12751276  it("failed counter rollback preserves a successful overlapping deletion", async () => {1277    const entry = await addCanary(); const entered = deferred(); const held = deferred();1278    const original = vi.mocked(chrome.storage.local.set).getMockImplementation()! as unknown as (values: Record<string, unknown>) => Promise<void>; let first = true;1279    vi.spyOn(chrome.storage.local, "set").mockImplementation(async values => {1280      if (first && Object.hasOwn(values, "peach_vault_a")) { first = false; entered.resolve(); await held.promise; throw new Error("synthetic failed counter write"); }1281      return original(values);1282    });1283    const vault = await import("./vault");1284    const failed = vault.updateEntry(entry.id, { canary: { ...entry.canary!, pingCount: 1 } }).catch(() => undefined);1285    await entered.promise; await vault.deleteEntry(entry.id); held.resolve(); await failed;1286    expect(vault.getEntryById(entry.id)).toBeUndefined();1287    await vault.lock(); await vault.unlock("canary-test-password");1288    expect(vault.getEntryById(entry.id)).toBeUndefined();1289  });12901291  it("GET_IDENTITIES when locked returns vault locked error", async () => {1292    const vault = await import("./vault");1293    await vault.createVault("correct-pass-12345");1294    vault.lock();1295    await expect(dispatch({ type: "GET_IDENTITIES" })).resolves.toMatchObject({1296      ok: false,1297      error: "vault_locked",1298    });1299  });13001301  it("GET_IDENTITIES returns emails and usernames derived from login entries", async () => {1302    const vault = await import("./vault");1303    await vault.createVault("correct-pass-12345");1304    await vault.addEntry({ title: "Gmail", username: "[email protected]", password: "pw1", url: "https://gmail.com" });1305    await vault.addEntry({ title: "GitHub", username: "[email protected]", password: "pw2", url: "https://github.com" });1306    await vault.addEntry({ title: "Slack", username: "juni_patel", password: "pw3", url: "https://slack.com" });13071308    const resp = await dispatch({ type: "GET_IDENTITIES" }) as { ok: boolean; data: unknown[] };1309    expect(resp.ok).toBe(true);1310    const data = resp.data as Array<{ value: string; type: string; useCount: number }>;1311    expect(data.find((d) => d.value === "[email protected]")).toMatchObject({1312      type: "email",1313      useCount: 2,1314    });1315    expect(data.find((d) => d.value === "juni_patel")).toMatchObject({1316      type: "username",1317      useCount: 1,1318    });1319    // emails appear before usernames1320    const emailIdx = data.findIndex((d) => d.value === "[email protected]");1321    const userIdx = data.findIndex((d) => d.value === "juni_patel");1322    expect(emailIdx).toBeLessThan(userIdx);1323  });13241325  it("GET_IDENTITIES deduplicates correctly — same email across 3 entries appears once with useCount 3", async () => {1326    const vault = await import("./vault");1327    await vault.createVault("correct-pass-12345");1328    for (let i = 0; i < 3; i++) {1329      await vault.addEntry({ title: `Site${i}`, username: "[email protected]", password: "pw", url: `https://site${i}.com` });1330    }13311332    const resp = await dispatch({ type: "GET_IDENTITIES" }) as { ok: boolean; data: unknown[] };1333    const data = resp.data as Array<{ value: string; useCount: number }>;1334    const hits = data.filter((d) => d.value === "[email protected]");1335    expect(hits).toHaveLength(1);1336    expect(hits[0]!.useCount).toBe(3);1337  });13381339  it("GET_IDENTITIES rejects content-script and page-relay senders", async () => {1340    const vault = await import("./vault");1341    await vault.createVault("correct-pass-12345");1342    await vault.addEntry({1343      title: "Private identity",1344      username: "[email protected]",1345      password: "pw",1346      url: "https://private.example",1347    });13481349    const senders = [1350      {1351        id: "peach-extension",1352        url: "https://private.example/signup",1353        tab: { id: 1 } as chrome.tabs.Tab,1354      },1355      { id: "peach-extension", url: "https://private.example/signup" },1356    ] satisfies chrome.runtime.MessageSender[];1357    for (const sender of senders) {1358      await expect(dispatch({ type: "GET_IDENTITIES" }, sender)).resolves.toMatchObject({1359        ok: false,1360        error: "invalid_sender",1361      });1362    }1363  });13641365  it("IS_CARD_DECLINED does not refresh the auto-lock timer", async () => {1366    const vault = await import("./vault");1367    await vault.createVault("correct-pass-12345");1368    const alarmsCreate = chrome.alarms.create as unknown as ReturnType<typeof vi.fn>;13691370    // Sanity: a non-excluded message (GET_ENTRIES) DOES refresh the timer1371    alarmsCreate.mockClear();1372    await dispatch({ type: "GET_ENTRIES" });1373    expect(alarmsCreate).toHaveBeenCalled();13741375    // Passive queries are in the exclusion list and must not re-arm1376    alarmsCreate.mockClear();1377    await dispatch({ type: "IS_CARD_DECLINED", payload: { origin: "https://example.com" } });1378    expect(alarmsCreate).not.toHaveBeenCalled();1379  });13801381  it("DESTROY_VAULT preserves the Pro license and celebration flag", async () => {1382    const vault = await import("./vault");1383    await vault.createVault("correct-pass-12345");1384    await vault.addEntry({ title: "Gmail", username: "june", password: "s", url: "https://mail.google.com" });13851386    // Simulate an activated Pro license + already-celebrated marker.1387    storage.peach_license = "PEACH-PRO-TEST-KEY";1388    storage.peach_pro_celebrated = true;13891390    const res = await dispatch({ type: "DESTROY_VAULT" }, { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" });1391    expect(res).toMatchObject({ ok: true });13921393    // Vault data is gone…1394    expect(storage.peach_vault_a).toBeUndefined();1395    // …but the paid license and celebration flag survive the wipe.1396    expect(storage.peach_license).toBe("PEACH-PRO-TEST-KEY");1397    expect(storage.peach_pro_celebrated).toBe(true);1398  });13991400  it("handleMessage waits for the restore gate before serving (cold-start: no premature onboarding/lock)", async () => {1401    const messages = await import("./messages");1402    const vault = await import("./vault");14031404    let resolveGate: () => void = () => {};1405    messages.setRestoreReady(new Promise<void>((r) => { resolveGate = r; }));14061407    let settled = false;1408    const pending = dispatch({ type: "HAS_VAULT" }).then((r) => { settled = true; return r; });14091410    // While restore is in flight the handler must NOT have answered yet —1411    // this is the window where the old code returned "no vault" → onboarding.1412    await new Promise((r) => setTimeout(r, 20));1413    expect(settled).toBe(false);14141415    // Restore completes (the vault becomes available), gate opens.1416    await vault.createVault("correct-pass-12345");1417    resolveGate();14181419    await expect(pending).resolves.toMatchObject({ ok: true, data: true });1420  });14211422  it.each([null, true, false, 1, {}, "replace", "warned-import "])("CREATE_VAULT rejects malformed replacement intent %j", async (replacement) => {1423    const result = await dispatch({ type: "CREATE_VAULT", payload: { password: "new-password", replacement } });1424    expect(result).toMatchObject({ ok: false, error: "invalid_payload" });1425    expect(storage.peach_vault_a).toBeUndefined();1426  });14271428  it("CREATE_VAULT refuses ordinary replacement of an existing locked vault", async () => {1429    const vault = await import("./vault");1430    await vault.createVault("original-password");1431    await vault.lock();1432    const before = structuredClone(storage);1433    expect(await dispatch({ type: "CREATE_VAULT", payload: { password: "new-password" } })).toMatchObject({ ok: false, error: "vault_already_exists" });1434    expect(storage).toEqual(before);1435    expect(await vault.unlock("original-password")).toBe(true);1436  });14371438  it("CREATE_VAULT rejects an empty master password (audit HIGH — no empty-key vault)", async () => {1439    const res = await dispatch({ type: "CREATE_VAULT", payload: { password: "" } });1440    expect(res.ok).toBe(false);1441    // Nothing was written — no vault exists.1442    const has = await dispatch({ type: "HAS_VAULT" });1443    expect((has as { data?: boolean }).data).toBe(false);1444  });14451446  it("GET_ENTRY_FOR_FILL sends a 6-digit TOTP code, never the seed (SEV-3-C)", async () => {1447    const vault = await import("./vault");1448    await vault.createVault("correct-pass-12345");1449    const e = await vault.addEntry({1450      title: "Mail",1451      username: "june",1452      password: "pw",1453      url: "https://mail.test",1454      totp: "JBSWY3DPEHPK3PXP",1455    });14561457    const res = await dispatch(1458      { type: "GET_ENTRY_FOR_FILL", payload: { id: e.id } },1459      { id: "peach-extension", url: "https://mail.test/login" },1460    );1461    expect(res.ok).toBe(true);1462    const data = res.data as { totp?: string; totpCode?: string; totpRemaining?: number };1463    expect(data.totp).toBeUndefined();1464    expect(data.totpCode).toMatch(/^\d{6}$/);1465    expect(data.totpRemaining).toBeGreaterThan(0);1466    expect(data.totpRemaining).toBeLessThanOrEqual(30);1467  });14681469  it("GET_ENTRY_FOR_FILL strips passwordHistory; GET_ENTRY_FOR_EDIT keeps it", async () => {1470    const vault = await import("./vault");1471    await vault.createVault("correct-pass-12345");1472    const e = await vault.addEntry({1473      title: "Bank",1474      username: "june",1475      password: "old-pw",1476      url: "https://bank.test",1477    });1478    await vault.updateEntry(e.id, { password: "new-pw" });14791480    const fill = await dispatch(1481      { type: "GET_ENTRY_FOR_FILL", payload: { id: e.id } },1482      { id: "peach-extension", url: "https://bank.test/login" },1483    );1484    expect(fill.ok).toBe(true);1485    // Passive autofill never receives prior passwords (blast-radius containment).1486    expect((fill.data as Record<string, unknown>).passwordHistory).toBeUndefined();14871488    const edit = await dispatch({ type: "GET_ENTRY_FOR_EDIT", payload: { id: e.id } });1489    expect(edit.ok).toBe(true);1490    const editHist = (edit.data as { passwordHistory?: Array<{ password: string }> }).passwordHistory ?? [];1491    expect(editHist.map((h) => h.password)).toEqual(["old-pw"]);1492  });14931494  it("PB-26-949: GET_ENTRY_FOR_FILL replies with only the fields a fill consumes", async () => {1495    const vault = await import("./vault");1496    await vault.createVault("correct-pass-12345");1497    const generated = await generatePasskeyKeypair(-7);1498    const entry = await vault.addEntry({1499      type: "login",1500      title: "Everything",1501      username: "june",1502      email: "[email protected]",1503      password: "before-rotation",1504      url: "https://everything.test",1505      additionalUrls: ["https://login.everything.test"],1506      totp: "JBSWY3DPEHPK3PXP",1507      notes: "recovery codes live here",1508      tags: ["work", "admin"],1509      canary: { webhookUrl: "https://example.com/hook" },1510    });1511    await vault.updateEntry(entry.id, {1512      password: "current-password",1513      breach: 7,1514      passkey: {1515        rpId: "everything.test",1516        rpName: "Everything",1517        credentialId: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1518        publicKeyCose: base64urlEncode(generated.publicKeyCose),1519        privateKeyJwk: generated.privateKeyJwk,1520        userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1521        userName: "june",1522        userDisplayName: "June",1523        algorithm: -7,1524        signCount: 0,1525        aaguid: "AAAAAAAAAAAAAAAAAAAAAA",1526        backupEligible: true,1527        backupState: false,1528        createdAt: Date.now(),1529      },1530    });15311532    const response = await dispatch(1533      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1534      { id: "peach-extension", url: "https://everything.test/login", tab: { id: 7 }, frameId: 0 } as chrome.runtime.MessageSender,1535    );15361537    expect(response.ok).toBe(true);1538    const data = (response as { data: Record<string, unknown> }).data;1539    // The reply is an allowlist, not the stored entry minus a few exclusions.1540    // Chrome drops undefined values on the wire; Firefox delivers them as1541    // undefined. Either way only defined keys count as delivered.1542    const delivered = Object.fromEntries(Object.entries(data).filter(([, value]) => value !== undefined));1543    expect(Object.keys(delivered).sort()).toEqual([1544      "additionalUrls",1545      "email",1546      "id",1547      "password",1548      "title",1549      "totpCode",1550      "totpRemaining",1551      "url",1552      "username",1553    ]);1554    expect(delivered).toMatchObject({1555      id: entry.id,1556      title: "Everything",1557      username: "june",1558      email: "[email protected]",1559      password: "current-password",1560      url: "https://everything.test",1561      additionalUrls: ["https://login.everything.test"],1562    });1563    const serialized = JSON.stringify(response);1564    expect(serialized).not.toContain("JBSWY3DPEHPK3PXP");1565    expect(serialized).not.toContain("before-rotation");1566    expect(serialized).not.toContain("recovery codes live here");1567  });15681569  it("PB-26-949: a card fill still receives the card fields it fills", async () => {1570    const vault = await import("./vault");1571    await vault.createVault("correct-pass-12345");1572    const card = await vault.addEntry({1573      type: "card",1574      title: "Personal Visa",1575      cardholderName: "June Peach",1576      cardNumber: "4111111111111111",1577      cvc: "123",1578      expMonth: "12",1579      expYear: "2030",1580    });15811582    const messages = await import("./messages");1583    const sender = tabSender("https://shop.test/checkout");1584    const token = messages.createSummonCapability(1, "https://shop.test");1585    // A fill capability is promoted from an inventory use, as the card selector does.1586    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "shop.test", kind: "card", capability: token } }, sender);1587    const response = await dispatch(1588      { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1589      sender,1590    );15911592    expect(response.ok).toBe(true);1593    const data = (response.data ?? {}) as Record<string, unknown>;1594    const delivered = Object.fromEntries(Object.entries(data).filter(([, value]) => value !== undefined));1595    expect(Object.keys(delivered).sort()).toEqual([1596      "cardNumber",1597      "cardholderName",1598      "cvc",1599      "expMonth",1600      "expYear",1601      "id",1602      "title",1603    ]);1604    expect(delivered).toMatchObject({1605      cardholderName: "June Peach",1606      cardNumber: "4111111111111111",1607      cvc: "123",1608      expMonth: "12",1609      expYear: "2030",1610    });1611  });16121613  it("GET_ENTRY_FOR_EDIT returns the raw TOTP seed for the trusted edit form", async () => {1614    const vault = await import("./vault");1615    await vault.createVault("correct-pass-12345");1616    const e = await vault.addEntry({1617      title: "Mail",1618      username: "june",1619      password: "pw",1620      url: "https://mail.test",1621      totp: "JBSWY3DPEHPK3PXP",1622    });16231624    const res = await dispatch({ type: "GET_ENTRY_FOR_EDIT", payload: { id: e.id } });1625    expect(res.ok).toBe(true);1626    const data = res.data as { totp?: string };1627    expect(data.totp).toBe("JBSWY3DPEHPK3PXP");1628  });16291630  it("DESTROY_VAULT with no license clears storage without resurrecting keys", async () => {1631    const vault = await import("./vault");1632    await vault.createVault("correct-pass-12345");16331634    const res = await dispatch({ type: "DESTROY_VAULT" }, { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" });1635    expect(res).toMatchObject({ ok: true });16361637    expect(storage.peach_vault_a).toBeUndefined();1638    expect(storage.peach_license).toBeUndefined();1639    expect(storage.peach_pro_celebrated).toBeUndefined();1640  });16411642  // --- MV-1: GET_ENTRY_FOR_FILL re-validates the requesting tab's origin ---16431644  function tabSender(url: string, tabId = 1, frameId = 0): chrome.runtime.MessageSender {1645    return { id: "peach-extension", tab: { id: tabId, url } as chrome.tabs.Tab, url, frameId };1646  }16471648  async function addPasskeyOnlyEntry(title: string, url: string) {1649    const vault = await import("./vault");1650    const generated = await generatePasskeyKeypair(-7);1651    return vault.addEntry({1652      type: "login",1653      title,1654      url,1655      passkey: {1656        rpId: new URL(url).hostname,1657        rpName: title,1658        credentialId: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1659        publicKeyCose: base64urlEncode(generated.publicKeyCose),1660        privateKeyJwk: generated.privateKeyJwk,1661        userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1662        userName: "june",1663        userDisplayName: "June",1664        algorithm: -7,1665        signCount: 0,1666        aaguid: "AAAAAAAAAAAAAAAAAAAAAA",1667        backupEligible: true,1668        backupState: false,1669        createdAt: Date.now(),1670      },1671    });1672  }16731674  it("PB-26-201: normal inventory ignores forged domain and gesture booleans", async () => {1675    const vault = await import("./vault");1676    await vault.createVault("correct-pass-12345");1677    await vault.addEntry({ title: "GitHub", username: "victim", password: "secret", url: "https://github.com" });1678    await vault.addEntry({ title: "Evil", username: "attacker", password: "known", url: "https://evil.example.com" });16791680    const result = await dispatch(1681      {1682        type: "AUTOFILL_QUERY",1683        payload: {1684          domain: "github.com",1685          includeAll: true,1686          userGesture: true,1687          explicitSummon: true,1688        },1689      },1690      tabSender("https://evil.example.com/phish"),1691    );16921693    expect(result).toMatchObject({ ok: true });1694    expect((result.data as Array<{ title: string }>).map((entry) => entry.title)).toEqual(["Evil"]);1695  });16961697  it("PB-26-201: normal TOTP inventory is scoped to the attested frame origin", async () => {1698    const vault = await import("./vault");1699    await vault.createVault("correct-pass-12345");1700    await vault.addEntry({ title: "GitHub 2FA", password: "secret", url: "https://github.com", totp: "JBSWY3DPEHPK3PXP" });1701    await vault.addEntry({ title: "Evil 2FA", password: "known", url: "https://evil.example.com", totp: "JBSWY3DPEHPK3PXP" });17021703    const result = await dispatch(1704      { type: "AUTOFILL_QUERY", payload: { domain: "github.com", kind: "totp" } },1705      tabSender("https://evil.example.com/verify"),1706    );17071708    expect((result.data as Array<{ title: string }>).map((entry) => entry.title)).toEqual(["Evil 2FA"]);1709  });17101711  it("PB-26-201: summon capability is one-shot after inventory authorization", async () => {1712    const vault = await import("./vault");1713    const messages = await import("./messages");1714    await vault.createVault("correct-pass-12345");1715    const entry = await vault.addEntry({ title: "GitHub", username: "june", password: "secret123", url: "https://github.com" });1716    const sender = tabSender("https://evil.example.com/phish");1717    const token = messages.createSummonCapability(1, "https://evil.example.com");17181719    const inventory = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1720    expect(inventory).toMatchObject({ ok: true, data: [{ id: entry.id }] });17211722    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1723    expect(firstFill).toMatchObject({ ok: true, data: { id: entry.id } });1724    const replay = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1725    expect(replay).toMatchObject({ ok: false, error: "entry_not_found" });1726  });17271728  it("PB-26-201: summon capability is consumed by a same-domain fill", async () => {1729    const vault = await import("./vault");1730    const messages = await import("./messages");1731    await vault.createVault("correct-pass-12345");1732    const entry = await vault.addEntry({ title: "GitHub", password: "secret123", url: "https://evil.example.com" });1733    const sender = tabSender("https://evil.example.com/login");1734    const token = messages.createSummonCapability(1, "https://evil.example.com");17351736    const inventory = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1737    expect(inventory).toMatchObject({ ok: true, data: [{ id: entry.id }] });1738    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1739    expect(firstFill).toMatchObject({ ok: true, data: { id: entry.id } });17401741    const offDomainReplay = await dispatch(1742      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1743      tabSender("https://github.com/login"),1744    );1745    expect(offDomainReplay).toMatchObject({ ok: false, error: "entry_not_found" });1746  });17471748  it("PB-26-201: summon capability cannot fill a different entry", async () => {1749    const vault = await import("./vault");1750    const messages = await import("./messages");1751    await vault.createVault("correct-pass-12345");1752    const first = await vault.addEntry({ title: "First", password: "one", url: "https://first.example" });1753    const second = await vault.addEntry({ title: "Second", password: "two", url: "https://second.example" });1754    const sender = tabSender("https://evil.example.com/phish");1755    const token = messages.createSummonCapability(1, "https://evil.example.com");1756    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1757    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: first.id, capability: token } }, sender);1758    expect(firstFill).toMatchObject({ ok: true, data: { id: first.id } });1759    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: second.id, capability: token } }, sender);1760    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1761    expect(first.id).not.toBe(second.id);1762  });17631764  it("PB-26-201: fill before inventory is rejected without an entry oracle", async () => {1765    const vault = await import("./vault");1766    const messages = await import("./messages");1767    await vault.createVault("correct-pass-12345");1768    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1769    const token = messages.createSummonCapability(1, "https://evil.example.com");1770    const result = await dispatch(1771      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1772      tabSender("https://evil.example.com/phish"),1773    );1774    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1775  });17761777  it("PB-26-201: an unused summon capability does not block a normal same-origin fill", async () => {1778    const vault = await import("./vault");1779    const messages = await import("./messages");1780    await vault.createVault("correct-pass-12345");1781    const entry = await vault.addEntry({1782      title: "Evil",1783      password: "known",1784      url: "https://evil.example.com",1785    });1786    const sender = tabSender("https://evil.example.com/login");1787    const token = messages.createSummonCapability(1, "https://evil.example.com");17881789    const result = await dispatch(1790      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1791      sender,1792    );17931794    expect(result).toMatchObject({ ok: true, data: { id: entry.id } });1795  });17961797  it("PB-26-201: expired fill capability is rejected before entry-specific errors", async () => {1798    vi.useFakeTimers();1799    vi.setSystemTime(new Date("2026-09-02T12:00:00Z"));1800    const vault = await import("./vault");1801    const messages = await import("./messages");1802    await vault.createVault("correct-pass-12345");1803    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1804    const sender = tabSender("https://evil.example.com/phish");1805    const token = messages.createSummonCapability(1, "https://evil.example.com");1806    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1807    vi.advanceTimersByTime(30_001);18081809    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1810    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1811  });18121813  it("PB-26-201: wrong-tab fill capability is rejected before entry-specific errors", async () => {1814    const vault = await import("./vault");1815    const messages = await import("./messages");1816    await vault.createVault("correct-pass-12345");1817    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1818    const token = messages.createSummonCapability(1, "https://evil.example.com");1819    await dispatch(1820      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1821      tabSender("https://evil.example.com/phish"),1822    );18231824    const result = await dispatch(1825      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1826      tabSender("https://evil.example.com/phish", 2),1827    );1828    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1829  });18301831  it("PB-26-201: wrong-frame fill capability is rejected before entry-specific errors", async () => {1832    const vault = await import("./vault");1833    const messages = await import("./messages");1834    await vault.createVault("correct-pass-12345");1835    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1836    const token = messages.createSummonCapability(1, "https://evil.example.com", 3);1837    await dispatch(1838      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1839      tabSender("https://evil.example.com/phish", 1, 3),1840    );18411842    const result = await dispatch(1843      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1844      tabSender("https://evil.example.com/phish", 1, 4),1845    );1846    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1847  });18481849  it("PB-26-201: wrong-origin fill capability is rejected before entry-specific errors", async () => {1850    const vault = await import("./vault");1851    const messages = await import("./messages");1852    await vault.createVault("correct-pass-12345");1853    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1854    const token = messages.createSummonCapability(1, "https://evil.example.com");1855    await dispatch(1856      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1857      tabSender("https://evil.example.com/phish"),1858    );18591860    const result = await dispatch(1861      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1862      tabSender("https://other.example.com/phish"),1863    );1864    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1865  });18661867  it("PB-26-201: selecting a missing id consumes the one-shot capability without an oracle", async () => {1868    const vault = await import("./vault");1869    const messages = await import("./messages");1870    await vault.createVault("correct-pass-12345");1871    const existing = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1872    const sender = tabSender("https://evil.example.com/phish");1873    const token = messages.createSummonCapability(1, "https://evil.example.com");1874    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);18751876    const missing = await dispatch(1877      { type: "GET_ENTRY_FOR_FILL", payload: { id: "missing", capability: token } },1878      sender,1879    );1880    const existingReplay = await dispatch(1881      { type: "GET_ENTRY_FOR_FILL", payload: { id: existing.id, capability: token } },1882      sender,1883    );1884    expect(missing).toMatchObject({ ok: false, error: "entry_not_found" });1885    expect(existingReplay).toEqual(missing);1886  });18871888  it("PB-26-201: inventory capability cannot be reused for a second inventory", async () => {1889    const vault = await import("./vault");1890    const messages = await import("./messages");1891    await vault.createVault("correct-pass-12345");1892    await vault.addEntry({ title: "GitHub", password: "secret", url: "https://github.com" });1893    const sender = tabSender("https://evil.example.com/phish");1894    const token = messages.createSummonCapability(1, "https://evil.example.com");1895    const first = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1896    const second = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);18971898    expect(first).toMatchObject({ ok: true, data: [{ title: "GitHub" }] });1899    expect(second).toMatchObject({ ok: false, error: "entry_not_found" });1900  });19011902  it("PB-26-201: cards require a capability and consume it on the selected fill", async () => {1903    const vault = await import("./vault");1904    const messages = await import("./messages");1905    await vault.createVault("correct-pass-12345");1906    const card = await vault.addEntry({1907      type: "card",1908      title: "Personal Visa",1909      cardholderName: "June Peach",1910      cardNumber: "4111111111111111",1911      cvc: "123",1912      expMonth: "12",1913      expYear: "2030",1914    });1915    const sender = tabSender("https://shop.example.com/checkout");1916    const passive = await dispatch(1917      { type: "AUTOFILL_QUERY", payload: { domain: "shop.example.com", kind: "card" } },1918      sender,1919    );1920    expect(passive).toMatchObject({ ok: true, data: [] });19211922    const token = messages.createSummonCapability(1, "https://shop.example.com");1923    const inventory = await dispatch(1924      { type: "AUTOFILL_QUERY", payload: { domain: "forged.example", kind: "card", capability: token } },1925      sender,1926    );1927    expect(inventory).toMatchObject({ ok: true, data: [{ id: card.id, title: "Personal Visa" }] });1928    expect((inventory.data as Array<Record<string, unknown>>)[0]).not.toHaveProperty("cardNumber");19291930    const fill = await dispatch(1931      { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1932      sender,1933    );1934    expect(fill).toMatchObject({ ok: true, data: { id: card.id, cardNumber: "4111111111111111" } });1935    const replay = await dispatch(1936      { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1937      sender,1938    );1939    expect(replay).toMatchObject({ ok: false, error: "entry_not_found" });1940  });19411942  it("PB-26-201: inline edit popup request stores only the selected entry id", async () => {1943    const result = await dispatch(1944      { type: "OPEN_POPUP", payload: { entryId: "entry-123" } },1945      tabSender("https://example.com/login"),1946    );19471948    expect(result).toMatchObject({ ok: true });1949    expect(sessionStorage.peach_open_entry).toBe("entry-123");1950    expect(sessionStorage.peach_inline_unlock).toBeUndefined();1951  });19521953  it("MV-1: tab request with a matching domain returns the entry", async () => {1954    const vault = await import("./vault");1955    await vault.createVault("correct-pass-12345");1956    const entry = await vault.addEntry({1957      title: "GitHub",1958      username: "june",1959      password: "secret123",1960      url: "https://github.com",1961    });19621963    const res = await dispatch(1964      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1965      tabSender("https://github.com/login"),1966    );1967    expect(res).toMatchObject({ ok: true, data: { id: entry.id } });1968  });19691970  it("MV-1: tab request with a mismatched domain and no explicitSummon is refused as entry_not_found", async () => {1971    const vault = await import("./vault");1972    await vault.createVault("correct-pass-12345");1973    const entry = await vault.addEntry({1974      title: "GitHub",1975      username: "june",1976      password: "secret123",1977      url: "https://github.com",1978    });19791980    const res = await dispatch(1981      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1982      tabSender("https://evil.example.com/phish"),1983    );1984    // Refused with the same error as a missing id — no cross-domain oracle.1985    expect(res).toMatchObject({ ok: false, error: "entry_not_found" });1986  });19871988  it("PB-26-201: explicitSummon cannot authorize off-domain fill", async () => {1989    const vault = await import("./vault");1990    await vault.createVault("correct-pass-12345");1991    const entry = await vault.addEntry({1992      title: "GitHub",1993      username: "june",1994      password: "secret123",1995      url: "https://github.com",1996    });19971998    const res = await dispatch(1999      {2000        type: "GET_ENTRY_FOR_FILL",2001        payload: { id: entry.id, explicitSummon: true },2002      },2003      tabSender("https://evil.example.com/phish"),2004    );2005    expect(res).toMatchObject({ ok: false, error: "entry_not_found" });2006  });20072008  it("MV-1: tab context with an unparseable URL is refused as origin_unverified", async () => {2009    const vault = await import("./vault");2010    await vault.createVault("correct-pass-12345");2011    const entry = await vault.addEntry({2012      title: "GitHub",2013      username: "june",2014      password: "secret123",2015      url: "https://github.com",2016    });20172018    const res = await dispatch(2019      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },2020      tabSender("not a url"),2021    );2022    expect(res).toMatchObject({ ok: false, error: "origin_unverified" });2023  });20242025  // --- MV-2: vault-wide inventory only ships on an explicit user gesture ---20262027  async function seedTwoDomainVault() {2028    const vault = await import("./vault");2029    await vault.createVault("correct-pass-12345");2030    await vault.addEntry({2031      title: "GitHub",2032      username: "june",2033      password: "gh",2034      url: "https://github.com",2035    });2036    await vault.addEntry({2037      title: "Example",2038      username: "june",2039      password: "ex",2040      url: "https://example.com",2041    });2042  }20432044  it("MV-2: AUTOFILL_QUERY with includeAll but no userGesture returns only the domain-scoped list", async () => {2045    await seedTwoDomainVault();20462047    const res = await dispatch({2048      type: "AUTOFILL_QUERY",2049      payload: { domain: "github.com", includeAll: true },2050    });2051    expect(res.ok).toBe(true);2052    const data = res.data as Array<{ title: string }>;2053    // includeAll was stripped — only the github.com match comes back.2054    expect(data).toHaveLength(1);2055    expect(data[0].title).toBe("GitHub");2056  });20572058  it("PB-26-201: userGesture cannot authorize vault-wide inventory", async () => {2059    await seedTwoDomainVault();20602061    const res = await dispatch({2062      type: "AUTOFILL_QUERY",2063      payload: { domain: "github.com", includeAll: true, userGesture: true },2064    });2065    expect(res.ok).toBe(true);2066    const data = res.data as Array<{ title: string }>;2067    expect(data.map((d) => d.title)).toEqual(["GitHub"]);2068  });20692070  it("PB-26-104: decoy pairing messages hide devices and prior sync outcome", async () => {2071    const vault = await import("./vault");2072    const { listPairedDevices, upsertPairedDevice } = await import("./paired-devices");2073    const { setSyncRunner, triggerSyncIfReachable } = await import("./sync-trigger");2074    await vault.createVault("correct-pass-12345");2075    await vault.setupDuress("decoy-pass-67890");2076    await upsertPairedDevice({2077      deviceId: "android-real",2078      deviceName: "Real Pixel",2079      deviceType: "android",2080      longTermPublicKeyHex: "a".repeat(64),2081      trustSource: "direct",2082      pairedAt: 1_700_000_000_000,2083    });2084    setSyncRunner(async () => ({ ok: true, entriesReceived: 3, entriesSent: 2 }));2085    await triggerSyncIfReachable({ reason: "manual" });20862087    await vault.lock();2088    expect(await vault.unlock("decoy-pass-67890")).toBe(true);2089    await expect(dispatch({ type: "LIST_PAIRED_DEVICES" })).resolves.toEqual({2090      ok: true,2091      data: { devices: [] },2092    });2093    await expect(dispatch({ type: "GET_SYNC_STATE" })).resolves.toEqual({2094      ok: true,2095      data: { status: "idle" },2096    });2097    expect((await listPairedDevices()).map((device) => device.deviceName)).toEqual(["Real Pixel"]);2098  });20992100  it("PB-26-104: real unlocked pairing messages retain the device list", async () => {2101    const vault = await import("./vault");2102    const { upsertPairedDevice } = await import("./paired-devices");2103    await vault.createVault("correct-pass-12345");2104    await upsertPairedDevice({2105      deviceId: "android-real",2106      deviceName: "Real Pixel",2107      deviceType: "android",2108      longTermPublicKeyHex: "a".repeat(64),2109      trustSource: "direct",2110      pairedAt: 1_700_000_000_000,2111    });21122113    await expect(dispatch({ type: "LIST_PAIRED_DEVICES" })).resolves.toMatchObject({2114      ok: true,2115      data: { devices: [{ deviceId: "android-real", deviceName: "Real Pixel" }] },2116    });2117  });21182119  async function seedPendingVouched(deviceId: string) {2120    await chrome.storage.local.set({2121      peach_pending_vouched_devices_v1: [{2122        deviceId,2123        deviceName: "New Pixel",2124        deviceType: "android",2125        longTermPublicKeyHex: "e".repeat(64),2126        signingPublicKeyHex: "a".repeat(64),2127        wsPort: 51234,2128        pairedAt: 1_700_000_000_020,2129        receivedAt: 1_700_000_000_050,2130        vouchedByDeviceId: "extension-issuer",2131      }],2132    });2133  }21342135  it("MV-7: CONFIRM_VOUCHED_DEVICE moves a pending device into the paired registry as vouched", async () => {2136    const vault = await import("./vault");2137    await vault.createVault("correct-pass-12345");2138    await seedPendingVouched("android-new");2139    const { findPairedDeviceById } = await import("./paired-devices");2140    const { listPendingVouchedDevices } = await import(2141      "./pending-vouched-devices"2142    );21432144    const res = await dispatch({2145      type: "CONFIRM_VOUCHED_DEVICE",2146      payload: { deviceId: "android-new" },2147    });2148    expect(res).toMatchObject({ ok: true });21492150    expect(await findPairedDeviceById("android-new")).toMatchObject({2151      deviceName: "New Pixel",2152      trustSource: "vouched",2153      longTermPublicKeyHex: "e".repeat(64),2154    });2155    expect(await listPendingVouchedDevices()).toHaveLength(0);2156  });21572158  it("S1: CONFIRM_VOUCHED_DEVICE refuses a pending device whose key is revoked", async () => {2159    const vault = await import("./vault");2160    await vault.createVault("correct-pass-12345");2161    await seedPendingVouched("android-relabelled");2162    const { findPairedDeviceById, revokeDeviceById, upsertPairedDevice } =2163      await import("./paired-devices");2164    const { listPendingVouchedDevices } = await import(2165      "./pending-vouched-devices"2166    );21672168    // The queue entry predates the revocation, and it carries a fresh id, so2169    // sweeping the queue by id at revocation time would not have caught it.2170    await upsertPairedDevice({2171      deviceId: "android-old",2172      deviceName: "New Pixel",2173      deviceType: "android",2174      longTermPublicKeyHex: "e".repeat(64),2175      signingPublicKeyHex: "a".repeat(64),2176      pairedAt: 1_700_000_000_000,2177      trustSource: "vouched",2178    });2179    await revokeDeviceById("android-old", "self");21802181    const res = await dispatch({2182      type: "CONFIRM_VOUCHED_DEVICE",2183      payload: { deviceId: "android-relabelled" },2184    });2185    expect(res).toMatchObject({ ok: false, error: "device_revoked" });2186    expect(await findPairedDeviceById("android-relabelled")).toBeNull();2187    expect(await listPendingVouchedDevices()).toHaveLength(0);2188  });21892190  it("MV-7: REJECT_VOUCHED_DEVICE clears the pending entry and never pairs it", async () => {2191    const vault = await import("./vault");2192    await vault.createVault("correct-pass-12345");2193    await seedPendingVouched("android-new");2194    const { findPairedDeviceById } = await import("./paired-devices");2195    const { listPendingVouchedDevices } = await import(2196      "./pending-vouched-devices"2197    );21982199    const res = await dispatch({2200      type: "REJECT_VOUCHED_DEVICE",2201      payload: { deviceId: "android-new" },2202    });2203    expect(res).toMatchObject({ ok: true });22042205    expect(await findPairedDeviceById("android-new")).toBeNull();2206    expect(await listPendingVouchedDevices()).toHaveLength(0);2207  });22082209  // --- unpair: UNPAIR_DEVICE revokes the device and drops it from the registry ---22102211  it("UNPAIR_DEVICE revokes a paired device, drops the row, and lists the revocation", async () => {2212    const vault = await import("./vault");2213    await vault.createVault("correct-pass-12345");2214    // Every real install mints its identity with (or before) its vault, so a2215    // fixture that seeds trust state without one is an install §11.5 refuses.2216    const identity = await import("./device-identity");2217    await identity.getOrCreateDeviceId();2218    const { findPairedDeviceById, isDeviceRevoked, listDeviceRevocations, upsertPairedDevice } =2219      await import("./paired-devices");22202221    await upsertPairedDevice({2222      deviceId: "phone-1",2223      deviceName: "June's Phone",2224      deviceType: "android",2225      longTermPublicKeyHex: "a".repeat(64),2226      signingPublicKeyHex: "b".repeat(64),2227      pairedAt: 1_700_000_000_000,2228      trustSource: "direct",2229    });22302231    const res = await dispatch({2232      type: "UNPAIR_DEVICE",2233      payload: { deviceId: "phone-1" },2234    });2235    expect(res).toMatchObject({ ok: true });22362237    // The row is gone locally — re-listing must not surface it.2238    expect(await findPairedDeviceById("phone-1")).toBeNull();2239    // The revocation is recorded so a future manifest from a peer cannot2240    // resurrect this device under either the same id or the same key (MV-7 + S1).2241    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);2242    const records = await listDeviceRevocations();2243    expect(records).toHaveLength(1);2244    expect(records[0]).toMatchObject({2245      deviceId: "phone-1",2246      longTermPublicKeyHex: "a".repeat(64),2247      revokedByDeviceId: expect.any(String),2248    });2249  });2250  it("UNPAIR_DEVICE resolves its issuer after an already queued adoption rotation", async () => {2251    const vault = await import("./vault");2252    await vault.createVault("correct-pass-12345");2253    const identity = await import("./device-identity");2254    const paired = await import("./paired-devices");2255    const oldId = await identity.getOrCreateDeviceId();2256    const rotation = paired.rotatePairedDeviceIdentity(() => identity.getLocalPairingIdentity({ existingOnly: true }), identity.rotateDeviceId);2257    const removal = dispatch({ type: "UNPAIR_DEVICE", payload: { deviceId: "phone-1" } });2258    await rotation;2259    expect(await removal).toMatchObject({ ok: true });2260    const newId = await identity.getExistingDeviceId();2261    expect(newId).not.toBe(oldId);2262    expect(await paired.listDeviceRevocations()).toMatchObject([{ deviceId: "phone-1", revokedByDeviceId: newId }]);2263  });22642265  it("UNPAIR_DEVICE still evicts a peer when the local identity needs migration", async () => {2266    const vault = await import("./vault");2267    await vault.createVault("correct-pass-12345");2268    const identity = await import("./device-identity");2269    await identity.getOrCreateDeviceId();2270    delete storage.peach_local_identity_v4;2271    delete sessionStorage.peach_local_identity_session;2272    const { findPairedDeviceById, isDeviceRevoked, upsertPairedDevice } = await import("./paired-devices");2273    await upsertPairedDevice({2274      deviceId: "phone-1",2275      deviceName: "June's Phone",2276      deviceType: "android",2277      longTermPublicKeyHex: "a".repeat(64),2278      signingPublicKeyHex: "b".repeat(64),2279      pairedAt: 1_700_000_000_000,2280      trustSource: "direct",2281    });22822283    const response = await dispatch({ type: "UNPAIR_DEVICE", payload: { deviceId: "phone-1" } });22842285    expect(response).toMatchObject({ ok: true });2286    expect(await findPairedDeviceById("phone-1")).toBeNull();2287    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);2288  });22892290  it("UNPAIR_DEVICE on an unknown id is a no-op (ok) and writes no revocation", async () => {2291    const vault = await import("./vault");2292    await vault.createVault("correct-pass-12345");2293    const { listDeviceRevocations } = await import("./paired-devices");22942295    const res = await dispatch({2296      type: "UNPAIR_DEVICE",2297      payload: { deviceId: "never-paired" },2298    });2299    expect(res).toMatchObject({ ok: true });2300    // A revocation with the all-zero key sentinel is still written — the2301    // contract is that the user-intent is recorded even when the registry had2302    // no row. This is what blocks a peer from later vouched-adopting the same2303    // fresh id back in.2304    const records = await listDeviceRevocations();2305    expect(records).toHaveLength(1);2306    expect(records[0]).toMatchObject({2307      deviceId: "never-paired",2308      longTermPublicKeyHex: "0".repeat(64),2309    });2310  });23112312  it("UNPAIR_DEVICE refuses an empty payload with invalid_payload", async () => {2313    const res = await dispatch({2314      type: "UNPAIR_DEVICE",2315      payload: { deviceId: "" },2316    });2317    expect(res).toMatchObject({ ok: false, error: "invalid_payload" });2318  });2319  it("SECURE_RESET reports archive review without clearing trust or a separate RESET_REQUIRED write", async () => {2320    const vault = await import("./vault");2321    await vault.createVault("correct-pass-12345");2322    const archive = { schemaVersion: 1, generation: 1, pairedDevices: ["incomplete"] };2323    storage.peach_sync_archive_g1_v1 = archive;2324    storage.peach_sync_generation_v1 = JSON.stringify({ schemaVersion: 1, active: {2325      schemaVersion: 1, generation: 1, state: "LEGACY_ACTIVE", createdAt: 100,2326    } });2327    const set = vi.mocked(chrome.storage.local.set);2328    set.mockClear();2329    const response = await dispatch({ type: "SECURE_RESET", payload: { password: "correct-pass-12345" } });2330    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." });2331    expect(storage.peach_sync_archive_g1_v1).toEqual(archive);2332    const states = set.mock.calls.flatMap(([values]) => {2333      const raw = (values as StorageShape).peach_sync_generation_v1;2334      return typeof raw === "string" ? [JSON.parse(raw).active.state] : [];2335    });2336    expect(states).toEqual(["RESET_CONFIRMED"]);2337  });2338  it("SECURE_RESET archives legacy trust, rotates identity, and reaches the new Sync anchor", async () => {2339    const vault = await import("./vault");2340    await vault.createVault("correct-pass-12345");2341    const identity = await import("./device-identity");2342    const previousDeviceId = await identity.getOrCreateDeviceId();2343    const { upsertPairedDevice } = await import("./paired-devices");2344    await upsertPairedDevice({2345      deviceId: "phone-1",2346      deviceName: "June's Phone",2347      deviceType: "android",2348      longTermPublicKeyHex: "a".repeat(64),2349      signingPublicKeyHex: "b".repeat(64),2350      pairedAt: 1_700_000_000_000,2351      trustSource: "direct",2352    });23532354    const response = await dispatch({2355      type: "SECURE_RESET",2356      payload: { password: "correct-pass-12345" },2357    });23582359    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });2360    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);2361  });2362  it("SECURE_RESET unlocks a locked real vault before rotating identity", async () => {2363    const vault = await import("./vault");2364    await vault.createVault("correct-pass-12345");2365    const identity = await import("./device-identity");2366    const previousDeviceId = await identity.getOrCreateDeviceId();2367    const { upsertPairedDevice } = await import("./paired-devices");2368    await upsertPairedDevice({2369      deviceId: "phone-1",2370      deviceName: "June's Phone",2371      deviceType: "android",2372      longTermPublicKeyHex: "a".repeat(64),2373      signingPublicKeyHex: "b".repeat(64),2374      pairedAt: 1_700_000_000_000,2375      trustSource: "direct",2376    });2377    await vault.lock();2378    expect(vault.isUnlocked()).toBe(false);23792380    const response = await dispatch({2381      type: "SECURE_RESET",2382      payload: { password: "correct-pass-12345" },2383    });23842385    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });2386    expect(vault.isUnlocked()).toBe(true);2387    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);2388  });2389  it("SECURE_RESET completes after fresh unlock when the locked spool hits identity migration", async () => {2390    const vault = await import("./vault");2391    const syncAdapter = await import("./sync-vault-adapter");2392    vault.setLockedSyncHooks({2393      refresh: syncAdapter.refreshLockedSyncSpool,2394      afterUnlock: syncAdapter.drainAndRefreshLockedSyncSpool,2395    });2396    await vault.createVault("correct-pass-12345");2397    const identity = await import("./device-identity");2398    const previousDeviceId = await identity.getOrCreateDeviceId();2399    const { upsertPairedDevice } = await import("./paired-devices");2400    await upsertPairedDevice({2401      deviceId: "phone-1",2402      deviceName: "June's Phone",2403      deviceType: "android",2404      longTermPublicKeyHex: "a".repeat(64),2405      signingPublicKeyHex: "b".repeat(64),2406      pairedAt: 1_700_000_000_000,2407      trustSource: "direct",2408    });2409    await vault.addEntry({ type: "login", title: "spooled", password: "secret" });2410    await syncAdapter.refreshLockedSyncSpool();2411    await vault.lock();2412    const { createLockedSyncVaultAdapter } = await import("./locked-sync-spool");2413    const lockedAdapter = await createLockedSyncVaultAdapter();2414    expect(lockedAdapter).not.toBeNull();2415    await lockedAdapter!.applyEntries({ remote: "AA==" }, { remote: Date.now() + 1 });2416    delete storage.peach_local_identity_v4;2417    delete sessionStorage.peach_local_identity_session;2418    const sessionSet = chrome.storage.session.set as unknown as ReturnType<typeof vi.fn>;2419    sessionSet.mockImplementation(async (next: Record<string, unknown>) => {2420      if (Object.hasOwn(next, "peach_local_identity_session")) {2421        throw new Error("QUOTA_BYTES");2422      }2423      Object.assign(sessionStorage, next);2424    });24252426    const unlocked = await dispatch({2427      type: "UNLOCK",2428      payload: { password: "correct-pass-12345" },2429    });2430    const pairSecrets = await import("./pair-secrets");2431    const root = Uint8Array.from((vault.getRootKeyHex() ?? "").match(/../g)!, (part) => Number.parseInt(part, 16));2432    await pairSecrets.setPairSecret("phone-1", "c".repeat(64), root);2433    root.fill(0);2434    expect(storage.peach_pair_secrets_v1).toBeDefined();2435    expect(sessionStorage.peach_pair_secrets_session).toBeDefined();2436    expect(unlocked).toMatchObject({ ok: true });24372438    const response = await dispatch({2439      type: "SECURE_RESET",2440      payload: { password: "correct-pass-12345" },2441    });24422443    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });2444    expect(storage.peach_local_identity_v4).toBeDefined();2445    expect(storage.peach_paired_devices_v3).toBeUndefined();2446    expect(storage.peach_pair_secrets_v1).toBeUndefined();2447    expect(sessionStorage.peach_pair_secrets_session).toBeUndefined();2448    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);2449  });2450  // The old "fresh direct re-pair clears the old revocation" test dispatched2451  // COMPLETE_PAIRING, a handler deleted on 2026-08-04 (no legitimate senders;2452  // adoption runs in-background via relay-adoption-bg.ts). The live2453  // revocation-overlap repair is pinned in paired-devices.test.ts2454  // (repairPairedRevocationOverlaps, runs at service-worker boot).2455  it("F1: privileged handlers reject content-script senders but keep extension-page senders (Codex Security 2026-08-04)", async () => {2456    const vault = await import("./vault");2457    await vault.createVault("correct-pass-12345");2458    const contentScriptSender = {2459      id: "peach-extension",2460      url: "https://evil.example/page",2461    };2462    const extensionPageSender = {2463      id: "peach-extension",2464      url: "chrome-extension://peach-extension/popup.html",2465    };2466    const completion = { requestId: 1, rpId: "evil.example" };24672468    // Content-script senders must never reach the gated passkey-store handler.2469    await expect(2470      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, contentScriptSender)2471    ).resolves.toMatchObject({ ok: false, error: "invalid_sender" });24722473    // Extension-page senders still reach it — refused by the pending-ceremony2474    // binding, not by the sender gate.2475    await expect(2476      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2477    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });2478  });24792480  it("F2: COMPLETE_FIREFOX_PASSKEY_CREATE must match the pending ceremony (Codex Security 2026-08-04)", async () => {2481    const vault = await import("./vault");2482    await vault.createVault("correct-pass-12345");2483    const extensionPageSender = {2484      id: "peach-extension",2485      url: "chrome-extension://peach-extension/popup.html",2486    };2487    const completion = {2488      requestId: 123,2489      rpId: "example.com",2490      rpName: "Example",2491      userName: "june",2492      userHandle: "BBBB",2493      credentialId: "cred-1",2494      publicKeyCose: "c3BraQ",2495      algorithm: -7 as const,2496    };24972498    // No pending ceremony at all -> refuse.2499    await expect(2500      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2501    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });25022503    // Seed a background-minted pending ceremony.2504    sessionStorage.passkey_pending_firefox = {2505      requestId: 123,2506      type: "create",2507      rpId: "example.com",2508      rpName: "Example",2509      userName: "june",2510      browser: "firefox",2511      challenge: "AAAA",2512      userHandle: "BBBB",2513    };25142515    // Mismatched userHandle (attacker-forged completion) -> refuse.2516    await expect(2517      dispatch(2518        { type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: { ...completion, userHandle: "CCCC" } },2519        extensionPageSender2520      )2521    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });25222523    // Matching completion -> stored.2524    await expect(2525      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2526    ).resolves.toMatchObject({ ok: true });2527    const entries = await dispatch({ type: "GET_ENTRIES" });2528    expect(entries).toMatchObject({ ok: true });2529    const stored = (entries as { data: Array<{ passkey?: { credentialId?: string } }> }).data;2530    expect(stored.some((entry) => entry.passkey?.credentialId === "cred-1")).toBe(true);2531  });25322533  it("F2: INITIATE_FIREFOX_PASSKEY_CREATE rejects an rpId the caller origin does not own (Codex Security 2026-08-04)", async () => {2534    await expect(2535      dispatch(2536        {2537          type: "INITIATE_FIREFOX_PASSKEY_CREATE",2538          payload: { rpId: "bank.example", rpName: "Bank", userName: "june" },2539        },2540        { id: "peach-extension", url: "https://evil.example/page" }2541      )2542    ).resolves.toMatchObject({ ok: false, error: "rpid_origin_mismatch" });2543  });25442545  it("after UNPAIR_DEVICE, a fresh id carrying the same revoked key is also refused (S1)", async () => {2546    // The cross-manifest refusal is exercised end-to-end in sync-vault-adapter.test.ts;2547    // here we just pin the storage-level invariant the UNPAIR_DEVICE call2548    // establishes, since the rest of the testbed's revoke coverage rides on2549    // this state.2550    const vault = await import("./vault");2551    await vault.createVault("correct-pass-12345");2552    const { isDeviceRevoked, revokeDeviceById, upsertPairedDevice } = await import(2553      "./paired-devices"2554    );25552556    await upsertPairedDevice({2557      deviceId: "phone-1",2558      deviceName: "June's Phone",2559      deviceType: "android",2560      longTermPublicKeyHex: "a".repeat(64),2561      signingPublicKeyHex: "b".repeat(64),2562      pairedAt: 1_700_000_000_000,2563      trustSource: "direct",2564    });25652566    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(false);2567    await revokeDeviceById("phone-1", "self");2568    // The key check is what blocks a re-vouch under a fresh id.2569    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);2570    expect(await isDeviceRevoked("fresh-id", "a".repeat(64))).toBe(true);2571  });25722573  // --- LV-4: GET_RECOVERY_WORDS requires a fresh password proof ---25742575  it("LV-4: GET_RECOVERY_WORDS without a password returns password_required", async () => {2576    const vault = await import("./vault");2577    await vault.createVault("correct-pass-12345");25782579    const res = await dispatch({ type: "GET_RECOVERY_WORDS", payload: {} });2580    expect(res).toMatchObject({ ok: false, error: "password_required" });2581  });25822583  it("LV-4: GET_RECOVERY_WORDS with a wrong password returns wrong_password and no words", async () => {2584    const vault = await import("./vault");2585    await vault.createVault("correct-pass-12345");25862587    const res = await dispatch({2588      type: "GET_RECOVERY_WORDS",2589      payload: { password: "not-the-password" },2590    });2591    expect(res).toMatchObject({ ok: false, error: "wrong_password" });2592    expect(res.data).toBeUndefined();2593  });25942595  it("LV-4: GET_RECOVERY_WORDS with the correct password returns 12 words", async () => {2596    const vault = await import("./vault");2597    await vault.createVault("correct-pass-12345");25982599    const res = await dispatch({2600      type: "GET_RECOVERY_WORDS",2601      payload: { password: "correct-pass-12345" },2602    });2603    expect(res.ok).toBe(true);2604    expect((res.data as string[]).length).toBe(12);2605  });26062607  it("PB-26-311: cleartext export requires a fresh master-password proof", async () => {2608    const vault = await import("./vault");2609    await vault.createVault("correct-pass-12345");26102611    await expect(2612      dispatch({ type: "EXPORT_ENTRIES" as never, payload: {} }),2613    ).resolves.toMatchObject({ ok: false, error: "password_required" });2614    await expect(2615      dispatch({2616        type: "EXPORT_ENTRIES" as never,2617        payload: { password: "not-the-password" },2618      }),2619    ).resolves.toMatchObject({ ok: false, error: "wrong_password" });2620    await expect(2621      dispatch({2622        type: "EXPORT_ENTRIES" as never,2623        payload: { password: "correct-pass-12345" },2624      }),2625    ).resolves.toMatchObject({ ok: true, data: [] });2626  });26272628  it("GET_PIN_STATUS reports only a session-available PIN wrapper", async () => {2629    const vault = await import("./vault");2630    const password = "correct-pass-12345";2631    const popupSender = {2632      id: "peach-extension",2633      url: "chrome-extension://peach-extension/src/popup/index.html",2634    } as chrome.runtime.MessageSender;26352636    await vault.createVault(password);2637    await vault.setupPinUnlock(password, "1234");2638    await vault.lock();26392640    await expect(dispatch({ type: "GET_PIN_STATUS" }, popupSender)).resolves.toMatchObject({2641      ok: true,2642      data: { configured: true, available: true, attemptsRemaining: 3 },2643    });2644  });2645});