messages.test.ts

108.9 KB · raw

1import { beforeEach, describe, expect, it, vi } from "vitest";23import { base64urlEncode, generatePasskeyKeypair } from "./passkey-crypto";4import type { Message, MessageResponse } from "../shared/types";56type StorageShape = Record<string, unknown>;78function deferred(): { promise: Promise<void>; resolve: () => void } {9  let resolve!: () => void;10  const promise = new Promise<void>((done) => {11    resolve = done;12  });13  return { promise, resolve };14}15type MessageListener = (16  msg: unknown,17  sender: chrome.runtime.MessageSender,18  sendResponse: (response: MessageResponse) => void19) => boolean;2021/**22 * Chrome re-encodes everything it stores: `undefined` is dropped and object23 * keys come back in its own order, so a value read back is deep-equal to what24 * was set but never the same object nor the same JSON text. Storing the value25 * by reference would let an order-sensitive write-verify pass here and fail on26 * a real device — exactly how the secure-reset archive check shipped broken.27 */28function asChromeStores(value: unknown): unknown {29  if (Array.isArray(value)) return value.map(asChromeStores);30  if (value && typeof value === "object") {31    const source = value as StorageShape;32    const clone: StorageShape = {};33    for (const key of Object.keys(source).sort()) clone[key] = asChromeStores(source[key]);34    return clone;35  }36  return value;37}3839function storeWrite(target: StorageShape, next: StorageShape): void {40  for (const [key, value] of Object.entries(next)) {41    if (value === undefined) continue;42    target[key] = asChromeStores(value);43  }44}4546describe("background messages", () => {47  let storage: StorageShape;48  let sessionStorage: StorageShape;49  let listener: MessageListener;50  let fetchMock: ReturnType<typeof vi.fn>;5152  beforeEach(async () => {53    vi.resetModules();54    vi.useRealTimers();55    storage = {56      peach_settings: { breachMonitoring: false },57    };58    sessionStorage = {};59    fetchMock = vi.fn(async () => ({60      ok: true,61      status: 200,62      text: async () => "",63    }));64    vi.stubGlobal("fetch", fetchMock);65    vi.stubGlobal("__PEACH_E2E_PASSKEYS__", false);6667    const tabs = [{ id: 1 }];68    const chromeMock = {69      runtime: {70        id: "peach-extension",71        getURL: (p: string) => `chrome-extension://peach-extension/${p}`,72        onMessage: {73          addListener: vi.fn((fn: MessageListener) => {74            listener = fn;75          }),76        },77        sendMessage: vi.fn(async () => ({ ok: true })),78      },79      tabs: {80        query: vi.fn((_query: unknown, callback?: (tabs: Array<{ id?: number }>) => void) => {81          if (typeof callback === "function") {82            callback(tabs);83            return;84          }85          return Promise.resolve(tabs);86        }),87        sendMessage: vi.fn(async () => ({ ok: true })),88      },89      storage: {90        local: {91          get: vi.fn(async (key?: string | string[]) => {92            if (!key) return storage;93            if (typeof key === "string") {94              return { [key]: storage[key] };95            }9697            return key.reduce<Record<string, unknown>>((result, entry) => {98              result[entry] = storage[entry];99              return result;100            }, {});101          }),102          set: vi.fn(async (next: Record<string, unknown>) => {103            storeWrite(storage, next);104          }),105          remove: vi.fn(async (keys: string | string[]) => {106            const list = Array.isArray(keys) ? keys : [keys];107            for (const key of list) {108              delete storage[key];109            }110          }),111          clear: vi.fn(async () => {112            for (const key of Object.keys(storage)) delete storage[key];113          }),114        },115        session: {116          get: vi.fn(async (key?: string | string[]) => {117            if (!key) return sessionStorage;118            if (typeof key === "string") {119              return { [key]: sessionStorage[key] };120            }121            return key.reduce<Record<string, unknown>>((result, entry) => {122              result[entry] = sessionStorage[entry];123              return result;124            }, {});125          }),126          set: vi.fn(async (next: Record<string, unknown>) => {127            storeWrite(sessionStorage, next);128          }),129          remove: vi.fn(async (keys: string | string[]) => {130            const list = Array.isArray(keys) ? keys : [keys];131            for (const key of list) {132              delete sessionStorage[key];133            }134          }),135          clear: vi.fn(async () => {136            for (const key of Object.keys(sessionStorage)) delete sessionStorage[key];137          }),138        },139        sync: {140          get: vi.fn(async (_key?: string | string[]) => ({})),141          set: vi.fn(async (_values: Record<string, unknown>) => undefined),142          remove: vi.fn(async (_keys: string | string[]) => undefined),143          clear: vi.fn(async () => undefined),144        },145      },146      alarms: {147        clear: vi.fn(),148        create: vi.fn(),149        onAlarm: { addListener: vi.fn() },150      },151      idle: {152        setDetectionInterval: vi.fn(),153        onStateChanged: { addListener: vi.fn() },154      },155      scripting: {156        executeScript: vi.fn(async () => []),157      },158    } as unknown as typeof chrome;159160    (globalThis as { chrome?: typeof chrome }).chrome = chromeMock;161162    const messages = await import("./messages");163    messages.setupMessageHandler();164    const vault = await import("./vault");165    await vault.ensureSettingsLoaded();166  });167168  async function dispatch(169    message: Message,170    sender: chrome.runtime.MessageSender = {171      id: "peach-extension",172      url: "chrome-extension://peach-extension/popup.html",173    }174  ): Promise<MessageResponse> {175    return await new Promise<MessageResponse>((resolve) => {176      const keepChannelOpen = listener(message, sender, (response) => resolve(response));177      expect(keepChannelOpen).toBe(true);178    });179  }180181  it("PB-26-303: page GET_SETTINGS returns only theme, accent, and its own summon record", async () => {182    storage.peach_settings = {183      theme: "dark",184      accentColor: "peach",185      autoLockMinutes: 5,186      pinEnabled: true,187      manualSummonDomains: {188        "example.com": { firstSummonedAt: 1, summonCount: 2, lastSummonedAt: 3 },189        "other.example": { firstSummonedAt: 4, summonCount: 5, lastSummonedAt: 6 },190      },191    };192    const response = await dispatch(193      { type: "GET_SETTINGS" },194      {195        id: "peach-extension",196        url: "https://login.example.com/form",197        tab: { id: 1 },198        frameId: 0,199      } as chrome.runtime.MessageSender,200    );201202    expect(response).toEqual({203      ok: true,204      data: {205        theme: "dark",206        accentColor: "peach",207        manualSummonDomains: {208          "example.com": { firstSummonedAt: 1, summonCount: 2, lastSummonedAt: 3 },209        },210      },211    });212    await expect(dispatch({ type: "GET_SETTINGS" })).resolves.toMatchObject({213      ok: true,214      data: {215        autoLockMinutes: 5,216        pinEnabled: true,217        manualSummonDomains: {218          "example.com": expect.anything(),219          "other.example": expect.anything(),220        },221      },222    });223  });224225  it("RECORD_MANUAL_SUMMON binds and bounds the sender domain", async () => {226    const 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("GET_ENTRY_FOR_EDIT returns the raw TOTP seed for the trusted edit form", async () => {1495    const vault = await import("./vault");1496    await vault.createVault("correct-pass-12345");1497    const e = await vault.addEntry({1498      title: "Mail",1499      username: "june",1500      password: "pw",1501      url: "https://mail.test",1502      totp: "JBSWY3DPEHPK3PXP",1503    });15041505    const res = await dispatch({ type: "GET_ENTRY_FOR_EDIT", payload: { id: e.id } });1506    expect(res.ok).toBe(true);1507    const data = res.data as { totp?: string };1508    expect(data.totp).toBe("JBSWY3DPEHPK3PXP");1509  });15101511  it("DESTROY_VAULT with no license clears storage without resurrecting keys", async () => {1512    const vault = await import("./vault");1513    await vault.createVault("correct-pass-12345");15141515    const res = await dispatch({ type: "DESTROY_VAULT" }, { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" });1516    expect(res).toMatchObject({ ok: true });15171518    expect(storage.peach_vault_a).toBeUndefined();1519    expect(storage.peach_license).toBeUndefined();1520    expect(storage.peach_pro_celebrated).toBeUndefined();1521  });15221523  // --- MV-1: GET_ENTRY_FOR_FILL re-validates the requesting tab's origin ---15241525  function tabSender(url: string, tabId = 1, frameId = 0): chrome.runtime.MessageSender {1526    return { id: "peach-extension", tab: { id: tabId, url } as chrome.tabs.Tab, url, frameId };1527  }15281529  async function addPasskeyOnlyEntry(title: string, url: string) {1530    const vault = await import("./vault");1531    const generated = await generatePasskeyKeypair(-7);1532    return vault.addEntry({1533      type: "login",1534      title,1535      url,1536      passkey: {1537        rpId: new URL(url).hostname,1538        rpName: title,1539        credentialId: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1540        publicKeyCose: base64urlEncode(generated.publicKeyCose),1541        privateKeyJwk: generated.privateKeyJwk,1542        userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1543        userName: "june",1544        userDisplayName: "June",1545        algorithm: -7,1546        signCount: 0,1547        aaguid: "AAAAAAAAAAAAAAAAAAAAAA",1548        backupEligible: true,1549        backupState: false,1550        createdAt: Date.now(),1551      },1552    });1553  }15541555  it("PB-26-201: normal inventory ignores forged domain and gesture booleans", async () => {1556    const vault = await import("./vault");1557    await vault.createVault("correct-pass-12345");1558    await vault.addEntry({ title: "GitHub", username: "victim", password: "secret", url: "https://github.com" });1559    await vault.addEntry({ title: "Evil", username: "attacker", password: "known", url: "https://evil.example.com" });15601561    const result = await dispatch(1562      {1563        type: "AUTOFILL_QUERY",1564        payload: {1565          domain: "github.com",1566          includeAll: true,1567          userGesture: true,1568          explicitSummon: true,1569        },1570      },1571      tabSender("https://evil.example.com/phish"),1572    );15731574    expect(result).toMatchObject({ ok: true });1575    expect((result.data as Array<{ title: string }>).map((entry) => entry.title)).toEqual(["Evil"]);1576  });15771578  it("PB-26-201: normal TOTP inventory is scoped to the attested frame origin", async () => {1579    const vault = await import("./vault");1580    await vault.createVault("correct-pass-12345");1581    await vault.addEntry({ title: "GitHub 2FA", password: "secret", url: "https://github.com", totp: "JBSWY3DPEHPK3PXP" });1582    await vault.addEntry({ title: "Evil 2FA", password: "known", url: "https://evil.example.com", totp: "JBSWY3DPEHPK3PXP" });15831584    const result = await dispatch(1585      { type: "AUTOFILL_QUERY", payload: { domain: "github.com", kind: "totp" } },1586      tabSender("https://evil.example.com/verify"),1587    );15881589    expect((result.data as Array<{ title: string }>).map((entry) => entry.title)).toEqual(["Evil 2FA"]);1590  });15911592  it("PB-26-201: summon capability is one-shot after inventory authorization", async () => {1593    const vault = await import("./vault");1594    const messages = await import("./messages");1595    await vault.createVault("correct-pass-12345");1596    const entry = await vault.addEntry({ title: "GitHub", username: "june", password: "secret123", url: "https://github.com" });1597    const sender = tabSender("https://evil.example.com/phish");1598    const token = messages.createSummonCapability(1, "https://evil.example.com");15991600    const inventory = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1601    expect(inventory).toMatchObject({ ok: true, data: [{ id: entry.id }] });16021603    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1604    expect(firstFill).toMatchObject({ ok: true, data: { id: entry.id } });1605    const replay = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1606    expect(replay).toMatchObject({ ok: false, error: "entry_not_found" });1607  });16081609  it("PB-26-201: summon capability is consumed by a same-domain fill", async () => {1610    const vault = await import("./vault");1611    const messages = await import("./messages");1612    await vault.createVault("correct-pass-12345");1613    const entry = await vault.addEntry({ title: "GitHub", password: "secret123", url: "https://evil.example.com" });1614    const sender = tabSender("https://evil.example.com/login");1615    const token = messages.createSummonCapability(1, "https://evil.example.com");16161617    const inventory = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1618    expect(inventory).toMatchObject({ ok: true, data: [{ id: entry.id }] });1619    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1620    expect(firstFill).toMatchObject({ ok: true, data: { id: entry.id } });16211622    const offDomainReplay = await dispatch(1623      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1624      tabSender("https://github.com/login"),1625    );1626    expect(offDomainReplay).toMatchObject({ ok: false, error: "entry_not_found" });1627  });16281629  it("PB-26-201: summon capability cannot fill a different entry", async () => {1630    const vault = await import("./vault");1631    const messages = await import("./messages");1632    await vault.createVault("correct-pass-12345");1633    const first = await vault.addEntry({ title: "First", password: "one", url: "https://first.example" });1634    const second = await vault.addEntry({ title: "Second", password: "two", url: "https://second.example" });1635    const sender = tabSender("https://evil.example.com/phish");1636    const token = messages.createSummonCapability(1, "https://evil.example.com");1637    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1638    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: first.id, capability: token } }, sender);1639    expect(firstFill).toMatchObject({ ok: true, data: { id: first.id } });1640    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: second.id, capability: token } }, sender);1641    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1642    expect(first.id).not.toBe(second.id);1643  });16441645  it("PB-26-201: fill before inventory is rejected without an entry oracle", async () => {1646    const vault = await import("./vault");1647    const messages = await import("./messages");1648    await vault.createVault("correct-pass-12345");1649    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1650    const token = messages.createSummonCapability(1, "https://evil.example.com");1651    const result = await dispatch(1652      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1653      tabSender("https://evil.example.com/phish"),1654    );1655    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1656  });16571658  it("PB-26-201: an unused summon capability does not block a normal same-origin fill", async () => {1659    const vault = await import("./vault");1660    const messages = await import("./messages");1661    await vault.createVault("correct-pass-12345");1662    const entry = await vault.addEntry({1663      title: "Evil",1664      password: "known",1665      url: "https://evil.example.com",1666    });1667    const sender = tabSender("https://evil.example.com/login");1668    const token = messages.createSummonCapability(1, "https://evil.example.com");16691670    const result = await dispatch(1671      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1672      sender,1673    );16741675    expect(result).toMatchObject({ ok: true, data: { id: entry.id } });1676  });16771678  it("PB-26-201: expired fill capability is rejected before entry-specific errors", async () => {1679    vi.useFakeTimers();1680    vi.setSystemTime(new Date("2026-09-02T12:00:00Z"));1681    const vault = await import("./vault");1682    const messages = await import("./messages");1683    await vault.createVault("correct-pass-12345");1684    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1685    const sender = tabSender("https://evil.example.com/phish");1686    const token = messages.createSummonCapability(1, "https://evil.example.com");1687    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1688    vi.advanceTimersByTime(30_001);16891690    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1691    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1692  });16931694  it("PB-26-201: wrong-tab fill capability is rejected before entry-specific errors", async () => {1695    const vault = await import("./vault");1696    const messages = await import("./messages");1697    await vault.createVault("correct-pass-12345");1698    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1699    const token = messages.createSummonCapability(1, "https://evil.example.com");1700    await dispatch(1701      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1702      tabSender("https://evil.example.com/phish"),1703    );17041705    const result = await dispatch(1706      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1707      tabSender("https://evil.example.com/phish", 2),1708    );1709    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1710  });17111712  it("PB-26-201: wrong-frame fill capability is rejected before entry-specific errors", async () => {1713    const vault = await import("./vault");1714    const messages = await import("./messages");1715    await vault.createVault("correct-pass-12345");1716    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1717    const token = messages.createSummonCapability(1, "https://evil.example.com", 3);1718    await dispatch(1719      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1720      tabSender("https://evil.example.com/phish", 1, 3),1721    );17221723    const result = await dispatch(1724      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1725      tabSender("https://evil.example.com/phish", 1, 4),1726    );1727    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1728  });17291730  it("PB-26-201: wrong-origin fill capability is rejected before entry-specific errors", async () => {1731    const vault = await import("./vault");1732    const messages = await import("./messages");1733    await vault.createVault("correct-pass-12345");1734    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1735    const token = messages.createSummonCapability(1, "https://evil.example.com");1736    await dispatch(1737      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1738      tabSender("https://evil.example.com/phish"),1739    );17401741    const result = await dispatch(1742      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1743      tabSender("https://other.example.com/phish"),1744    );1745    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1746  });17471748  it("PB-26-201: selecting a missing id consumes the one-shot capability without an oracle", async () => {1749    const vault = await import("./vault");1750    const messages = await import("./messages");1751    await vault.createVault("correct-pass-12345");1752    const existing = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1753    const sender = tabSender("https://evil.example.com/phish");1754    const token = messages.createSummonCapability(1, "https://evil.example.com");1755    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);17561757    const missing = await dispatch(1758      { type: "GET_ENTRY_FOR_FILL", payload: { id: "missing", capability: token } },1759      sender,1760    );1761    const existingReplay = await dispatch(1762      { type: "GET_ENTRY_FOR_FILL", payload: { id: existing.id, capability: token } },1763      sender,1764    );1765    expect(missing).toMatchObject({ ok: false, error: "entry_not_found" });1766    expect(existingReplay).toEqual(missing);1767  });17681769  it("PB-26-201: inventory capability cannot be reused for a second inventory", async () => {1770    const vault = await import("./vault");1771    const messages = await import("./messages");1772    await vault.createVault("correct-pass-12345");1773    await vault.addEntry({ title: "GitHub", password: "secret", url: "https://github.com" });1774    const sender = tabSender("https://evil.example.com/phish");1775    const token = messages.createSummonCapability(1, "https://evil.example.com");1776    const first = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1777    const second = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);17781779    expect(first).toMatchObject({ ok: true, data: [{ title: "GitHub" }] });1780    expect(second).toMatchObject({ ok: false, error: "entry_not_found" });1781  });17821783  it("PB-26-201: cards require a capability and consume it on the selected fill", async () => {1784    const vault = await import("./vault");1785    const messages = await import("./messages");1786    await vault.createVault("correct-pass-12345");1787    const card = await vault.addEntry({1788      type: "card",1789      title: "Personal Visa",1790      cardholderName: "June Peach",1791      cardNumber: "4111111111111111",1792      cvc: "123",1793      expMonth: "12",1794      expYear: "2030",1795    });1796    const sender = tabSender("https://shop.example.com/checkout");1797    const passive = await dispatch(1798      { type: "AUTOFILL_QUERY", payload: { domain: "shop.example.com", kind: "card" } },1799      sender,1800    );1801    expect(passive).toMatchObject({ ok: true, data: [] });18021803    const token = messages.createSummonCapability(1, "https://shop.example.com");1804    const inventory = await dispatch(1805      { type: "AUTOFILL_QUERY", payload: { domain: "forged.example", kind: "card", capability: token } },1806      sender,1807    );1808    expect(inventory).toMatchObject({ ok: true, data: [{ id: card.id, title: "Personal Visa" }] });1809    expect((inventory.data as Array<Record<string, unknown>>)[0]).not.toHaveProperty("cardNumber");18101811    const fill = await dispatch(1812      { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1813      sender,1814    );1815    expect(fill).toMatchObject({ ok: true, data: { id: card.id, cardNumber: "4111111111111111" } });1816    const replay = await dispatch(1817      { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1818      sender,1819    );1820    expect(replay).toMatchObject({ ok: false, error: "entry_not_found" });1821  });18221823  it("PB-26-201: inline edit popup request stores only the selected entry id", async () => {1824    const result = await dispatch(1825      { type: "OPEN_POPUP", payload: { entryId: "entry-123" } },1826      tabSender("https://example.com/login"),1827    );18281829    expect(result).toMatchObject({ ok: true });1830    expect(sessionStorage.peach_open_entry).toBe("entry-123");1831    expect(sessionStorage.peach_inline_unlock).toBeUndefined();1832  });18331834  it("MV-1: tab request with a matching domain returns the entry", async () => {1835    const vault = await import("./vault");1836    await vault.createVault("correct-pass-12345");1837    const entry = await vault.addEntry({1838      title: "GitHub",1839      username: "june",1840      password: "secret123",1841      url: "https://github.com",1842    });18431844    const res = await dispatch(1845      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1846      tabSender("https://github.com/login"),1847    );1848    expect(res).toMatchObject({ ok: true, data: { id: entry.id } });1849  });18501851  it("MV-1: tab request with a mismatched domain and no explicitSummon is refused as entry_not_found", async () => {1852    const vault = await import("./vault");1853    await vault.createVault("correct-pass-12345");1854    const entry = await vault.addEntry({1855      title: "GitHub",1856      username: "june",1857      password: "secret123",1858      url: "https://github.com",1859    });18601861    const res = await dispatch(1862      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1863      tabSender("https://evil.example.com/phish"),1864    );1865    // Refused with the same error as a missing id — no cross-domain oracle.1866    expect(res).toMatchObject({ ok: false, error: "entry_not_found" });1867  });18681869  it("PB-26-201: explicitSummon cannot authorize off-domain fill", async () => {1870    const vault = await import("./vault");1871    await vault.createVault("correct-pass-12345");1872    const entry = await vault.addEntry({1873      title: "GitHub",1874      username: "june",1875      password: "secret123",1876      url: "https://github.com",1877    });18781879    const res = await dispatch(1880      {1881        type: "GET_ENTRY_FOR_FILL",1882        payload: { id: entry.id, explicitSummon: true },1883      },1884      tabSender("https://evil.example.com/phish"),1885    );1886    expect(res).toMatchObject({ ok: false, error: "entry_not_found" });1887  });18881889  it("MV-1: tab context with an unparseable URL is refused as origin_unverified", async () => {1890    const vault = await import("./vault");1891    await vault.createVault("correct-pass-12345");1892    const entry = await vault.addEntry({1893      title: "GitHub",1894      username: "june",1895      password: "secret123",1896      url: "https://github.com",1897    });18981899    const res = await dispatch(1900      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1901      tabSender("not a url"),1902    );1903    expect(res).toMatchObject({ ok: false, error: "origin_unverified" });1904  });19051906  // --- MV-2: vault-wide inventory only ships on an explicit user gesture ---19071908  async function seedTwoDomainVault() {1909    const vault = await import("./vault");1910    await vault.createVault("correct-pass-12345");1911    await vault.addEntry({1912      title: "GitHub",1913      username: "june",1914      password: "gh",1915      url: "https://github.com",1916    });1917    await vault.addEntry({1918      title: "Example",1919      username: "june",1920      password: "ex",1921      url: "https://example.com",1922    });1923  }19241925  it("MV-2: AUTOFILL_QUERY with includeAll but no userGesture returns only the domain-scoped list", async () => {1926    await seedTwoDomainVault();19271928    const res = await dispatch({1929      type: "AUTOFILL_QUERY",1930      payload: { domain: "github.com", includeAll: true },1931    });1932    expect(res.ok).toBe(true);1933    const data = res.data as Array<{ title: string }>;1934    // includeAll was stripped — only the github.com match comes back.1935    expect(data).toHaveLength(1);1936    expect(data[0].title).toBe("GitHub");1937  });19381939  it("PB-26-201: userGesture cannot authorize vault-wide inventory", async () => {1940    await seedTwoDomainVault();19411942    const res = await dispatch({1943      type: "AUTOFILL_QUERY",1944      payload: { domain: "github.com", includeAll: true, userGesture: true },1945    });1946    expect(res.ok).toBe(true);1947    const data = res.data as Array<{ title: string }>;1948    expect(data.map((d) => d.title)).toEqual(["GitHub"]);1949  });19501951  it("PB-26-104: decoy pairing messages hide devices and prior sync outcome", async () => {1952    const vault = await import("./vault");1953    const { listPairedDevices, upsertPairedDevice } = await import("./paired-devices");1954    const { setSyncRunner, triggerSyncIfReachable } = await import("./sync-trigger");1955    await vault.createVault("correct-pass-12345");1956    await vault.setupDuress("decoy-pass-67890");1957    await upsertPairedDevice({1958      deviceId: "android-real",1959      deviceName: "Real Pixel",1960      deviceType: "android",1961      longTermPublicKeyHex: "a".repeat(64),1962      trustSource: "direct",1963      pairedAt: 1_700_000_000_000,1964    });1965    setSyncRunner(async () => ({ ok: true, entriesReceived: 3, entriesSent: 2 }));1966    await triggerSyncIfReachable({ reason: "manual" });19671968    await vault.lock();1969    expect(await vault.unlock("decoy-pass-67890")).toBe(true);1970    await expect(dispatch({ type: "LIST_PAIRED_DEVICES" })).resolves.toEqual({1971      ok: true,1972      data: { devices: [] },1973    });1974    await expect(dispatch({ type: "GET_SYNC_STATE" })).resolves.toEqual({1975      ok: true,1976      data: { status: "idle" },1977    });1978    expect((await listPairedDevices()).map((device) => device.deviceName)).toEqual(["Real Pixel"]);1979  });19801981  it("PB-26-104: real unlocked pairing messages retain the device list", async () => {1982    const vault = await import("./vault");1983    const { upsertPairedDevice } = await import("./paired-devices");1984    await vault.createVault("correct-pass-12345");1985    await upsertPairedDevice({1986      deviceId: "android-real",1987      deviceName: "Real Pixel",1988      deviceType: "android",1989      longTermPublicKeyHex: "a".repeat(64),1990      trustSource: "direct",1991      pairedAt: 1_700_000_000_000,1992    });19931994    await expect(dispatch({ type: "LIST_PAIRED_DEVICES" })).resolves.toMatchObject({1995      ok: true,1996      data: { devices: [{ deviceId: "android-real", deviceName: "Real Pixel" }] },1997    });1998  });19992000  async function seedPendingVouched(deviceId: string) {2001    await chrome.storage.local.set({2002      peach_pending_vouched_devices_v1: [{2003        deviceId,2004        deviceName: "New Pixel",2005        deviceType: "android",2006        longTermPublicKeyHex: "e".repeat(64),2007        signingPublicKeyHex: "a".repeat(64),2008        wsPort: 51234,2009        pairedAt: 1_700_000_000_020,2010        receivedAt: 1_700_000_000_050,2011        vouchedByDeviceId: "extension-issuer",2012      }],2013    });2014  }20152016  it("MV-7: CONFIRM_VOUCHED_DEVICE moves a pending device into the paired registry as vouched", async () => {2017    const vault = await import("./vault");2018    await vault.createVault("correct-pass-12345");2019    await seedPendingVouched("android-new");2020    const { findPairedDeviceById } = await import("./paired-devices");2021    const { listPendingVouchedDevices } = await import(2022      "./pending-vouched-devices"2023    );20242025    const res = await dispatch({2026      type: "CONFIRM_VOUCHED_DEVICE",2027      payload: { deviceId: "android-new" },2028    });2029    expect(res).toMatchObject({ ok: true });20302031    expect(await findPairedDeviceById("android-new")).toMatchObject({2032      deviceName: "New Pixel",2033      trustSource: "vouched",2034      longTermPublicKeyHex: "e".repeat(64),2035    });2036    expect(await listPendingVouchedDevices()).toHaveLength(0);2037  });20382039  it("S1: CONFIRM_VOUCHED_DEVICE refuses a pending device whose key is revoked", async () => {2040    const vault = await import("./vault");2041    await vault.createVault("correct-pass-12345");2042    await seedPendingVouched("android-relabelled");2043    const { findPairedDeviceById, revokeDeviceById, upsertPairedDevice } =2044      await import("./paired-devices");2045    const { listPendingVouchedDevices } = await import(2046      "./pending-vouched-devices"2047    );20482049    // The queue entry predates the revocation, and it carries a fresh id, so2050    // sweeping the queue by id at revocation time would not have caught it.2051    await upsertPairedDevice({2052      deviceId: "android-old",2053      deviceName: "New Pixel",2054      deviceType: "android",2055      longTermPublicKeyHex: "e".repeat(64),2056      signingPublicKeyHex: "a".repeat(64),2057      pairedAt: 1_700_000_000_000,2058      trustSource: "vouched",2059    });2060    await revokeDeviceById("android-old", "self");20612062    const res = await dispatch({2063      type: "CONFIRM_VOUCHED_DEVICE",2064      payload: { deviceId: "android-relabelled" },2065    });2066    expect(res).toMatchObject({ ok: false, error: "device_revoked" });2067    expect(await findPairedDeviceById("android-relabelled")).toBeNull();2068    expect(await listPendingVouchedDevices()).toHaveLength(0);2069  });20702071  it("MV-7: REJECT_VOUCHED_DEVICE clears the pending entry and never pairs it", async () => {2072    const vault = await import("./vault");2073    await vault.createVault("correct-pass-12345");2074    await seedPendingVouched("android-new");2075    const { findPairedDeviceById } = await import("./paired-devices");2076    const { listPendingVouchedDevices } = await import(2077      "./pending-vouched-devices"2078    );20792080    const res = await dispatch({2081      type: "REJECT_VOUCHED_DEVICE",2082      payload: { deviceId: "android-new" },2083    });2084    expect(res).toMatchObject({ ok: true });20852086    expect(await findPairedDeviceById("android-new")).toBeNull();2087    expect(await listPendingVouchedDevices()).toHaveLength(0);2088  });20892090  // --- unpair: UNPAIR_DEVICE revokes the device and drops it from the registry ---20912092  it("UNPAIR_DEVICE revokes a paired device, drops the row, and lists the revocation", async () => {2093    const vault = await import("./vault");2094    await vault.createVault("correct-pass-12345");2095    // Every real install mints its identity with (or before) its vault, so a2096    // fixture that seeds trust state without one is an install §11.5 refuses.2097    const identity = await import("./device-identity");2098    await identity.getOrCreateDeviceId();2099    const { findPairedDeviceById, isDeviceRevoked, listDeviceRevocations, upsertPairedDevice } =2100      await import("./paired-devices");21012102    await upsertPairedDevice({2103      deviceId: "phone-1",2104      deviceName: "June's Phone",2105      deviceType: "android",2106      longTermPublicKeyHex: "a".repeat(64),2107      signingPublicKeyHex: "b".repeat(64),2108      pairedAt: 1_700_000_000_000,2109      trustSource: "direct",2110    });21112112    const res = await dispatch({2113      type: "UNPAIR_DEVICE",2114      payload: { deviceId: "phone-1" },2115    });2116    expect(res).toMatchObject({ ok: true });21172118    // The row is gone locally — re-listing must not surface it.2119    expect(await findPairedDeviceById("phone-1")).toBeNull();2120    // The revocation is recorded so a future manifest from a peer cannot2121    // resurrect this device under either the same id or the same key (MV-7 + S1).2122    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);2123    const records = await listDeviceRevocations();2124    expect(records).toHaveLength(1);2125    expect(records[0]).toMatchObject({2126      deviceId: "phone-1",2127      longTermPublicKeyHex: "a".repeat(64),2128      revokedByDeviceId: expect.any(String),2129    });2130  });2131  it("UNPAIR_DEVICE resolves its issuer after an already queued adoption rotation", async () => {2132    const vault = await import("./vault");2133    await vault.createVault("correct-pass-12345");2134    const identity = await import("./device-identity");2135    const paired = await import("./paired-devices");2136    const oldId = await identity.getOrCreateDeviceId();2137    const rotation = paired.rotatePairedDeviceIdentity(() => identity.getLocalPairingIdentity({ existingOnly: true }), identity.rotateDeviceId);2138    const removal = dispatch({ type: "UNPAIR_DEVICE", payload: { deviceId: "phone-1" } });2139    await rotation;2140    expect(await removal).toMatchObject({ ok: true });2141    const newId = await identity.getExistingDeviceId();2142    expect(newId).not.toBe(oldId);2143    expect(await paired.listDeviceRevocations()).toMatchObject([{ deviceId: "phone-1", revokedByDeviceId: newId }]);2144  });21452146  it("UNPAIR_DEVICE still evicts a peer when the local identity needs migration", async () => {2147    const vault = await import("./vault");2148    await vault.createVault("correct-pass-12345");2149    const identity = await import("./device-identity");2150    await identity.getOrCreateDeviceId();2151    delete storage.peach_local_identity_v4;2152    delete sessionStorage.peach_local_identity_session;2153    const { findPairedDeviceById, isDeviceRevoked, upsertPairedDevice } = await import("./paired-devices");2154    await upsertPairedDevice({2155      deviceId: "phone-1",2156      deviceName: "June's Phone",2157      deviceType: "android",2158      longTermPublicKeyHex: "a".repeat(64),2159      signingPublicKeyHex: "b".repeat(64),2160      pairedAt: 1_700_000_000_000,2161      trustSource: "direct",2162    });21632164    const response = await dispatch({ type: "UNPAIR_DEVICE", payload: { deviceId: "phone-1" } });21652166    expect(response).toMatchObject({ ok: true });2167    expect(await findPairedDeviceById("phone-1")).toBeNull();2168    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);2169  });21702171  it("UNPAIR_DEVICE on an unknown id is a no-op (ok) and writes no revocation", async () => {2172    const vault = await import("./vault");2173    await vault.createVault("correct-pass-12345");2174    const { listDeviceRevocations } = await import("./paired-devices");21752176    const res = await dispatch({2177      type: "UNPAIR_DEVICE",2178      payload: { deviceId: "never-paired" },2179    });2180    expect(res).toMatchObject({ ok: true });2181    // A revocation with the all-zero key sentinel is still written — the2182    // contract is that the user-intent is recorded even when the registry had2183    // no row. This is what blocks a peer from later vouched-adopting the same2184    // fresh id back in.2185    const records = await listDeviceRevocations();2186    expect(records).toHaveLength(1);2187    expect(records[0]).toMatchObject({2188      deviceId: "never-paired",2189      longTermPublicKeyHex: "0".repeat(64),2190    });2191  });21922193  it("UNPAIR_DEVICE refuses an empty payload with invalid_payload", async () => {2194    const res = await dispatch({2195      type: "UNPAIR_DEVICE",2196      payload: { deviceId: "" },2197    });2198    expect(res).toMatchObject({ ok: false, error: "invalid_payload" });2199  });2200  it("SECURE_RESET reports archive review without clearing trust or a separate RESET_REQUIRED write", async () => {2201    const vault = await import("./vault");2202    await vault.createVault("correct-pass-12345");2203    const archive = { schemaVersion: 1, generation: 1, pairedDevices: ["incomplete"] };2204    storage.peach_sync_archive_g1_v1 = archive;2205    storage.peach_sync_generation_v1 = JSON.stringify({ schemaVersion: 1, active: {2206      schemaVersion: 1, generation: 1, state: "LEGACY_ACTIVE", createdAt: 100,2207    } });2208    const set = vi.mocked(chrome.storage.local.set);2209    set.mockClear();2210    const response = await dispatch({ type: "SECURE_RESET", payload: { password: "correct-pass-12345" } });2211    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." });2212    expect(storage.peach_sync_archive_g1_v1).toEqual(archive);2213    const states = set.mock.calls.flatMap(([values]) => {2214      const raw = (values as StorageShape).peach_sync_generation_v1;2215      return typeof raw === "string" ? [JSON.parse(raw).active.state] : [];2216    });2217    expect(states).toEqual(["RESET_CONFIRMED"]);2218  });2219  it("SECURE_RESET archives legacy trust, rotates identity, and reaches the new Sync anchor", async () => {2220    const vault = await import("./vault");2221    await vault.createVault("correct-pass-12345");2222    const identity = await import("./device-identity");2223    const previousDeviceId = await identity.getOrCreateDeviceId();2224    const { upsertPairedDevice } = await import("./paired-devices");2225    await upsertPairedDevice({2226      deviceId: "phone-1",2227      deviceName: "June's Phone",2228      deviceType: "android",2229      longTermPublicKeyHex: "a".repeat(64),2230      signingPublicKeyHex: "b".repeat(64),2231      pairedAt: 1_700_000_000_000,2232      trustSource: "direct",2233    });22342235    const response = await dispatch({2236      type: "SECURE_RESET",2237      payload: { password: "correct-pass-12345" },2238    });22392240    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });2241    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);2242  });2243  it("SECURE_RESET unlocks a locked real vault before rotating identity", async () => {2244    const vault = await import("./vault");2245    await vault.createVault("correct-pass-12345");2246    const identity = await import("./device-identity");2247    const previousDeviceId = await identity.getOrCreateDeviceId();2248    const { upsertPairedDevice } = await import("./paired-devices");2249    await upsertPairedDevice({2250      deviceId: "phone-1",2251      deviceName: "June's Phone",2252      deviceType: "android",2253      longTermPublicKeyHex: "a".repeat(64),2254      signingPublicKeyHex: "b".repeat(64),2255      pairedAt: 1_700_000_000_000,2256      trustSource: "direct",2257    });2258    await vault.lock();2259    expect(vault.isUnlocked()).toBe(false);22602261    const response = await dispatch({2262      type: "SECURE_RESET",2263      payload: { password: "correct-pass-12345" },2264    });22652266    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });2267    expect(vault.isUnlocked()).toBe(true);2268    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);2269  });2270  it("SECURE_RESET completes after fresh unlock when the locked spool hits identity migration", async () => {2271    const vault = await import("./vault");2272    const syncAdapter = await import("./sync-vault-adapter");2273    vault.setLockedSyncHooks({2274      refresh: syncAdapter.refreshLockedSyncSpool,2275      afterUnlock: syncAdapter.drainAndRefreshLockedSyncSpool,2276    });2277    await vault.createVault("correct-pass-12345");2278    const identity = await import("./device-identity");2279    const previousDeviceId = await identity.getOrCreateDeviceId();2280    const { upsertPairedDevice } = await import("./paired-devices");2281    await upsertPairedDevice({2282      deviceId: "phone-1",2283      deviceName: "June's Phone",2284      deviceType: "android",2285      longTermPublicKeyHex: "a".repeat(64),2286      signingPublicKeyHex: "b".repeat(64),2287      pairedAt: 1_700_000_000_000,2288      trustSource: "direct",2289    });2290    await vault.addEntry({ type: "login", title: "spooled", password: "secret" });2291    await syncAdapter.refreshLockedSyncSpool();2292    await vault.lock();2293    const { createLockedSyncVaultAdapter } = await import("./locked-sync-spool");2294    const lockedAdapter = await createLockedSyncVaultAdapter();2295    expect(lockedAdapter).not.toBeNull();2296    await lockedAdapter!.applyEntries({ remote: "AA==" }, { remote: Date.now() + 1 });2297    delete storage.peach_local_identity_v4;2298    delete sessionStorage.peach_local_identity_session;2299    const sessionSet = chrome.storage.session.set as unknown as ReturnType<typeof vi.fn>;2300    sessionSet.mockImplementation(async (next: Record<string, unknown>) => {2301      if (Object.hasOwn(next, "peach_local_identity_session")) {2302        throw new Error("QUOTA_BYTES");2303      }2304      Object.assign(sessionStorage, next);2305    });23062307    const unlocked = await dispatch({2308      type: "UNLOCK",2309      payload: { password: "correct-pass-12345" },2310    });2311    const pairSecrets = await import("./pair-secrets");2312    const root = Uint8Array.from((vault.getRootKeyHex() ?? "").match(/../g)!, (part) => Number.parseInt(part, 16));2313    await pairSecrets.setPairSecret("phone-1", "c".repeat(64), root);2314    root.fill(0);2315    expect(storage.peach_pair_secrets_v1).toBeDefined();2316    expect(sessionStorage.peach_pair_secrets_session).toBeDefined();2317    expect(unlocked).toMatchObject({ ok: true });23182319    const response = await dispatch({2320      type: "SECURE_RESET",2321      payload: { password: "correct-pass-12345" },2322    });23232324    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });2325    expect(storage.peach_local_identity_v4).toBeDefined();2326    expect(storage.peach_paired_devices_v3).toBeUndefined();2327    expect(storage.peach_pair_secrets_v1).toBeUndefined();2328    expect(sessionStorage.peach_pair_secrets_session).toBeUndefined();2329    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);2330  });2331  // The old "fresh direct re-pair clears the old revocation" test dispatched2332  // COMPLETE_PAIRING, a handler deleted on 2026-08-04 (no legitimate senders;2333  // adoption runs in-background via relay-adoption-bg.ts). The live2334  // revocation-overlap repair is pinned in paired-devices.test.ts2335  // (repairPairedRevocationOverlaps, runs at service-worker boot).2336  it("F1: privileged handlers reject content-script senders but keep extension-page senders (Codex Security 2026-08-04)", async () => {2337    const vault = await import("./vault");2338    await vault.createVault("correct-pass-12345");2339    const contentScriptSender = {2340      id: "peach-extension",2341      url: "https://evil.example/page",2342    };2343    const extensionPageSender = {2344      id: "peach-extension",2345      url: "chrome-extension://peach-extension/popup.html",2346    };2347    const completion = { requestId: 1, rpId: "evil.example" };23482349    // Content-script senders must never reach the gated passkey-store handler.2350    await expect(2351      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, contentScriptSender)2352    ).resolves.toMatchObject({ ok: false, error: "invalid_sender" });23532354    // Extension-page senders still reach it — refused by the pending-ceremony2355    // binding, not by the sender gate.2356    await expect(2357      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2358    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });2359  });23602361  it("F2: COMPLETE_FIREFOX_PASSKEY_CREATE must match the pending ceremony (Codex Security 2026-08-04)", async () => {2362    const vault = await import("./vault");2363    await vault.createVault("correct-pass-12345");2364    const extensionPageSender = {2365      id: "peach-extension",2366      url: "chrome-extension://peach-extension/popup.html",2367    };2368    const completion = {2369      requestId: 123,2370      rpId: "example.com",2371      rpName: "Example",2372      userName: "june",2373      userHandle: "BBBB",2374      credentialId: "cred-1",2375      publicKeyCose: "c3BraQ",2376      algorithm: -7 as const,2377    };23782379    // No pending ceremony at all -> refuse.2380    await expect(2381      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2382    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });23832384    // Seed a background-minted pending ceremony.2385    sessionStorage.passkey_pending_firefox = {2386      requestId: 123,2387      type: "create",2388      rpId: "example.com",2389      rpName: "Example",2390      userName: "june",2391      browser: "firefox",2392      challenge: "AAAA",2393      userHandle: "BBBB",2394    };23952396    // Mismatched userHandle (attacker-forged completion) -> refuse.2397    await expect(2398      dispatch(2399        { type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: { ...completion, userHandle: "CCCC" } },2400        extensionPageSender2401      )2402    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });24032404    // Matching completion -> stored.2405    await expect(2406      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2407    ).resolves.toMatchObject({ ok: true });2408    const entries = await dispatch({ type: "GET_ENTRIES" });2409    expect(entries).toMatchObject({ ok: true });2410    const stored = (entries as { data: Array<{ passkey?: { credentialId?: string } }> }).data;2411    expect(stored.some((entry) => entry.passkey?.credentialId === "cred-1")).toBe(true);2412  });24132414  it("F2: INITIATE_FIREFOX_PASSKEY_CREATE rejects an rpId the caller origin does not own (Codex Security 2026-08-04)", async () => {2415    await expect(2416      dispatch(2417        {2418          type: "INITIATE_FIREFOX_PASSKEY_CREATE",2419          payload: { rpId: "bank.example", rpName: "Bank", userName: "june" },2420        },2421        { id: "peach-extension", url: "https://evil.example/page" }2422      )2423    ).resolves.toMatchObject({ ok: false, error: "rpid_origin_mismatch" });2424  });24252426  it("after UNPAIR_DEVICE, a fresh id carrying the same revoked key is also refused (S1)", async () => {2427    // The cross-manifest refusal is exercised end-to-end in sync-vault-adapter.test.ts;2428    // here we just pin the storage-level invariant the UNPAIR_DEVICE call2429    // establishes, since the rest of the testbed's revoke coverage rides on2430    // this state.2431    const vault = await import("./vault");2432    await vault.createVault("correct-pass-12345");2433    const { isDeviceRevoked, revokeDeviceById, upsertPairedDevice } = await import(2434      "./paired-devices"2435    );24362437    await upsertPairedDevice({2438      deviceId: "phone-1",2439      deviceName: "June's Phone",2440      deviceType: "android",2441      longTermPublicKeyHex: "a".repeat(64),2442      signingPublicKeyHex: "b".repeat(64),2443      pairedAt: 1_700_000_000_000,2444      trustSource: "direct",2445    });24462447    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(false);2448    await revokeDeviceById("phone-1", "self");2449    // The key check is what blocks a re-vouch under a fresh id.2450    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);2451    expect(await isDeviceRevoked("fresh-id", "a".repeat(64))).toBe(true);2452  });24532454  // --- LV-4: GET_RECOVERY_WORDS requires a fresh password proof ---24552456  it("LV-4: GET_RECOVERY_WORDS without a password returns password_required", async () => {2457    const vault = await import("./vault");2458    await vault.createVault("correct-pass-12345");24592460    const res = await dispatch({ type: "GET_RECOVERY_WORDS", payload: {} });2461    expect(res).toMatchObject({ ok: false, error: "password_required" });2462  });24632464  it("LV-4: GET_RECOVERY_WORDS with a wrong password returns wrong_password and no words", async () => {2465    const vault = await import("./vault");2466    await vault.createVault("correct-pass-12345");24672468    const res = await dispatch({2469      type: "GET_RECOVERY_WORDS",2470      payload: { password: "not-the-password" },2471    });2472    expect(res).toMatchObject({ ok: false, error: "wrong_password" });2473    expect(res.data).toBeUndefined();2474  });24752476  it("LV-4: GET_RECOVERY_WORDS with the correct password returns 12 words", async () => {2477    const vault = await import("./vault");2478    await vault.createVault("correct-pass-12345");24792480    const res = await dispatch({2481      type: "GET_RECOVERY_WORDS",2482      payload: { password: "correct-pass-12345" },2483    });2484    expect(res.ok).toBe(true);2485    expect((res.data as string[]).length).toBe(12);2486  });24872488  it("PB-26-311: cleartext export requires a fresh master-password proof", async () => {2489    const vault = await import("./vault");2490    await vault.createVault("correct-pass-12345");24912492    await expect(2493      dispatch({ type: "EXPORT_ENTRIES" as never, payload: {} }),2494    ).resolves.toMatchObject({ ok: false, error: "password_required" });2495    await expect(2496      dispatch({2497        type: "EXPORT_ENTRIES" as never,2498        payload: { password: "not-the-password" },2499      }),2500    ).resolves.toMatchObject({ ok: false, error: "wrong_password" });2501    await expect(2502      dispatch({2503        type: "EXPORT_ENTRIES" as never,2504        payload: { password: "correct-pass-12345" },2505      }),2506    ).resolves.toMatchObject({ ok: true, data: [] });2507  });25082509  it("GET_PIN_STATUS reports only a session-available PIN wrapper", async () => {2510    const vault = await import("./vault");2511    const password = "correct-pass-12345";2512    const popupSender = {2513      id: "peach-extension",2514      url: "chrome-extension://peach-extension/src/popup/index.html",2515    } as chrome.runtime.MessageSender;25162517    await vault.createVault(password);2518    await vault.setupPinUnlock(password, "1234");2519    await vault.lock();25202521    await expect(dispatch({ type: "GET_PIN_STATUS" }, popupSender)).resolves.toMatchObject({2522      ok: true,2523      data: { configured: true, available: true, attemptsRemaining: 3 },2524    });2525  });2526});