messages.test.ts

107.2 KB · raw

1import { beforeEach, describe, expect, it, vi } from "vitest";23import { base64urlEncode, generatePasskeyKeypair } from "./passkey-crypto";4import type { Message, MessageResponse } from "../shared/types";56type StorageShape = Record<string, unknown>;78function deferred(): { promise: Promise<void>; resolve: () => void } {9  let resolve!: () => void;10  const promise = new Promise<void>((done) => {11    resolve = done;12  });13  return { promise, resolve };14}15type MessageListener = (16  msg: unknown,17  sender: chrome.runtime.MessageSender,18  sendResponse: (response: MessageResponse) => void19) => boolean;2021/**22 * Chrome re-encodes everything it stores: `undefined` is dropped and object23 * keys come back in its own order, so a value read back is deep-equal to what24 * was set but never the same object nor the same JSON text. Storing the value25 * by reference would let an order-sensitive write-verify pass here and fail on26 * a real device — exactly how the secure-reset archive check shipped broken.27 */28function asChromeStores(value: unknown): unknown {29  if (Array.isArray(value)) return value.map(asChromeStores);30  if (value && typeof value === "object") {31    const source = value as StorageShape;32    const clone: StorageShape = {};33    for (const key of Object.keys(source).sort()) clone[key] = asChromeStores(source[key]);34    return clone;35  }36  return value;37}3839function storeWrite(target: StorageShape, next: StorageShape): void {40  for (const [key, value] of Object.entries(next)) {41    if (value === undefined) continue;42    target[key] = asChromeStores(value);43  }44}4546describe("background messages", () => {47  let storage: StorageShape;48  let sessionStorage: StorageShape;49  let listener: MessageListener;50  let fetchMock: ReturnType<typeof vi.fn>;5152  beforeEach(async () => {53    vi.resetModules();54    vi.useRealTimers();55    storage = {56      peach_settings: { breachMonitoring: false },57    };58    sessionStorage = {};59    fetchMock = vi.fn(async () => ({60      ok: true,61      status: 200,62      text: async () => "",63    }));64    vi.stubGlobal("fetch", fetchMock);65    vi.stubGlobal("__PEACH_E2E_PASSKEYS__", false);6667    const tabs = [{ id: 1 }];68    const chromeMock = {69      runtime: {70        id: "peach-extension",71        getURL: (p: string) => `chrome-extension://peach-extension/${p}`,72        onMessage: {73          addListener: vi.fn((fn: MessageListener) => {74            listener = fn;75          }),76        },77        sendMessage: vi.fn(async () => ({ ok: true })),78      },79      tabs: {80        query: vi.fn((_query: unknown, callback?: (tabs: Array<{ id?: number }>) => void) => {81          if (typeof callback === "function") {82            callback(tabs);83            return;84          }85          return Promise.resolve(tabs);86        }),87        sendMessage: vi.fn(async () => ({ ok: true })),88      },89      storage: {90        local: {91          get: vi.fn(async (key?: string | string[]) => {92            if (!key) return storage;93            if (typeof key === "string") {94              return { [key]: storage[key] };95            }9697            return key.reduce<Record<string, unknown>>((result, entry) => {98              result[entry] = storage[entry];99              return result;100            }, {});101          }),102          set: vi.fn(async (next: Record<string, unknown>) => {103            storeWrite(storage, next);104          }),105          remove: vi.fn(async (keys: string | string[]) => {106            const list = Array.isArray(keys) ? keys : [keys];107            for (const key of list) {108              delete storage[key];109            }110          }),111          clear: vi.fn(async () => {112            for (const key of Object.keys(storage)) delete storage[key];113          }),114        },115        session: {116          get: vi.fn(async (key?: string | string[]) => {117            if (!key) return sessionStorage;118            if (typeof key === "string") {119              return { [key]: sessionStorage[key] };120            }121            return key.reduce<Record<string, unknown>>((result, entry) => {122              result[entry] = sessionStorage[entry];123              return result;124            }, {});125          }),126          set: vi.fn(async (next: Record<string, unknown>) => {127            storeWrite(sessionStorage, next);128          }),129          remove: vi.fn(async (keys: string | string[]) => {130            const list = Array.isArray(keys) ? keys : [keys];131            for (const key of list) {132              delete sessionStorage[key];133            }134          }),135          clear: vi.fn(async () => {136            for (const key of Object.keys(sessionStorage)) delete sessionStorage[key];137          }),138        },139        sync: {140          get: vi.fn(async (_key?: string | string[]) => ({})),141          set: vi.fn(async (_values: Record<string, unknown>) => undefined),142          remove: vi.fn(async (_keys: string | string[]) => undefined),143          clear: vi.fn(async () => undefined),144        },145      },146      alarms: {147        clear: vi.fn(),148        create: vi.fn(),149        onAlarm: { addListener: vi.fn() },150      },151      idle: {152        setDetectionInterval: vi.fn(),153        onStateChanged: { addListener: vi.fn() },154      },155      scripting: {156        executeScript: vi.fn(async () => []),157      },158    } as unknown as typeof chrome;159160    (globalThis as { chrome?: typeof chrome }).chrome = chromeMock;161162    const messages = await import("./messages");163    messages.setupMessageHandler();164    const vault = await import("./vault");165    await vault.ensureSettingsLoaded();166  });167168  async function dispatch(169    message: Message,170    sender: chrome.runtime.MessageSender = {171      id: "peach-extension",172      url: "chrome-extension://peach-extension/popup.html",173    }174  ): Promise<MessageResponse> {175    return await new Promise<MessageResponse>((resolve) => {176      const keepChannelOpen = listener(message, sender, (response) => resolve(response));177      expect(keepChannelOpen).toBe(true);178    });179  }180181  it("PB-26-303: page GET_SETTINGS returns only theme, accent, and its own summon record", async () => {182    storage.peach_settings = {183      theme: "dark",184      accentColor: "peach",185      autoLockMinutes: 5,186      pinEnabled: true,187      manualSummonDomains: {188        "example.com": { firstSummonedAt: 1, summonCount: 2, lastSummonedAt: 3 },189        "other.example": { firstSummonedAt: 4, summonCount: 5, lastSummonedAt: 6 },190      },191    };192    const response = await dispatch(193      { type: "GET_SETTINGS" },194      {195        id: "peach-extension",196        url: "https://login.example.com/form",197        tab: { id: 1 },198        frameId: 0,199      } as chrome.runtime.MessageSender,200    );201202    expect(response).toEqual({203      ok: true,204      data: {205        theme: "dark",206        accentColor: "peach",207        manualSummonDomains: {208          "example.com": { firstSummonedAt: 1, summonCount: 2, lastSummonedAt: 3 },209        },210      },211    });212    await expect(dispatch({ type: "GET_SETTINGS" })).resolves.toMatchObject({213      ok: true,214      data: {215        autoLockMinutes: 5,216        pinEnabled: true,217        manualSummonDomains: {218          "example.com": expect.anything(),219          "other.example": expect.anything(),220        },221      },222    });223  });224225  it("RECORD_MANUAL_SUMMON binds and bounds the sender domain", async () => {226    const sender = {227      id: "peach-extension",228      url: "https://login.example.com/form",229      origin: "https://login.example.com",230      tab: { id: 1 },231      frameId: 0,232    } as chrome.runtime.MessageSender;233234    await expect(dispatch({235      type: "RECORD_MANUAL_SUMMON",236      payload: { domain: "evil.example" },237    }, sender)).resolves.toEqual({ ok: false, error: "invalid_domain" });238    await expect(dispatch({239      type: "RECORD_MANUAL_SUMMON",240      payload: { domain: "example.com" },241    }, sender)).resolves.toEqual({ ok: true });242    await expect(dispatch({243      type: "RECORD_MANUAL_SUMMON",244      payload: { domain: "a".repeat(254) },245    }, { ...sender, origin: "https://a.com", url: "https://a.com/form" })).resolves.toEqual({246      ok: false,247      error: "invalid_domain",248    });249  });250251  it("GET_ENTRIES when unlocked returns the entry array", async () => {252    const vault = await import("./vault");253    await vault.createVault("correct-pass-12345");254    await vault.addEntry({255      title: "GitHub",256      username: "june",257      password: "secret123",258      url: "https://github.com",259    });260261    await expect(dispatch({ type: "GET_ENTRIES" })).resolves.toMatchObject({262      ok: true,263      data: [264        expect.objectContaining({265          title: "GitHub",266          username: "june",267        }),268      ],269    });270  });271272  it("GET_ENTRIES when locked returns a vault locked error", async () => {273    const vault = await import("./vault");274    await vault.createVault("correct-pass-12345");275    vault.lock();276277    await expect(dispatch({ type: "GET_ENTRIES" })).resolves.toMatchObject({278      ok: false,279      error: "vault_locked",280    });281  });282283  it("ADD_ENTRY with a valid payload returns the created entry", async () => {284    const vault = await import("./vault");285    await vault.createVault("correct-pass-12345");286287    const response = await dispatch({288      type: "ADD_ENTRY",289      payload: {290        title: "GitHub",291        username: "june",292        password: "secret123",293        url: "https://github.com",294      },295    });296297    expect(response).toMatchObject({298      ok: true,299      data: expect.objectContaining({300        id: expect.any(String),301        title: "GitHub",302      }),303    });304    expect(vault.getEntries()).toHaveLength(1);305  });306307  it("ADD_ENTRY when locked returns a vault locked error", async () => {308    const vault = await import("./vault");309    await vault.createVault("correct-pass-12345");310    vault.lock();311312    await expect(313      dispatch({314        type: "ADD_ENTRY",315        payload: {316          title: "GitHub",317          username: "june",318          password: "secret123",319          url: "https://github.com",320        },321      })322    ).resolves.toMatchObject({ ok: false, error: "vault_locked" });323  });324325  it("ADD_ENTRY with no password succeeds for email-only accounts", async () => {326    const vault = await import("./vault");327    await vault.createVault("correct-pass-12345");328329    await expect(330      dispatch({331        type: "ADD_ENTRY",332        payload: {333          title: "GitHub",334          username: "june",335          password: "",336          url: "https://github.com",337        },338      })339    ).resolves.toMatchObject({ ok: true });340  });341342  it("UPDATE_ENTRY updates an existing entry and returns ok", async () => {343    const vault = await import("./vault");344    await vault.createVault("correct-pass-12345");345    const entry = await vault.addEntry({346      title: "GitHub",347      username: "june",348      password: "secret123",349      url: "https://github.com",350    });351352    await expect(353      dispatch({354        type: "UPDATE_ENTRY",355        payload: { id: entry.id, patch: { password: "new-secret" } },356      })357    ).resolves.toMatchObject({ ok: true });358359    expect(vault.getEntryById(entry.id)?.password).toBe("new-secret");360  });361362  it("UPDATE_ENTRY with an empty password clears it for email-only accounts", async () => {363    const vault = await import("./vault");364    await vault.createVault("correct-pass-12345");365    const entry = await vault.addEntry({366      title: "GitHub",367      username: "june",368      password: "secret123",369      url: "https://github.com",370    });371372    await expect(373      dispatch({374        type: "UPDATE_ENTRY",375        payload: { id: entry.id, patch: { password: "" } },376      })377    ).resolves.toMatchObject({ ok: true });378379    expect(vault.getEntryById(entry.id)?.password).toBeUndefined();380  });381382  it("DELETE_ENTRY soft-deletes the target entry", async () => {383    const vault = await import("./vault");384    await vault.createVault("correct-pass-12345");385    const entry = await vault.addEntry({386      title: "GitHub",387      username: "june",388      password: "secret123",389      url: "https://github.com",390    });391392    await expect(393      dispatch({394        type: "DELETE_ENTRY",395        payload: { id: entry.id },396      })397    ).resolves.toMatchObject({ ok: true });398399    expect(vault.getEntries()).toEqual([]);400    expect(vault.getDeletedEntries()).toHaveLength(1);401  });402403  it("DELETE_ENTRY of a missing id returns an error", async () => {404    const vault = await import("./vault");405    await vault.createVault("correct-pass-12345");406407    await expect(408      dispatch({409        type: "DELETE_ENTRY",410        payload: { id: "missing" },411      })412    ).resolves.toMatchObject({ ok: false, error: "entry_not_found" });413  });414415  it("GET_ENTRY_FOR_FILL returns a safe login entry without privateKeyJwk", async () => {416    const vault = await import("./vault");417    await vault.createVault("correct-pass-12345");418    const entry = await vault.addEntry({419      title: "GitHub",420      username: "june",421      password: "secret123",422      url: "https://github.com",423    });424425    const response = await dispatch(426      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },427      { id: "peach-extension", url: "https://github.com/login" },428    );429430    expect(response).toMatchObject({431      ok: true,432      data: expect.objectContaining({433        id: entry.id,434        username: "june",435        password: "secret123",436      }),437    });438    expect((response.data as Record<string, unknown>).privateKeyJwk).toBeUndefined();439  });440441  it("GET_ENTRY_FOR_FILL when locked returns an error", async () => {442    const vault = await import("./vault");443    await vault.createVault("correct-pass-12345");444    vault.lock();445446    await expect(447      dispatch({448        type: "GET_ENTRY_FOR_FILL",449        payload: { id: "missing" },450      })451    ).resolves.toMatchObject({ ok: false, error: "vault_locked" });452  });453454  it("GET_ENTRY_FOR_FILL rejects passkey-only entries", async () => {455    const vault = await import("./vault");456    await vault.createVault("correct-pass-12345");457    const generated = await generatePasskeyKeypair(-7);458    const entry = await vault.addEntry({459      type: "login",460      title: "WebAuthn.io",461      passkey: {462        rpId: "webauthn.io",463        rpName: "WebAuthn.io",464        credentialId: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),465        publicKeyCose: base64urlEncode(generated.publicKeyCose),466        privateKeyJwk: generated.privateKeyJwk,467        userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),468        userName: "june",469        userDisplayName: "June",470        algorithm: -7,471        signCount: 0,472        aaguid: "AAAAAAAAAAAAAAAAAAAAAA",473        backupEligible: true,474        backupState: false,475        createdAt: Date.now(),476      },477    });478479    await expect(480      dispatch({481        type: "GET_ENTRY_FOR_FILL",482        payload: { id: entry.id },483      })484    ).resolves.toMatchObject({ ok: false, error: "passkey_not_fillable" });485  });486487  it("AUTOFILL_QUERY returns matched domain metadata without secrets", async () => {488    const vault = await import("./vault");489    await vault.createVault("correct-pass-12345");490    await vault.addEntry({491      title: "GitHub",492      username: "june",493      password: "secret123",494      url: "https://github.com",495      totp: "JBSWY3DPEHPK3PXP",496    });497498    const response = await dispatch({499      type: "AUTOFILL_QUERY",500      payload: { domain: "github.com" },501    });502503    expect(response).toMatchObject({504      ok: true,505      data: [506        {507          id: expect.any(String),508          title: "GitHub",509          username: "june",510          url: "https://github.com",511          hasTotp: true,512        },513      ],514    });515    expect((response.data as Array<Record<string, unknown>>)[0].password).toBeUndefined();516    expect((response.data as Array<Record<string, unknown>>)[0].totp).toBeUndefined();517  });518519  it("AUTOFILL_QUERY includeAll returns search-ready summaries for non-note, non-passkey entries", async () => {520    const vault = await import("./vault");521    await vault.createVault("correct-pass-12345");522    await vault.addEntry({523      title: "GitHub",524      username: "june",525      password: "secret123",526      url: "https://github.com",527    });528    await vault.addEntry({529      type: "note",530      title: "Secure note",531      notes: "hello",532    });533534    const response = await dispatch({535      type: "AUTOFILL_QUERY",536      payload: { domain: "github.com", includeAll: true },537    });538539    expect(response).toMatchObject({540      ok: true,541      data: [542        {543          id: expect.any(String),544          title: "GitHub",545          username: "june",546          url: "https://github.com",547          hasPasskey: false,548        },549      ],550    });551    const data = response.data as Array<Record<string, unknown>>;552    expect(data).toHaveLength(1);553    // No secrets cross the boundary.554    expect(data[0]).not.toHaveProperty("password");555    expect(data[0]).not.toHaveProperty("totp");556  });557558  it("AUTOFILL_QUERY kind=totp returns only matching entries with 2FA summaries", async () => {559    const vault = await import("./vault");560    await vault.createVault("correct-pass-12345");561    await vault.addEntry({562      title: "GitHub",563      username: "june",564      password: "secret123",565      url: "https://github.com",566      totp: "JBSWY3DPEHPK3PXP",567    });568    await vault.addEntry({569      title: "No 2FA",570      username: "person",571      password: "secret123",572      url: "https://github.com",573    });574575    const response = await dispatch({576      type: "AUTOFILL_QUERY",577      payload: { domain: "github.com", kind: "totp" },578    });579580    expect(response).toMatchObject({581      ok: true,582      data: [583        {584          id: expect.any(String),585          title: "GitHub",586          username: "june",587          url: "https://github.com",588          hasTotp: true,589        },590      ],591    });592    expect((response.data as Array<Record<string, unknown>>)[0].totp).toBeUndefined();593    expect(response.data).toHaveLength(1);594  });595596  it("RESTORE_ENTRIES replace mode restores the provided entries", async () => {597    const vault = await import("./vault");598    await vault.createVault("correct-pass-12345");599    await vault.addEntry({ title: "A", username: "", password: "one", url: "" });600601    const response = await dispatch({602      type: "RESTORE_ENTRIES",603      payload: {604        mode: "replace",605        entries: [606          {607            id: "restored-1",608            type: "login",609            title: "B",610            username: "june",611            password: "two",612            url: "https://b.test",613            createdAt: 1,614            modifiedAt: 1,615          },616        ],617      },618    });619620    expect(response).toMatchObject({ ok: true, data: { added: 1, updated: 0, skipped: 0 } });621    expect(vault.getEntries().map((entry) => entry.id)).toEqual(["restored-1"]);622  });623624  it("RESTORE_ENTRIES replace mode with an empty array returns an error", async () => {625    const vault = await import("./vault");626    await vault.createVault("correct-pass-12345");627628    await expect(629      dispatch({630        type: "RESTORE_ENTRIES",631        payload: { mode: "replace", entries: [] },632      })633    ).resolves.toMatchObject({ ok: false, error: "refuse to replace with empty entry set" });634  });635636  it("CHANGE_PASSWORD responds true for the happy path and false for a wrong current password", async () => {637    const vault = await import("./vault");638    await vault.createVault("correct-pass-12345");639640    await expect(641      dispatch({642        type: "CHANGE_PASSWORD",643        payload: {644          currentPassword: "correct-pass-12345",645          newPassword: "new-pass-67890",646        },647      })648    ).resolves.toMatchObject({ ok: true });649650    vault.lock();651    expect(await vault.unlock("new-pass-67890")).toBe(true);652653    await expect(654      dispatch({655        type: "CHANGE_PASSWORD",656        payload: {657          currentPassword: "wrong-pass",658          newPassword: "another-pass",659        },660      })661    ).resolves.toMatchObject({ ok: false, error: "incorrect_current_password" });662  });663664  it("UPDATE_SETTINGS reschedules auto-lock using the new minutes value", async () => {665    const vault = await import("./vault");666    await vault.createVault("correct-pass-12345");667668    (669      chrome.alarms.create as unknown as ReturnType<typeof vi.fn>670    ).mockClear();671    (672      chrome.idle.setDetectionInterval as unknown as ReturnType<typeof vi.fn>673    ).mockClear();674675    await expect(676      dispatch({677        type: "UPDATE_SETTINGS",678        payload: { autoLockMinutes: 30 },679      })680    ).resolves.toMatchObject({ ok: true });681682    expect(vault.getSettings().autoLockMinutes).toBe(30);683    expect(chrome.idle.setDetectionInterval).toHaveBeenLastCalledWith(1800);684    expect(chrome.alarms.create).toHaveBeenLastCalledWith("autolock", {685      delayInMinutes: 30,686    });687  });688689  it("CHECK_ALL_BREACHES updates matching entries without corrupting the vault", async () => {690    vi.useFakeTimers();691    const vault = await import("./vault");692    await vault.createVault("correct-pass-12345");693    const entry = await vault.addEntry({694      title: "GitHub",695      username: "june",696      password: "secret123",697      url: "https://github.com",698    });699    const breachSpy = vi.spyOn(vault, "checkBreach").mockResolvedValue(7);700701    const responsePromise = dispatch({ type: "CHECK_ALL_BREACHES" });702    await vi.runAllTimersAsync();703    const response = await responsePromise;704705    expect(response).toMatchObject({ ok: true, data: { [entry.id]: 7 } });706    expect(vault.getEntryById(entry.id)?.breach).toBe(7);707    breachSpy.mockRestore();708  });709710  it("rejects passkey approval from a different tab than the ceremony", async () => {711    sessionStorage.passkey_pending_301 = {712      requestId: 301,713      type: "get",714      rpId: "example.com",715      rpName: "Example",716      userName: "[email protected]",717      tabId: 7,718      origin: "https://example.com",719    };720721    await expect(722      dispatch(723        { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 301, approved: true } },724        { id: "peach-extension", tab: { id: 8 }, url: "https://example.com/login" } as chrome.runtime.MessageSender,725      ),726    ).resolves.toMatchObject({ ok: false, error: "invalid_passkey_approval_sender" });727  });728729  it("requires trusted popup approval for embedded passkey requests", async () => {730    sessionStorage.passkey_pending_302 = {731      requestId: 302, type: "get", rpId: "login.example", rpName: "Login",732      userName: "june", origin: "https://login.example", crossOrigin: true,733    };734    for (const origin of ["https://top.example", "https://login.example"]) {735      await expect(dispatch(736        { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 302, approved: true } },737        { id: "peach-extension", tab: { id: 7 }, origin, url: `${origin}/login` } as chrome.runtime.MessageSender,738      )).resolves.toMatchObject({ ok: false, error: "invalid_passkey_approval_sender" });739      expect(sessionStorage.passkey_pending_302).toBeDefined();740    }741    await expect(dispatch({ type: "APPROVE_PASSKEY", payload: { requestId: 302 } })).resolves.toMatchObject({ ok: true });742    expect(sessionStorage.passkey_pending_302).toBeUndefined();743  });744745  it.each([false, true])("rejects content approval without a bound toast (missing pending: %s)", async (missing) => {746    if (!missing) sessionStorage.passkey_pending_303 = {747      requestId: 303, type: "get", rpId: "example.com", rpName: "Example",748      userName: "june", origin: "https://example.com", crossOrigin: false,749    };750    await expect(dispatch(751      { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 303, approved: true } },752      { id: "peach-extension", tab: { id: 7 }, url: "https://example.com/login" } as chrome.runtime.MessageSender,753    )).resolves.toMatchObject({ ok: false, error: "invalid_passkey_approval_sender" });754    if (!missing) expect(sessionStorage.passkey_pending_303).toBeDefined();755  });756757  it.each([true, false])("accepts bound same-origin toast consent: %s", async (approved) => {758    sessionStorage.passkey_pending_304 = {759      requestId: 304, type: "get", rpId: "example.com", rpName: "Example",760      userName: "june", tabId: 7, origin: "https://example.com", crossOrigin: false,761    };762    await expect(dispatch(763      { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 304, approved } },764      { id: "peach-extension", tab: { id: 7 }, url: "https://example.com/login" } as chrome.runtime.MessageSender,765    )).resolves.toMatchObject({ ok: true });766    expect(sessionStorage.passkey_pending_304).toBeUndefined();767  });768769  it("messages from foreign or URL-less senders are rejected", async () => {770    const vault = await import("./vault");771    await vault.createVault("correct-pass-12345");772773    await expect(dispatch({ type: "GET_ENTRIES" }, { id: "other-extension" })).resolves.toMatchObject({774      ok: false,775      error: "invalid_sender",776    });777778    await expect(dispatch({ type: "GET_ENTRIES" }, {})).resolves.toMatchObject({779      ok: false,780      error: "invalid_sender",781    });782  });783784  it("LOCK and UNLOCK messages update vault state correctly", async () => {785    const vault = await import("./vault");786787    await expect(788      dispatch({ type: "CREATE_VAULT", payload: { password: "correct-pass-12345" } })789    ).resolves.toMatchObject({ ok: true });790    expect(vault.isUnlocked()).toBe(true);791792    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });793    expect(vault.isUnlocked()).toBe(false);794795    await expect(796      dispatch({ type: "UNLOCK", payload: { password: "wrong-pass" } })797    ).resolves.toMatchObject({ ok: false });798    expect(vault.isUnlocked()).toBe(false);799800    await expect(801      dispatch({ type: "UNLOCK", payload: { password: "correct-pass-12345" } })802    ).resolves.toMatchObject({ ok: true });803    expect(vault.isUnlocked()).toBe(true);804  });805806  it("does not acknowledge LOCK until session cleanup finishes", async () => {807    await expect(808      dispatch({ type: "CREATE_VAULT", payload: { password: "correct-pass-12345" } })809    ).resolves.toMatchObject({ ok: true });810811    const removalStarted = deferred();812    const releaseRemoval = deferred();813    const remove = chrome.storage.session.remove as unknown as ReturnType<typeof vi.fn>;814    remove.mockImplementation(async (keys: string | string[]) => {815      removalStarted.resolve();816      await releaseRemoval.promise;817      for (const key of Array.isArray(keys) ? keys : [keys]) delete sessionStorage[key];818    });819820    let responded = false;821    const response = dispatch({ type: "LOCK" }).then((result) => {822      responded = true;823      return result;824    });825    await removalStarted.promise;826827    try {828      await Promise.resolve();829      expect(responded).toBe(false);830    } finally {831      releaseRemoval.resolve();832    }833834    await expect(response).resolves.toMatchObject({ ok: true });835  });836837  it("remembers the last successful unlock method", async () => {838    const vault = await import("./vault");839    const password = "correct-pass-12345";840    const popupSender = {841      id: "peach-extension",842      url: "chrome-extension://peach-extension/src/popup/index.html",843    } as chrome.runtime.MessageSender;844845    await vault.createVault(password);846    expect(await vault.setupPinUnlock(password, "1234")).toBe(true);847    vault.lock();848849    await expect(850      dispatch({ type: "UNLOCK_WITH_PIN", payload: { pin: "1234" } }, popupSender),851    ).resolves.toMatchObject({ ok: true });852    expect((await vault.ensureSettingsLoaded()).pinPreferred).toBe(true);853854    vault.lock();855    await expect(856      dispatch({ type: "UNLOCK", payload: { password } }, popupSender),857    ).resolves.toMatchObject({ ok: true });858    expect((await vault.ensureSettingsLoaded()).pinPreferred).toBe(false);859  });860861  describe("credential save comparison", () => {862    const sender = { id: "peach-extension", url: "https://github.com/login", tab: { id: 7 }, frameId: 0 } as chrome.runtime.MessageSender;863    const compare = (username = "june", password = "secret", source = sender) =>864      dispatch({ type: "CHECK_SAVE_CREDENTIAL", payload: { username, password } } as Message, source);865866    it("selects the submitted identity instead of the first domain entry", async () => {867      const vault = await import("./vault");868      await vault.createVault("comparison-password");869      await vault.addEntry({ title: "Other", username: "other", password: "secret", url: "https://github.com" });870      const entry = await vault.addEntry({ title: "June", username: "june", email: "[email protected]", password: "old", url: "https://github.com", notes: "private" });871      expect(await compare(" [email protected] ")).toEqual({ ok: true, data: { status: "changed", id: entry.id } });872      expect(await compare("other")).toEqual({ ok: true, data: { status: "same" } });873      expect(await compare("new")).toEqual({ ok: true, data: { status: "new" } });874    });875876    it("prefers an exact password and refuses ambiguous updates", async () => {877      const vault = await import("./vault");878      await vault.createVault("comparison-password");879      await vault.addEntry({ title: "One", username: "june", password: "one", url: "https://github.com" });880      await vault.addEntry({ title: "Two", username: "june", password: "two", url: "https://github.com" });881      expect(await compare("june", "two")).toEqual({ ok: true, data: { status: "same" } });882      expect(await compare()).toEqual({ ok: true, data: { status: "ambiguous" } });883      expect(fetchMock).not.toHaveBeenCalled();884    });885886    it("recognizes password-only named accounts without selecting them for updates", async () => {887      const vault = await import("./vault");888      await vault.createVault("comparison-password");889      await vault.addEntry({ title: "Named", username: "june", password: "secret", url: "https://github.com" });890      expect(await compare("")).toEqual({ ok: true, data: { status: "same" } });891      expect(await compare("", "different")).toEqual({ ok: true, data: { status: "new" } });892      const entry = await vault.addEntry({ title: "Anonymous", username: "", password: "old", url: "https://github.com" });893      expect(await compare(" ", "different")).toEqual({ ok: true, data: { status: "changed", id: entry.id } });894    });895896    it("excludes foreign, deleted, and non-login entries", async () => {897      const vault = await import("./vault");898      await vault.createVault("comparison-password");899      await vault.addEntry({ title: "Foreign", username: "june", password: "secret", url: "https://other.example" });900      await vault.addEntry({ type: "note", title: "Note", username: "june", password: "secret", url: "https://github.com" });901      const deleted = await vault.addEntry({ title: "Deleted", username: "june", password: "secret", url: "https://github.com" });902      await vault.deleteEntry(deleted.id);903      expect(await compare()).toEqual({ ok: true, data: { status: "new" } });904    });905906    it("rejects malformed payloads, caller domains, nonpage senders, and locked vaults", async () => {907      const vault = await import("./vault");908      await vault.createVault("comparison-password");909      for (const payload of [null, [], {}, { username: 1, password: "secret" }, { username: "june", password: 1 }, { username: "june", password: "secret", domain: "github.com" }]) {910        expect(await dispatch({ type: "CHECK_SAVE_CREDENTIAL", payload } as Message, sender)).toMatchObject({ ok: false });911      }912      expect(await compare("june", "secret", { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" })).toMatchObject({ ok: false });913      expect(await compare("june", "secret", { ...sender, url: "about:blank" })).toMatchObject({ ok: false });914      expect(await compare("june", "secret", { id: "peach-extension", url: "https://github.com/login" })).toMatchObject({ ok: false });915      await vault.lock();916      expect(await compare()).toMatchObject({ ok: false, error: "vault_locked" });917    });918919    it("alerts every exact canary match as submitted without returning entry data", async () => {920      await addCanary("First"); await addCanary("Second");921      expect(await compare("wrong")).toEqual({ ok: true, data: { status: "new" } });922      expect(await compare("june", "wrong")).toEqual({ ok: true, data: { status: "ambiguous" } });923      expect(fetchMock).not.toHaveBeenCalled();924      expect(await compare()).toEqual({ ok: true, data: { status: "same" } });925      expect(fetchMock).toHaveBeenCalledTimes(2);926      for (const call of fetchMock.mock.calls) expect(JSON.parse(call[1].body as string).trigger).toBe("submitted");927    });928929    it("alerts every named canary for an exact password-only submission", async () => {930      await addCanary("First"); const second = await addCanary("Second");931      const vault = await import("./vault");932      await vault.updateEntry(second.id, { username: "other" });933      expect(await compare("", "different")).toEqual({ ok: true, data: { status: "new" } });934      expect(fetchMock).not.toHaveBeenCalled();935      expect(await compare("")).toEqual({ ok: true, data: { status: "same" } });936      expect(fetchMock).toHaveBeenCalledTimes(2);937      for (const call of fetchMock.mock.calls) expect(JSON.parse(call[1].body as string).trigger).toBe("submitted");938    });939940    it("rechecks non-canary exact matches after a sibling canary await", async () => {941      await addCanary(); const vault = await import("./vault");942      const sibling = await vault.addEntry({ title: "Ordinary", username: "june", password: "secret", url: "https://github.com" });943      const held = deferred(); const entered = deferred();944      const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;945      vi.mocked(chrome.storage.local.get).mockImplementation(async key => {946        if (typeof key === "string" && key.startsWith("canary-last-fetch:")) { entered.resolve(); await held.promise; }947        return original(key);948      });949      const pending = compare(); await entered.promise;950      await vault.updateEntry(sibling.id, { password: "changed" });951      held.resolve();952      expect(await pending).toEqual({ ok: false, error: "entry_changed" });953      expect(fetchMock).toHaveBeenCalledTimes(1);954    });955956    it.each(["lock", "domain", "identity", "password"])("refuses stale comparison after an awaited canary %s change", async change => {957      const entry = await addCanary(); const vault = await import("./vault");958      const held = deferred(); const entered = deferred();959      const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;960      vi.mocked(chrome.storage.local.get).mockImplementation(async key => {961        if (typeof key === "string" && key.startsWith("canary-last-fetch:")) { entered.resolve(); await held.promise; }962        return original(key);963      });964      const pending = compare(); await entered.promise;965      if (change === "lock") { await vault.lock(); await vault.unlock("canary-test-password"); }966      else await vault.updateEntry(entry.id, change === "domain" ? { url: "https://other.example" } : change === "identity" ? { username: "other" } : { password: "changed" });967      held.resolve();968      expect(await pending).toMatchObject({ ok: false });969    });970  });971972  async function addCanary(title = "GitHub", webhookUrl = "https://example.com/hook") {973    const vault = await import("./vault");974    if (!vault.isUnlocked()) await vault.createVault("canary-test-password");975    return vault.addEntry({ type: "login", title, username: "june", password: "secret", url: "https://github.com", canary: { webhookUrl } });976  }977978  const canarySender = { id: "peach-extension", url: "https://github.com/login", tab: { id: 7 }, frameId: 0 } as chrome.runtime.MessageSender;979980  it("rejects unsafe canary destinations at trusted writes", async () => {981    const entry = await addCanary();982    for (const webhookUrl of ["https://user:[email protected]/hook", "https://100.64.1.2/hook"]) {983      expect(await dispatch({ type: "UPDATE_ENTRY", payload: { id: entry.id, patch: { canary: { webhookUrl } } } })).toMatchObject({ ok: false, error: "invalid_webhook_url" });984      expect(await dispatch({ type: "ADD_ENTRY", payload: { title: "Bad", canary: { webhookUrl } } })).toMatchObject({ ok: false, error: "invalid_webhook_url" });985    }986  });987988  it("keeps fresh background counters when a stale popup saves a label", async () => {989    const entry = await addCanary(); const vault = await import("./vault");990    await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender);991    expect(await dispatch({ type: "UPDATE_ENTRY", payload: { id: entry.id, patch: { canary: { ...entry.canary!, label: "new label", pingCount: 0, lastPinged: 1 } } } })).toMatchObject({ ok: true });992    expect(vault.getEntryById(entry.id)?.canary).toMatchObject({ label: "new label", pingCount: 1, lastPinged: expect.any(Number) });993    expect(vault.getEntryById(entry.id)?.canary?.lastPinged).not.toBe(1);994  });995996  it("counts a dispatched request even when rate storage fails", async () => {997    const entry = await addCanary(); const vault = await import("./vault");998    const original = vi.mocked(chrome.storage.local.set).getMockImplementation()! as unknown as (values: Record<string, unknown>) => Promise<void>;999    vi.mocked(chrome.storage.local.set).mockImplementation(async values => {1000      if (Object.keys(values).some(key => key.startsWith("canary-last-fetch:"))) throw new Error("rate storage failed");1001      return original(values);1002    });1003    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender)).toMatchObject({ ok: false, error: "canary_update_failed" });1004    expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(1);1005    expect(fetchMock).toHaveBeenCalledTimes(1);1006  });10071008  it("expires future persisted timestamps and future in-memory claims", async () => {1009    const entry = await addCanary();1010    const now = Date.now();1011    const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;1012    vi.mocked(chrome.storage.local.get).mockImplementation(async key => typeof key === "string" && key.startsWith("canary-last-fetch:") ? { [key]: now + 3600000 } : original(key));1013    expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender)).ok).toBe(true);1014    expect(fetchMock).toHaveBeenCalledTimes(1);1015    vi.spyOn(Date, "now").mockReturnValue(now - 1000);1016    expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender)).ok).toBe(true);1017    expect(fetchMock).toHaveBeenCalledTimes(2);1018  });10191020  it.each(["rename", "label", "counters", "destination", "delete"])("merges post-dispatch %s edits without losing a counted attempt", async change => {1021    const entry = await addCanary(); const vault = await import("./vault");1022    const held = deferred(); const entered = deferred();1023    const original = vi.mocked(chrome.storage.local.set).getMockImplementation()! as unknown as (values: Record<string, unknown>) => Promise<void>;1024    vi.mocked(chrome.storage.local.set).mockImplementation(async values => {1025      if (Object.keys(values).some(key => key.startsWith("canary-last-fetch:"))) { entered.resolve(); await held.promise; }1026      return original(values);1027    });1028    const pending = dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1029    await entered.promise;1030    if (change === "delete") await vault.deleteEntry(entry.id);1031    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" }) } });1032    held.resolve(); const result = await pending;1033    expect(fetchMock).toHaveBeenCalledTimes(1);1034    if (change === "delete" || change === "destination") {1035      expect(result).toMatchObject({ ok: false, error: "entry_changed" });1036      expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBeUndefined();1037    } else {1038      expect(result).toMatchObject({ ok: true, data: { password: "secret" } });1039      expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(change === "counters" ? 8 : 1);1040      if (change === "rename") expect(vault.getEntryById(entry.id)?.title).toBe("Renamed");1041      if (change === "label") expect(vault.getEntryById(entry.id)?.canary?.label).toBe("fresh");1042    }1043  });10441045  it.each(["get", "remove"] as const)("retries an undispatched alert after rate storage %s fails", async operation => {1046    const entry = await addCanary();1047    const original = vi.mocked(chrome.storage.local[operation]).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;1048    let failed = false;1049    vi.mocked(chrome.storage.local[operation]).mockImplementation(async key => {1050      if (!failed && typeof key === "string" && key.startsWith("canary-last-fetch:")) { failed = true; throw new Error("before dispatch"); }1051      return original(key);1052    });1053    expect((await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).ok).toBe(false);1054    expect(fetchMock).not.toHaveBeenCalled();1055    expect((await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).ok).toBe(true);1056    expect(fetchMock).toHaveBeenCalledTimes(1);1057  });10581059  it("fails closed on legacy invalid stored webhooks without dropping their metadata", async () => {1060    const entry = await addCanary("Legacy", "https://100.64.1.2/hook");1061    expect(await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).toMatchObject({ ok: false, error: "invalid_webhook_url" });1062    const vault = await import("./vault");1063    expect(vault.getEntryById(entry.id)?.canary?.webhookUrl).toBe("https://100.64.1.2/hook");1064    expect(fetchMock).not.toHaveBeenCalled();1065  });10661067  it("starts trusted new canaries with clean counters", async () => {1068    await addCanary();1069    const result = await dispatch({ type: "ADD_ENTRY", payload: { title: "New", canary: { webhookUrl: "https://example.com/hook", pingCount: 99, lastPinged: 1 } } });1070    expect(result).toMatchObject({ ok: true });1071    expect((result.data as import("../shared/types").VaultEntry).canary?.pingCount).toBeUndefined();1072    expect((result.data as import("../shared/types").VaultEntry).canary?.lastPinged).toBeUndefined();1073  });10741075  it("resolves canary destination and title from the stored entry", async () => {1076    const entry = await addCanary();1077    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "password_copied" } })).toMatchObject({ ok: true });1078    expect(fetchMock).toHaveBeenCalledWith("https://example.com/hook", expect.objectContaining({ method: "POST", redirect: "error" }));1079    expect(JSON.parse(fetchMock.mock.calls[0][1].body as string)).toMatchObject({ event: "peach_canary_accessed", entry: "GitHub", trigger: "password_copied", source: "peach-extension" });1080    const vault = await import("./vault");1081    expect(vault.getEntryById(entry.id)?.canary).toMatchObject({ pingCount: 1, lastPinged: expect.any(Number) });1082  });10831084  it("refuses caller-selected non-test destinations without fetching", async () => {1085    const entry = await addCanary();1086    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" });1087    expect(fetchMock).not.toHaveBeenCalled();1088  });10891090  it("rejects array and boxed triggers without poisoning a later valid access", async () => {1091    const entry = await addCanary(); const vault = await import("./vault");1092    const malformed: unknown[] = [structuredClone(["accessed"]), Object("accessed") as unknown];1093    for (const trigger of malformed) {1094      expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger } }, canarySender)).toMatchObject({ ok: false, error: "invalid_payload" });1095      expect(fetchMock).not.toHaveBeenCalled();1096      expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBeUndefined();1097      expect(Object.keys(storage).some(key => key.startsWith("canary-last-fetch:"))).toBe(false);1098    }1099    expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "accessed" } }, canarySender)).ok).toBe(true);1100    expect(fetchMock).toHaveBeenCalledTimes(1);1101    expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(1);1102  });11031104  it("requires unlock and the requesting frame's own domain", async () => {1105    const entry = await addCanary();1106    const payload = { id: entry.id, trigger: "submitted" };1107    expect(await dispatch({ type: "FIRE_CANARY_PING", payload }, { ...canarySender, url: "https://foreign.example/" })).toMatchObject({ ok: false, error: "entry_not_found" });1108    const vault = await import("./vault"); await vault.lock();1109    expect(await dispatch({ type: "FIRE_CANARY_PING", payload }, canarySender)).toMatchObject({ ok: false, error: "vault_locked" });1110    expect(fetchMock).not.toHaveBeenCalled();1111  });11121113  it("dispatches before credential return without waiting for HTTP completion", async () => {1114    const entry = await addCanary();1115    fetchMock.mockImplementation(() => new Promise(() => {}));1116    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1117    expect(result).toMatchObject({ ok: true, data: { password: "secret" } });1118    expect(fetchMock).toHaveBeenCalledTimes(1);1119    expect(JSON.parse(fetchMock.mock.calls[0][1].body as string).trigger).toBe("accessed");1120  });11211122  it("coalesces concurrent accesses and counts one outbound attempt", async () => {1123    const entry = await addCanary();1124    const payload = { id: entry.id, trigger: "autofilled" };1125    const replies = await Promise.all([dispatch({ type: "FIRE_CANARY_PING", payload }, canarySender), dispatch({ type: "FIRE_CANARY_PING", payload }, canarySender)]);1126    expect(replies.every(reply => reply.ok)).toBe(true);1127    expect(fetchMock).toHaveBeenCalledTimes(1);1128    const vault = await import("./vault");1129    expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(1);1130    await vault.updateEntry(entry.id, { title: "Renamed" });1131    expect(await dispatch({ type: "FIRE_CANARY_PING", payload }, canarySender)).toMatchObject({ ok: true, data: { rateLimited: true } });1132    expect(fetchMock).toHaveBeenCalledTimes(1);1133    expect(Object.keys(storage).some(key => key.includes("GitHub"))).toBe(false);1134  });11351136  it("removes the legacy plaintext canary rate key", async () => {1137    const entry = await addCanary(); const legacy = "canary-last-fetch:https://example.com/hook:GitHub";1138    storage[legacy] = Date.now();1139    expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "submitted" } }, canarySender)).ok).toBe(true);1140    expect(storage[legacy]).toBeUndefined();1141  });11421143  it("does not conflate distinct equal-title entries on one webhook", async () => {1144    const first = await addCanary(); const second = await addCanary();1145    for (const entry of [first, second]) await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "submitted" } }, canarySender);1146    expect(fetchMock).toHaveBeenCalledTimes(2);1147  });11481149  it("keeps accepted ID and canonical URL tuples unambiguous", async () => {1150    const base = await addCanary(); const vault = await import("./vault");1151    const first = { ...base, id: "a", canary: { webhookUrl: "https://x/:https://y/" } };1152    const second = { ...base, id: "a:https://x/", canary: { webhookUrl: "https://y/" } };1153    await vault.applyMergedRemoteEntries([first, second], {});1154    expect(vault.getEntryById(second.id)?.id).toBe(second.id);1155    for (const entry of [first, second]) expect((await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "submitted" } }, canarySender)).ok).toBe(true);1156    expect(fetchMock).toHaveBeenCalledTimes(2);1157    expect(Object.keys(storage).filter(key => key.startsWith("canary-last-fetch:")).length).toBe(2);1158  });11591160  it("counts failed network attempts but not trusted test pings", async () => {1161    const entry = await addCanary();1162    fetchMock.mockRejectedValueOnce(new Error("synthetic network failure"));1163    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { id: entry.id, trigger: "password_copied" } })).toMatchObject({ ok: true });1164    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 });1165    const vault = await import("./vault");1166    expect(vault.getEntryById(entry.id)?.canary?.pingCount).toBe(1);1167    expect(fetchMock).toHaveBeenCalledTimes(3);1168  });11691170  it("rejects test pings from content scripts", async () => {1171    await addCanary();1172    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { webhookUrl: "https://example.com/hook", entryTitle: "Draft", trigger: "test" } }, canarySender)).toMatchObject({ ok: false, error: "invalid_sender" });1173    expect(fetchMock).not.toHaveBeenCalled();1174  });11751176  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) => {1177    await addCanary();1178    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { webhookUrl, entryTitle: "Draft", trigger: "test" } })).toMatchObject({ ok: false, error: "invalid_webhook_url" });1179    expect(fetchMock).not.toHaveBeenCalled();1180  });11811182  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) => {1183    await addCanary();1184    expect(await dispatch({ type: "FIRE_CANARY_PING", payload: { webhookUrl, entryTitle: "Draft", trigger: "test" } })).toMatchObject({ ok: true });1185    expect(fetchMock).toHaveBeenCalledWith(webhookUrl, expect.objectContaining({ redirect: "error" }));1186  });11871188  it("does not release credentials after lock during a new canary await", async () => {1189    const entry = await addCanary(); const held = deferred(); const entered = deferred();1190    const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;1191    vi.spyOn(chrome.storage.local, "get").mockImplementation(async key => {1192      if (typeof key === "string" && key.startsWith("canary-last-fetch:")) { entered.resolve(); await held.promise; }1193      return original(key);1194    });1195    const filling = dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1196    await entered.promise; const vault = await import("./vault"); await vault.lock(); held.resolve();1197    expect(await filling).toMatchObject({ ok: false, error: "vault_locked" });1198    expect(fetchMock).not.toHaveBeenCalled();1199  });12001201  it("never treats an undispatched alert as an already attempted rate claim", async () => {1202    const entry = await addCanary(); const vault = await import("./vault");1203    vi.spyOn(vault, "updateEntry").mockRejectedValueOnce(new Error("synthetic counter persistence failure"));1204    const first = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1205    expect(first.ok).toBe(false);1206    const retry = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1207    if (retry.ok) expect(fetchMock).toHaveBeenCalledTimes(1);1208    expect(fetchMock).toHaveBeenCalledTimes(1);1209  });12101211  it("rechecks canary configuration after an awaited claim read", async () => {1212    const entry = await addCanary(); const held = deferred(); const entered = deferred();1213    const original = vi.mocked(chrome.storage.local.get).getMockImplementation()! as unknown as (key: unknown) => Promise<Record<string, unknown>>;1214    vi.spyOn(chrome.storage.local, "get").mockImplementation(async key => {1215      if (typeof key === "string" && key.startsWith("canary-last-fetch:")) { entered.resolve(); await held.promise; }1216      return original(key);1217    });1218    const filling = dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1219    await entered.promise; const vault = await import("./vault");1220    await vault.updateEntry(entry.id, { canary: { webhookUrl: "https://new.example/hook", label: "new" } });1221    held.resolve();1222    expect(await filling).toMatchObject({ ok: false, error: "entry_changed" });1223    expect(fetchMock).not.toHaveBeenCalled();1224    expect(vault.getEntryById(entry.id)?.canary?.webhookUrl).toBe("https://new.example/hook");1225  });12261227  it("rejects a late canary edit between helper completion and credential return", async () => {1228    const entry = await addCanary(); const vault = await import("./vault"); const edited = deferred();1229    const original = vault.getEntryById; let queued = false;1230    vi.spyOn(vault, "getEntryById").mockImplementation(id => {1231      const current = original(id);1232      if (!queued && current?.canary?.pingCount === 1) {1233        queued = true;1234        queueMicrotask(() => { void vault.updateEntry(entry.id, { canary: { webhookUrl: "https://new.example/hook", label: "changed" } }).then(edited.resolve); });1235      }1236      return current;1237    });1238    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender);1239    await edited.promise;1240    expect(result).toMatchObject({ ok: false, error: "entry_changed" });1241    expect(fetchMock).toHaveBeenCalledTimes(1);1242  });12431244  it("does not cache a post-dispatch persistence error as a permanent access block", async () => {1245    const entry = await addCanary(); const vault = await import("./vault");1246    vi.spyOn(vault, "updateEntry").mockRejectedValueOnce(new Error("synthetic counter failure"));1247    expect((await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).ok).toBe(false);1248    await vault.updateEntry(entry.id, { canary: { ...entry.canary!, label: "corrected" } });1249    expect(await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } }, canarySender)).toMatchObject({ ok: true, data: { password: "secret" } });1250    expect(fetchMock).toHaveBeenCalledTimes(1);1251  });12521253  it("uses a valid cross-domain capability once for access and notification", async () => {1254    const entry = await addCanary(); const messages = await import("./messages");1255    const sender = { ...canarySender, url: "https://other.example/" };1256    const token = messages.createSummonCapability(7, "https://other.example");1257    expect((await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "other.example", capability: token } }, sender)).ok).toBe(true);1258    expect(await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender)).toMatchObject({ ok: true, data: { password: "secret" } });1259    expect(await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender)).toMatchObject({ ok: false, error: "entry_not_found" });1260    expect(fetchMock).toHaveBeenCalledTimes(1);1261  });12621263  it("a failed counter write cannot restore a superseded canary configuration", async () => {1264    const entry = await addCanary(); const entered = deferred(); const held = deferred();1265    const original = vi.mocked(chrome.storage.local.set).getMockImplementation()! as unknown as (values: Record<string, unknown>) => Promise<void>; let first = true;1266    vi.spyOn(chrome.storage.local, "set").mockImplementation(async values => {1267      if (first && Object.hasOwn(values, "peach_vault_a")) { first = false; entered.resolve(); await held.promise; throw new Error("synthetic failed counter write"); }1268      return original(values);1269    });1270    const vault = await import("./vault");1271    const failed = vault.updateEntry(entry.id, { canary: { ...entry.canary!, pingCount: 1 } }).catch(() => undefined);1272    await entered.promise;1273    await vault.updateEntry(entry.id, { canary: { webhookUrl: "https://new.example/hook", label: "new configuration" } });1274    held.resolve(); await failed;1275    expect(vault.getEntryById(entry.id)?.canary).toMatchObject({ webhookUrl: "https://new.example/hook", label: "new configuration" });1276  });12771278  it("failed counter rollback preserves a successful overlapping deletion", async () => {1279    const entry = await addCanary(); const entered = deferred(); const held = deferred();1280    const original = vi.mocked(chrome.storage.local.set).getMockImplementation()! as unknown as (values: Record<string, unknown>) => Promise<void>; let first = true;1281    vi.spyOn(chrome.storage.local, "set").mockImplementation(async values => {1282      if (first && Object.hasOwn(values, "peach_vault_a")) { first = false; entered.resolve(); await held.promise; throw new Error("synthetic failed counter write"); }1283      return original(values);1284    });1285    const vault = await import("./vault");1286    const failed = vault.updateEntry(entry.id, { canary: { ...entry.canary!, pingCount: 1 } }).catch(() => undefined);1287    await entered.promise; await vault.deleteEntry(entry.id); held.resolve(); await failed;1288    expect(vault.getEntryById(entry.id)).toBeUndefined();1289    await vault.lock(); await vault.unlock("canary-test-password");1290    expect(vault.getEntryById(entry.id)).toBeUndefined();1291  });12921293  it("GET_IDENTITIES when locked returns vault locked error", async () => {1294    const vault = await import("./vault");1295    await vault.createVault("correct-pass-12345");1296    vault.lock();1297    await expect(dispatch({ type: "GET_IDENTITIES" })).resolves.toMatchObject({1298      ok: false,1299      error: "vault_locked",1300    });1301  });13021303  it("GET_IDENTITIES returns emails and usernames derived from login entries", async () => {1304    const vault = await import("./vault");1305    await vault.createVault("correct-pass-12345");1306    await vault.addEntry({ title: "Gmail", username: "[email protected]", password: "pw1", url: "https://gmail.com" });1307    await vault.addEntry({ title: "GitHub", username: "[email protected]", password: "pw2", url: "https://github.com" });1308    await vault.addEntry({ title: "Slack", username: "juni_patel", password: "pw3", url: "https://slack.com" });13091310    const resp = await dispatch({ type: "GET_IDENTITIES" }) as { ok: boolean; data: unknown[] };1311    expect(resp.ok).toBe(true);1312    const data = resp.data as Array<{ value: string; type: string; useCount: number }>;1313    expect(data.find((d) => d.value === "[email protected]")).toMatchObject({1314      type: "email",1315      useCount: 2,1316    });1317    expect(data.find((d) => d.value === "juni_patel")).toMatchObject({1318      type: "username",1319      useCount: 1,1320    });1321    // emails appear before usernames1322    const emailIdx = data.findIndex((d) => d.value === "[email protected]");1323    const userIdx = data.findIndex((d) => d.value === "juni_patel");1324    expect(emailIdx).toBeLessThan(userIdx);1325  });13261327  it("GET_IDENTITIES deduplicates correctly — same email across 3 entries appears once with useCount 3", async () => {1328    const vault = await import("./vault");1329    await vault.createVault("correct-pass-12345");1330    for (let i = 0; i < 3; i++) {1331      await vault.addEntry({ title: `Site${i}`, username: "[email protected]", password: "pw", url: `https://site${i}.com` });1332    }13331334    const resp = await dispatch({ type: "GET_IDENTITIES" }) as { ok: boolean; data: unknown[] };1335    const data = resp.data as Array<{ value: string; useCount: number }>;1336    const hits = data.filter((d) => d.value === "[email protected]");1337    expect(hits).toHaveLength(1);1338    expect(hits[0]!.useCount).toBe(3);1339  });13401341  it("GET_IDENTITIES rejects content-script and page-relay senders", async () => {1342    const vault = await import("./vault");1343    await vault.createVault("correct-pass-12345");1344    await vault.addEntry({1345      title: "Private identity",1346      username: "[email protected]",1347      password: "pw",1348      url: "https://private.example",1349    });13501351    const senders = [1352      {1353        id: "peach-extension",1354        url: "https://private.example/signup",1355        tab: { id: 1 } as chrome.tabs.Tab,1356      },1357      { id: "peach-extension", url: "https://private.example/signup" },1358    ] satisfies chrome.runtime.MessageSender[];1359    for (const sender of senders) {1360      await expect(dispatch({ type: "GET_IDENTITIES" }, sender)).resolves.toMatchObject({1361        ok: false,1362        error: "invalid_sender",1363      });1364    }1365  });13661367  it("IS_CARD_DECLINED does not refresh the auto-lock timer", async () => {1368    const vault = await import("./vault");1369    await vault.createVault("correct-pass-12345");1370    const alarmsCreate = chrome.alarms.create as unknown as ReturnType<typeof vi.fn>;13711372    // Sanity: a non-excluded message (GET_ENTRIES) DOES refresh the timer1373    alarmsCreate.mockClear();1374    await dispatch({ type: "GET_ENTRIES" });1375    expect(alarmsCreate).toHaveBeenCalled();13761377    // Passive queries are in the exclusion list and must not re-arm1378    alarmsCreate.mockClear();1379    await dispatch({ type: "IS_CARD_DECLINED", payload: { origin: "https://example.com" } });1380    expect(alarmsCreate).not.toHaveBeenCalled();1381  });13821383  it("DESTROY_VAULT preserves the Pro license and celebration flag", async () => {1384    const vault = await import("./vault");1385    await vault.createVault("correct-pass-12345");1386    await vault.addEntry({ title: "Gmail", username: "june", password: "s", url: "https://mail.google.com" });13871388    // Simulate an activated Pro license + already-celebrated marker.1389    storage.peach_license = "PEACH-PRO-TEST-KEY";1390    storage.peach_pro_celebrated = true;13911392    const res = await dispatch({ type: "DESTROY_VAULT" }, { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" });1393    expect(res).toMatchObject({ ok: true });13941395    // Vault data is gone…1396    expect(storage.peach_vault_a).toBeUndefined();1397    // …but the paid license and celebration flag survive the wipe.1398    expect(storage.peach_license).toBe("PEACH-PRO-TEST-KEY");1399    expect(storage.peach_pro_celebrated).toBe(true);1400  });14011402  it("handleMessage waits for the restore gate before serving (cold-start: no premature onboarding/lock)", async () => {1403    const messages = await import("./messages");1404    const vault = await import("./vault");14051406    let resolveGate: () => void = () => {};1407    messages.setRestoreReady(new Promise<void>((r) => { resolveGate = r; }));14081409    let settled = false;1410    const pending = dispatch({ type: "HAS_VAULT" }).then((r) => { settled = true; return r; });14111412    // While restore is in flight the handler must NOT have answered yet —1413    // this is the window where the old code returned "no vault" → onboarding.1414    await new Promise((r) => setTimeout(r, 20));1415    expect(settled).toBe(false);14161417    // Restore completes (the vault becomes available), gate opens.1418    await vault.createVault("correct-pass-12345");1419    resolveGate();14201421    await expect(pending).resolves.toMatchObject({ ok: true, data: true });1422  });14231424  it.each([null, true, false, 1, {}, "replace", "warned-import "])("CREATE_VAULT rejects malformed replacement intent %j", async (replacement) => {1425    const result = await dispatch({ type: "CREATE_VAULT", payload: { password: "new-password", replacement } });1426    expect(result).toMatchObject({ ok: false, error: "invalid_payload" });1427    expect(storage.peach_vault_a).toBeUndefined();1428  });14291430  it("CREATE_VAULT refuses ordinary replacement of an existing locked vault", async () => {1431    const vault = await import("./vault");1432    await vault.createVault("original-password");1433    await vault.lock();1434    const before = structuredClone(storage);1435    expect(await dispatch({ type: "CREATE_VAULT", payload: { password: "new-password" } })).toMatchObject({ ok: false, error: "vault_already_exists" });1436    expect(storage).toEqual(before);1437    expect(await vault.unlock("original-password")).toBe(true);1438  });14391440  it("CREATE_VAULT rejects an empty master password (audit HIGH — no empty-key vault)", async () => {1441    const res = await dispatch({ type: "CREATE_VAULT", payload: { password: "" } });1442    expect(res.ok).toBe(false);1443    // Nothing was written — no vault exists.1444    const has = await dispatch({ type: "HAS_VAULT" });1445    expect((has as { data?: boolean }).data).toBe(false);1446  });14471448  it("GET_ENTRY_FOR_FILL sends a 6-digit TOTP code, never the seed (SEV-3-C)", async () => {1449    const vault = await import("./vault");1450    await vault.createVault("correct-pass-12345");1451    const e = await vault.addEntry({1452      title: "Mail",1453      username: "june",1454      password: "pw",1455      url: "https://mail.test",1456      totp: "JBSWY3DPEHPK3PXP",1457    });14581459    const res = await dispatch(1460      { type: "GET_ENTRY_FOR_FILL", payload: { id: e.id } },1461      { id: "peach-extension", url: "https://mail.test/login" },1462    );1463    expect(res.ok).toBe(true);1464    const data = res.data as { totp?: string; totpCode?: string; totpRemaining?: number };1465    expect(data.totp).toBeUndefined();1466    expect(data.totpCode).toMatch(/^\d{6}$/);1467    expect(data.totpRemaining).toBeGreaterThan(0);1468    expect(data.totpRemaining).toBeLessThanOrEqual(30);1469  });14701471  it("GET_ENTRY_FOR_FILL strips passwordHistory; GET_ENTRY_FOR_EDIT keeps it", async () => {1472    const vault = await import("./vault");1473    await vault.createVault("correct-pass-12345");1474    const e = await vault.addEntry({1475      title: "Bank",1476      username: "june",1477      password: "old-pw",1478      url: "https://bank.test",1479    });1480    await vault.updateEntry(e.id, { password: "new-pw" });14811482    const fill = await dispatch(1483      { type: "GET_ENTRY_FOR_FILL", payload: { id: e.id } },1484      { id: "peach-extension", url: "https://bank.test/login" },1485    );1486    expect(fill.ok).toBe(true);1487    // Passive autofill never receives prior passwords (blast-radius containment).1488    expect((fill.data as Record<string, unknown>).passwordHistory).toBeUndefined();14891490    const edit = await dispatch({ type: "GET_ENTRY_FOR_EDIT", payload: { id: e.id } });1491    expect(edit.ok).toBe(true);1492    const editHist = (edit.data as { passwordHistory?: Array<{ password: string }> }).passwordHistory ?? [];1493    expect(editHist.map((h) => h.password)).toEqual(["old-pw"]);1494  });14951496  it("GET_ENTRY_FOR_EDIT returns the raw TOTP seed for the trusted edit form", async () => {1497    const vault = await import("./vault");1498    await vault.createVault("correct-pass-12345");1499    const e = await vault.addEntry({1500      title: "Mail",1501      username: "june",1502      password: "pw",1503      url: "https://mail.test",1504      totp: "JBSWY3DPEHPK3PXP",1505    });15061507    const res = await dispatch({ type: "GET_ENTRY_FOR_EDIT", payload: { id: e.id } });1508    expect(res.ok).toBe(true);1509    const data = res.data as { totp?: string };1510    expect(data.totp).toBe("JBSWY3DPEHPK3PXP");1511  });15121513  it("DESTROY_VAULT with no license clears storage without resurrecting keys", async () => {1514    const vault = await import("./vault");1515    await vault.createVault("correct-pass-12345");15161517    const res = await dispatch({ type: "DESTROY_VAULT" }, { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" });1518    expect(res).toMatchObject({ ok: true });15191520    expect(storage.peach_vault_a).toBeUndefined();1521    expect(storage.peach_license).toBeUndefined();1522    expect(storage.peach_pro_celebrated).toBeUndefined();1523  });15241525  // --- MV-1: GET_ENTRY_FOR_FILL re-validates the requesting tab's origin ---15261527  function tabSender(url: string, tabId = 1, frameId = 0): chrome.runtime.MessageSender {1528    return { id: "peach-extension", tab: { id: tabId, url } as chrome.tabs.Tab, url, frameId };1529  }15301531  async function addPasskeyOnlyEntry(title: string, url: string) {1532    const vault = await import("./vault");1533    const generated = await generatePasskeyKeypair(-7);1534    return vault.addEntry({1535      type: "login",1536      title,1537      url,1538      passkey: {1539        rpId: new URL(url).hostname,1540        rpName: title,1541        credentialId: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1542        publicKeyCose: base64urlEncode(generated.publicKeyCose),1543        privateKeyJwk: generated.privateKeyJwk,1544        userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1545        userName: "june",1546        userDisplayName: "June",1547        algorithm: -7,1548        signCount: 0,1549        aaguid: "AAAAAAAAAAAAAAAAAAAAAA",1550        backupEligible: true,1551        backupState: false,1552        createdAt: Date.now(),1553      },1554    });1555  }15561557  it("PB-26-201: normal inventory ignores forged domain and gesture booleans", async () => {1558    const vault = await import("./vault");1559    await vault.createVault("correct-pass-12345");1560    await vault.addEntry({ title: "GitHub", username: "victim", password: "secret", url: "https://github.com" });1561    await vault.addEntry({ title: "Evil", username: "attacker", password: "known", url: "https://evil.example.com" });15621563    const result = await dispatch(1564      {1565        type: "AUTOFILL_QUERY",1566        payload: {1567          domain: "github.com",1568          includeAll: true,1569          userGesture: true,1570          explicitSummon: true,1571        },1572      },1573      tabSender("https://evil.example.com/phish"),1574    );15751576    expect(result).toMatchObject({ ok: true });1577    expect((result.data as Array<{ title: string }>).map((entry) => entry.title)).toEqual(["Evil"]);1578  });15791580  it("PB-26-201: normal TOTP inventory is scoped to the attested frame origin", async () => {1581    const vault = await import("./vault");1582    await vault.createVault("correct-pass-12345");1583    await vault.addEntry({ title: "GitHub 2FA", password: "secret", url: "https://github.com", totp: "JBSWY3DPEHPK3PXP" });1584    await vault.addEntry({ title: "Evil 2FA", password: "known", url: "https://evil.example.com", totp: "JBSWY3DPEHPK3PXP" });15851586    const result = await dispatch(1587      { type: "AUTOFILL_QUERY", payload: { domain: "github.com", kind: "totp" } },1588      tabSender("https://evil.example.com/verify"),1589    );15901591    expect((result.data as Array<{ title: string }>).map((entry) => entry.title)).toEqual(["Evil 2FA"]);1592  });15931594  it("PB-26-201: summon capability is one-shot after inventory authorization", async () => {1595    const vault = await import("./vault");1596    const messages = await import("./messages");1597    await vault.createVault("correct-pass-12345");1598    const entry = await vault.addEntry({ title: "GitHub", username: "june", password: "secret123", url: "https://github.com" });1599    const sender = tabSender("https://evil.example.com/phish");1600    const token = messages.createSummonCapability(1, "https://evil.example.com");16011602    const inventory = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1603    expect(inventory).toMatchObject({ ok: true, data: [{ id: entry.id }] });16041605    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1606    expect(firstFill).toMatchObject({ ok: true, data: { id: entry.id } });1607    const replay = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1608    expect(replay).toMatchObject({ ok: false, error: "entry_not_found" });1609  });16101611  it("PB-26-201: summon capability is consumed by a same-domain fill", async () => {1612    const vault = await import("./vault");1613    const messages = await import("./messages");1614    await vault.createVault("correct-pass-12345");1615    const entry = await vault.addEntry({ title: "GitHub", password: "secret123", url: "https://evil.example.com" });1616    const sender = tabSender("https://evil.example.com/login");1617    const token = messages.createSummonCapability(1, "https://evil.example.com");16181619    const inventory = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1620    expect(inventory).toMatchObject({ ok: true, data: [{ id: entry.id }] });1621    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1622    expect(firstFill).toMatchObject({ ok: true, data: { id: entry.id } });16231624    const offDomainReplay = await dispatch(1625      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1626      tabSender("https://github.com/login"),1627    );1628    expect(offDomainReplay).toMatchObject({ ok: false, error: "entry_not_found" });1629  });16301631  it("PB-26-201: summon capability cannot fill a different entry", async () => {1632    const vault = await import("./vault");1633    const messages = await import("./messages");1634    await vault.createVault("correct-pass-12345");1635    const first = await vault.addEntry({ title: "First", password: "one", url: "https://first.example" });1636    const second = await vault.addEntry({ title: "Second", password: "two", url: "https://second.example" });1637    const sender = tabSender("https://evil.example.com/phish");1638    const token = messages.createSummonCapability(1, "https://evil.example.com");1639    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1640    const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: first.id, capability: token } }, sender);1641    expect(firstFill).toMatchObject({ ok: true, data: { id: first.id } });1642    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: second.id, capability: token } }, sender);1643    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1644    expect(first.id).not.toBe(second.id);1645  });16461647  it("PB-26-201: fill before inventory is rejected without an entry oracle", async () => {1648    const vault = await import("./vault");1649    const messages = await import("./messages");1650    await vault.createVault("correct-pass-12345");1651    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1652    const token = messages.createSummonCapability(1, "https://evil.example.com");1653    const result = await dispatch(1654      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1655      tabSender("https://evil.example.com/phish"),1656    );1657    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1658  });16591660  it("PB-26-201: an unused summon capability does not block a normal same-origin fill", async () => {1661    const vault = await import("./vault");1662    const messages = await import("./messages");1663    await vault.createVault("correct-pass-12345");1664    const entry = await vault.addEntry({1665      title: "Evil",1666      password: "known",1667      url: "https://evil.example.com",1668    });1669    const sender = tabSender("https://evil.example.com/login");1670    const token = messages.createSummonCapability(1, "https://evil.example.com");16711672    const result = await dispatch(1673      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1674      sender,1675    );16761677    expect(result).toMatchObject({ ok: true, data: { id: entry.id } });1678  });16791680  it("PB-26-201: expired fill capability is rejected before entry-specific errors", async () => {1681    vi.useFakeTimers();1682    vi.setSystemTime(new Date("2026-09-02T12:00:00Z"));1683    const vault = await import("./vault");1684    const messages = await import("./messages");1685    await vault.createVault("correct-pass-12345");1686    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1687    const sender = tabSender("https://evil.example.com/phish");1688    const token = messages.createSummonCapability(1, "https://evil.example.com");1689    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1690    vi.advanceTimersByTime(30_001);16911692    const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1693    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1694  });16951696  it("PB-26-201: wrong-tab fill capability is rejected before entry-specific errors", async () => {1697    const vault = await import("./vault");1698    const messages = await import("./messages");1699    await vault.createVault("correct-pass-12345");1700    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1701    const token = messages.createSummonCapability(1, "https://evil.example.com");1702    await dispatch(1703      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1704      tabSender("https://evil.example.com/phish"),1705    );17061707    const result = await dispatch(1708      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1709      tabSender("https://evil.example.com/phish", 2),1710    );1711    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1712  });17131714  it("PB-26-201: wrong-frame fill capability is rejected before entry-specific errors", async () => {1715    const vault = await import("./vault");1716    const messages = await import("./messages");1717    await vault.createVault("correct-pass-12345");1718    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1719    const token = messages.createSummonCapability(1, "https://evil.example.com", 3);1720    await dispatch(1721      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1722      tabSender("https://evil.example.com/phish", 1, 3),1723    );17241725    const result = await dispatch(1726      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1727      tabSender("https://evil.example.com/phish", 1, 4),1728    );1729    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1730  });17311732  it("PB-26-201: wrong-origin fill capability is rejected before entry-specific errors", async () => {1733    const vault = await import("./vault");1734    const messages = await import("./messages");1735    await vault.createVault("correct-pass-12345");1736    const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1737    const token = messages.createSummonCapability(1, "https://evil.example.com");1738    await dispatch(1739      { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1740      tabSender("https://evil.example.com/phish"),1741    );17421743    const result = await dispatch(1744      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1745      tabSender("https://other.example.com/phish"),1746    );1747    expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1748  });17491750  it("PB-26-201: selecting a missing id consumes the one-shot capability without an oracle", async () => {1751    const vault = await import("./vault");1752    const messages = await import("./messages");1753    await vault.createVault("correct-pass-12345");1754    const existing = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1755    const sender = tabSender("https://evil.example.com/phish");1756    const token = messages.createSummonCapability(1, "https://evil.example.com");1757    await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);17581759    const missing = await dispatch(1760      { type: "GET_ENTRY_FOR_FILL", payload: { id: "missing", capability: token } },1761      sender,1762    );1763    const existingReplay = await dispatch(1764      { type: "GET_ENTRY_FOR_FILL", payload: { id: existing.id, capability: token } },1765      sender,1766    );1767    expect(missing).toMatchObject({ ok: false, error: "entry_not_found" });1768    expect(existingReplay).toEqual(missing);1769  });17701771  it("PB-26-201: inventory capability cannot be reused for a second inventory", async () => {1772    const vault = await import("./vault");1773    const messages = await import("./messages");1774    await vault.createVault("correct-pass-12345");1775    await vault.addEntry({ title: "GitHub", password: "secret", url: "https://github.com" });1776    const sender = tabSender("https://evil.example.com/phish");1777    const token = messages.createSummonCapability(1, "https://evil.example.com");1778    const first = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1779    const second = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);17801781    expect(first).toMatchObject({ ok: true, data: [{ title: "GitHub" }] });1782    expect(second).toMatchObject({ ok: false, error: "entry_not_found" });1783  });17841785  it("PB-26-201: cards require a capability and consume it on the selected fill", async () => {1786    const vault = await import("./vault");1787    const messages = await import("./messages");1788    await vault.createVault("correct-pass-12345");1789    const card = await vault.addEntry({1790      type: "card",1791      title: "Personal Visa",1792      cardholderName: "June Peach",1793      cardNumber: "4111111111111111",1794      cvc: "123",1795      expMonth: "12",1796      expYear: "2030",1797    });1798    const sender = tabSender("https://shop.example.com/checkout");1799    const passive = await dispatch(1800      { type: "AUTOFILL_QUERY", payload: { domain: "shop.example.com", kind: "card" } },1801      sender,1802    );1803    expect(passive).toMatchObject({ ok: true, data: [] });18041805    const token = messages.createSummonCapability(1, "https://shop.example.com");1806    const inventory = await dispatch(1807      { type: "AUTOFILL_QUERY", payload: { domain: "forged.example", kind: "card", capability: token } },1808      sender,1809    );1810    expect(inventory).toMatchObject({ ok: true, data: [{ id: card.id, title: "Personal Visa" }] });1811    expect((inventory.data as Array<Record<string, unknown>>)[0]).not.toHaveProperty("cardNumber");18121813    const fill = await dispatch(1814      { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1815      sender,1816    );1817    expect(fill).toMatchObject({ ok: true, data: { id: card.id, cardNumber: "4111111111111111" } });1818    const replay = await dispatch(1819      { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1820      sender,1821    );1822    expect(replay).toMatchObject({ ok: false, error: "entry_not_found" });1823  });18241825  it("PB-26-201: inline edit popup request stores only the selected entry id", async () => {1826    const result = await dispatch(1827      { type: "OPEN_POPUP", payload: { entryId: "entry-123" } },1828      tabSender("https://example.com/login"),1829    );18301831    expect(result).toMatchObject({ ok: true });1832    expect(sessionStorage.peach_open_entry).toBe("entry-123");1833    expect(sessionStorage.peach_inline_unlock).toBeUndefined();1834  });18351836  it("MV-1: tab request with a matching domain returns the entry", async () => {1837    const vault = await import("./vault");1838    await vault.createVault("correct-pass-12345");1839    const entry = await vault.addEntry({1840      title: "GitHub",1841      username: "june",1842      password: "secret123",1843      url: "https://github.com",1844    });18451846    const res = await dispatch(1847      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1848      tabSender("https://github.com/login"),1849    );1850    expect(res).toMatchObject({ ok: true, data: { id: entry.id } });1851  });18521853  it("MV-1: tab request with a mismatched domain and no explicitSummon is refused as entry_not_found", async () => {1854    const vault = await import("./vault");1855    await vault.createVault("correct-pass-12345");1856    const entry = await vault.addEntry({1857      title: "GitHub",1858      username: "june",1859      password: "secret123",1860      url: "https://github.com",1861    });18621863    const res = await dispatch(1864      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1865      tabSender("https://evil.example.com/phish"),1866    );1867    // Refused with the same error as a missing id — no cross-domain oracle.1868    expect(res).toMatchObject({ ok: false, error: "entry_not_found" });1869  });18701871  it("PB-26-201: explicitSummon cannot authorize off-domain fill", async () => {1872    const vault = await import("./vault");1873    await vault.createVault("correct-pass-12345");1874    const entry = await vault.addEntry({1875      title: "GitHub",1876      username: "june",1877      password: "secret123",1878      url: "https://github.com",1879    });18801881    const res = await dispatch(1882      {1883        type: "GET_ENTRY_FOR_FILL",1884        payload: { id: entry.id, explicitSummon: true },1885      },1886      tabSender("https://evil.example.com/phish"),1887    );1888    expect(res).toMatchObject({ ok: false, error: "entry_not_found" });1889  });18901891  it("MV-1: tab context with an unparseable URL is refused as origin_unverified", async () => {1892    const vault = await import("./vault");1893    await vault.createVault("correct-pass-12345");1894    const entry = await vault.addEntry({1895      title: "GitHub",1896      username: "june",1897      password: "secret123",1898      url: "https://github.com",1899    });19001901    const res = await dispatch(1902      { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1903      tabSender("not a url"),1904    );1905    expect(res).toMatchObject({ ok: false, error: "origin_unverified" });1906  });19071908  // --- MV-2: vault-wide inventory only ships on an explicit user gesture ---19091910  async function seedTwoDomainVault() {1911    const vault = await import("./vault");1912    await vault.createVault("correct-pass-12345");1913    await vault.addEntry({1914      title: "GitHub",1915      username: "june",1916      password: "gh",1917      url: "https://github.com",1918    });1919    await vault.addEntry({1920      title: "Example",1921      username: "june",1922      password: "ex",1923      url: "https://example.com",1924    });1925  }19261927  it("MV-2: AUTOFILL_QUERY with includeAll but no userGesture returns only the domain-scoped list", async () => {1928    await seedTwoDomainVault();19291930    const res = await dispatch({1931      type: "AUTOFILL_QUERY",1932      payload: { domain: "github.com", includeAll: true },1933    });1934    expect(res.ok).toBe(true);1935    const data = res.data as Array<{ title: string }>;1936    // includeAll was stripped — only the github.com match comes back.1937    expect(data).toHaveLength(1);1938    expect(data[0].title).toBe("GitHub");1939  });19401941  it("PB-26-201: userGesture cannot authorize vault-wide inventory", async () => {1942    await seedTwoDomainVault();19431944    const res = await dispatch({1945      type: "AUTOFILL_QUERY",1946      payload: { domain: "github.com", includeAll: true, userGesture: true },1947    });1948    expect(res.ok).toBe(true);1949    const data = res.data as Array<{ title: string }>;1950    expect(data.map((d) => d.title)).toEqual(["GitHub"]);1951  });19521953  it("PB-26-104: decoy pairing messages hide devices and prior sync outcome", async () => {1954    const vault = await import("./vault");1955    const { listPairedDevices, upsertPairedDevice } = await import("./paired-devices");1956    const { setSyncRunner, triggerSyncIfReachable } = await import("./sync-trigger");1957    await vault.createVault("correct-pass-12345");1958    await vault.setupDuress("decoy-pass-67890");1959    await upsertPairedDevice({1960      deviceId: "android-real",1961      deviceName: "Real Pixel",1962      deviceType: "android",1963      longTermPublicKeyHex: "a".repeat(64),1964      trustSource: "direct",1965      pairedAt: 1_700_000_000_000,1966    });1967    setSyncRunner(async () => ({ ok: true, entriesReceived: 3, entriesSent: 2 }));1968    await triggerSyncIfReachable({ reason: "manual" });19691970    await vault.lock();1971    expect(await vault.unlock("decoy-pass-67890")).toBe(true);1972    await expect(dispatch({ type: "LIST_PAIRED_DEVICES" })).resolves.toEqual({1973      ok: true,1974      data: { devices: [] },1975    });1976    await expect(dispatch({ type: "GET_SYNC_STATE" })).resolves.toEqual({1977      ok: true,1978      data: { status: "idle" },1979    });1980    expect((await listPairedDevices()).map((device) => device.deviceName)).toEqual(["Real Pixel"]);1981  });19821983  it("PB-26-104: real unlocked pairing messages retain the device list", async () => {1984    const vault = await import("./vault");1985    const { upsertPairedDevice } = await import("./paired-devices");1986    await vault.createVault("correct-pass-12345");1987    await upsertPairedDevice({1988      deviceId: "android-real",1989      deviceName: "Real Pixel",1990      deviceType: "android",1991      longTermPublicKeyHex: "a".repeat(64),1992      trustSource: "direct",1993      pairedAt: 1_700_000_000_000,1994    });19951996    await expect(dispatch({ type: "LIST_PAIRED_DEVICES" })).resolves.toMatchObject({1997      ok: true,1998      data: { devices: [{ deviceId: "android-real", deviceName: "Real Pixel" }] },1999    });2000  });20012002  async function seedPendingVouched(deviceId: string) {2003    await chrome.storage.local.set({2004      peach_pending_vouched_devices_v1: [{2005        deviceId,2006        deviceName: "New Pixel",2007        deviceType: "android",2008        longTermPublicKeyHex: "e".repeat(64),2009        signingPublicKeyHex: "a".repeat(64),2010        wsPort: 51234,2011        pairedAt: 1_700_000_000_020,2012        receivedAt: 1_700_000_000_050,2013        vouchedByDeviceId: "extension-issuer",2014      }],2015    });2016  }20172018  it("MV-7: CONFIRM_VOUCHED_DEVICE moves a pending device into the paired registry as vouched", async () => {2019    const vault = await import("./vault");2020    await vault.createVault("correct-pass-12345");2021    await seedPendingVouched("android-new");2022    const { findPairedDeviceById } = await import("./paired-devices");2023    const { listPendingVouchedDevices } = await import(2024      "./pending-vouched-devices"2025    );20262027    const res = await dispatch({2028      type: "CONFIRM_VOUCHED_DEVICE",2029      payload: { deviceId: "android-new" },2030    });2031    expect(res).toMatchObject({ ok: true });20322033    expect(await findPairedDeviceById("android-new")).toMatchObject({2034      deviceName: "New Pixel",2035      trustSource: "vouched",2036      longTermPublicKeyHex: "e".repeat(64),2037    });2038    expect(await listPendingVouchedDevices()).toHaveLength(0);2039  });20402041  it("S1: CONFIRM_VOUCHED_DEVICE refuses a pending device whose key is revoked", async () => {2042    const vault = await import("./vault");2043    await vault.createVault("correct-pass-12345");2044    await seedPendingVouched("android-relabelled");2045    const { findPairedDeviceById, revokeDeviceById, upsertPairedDevice } =2046      await import("./paired-devices");2047    const { listPendingVouchedDevices } = await import(2048      "./pending-vouched-devices"2049    );20502051    // The queue entry predates the revocation, and it carries a fresh id, so2052    // sweeping the queue by id at revocation time would not have caught it.2053    await upsertPairedDevice({2054      deviceId: "android-old",2055      deviceName: "New Pixel",2056      deviceType: "android",2057      longTermPublicKeyHex: "e".repeat(64),2058      signingPublicKeyHex: "a".repeat(64),2059      pairedAt: 1_700_000_000_000,2060      trustSource: "vouched",2061    });2062    await revokeDeviceById("android-old", "self");20632064    const res = await dispatch({2065      type: "CONFIRM_VOUCHED_DEVICE",2066      payload: { deviceId: "android-relabelled" },2067    });2068    expect(res).toMatchObject({ ok: false, error: "device_revoked" });2069    expect(await findPairedDeviceById("android-relabelled")).toBeNull();2070    expect(await listPendingVouchedDevices()).toHaveLength(0);2071  });20722073  it("MV-7: REJECT_VOUCHED_DEVICE clears the pending entry and never pairs it", async () => {2074    const vault = await import("./vault");2075    await vault.createVault("correct-pass-12345");2076    await seedPendingVouched("android-new");2077    const { findPairedDeviceById } = await import("./paired-devices");2078    const { listPendingVouchedDevices } = await import(2079      "./pending-vouched-devices"2080    );20812082    const res = await dispatch({2083      type: "REJECT_VOUCHED_DEVICE",2084      payload: { deviceId: "android-new" },2085    });2086    expect(res).toMatchObject({ ok: true });20872088    expect(await findPairedDeviceById("android-new")).toBeNull();2089    expect(await listPendingVouchedDevices()).toHaveLength(0);2090  });20912092  // --- unpair: UNPAIR_DEVICE revokes the device and drops it from the registry ---20932094  it("UNPAIR_DEVICE revokes a paired device, drops the row, and lists the revocation", async () => {2095    const vault = await import("./vault");2096    await vault.createVault("correct-pass-12345");2097    // Every real install mints its identity with (or before) its vault, so a2098    // fixture that seeds trust state without one is an install §11.5 refuses.2099    const identity = await import("./device-identity");2100    await identity.getOrCreateDeviceId();2101    const { findPairedDeviceById, isDeviceRevoked, listDeviceRevocations, upsertPairedDevice } =2102      await import("./paired-devices");21032104    await upsertPairedDevice({2105      deviceId: "phone-1",2106      deviceName: "June's Phone",2107      deviceType: "android",2108      longTermPublicKeyHex: "a".repeat(64),2109      signingPublicKeyHex: "b".repeat(64),2110      pairedAt: 1_700_000_000_000,2111      trustSource: "direct",2112    });21132114    const res = await dispatch({2115      type: "UNPAIR_DEVICE",2116      payload: { deviceId: "phone-1" },2117    });2118    expect(res).toMatchObject({ ok: true });21192120    // The row is gone locally — re-listing must not surface it.2121    expect(await findPairedDeviceById("phone-1")).toBeNull();2122    // The revocation is recorded so a future manifest from a peer cannot2123    // resurrect this device under either the same id or the same key (MV-7 + S1).2124    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);2125    const records = await listDeviceRevocations();2126    expect(records).toHaveLength(1);2127    expect(records[0]).toMatchObject({2128      deviceId: "phone-1",2129      longTermPublicKeyHex: "a".repeat(64),2130      revokedByDeviceId: expect.any(String),2131    });2132  });2133  it("UNPAIR_DEVICE resolves its issuer after an already queued adoption rotation", async () => {2134    const vault = await import("./vault");2135    await vault.createVault("correct-pass-12345");2136    const identity = await import("./device-identity");2137    const paired = await import("./paired-devices");2138    const oldId = await identity.getOrCreateDeviceId();2139    const rotation = paired.rotatePairedDeviceIdentity(() => identity.getLocalPairingIdentity({ existingOnly: true }), identity.rotateDeviceId);2140    const removal = dispatch({ type: "UNPAIR_DEVICE", payload: { deviceId: "phone-1" } });2141    await rotation;2142    expect(await removal).toMatchObject({ ok: true });2143    const newId = await identity.getExistingDeviceId();2144    expect(newId).not.toBe(oldId);2145    expect(await paired.listDeviceRevocations()).toMatchObject([{ deviceId: "phone-1", revokedByDeviceId: newId }]);2146  });21472148  it("UNPAIR_DEVICE still evicts a peer when the local identity needs migration", async () => {2149    const vault = await import("./vault");2150    await vault.createVault("correct-pass-12345");2151    const identity = await import("./device-identity");2152    await identity.getOrCreateDeviceId();2153    delete storage.peach_local_identity_v4;2154    delete sessionStorage.peach_local_identity_session;2155    const { findPairedDeviceById, isDeviceRevoked, upsertPairedDevice } = await import("./paired-devices");2156    await upsertPairedDevice({2157      deviceId: "phone-1",2158      deviceName: "June's Phone",2159      deviceType: "android",2160      longTermPublicKeyHex: "a".repeat(64),2161      signingPublicKeyHex: "b".repeat(64),2162      pairedAt: 1_700_000_000_000,2163      trustSource: "direct",2164    });21652166    const response = await dispatch({ type: "UNPAIR_DEVICE", payload: { deviceId: "phone-1" } });21672168    expect(response).toMatchObject({ ok: true });2169    expect(await findPairedDeviceById("phone-1")).toBeNull();2170    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);2171  });21722173  it("UNPAIR_DEVICE on an unknown id is a no-op (ok) and writes no revocation", async () => {2174    const vault = await import("./vault");2175    await vault.createVault("correct-pass-12345");2176    const { listDeviceRevocations } = await import("./paired-devices");21772178    const res = await dispatch({2179      type: "UNPAIR_DEVICE",2180      payload: { deviceId: "never-paired" },2181    });2182    expect(res).toMatchObject({ ok: true });2183    // A revocation with the all-zero key sentinel is still written — the2184    // contract is that the user-intent is recorded even when the registry had2185    // no row. This is what blocks a peer from later vouched-adopting the same2186    // fresh id back in.2187    const records = await listDeviceRevocations();2188    expect(records).toHaveLength(1);2189    expect(records[0]).toMatchObject({2190      deviceId: "never-paired",2191      longTermPublicKeyHex: "0".repeat(64),2192    });2193  });21942195  it("UNPAIR_DEVICE refuses an empty payload with invalid_payload", async () => {2196    const res = await dispatch({2197      type: "UNPAIR_DEVICE",2198      payload: { deviceId: "" },2199    });2200    expect(res).toMatchObject({ ok: false, error: "invalid_payload" });2201  });2202  it("SECURE_RESET archives legacy trust, rotates identity, and reaches the new Sync anchor", async () => {2203    const vault = await import("./vault");2204    await vault.createVault("correct-pass-12345");2205    const identity = await import("./device-identity");2206    const previousDeviceId = await identity.getOrCreateDeviceId();2207    const { upsertPairedDevice } = await import("./paired-devices");2208    await upsertPairedDevice({2209      deviceId: "phone-1",2210      deviceName: "June's Phone",2211      deviceType: "android",2212      longTermPublicKeyHex: "a".repeat(64),2213      signingPublicKeyHex: "b".repeat(64),2214      pairedAt: 1_700_000_000_000,2215      trustSource: "direct",2216    });22172218    const response = await dispatch({2219      type: "SECURE_RESET",2220      payload: { password: "correct-pass-12345" },2221    });22222223    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });2224    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);2225  });2226  it("SECURE_RESET unlocks a locked real vault before rotating identity", async () => {2227    const vault = await import("./vault");2228    await vault.createVault("correct-pass-12345");2229    const identity = await import("./device-identity");2230    const previousDeviceId = await identity.getOrCreateDeviceId();2231    const { upsertPairedDevice } = await import("./paired-devices");2232    await upsertPairedDevice({2233      deviceId: "phone-1",2234      deviceName: "June's Phone",2235      deviceType: "android",2236      longTermPublicKeyHex: "a".repeat(64),2237      signingPublicKeyHex: "b".repeat(64),2238      pairedAt: 1_700_000_000_000,2239      trustSource: "direct",2240    });2241    await vault.lock();2242    expect(vault.isUnlocked()).toBe(false);22432244    const response = await dispatch({2245      type: "SECURE_RESET",2246      payload: { password: "correct-pass-12345" },2247    });22482249    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });2250    expect(vault.isUnlocked()).toBe(true);2251    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);2252  });2253  it("SECURE_RESET completes after fresh unlock when the locked spool hits identity migration", async () => {2254    const vault = await import("./vault");2255    const syncAdapter = await import("./sync-vault-adapter");2256    vault.setLockedSyncHooks({2257      refresh: syncAdapter.refreshLockedSyncSpool,2258      afterUnlock: syncAdapter.drainAndRefreshLockedSyncSpool,2259    });2260    await vault.createVault("correct-pass-12345");2261    const identity = await import("./device-identity");2262    const previousDeviceId = await identity.getOrCreateDeviceId();2263    const { upsertPairedDevice } = await import("./paired-devices");2264    await upsertPairedDevice({2265      deviceId: "phone-1",2266      deviceName: "June's Phone",2267      deviceType: "android",2268      longTermPublicKeyHex: "a".repeat(64),2269      signingPublicKeyHex: "b".repeat(64),2270      pairedAt: 1_700_000_000_000,2271      trustSource: "direct",2272    });2273    await vault.addEntry({ type: "login", title: "spooled", password: "secret" });2274    await syncAdapter.refreshLockedSyncSpool();2275    await vault.lock();2276    const { createLockedSyncVaultAdapter } = await import("./locked-sync-spool");2277    const lockedAdapter = await createLockedSyncVaultAdapter();2278    expect(lockedAdapter).not.toBeNull();2279    await lockedAdapter!.applyEntries({ remote: "AA==" }, { remote: Date.now() + 1 });2280    delete storage.peach_local_identity_v4;2281    delete sessionStorage.peach_local_identity_session;2282    const sessionSet = chrome.storage.session.set as unknown as ReturnType<typeof vi.fn>;2283    sessionSet.mockImplementation(async (next: Record<string, unknown>) => {2284      if (Object.hasOwn(next, "peach_local_identity_session")) {2285        throw new Error("QUOTA_BYTES");2286      }2287      Object.assign(sessionStorage, next);2288    });22892290    const unlocked = await dispatch({2291      type: "UNLOCK",2292      payload: { password: "correct-pass-12345" },2293    });2294    const pairSecrets = await import("./pair-secrets");2295    const root = Uint8Array.from((vault.getRootKeyHex() ?? "").match(/../g)!, (part) => Number.parseInt(part, 16));2296    await pairSecrets.setPairSecret("phone-1", "c".repeat(64), root);2297    root.fill(0);2298    expect(storage.peach_pair_secrets_v1).toBeDefined();2299    expect(sessionStorage.peach_pair_secrets_session).toBeDefined();2300    expect(unlocked).toMatchObject({ ok: true });23012302    const response = await dispatch({2303      type: "SECURE_RESET",2304      payload: { password: "correct-pass-12345" },2305    });23062307    expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });2308    expect(storage.peach_local_identity_v4).toBeDefined();2309    expect(storage.peach_paired_devices_v3).toBeUndefined();2310    expect(storage.peach_pair_secrets_v1).toBeUndefined();2311    expect(sessionStorage.peach_pair_secrets_session).toBeUndefined();2312    expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);2313  });2314  // The old "fresh direct re-pair clears the old revocation" test dispatched2315  // COMPLETE_PAIRING, a handler deleted on 2026-08-04 (no legitimate senders;2316  // adoption runs in-background via relay-adoption-bg.ts). The live2317  // revocation-overlap repair is pinned in paired-devices.test.ts2318  // (repairPairedRevocationOverlaps, runs at service-worker boot).2319  it("F1: privileged handlers reject content-script senders but keep extension-page senders (Codex Security 2026-08-04)", async () => {2320    const vault = await import("./vault");2321    await vault.createVault("correct-pass-12345");2322    const contentScriptSender = {2323      id: "peach-extension",2324      url: "https://evil.example/page",2325    };2326    const extensionPageSender = {2327      id: "peach-extension",2328      url: "chrome-extension://peach-extension/popup.html",2329    };2330    const completion = { requestId: 1, rpId: "evil.example" };23312332    // Content-script senders must never reach the gated passkey-store handler.2333    await expect(2334      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, contentScriptSender)2335    ).resolves.toMatchObject({ ok: false, error: "invalid_sender" });23362337    // Extension-page senders still reach it — refused by the pending-ceremony2338    // binding, not by the sender gate.2339    await expect(2340      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2341    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });2342  });23432344  it("F2: COMPLETE_FIREFOX_PASSKEY_CREATE must match the pending ceremony (Codex Security 2026-08-04)", async () => {2345    const vault = await import("./vault");2346    await vault.createVault("correct-pass-12345");2347    const extensionPageSender = {2348      id: "peach-extension",2349      url: "chrome-extension://peach-extension/popup.html",2350    };2351    const completion = {2352      requestId: 123,2353      rpId: "example.com",2354      rpName: "Example",2355      userName: "june",2356      userHandle: "BBBB",2357      credentialId: "cred-1",2358      publicKeyCose: "c3BraQ",2359      algorithm: -7 as const,2360    };23612362    // No pending ceremony at all -> refuse.2363    await expect(2364      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2365    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });23662367    // Seed a background-minted pending ceremony.2368    sessionStorage.passkey_pending_firefox = {2369      requestId: 123,2370      type: "create",2371      rpId: "example.com",2372      rpName: "Example",2373      userName: "june",2374      browser: "firefox",2375      challenge: "AAAA",2376      userHandle: "BBBB",2377    };23782379    // Mismatched userHandle (attacker-forged completion) -> refuse.2380    await expect(2381      dispatch(2382        { type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: { ...completion, userHandle: "CCCC" } },2383        extensionPageSender2384      )2385    ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });23862387    // Matching completion -> stored.2388    await expect(2389      dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2390    ).resolves.toMatchObject({ ok: true });2391    const entries = await dispatch({ type: "GET_ENTRIES" });2392    expect(entries).toMatchObject({ ok: true });2393    const stored = (entries as { data: Array<{ passkey?: { credentialId?: string } }> }).data;2394    expect(stored.some((entry) => entry.passkey?.credentialId === "cred-1")).toBe(true);2395  });23962397  it("F2: INITIATE_FIREFOX_PASSKEY_CREATE rejects an rpId the caller origin does not own (Codex Security 2026-08-04)", async () => {2398    await expect(2399      dispatch(2400        {2401          type: "INITIATE_FIREFOX_PASSKEY_CREATE",2402          payload: { rpId: "bank.example", rpName: "Bank", userName: "june" },2403        },2404        { id: "peach-extension", url: "https://evil.example/page" }2405      )2406    ).resolves.toMatchObject({ ok: false, error: "rpid_origin_mismatch" });2407  });24082409  it("after UNPAIR_DEVICE, a fresh id carrying the same revoked key is also refused (S1)", async () => {2410    // The cross-manifest refusal is exercised end-to-end in sync-vault-adapter.test.ts;2411    // here we just pin the storage-level invariant the UNPAIR_DEVICE call2412    // establishes, since the rest of the testbed's revoke coverage rides on2413    // this state.2414    const vault = await import("./vault");2415    await vault.createVault("correct-pass-12345");2416    const { isDeviceRevoked, revokeDeviceById, upsertPairedDevice } = await import(2417      "./paired-devices"2418    );24192420    await upsertPairedDevice({2421      deviceId: "phone-1",2422      deviceName: "June's Phone",2423      deviceType: "android",2424      longTermPublicKeyHex: "a".repeat(64),2425      signingPublicKeyHex: "b".repeat(64),2426      pairedAt: 1_700_000_000_000,2427      trustSource: "direct",2428    });24292430    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(false);2431    await revokeDeviceById("phone-1", "self");2432    // The key check is what blocks a re-vouch under a fresh id.2433    expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);2434    expect(await isDeviceRevoked("fresh-id", "a".repeat(64))).toBe(true);2435  });24362437  // --- LV-4: GET_RECOVERY_WORDS requires a fresh password proof ---24382439  it("LV-4: GET_RECOVERY_WORDS without a password returns password_required", async () => {2440    const vault = await import("./vault");2441    await vault.createVault("correct-pass-12345");24422443    const res = await dispatch({ type: "GET_RECOVERY_WORDS", payload: {} });2444    expect(res).toMatchObject({ ok: false, error: "password_required" });2445  });24462447  it("LV-4: GET_RECOVERY_WORDS with a wrong password returns wrong_password and no words", async () => {2448    const vault = await import("./vault");2449    await vault.createVault("correct-pass-12345");24502451    const res = await dispatch({2452      type: "GET_RECOVERY_WORDS",2453      payload: { password: "not-the-password" },2454    });2455    expect(res).toMatchObject({ ok: false, error: "wrong_password" });2456    expect(res.data).toBeUndefined();2457  });24582459  it("LV-4: GET_RECOVERY_WORDS with the correct password returns 12 words", async () => {2460    const vault = await import("./vault");2461    await vault.createVault("correct-pass-12345");24622463    const res = await dispatch({2464      type: "GET_RECOVERY_WORDS",2465      payload: { password: "correct-pass-12345" },2466    });2467    expect(res.ok).toBe(true);2468    expect((res.data as string[]).length).toBe(12);2469  });24702471  it("PB-26-311: cleartext export requires a fresh master-password proof", async () => {2472    const vault = await import("./vault");2473    await vault.createVault("correct-pass-12345");24742475    await expect(2476      dispatch({ type: "EXPORT_ENTRIES" as never, payload: {} }),2477    ).resolves.toMatchObject({ ok: false, error: "password_required" });2478    await expect(2479      dispatch({2480        type: "EXPORT_ENTRIES" as never,2481        payload: { password: "not-the-password" },2482      }),2483    ).resolves.toMatchObject({ ok: false, error: "wrong_password" });2484    await expect(2485      dispatch({2486        type: "EXPORT_ENTRIES" as never,2487        payload: { password: "correct-pass-12345" },2488      }),2489    ).resolves.toMatchObject({ ok: true, data: [] });2490  });24912492  it("GET_PIN_STATUS reports only a session-available PIN wrapper", async () => {2493    const vault = await import("./vault");2494    const password = "correct-pass-12345";2495    const popupSender = {2496      id: "peach-extension",2497      url: "chrome-extension://peach-extension/src/popup/index.html",2498    } as chrome.runtime.MessageSender;24992500    await vault.createVault(password);2501    await vault.setupPinUnlock(password, "1234");2502    await vault.lock();25032504    await expect(dispatch({ type: "GET_PIN_STATUS" }, popupSender)).resolves.toMatchObject({2505      ok: true,2506      data: { configured: true, available: true, attemptsRemaining: 3 },2507    });2508  });2509});