0f81e2f6c7e6
wip: hand off breach scan candidate with failing type and disposal checks (v5.3.25)
- time
- 2026-11-22 18:31 UTC · 5 days ago
- machine
- Junes-MacBook-Pro.local
- agent
- gpt-6
- session
- remediate interim audit findings
- parent
- 9a1ce208ee40
↓ peach-browser-0f81e2f6.tar.gzatlas at this save
files changed17 files
manifest.firefox.json+1 −1manifest.json+1 −1package.json+1 −1src/background/message-policy.test.ts+1 −1src/background/message-policy.ts+1 −0src/background/messages.autolock-refresh.test.ts+8 −0src/background/messages.test.ts+12 −16src/background/messages.ts+5 −17src/background/vault.breach.test.ts+277 −0src/background/vault.hibp-padding.test.ts+36 −1src/background/vault.ts+184 −50src/popup/views/Health.test.tsx+105 −0src/popup/views/Health.tsx+11 −14src/popup/views/Settings.tsx+8 −22src/popup/views/breach-scan.ts+71 −0src/popup/views/contracts.test.tsx+12 −0src/shared/types.ts+13 −1manifest.firefox.json+1 −1
@@ -1,7 +1,7 @@11 {22 "manifest_version": 3,33 "name": "Peach Password Manager",4- "version": "5.3.24",4+ "version": "5.3.25",55 "description": "Zero-knowledge password manager",66 "browser_specific_settings": {77 "gecko": {manifest.json+1 −1
@@ -2,7 +2,7 @@22 "manifest_version": 3,33 "minimum_chrome_version": "116",44 "name": "Peach Password Manager",5- "version": "5.3.24",5+ "version": "5.3.25",66 "description": "Zero-knowledge password manager",77 "action": {88 "default_popup": "src/popup/index.html",package.json+1 −1
@@ -1,6 +1,6 @@11 {22 "name": "peach",3- "version": "5.3.24",3+ "version": "5.3.25",44 "description": "Zero-knowledge password manager",55 "license": "GPL-3.0-only",66 "type": "module",src/background/message-policy.test.ts+1 −1
@@ -17,7 +17,7 @@1717 "BATCH_ADD_ENTRIES", "RESTORE_ENTRIES", "CLEAR_VAULT_ENTRIES", "UPDATE_ENTRY", "ADD_ADDITIONAL_URL",1818 "REQUEST_REMEMBER_SITE",1919 "DELETE_ENTRY", "CHECK_SAVE_CREDENTIAL", "AUTOFILL_QUERY", "COPY", "CREATE_VAULT", "CREATE_VAULT_FROM_ROOT_KEY",20- "GET_ENTRY_FOR_FILL", "GET_ENTRY_FOR_EDIT", "CHECK_ALL_BREACHES", "GET_SETTINGS", "UPDATE_SETTINGS",20+ "GET_ENTRY_FOR_FILL", "GET_ENTRY_FOR_EDIT", "CHECK_ALL_BREACHES", "GET_BREACH_SCAN_STATUS", "GET_SETTINGS", "UPDATE_SETTINGS",2121 "SETUP_PIN", "DISABLE_PIN", "FIRE_CANARY_PING", "ACTIVATE_LICENSE", "GET_LICENSE", "GET_LICENSE_KEY",2222 "IS_DURESS_ENABLED", "SETUP_DURESS", "DISABLE_DURESS", "VERIFY_MAIN_PASSWORD", "CHANGE_PASSWORD",2323 "GET_SITE_PASSWORD_POLICY", "GET_LOCAL_IDENTITY", "LIST_PAIRED_DEVICES", "RENAME_PAIRED_DEVICE",src/background/message-policy.ts+1 −0
@@ -38,6 +38,7 @@3838 CREATE_VAULT: "extension-page-only",3939 CREATE_VAULT_FROM_ROOT_KEY: "extension-page-only",4040 CHECK_ALL_BREACHES: "extension-page-only",41+ GET_BREACH_SCAN_STATUS: "extension-page-only",4142 UPDATE_SETTINGS: "extension-page-only",4243 SETUP_PIN: "extension-page-only",4344 DISABLE_PIN: "extension-page-only",src/background/messages.autolock-refresh.test.ts+8 −0
@@ -111,6 +111,14 @@111111 expect(alarmCreations()).toBe(0);112112 });113113 114+ it("breach scan polling does not reschedule the lock alarm", async () => {115+ (chrome.alarms.create as unknown as ReturnType<typeof vi.fn>).mockClear();116+ for (let i = 0; i < 10; i++) {117+ await messages.handleMessage({ type: "GET_BREACH_SCAN_STATUS" }, { url: "chrome-extension://test-extension-id/popup.html" });118+ }119+ expect(alarmCreations()).toBe(0);120+ });121+114122 it("an extension-page TOUCH_AUTO_LOCK reschedules the lock alarm", async () => {115123 (chrome.alarms.create as unknown as ReturnType<typeof vi.fn>).mockClear();116124 src/background/messages.test.ts+12 −16
@@ -686,25 +686,21 @@686686 });687687 });688688 689- it("CHECK_ALL_BREACHES updates matching entries without corrupting the vault", async () => {690- vi.useFakeTimers();689+ it("CHECK_ALL_BREACHES acknowledges then persists its background result", async () => {691690 const vault = await import("./vault");692691 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);700-701- const responsePromise = dispatch({ type: "CHECK_ALL_BREACHES" });702- await vi.runAllTimersAsync();703- const response = await responsePromise;704-705- expect(response).toMatchObject({ ok: true, data: { [entry.id]: 7 } });692+ await vault.updateSettings({ breachMonitoring: false });693+ const entry = await vault.addEntry({ type: "login", title: "GitHub", username: "june", password: "password", url: "https://github.com" });694+ fetchMock.mockResolvedValueOnce({ ok: true, text: async () => "1E4C9B93F3F0682250B6CF8331B7EE68FD8:7" });695+ const response = await dispatch({ type: "CHECK_ALL_BREACHES" });696+ expect(response).toMatchObject({ ok: true, data: { state: "running", total: 1 } });697+ await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete"));706698 expect(vault.getEntryById(entry.id)?.breach).toBe(7);707- breachSpy.mockRestore();699+ expect(await dispatch({ type: "GET_BREACH_SCAN_STATUS" })).toMatchObject({ ok: true, data: { state: "complete", scanned: 1, breached: 1 } });700+ });701+702+ it("rejects page breach scan status requests", async () => {703+ expect(await dispatch({ type: "GET_BREACH_SCAN_STATUS" }, { id: "peach-extension", url: "https://example.com" })).toMatchObject({ ok: false, error: "invalid_sender" });708704 });709705 710706 it("rejects passkey approval from a different tab than the ceremony", async () => {src/background/messages.ts+5 −17
@@ -1228,24 +1228,11 @@12281228 return { ok: true, clearSeconds: getEffectiveClearSeconds() };12291229 }12301230 case "CHECK_ALL_BREACHES": {1231- const allEntries = vault.getEntries();1232- const results: Record<string, number> = {};1233- for (const entry of allEntries) {1234- if (entry.type === "note") continue;1235- if (!entry.password) continue;1236- results[entry.id] = await vault.checkBreach(entry.password);1237- // Small delay — be a good citizen to the HIBP API1238- await new Promise((r) => setTimeout(r, 200));1239- }1240- // Persist any non-zero counts back to entries1241- for (const [id, count] of Object.entries(results)) {1242- const entry = vault.getEntryById(id);1243- if (entry && (entry.breach ?? 0) !== count) {1244- await vault.updateEntry(id, { breach: count > 0 ? count : undefined });1245- }1246- }1247- return { ok: true, data: results };1231+ return { ok: true, data: vault.startBreachScan() };12481232 }1233+ case "GET_BREACH_SCAN_STATUS": {1234+ return { ok: true, data: vault.getBreachScanStatus() };1235+ }12491236 case "GET_SETTINGS": {12501237 const settings = await vault.ensureSettingsLoaded();12511238 if (!isPageSender(sender)) return { ok: true, data: settings };@@ -2139,6 +2126,7 @@21392126 type !== "HAS_VAULT" &&21402127 type !== "IS_UNLOCKED" &&21412128 type !== "GET_VAULT_STATUS" &&2129+ type !== "GET_BREACH_SCAN_STATUS" &&21422130 type !== "LOCK" &&21432131 type !== "UPDATE_SETTINGS" &&21442132 type !== "GET_PENDING_PASSKEY" &&src/background/vault.breach.test.ts+277 −0
@@ -0,0 +1,277 @@1+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";2+3+function deferred<T>() {4+ let resolve!: (value: T) => void;5+ const promise = new Promise<T>((done) => { resolve = done; });6+ return { promise, resolve };7+}8+9+type RangeResponse = { ok: boolean; text: () => Promise<string> };10+const suffix = "1E4C9B93F3F0682250B6CF8331B7EE68FD8";11+const response = (count: number): RangeResponse => ({ ok: true, text: async () => `${suffix}:${count}` });12+13+describe("PB-26-947 breach result ownership", () => {14+ let vault: typeof import("./vault");15+ let fetchMock: ReturnType<typeof vi.fn>;16+ let stored: Record<string, unknown>;17+18+ beforeEach(async () => {19+ vi.resetModules();20+ stored = { peach_settings: { breachMonitoring: false } };21+ const local = {22+ get: vi.fn(async (key?: string | string[]) => key === undefined ? { ...stored } : Object.fromEntries((typeof key === "string" ? [key] : key).map((k) => [k, stored[k]]))),23+ set: vi.fn(async (next: Record<string, unknown>) => { Object.assign(stored, next); }),24+ remove: vi.fn(async (keys: string | string[]) => { for (const key of typeof keys === "string" ? [keys] : keys) delete stored[key]; }),25+ };26+ vi.stubGlobal("chrome", {27+ storage: { local, session: { get: vi.fn(async () => ({})), set: vi.fn(async () => {}), remove: vi.fn(async () => {}) } },28+ alarms: { clear: vi.fn(), create: vi.fn(), onAlarm: { addListener: vi.fn() } },29+ idle: { setDetectionInterval: vi.fn(), onStateChanged: { addListener: vi.fn() } },30+ runtime: { sendMessage: vi.fn(async () => {}) },31+ });32+ fetchMock = vi.fn(async () => { throw new Error("offline"); });33+ vi.stubGlobal("fetch", fetchMock);34+ vault = await import("./vault");35+ await vault.createVault("breach-test-pass");36+ await vault.updateSettings({ breachMonitoring: false });37+ });38+39+ afterEach(async () => { await vault.lock(); vi.useRealTimers(); vi.unstubAllGlobals(); });40+41+ async function entry() {42+ return vault.addEntry({ type: "login", title: "Example", url: "https://example.com", password: "password", breach: 12 });43+ }44+45+ async function enable() { await vault.updateSettings({ breachMonitoring: true }); }46+47+ it("keeps the known warning while a changed password lookup is pending or unavailable", async () => {48+ const item = await entry();49+ await enable();50+ const pending = deferred<RangeResponse>();51+ fetchMock.mockReturnValueOnce(pending.promise);52+ await vault.updateEntry(item.id, { password: "new-password" });53+ expect(vault.getEntryById(item.id)?.breach).toBe(12);54+ pending.resolve({ ok: false, text: async () => "" });55+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));56+ await new Promise((resolve) => setTimeout(resolve, 20));57+ expect(vault.getEntryById(item.id)?.breach).toBe(12);58+ });59+60+ it.each(["edit", "delete", "lock"])("ignores a delayed add result after %s", async (change) => {61+ await enable();62+ const pending = deferred<RangeResponse>();63+ fetchMock.mockReturnValueOnce(pending.promise);64+ const item = await entry();65+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));66+ await vault.updateSettings({ breachMonitoring: false });67+ if (change === "edit") await vault.updateEntry(item.id, { password: "different" });68+ if (change === "delete") await vault.deleteEntry(item.id);69+ if (change === "lock") { await vault.lock(); await vault.unlock("breach-test-pass"); }70+ pending.resolve(response(99));71+ await new Promise((resolve) => setTimeout(resolve, 30));72+ const current = vault.getEntryById(item.id);73+ expect(current?.breach).not.toBe(99);74+ });75+76+ it("checks only actual password edits", async () => {77+ const item = await entry();78+ await enable();79+ await vault.updateEntry(item.id, { password: "password", title: "Renamed" });80+ expect(fetchMock).not.toHaveBeenCalled();81+ expect(vault.getEntryById(item.id)?.breach).toBe(12);82+ });83+ it("acknowledges and coalesces a background scan before its lookup resolves", async () => {84+ const item = await entry();85+ const pending = deferred<RangeResponse>();86+ fetchMock.mockReturnValueOnce(pending.promise);87+ const started = vault.startBreachScan();88+ expect(started).toMatchObject({ state: "running", total: 1, scanned: 0 });89+ expect(vault.startBreachScan().id).toBe(started.id);90+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));91+ pending.resolve(response(7));92+ await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete"));93+ expect(vault.getBreachScanStatus()).toMatchObject({ scanned: 1, breached: 1, unknown: 0, unapplied: 0, cancelled: 0 });94+ expect(vault.getEntryById(item.id)?.breach).toBe(7);95+ expect(JSON.stringify(vault.getBreachScanStatus())).not.toContain(item.id);96+ expect(JSON.stringify(vault.getBreachScanStatus())).not.toContain("password");97+ });98+99+ it("counts unknown without clearing a known warning", async () => {100+ const item = await entry();101+ vault.startBreachScan();102+ await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete"));103+ expect(vault.getBreachScanStatus()).toMatchObject({ total: 1, scanned: 0, unknown: 1, breached: 0 });104+ expect(vault.getEntryById(item.id)?.breach).toBe(12);105+ });106+107+ it("counts stale passwords separately from unavailable lookups", async () => {108+ const item = await entry();109+ const pending = deferred<RangeResponse>();110+ fetchMock.mockReturnValueOnce(pending.promise);111+ vault.startBreachScan();112+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));113+ await vault.updateEntry(item.id, { password: "different" });114+ pending.resolve(response(77));115+ await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete"));116+ expect(vault.getBreachScanStatus()).toMatchObject({ scanned: 0, unknown: 0, unapplied: 1 });117+ expect(vault.getEntryById(item.id)?.breach).toBe(12);118+ });119+120+ it("prevents an older automatic zero overwriting a newer positive for the same password", async () => {121+ await enable();122+ const old = deferred<RangeResponse>();123+ const recent = deferred<RangeResponse>();124+ fetchMock.mockReturnValueOnce(old.promise).mockReturnValueOnce(recent.promise);125+ const item = await entry();126+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));127+ vault.startBreachScan();128+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));129+ recent.resolve(response(25));130+ await vi.waitFor(() => expect(vault.getEntryById(item.id)?.breach).toBe(25));131+ old.resolve(response(0));132+ await new Promise((resolve) => setTimeout(resolve, 30));133+ expect(vault.getEntryById(item.id)?.breach).toBe(25);134+ });135+136+ it("aborts on lock and hides prior session counts after unlocking", async () => {137+ await entry();138+ const pending = deferred<RangeResponse>();139+ fetchMock.mockReturnValueOnce(pending.promise);140+ vault.startBreachScan();141+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));142+ const signal = fetchMock.mock.calls[0][1].signal as AbortSignal;143+ await vault.lock();144+ expect(signal.aborted).toBe(true);145+ expect(vault.getBreachScanStatus()).toMatchObject({ state: "cancelled", total: 0 });146+ await vault.unlock("breach-test-pass");147+ expect(vault.getBreachScanStatus()).toMatchObject({ state: "idle", total: 0 });148+ pending.resolve(response(99));149+ await new Promise((resolve) => setTimeout(resolve, 30));150+ expect(vault.getEntries()[0].breach).toBe(12);151+ });152+153+ it("does not count empty or non-login entries as scanned", async () => {154+ await vault.addEntry({ type: "note", title: "Note", password: "password" });155+ expect(vault.startBreachScan()).toMatchObject({ state: "complete", total: 0, scanned: 0 });156+ expect(fetchMock).not.toHaveBeenCalled();157+ });158+159+ it("clears a known warning only after a valid zero lookup", async () => {160+ const item = await entry();161+ fetchMock.mockResolvedValueOnce(response(0));162+ vault.startBreachScan();163+ await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete"));164+ expect(vault.getEntryById(item.id)?.breach).toBe(0);165+ expect(vault.getBreachScanStatus()).toMatchObject({ scanned: 1, unknown: 0, breached: 0 });166+ await vault.lock(); await vault.unlock("breach-test-pass");167+ expect(vault.getEntryById(item.id)?.breach).toBe(0);168+ });169+170+ it("rolls back a rejected breach write without clearing the known warning", async () => {171+ const item = await entry();172+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});173+ const set = vi.mocked(chrome.storage.local.set);174+ const original = set.getMockImplementation()!;175+ set.mockImplementation(async (next) => {176+ if ("peach_vault_a" in next) throw new Error("storage unavailable");177+ return original(next);178+ });179+ fetchMock.mockResolvedValueOnce(response(0));180+ vault.startBreachScan();181+ await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete"));182+ expect(vault.getEntryById(item.id)?.breach).toBe(12);183+ expect(vault.getBreachScanStatus()).toMatchObject({ scanned: 0, unknown: 1 });184+ expect(warn).toHaveBeenCalled();185+ warn.mockRestore();186+ });187+188+ it("handles a detached breach persistence failure", async () => {189+ const item = await entry();190+ const pending = deferred<RangeResponse>();191+ await enable();192+ fetchMock.mockReturnValueOnce(pending.promise);193+ await vault.updateEntry(item.id, { password: "new-password" });194+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});195+ const set = vi.mocked(chrome.storage.local.set);196+ const original = set.getMockImplementation()!;197+ set.mockImplementation(async (next) => {198+ if ("peach_vault_a" in next) throw new Error("storage unavailable");199+ return original(next);200+ });201+ pending.resolve(response(0));202+ await vi.waitFor(() => expect(warn).toHaveBeenCalled());203+ expect(vault.getEntryById(item.id)?.breach).toBe(12);204+ warn.mockRestore();205+ });206+207+ it.each(["edit", "delete", "lock"])("ignores a delayed password-edit result after %s", async (change) => {208+ const item = await entry();209+ await enable();210+ const pending = deferred<RangeResponse>();211+ fetchMock.mockReturnValueOnce(pending.promise);212+ await vault.updateEntry(item.id, { password: "password2" });213+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));214+ await vault.updateSettings({ breachMonitoring: false });215+ if (change === "edit") await vault.updateEntry(item.id, { password: "password3" });216+ if (change === "delete") await vault.deleteEntry(item.id);217+ if (change === "lock") { await vault.lock(); await vault.unlock("breach-test-pass"); }218+ // A valid range for the new password also means a conclusive zero for password2.219+ pending.resolve(response(77));220+ await new Promise((resolve) => setTimeout(resolve, 30));221+ expect(vault.getEntryById(item.id)?.breach).not.toBe(0);222+ expect(vault.getEntryById(item.id)?.breach).not.toBe(77);223+ });224+225+ it("does not expose a real scan in a directly unlocked decoy session", async () => {226+ await vault.setupDuress("decoy-pass");227+ await entry();228+ const pending = deferred<RangeResponse>();229+ fetchMock.mockReturnValueOnce(pending.promise);230+ vault.startBreachScan();231+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));232+ const signal = fetchMock.mock.calls[0][1].signal as AbortSignal;233+ expect(await vault.unlock("decoy-pass")).toBe(true);234+ expect(signal.aborted).toBe(true);235+ expect(vault.getBreachScanStatus()).toMatchObject({ state: "idle", total: 0 });236+ expect(vault.startBreachScan()).toMatchObject({ state: "complete", total: 0 });237+ pending.resolve(response(99));238+ await new Promise((resolve) => setTimeout(resolve, 30));239+ expect(vault.getEntries()).toHaveLength(0);240+ });241+242+ it("continues beyond the bridge deadline and accounts for mixed outcomes", async () => {243+ await entry();244+ await vault.addEntry({ type: "login", title: "Other", password: "password" });245+ const pending = deferred<RangeResponse>();246+ fetchMock.mockReturnValueOnce(pending.promise).mockRejectedValueOnce(new Error("offline"));247+ const start = vault.startBreachScan();248+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));249+ vi.useFakeTimers();250+ await vi.advanceTimersByTimeAsync(6000);251+ expect(vault.getBreachScanStatus()).toMatchObject({ id: start.id, state: "running", scanned: 0 });252+ pending.resolve(response(7));253+ await vi.advanceTimersByTimeAsync(1000);254+ await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete"));255+ expect(vault.getBreachScanStatus()).toMatchObject({ total: 2, scanned: 1, breached: 1, unknown: 1, unapplied: 0 });256+ });257+258+ it("does not let cancelled work replace a new session scan", async () => {259+ await entry();260+ await vault.addEntry({ type: "login", title: "Queued", password: "password" });261+ const pending = deferred<RangeResponse>();262+ fetchMock.mockReturnValueOnce(pending.promise);263+ const first = vault.startBreachScan();264+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));265+ await vault.lock(); await vault.unlock("breach-test-pass");266+ fetchMock.mockResolvedValue(response(4));267+ const next = vault.startBreachScan();268+ expect(next.id).not.toBe(first.id);269+ await vi.waitFor(() => expect(vault.getBreachScanStatus().state).toBe("complete"));270+ pending.resolve(response(99));271+ await new Promise((resolve) => setTimeout(resolve, 30));272+ expect(vault.getBreachScanStatus()).toMatchObject({ id: next.id, scanned: 2, breached: 2 });273+ expect(vault.getEntries().every((item) => item.breach === 4)).toBe(true);274+ expect(fetchMock).toHaveBeenCalledTimes(3);275+ });276+277+});src/background/vault.hibp-padding.test.ts+36 −1
@@ -1,7 +1,7 @@11 // PCH-02-007 regression tests — the HIBP k-anonymity range request must ask22 // for response padding, and the parser must stay correct on padded responses.33 4-import { beforeEach, describe, expect, it, vi } from "vitest";4+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";55 66 // SHA-1("password") = 5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD877 const PREFIX = "5BAA6";@@ -45,6 +45,8 @@4545 vi.stubGlobal("fetch", fetchMock);4646 });4747 48+ afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });49+4850 it("sends Add-Padding: true on the range request", async () => {4951 const vault = await import("./vault");5052 await vault.checkBreach("password");@@ -77,4 +79,37 @@7779 const count = await vault.checkBreach("password");7880 expect(count).toBe(0);7981 });82+ it.each(["", "not a range", `${SUFFIX}:7junk`, `${SUFFIX}:9007199254740992`, `${SUFFIX}A:7`, `${SUFFIX}:-1`, `${SUFFIX}:NaN`, `${SUFFIX}:7\ninvalid`])("reports unknown for malformed range %s", async (body) => {83+ fetchMock.mockResolvedValueOnce({ ok: true, text: async () => body });84+ const vault = await import("./vault");85+ expect(await vault.checkBreach("password")).toBeNull();86+ });87+88+ it.each(["http", "network", "body"])("reports unknown on %s failure", async (failure) => {89+ fetchMock.mockImplementationOnce(async () => {90+ if (failure === "network") throw new Error("offline");91+ return { ok: failure !== "http", text: async () => { throw new Error("body failed"); } };92+ });93+ const vault = await import("./vault");94+ expect(await vault.checkBreach("password")).toBeNull();95+ });96+97+ it.each(["fetch", "body"])("bounds a stalled %s even if transport ignores abort", async (stage) => {98+ vi.useFakeTimers();99+ const stalled = new Promise<never>(() => {});100+ fetchMock.mockImplementationOnce(() => stage === "fetch" ? stalled : Promise.resolve({ ok: true, text: () => stalled }));101+ const vault = await import("./vault");102+ const lookup = vault.checkBreach("password");103+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalled());104+ await vi.advanceTimersByTimeAsync(10_000);105+ expect(await lookup).toBeNull();106+ expect(fetchMock.mock.calls[0][1].signal.aborted).toBe(true);107+ });108+109+ it("accepts LF ranges and a trailing newline", async () => {110+ fetchMock.mockResolvedValueOnce({ ok: true, text: async () => `${SUFFIX}:9\n${"A".repeat(35)}:0\n` });111+ const vault = await import("./vault");112+ expect(await vault.checkBreach("password")).toBe(9);113+ });114+80115 });src/background/vault.ts+184 −50
@@ -24,6 +24,7 @@2424 } from "../shared/recovery-words";2525 import type {2626 AccentColorName,27+ BreachScanStatus,2728 Canary,2829 ManualSummonRecord,2930 PasskeyData,@@ -486,34 +487,177 @@486487 // HIBP breach check (k-anonymity model)487488 // ---------------------------------------------------------------------------488489 489-export async function checkBreach(password: string): Promise<number> {490- // HIBP k-anonymity API is keyed on SHA-1 prefixes — this is dictated by491- // the public API, not a security choice. Do not migrate to SHA-256 here.492- const encoder = new TextEncoder();493- const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));494- const hashHex = Array.from(new Uint8Array(hashBuffer))495- .map((b) => b.toString(16).padStart(2, "0"))496- .join("")497- .toUpperCase();498-499- const prefix = hashHex.slice(0, 5);500- const suffix = hashHex.slice(5);501-490+export async function checkBreach(password: string, signal?: AbortSignal): Promise<number | null> {491+ const controller = new AbortController();492+ let timeout: ReturnType<typeof setTimeout> | undefined;493+ let onAbort: (() => void) | undefined;502494 try {503- // PCH-02-007: request HIBP response padding so response length does not504- // reveal how many suffixes a queried prefix returned.505- const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {506- headers: { "Add-Padding": "true" },495+ const unavailable = new Promise<null>((resolve) => {496+ onAbort = () => { controller.abort(); resolve(null); };497+ signal?.addEventListener("abort", onAbort, { once: true });498+ timeout = setTimeout(onAbort, 8_000);499+ if (signal?.aborted) onAbort();507500 });508- if (!res.ok) return 0;509- const text = await res.text();510- const match = text.split("\r\n").find((l) => l.startsWith(suffix));511- return match ? parseInt(match.split(":")[1], 10) : 0;501+ const lookup = async (): Promise<number | null> => {502+ // HIBP's range API requires SHA-1; only the five-character prefix leaves the device.503+ const hash = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(password));504+ if (controller.signal.aborted) return null;505+ const hex = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, "0")).join("").toUpperCase();506+ const res = await fetch(`https://api.pwnedpasswords.com/range/${hex.slice(0, 5)}`, {507+ headers: { "Add-Padding": "true" },508+ signal: controller.signal,509+ });510+ if (!res.ok) return null;511+ const text = await res.text();512+ const lines = text.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");513+ let count = 0;514+ const seen = new Set<string>();515+ for (const line of lines) {516+ const match = /^([A-Fa-f0-9]{35}):([0-9]+)$/.exec(line);517+ if (!match) return null;518+ const suffix = match[1].toUpperCase();519+ const value = Number(match[2]);520+ if (!Number.isSafeInteger(value) || seen.has(suffix)) return null;521+ seen.add(suffix);522+ if (suffix === hex.slice(5)) count = value;523+ }524+ return count;525+ };526+ return await Promise.race([lookup(), unavailable]);512527 } catch {513- return 0; // Network unavailable — don't block528+ return null;529+ } finally {530+ clearTimeout(timeout);531+ if (onAbort) signal?.removeEventListener("abort", onAbort);514532 }515533 }516534 535+type BreachCredential = { id: string; password: string; epoch: number; key: Uint8Array };536+const breachChecks = new Map<string, symbol>();537+538+async function checkEntryBreach(credential: BreachCredential, signal?: AbortSignal): Promise<"unknown" | "unapplied" | number> {539+ const { id, password, epoch } = credential;540+ const isCurrent = () => {541+ const entry = entries.find((entry) => entry.id === id);542+ return !signal?.aborted && epoch === vaultEpoch && credential.key === derivedKey && !vaultCreatesInFlight &&543+ entry?.type === "login" && !entry.deletedAt && entry.password === password;544+ };545+ if (!isCurrent()) return "unapplied";546+ const token = Symbol();547+ breachChecks.set(id, token);548+ try {549+ const count = await checkBreach(password, signal);550+ const idx = entries.findIndex((entry) => entry.id === id);551+ const current = entries[idx];552+ if (signal?.aborted || epoch !== vaultEpoch || credential.key !== derivedKey || vaultCreatesInFlight ||553+ breachChecks.get(id) !== token || !current || current.deletedAt || current.type !== "login" || current.password !== password) return "unapplied";554+ if (count === null) return "unknown";555+ if ((current.breach ?? 0) === count) return count;556+ const owner = entries;557+ const next = { ...current, breach: count, modifiedAt: monotonicEntryTimestamp(current.modifiedAt) };558+ entries[idx] = next;559+ try {560+ await persistEntries();561+ } catch (error) {562+ if (epoch === vaultEpoch && entries === owner && entries[idx] === next && !next.deletedAt) entries[idx] = current;563+ throw error;564+ }565+ if (!isCurrent() || breachChecks.get(id) !== token) return "unapplied";566+ fireSyncTrigger("vault_change");567+ return count;568+ } finally {569+ if (breachChecks.get(id) === token) breachChecks.delete(id);570+ }571+}572+573+function checkEntryBreachDetached(credential: BreachCredential): void {574+ void checkEntryBreach(credential).catch(() => {575+ console.warn("[Peach] Could not save a breach check result");576+ });577+}578+579+function emptyBreachScan(state: BreachScanStatus["state"] = "idle"): BreachScanStatus {580+ return { id: null, state, total: 0, scanned: 0, unknown: 0, unapplied: 0, breached: 0, cancelled: 0 };581+}582+583+type BreachScan = {584+ epoch: number;585+ key: Uint8Array | null;586+ status: BreachScanStatus;587+ credentials: BreachCredential[];588+ controller: AbortController;589+};590+let breachScan: BreachScan | null = null;591+592+function cancelBreachScan(): void {593+ breachChecks.clear();594+ const scan = breachScan;595+ if (!scan) return;596+ scan.controller.abort();597+ scan.credentials.length = 0;598+ scan.key = null;599+ if (scan.status.state === "running") {600+ scan.status.cancelled = scan.status.total - scan.status.scanned - scan.status.unknown - scan.status.unapplied;601+ scan.status.state = "cancelled";602+ }603+}604+605+/// Returns aggregate progress for the current unlock session without credential data.606+export function getBreachScanStatus(): BreachScanStatus {607+ if (!derivedKey) return emptyBreachScan(breachScan ? "cancelled" : "idle");608+ if (!breachScan || breachScan.epoch !== vaultEpoch || breachScan.key !== derivedKey) return emptyBreachScan();609+ return { ...breachScan.status };610+}611+612+/// Starts a single background scan, or returns the current scan if it is still running.613+export function startBreachScan(): BreachScanStatus {614+ if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");615+ if (breachScan?.status.state === "running" && breachScan.epoch === vaultEpoch && breachScan.key === derivedKey) return getBreachScanStatus();616+ cancelBreachScan();617+ const key = derivedKey;618+ const credentials = entries.filter((entry) => !entry.deletedAt && entry.type === "login" && entry.password)619+ .map((entry) => ({ id: entry.id, password: entry.password!, epoch: vaultEpoch, key }));620+ const scan: BreachScan = {621+ epoch: vaultEpoch, key, credentials, controller: new AbortController(),622+ status: { ...emptyBreachScan(credentials.length ? "running" : "complete"), id: crypto.randomUUID(), total: credentials.length },623+ };624+ breachScan = scan;625+ void runBreachScan(scan);626+ return { ...scan.status };627+}628+629+async function runBreachScan(scan: BreachScan): Promise<void> {630+ try {631+ while (scan.credentials.length) {632+ if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) break;633+ const credential = scan.credentials.shift()!;634+ let result: "unknown" | "unapplied" | number;635+ try { result = await checkEntryBreach(credential, scan.controller.signal); }636+ catch { result = "unknown"; console.warn("[Peach] Could not save a breach scan result"); }637+ if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) break;638+ if (result === "unknown") scan.status.unknown++;639+ else if (result === "unapplied") scan.status.unapplied++;640+ else { scan.status.scanned++; if (result > 0) scan.status.breached++; }641+ if (scan.credentials.length) {642+ await new Promise<void>((resolve) => {643+ const done = () => { clearTimeout(timer); scan.controller.signal.removeEventListener("abort", done); resolve(); };644+ const timer = setTimeout(done, 200);645+ scan.controller.signal.addEventListener("abort", done, { once: true });646+ if (scan.controller.signal.aborted) done();647+ });648+ }649+ }650+ } finally {651+ scan.credentials.length = 0;652+ if (scan.status.state === "running") {653+ if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) {654+ scan.status.cancelled = scan.status.total - scan.status.scanned - scan.status.unknown - scan.status.unapplied;655+ scan.status.state = "cancelled";656+ } else scan.status.state = "complete";657+ }658+ }659+}660+517661 export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {518662 // Unreachable from the message layer, which gates on isUnlocked first.519663 const key = await cardDeclineKey();@@ -736,6 +880,7 @@736880 recoveryInFlight = true;737881 let settle!: () => void;738882 recoverySettled = new Promise<void>((resolve) => { settle = resolve; });883+ cancelBreachScan();739884 const epoch = ++vaultEpoch;740885 const check = () => {741886 if (epoch !== vaultEpoch || derivedKey) throw new Error("vault_locked");@@ -795,7 +940,8 @@795940 });796941 committed = true;797942 check();798- derivedKey = newKey;943+ cancelBreachScan();944+ derivedKey = newKey;799945 rootKey = recoveredRoot;800946 newKey = null;801947 recoveredRoot = null;@@ -1439,6 +1585,7 @@14391585 if (epoch !== vaultEpoch || vaultRemovalsInFlight) return { committed: true, unlocked: false };14401586 const previousKey = derivedKey;14411587 const previousRoot = rootKey;1588+ cancelBreachScan();14421589 publishedEpoch = ++vaultEpoch;14431590 derivedKey = nextKey;14441591 rootKey = nextRoot;@@ -1539,6 +1686,7 @@15391686 await commitCreatedVaultSlots(slotA, slotB);15401687 committed = true;15411688 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1689+ cancelBreachScan();15421690 vaultEpoch++;15431691 15441692 const previousDerivedKey = derivedKey;@@ -1728,6 +1876,7 @@17281876 if (keyB) zeroKey(keyB);17291877 return false;17301878 }1879+ cancelBreachScan();17311880 derivedKey = keyA;17321881 vaultMode = "real";17331882 entries = payloadA.entries;@@ -1800,6 +1949,7 @@18001949 if (keyA) zeroKey(keyA);18011950 return false;18021951 }1952+ cancelBreachScan();18031953 derivedKey = keyB;18041954 vaultMode = "decoy";18051955 decoySyncTeardownHook?.();@@ -1987,6 +2137,7 @@19872137 await notifyIdentitySessionEnded();19882138 if (stale()) { zeroKey(key); return false; }19892139 }2140+ cancelBreachScan();19902141 derivedKey = key;19912142 vaultMode = entry.mode;19922143 if (entry.mode === "decoy") decoySyncTeardownHook?.();@@ -2016,6 +2167,7 @@20162167 // session key once bought (sync runner re-waking to a restored vault) is20172168 // not worth an unlocked vault the user never asked to unlock; when locked,20182169 // sync-runner correctly reports VAULT_LOCKED instead.2170+ cancelBreachScan();20192171 vaultEpoch++;20202172 if (derivedKey) {20212173 zeroKey(derivedKey);@@ -2079,6 +2231,7 @@20792231 return { ok: false, error: "invalid_key" };20802232 }20812233 2234+ cancelBreachScan();20822235 derivedKey = masterKeyBytes;20832236 vaultMode = "real";20842237 entries = payload.entries;@@ -2635,6 +2788,8 @@26352788 26362789 export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {26372790 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2791+ const epoch = vaultEpoch;2792+ const key = derivedKey;26382793 26392794 const sanitized = sanitizeEntryDraft(entry);26402795 const now = Date.now();@@ -2661,18 +2816,8 @@26612816 throw err;26622817 }26632818 2664- // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)2665- if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {2666- const breachEpoch = vaultEpoch;2667- checkBreach(nextEntry.password).then(async (count) => {2668- if (count > 0 && breachEpoch === vaultEpoch && !vaultCreatesInFlight) {2669- const idx = entries.findIndex((e) => e.id === nextEntry.id);2670- if (idx !== -1) {2671- entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };2672- await persistEntries();2673- }2674- }2675- });2819+ if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password && epoch === vaultEpoch) {2820+ checkEntryBreachDetached({ id: nextEntry.id, password: nextEntry.password, epoch, key });26762821 }26772822 26782823 fireSyncTrigger("vault_change");@@ -2716,6 +2861,7 @@27162861 const current = entries[idx];27172862 const owner = entries;27182863 const epoch = vaultEpoch;2864+ const key = derivedKey;27192865 const sanitizedPatch = sanitizeEntryPatch(patch);27202866 // Refresh passwordChangedAt only when the password value actually changes —27212867 // a metadata-only update (title, tags, etc.) must not reset the age clock@@ -2769,21 +2915,8 @@27692915 throw err;27702916 }27712917 2772- // Breach check when password changes: clear immediately so old breach doesn't linger,2773- // then async-check the new password and only re-set if it's also found.2774- if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2775- entries[idx] = { ...entries[idx], breach: undefined };2776- await persistEntries();2777- const password = entries[idx].password;2778- if (password) {2779- checkBreach(password).then(async (count) => {2780- const i = entries.findIndex((e) => e.id === id);2781- if (i !== -1 && count > 0) {2782- entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2783- await persistEntries();2784- }2785- });2786- }2918+ if (passwordChanged && settings.breachMonitoring !== false && next.type === "login" && next.password && epoch === vaultEpoch) {2919+ checkEntryBreachDetached({ id, password: next.password, epoch, key });27872920 }27882921 27892922 fireSyncTrigger("vault_change");@@ -3813,6 +3946,7 @@38133946 // threw between the Slot A write and this swap, the next persistEntries()38143947 // would overwrite Slot A with old-key ciphertext, locking the user out.38153948 zeroKey(derivedKey);3949+ cancelBreachScan();38163950 derivedKey = newKey;38173951 38183952 // PCH-01-008: the MV3 session escrow still holds the OLD key. Without this,src/popup/views/Health.test.tsx+105 −0
@@ -33,6 +33,7 @@3333 dispose = undefined;3434 sendMessageMock.mockReset();3535 document.body.innerHTML = "";36+ vi.useRealTimers();3637 });3738 3839 it("opens the local entry editor from the Pro remediation queue", async () => {@@ -89,4 +90,108 @@8990 button?.click();9091 expect(onFixEntry).toHaveBeenCalledWith(expect.objectContaining({ id: "entry-1" }));9192 });93+ it("reconnects to a running scan and reports partial results without claiming clean", async () => {94+ vi.useFakeTimers();95+ const running = { id: "scan", state: "running", total: 3, scanned: 1, breached: 0, unknown: 0, unapplied: 0, cancelled: 0 };96+ sendMessageMock.mockResolvedValueOnce({ ok: true, data: running }).mockResolvedValue({ ok: true, data: { ...running, state: "complete", unknown: 1, unapplied: 1 } });97+ const refresh = vi.fn();98+ const { HealthView } = await import("./Health");99+ const mounted = renderView(<HealthView entries={[]} onFixEntry={vi.fn()} onBack={vi.fn()} onRefresh={refresh} />);100+ dispose = mounted.dispose;101+ await vi.advanceTimersByTimeAsync(0);102+ expect(mounted.container.textContent).toContain("1 of 3 checked");103+ expect(mounted.container.querySelector<HTMLButtonElement>(".peach-health-check-btn")?.disabled).toBe(true);104+ await vi.advanceTimersByTimeAsync(1000);105+ expect(mounted.container.textContent).toContain("1 unavailable");106+ expect(mounted.container.textContent).toContain("1 changed or superseded");107+ expect(mounted.container.textContent).not.toContain("All passwords clean");108+ expect(refresh).toHaveBeenCalled();109+ const calls = sendMessageMock.mock.calls.length;110+ mounted.dispose(); dispose = undefined;111+ await vi.advanceTimersByTimeAsync(5000);112+ expect(sendMessageMock.mock.calls.length).toBe(calls);113+ });114+115+ it.each(["empty", "unknown", "cancelled", "error"])("does not claim clean for %s scans", async (kind) => {116+ const status = { id: "scan", state: kind === "cancelled" ? "cancelled" : "complete", total: kind === "empty" ? 0 : 1, scanned: 0, breached: 0, unknown: kind === "unknown" ? 1 : 0, unapplied: 0, cancelled: kind === "cancelled" ? 1 : 0 };117+ sendMessageMock.mockResolvedValue(kind === "error" ? { ok: false, error: "offline" } : { ok: true, data: status });118+ const { HealthView } = await import("./Health");119+ const mounted = renderView(<HealthView entries={[]} onFixEntry={vi.fn()} onBack={vi.fn()} onRefresh={vi.fn()} />);120+ dispose = mounted.dispose;121+ await flushView();122+ expect(mounted.container.textContent).toContain(kind === "empty" ? "No passwords to check" : kind === "unknown" ? "1 unavailable" : kind === "cancelled" ? "Scan cancelled" : "Could not read breach scan status");123+ expect(mounted.container.textContent).not.toContain("All passwords clean");124+ });125+126+ it.each(["failure", "idle"])("ends polling truthfully after worker %s", async (kind) => {127+ vi.useFakeTimers();128+ const running = { id: "scan", state: "running", total: 1, scanned: 0, breached: 0, unknown: 0, unapplied: 0, cancelled: 0 };129+ sendMessageMock.mockResolvedValueOnce({ ok: true, data: running }).mockResolvedValue(kind === "failure" ? { ok: false } : { ok: true, data: { ...running, id: null, state: "idle", total: 0 } });130+ const { HealthView } = await import("./Health");131+ const mounted = renderView(<HealthView entries={[]} onFixEntry={vi.fn()} onBack={vi.fn()} onRefresh={vi.fn()} />);132+ dispose = mounted.dispose;133+ await vi.advanceTimersByTimeAsync(1000);134+ expect(mounted.container.textContent).toContain(kind === "failure" ? "Could not read breach scan status" : "Breach scan interrupted");135+ expect(mounted.container.querySelector<HTMLButtonElement>(".peach-health-check-btn")?.disabled).toBe(false);136+ const calls = sendMessageMock.mock.calls.length;137+ await vi.advanceTimersByTimeAsync(5000);138+ expect(sendMessageMock.mock.calls.length).toBe(calls);139+ });140+141+ it.each([0, 2])("reports a fully checked scan with %s breached passwords", async (breached) => {142+ sendMessageMock.mockResolvedValue({ ok: true, data: { id: "scan", state: "complete", total: 2, scanned: 2, breached, unknown: 0, unapplied: 0, cancelled: 0 } });143+ const { HealthView } = await import("./Health");144+ const mounted = renderView(<HealthView entries={[]} onFixEntry={vi.fn()} onBack={vi.fn()} onRefresh={vi.fn()} />);145+ dispose = mounted.dispose;146+ await flushView();147+ expect(mounted.container.textContent).toContain(breached ? "2 found in breaches" : "No breaches found in 2 checked passwords");148+ });149+150+ it.each([151+ { scanned: 2, total: 1 }, { breached: 1, scanned: 0 }, { unknown: -1 }, { unknown: 0.5 }, { unapplied: 2 },152+ ])("rejects inconsistent scan counters %j", async (override) => {153+ sendMessageMock.mockResolvedValue({ ok: true, data: { id: "scan", state: "complete", total: 1, scanned: 0, breached: 0, unknown: 1, unapplied: 0, cancelled: 0, ...override } });154+ const { HealthView } = await import("./Health");155+ const mounted = renderView(<HealthView entries={[]} onFixEntry={vi.fn()} onBack={vi.fn()} onRefresh={vi.fn()} />);156+ dispose = mounted.dispose;157+ await flushView();158+ expect(mounted.container.textContent).toContain("Could not read breach scan status");159+ expect(mounted.container.textContent).not.toContain("No breaches found");160+ });161+162+ it("ignores a stale mount response after a scan start and responses after disposal", async () => {163+ let mountResolve!: (value: unknown) => void;164+ let startResolve!: (value: unknown) => void;165+ sendMessageMock.mockReturnValueOnce(new Promise((resolve) => { mountResolve = resolve; }))166+ .mockReturnValueOnce(new Promise((resolve) => { startResolve = resolve; }));167+ const refresh = vi.fn();168+ const { HealthView } = await import("./Health");169+ const mounted = renderView(<HealthView entries={[]} onFixEntry={vi.fn()} onBack={vi.fn()} onRefresh={refresh} />);170+ dispose = mounted.dispose;171+ await flushView();172+ mounted.container.querySelector<HTMLButtonElement>(".peach-health-check-btn")!.click();173+ await flushView();174+ const complete = { id: "old", state: "complete", total: 1, scanned: 1, breached: 0, unknown: 0, unapplied: 0, cancelled: 0 };175+ mountResolve({ ok: true, data: complete });176+ await flushView();177+ expect(mounted.container.textContent).not.toContain("No breaches found");178+ expect(mounted.container.querySelector<HTMLButtonElement>(".peach-health-check-btn")?.disabled).toBe(true);179+ mounted.dispose(); dispose = undefined;180+ startResolve({ ok: true, data: complete });181+ await flushView();182+ expect(refresh).not.toHaveBeenCalled();183+ });184+185+ it("allows retry after a failed scan start", async () => {186+ sendMessageMock.mockResolvedValueOnce({ ok: true, data: { id: null, state: "idle", total: 0, scanned: 0, breached: 0, unknown: 0, unapplied: 0, cancelled: 0 } }).mockResolvedValue({ ok: false });187+ const { HealthView } = await import("./Health");188+ const mounted = renderView(<HealthView entries={[]} onFixEntry={vi.fn()} onBack={vi.fn()} onRefresh={vi.fn()} />);189+ dispose = mounted.dispose;190+ await flushView();191+ mounted.container.querySelector<HTMLButtonElement>(".peach-health-check-btn")!.click();192+ await flushView();193+ expect(mounted.container.textContent).toContain("Could not start breach scan");194+ expect(mounted.container.querySelector<HTMLButtonElement>(".peach-health-check-btn")?.disabled).toBe(false);195+ });196+92197 });src/popup/views/Health.tsx+11 −14
@@ -5,6 +5,7 @@55 import type { AdvancedHealthReport, VaultEntry } from "../../shared/types";66 import { getDisplayDomain } from "../../shared/domain";77 import { sendMessage } from "../App";8+import { createBreachScan } from "./breach-scan";89 import { VaultView } from "./Vault";910 1011 // Replaces the unmaintained `zxcvbn` package (LV-8; see Lock.tsx) — this file@@ -70,7 +71,7 @@7071 }7172 7273 export function HealthView(props: HealthProps) {73- const [checkingBreaches, setCheckingBreaches] = createSignal(false);74+ const breachScan = createBreachScan(() => props.onRefresh());7475 const [reusedGroups, setReusedGroups] = createSignal<ReusedGroup[]>([]);7576 const [reusedLoading, setReusedLoading] = createSignal(true);7677 const [expandedSections, setExpandedSections] = createSignal<Record<string, boolean>>({@@ -180,14 +181,6 @@180181 setExpandedSections((prev) => ({ ...prev, [key]: !prev[key] }));181182 }182183 183- async function handleCheckAllBreaches() {184- setCheckingBreaches(true);185- const res = await sendMessage({ type: "CHECK_ALL_BREACHES" });186- setCheckingBreaches(false);187- if ((res as { ok: boolean }).ok) {188- props.onRefresh();189- }190- }191184 192185 const totalNeedsAttention = createMemo(193186 () =>@@ -285,7 +278,7 @@285278 <div class="peach-health-summary">286279 <Show287280 when={totalNeedsAttention() > 0}288- fallback={<span class="peach-health-summary-ok">Your vault looks healthy.</span>}281+ fallback={<span class="peach-health-summary-ok">No known issues in saved vault data.</span>}289282 >290283 <span class="peach-health-summary-warn">291284 {totalNeedsAttention()} {totalNeedsAttention() === 1 ? "entry needs" : "entries need"} attention@@ -296,24 +289,28 @@296289 <div class="peach-health-check-row">297290 <button298291 class="peach-btn peach-btn--accent peach-btn--sm peach-health-check-btn"299- onClick={() => void handleCheckAllBreaches()}300- disabled={checkingBreaches()}292+ onClick={() => void breachScan.start()}293+ disabled={breachScan.checking()}301294 >302295 <svg width="10" height="12" viewBox="0 0 10 12" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round" style="margin-right:5px;">303296 <path d="M9 6L5 10L1 6" />304297 <path d="M5 10V2" />305298 </svg>306- {checkingBreaches() ? "checking..." : "Check all breaches now"}299+ {breachScan.checking() ? "checking..." : "Check all breaches now"}307300 </button>308301 </div>309302 303+ <Show when={breachScan.result()}>304+ <p role="status">{breachScan.result()}</p>305+ </Show>306+310307 <div class="peach-health-sections">311308 <HealthSection312309 title="Breached"313310 count={breachedEntries().length}314311 expanded={expandedSections().breached}315312 onToggle={() => toggleSection("breached")}316- emptyMessage="No breached entries"313+ emptyMessage="No known breached entries"317314 >318315 <For each={breachedEntries()}>319316 {(entry) => (src/popup/views/Settings.tsx+8 −22
@@ -1,5 +1,6 @@11 import { createEffect, createMemo, createSignal, For, Match, onCleanup, onMount, Show, Switch } from "solid-js";22 import { sendMessage } from "../App";3+import { createBreachScan } from "./breach-scan";34 import { PeachMark } from "../components/PeachMark";45 import { SyncModeSelector } from "../components/SyncModeSelector";56 import { StackDeck } from "../components/settings/StackDeck";@@ -216,8 +217,7 @@216217 triggerCelebration();217218 }218219 219- const [checkingBreaches, setCheckingBreaches] = createSignal(false);220- const [breachResult, setBreachResult] = createSignal<string | null>(null);220+ const breachScan = createBreachScan(() => props.onBreachCheckDone());221221 const [licenseInfo, setLicenseInfo] = createSignal<LicenseInfo | null>(null);222222 const [licenseKeyInput, setLicenseKeyInput] = createSignal("");223223 const [licenseError, setLicenseError] = createSignal<string | null>(null);@@ -864,20 +864,6 @@864864 }865865 }866866 867- async function handleCheckAllBreaches() {868- setCheckingBreaches(true);869- setBreachResult(null);870- const res = await sendMessage({ type: "CHECK_ALL_BREACHES" });871- setCheckingBreaches(false);872- if ((res as { ok: boolean }).ok) {873- const data = (res as { ok: boolean; data?: Record<string, number> }).data ?? {};874- const breached = Object.values(data).filter((count) => count > 0).length;875- setBreachResult(876- breached > 0 ? `${breached} password${breached > 1 ? "s" : ""} found in breaches` : "All passwords clean"877- );878- props.onBreachCheckDone();879- }880- }881867 882868 883869 async function handleSetupDuress() {@@ -1141,16 +1127,16 @@11411127 <span>Check all passwords</span>11421128 <button11431129 class="peach-btn peach-btn--subtle peach-btn--sm"1144- onClick={() => void handleCheckAllBreaches()}1145- disabled={checkingBreaches()}1130+ onClick={() => void breachScan.start()}1131+ disabled={breachScan.checking()}11461132 >1147- {checkingBreaches() ? "checking..." : "run"}1133+ {breachScan.checking() ? "checking..." : "run"}11481134 </button>11491135 </div>1150- <Show when={breachResult()}>1136+ <Show when={breachScan.result()}>11511137 <div class="peach-settings-row peach-settings-row--meta">1152- <span>Last check</span>1153- <span class="peach-settings-value">{breachResult()}</span>1138+ <span>Current check</span>1139+ <span class="peach-settings-value" role="status">{breachScan.result()}</span>11541140 </div>11551141 </Show>11561142 src/popup/views/breach-scan.ts+71 −0
@@ -0,0 +1,71 @@1+import { createMemo, createSignal, onCleanup, onMount } from "solid-js";2+import type { BreachScanStatus } from "../../shared/types";3+import { sendMessage } from "../App";4+5+function isScanStatus(value: unknown): value is BreachScanStatus {6+ if (!value || typeof value !== "object") return false;7+ const status = value as Record<string, unknown>;8+ const shaped = (status.id === null || typeof status.id === "string") &&9+ ["idle", "running", "complete", "cancelled"].includes(String(status.state)) &&10+ ["total", "scanned", "unknown", "unapplied", "breached", "cancelled"].every((field) =>11+ typeof status[field] === "number" && Number.isSafeInteger(status[field]) && Number(status[field]) >= 0);12+ if (!shaped) return false;13+ const scan = value as BreachScanStatus;14+ const accounted = scan.scanned + scan.unknown + scan.unapplied + scan.cancelled;15+ return scan.breached <= scan.scanned && accounted <= scan.total &&16+ (scan.state === "running" || accounted === scan.total) &&17+ (scan.state !== "idle" || (scan.id === null && scan.total === 0));18+}19+20+function describeScan(status: BreachScanStatus | null): string | null {21+ if (!status || status.state === "idle") return null;22+ if (!status.total) return status.state === "cancelled" ? "Scan cancelled" : "No passwords to check";23+ const details = `${status.scanned} of ${status.total} checked · ${status.breached} found in breaches · ${status.unknown} unavailable · ${status.unapplied} changed or superseded · ${status.cancelled} cancelled`;24+ if (status.state === "cancelled") return `Scan cancelled. ${details}`;25+ if (status.state === "complete" && status.scanned === status.total && status.breached === 0) {26+ return `No breaches found in ${status.scanned} checked password${status.scanned === 1 ? "" : "s"}`;27+ }28+ return details;29+}30+31+/// Keeps an extension view connected to the current background breach scan.32+export function createBreachScan(onRefresh: () => void) {33+ const [status, setStatus] = createSignal<BreachScanStatus | null>(null);34+ const [error, setError] = createSignal<string | null>(null);35+ const [starting, setStarting] = createSignal(false);36+ let timer: ReturnType<typeof setTimeout> | undefined;37+ let disposed = false;38+ let request = 0;39+40+ async function read(start = false): Promise<void> {41+ const current = ++request;42+ clearTimeout(timer);43+ if (start) setStarting(true);44+ try {45+ const response = await sendMessage({ type: start ? "CHECK_ALL_BREACHES" : "GET_BREACH_SCAN_STATUS" });46+ if (disposed || current !== request) return;47+ if (!response.ok || !isScanStatus(response.data)) {48+ setError(start ? "Could not start breach scan. Try again." : "Could not read breach scan status. Try again.");49+ return;50+ }51+ const previous = status();52+ const next = response.data;53+ setError(previous?.state === "running" && next.state === "idle" ? "Breach scan interrupted. Run it again." : null);54+ setStatus(next);55+ if (next.scanned > (previous?.id === next.id ? previous.scanned : 0)) onRefresh();56+ if (next.state === "running") timer = setTimeout(() => { void read(); }, 1000);57+ } catch {58+ if (!disposed && current === request) setError(start ? "Could not start breach scan. Try again." : "Could not read breach scan status. Try again.");59+ } finally {60+ if (!disposed && current === request) setStarting(false);61+ }62+ }63+64+ onMount(() => { void read(); });65+ onCleanup(() => { disposed = true; request++; clearTimeout(timer); });66+ return {67+ checking: createMemo(() => starting() || (status()?.state === "running" && !error())),68+ result: createMemo(() => error() ?? describeScan(status())),69+ start: () => read(true),70+ };71+}src/popup/views/contracts.test.tsx+12 −0
@@ -1111,6 +1111,18 @@11111111 expect(container.textContent).toContain("incorrect password");11121112 });11131113 1114+ it("Settings shows unavailable breach results after reconnect", async () => {1115+ sendMessageMock.mockImplementation(async (raw) => {1116+ const msg = raw as { type: string };1117+ if (msg.type === "GET_BREACH_SCAN_STATUS") return { ok: true, data: { id: "scan", state: "complete", total: 2, scanned: 1, unknown: 1, unapplied: 0, breached: 0, cancelled: 0 } };1118+ return { ok: true, data: null };1119+ });1120+ const container = mount(<SettingsView {...settingsProps()} />);1121+ await flushView();1122+ expect(container.textContent).toContain("1 unavailable");1123+ expect(container.textContent).not.toContain("All passwords clean");1124+ });1125+11141126 it("Settings requires current, new, and confirm passwords before enabling save", async () => {11151127 sendMessageMock.mockResolvedValue({ ok: true, data: null });11161128 const container = mount(src/shared/types.ts+13 −1
@@ -92,7 +92,7 @@9292 totpDigits?: number;9393 totpPeriod?: number;9494 notes?: string;95- breach?: number; // HIBP exposure count; 0 or undefined = clean — only for login entries95+ breach?: number; // Last known HIBP exposure count; absence does not prove a completed check9696 /**9797 * When the password field was last changed. Set on first-write of `password`9898 * and refreshed on every subsequent change.@@ -201,6 +201,17 @@201201 // Background-bound message types — sent from popup/content scripts,202202 // handled in src/background/messages.ts. Everything in this group must203203 // have a matching case in that file's switch statement.204+export type BreachScanStatus = {205+ id: string | null;206+ state: "idle" | "running" | "complete" | "cancelled";207+ total: number;208+ scanned: number;209+ unknown: number;210+ unapplied: number;211+ breached: number;212+ cancelled: number;213+};214+204215 export type MessageType =205216 | "CLEAR_CLIPBOARD"206217 | "GET_SYNC_ALERTS"@@ -235,6 +246,7 @@235246 | "GET_ENTRY_FOR_FILL"236247 | "GET_ENTRY_FOR_EDIT"237248 | "CHECK_ALL_BREACHES"249+ | "GET_BREACH_SCAN_STATUS"238250 | "GET_SETTINGS"239251 | "UPDATE_SETTINGS"240252 | "SETUP_PIN"