7469acdae58d
authorize canary alerts from stored entries (v5.3.20)
- time
- 2026-11-20 00:45 UTC · 1 week ago
- machine
- Junes-MacBook-Pro.local
- agent
- gpt-6
- session
- remediate interim audit findings
- parent
- 877d99382447
↓ peach-browser-7469acda.tar.gzatlas at this save
files changed19 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.test.ts+399 −102src/background/messages.ts+193 −146src/background/vault.ts+7 −6src/content/content.form-action-gate.test.ts+34 −1src/content/content.save.test.ts+40 −24src/content/index.ts+4 −25src/content/inject.ts+12 −2src/content/save.ts+27 −56src/popup/App.tsx+2 −2src/popup/copy.ts+3 −5src/popup/views/Entry.tsx+20 −9src/popup/views/Vault.tsx+3 −3src/popup/views/contracts.test.tsx+37 −8src/shared/types.ts+5 −0manifest.firefox.json+1 −1
@@ -1,7 +1,7 @@11 {22 "manifest_version": 3,33 "name": "Peach Password Manager",4- "version": "5.3.18",4+ "version": "5.3.20",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.18",5+ "version": "5.3.20",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.18",3+ "version": "5.3.20",44 "description": "Zero-knowledge password manager",55 "license": "GPL-3.0-only",66 "type": "module",src/background/message-policy.test.ts+1 −1
@@ -16,7 +16,7 @@1616 "UNLOCK", "UNLOCK_WITH_PIN", "GET_PIN_STATUS", "LOCK", "IS_UNLOCKED", "HAS_VAULT", "GET_ENTRIES", "EXPORT_ENTRIES", "ADD_ENTRY",1717 "BATCH_ADD_ENTRIES", "RESTORE_ENTRIES", "CLEAR_VAULT_ENTRIES", "UPDATE_ENTRY", "ADD_ADDITIONAL_URL",1818 "REQUEST_REMEMBER_SITE",19- "DELETE_ENTRY", "AUTOFILL_QUERY", "COPY", "CREATE_VAULT", "CREATE_VAULT_FROM_ROOT_KEY",19+ "DELETE_ENTRY", "CHECK_SAVE_CREDENTIAL", "AUTOFILL_QUERY", "COPY", "CREATE_VAULT", "CREATE_VAULT_FROM_ROOT_KEY",2020 "GET_ENTRY_FOR_FILL", "GET_ENTRY_FOR_EDIT", "CHECK_ALL_BREACHES", "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",src/background/message-policy.ts+1 −0
@@ -109,6 +109,7 @@109109 UPDATE_ENTRY: "content-script-allowed",110110 ADD_ADDITIONAL_URL: "content-script-allowed",111111 REQUEST_REMEMBER_SITE: "content-script-allowed",112+ CHECK_SAVE_CREDENTIAL: "content-script-allowed",112113 AUTOFILL_QUERY: "content-script-allowed",113114 COPY: "content-script-allowed",114115 FIRE_CANARY_PING: "content-script-allowed",src/background/messages.test.ts+399 −102
@@ -858,139 +858,436 @@858858 expect((await vault.ensureSettingsLoaded()).pinPreferred).toBe(false);859859 });860860 861- it("FIRE_CANARY_PING sends a minimal payload to allowed HTTPS webhooks", async () => {862- const response = await dispatch({863- type: "FIRE_CANARY_PING",864- payload: {865- webhookUrl: "https://example.com/hook",866- entryTitle: "GitHub",867- trigger: "password_copied",868- },861+ 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);865+866+ 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" } });869874 });870875 871- expect(response).toMatchObject({ ok: true });872- expect(fetchMock).toHaveBeenCalledWith(873- "https://example.com/hook",874- expect.objectContaining({875- method: "POST",876- headers: { "Content-Type": "application/json" },877- body: expect.any(String),878- })879- );880- const body = JSON.parse(fetchMock.mock.calls[0][1].body as string) as Record<string, unknown>;881- expect(body).toMatchObject({882- entry: "GitHub",883- trigger: "password_copied",884- source: "peach-extension",876+ 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();885884 });885+886+ 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+ });895+896+ 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+ });905+906+ 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+ });918+919+ 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+ });928+929+ 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+ });939+940+ 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+ });955+956+ 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+ });886970 });887971 888- it("LV-3: debounces a repeat non-test ping for the same webhook+entry", async () => {889- const payload = {890- webhookUrl: "https://example.com/hook",891- entryTitle: "GitHub",892- trigger: "autofilled" as const,893- };894- const first = await dispatch({ type: "FIRE_CANARY_PING", payload });895- expect(first).toMatchObject({ ok: true });896- expect(fetchMock).toHaveBeenCalledTimes(1);897- expect(Object.keys(storage).some((key) => key.includes("GitHub"))).toBe(false);898- expect(Object.keys(storage).some((key) => key.startsWith("canary-last-fetch:"))).toBe(true);972+ 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+ }899977 900- const second = await dispatch({ type: "FIRE_CANARY_PING", payload });901- expect(second).toMatchObject({ ok: true, data: { rateLimited: true } });902- expect(fetchMock).toHaveBeenCalledTimes(1); // not fired again978+ const canarySender = { id: "peach-extension", url: "https://github.com/login", tab: { id: 7 }, frameId: 0 } as chrome.runtime.MessageSender;979+980+ 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+ }903986 });904987 905- it("LV-3: removes legacy plaintext rate-limit keys", async () => {906- const legacyKey = "canary-last-fetch:https://example.com/hook:GitHub";907- storage[legacyKey] = Date.now();988+ 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+ });908995 909- await dispatch({910- type: "FIRE_CANARY_PING",911- payload: { webhookUrl: "https://example.com/hook", entryTitle: "GitHub", trigger: "autofilled" },996+ 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);9121002 });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+ });9131007 914- expect(storage[legacyKey]).toBeUndefined();1008+ 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);9151018 });9161019 917- it("LV-3: debounce is per-entry — a different entry on the same webhook still fires", async () => {918- await dispatch({919- type: "FIRE_CANARY_PING",920- payload: { webhookUrl: "https://example.com/hook", entryTitle: "GitHub", trigger: "autofilled" },1020+ 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);9211027 });922- await dispatch({923- type: "FIRE_CANARY_PING",924- payload: { webhookUrl: "https://example.com/hook", entryTitle: "GitLab", trigger: "autofilled" },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+ });1044+1045+ 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);9251052 });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+ });1058+1059+ 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+ });1066+1067+ 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+ });1074+1075+ 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+ });1083+1084+ 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+ });1089+1090+ 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+ });1103+1104+ 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+ });1112+1113+ 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+ });1121+1122+ 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+ });1135+1136+ 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+ });1142+1143+ 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);9261146 expect(fetchMock).toHaveBeenCalledTimes(2);9271147 });9281148 929- it("LV-3: test pings are exempt from the debounce", async () => {930- const payload = {931- webhookUrl: "https://example.com/hook",932- entryTitle: "GitHub",933- trigger: "test" as const,934- };935- await dispatch({ type: "FIRE_CANARY_PING", payload });936- await dispatch({ type: "FIRE_CANARY_PING", payload });1149+ 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);9371156 expect(fetchMock).toHaveBeenCalledTimes(2);1157+ expect(Object.keys(storage).filter(key => key.startsWith("canary-last-fetch:")).length).toBe(2);9381158 });9391159 940- it("rejects test pings from content scripts before contacting the webhook", async () => {941- const response = await dispatch(942- {943- type: "FIRE_CANARY_PING",944- payload: {945- webhookUrl: "https://example.com/hook",946- entryTitle: "GitHub",947- trigger: "test",948- },949- },950- {951- id: "peach-extension",952- url: "https://example.com/login",953- tab: { id: 7 },954- } as chrome.runtime.MessageSender,955- );1160+ 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+ });9561169 957- expect(response).toMatchObject({ ok: false, error: "invalid_sender" });1170+ 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" });9581173 expect(fetchMock).not.toHaveBeenCalled();9591174 });9601175 961- it("FIRE_CANARY_PING rejects insecure webhook urls", async () => {962- await expect(963- dispatch({964- type: "FIRE_CANARY_PING",965- payload: {966- webhookUrl: "http://example.com/hook",967- entryTitle: "GitHub",968- trigger: "password_copied",969- },970- })971- ).resolves.toMatchObject({ ok: false, error: "invalid_webhook_url" });1176+ 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+ });9721181 1182+ 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+ });1187+1188+ 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" });9731198 expect(fetchMock).not.toHaveBeenCalled();9741199 });9751200 976- it("F3: FIRE_CANARY_PING rejects IPv4-mapped IPv6 webhooks pointing at private ranges (Codex Security 2026-08-04)", async () => {977- for (const webhookUrl of [978- "https://[::ffff:192.168.0.1]/hook",979- "https://[::ffff:c0a8:1]/hook",980- "https://[::ffff:10.0.0.1]/hook",981- "https://[::ffff:127.0.0.1]/hook",982- "https://[::ffff:169.254.1.1]/hook",983- "https://[::ffff:172.16.0.1]/hook",984- ]) {985- await expect(986- dispatch({987- type: "FIRE_CANARY_PING",988- payload: { webhookUrl, entryTitle: "GitHub", trigger: "password_copied" },989- })990- ).resolves.toMatchObject({ ok: false, error: "invalid_webhook_url" });991- }1201+ 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+ });9921210 1211+ 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" });9931223 expect(fetchMock).not.toHaveBeenCalled();1224+ expect(vault.getEntryById(entry.id)?.canary?.webhookUrl).toBe("https://new.example/hook");1225+ });1226+1227+ 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+ });1243+1244+ 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+ });1252+1253+ 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+ });1262+1263+ 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+ });1277+1278+ 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();9941291 });9951292 9961293 it("GET_IDENTITIES when locked returns vault locked error", async () => {src/background/messages.ts+193 −146
@@ -200,13 +200,73 @@200200 // LV-3: minimum interval between non-test canary pings per webhook+entry.201201 const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour202202 203-const PRIVATE_IPV4_RANGES = [204- { prefix: "10." },205- { prefix: "127." },206- { prefix: "169.254." },207- { prefix: "192.168." },208-];203+type CanaryTrigger = "accessed" | "password_copied" | "username_copied" | "autofilled" | "submitted";204+const canaryClaims = new Map<string, { at: number; dispatched: boolean; result: Promise<MessageResponse> }>();209205 206+function fireStoredCanary(entry: VaultEntry, trigger: CanaryTrigger): Promise<MessageResponse> {207+ if (!entry.canary) return Promise.resolve({ ok: true });208+ const canary = entry.canary;209+ const webhookUrl = canaryWebhookUrl(canary.webhookUrl);210+ if (!webhookUrl) return Promise.resolve({ ok: false, error: "invalid_webhook_url" });211+ const epoch = vault.getVaultEpoch();212+ const now = Date.now();213+ const identity = JSON.stringify([entry.id, webhookUrl]);214+ const key = `${epoch}:${identity}`;215+ for (const [existingKey, claim] of canaryClaims) {216+ if (!existingKey.startsWith(`${epoch}:`) || claim.at > now || now - claim.at >= CANARY_MIN_INTERVAL_MS) canaryClaims.delete(existingKey);217+ }218+ const prior = canaryClaims.get(key);219+ // A dispatched alert stays rate-limited even when its counter write failed.220+ if (prior) return prior.result.then(result => result.ok || prior.dispatched ? { ok: true, data: { rateLimited: true } } : result);221+ const current = () => vault.isUnlocked() && epoch === vault.getVaultEpoch();222+ const unchanged = () => current() && vault.getEntryById(entry.id) === entry;223+ // Publish the claim before hashing or storage can yield to another request.224+ const result: Promise<MessageResponse> = Promise.resolve().then(async (): Promise<MessageResponse> => {225+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(identity)));226+ const suffix = Array.from(digest, byte => byte.toString(16).padStart(2, "0")).join("");227+ const rateKey = `canary-last-fetch:${suffix}`;228+ const stored = await chrome.storage.local.get(rateKey);229+ if (!unchanged()) return { ok: false, error: current() ? "entry_changed" : "vault_locked" };230+ const last = stored[rateKey];231+ if (typeof last === "number" && Number.isFinite(last) && last <= now && now - last < CANARY_MIN_INTERVAL_MS) {232+ const claim = canaryClaims.get(key);233+ if (claim) claim.at = last;234+ return { ok: true, data: { rateLimited: true } };235+ }236+ await chrome.storage.local.remove(`canary-last-fetch:${canary.webhookUrl}:${entry.title}`);237+ if (!unchanged()) return { ok: false, error: current() ? "entry_changed" : "vault_locked" };238+ // Alerts must not hold credential release hostage to webhook response time.239+ claim.dispatched = true;240+ try {241+ void fetch(webhookUrl, { method: "POST", headers: { "Content-Type": "application/json" },242+ body: canaryBody(entry.title, trigger), redirect: "error" })243+ .catch(() => console.warn("[Peach] canary alert request failed"));244+ } catch { console.warn("[Peach] canary alert request failed"); }245+ let rateWriteFailed = false;246+ try { await chrome.storage.local.set({ [rateKey]: now }); }247+ catch { rateWriteFailed = true; }248+ if (!current()) return { ok: false, error: "vault_locked" };249+ const latestCanary = vault.getEntryById(entry.id)?.canary;250+ if (!latestCanary || canaryWebhookUrl(latestCanary.webhookUrl) !== webhookUrl) return { ok: false, error: "entry_changed" };251+ const pingCount = (latestCanary.pingCount ?? 0) + 1;252+ await vault.updateEntry(entry.id, { canary: { ...latestCanary, lastPinged: now, pingCount } });253+ if (!current()) return { ok: false, error: "vault_locked" };254+ const latest = vault.getEntryById(entry.id);255+ if (!latest?.canary || canaryWebhookUrl(latest.canary.webhookUrl) !== webhookUrl ||256+ latest.canary.pingCount !== pingCount || latest.canary.lastPinged !== now) return { ok: false, error: "entry_changed" };257+ return rateWriteFailed ? { ok: false, error: "canary_update_failed" } : { ok: true };258+ }).catch((): MessageResponse => ({ ok: false, error: current() ? "canary_update_failed" : "vault_locked" }));259+ const claim = { at: now, dispatched: false, result };260+ canaryClaims.set(key, claim);261+ void result.then(reply => { if (!reply.ok && !claim.dispatched) canaryClaims.delete(key); });262+ return result;263+}264+265+function canaryBody(entryTitle: string, trigger: CanaryTrigger | "test"): string {266+ return JSON.stringify({ event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed", entry: entryTitle,267+ trigger, timestamp: new Date().toISOString(), source: "peach-extension" });268+}269+210270 export function setupMessageHandler(): void {211271 chrome.runtime.onMessage.addListener(212272 (msg: unknown, sender, sendResponse) => {@@ -680,6 +740,13 @@680740 return { ok: false, error: "origin_binding_required" };681741 }682742 }743+ if (isExtensionPageSender(sender)) {744+ const canary = (payload as { canary?: unknown }).canary;745+ if (canary !== undefined) {746+ if (!canary || typeof canary !== "object" || !canaryWebhookUrl((canary as { webhookUrl?: unknown }).webhookUrl)) return { ok: false, error: "invalid_webhook_url" };747+ payload = { ...(payload as object), canary: { ...canary, lastPinged: undefined, pingCount: undefined } };748+ }749+ }683750 const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);684751 return { ok: true, data: entry };685752 }@@ -780,6 +847,8 @@780847 // canary (`canary: undefined`) is always allowed, so existing781848 // canary entries remain manageable.782849 const incomingCanary = (patch as { canary?: unknown }).canary;850+ if (isExtensionPageSender(sender) && incomingCanary !== undefined &&851+ (!incomingCanary || typeof incomingCanary !== "object" || !canaryWebhookUrl((incomingCanary as { webhookUrl?: unknown }).webhookUrl))) return { ok: false, error: "invalid_webhook_url" };783852 if (incomingCanary && typeof incomingCanary === "object") {784853 const existing = vault.getEntryById(id);785854 if (!existing?.canary) {@@ -787,6 +856,10 @@787856 if (!gate.allowed) return { ok: false, error: "pro_required" };788857 }789858 }859+ if (isExtensionPageSender(sender) && incomingCanary && typeof incomingCanary === "object") {860+ const stored = vault.getEntryById(id)?.canary;861+ patch = { ...patch, canary: { ...incomingCanary, lastPinged: stored?.lastPinged, pingCount: stored?.pingCount } };862+ }790863 await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);791864 return { ok: true };792865 }@@ -901,6 +974,44 @@901974 );902975 return { ok: true, data: searchResults } as MessageResponse;903976 }977+ case "CHECK_SAVE_CREDENTIAL": {978+ if (!isPageSender(sender) || sender.tab?.id === undefined) return { ok: false, error: "invalid_sender" };979+ if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };980+ const domain = attestedSenderDomain(sender);981+ if (!domain) return { ok: false, error: "origin_unverified" };982+ const payload = msg.payload;983+ if (!payload || typeof payload !== "object" || Array.isArray(payload) ||984+ Object.keys(payload).some(key => key !== "username" && key !== "password")) {985+ return { ok: false, error: "invalid_payload" };986+ }987+ const { username, password } = payload as { username?: unknown; password?: unknown };988+ if (typeof username !== "string" || typeof password !== "string") return { ok: false, error: "invalid_payload" };989+ const identity = username.trim().toLowerCase();990+ const matchesIdentity = (entry: VaultEntry) => {991+ const names = [entry.username ?? "", entry.email ?? ""].map(name => name.trim().toLowerCase());992+ return identity ? names.includes(identity) : names.every(name => !name);993+ };994+ const isCandidate = (entry: VaultEntry) => !entry.deletedAt &&995+ (entry.type === undefined || entry.type === "login") && !isPasskeyOnly(entry) &&996+ entryDomains(entry.url, entry.additionalUrls).has(domain);997+ const eligible = vault.getEntries().filter(isCandidate);998+ const candidates = eligible.filter(matchesIdentity);999+ const exact = (identity ? candidates : eligible).filter(entry => entry.password === password);1000+ if (exact.length) {1001+ const epoch = vault.getVaultEpoch();1002+ const alerts = await Promise.all(exact.map(entry => fireStoredCanary(entry, "submitted")));1003+ if (!vault.isUnlocked() || epoch !== vault.getVaultEpoch()) return { ok: false, error: "vault_locked" };1004+ const failed = alerts.find(alert => !alert.ok);1005+ if (failed) return failed;1006+ if (exact.some(entry => {1007+ const current = vault.getEntryById(entry.id);1008+ return !current || !isCandidate(current) || (identity && !matchesIdentity(current)) || current.password !== password;1009+ })) return { ok: false, error: "entry_changed" };1010+ return { ok: true, data: { status: "same" } };1011+ }1012+ if (candidates.length === 1) return { ok: true, data: { status: "changed", id: candidates[0].id } };1013+ return { ok: true, data: { status: candidates.length ? "ambiguous" : "new" } };1014+ }9041015 case "AUTOFILL_QUERY": {9051016 if (!vault.isUnlocked()) {9061017 return { ok: false, error: "vault_locked" };@@ -1014,7 +1125,7 @@10141125 if (isPageSender(sender) && !senderDomain) {10151126 return { ok: false, error: "origin_unverified" };10161127 }1017- const entry = vault.getEntryById(id);1128+ let entry = vault.getEntryById(id);10181129 if (!entry) return { ok: false, error: "entry_not_found" };10191130 10201131 // MV-1: re-validate the entry against the requesting frame's origin.@@ -1034,6 +1145,21 @@10341145 // filled into a form — sign-in goes through the WebAuthn path. A10351146 // login that ALSO has a passkey is still fillable for its password.10361147 if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };1148+ if (entry.canary) {1149+ const requestedCanary = entry.canary;1150+ const epoch = vault.getVaultEpoch();1151+ const alerted = await fireStoredCanary(entry, "accessed");1152+ if (!vault.isUnlocked() || epoch !== vault.getVaultEpoch()) return { ok: false, error: "vault_locked" };1153+ if (!alerted.ok) return alerted;1154+ entry = vault.getEntryById(id);1155+ if (!entry || (senderDomain && !capabilityAuthorized && !entryDomains(entry.url, entry.additionalUrls).has(senderDomain))) {1156+ return { ok: false, error: "entry_not_found" };1157+ }1158+ if (canaryWebhookUrl(entry.canary?.webhookUrl) !== canaryWebhookUrl(requestedCanary.webhookUrl)) {1159+ return { ok: false, error: "entry_changed" };1160+ }1161+ if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };1162+ }10371163 // Strip the passkey credential AND the raw base32 TOTP seed from the10381164 // response. Content scripts never need either: the private key is the10391165 // authenticator's, and handing over the TOTP seed would let a@@ -1194,86 +1320,34 @@11941320 }11951321 return { ok: true, data: await setPasskeyProviderEnabled(enabled) };11961322 }1197- // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS1198- // endpoint. Intentional product behavior — users configure their own1199- // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private1200- // IPs, and non-HTTPS schemes, but cannot defend against every DNS-1201- // rebinding case. The UI under CanarySection (Entry.tsx) discloses to1202- // users that the entry title leaves the device when the canary fires.12031323 case "FIRE_CANARY_PING": {1204- // Canary alert fires unconditionally for any entry with canary: true.1205- // The Pro gate only governs creation/flagging of canary entries; once1206- // an entry is flagged, the alert path is a security property and must1207- // never be license-gated.1208- const { webhookUrl, entryTitle, trigger } = msg.payload as {1209- webhookUrl: string;1210- entryTitle: string;1211- trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";1324+ const payload = msg.payload;1325+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return { ok: false, error: "invalid_payload" };1326+ const { id, trigger, capability, webhookUrl: draftUrl, entryTitle } = payload as {1327+ id?: unknown; trigger?: unknown; capability?: unknown; webhookUrl?: unknown; entryTitle?: unknown;12121328 };1213- if (trigger === "test" && !isExtensionPageSender(sender)) {1214- return { ok: false, error: "invalid_sender" };1215- }1216- if (!isAllowedCanaryWebhookUrl(webhookUrl)) {1217- return { ok: false, error: "invalid_webhook_url" };1218- }1219- // LV-3: debounce non-test pings per (webhook, entry) so a page that1220- // strobes focus/fill events can't turn the canary into a request1221- // firehose at the user's endpoint. Test pings are exempt — they are1222- // explicit user clicks in the settings UI and are awaited for1223- // feedback. The FIRST ping in a window always goes out, so the1224- // dead-man's-switch property (canary fires on access) is preserved;1225- // only repeats within the window are coalesced.1226- if (trigger !== "test") {1227- const keyDigest = new Uint8Array(1228- await crypto.subtle.digest(1229- "SHA-256",1230- new TextEncoder().encode(`${webhookUrl}:${entryTitle}`),1231- ),1232- );1233- const keySuffix = Array.from(keyDigest)1234- .map((byte) => byte.toString(16).padStart(2, "0"))1235- .join("");1236- const rlKey = `canary-last-fetch:${keySuffix}`;1237- const legacyRlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;1238- const stored = await chrome.storage.local.get(rlKey);1239- await chrome.storage.local.remove(legacyRlKey);1240- const last = (stored as Record<string, unknown>)[rlKey];1241- if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {1242- return { ok: true, data: { rateLimited: true } };1243- }1244- await chrome.storage.local.set({ [rlKey]: Date.now() });1245- }1246- const body = JSON.stringify({1247- event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",1248- entry: entryTitle,1249- trigger,1250- timestamp: new Date().toISOString(),1251- source: "peach-extension",1252- });1329+ if (trigger === "test" && !isExtensionPageSender(sender)) return { ok: false, error: "invalid_sender" };1330+ if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };12531331 if (trigger === "test") {1254- // Permitted outbound fetch: user-configured canary alert endpoint1255- // (validated by isAllowedCanaryWebhookUrl above). This is the1256- // only non-HIBP outbound call in the extension — see1257- // Projects.md §3.7. Test pings are awaited so the UI can show1258- // success/failure.1332+ if (typeof entryTitle !== "string") return { ok: false, error: "invalid_payload" };1333+ const webhookUrl = canaryWebhookUrl(draftUrl);1334+ if (!webhookUrl) return { ok: false, error: "invalid_webhook_url" };12591335 try {1260- const res = await fetch(webhookUrl, {1261- method: "POST",1262- headers: { "Content-Type": "application/json" },1263- body,1264- });1265- return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1266- } catch (err) {1267- return { ok: false, error: err instanceof Error ? err.message : "network_error" };1268- }1336+ const response = await fetch(webhookUrl, { method: "POST", headers: { "Content-Type": "application/json" },1337+ body: canaryBody(entryTitle, "test"), redirect: "error" });1338+ return { ok: response.ok, error: response.ok ? undefined : `HTTP ${response.status}` };1339+ } catch { return { ok: false, error: "network_error" }; }12691340 }1270- // Non-test triggers are fire-and-forget1271- fetch(webhookUrl, {1272- method: "POST",1273- headers: { "Content-Type": "application/json" },1274- body,1275- }).catch(() => {});1276- return { ok: true };1341+ if (typeof id !== "string" || !id || typeof trigger !== "string" || !["accessed", "password_copied", "username_copied", "autofilled", "submitted"].includes(trigger) ||1342+ Object.keys(payload).some(key => !["id", "trigger", "capability"].includes(key))) return { ok: false, error: "invalid_payload" };1343+ const capabilityAuthorized = capability !== undefined && consumeSummonCapability(capability, sender, "fill");1344+ const domain = isPageSender(sender) ? attestedSenderDomain(sender) : null;1345+ if (isPageSender(sender) && !domain) return { ok: false, error: "origin_unverified" };1346+ const entry = vault.getEntryById(id);1347+ if (!entry || (domain && !capabilityAuthorized && !entryDomains(entry.url, entry.additionalUrls).has(domain))) {1348+ return { ok: false, error: "entry_not_found" };1349+ }1350+ return fireStoredCanary(entry, trigger as CanaryTrigger);12771351 }12781352 case "ACTIVATE_LICENSE": {12791353 const { key } = msg.payload as { key: string };@@ -2080,75 +2154,48 @@20802154 );20812155 }20822156 2083-function isAllowedCanaryWebhookUrl(value: string): boolean {2157+function canaryWebhookUrl(value: unknown): string | null {2158+ if (typeof value !== "string") return null;20842159 try {20852160 const url = new URL(value);2086- if (url.protocol !== "https:") return false;2087-2088- const hostname = url.hostname.toLowerCase();2089- if (2090- hostname === "localhost" ||2091- hostname.endsWith(".localhost") ||2092- isPrivateIpv4(hostname) ||2093- isPrivateIpv6(hostname)2094- ) {2095- return false;2096- }2097-2098- return true;2099- } catch {2100- return false;2101- }2161+ if (url.protocol !== "https:" || url.username || url.password) return null;2162+ const host = url.hostname.toLowerCase().replace(/\.+$/, "");2163+ if (!host || host === "localhost" || host.endsWith(".localhost")) return null;2164+ if (host.startsWith("[")) {2165+ if (isUnsafeCanaryIpv6(host.slice(1, -1))) return null;2166+ } else if (/^\d+(?:\.\d+){3}$/.test(host) && isUnsafeCanaryIpv4(host)) return null;2167+ url.hostname = host;2168+ return url.href;2169+ } catch { return null; }21022170 }21032171 2104-function isPrivateIpv4(hostname: string): boolean {2105- if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {2106- return true;2107- }2108-2109- const octets = hostname.split(".").map((part) => Number(part));2110- if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {2111- return false;2112- }2113-2114- return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;2172+function isUnsafeCanaryIpv4(host: string): boolean {2173+ const [a, b, c, d] = host.split(".").map(Number);2174+ return a === 0 || a === 10 || a === 127 || a >= 224 ||2175+ (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) ||2176+ (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) ||2177+ (a === 192 && b === 0 && c === 0 && d !== 9 && d !== 10) ||2178+ (a === 192 && b === 0 && c === 2) || (a === 192 && b === 88 && c === 99) ||2179+ (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) ||2180+ (a === 203 && b === 0 && c === 113);21152181 }21162182 2117-function isPrivateIpv6(hostname: string): boolean {2118- const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();2119- // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix2120- // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]2121- // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped2122- // tails fail closed. (Codex Security 2026-08-04 LOW,2123- // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a2124- // one-shot host check.2125- const mapped = /^::ffff:(.+)$/.exec(normalized);2126- if (mapped) {2127- const tail = mapped[1] ?? "";2128- if (tail.includes(".")) return isPrivateIpv4(tail);2129- const parts = tail.split(":");2130- const [hi, lo] = parts;2131- if (2132- parts.length !== 2 ||2133- !hi ||2134- !lo ||2135- !/^[0-9a-f]{1,4}$/.test(hi) ||2136- !/^[0-9a-f]{1,4}$/.test(lo)2137- ) {2138- return true;2139- }2140- const octets = [2141- (Number.parseInt(hi, 16) >>> 8) & 0xff,2142- Number.parseInt(hi, 16) & 0xff,2143- (Number.parseInt(lo, 16) >>> 8) & 0xff,2144- Number.parseInt(lo, 16) & 0xff,2145- ];2146- return isPrivateIpv4(octets.join("."));2183+function isUnsafeCanaryIpv6(host: string): boolean {2184+ const [head, tail = ""] = host.split("::");2185+ const left = head ? head.split(":").map(value => Number.parseInt(value, 16)) : [];2186+ const right = tail ? tail.split(":").map(value => Number.parseInt(value, 16)) : [];2187+ const words = [...left, ...Array<number>(8 - left.length - right.length).fill(0), ...right];2188+ if (words.slice(0, 5).every(word => word === 0) && words[5] === 0xffff) {2189+ return isUnsafeCanaryIpv4(`${words[6] >>> 8}.${words[6] & 255}.${words[7] >>> 8}.${words[7] & 255}`);21472190 }2148- return (2149- normalized === "::1" ||2150- normalized.startsWith("fc") ||2151- normalized.startsWith("fd") ||2152- normalized.startsWith("fe80:")2153- );2191+ // Native global-unicast literals only; transition formats are conservative exclusions.2192+ if ((words[0] & 0xe000) !== 0x2000 || words[0] === 0x2002) return true;2193+ if (words[0] === 0x3fff && (words[1] & 0xf000) === 0) return true;2194+ if (words[0] !== 0x2001) return false;2195+ if (words[1] === 0xdb8) return true;2196+ if ((words[1] & 0xfe00) !== 0) return false;2197+ const globalAssignment = words[1] === 3 || (words[1] === 4 && words[2] === 0x112) ||2198+ (words[1] & 0xfff0) === 0x20 || (words[1] & 0xfff0) === 0x30 ||2199+ (words[1] === 1 && words.slice(2, 7).every(word => word === 0) && [1, 2, 3].includes(words[7]));2200+ return !globalAssignment;21542201 }src/background/vault.ts+7 −6
@@ -2566,8 +2566,8 @@25662566 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing25672567 * exfiltration endpoint that the canary subsystem will POST entry titles25682568 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the2569- * entry. FIRE_CANARY_PING re-validates with the full SSRF guard at fire2570- * time (isAllowedCanaryWebhookUrl), so this import-time check is the2569+ * entry. FIRE_CANARY_PING revalidates the destination policy at dispatch2570+ * (canaryWebhookUrl), so this import-time check is the25712571 * outer of two gates.25722572 */25732573 function sanitizeCanary(c: unknown): Canary | undefined {@@ -2714,6 +2714,8 @@27142714 }27152715 27162716 const current = entries[idx];2717+ const owner = entries;2718+ const epoch = vaultEpoch;27172719 const sanitizedPatch = sanitizeEntryPatch(patch);27182720 // Refresh passwordChangedAt only when the password value actually changes —27192721 // a metadata-only update (title, tags, etc.) must not reset the age clock@@ -2742,15 +2744,14 @@27422744 ...(current.passwordHistory ?? []),27432745 ].slice(0, PASSWORD_HISTORY_MAX)27442746 : current.passwordHistory;2745- entries[idx] = {2747+ const next = {27462748 ...current,27472749 ...sanitizedPatch,27482750 modifiedAt: stamp,27492751 ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),27502752 };2753+ entries[idx] = next;27512754 2752-2753-27542755 // Card entries must retain their card number27552756 if (entries[idx].type === "card" && !entries[idx].cardNumber) {27562757 entries[idx] = current;@@ -2764,7 +2765,7 @@27642765 try {27652766 await persistEntries();27662767 } catch (err) {2767- entries[idx] = current;2768+ if (epoch === vaultEpoch && entries === owner && entries[idx] === next && next.modifiedAt === stamp && !next.deletedAt) entries[idx] = current;27682769 throw err;27692770 }27702771 src/content/content.form-action-gate.test.ts+34 −1
@@ -147,7 +147,7 @@147147 expect(confirm.value).toBe("");148148 });149149 150- it("refused credential fill writes no TOTP, no clipboard and no canary ping", async () => {150+ it("refused fill creates no content-side TOTP, clipboard or canary side effects", async () => {151151 const { setup, handleFieldInteraction, showSelector } = await loadSubject();152152 const { form, username, password } = setup.createLoginForm();153153 form.action = "https://evil.example/login";@@ -181,4 +181,37 @@181181 expect(setup.clipboardWrite).not.toHaveBeenCalled();182182 expect(setup.sentMessages.some((m: any) => m?.type === "FIRE_CANARY_PING")).toBe(false);183183 });184+ it("shows generic access failure without exposing a canary marker or filling secrets", async () => {185+ const { setup, handleFieldInteraction, showSelector } = await loadSubject();186+ const { username, password } = setup.createLoginForm();187+ setup.setMessageResponder((message: { type: string }) => {188+ if (message.type === "AUTOFILL_QUERY") return { ok: true, data: [{ id: "e1", title: "Acme", username: "alice" }] };189+ if (message.type === "GET_ENTRY_FOR_FILL") return { ok: false, error: "invalid_webhook_url" };190+ return { ok: true, data: null };191+ });192+ await handleFieldInteraction(password, true);193+ await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());194+ await (showSelector.mock.calls.at(-1)![2] as (id: string) => Promise<void>)("e1");195+ expect(password.value).toBe(""); expect(username.value).toBe("");196+ expect(document.body.textContent).toContain("Could not access this entry. Open Peach to check it.");197+ expect(document.body.textContent).not.toMatch(/canary|webhook|invalid_webhook_url/i);198+ });199+200+ it("successful fill leaves canary dispatch and counters to the background", async () => {201+ const { setup, handleFieldInteraction, showSelector } = await loadSubject();202+ const { form, username, password } = setup.createLoginForm();203+ form.action = `https://${location.hostname}/login`;204+ setup.setMessageResponder((message: { type?: string }) => {205+ if (message.type === "AUTOFILL_QUERY") return { ok: true, data: [{ id: "e1", title: "Acme", username: "alice" }] };206+ if (message.type === "GET_ENTRY_FOR_FILL") return { ok: true, data: { id: "e1", title: "Acme", username: "alice", password: "correct-horse", canary: { webhookUrl: "https://hooks.example/x" } } };207+ return { ok: true, data: null };208+ });209+ await handleFieldInteraction(username, true);210+ await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());211+ await (showSelector.mock.calls.at(-1)![2] as (id: string) => Promise<void>)("e1");212+ expect(username.value).toBe("alice");213+ expect(password.value).toBe("correct-horse");214+ expect(setup.sentMessages.some((message: { type?: string }) => message.type === "FIRE_CANARY_PING" || message.type === "UPDATE_ENTRY")).toBe(false);215+ });216+184217 });src/content/content.save.test.ts+40 −24
@@ -4,14 +4,14 @@44 //55 // setupSaveDetection installs a document submit listener that scrapes the66 // submitted username/password, looks up a matching vault entry7-// (AUTOFILL_QUERY → GET_ENTRY_FOR_FILL), and shows a save/update banner unless7+// (CHECK_SAVE_CREDENTIAL), and shows a save/update banner unless88 // the credentials already match. The banner itself is a CLOSED shadow root, and99 // its Save/Update buttons (which send ADD_ENTRY/UPDATE_ENTRY) are unreachable1010 // from outside — so those acceptance flows are routed to the e2e. What we pin1111 // here is the decision: does the banner mount, and is the lookup correct?1212 1313 import "./_setup";14-import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";14+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";1515 import { setupSaveDetection } from "./save";1616 import { resetChromeMock, setMessageResponder, sentMessages, makeInput } from "./_setup";1717 @@ -34,7 +34,7 @@3434 p.value = fields.pass;3535 }3636 form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));37- await new Promise((r) => setTimeout(r, 30)); // let the AUTOFILL_QUERY/GET_ENTRY roundtrip settle37+ await new Promise((r) => setTimeout(r, 30)); // let the comparison roundtrip settle3838 }3939 4040 beforeAll(() => {@@ -47,12 +47,13 @@4747 });4848 afterEach(() => {4949 document.body.innerHTML = "";50+ vi.useRealTimers();5051 });5152 5253 describe("T-SV01, T-SV03: banner mounts for new and changed credentials", () => {5354 // T-SV01: submitting credentials with no matching vault entry → save banner.5455 it("T-SV01: new credentials → save banner mounts", async () => {55- setMessageResponder((msg) => (msg.type === "AUTOFILL_QUERY" ? { ok: true, data: [] } : { ok: true, data: null }));56+ setMessageResponder((msg) => (msg.type === "CHECK_SAVE_CREDENTIAL" ? { ok: true, data: { status: "new" } } : { ok: true, data: null }));5657 await submitForm({ user: "alice", pass: "s3cret" });5758 expect(bannerHost()).not.toBeNull();5859 });@@ -60,8 +61,7 @@6061 // T-SV03: submitting a changed password for an existing entry → update banner.6162 it("T-SV03: changed password for an existing entry → banner mounts (update)", async () => {6263 setMessageResponder((msg) => {63- if (msg.type === "AUTOFILL_QUERY") return { ok: true, data: [{ id: "e1" }] };64- if (msg.type === "GET_ENTRY_FOR_FILL") return { ok: true, data: { id: "e1", title: "Acme", password: "old-password" } };64+ if (msg.type === "CHECK_SAVE_CREDENTIAL") return { ok: true, data: { status: "changed", id: "e1" } };6565 return { ok: true, data: null };6666 });6767 await submitForm({ user: "alice", pass: "new-password" });@@ -73,8 +73,7 @@7373 // T-SV02: the submitted password already matches the saved entry → no banner.7474 it("T-SV02: credentials already saved (password matches) → no banner", async () => {7575 setMessageResponder((msg) => {76- if (msg.type === "AUTOFILL_QUERY") return { ok: true, data: [{ id: "e1" }] };77- if (msg.type === "GET_ENTRY_FOR_FILL") return { ok: true, data: { id: "e1", title: "Acme", password: "s3cret" } };76+ if (msg.type === "CHECK_SAVE_CREDENTIAL") return { ok: true, data: { status: "same" } };7877 return { ok: true, data: null };7978 });8079 await submitForm({ user: "alice", pass: "s3cret" });@@ -92,7 +91,7 @@9291 form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));9392 await new Promise((r) => setTimeout(r, 30));9493 expect(bannerHost()).toBeNull();95- expect(sentMessages.some((m) => m.type === "AUTOFILL_QUERY")).toBe(false);94+ expect(sentMessages.some((m) => m.type === "CHECK_SAVE_CREDENTIAL")).toBe(false);9695 });9796 9897 // T-SV05: an empty password short-circuits before any lookup.@@ -100,24 +99,41 @@10099 setMessageResponder(() => ({ ok: true, data: [] }));101100 await submitForm({ user: "alice", pass: "" });102101 expect(bannerHost()).toBeNull();103- expect(sentMessages.some((m) => m.type === "AUTOFILL_QUERY")).toBe(false);102+ expect(sentMessages.some((m) => m.type === "CHECK_SAVE_CREDENTIAL")).toBe(false);104103 });105104 });106105 107-describe("T-SV10: domain-matched lookup (MV-1 surface)", () => {108- // T-SV10: the lookup queries AUTOFILL_QUERY with the page domain, then fetches109- // the full entry by the returned id via GET_ENTRY_FOR_FILL.110- it("T-SV10: sends AUTOFILL_QUERY{domain} then GET_ENTRY_FOR_FILL{id}", async () => {111- setMessageResponder((msg) => {112- if (msg.type === "AUTOFILL_QUERY") return { ok: true, data: [{ id: "e1" }] };113- if (msg.type === "GET_ENTRY_FOR_FILL") return { ok: true, data: { id: "e1", title: "Acme", password: "old" } };114- return { ok: true, data: null };115- });116- await submitForm({ user: "alice", pass: "new" });106+describe("background credential comparison", () => {107+ it("sends only submitted credentials and never requests a stored entry or canary ping", async () => {108+ setMessageResponder(() => ({ ok: true, data: { status: "same" } }));109+ await submitForm({ user: "alice", pass: "secret" });110+ expect(sentMessages).toContainEqual({ type: "CHECK_SAVE_CREDENTIAL", payload: { username: "alice", password: "secret" } });111+ expect(sentMessages.some(message => ["AUTOFILL_QUERY", "GET_ENTRY_FOR_FILL", "FIRE_CANARY_PING", "UPDATE_ENTRY"].includes(message.type))).toBe(false);112+ expect(bannerHost()).toBeNull();113+ });117114 118- const query = sentMessages.find((m) => m.type === "AUTOFILL_QUERY");119- expect(query?.payload?.domain).toBeTruthy();120- const fetch = sentMessages.find((m) => m.type === "GET_ENTRY_FOR_FILL");121- expect(fetch?.payload?.id).toBe("e1");115+ it.each([undefined, null, { ok: false, error: "vault_locked" }, { ok: true }, { ok: true, data: { status: "ambiguous" } }, { ok: true, data: { status: "changed" } }, { ok: true, data: { status: "unknown" } }, { ok: true, data: { status: "new", id: "unexpected" } }, { ok: true, data: { status: "changed", id: "entry", password: "unexpected" } }])("suppresses the banner for an inconclusive response: %j", async response => {116+ setMessageResponder(() => response);117+ await submitForm({ user: "alice", pass: "secret" });118+ expect(bannerHost()).toBeNull();122119 });120+121+ it("suppresses the banner when the comparison fails", async () => {122+ setMessageResponder(() => Promise.reject(new Error("disconnected")));123+ await submitForm({ user: "alice", pass: "secret" });124+ expect(bannerHost()).toBeNull();125+ });126+ it("suppresses a timed-out comparison and ignores its late response", async () => {127+ vi.useFakeTimers();128+ let resolve!: (value: unknown) => void;129+ setMessageResponder(() => new Promise(done => { resolve = done; }));130+ const submitting = submitForm({ user: "alice", pass: "secret" });131+ await vi.advanceTimersByTimeAsync(5_001);132+ await submitting;133+ expect(bannerHost()).toBeNull();134+ resolve({ ok: true, data: { status: "new" } });135+ await vi.advanceTimersByTimeAsync(0);136+ expect(bannerHost()).toBeNull();137+ });138+123139 });src/content/index.ts+4 −25
@@ -255,6 +255,7 @@255255 // explicitly picked this entry to fill on this page.256256 const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability } });257257 const r = resp as { ok: boolean; data?: { password?: string } };258+ if (!r.ok) showToast("Could not access this entry. Open Peach to check it.");258259 if (r.ok && r.data?.password) {259260 let alreadyWritten = false;260261 try {@@ -325,30 +326,6 @@325326 const gatePassed = fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain, emailEl, emailValue);326327 let filledTOTPField: HTMLInputElement | null = null;327328 328- if (entry.canary && gatePassed) {329- chrome.runtime.sendMessage({330- type: "FIRE_CANARY_PING",331- payload: {332- webhookUrl: entry.canary.webhookUrl,333- entryTitle: entry.title,334- trigger: "autofilled",335- },336- }).catch(() => {});337- chrome.runtime.sendMessage({338- type: "UPDATE_ENTRY",339- payload: {340- id: entry.id,341- patch: {342- canary: {343- ...entry.canary,344- lastPinged: Date.now(),345- pingCount: (entry.canary.pingCount ?? 0) + 1,346- },347- },348- },349- }).catch(() => {});350- }351-352329 // The background sends a freshly-generated 6-digit code (totpCode), never the353330 // base32 seed (SEV-3-C). Fill the code straight in.354331 const totpCode = (entry as { totpCode?: string }).totpCode;@@ -476,7 +453,8 @@476453 type: "GET_ENTRY_FOR_FILL",477454 payload: { id, capability },478455 });479- const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;456+ if (!(entryResponse as { ok: boolean }).ok) showToast("Could not access this entry. Open Peach to check it.");457+ const entry = (entryResponse as { ok: boolean }).ok ? (entryResponse as { data?: VaultEntry }).data : undefined;480458 if (entry) {481459 const { filledTOTPField, gatePassed } = await handleAutofill(anchorField, usernameEl, passwordEl, entry, emailEl);482460 if (gatePassed) recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);@@ -562,6 +540,7 @@562540 type: "GET_ENTRY_FOR_FILL",563541 payload: { id, capability },564542 }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;543+ if (!entryResponse?.ok) showToast("Could not access this entry. Open Peach to check it.");565544 const entry = entryResponse?.ok ? entryResponse.data : undefined;566545 const code = (entry as { totpCode?: string } | undefined)?.totpCode;567546 if (!code) return;src/content/inject.ts+12 −2
@@ -28,6 +28,15 @@2828 type IdentityKind,2929 } from "./identity-helper";3030 31+function showEntryAccessError(): void {32+ const error = document.createElement("div");33+ error.setAttribute("role", "alert");34+ error.textContent = "Could not access this entry. Open Peach to check it.";35+ error.style.cssText = "position:fixed;bottom:20px;left:20px;z-index:2147483647;background:#131109;color:#F0E8D8;padding:12px;font:12px monospace;";36+ document.body.appendChild(error);37+ setTimeout(() => error.remove(), 4000);38+}39+3140 let accentHex = "#E8956D";3241 let popupTheme: "dark" | "light" = "dark";3342 chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string; theme?: string } } | undefined) => {@@ -2831,6 +2840,7 @@28312840 payload: { id: entry.id, capability: options.capability },28322841 }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;28332842 if (!resp?.ok || !resp.data?.password) {2843+ showEntryAccessError();28342844 if (options.capability) dismiss();28352845 return;28362846 }@@ -2873,7 +2883,7 @@28732883 type: "GET_ENTRY_FOR_FILL",28742884 payload: { id: entry.id, capability: options.capability },28752885 }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2876- if (!r?.ok || !r.data?.totpCode) return null;2886+ if (!r?.ok || !r.data?.totpCode) { showEntryAccessError(); return null; }28772887 return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };28782888 }28792889 let current = await fetchCode();@@ -3024,7 +3034,7 @@30243034 };30253035 } | null;30263036 if (!response?.ok || !response.data) {3027- loading.textContent = "couldn't load this entry";3037+ loading.textContent = "Could not access this entry. Open Peach to check it.";30283038 return;30293039 }30303040 body.innerHTML = "";src/content/save.ts+27 −56
@@ -1,6 +1,6 @@11 import { detectHomograph, extractDomain } from "../shared/domain";22 import { ACCENT_COLORS } from "../shared/types";3-import type { VaultEntry } from "../shared/types";3+import type { SaveCredentialCheckResult } from "../shared/types";44 55 let accentHex = "#E8956D";66 chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string } } | undefined) => {@@ -17,26 +17,24 @@1717 domain: string;1818 }1919 20-async function getMatchingEntry(domain: string): Promise<VaultEntry | null> {21- const response = await chrome.runtime.sendMessage({22- type: "AUTOFILL_QUERY",23- payload: { domain },24- });25- const summary = (response as {26- ok: boolean;27- data?: Array<{ id: string }>;28- }).data?.[0];29-30- if (!summary) return null;31-32- const entryResponse = await chrome.runtime.sendMessage({33- type: "GET_ENTRY_FOR_FILL",34- payload: { id: summary.id },35- });36-37- return (38- (entryResponse as { ok: boolean; data?: VaultEntry }).data ?? null39- );20+async function checkCredential(credential: DetectedCredential): Promise<SaveCredentialCheckResult | null> {21+ let timeout: ReturnType<typeof setTimeout> | undefined;22+ try {23+ const response: unknown = await Promise.race([24+ chrome.runtime.sendMessage({ type: "CHECK_SAVE_CREDENTIAL", payload: { username: credential.username, password: credential.password } }),25+ new Promise<null>(resolve => { timeout = setTimeout(() => resolve(null), 5_000); }),26+ ]);27+ if (!response || typeof response !== "object" || !("ok" in response) || response.ok !== true || !("data" in response)) return null;28+ const data = response.data;29+ if (!data || typeof data !== "object" || !("status" in data)) return null;30+ if ((data.status === "new" || data.status === "same" || data.status === "ambiguous") && Object.keys(data).length === 1) return { status: data.status };31+ if (data.status === "changed" && Object.keys(data).length === 2 && "id" in data && typeof data.id === "string" && data.id) return { status: "changed", id: data.id };32+ return null;33+ } catch {34+ return null;35+ } finally {36+ clearTimeout(timeout);37+ }4038 }4139 4240 async function saveEntry(@@ -62,7 +60,7 @@6260 6361 function showBanner(6462 credential: DetectedCredential,65- existingEntry: VaultEntry | null,63+ existingId: string | null,6664 onPrimaryAction: () => Promise<void>,6765 onDismiss: () => void6866 ): () => void {@@ -74,7 +72,7 @@7472 host.style.setProperty("--peach-accent", accentHex);7573 const shadow = host.attachShadow({ mode: "closed" });7674 77- const isUpdate = existingEntry !== null;75+ const isUpdate = existingId !== null;7876 const title = isUpdate ? "Update password?" : "Save password?";7977 const subtitle = isUpdate8078 ? `Update password for ${credential.domain}?`@@ -215,43 +213,16 @@215213 currentBanner = null;216214 }217215 218- const existing = await getMatchingEntry(credential.domain);219- const isUpdate = existing !== null && existing.password !== credential.password;220- const isNew = existing === null;216+ const result = await checkCredential(credential);217+ if (!result || (result.status !== "new" && result.status !== "changed") || location.href !== credential.url) return;218+ const existingId = result.status === "changed" ? result.id : null;221219 222- if (!isUpdate && !isNew) {223- if (existing && existing.canary && existing.password === credential.password) {224- chrome.runtime.sendMessage({225- type: "FIRE_CANARY_PING",226- payload: {227- webhookUrl: existing.canary.webhookUrl,228- entryTitle: existing.title,229- trigger: "submitted",230- },231- }).catch(() => {});232- chrome.runtime.sendMessage({233- type: "UPDATE_ENTRY",234- payload: {235- id: existing.id,236- patch: {237- canary: {238- ...existing.canary,239- lastPinged: Date.now(),240- pingCount: (existing.canary.pingCount ?? 0) + 1,241- },242- },243- },244- }).catch(() => {});245- }246- return;247- }248-249220 currentBanner = showBanner(250221 credential,251- isUpdate ? existing : null,222+ existingId,252223 async () => {253- if (isUpdate && existing) {254- await updateEntryPassword(existing.id, credential.password);224+ if (existingId) {225+ await updateEntryPassword(existingId, credential.password);255226 } else {256227 await saveEntry(credential.username, credential.password, credential.url);257228 }src/popup/App.tsx+2 −2
@@ -835,7 +835,7 @@835835 if (entry?.password) void popupCopy(836836 entry.password,837837 "Password",838- entry.canary?.webhookUrl ? { webhookUrl: entry.canary.webhookUrl, entryTitle: entry.title } : undefined,838+ entry.id,839839 ).then((ok) => { if (ok) triggerRing(); });840840 },841841 copy_username: () => {@@ -843,7 +843,7 @@843843 if (entry?.username) void popupCopy(844844 entry.username,845845 "Username",846- entry.canary?.webhookUrl ? { webhookUrl: entry.canary.webhookUrl, entryTitle: entry.title } : undefined,846+ entry.id,847847 ).then((ok) => { if (ok) triggerRing(); });848848 },849849 copy_totp: () => {src/popup/copy.ts+3 −5
@@ -11,13 +11,12 @@1111 * auto-clear timer.1212 */1313 14-import type { Canary } from "../shared/types";1514 import { sendMessage } from "./App";1615 1716 export async function popupCopy(1817 text: string,1918 label: string,20- canary?: { webhookUrl: Canary["webhookUrl"]; entryTitle: string },19+ entryId?: string,2120 ): Promise<boolean> {2221 let alreadyWritten = false;2322 try {@@ -34,12 +33,11 @@3433 });3534 const ok = alreadyWritten || Boolean((response as { ok?: boolean })?.ok);3635 const canaryLabel = label.toLowerCase();37- if (ok && canary && (canaryLabel === "password" || canaryLabel === "username")) {36+ if (ok && entryId && (canaryLabel === "password" || canaryLabel === "username")) {3837 void sendMessage({3938 type: "FIRE_CANARY_PING",4039 payload: {41- webhookUrl: canary.webhookUrl,42- entryTitle: canary.entryTitle,40+ id: entryId,4341 trigger: canaryLabel === "password" ? "password_copied" : "username_copied",4442 },4543 });src/popup/views/Entry.tsx+20 −9
@@ -505,7 +505,7 @@505505 const ok = await popupCopy(506506 text,507507 label,508- entry?.canary?.webhookUrl ? { webhookUrl: entry.canary.webhookUrl, entryTitle: entry.title } : undefined,508+ entry?.id,509509 );510510 if (ok) {511511 triggerRing();@@ -883,7 +883,7 @@883883 if (entry().canary?.webhookUrl) {884884 void sendMessage({885885 type: "FIRE_CANARY_PING",886- payload: { webhookUrl: entry().canary!.webhookUrl, entryTitle: entry().title, trigger: "password_copied" },886+ payload: { id: entry().id, trigger: "password_copied" },887887 });888888 }889889 void copyField(cardNum, "cardNumber", e.currentTarget as HTMLButtonElement);@@ -1665,6 +1665,7 @@16651665 const [label, setLabel] = createSignal(props.entry.canary?.label ?? "");16661666 const [testResult, setTestResult] = createSignal<string | null>(null);16671667 const [testing, setTesting] = createSignal(false);1668+ const [saveError, setSaveError] = createSignal<string | null>(null);16681669 16691670 // Pro gate entry-point for canary creation. Free users cannot toggle the16701671 // canary on; the server-side UPDATE_ENTRY handler is the single hard@@ -1681,15 +1682,24 @@16811682 ? {16821683 webhookUrl: url,16831684 label: nextLabel,1684- lastPinged: props.entry.canary?.lastPinged,1685- pingCount: props.entry.canary?.pingCount,16861685 }16871686 : undefined;1688- await sendMessage({1689- type: "UPDATE_ENTRY",1690- payload: { id: props.entry.id, patch: { canary } },1691- });1692- await props.onSaved();1687+ setSaveError(null);1688+ try {1689+ const result = await sendMessage({1690+ type: "UPDATE_ENTRY",1691+ payload: { id: props.entry.id, patch: { canary } },1692+ });1693+ if (!result.ok) {1694+ setSaveError(result.error === "invalid_webhook_url"1695+ ? "Use a public HTTPS webhook URL without a username or password."1696+ : "Could not save this canary. Try again.");1697+ return;1698+ }1699+ await props.onSaved();1700+ } catch {1701+ setSaveError("Could not save this canary. Try again.");1702+ }16931703 }16941704 16951705 async function testPing() {@@ -1707,6 +1717,7 @@17071717 17081718 return (17091719 <div class="peach-canary-section">1720+ <Show when={saveError()}><p role="alert">{saveError()}</p></Show>17101721 <div class="peach-field-value-row">17111722 <span class="peach-field-value" style="font-size:12px;">17121723 canary alertsrc/popup/views/Vault.tsx+3 −3
@@ -179,7 +179,7 @@179179 await popupCopy(180180 entry.password,181181 "password",182- entry.canary?.webhookUrl ? { webhookUrl: entry.canary.webhookUrl, entryTitle: entry.title } : undefined,182+ entry.id,183183 );184184 }185185 }@@ -652,7 +652,7 @@652652 onClick={async () => {653653 const e = contextEntry();654654 if (!e?.username) return;655- await popupCopy(e.username, "username");655+ await popupCopy(e.username, "username", e.id);656656 setContextEntry(null);657657 }}658658 >@@ -666,7 +666,7 @@666666 onClick={async () => {667667 const e = contextEntry();668668 if (!e?.password) return;669- await popupCopy(e.password, "password");669+ await popupCopy(e.password, "password", e.id);670670 setContextEntry(null);671671 }}672672 >src/popup/views/contracts.test.tsx+37 −8
@@ -1476,6 +1476,25 @@14761476 expect(sendMessageMock).toHaveBeenCalledWith({ type: "GET_RECOVERY_WORDS" });14771477 });14781478 1479+ it("shows rejected canary saves and only refreshes after success", async () => {1480+ sendMessageMock.mockResolvedValue({ ok: false, error: "invalid_webhook_url" });1481+ const onSaved = vi.fn(async () => undefined);1482+ const container = mount(<EntryView entry={sampleEntry()} onDelete={vi.fn()} onFieldSaved={onSaved} />);1483+ const advanced = Array.from(container.querySelectorAll("button")).find(button => button.textContent?.includes("Advanced"))!;1484+ advanced.click(); await flushView();1485+ const webhook = container.querySelector('input[placeholder="https://hooks.zapier.com/..."]') as HTMLInputElement;1486+ inputText(webhook, "https://100.64.1.2/hook");1487+ webhook.dispatchEvent(new FocusEvent("blur", { bubbles: true })); await flushView();1488+ expect(container.textContent).toContain("Use a public HTTPS webhook URL without a username or password.");1489+ expect(onSaved).not.toHaveBeenCalled();1490+ sendMessageMock.mockResolvedValue({ ok: true });1491+ inputText(webhook, "https://example.com/updated");1492+ webhook.dispatchEvent(new FocusEvent("blur", { bubbles: true })); await flushView();1493+ expect(onSaved).toHaveBeenCalledTimes(1);1494+ expect(container.querySelector('[role="alert"]')).toBeNull();1495+ expect(sendMessageMock).toHaveBeenLastCalledWith({ type: "UPDATE_ENTRY", payload: { id: "entry-1", patch: { canary: { webhookUrl: "https://example.com/updated", label: undefined } } } });1496+ });1497+14791498 it("Entry copy actions send COPY and canary ping messages for password and username", async () => {14801499 sendMessageMock.mockResolvedValue({ ok: true });14811500 const container = mount(@@ -1497,8 +1516,7 @@14971516 expect(sendMessageMock).toHaveBeenNthCalledWith(2, {14981517 type: "FIRE_CANARY_PING",14991518 payload: {1500- webhookUrl: "https://example.com/hook",1501- entryTitle: "GitHub",1519+ id: "entry-1",15021520 trigger: "password_copied",15031521 },15041522 });@@ -1515,8 +1533,7 @@15151533 expect(sendMessageMock).toHaveBeenNthCalledWith(2, {15161534 type: "FIRE_CANARY_PING",15171535 payload: {1518- webhookUrl: "https://example.com/hook",1519- entryTitle: "GitHub",1536+ id: "entry-1",15201537 trigger: "username_copied",15211538 },15221539 });@@ -1543,8 +1560,7 @@15431560 expect(sendMessageMock.mock.calls).toContainEqual([{15441561 type: "FIRE_CANARY_PING",15451562 payload: {1546- webhookUrl: "https://example.com/hook",1547- entryTitle: "GitHub",1563+ id: "entry-1",15481564 trigger: "password_copied",15491565 },15501566 }]);@@ -1596,11 +1612,24 @@15961612 expect(sendMessageMock.mock.calls).toContainEqual([{15971613 type: "FIRE_CANARY_PING",15981614 payload: {1599- webhookUrl: "https://example.com/hook",1600- entryTitle: "GitHub",1615+ id: "entry-1",16011616 trigger: "password_copied",16021617 },16031618 }]);1619+ });1620+1621+ it("Vault context-menu copies report only the stored entry ID", async () => {1622+ sendMessageMock.mockResolvedValue({ ok: true });1623+ const container = mount(<VaultView entries={[sampleEntry()]} sortOrder="url-first" onSelectEntry={vi.fn()} onSortOrderChange={vi.fn()} onAdd={vi.fn()} onClose={vi.fn()} />);1624+ for (const label of ["Copy username", "Copy password"]) {1625+ const row = container.querySelector(".peach-entry-row") as HTMLButtonElement;1626+ row.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }));1627+ await flushView();1628+ const action = Array.from(container.querySelectorAll<HTMLButtonElement>('button[role="menuitem"]')).find(button => button.textContent?.trim() === label)!;1629+ action.click(); await flushView();1630+ expect(sendMessageMock.mock.calls).toContainEqual([{ type: "FIRE_CANARY_PING", payload: { id: "entry-1", trigger: label === "Copy password" ? "password_copied" : "username_copied" } }]);1631+ sendMessageMock.mockClear();1632+ }16041633 });16051634 16061635 it("Entry shows Advanced for passkey-bearing credential entries", async () => {src/shared/types.ts+5 −0
@@ -227,6 +227,7 @@227227 | "ADD_ADDITIONAL_URL"228228 | "REQUEST_REMEMBER_SITE"229229 | "DELETE_ENTRY"230+ | "CHECK_SAVE_CREDENTIAL"230231 | "AUTOFILL_QUERY"231232 | "COPY"232233 | "CREATE_VAULT"@@ -344,6 +345,10 @@344345 | "ESTIMATE_CODEX_PAGES"345346 | "GENERATE_CODEX"346347 | "RESTORE_FROM_CODEX";348+349+export type SaveCredentialCheckResult =350+ | { status: "new" | "same" | "ambiguous" }351+ | { status: "changed"; id: string };347352 348353 export type ProFeature =349354 | "sync"