import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; function deferred() { let resolve!: (value: T) => void; const promise = new Promise((done) => { resolve = done; }); return { promise, resolve }; } type RangeResponse = { ok: boolean; text: () => Promise }; const suffix = "1E4C9B93F3F0682250B6CF8331B7EE68FD8"; const response = (count: number): RangeResponse => ({ ok: true, text: async () => `${suffix}:${count}` }); describe("PB-26-947 breach result ownership", () => { let vault: typeof import("./vault"); let fetchMock: ReturnType; let stored: Record; beforeEach(async () => { vi.resetModules(); stored = { peach_settings: { breachMonitoring: false } }; const local = { get: vi.fn(async (key?: string | string[]) => key === undefined ? { ...stored } : Object.fromEntries((typeof key === "string" ? [key] : key).map((k) => [k, stored[k]]))), set: vi.fn(async (next: Record) => { Object.assign(stored, next); }), remove: vi.fn(async (keys: string | string[]) => { for (const key of typeof keys === "string" ? [keys] : keys) delete stored[key]; }), }; vi.stubGlobal("chrome", { storage: { local, session: { get: vi.fn(async () => ({})), set: vi.fn(async () => {}), remove: vi.fn(async () => {}) } }, alarms: { clear: vi.fn(), create: vi.fn(), onAlarm: { addListener: vi.fn() } }, idle: { setDetectionInterval: vi.fn(), onStateChanged: { addListener: vi.fn() } }, runtime: { sendMessage: vi.fn(async () => {}) }, }); fetchMock = vi.fn(async () => { throw new Error("offline"); }); vi.stubGlobal("fetch", fetchMock); vault = await import("./vault"); await vault.createVault("breach-test-pass"); await vault.updateSettings({ breachMonitoring: false }); }); afterEach(async () => { await vault.lock(); vi.useRealTimers(); vi.unstubAllGlobals(); }); async function entry() { return vault.addEntry({ type: "login", title: "Example", url: "https://example.com", password: "password", breach: 12 }); } async function enable() { await vault.updateSettings({ breachMonitoring: true }); } it("keeps the known warning while a changed password lookup is pending or unavailable", async () => { const item = await entry(); await enable(); const pending = deferred(); fetchMock.mockReturnValueOnce(pending.promise); await vault.updateEntry(item.id, { password: "new-password" }); expect(vault.getEntryById(item.id)?.breach).toBe(12); pending.resolve({ ok: false, text: async () => "" }); await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); await new Promise((resolve) => setTimeout(resolve, 20)); expect(vault.getEntryById(item.id)?.breach).toBe(12); }); it.each(["edit", "delete", "lock"])("ignores a delayed add result after %s", async (change) => { await enable(); const pending = deferred(); fetchMock.mockReturnValueOnce(pending.promise); const item = await entry(); await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); await vault.updateSettings({ breachMonitoring: false }); if (change === "edit") await vault.updateEntry(item.id, { password: "different" }); if (change === "delete") await vault.deleteEntry(item.id); if (change === "lock") { await vault.lock(); await vault.unlock("breach-test-pass"); } pending.resolve(response(99)); await new Promise((resolve) => setTimeout(resolve, 30)); const current = vault.getEntryById(item.id); expect(current?.breach).not.toBe(99); }); it("checks only actual password edits", async () => { const item = await entry(); await enable(); await vault.updateEntry(item.id, { password: "password", title: "Renamed" }); expect(fetchMock).not.toHaveBeenCalled(); expect(vault.getEntryById(item.id)?.breach).toBe(12); }); it("acknowledges and coalesces a background scan before its lookup resolves", async () => { const item = await entry(); const pending = deferred(); fetchMock.mockReturnValueOnce(pending.promise); const started = vault.startBreachScan(); expect(started).toMatchObject({ state: "running", total: 1, scanned: 0 }); expect(vault.startBreachScan().id).toBe(started.id); await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); pending.resolve(response(7)); await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete")); expect(vault.getBreachScanStatus()).toMatchObject({ scanned: 1, breached: 1, unknown: 0, unapplied: 0, cancelled: 0 }); expect(vault.getEntryById(item.id)?.breach).toBe(7); expect(JSON.stringify(vault.getBreachScanStatus())).not.toContain(item.id); expect(JSON.stringify(vault.getBreachScanStatus())).not.toContain("password"); }); it("counts unknown without clearing a known warning", async () => { const item = await entry(); vault.startBreachScan(); await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete")); expect(vault.getBreachScanStatus()).toMatchObject({ total: 1, scanned: 0, unknown: 1, breached: 0 }); expect(vault.getEntryById(item.id)?.breach).toBe(12); }); it("counts stale passwords separately from unavailable lookups", async () => { const item = await entry(); const pending = deferred(); fetchMock.mockReturnValueOnce(pending.promise); vault.startBreachScan(); await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); await vault.updateEntry(item.id, { password: "different" }); pending.resolve(response(77)); await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete")); expect(vault.getBreachScanStatus()).toMatchObject({ scanned: 0, unknown: 0, unapplied: 1 }); expect(vault.getEntryById(item.id)?.breach).toBe(12); }); it("prevents an older automatic zero overwriting a newer positive for the same password", async () => { await enable(); const old = deferred(); const recent = deferred(); fetchMock.mockReturnValueOnce(old.promise).mockReturnValueOnce(recent.promise); const item = await entry(); await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); vault.startBreachScan(); await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2)); recent.resolve(response(25)); await vi.waitFor(() => expect(vault.getEntryById(item.id)?.breach).toBe(25)); old.resolve(response(0)); await new Promise((resolve) => setTimeout(resolve, 30)); expect(vault.getEntryById(item.id)?.breach).toBe(25); }); it("aborts on lock and hides prior session counts after unlocking", async () => { await entry(); const pending = deferred(); fetchMock.mockReturnValueOnce(pending.promise); vault.startBreachScan(); await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); const signal = fetchMock.mock.calls[0][1].signal as AbortSignal; await vault.lock(); expect(signal.aborted).toBe(true); expect(vault.getBreachScanStatus()).toMatchObject({ state: "cancelled", total: 0 }); await vault.unlock("breach-test-pass"); expect(vault.getBreachScanStatus()).toMatchObject({ state: "idle", total: 0 }); pending.resolve(response(99)); await new Promise((resolve) => setTimeout(resolve, 30)); expect(vault.getEntries()[0].breach).toBe(12); }); it("does not apply a delayed scan result after the vault key changes", async () => { const item = await entry(); const pending = deferred(); fetchMock.mockReturnValueOnce(pending.promise); vault.startBreachScan(); await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); const signal = fetchMock.mock.calls[0][1].signal as AbortSignal; expect(await vault.changePassword("breach-test-pass", "changed-breach-test-pass")).toBe(true); expect(signal.aborted).toBe(true); expect(vault.getBreachScanStatus()).toMatchObject({ state: "idle", total: 0, scanned: 0, breached: 0, unknown: 0, unapplied: 0, cancelled: 0, }); pending.resolve(response(99)); await new Promise((resolve) => setTimeout(resolve, 30)); expect(vault.getEntryById(item.id)?.breach).toBe(12); expect(vault.getBreachScanStatus()).toMatchObject({ state: "idle", total: 0, scanned: 0, breached: 0, unknown: 0, unapplied: 0, cancelled: 0, }); }); it("does not count empty or non-login entries as scanned", async () => { await vault.addEntry({ type: "note", title: "Note", password: "password" }); expect(vault.startBreachScan()).toMatchObject({ state: "complete", total: 0, scanned: 0 }); expect(fetchMock).not.toHaveBeenCalled(); }); it("clears a known warning only after a valid zero lookup", async () => { const item = await entry(); fetchMock.mockResolvedValueOnce(response(0)); vault.startBreachScan(); await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete")); expect(vault.getEntryById(item.id)?.breach).toBe(0); expect(vault.getBreachScanStatus()).toMatchObject({ scanned: 1, unknown: 0, breached: 0 }); await vault.lock(); await vault.unlock("breach-test-pass"); expect(vault.getEntryById(item.id)?.breach).toBe(0); }); it("rolls back a rejected breach write without clearing the known warning", async () => { const item = await entry(); const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); const set = vi.mocked(chrome.storage.local.set); const original = set.getMockImplementation()!; set.mockImplementation(async (next) => { if ("peach_vault_a" in next) throw new Error("storage unavailable"); return original(next, () => {}); }); fetchMock.mockResolvedValueOnce(response(0)); vault.startBreachScan(); await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete")); expect(vault.getEntryById(item.id)?.breach).toBe(12); expect(vault.getBreachScanStatus()).toMatchObject({ scanned: 0, unknown: 1 }); expect(warn).toHaveBeenCalled(); warn.mockRestore(); }); it("handles a detached breach persistence failure", async () => { const item = await entry(); const pending = deferred(); await enable(); fetchMock.mockReturnValueOnce(pending.promise); await vault.updateEntry(item.id, { password: "new-password" }); const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); const set = vi.mocked(chrome.storage.local.set); const original = set.getMockImplementation()!; set.mockImplementation(async (next) => { if ("peach_vault_a" in next) throw new Error("storage unavailable"); return original(next, () => {}); }); pending.resolve(response(0)); await vi.waitFor(() => expect(warn).toHaveBeenCalled()); expect(vault.getEntryById(item.id)?.breach).toBe(12); warn.mockRestore(); }); it.each(["edit", "delete", "lock"])("ignores a delayed password-edit result after %s", async (change) => { const item = await entry(); await enable(); const pending = deferred(); fetchMock.mockReturnValueOnce(pending.promise); await vault.updateEntry(item.id, { password: "password2" }); await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); await vault.updateSettings({ breachMonitoring: false }); if (change === "edit") await vault.updateEntry(item.id, { password: "password3" }); if (change === "delete") await vault.deleteEntry(item.id); if (change === "lock") { await vault.lock(); await vault.unlock("breach-test-pass"); } // A valid range for the new password also means a conclusive zero for password2. pending.resolve(response(77)); await new Promise((resolve) => setTimeout(resolve, 30)); expect(vault.getEntryById(item.id)?.breach).not.toBe(0); expect(vault.getEntryById(item.id)?.breach).not.toBe(77); }); it("does not expose a real scan in a directly unlocked decoy session", async () => { await vault.setupDuress("decoy-pass"); await entry(); const pending = deferred(); fetchMock.mockReturnValueOnce(pending.promise); vault.startBreachScan(); await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); const signal = fetchMock.mock.calls[0][1].signal as AbortSignal; expect(await vault.unlock("decoy-pass")).toBe(true); expect(signal.aborted).toBe(true); expect(vault.getBreachScanStatus()).toMatchObject({ state: "idle", total: 0 }); expect(vault.startBreachScan()).toMatchObject({ state: "complete", total: 0 }); pending.resolve(response(99)); await new Promise((resolve) => setTimeout(resolve, 30)); expect(vault.getEntries()).toHaveLength(0); }); it("continues beyond the bridge deadline and accounts for mixed outcomes", async () => { await entry(); await vault.addEntry({ type: "login", title: "Other", password: "password" }); const pending = deferred(); fetchMock.mockReturnValueOnce(pending.promise).mockRejectedValueOnce(new Error("offline")); const start = vault.startBreachScan(); await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); vi.useFakeTimers(); await vi.advanceTimersByTimeAsync(6000); expect(vault.getBreachScanStatus()).toMatchObject({ id: start.id, state: "running", scanned: 0 }); pending.resolve(response(7)); await vi.advanceTimersByTimeAsync(1000); await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete")); expect(vault.getBreachScanStatus()).toMatchObject({ total: 2, scanned: 1, breached: 1, unknown: 1, unapplied: 0 }); }); it("does not let cancelled work replace a new session scan", async () => { await entry(); await vault.addEntry({ type: "login", title: "Queued", password: "password" }); const pending = deferred(); fetchMock.mockReturnValueOnce(pending.promise); const first = vault.startBreachScan(); await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); await vault.lock(); await vault.unlock("breach-test-pass"); fetchMock.mockResolvedValue(response(4)); const next = vault.startBreachScan(); expect(next.id).not.toBe(first.id); await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete")); pending.resolve(response(99)); await new Promise((resolve) => setTimeout(resolve, 30)); expect(vault.getBreachScanStatus()).toMatchObject({ id: next.id, scanned: 2, breached: 2 }); expect(vault.getEntries().every((item) => item.breach === 4)).toBe(true); expect(fetchMock).toHaveBeenCalledTimes(3); }); });