ff11901fb9f8

preserve distinct passkey credentials (v5.3.15)

time
2026-11-13 03:08 UTC · 2 weeks ago
machine
Junes-MacBook-Pro.local
agent
gpt-6
session
remediate interim audit findings
parent
a96147f2af05
10 files manifest.firefox.json+1 −1manifest.json+1 −1package.json+1 −1src/background/passkey-chrome-ceremony.test.ts+77 −1src/background/passkey-firefox-proxy.test.ts+71 −0src/background/passkey.ts+50 −31src/background/vault.consolidate-passkeys.test.ts+158 −48src/background/vault.ts+56 −98src/content/passkeys-firefox.test.ts+18 −1src/content/passkeys-firefox.ts+9 −1
manifest.firefox.json+1 −1
@@ -1,7 +1,7 @@11 {22   "manifest_version": 3,33   "name": "Peach Password Manager",4-  "version": "5.3.14",4+  "version": "5.3.15",55   "description": "Zero-knowledge password manager",66   "browser_specific_settings": {77     "gecko": {

view file

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.14",5+  "version": "5.3.15",66   "description": "Zero-knowledge password manager",77   "action": {88     "default_popup": "src/popup/index.html",

view file

package.json+1 −1
@@ -1,6 +1,6 @@11 {22   "name": "peach",3-  "version": "5.3.14",3+  "version": "5.3.15",44   "description": "Zero-knowledge password manager",55   "license": "GPL-3.0-only",66   "type": "module",

view file

src/background/passkey-chrome-ceremony.test.ts+77 −1
@@ -483,12 +483,88 @@483483     const beforeCount = vault.getEntries().length;484484 485485     autoApprove();486-    fireCreate(buildCreateOptions({ rpId: "github.com", rpName: "GitHub" }), 125);486+    fireCreate(buildCreateOptions({ rpId: "github.com", rpName: "GitHub", userName: "june" }), 125);487487     await waitForCreateComplete(125);488488 489489     expect(vault.getEntries().length).toBe(beforeCount);490490     const updated = vault.getEntries().find((e) => e.id === existing.id);491491     expect(updated?.passkey?.rpId).toBe("github.com");492+  });493+494+495+  it("preserves repeated registrations for the same RP and account", async () => {496+    const vault = await import("./vault");497+    await vault.createVault("correct-pass-12345");498+    const ids: string[] = [];499+    for (const requestId of [810, 811, 812]) {500+      autoApprove();501+      fireCreate(buildCreateOptions({ userName: requestId === 812 ? "other" : "june" }), requestId);502+      const completed = await waitForCreateComplete(requestId);503+      ids.push(JSON.parse(completed.responseJson!).id);504+    }505+    expect(new Set(ids).size).toBe(3);506+    expect(vault.getEntries().map(entry => entry.passkey?.credentialId).sort()).toEqual(ids.sort());507+    for (const [index, id] of ids.entries()) {508+      autoApprove();509+      fireGet({ rpId: "google.com", challenge: "Y2g", allowCredentials: [{ type: "public-key", id }] }, 820 + index);510+      expect(JSON.parse((await waitForGetComplete(820 + index)).responseJson!).id).toBe(id);511+    }512+    vault.lock();513+    expect(await vault.unlock("correct-pass-12345")).toBe(true);514+    expect(vault.getEntries().map(entry => entry.passkey?.credentialId).sort()).toEqual(ids.sort());515+  });516+517+  it.each(["different", "June", "", "ambiguous"])("does not attach to %s account candidates", async (account) => {518+    const vault = await import("./vault");519+    await vault.createVault("correct-pass-12345");520+    const draft = { type: "login" as const, title: "Login", url: "https://google.com", username: account === "ambiguous" ? "june" : account, password: "pw" };521+    const login = await vault.addEntry(draft);522+    if (account === "ambiguous") await vault.addEntry(draft);523+    autoApprove();524+    fireCreate(buildCreateOptions({ userName: "june" }), 813);525+    await waitForCreateComplete(813);526+    expect(vault.getEntryById(login.id)?.passkey).toBeUndefined();527+    expect(vault.getEntries().filter(entry => entry.passkey)).toHaveLength(1);528+  });529+530+  it.each(["active", "foreign-rp", "deleted"])("honors excluded credential with %s state after approval", async (state) => {531+    const vault = await import("./vault");532+    await vault.createVault("correct-pass-12345");533+    const seeded = await seedPasskey(state === "foreign-rp" ? "another.com" : "google.com");534+    const entry = vault.getEntries().find(candidate => candidate.passkey?.credentialId === seeded.credentialId)!;535+    if (state === "deleted") await vault.deleteEntry(entry.id);536+    const before = vault.getEntries();537+    const generate = vi.spyOn(crypto.subtle, "generateKey");538+    autoApprove();539+    fireCreate({ ...buildCreateOptions(), excludeCredentials: [{ type: "public-key", id: seeded.credentialId }] }, 814);540+    const completed = await waitForCreateComplete(814);541+    if (state === "active") {542+      expect(completed.error?.name).toBe("InvalidStateError");543+      expect(generate).not.toHaveBeenCalled();544+      expect(vault.getEntries()).toEqual(before);545+    } else {546+      expect(completed.responseJson).toBeDefined();547+    }548+    generate.mockRestore();549+  });550+551+552+  it("rechecks excluded credentials when the vault changes during key generation", async () => {553+    const vault = await import("./vault");554+    await vault.createVault("correct-pass-12345");555+    const seeded = await seedPasskey("another.com");556+    const original = crypto.subtle.generateKey.bind(crypto.subtle);557+    const generate = vi.spyOn(crypto.subtle, "generateKey").mockImplementation(async (...args: Parameters<typeof crypto.subtle.generateKey>) => {558+      const generated = await Reflect.apply(original, crypto.subtle, args);559+      await vault.updateEntry(seeded.entry.id, { passkey: { ...seeded.entry.passkey!, rpId: "google.com" } });560+      return generated;561+    });562+    autoApprove();563+    fireCreate({ ...buildCreateOptions(), excludeCredentials: [{ type: "public-key", id: seeded.credentialId }] }, 815);564+    const completed = await waitForCreateComplete(815);565+    expect(completed.error?.name).toBe("InvalidStateError");566+    expect(vault.getEntries()).toHaveLength(1);567+    generate.mockRestore();492568   });493569 494570   // ─────────────────────────────────────────────────────────────────────

view file

src/background/passkey-firefox-proxy.test.ts+71 −0
@@ -639,4 +639,75 @@639639     expect(after!.passkey!.signCount).toBe(1);640640     expect(after!.passkey!.lastUsedAt).toBeDefined();641641   });642+  function createPayload(userName = "june") {643+    return { rpId: "github.com", userId: "AQID", userName, challenge: "x", origin: "https://github.com", clientDataJSON: Array.from(new TextEncoder().encode("{}")), pubKeyCredParams: [{ alg: -7, type: "public-key" }] };644+  }645+646+  it("preserves distinct Firefox proxy registrations for each account", async () => {647+    const vault = await import("./vault");648+    await vault.createVault("correct-pass-12345");649+    const ids: string[] = [];650+    for (const account of ["june", "june", "other"]) {651+      await autoApprove();652+      const result = await dispatch({ type: "PASSKEY_CREATE", payload: createPayload(account) });653+      expect(result.ok).toBe(true);654+      ids.push((result as unknown as { credential: { id: string } }).credential.id);655+    }656+    expect(vault.getEntries().map(entry => entry.passkey?.credentialId).sort()).toEqual(ids.sort());657+    for (const id of ids) {658+      await autoApprove();659+      const result = await dispatch({ type: "PASSKEY_GET", payload: { rpId: "github.com", challenge: "x", origin: "https://github.com", clientDataJSON: Array.from(new TextEncoder().encode("{}")), allowCredentials: [{ type: "public-key", id }] } });660+      expect(result).toMatchObject({ ok: true, credential: { id } });661+    }662+    vault.lock();663+    expect(await vault.unlock("correct-pass-12345")).toBe(true);664+    expect(vault.getEntries().map(entry => entry.passkey?.credentialId).sort()).toEqual(ids.sort());665+  });666+667+  it.each(["active", "foreign-rp", "deleted"])("enforces Firefox exclusions for %s credentials after approval", async (state) => {668+    const vault = await import("./vault");669+    await vault.createVault("correct-pass-12345");670+    await autoApprove();671+    const original = await dispatch({ type: "PASSKEY_CREATE", payload: createPayload() });672+    const credentialId = (original as unknown as { credential: { id: string } }).credential.id;673+    const entry = vault.getEntries()[0]!;674+    if (state === "foreign-rp") await vault.updateEntry(entry.id, { passkey: { ...entry.passkey!, rpId: "another.com" } });675+    if (state === "deleted") await vault.deleteEntry(entry.id);676+    const before = vault.getEntries();677+    const generate = vi.spyOn(crypto.subtle, "generateKey");678+    await autoApprove();679+    const result = await dispatch({ type: "PASSKEY_CREATE", payload: { ...createPayload(), excludeCredentials: [{ type: "public-key", id: credentialId }] } });680+    if (state === "active") {681+      expect(result).toMatchObject({ ok: false, error: "credential_excluded" });682+      expect(generate).not.toHaveBeenCalled();683+      expect(vault.getEntries()).toEqual(before);684+    } else expect(result.ok).toBe(true);685+    generate.mockRestore();686+  });687+688+  it("native Firefox completion preserves prior credentials and refuses credential replay", async () => {689+    const vault = await import("./vault");690+    const passkey = await import("./passkey");691+    await vault.createVault("correct-pass-12345");692+    for (const [index, credentialId] of ["first", "second", "first"].entries()) {693+      expect(await passkey.initiateFirefoxPasskeyCreate({ rpId: "github.com", rpName: "GitHub", userName: "june" }, "https://github.com")).toEqual({ ok: true });694+      const pending = sessionStorage.passkey_pending_firefox as { requestId: number; userHandle: string };695+      const result = await passkey.completeFirefoxPasskeyCreate({ requestId: pending.requestId, rpId: "github.com", rpName: "GitHub", userName: "june", userHandle: pending.userHandle, credentialId, publicKeyCose: "AQID", algorithm: -7 });696+      expect(result.ok).toBe(index < 2);697+    }698+    expect(vault.getEntries().map(entry => entry.passkey?.credentialId).sort()).toEqual(["first", "second"]);699+  });700+701+  it.each(["exact", "different", "June", "", "ambiguous"])("Firefox proxy attaches only an unambiguous exact account (%s)", async (account) => {702+    const vault = await import("./vault");703+    await vault.createVault("correct-pass-12345");704+    const draft = { type: "login" as const, title: "Login", url: "https://github.com", username: account === "exact" || account === "ambiguous" ? "june" : account, password: "pw" };705+    const login = await vault.addEntry(draft);706+    if (account === "ambiguous") await vault.addEntry(draft);707+    await autoApprove();708+    expect((await dispatch({ type: "PASSKEY_CREATE", payload: createPayload() })).ok).toBe(true);709+    expect(Boolean(vault.getEntryById(login.id)?.passkey)).toBe(account === "exact");710+    expect(vault.getEntryById(login.id)?.password).toBe("pw");711+  });712+642713 });

view file

src/background/passkey.ts+50 −31
@@ -384,27 +384,28 @@384384   await detachPasskeyProxy();385385 }386386 387-/**388- * Find the entry that already holds a passkey for the given RP, or the most389- * recently-modified login entry whose URL/additionalUrls match the RP — that390- * entry is the natural attach target when the user adds a passkey to a site391- * they already have a password for. Returns null when there's no candidate;392- * the caller creates a new entry in that case.393- */394-function findAttachTarget(rpId: string): VaultEntry | null {395-  const all = vault.getEntries();396-  const passkeyMatch = all.find(397-    (entry) => entry.passkey?.rpId === rpId && !entry.deletedAt398-  );399-  if (passkeyMatch) return passkeyMatch;400-  const loginMatches = vault.queryDomain(rpId).filter((entry) => entry.type === "login" && !entry.passkey);401-  if (loginMatches.length === 0) return null;402-  // Pick the most recently modified candidate to be deterministic.403-  return loginMatches.reduce((best, e) =>404-    (e.modifiedAt ?? 0) > (best.modifiedAt ?? 0) ? e : best405-  );387+// Multiple accounts and credentials for one RP must remain independently usable.388+function findAttachTarget(rpId: string, userName: string): VaultEntry | null {389+  if (!userName) return null;390+  const matches = vault.getEntries().filter((entry) => {391+    if (entry.deletedAt || entry.type !== "login" || entry.passkey || entry.username !== userName) return false;392+    return [entry.url, ...(entry.additionalUrls ?? [])].some((url) => {393+      if (!url) return false;394+      try {395+        return new URL(url.includes("://") ? url : `https://${url}`).hostname === rpId;396+      } catch {397+        return false;398+      }399+    });400+  });401+  return matches.length === 1 ? matches[0]! : null;406402 }407403 404+function hasExcludedCredential(rpId: string, excluded: Array<{ id: string; type?: string }> = []): boolean {405+  return listPasskeyEntries().some((entry) => entry.passkey.rpId === rpId &&406+    excluded.some((descriptor) => descriptor.type === "public-key" && descriptor.id === entry.passkey.credentialId));407+}408+408409 async function handleCreateRequest(409410   request: chrome.webAuthenticationProxy.CreateRequest410411 ): Promise<void> {@@ -491,6 +492,11 @@491492     return;492493   }493494 495+  if (hasExcludedCredential(rpId, options.excludeCredentials)) {496+    await rejectCreate(request.requestId, "InvalidStateError", "A listed credential already exists.");497+    return;498+  }499+494500   const algorithm = pickPasskeyAlgorithm(options.pubKeyCredParams ?? []);495501   if (!algorithm) {496502     console.warn("[Peach passkey] reject: no supported algorithm", options.pubKeyCredParams);@@ -534,9 +540,13 @@534540     createdAt: Date.now(),535541   };536542 537-  // Attach to an existing login (same domain) when one exists; otherwise538-  // create a fresh login entry that exists solely to hold the passkey.539-  const target = findAttachTarget(rpId);543+  if (hasExcludedCredential(rpId, options.excludeCredentials)) {544+    await rejectCreate(request.requestId, "InvalidStateError", "A listed credential already exists.");545+    return;546+  }547+548+  // Attach only when the account identifies one credential-free login.549+  const target = findAttachTarget(rpId, userName);540550   if (target) {541551     await vault.updateEntry(target.id, { passkey });542552   } else {@@ -548,9 +558,7 @@548558       passkey,549559     });550560   }551-  // Merge any same-domain TOTP-only entries into the passkey entry right now552-  // so the user sees one consolidated entry rather than waiting until next553-  // unlock for the decodePayload merge pass to run.561+  // Consolidate only account matches whose data can be retained.554562   await vault.consolidatePasskeyEntries();555563 556564   try {@@ -899,6 +907,10 @@899907     return { ok: false, error: "no_pending_request" };900908   }901909 910+  if (hasExcludedCredential(payload.rpId, [{ type: "public-key", id: payload.credentialId }])) {911+    return { ok: false, error: "credential_exists" };912+  }913+902914   const passkey: PasskeyData = {903915     rpId: payload.rpId,904916     rpName: payload.rpName,@@ -917,10 +929,8 @@917929     createdAt: Date.now(),918930   };919931 920-  // Same attach-or-create flow as the Chrome path: prefer attaching to an921-  // existing login entry for the same domain so the user ends up with one922-  // entry per site, not two (a login + a passkey-only).923-  const target = findAttachTarget(payload.rpId);932+  // Native Firefox credentials follow the same account-specific attachment rule.933+  const target = findAttachTarget(payload.rpId, payload.userName);924934   if (target) {925935     await vault.updateEntry(target.id, { passkey });926936   } else {@@ -1015,6 +1025,7 @@10151025   clientDataJSON: number[];10161026   origin: string;10171027   pubKeyCredParams?: FirefoxPubKeyCredParam[];1028+  excludeCredentials?: FirefoxAllowCredential[];10181029   authenticatorSelection?: Record<string, unknown>;10191030   timeout?: number;10201031   attestation?: string;@@ -1050,7 +1061,7 @@10501061 10511062 type FirefoxPasskeyResult<T> =10521063   | { ok: true; credential: T }1053-  | { ok: false; error: "pro_required" | "user_cancelled" | "no_credentials" | "vault_locked" | "not_applicable" | "internal_error"; message?: string };1064+  | { ok: false; error: "pro_required" | "user_cancelled" | "no_credentials" | "vault_locked" | "not_applicable" | "internal_error" | "credential_excluded"; message?: string };10541065 10551066 function listPasskeyEntries(): Array<VaultEntry & { passkey: PasskeyData }> {10561067   return vault.getEntries().filter(@@ -1202,6 +1213,10 @@12021213     userDisplayName: payload.userDisplayName,12031214   }, async () => {12041215 1216+    if (hasExcludedCredential(payload.rpId, payload.excludeCredentials)) {1217+      return { ok: false, error: "credential_excluded" };1218+    }1219+12051220     const { bytes: credentialIdBytes, base64url: credentialId } = generateCredentialId();12061221     const { publicKeyCose, publicKeySpki, privateKeyJwk } = await generatePasskeyKeypair(algorithm);12071222 @@ -1235,7 +1250,11 @@12351250       createdAt: Date.now(),12361251     };12371252 1238-    const target = findAttachTarget(payload.rpId);1253+    if (hasExcludedCredential(payload.rpId, payload.excludeCredentials)) {1254+      return { ok: false, error: "credential_excluded" };1255+    }1256+1257+    const target = findAttachTarget(payload.rpId, payload.userName);12391258     if (target) {12401259       await vault.updateEntry(target.id, { passkey });12411260     } else {

view file

src/background/vault.consolidate-passkeys.test.ts+158 −48
@@ -1,18 +1,4 @@1-// T-023: vault.consolidatePasskeyEntries — passkey merge with lastUsed ranking2-//3-// Why this test exists: `consolidatePasskeyEntries()` (exposed via the4-// CONSOLIDATE_PASSKEYS message) calls `mergePasskeyOnlyIntoLogins()`, which:5-//   1. Groups all passkey-bearing entries by rpId.6-//   2. Within each group, sorts by lastUsedAt (then createdAt, then modifiedAt).7-//   3. The "winner" (most-recently-used) passkey is merged into the existing8-//      non-passkey login for the same rpId domain (if one exists).9-//   4. If no login exists but multiple passkey entries exist for the same rpId,10-//      the loser entries are soft-deleted (winner kept).11-//12-// This function is called on every passkey registration (via REGISTER_PASSKEY)13-// and has ZERO direct test coverage. A regression in the sort order would14-// incorrectly merge an older passkey, losing a newer one — a silent security15-// regression.1+// Registration consolidation must preserve distinct credentials and account data.162 173 import { beforeEach, describe, expect, it, vi } from "vitest";184 @@ -63,7 +49,7 @@6349     publicKeyCose: "a401020326",6450     privateKeyJwk: { kty: "EC", crv: "P-256", d: "test", x: "test", y: "test" },6551     userHandle: "uh",66-    userName: opts.rpId + "-user",52+    userName: "[email protected]",6753     userDisplayName: opts.rpId + " User",6854     algorithm: -7 as const,6955     signCount: 0,@@ -88,14 +74,7 @@8874     await vault.createVault("consolidate-test-pass");8975   });9076 91-  // T-023a: passkey entry for a domain + login entry for the same domain →92-  // consolidatePasskeyEntries() merges the passkey onto the login entry and93-  // soft-deletes the passkey-only entry.94-  //95-  // Bug this catches: if the rpId → URL domain match is broken (e.g., wrong96-  // extractDomain call), the passkey would never merge and the user would see97-  // duplicate entries.98-  it("T-023a: passkey-only entry merges into existing login with matching domain", async () => {77+  it("T-023a: passkey-only entry attaches to the exact account login", async () => {9978     // Add a login entry for example.com10079     const login = await vault.addEntry({10180       type: "login",@@ -161,16 +140,11 @@161140     expect(vault.getEntryById(passkeyEntry.id)).toBeUndefined();162141   });163142 164-  // T-023b: two passkey entries for the same rpId, no login → winner is kept165-  // (by lastUsedAt), loser is soft-deleted.166-  //167-  // Bug this catches: an incorrect sort that picks the OLDER passkey as the168-  // winner would retain a stale credential and soft-delete the current one.169-  it("T-023b: two passkeys for same rpId → most recently used is kept, other soft-deleted", async () => {143+  it("T-023b: distinct credentials for the same RP remain active", async () => {170144     const olderPasskey = await vault.addEntry({171145       type: "login",172146       title: "Old Passkey",173-      username: "user",147+      username: "[email protected]",174148       password: "",175149       url: "https://github.com",176150       passkey: makePasskey({@@ -184,7 +158,7 @@184158     const newerPasskey = await vault.addEntry({185159       type: "login",186160       title: "New Passkey",187-      username: "user",161+      username: "[email protected]",188162       password: "",189163       url: "https://github.com",190164       passkey: makePasskey({@@ -197,20 +171,9 @@197171 198172     await vault.consolidatePasskeyEntries();199173 200-    const entries = vault.getEntries();174+    expect(vault.getEntryById(olderPasskey.id)?.passkey?.credentialId).toBe("cred-old");175+    expect(vault.getEntryById(newerPasskey.id)?.passkey?.credentialId).toBe("cred-new");201176 202-    // The newer passkey must still be in active entries203-    const keptEntry = entries.find((e) =>204-      e.passkey?.credentialId === "cred-new" && !e.deletedAt,205-    );206-    expect(keptEntry).toBeDefined();207-208-    // The older passkey must be soft-deleted209-    const deletedEntry = vault.getEntryById(olderPasskey.id);210-    expect(deletedEntry).toBeUndefined();211-212-    // Void reference to suppress unused var warning213-    void newerPasskey;214177   });215178 216179   // T-023c: passkey entry for a domain with no matching login → it stays@@ -220,7 +183,7 @@220183     const passkey = await vault.addEntry({221184       type: "login",222185       title: "Solo Passkey",223-      username: "user",186+      username: "[email protected]",224187       password: "",225188       url: "https://uniquesite.example.com",226189       passkey: makePasskey({ rpId: "uniquesite.example.com", credentialId: "cred-solo" }),@@ -240,7 +203,7 @@240203     await vault.addEntry({241204       type: "login",242205       title: "Google Login",243-      username: "user",206+      username: "[email protected]",244207       password: "pw",245208       url: "https://google.com",246209     });@@ -248,7 +211,7 @@248211     const signinPasskey = await vault.addEntry({249212       type: "login",250213       title: "Google Signin Passkey",251-      username: "user",214+      username: "[email protected]",252215       password: "",253216       url: "https://signin.google.com",254217       passkey: makePasskey({ rpId: "signin.google.com", credentialId: "cred-signin" }),@@ -260,4 +223,151 @@260223     const after = vault.getEntryById(signinPasskey.id);261224     expect(after).toBeDefined();262225   });226+  it.each(["another-account", "[email protected]", ""])("does not attach a credential to account %s", async (username) => {227+    const login = await vault.addEntry({ type: "login", title: "Login", username, password: "pw", url: "https://example.com" });228+    const source = await vault.addEntry({ type: "login", title: "Passkey", username: "[email protected]", url: "https://example.com", passkey: makePasskey({ rpId: "example.com", credentialId: "cred-account" }) });229+    await vault.consolidatePasskeyEntries();230+    expect(vault.getEntryById(login.id)?.passkey).toBeUndefined();231+    expect(vault.getEntryById(source.id)?.passkey?.credentialId).toBe("cred-account");232+  });233+234+  it.each(["totp", "notes", "password", "ambiguous"])("preserves consolidation candidates with %s data", async (conflict) => {235+    const draft = { type: "login" as const, title: "Login", username: "[email protected]", password: "pw", url: "https://example.com" };236+    const login = await vault.addEntry({ ...draft, ...(conflict === "totp" ? { totp: "JBSWY3DPEHPK3PXP" } : {}) });237+    if (conflict === "ambiguous") await vault.addEntry(draft);238+    const source = await vault.addEntry({ type: "login", title: "Passkey", username: "[email protected]", url: "https://example.com", passkey: makePasskey({ rpId: "example.com", credentialId: "cred-conflict" }), ...(conflict === "totp" ? { totp: "KRUGS4ZANFZSAYJA" } : {}), ...(conflict === "notes" ? { notes: "Keep this note" } : {}), ...(conflict === "password" ? { password: "another-password" } : {}) });239+    await vault.consolidatePasskeyEntries();240+    expect(vault.getEntryById(login.id)?.passkey).toBeUndefined();241+    expect(vault.getEntryById(source.id)).toBeDefined();242+  });243+244+  it("manual deduplication preserves distinct RP/credential-ID pairs", async () => {245+    for (const [rpId, credentialId] of [["example.com", "first"], ["example.com", "second"], ["another.com", "first"]]) {246+      await vault.addEntry({ type: "login", title: "Passkey", username: "[email protected]", passkey: makePasskey({ rpId: rpId!, credentialId: credentialId! }) });247+    }248+    expect(vault.countDuplicates()).toBe(0);249+    expect(await vault.deduplicateEntries()).toBe(0);250+    expect(vault.getEntries()).toHaveLength(3);251+  });252+253+  it("manual deduplication removes an identical credential copy while preserving conflicting data", async () => {254+    const draft = { type: "login" as const, title: "Passkey", username: "[email protected]", passkey: makePasskey({ rpId: "example.com", credentialId: "same-id" }) };255+    await vault.addEntry(draft);256+    await vault.addEntry(draft);257+    const withNotes = await vault.addEntry({ ...draft, notes: "Keep this note" });258+    const withTotp = await vault.addEntry({ ...draft, totp: "JBSWY3DPEHPK3PXP" });259+    expect(vault.countDuplicates()).toBe(1);260+    expect(await vault.deduplicateEntries()).toBe(1);261+    expect(vault.getEntryById(withNotes.id)?.notes).toBe("Keep this note");262+    expect(vault.getEntryById(withTotp.id)?.totp).toBe("JBSWY3DPEHPK3PXP");263+    vault.lock();264+    expect(await vault.unlock("consolidate-test-pass")).toBe(true);265+    expect(vault.getEntries()).toHaveLength(3);266+  });267+268+  it("failed consolidation persistence leaves both in-memory records intact", async () => {269+    const login = await vault.addEntry({ type: "login", title: "Login", username: "[email protected]", password: "pw", url: "https://example.com" });270+    const source = await vault.addEntry({ type: "login", title: "Passkey", username: "[email protected]", url: "https://example.com", passkey: makePasskey({ rpId: "example.com", credentialId: "persisted" }) });271+    const set = vi.spyOn(chrome.storage.local, "set").mockRejectedValue(new Error("storage unavailable"));272+    await expect(vault.consolidatePasskeyEntries()).rejects.toThrow("storage unavailable");273+    expect(vault.getEntryById(login.id)?.passkey).toBeUndefined();274+    expect(vault.getEntryById(source.id)?.passkey?.credentialId).toBe("persisted");275+    set.mockRestore();276+    vault.lock();277+    expect(await vault.unlock("consolidate-test-pass")).toBe(true);278+    expect(vault.getEntries()).toHaveLength(2);279+  });280+281+  it("a lock during consolidation failure cannot restore decrypted entries", async () => {282+    await vault.addEntry({ type: "login", title: "Login", username: "[email protected]", password: "pw", url: "https://example.com" });283+    const source = await vault.addEntry({ type: "login", title: "Passkey", username: "[email protected]", url: "https://example.com", passkey: makePasskey({ rpId: "example.com", credentialId: "persisted" }) });284+    const set = vi.spyOn(chrome.storage.local, "set").mockImplementationOnce(async () => { await vault.lock(); throw new Error("storage unavailable"); });285+    await expect(vault.consolidatePasskeyEntries()).rejects.toThrow();286+    expect(vault.isUnlocked()).toBe(false);287+    expect(vault.getEntryById(source.id)).toBeUndefined();288+    set.mockRestore();289+  });290+291+  it("preserves credentials carried by note entries during consolidation and manual deduplication", async () => {292+    const login = await vault.addEntry({ type: "login", title: "Login", username: "[email protected]", password: "pw", url: "https://example.com" });293+    for (const credentialId of ["first-note", "second-note"]) {294+      await vault.addEntry({ type: "note", title: "Same note", username: "[email protected]", passkey: makePasskey({ rpId: "example.com", credentialId }) });295+    }296+    await vault.consolidatePasskeyEntries();297+    expect(vault.getEntryById(login.id)?.passkey).toBeUndefined();298+    expect(vault.countDuplicates()).toBe(0);299+    expect(await vault.deduplicateEntries()).toBe(0);300+    expect(vault.getEntries()).toHaveLength(3);301+  });302+303+  it.each([304+    ["edit", "before", "read"], ["delete", "before", "read"], ["purge", "before", "read"],305+    ["edit", "after", "read"], ["delete", "after", "read"], ["purge", "after", "read"],306+    ["edit", "before", "write"], ["delete", "before", "write"], ["purge", "before", "write"],307+  ])("failed consolidation preserves an overlapping %s that finishes %s a %s failure", async (operation, completion, failedStage) => {308+    await vault.addEntry({ type: "login", title: "Login", username: "[email protected]", password: "pw", url: "https://example.com" });309+    await vault.addEntry({ type: "login", title: "Passkey", username: "[email protected]", url: "https://example.com", passkey: makePasskey({ rpId: "example.com", credentialId: "persisted" }) });310+    const other = await vault.addEntry({ type: "login", title: "Other", username: "other", password: "pw", url: "https://other.com" });311+    let failConsolidation!: (error: Error) => void;312+    let entered!: () => void;313+    const blocked = new Promise<void>((resolve) => { entered = resolve; });314+    const read = vi.mocked(chrome.storage.local.get).getMockImplementation()!;315+    let intercept = true;316+    let delayOther = false;317+    let resumeOther!: () => void;318+    let otherEntered!: () => void;319+    const otherBlocked = new Promise<void>((resolve) => { otherEntered = resolve; });320+    const get = vi.spyOn(chrome.storage.local, "get").mockImplementation(async (keys) => {321+      if (intercept && failedStage === "read" && keys === "peach_vault_a") {322+        intercept = false;323+        entered();324+        await new Promise<never>((_resolve, reject) => { failConsolidation = reject; });325+      }326+      if (delayOther && keys === "peach_vault_a") {327+        delayOther = false;328+        otherEntered();329+        await new Promise<void>((resolve) => { resumeOther = resolve; });330+      }331+      return Reflect.apply(read, chrome.storage.local, [keys]);332+    });333+    const write = vi.mocked(chrome.storage.local.set).getMockImplementation()!;334+    const set = vi.spyOn(chrome.storage.local, "set").mockImplementation(async (data) => {335+      if (intercept && failedStage === "write" && "peach_vault_a" in data) {336+        intercept = false;337+        entered();338+        await new Promise<never>((_resolve, reject) => { failConsolidation = reject; });339+      }340+      return Reflect.apply(write, chrome.storage.local, [data]);341+    });342+    const failed = vault.consolidatePasskeyEntries().then(() => null, error => error);343+    await blocked;344+    if (operation === "purge") await vault.deleteEntry(other.id);345+    delayOther = completion === "after";346+    const otherWrite = operation === "edit"347+      ? vault.updateEntry(other.id, { notes: "Successful overlapping edit" })348+      : operation === "delete" ? vault.deleteEntry(other.id) : vault.purgeEntry(other.id);349+    if (completion === "after") await otherBlocked;350+    else await otherWrite;351+    const expectedTombstones = vault.getTombstoneManifest();352+    const expectedEntries = vault.getEntries();353+    const expectedDeleted = vault.getDeletedEntries();354+    failConsolidation(new Error("consolidation save failed"));355+    expect(await failed).toMatchObject({ message: "consolidation save failed" });356+    if (completion === "after") {357+      resumeOther();358+      await otherWrite;359+    }360+    get.mockRestore();361+    set.mockRestore();362+    expect(vault.getTombstoneManifest()).toEqual(expectedTombstones);363+    expect(vault.getEntries()).toEqual(expectedEntries);364+    expect(vault.getDeletedEntries()).toEqual(expectedDeleted);365+    await vault.lock();366+    expect(await vault.unlock("consolidate-test-pass")).toBe(true);367+    expect(vault.getEntries()).toEqual(expectedEntries);368+    expect(vault.getDeletedEntries()).toEqual(expectedDeleted);369+    expect(vault.getTombstoneManifest()).toEqual(expectedTombstones);370+    if (operation === "purge") expect(vault.getTombstoneManifest()[other.id]).toBeGreaterThan(0);371+  });372+263373 });

view file

src/background/vault.ts+56 −98
@@ -1205,93 +1205,42 @@12051205   };12061206 }12071207 1208-/**1209- * Consolidate duplicate passkey records after registration.1210- *1211- * Multiple registrations for one RP can leave duplicate passkey records. This1212- * pass collapses the duplicates:1213- *1214- *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.1215- *   2. Within each group, the most recently-active credential wins (prefer1216- *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).1217- *   3. If a NON-passkey login entry exists for that RP (matched by url or1218- *      additionalUrls hostname), attach the winning passkey to it and1219- *      soft-delete every passkey-bearing entry in the group.1220- *   4. Otherwise, soft-delete every loser in the group, keeping the winner1221- *      as a passkey-only entry.1222- *1223- * Soft delete (deletedAt) rather than splice — the trash flow keeps the1224- * record around for retention and the user can restore if the heuristic1225- * picked wrong. The `merged` flag goes back to decodePayload so the1226- * unlock path persists the consolidated shape immediately.1227- */1208+// Keep ambiguous records intact: an RP or account can own several credentials.12281209 function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {12291210   let merged = false;1230-  const now = Date.now();1231-1232-  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);1233-  const byRpId = new Map<string, VaultEntry[]>();1234-  for (const e of candidates) {1235-    const rpId = e.passkey!.rpId;1236-    const list = byRpId.get(rpId);1237-    if (list) list.push(e);1238-    else byRpId.set(rpId, [e]);1239-  }1240-1241-  for (const [rpId, group] of byRpId) {1242-    if (group.length === 0) continue;1243-    group.sort((a, b) => {1244-      const aT =1245-        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;1246-      const bT =1247-        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;1248-      return bT - aT;1249-    });1250-    const winner = group[0]!;1251-1252-    // Look for a NON-passkey login entry matching this RP. Use the URL1253-    // hostname rather than a substring search so a "login.foo.com" entry1254-    // doesn't accidentally absorb a passkey for "foo.com".1255-    const loginTarget = entries.find((e) => {1256-      if (e.deletedAt || e.passkey || e.type !== "login") return false;1257-      if (e.url && extractDomain(e.url) === rpId) return true;1258-      for (const extra of e.additionalUrls ?? []) {1259-        if (extractDomain(extra) === rpId) return true;1260-      }1261-      return false;1262-    });1263-1264-    if (loginTarget) {1265-      loginTarget.passkey = winner.passkey;1266-      // A passkey entry may also carry the site's TOTP seed. Preserve it when1267-      // the passkey is consolidated onto an existing login instead of1268-      // soft-deleting the only record that held the 2FA configuration.1269-      if (!loginTarget.totp && winner.totp) {1270-        loginTarget.totp = winner.totp;1271-        loginTarget.totpAlgorithm = winner.totpAlgorithm;1272-        loginTarget.totpDigits = winner.totpDigits;1273-        loginTarget.totpPeriod = winner.totpPeriod;1274-      }1275-      loginTarget.modifiedAt = now;1276-      for (const dup of group) {1277-        if (!dup.deletedAt) {1278-          dup.deletedAt = now;1279-          dup.modifiedAt = now;1211+  const transferable = new Set(["id", "type", "title", "username", "url", "passkey", "createdAt", "modifiedAt", "totp", "totpAlgorithm", "totpDigits", "totpPeriod"]);1212+  for (const source of entries.filter((entry) => !entry.deletedAt && entry.passkey)) {1213+    const passkey = source.passkey!;1214+    if (source.type !== "login" && source.type !== "passkey") continue;1215+    if (!passkey.userName || (source.username && source.username !== passkey.userName)) continue;1216+    if (Object.entries(source).some(([key, value]) => !transferable.has(key) && value !== undefined && value !== "")) continue;1217+    const targets = entries.filter((entry) => {1218+      if (entry.deletedAt || entry.passkey || entry.type !== "login" || entry.username !== passkey.userName) return false;1219+      return [entry.url, ...(entry.additionalUrls ?? [])].some((url) => {1220+        if (!url) return false;1221+        try {1222+          return new URL(url.includes("://") ? url : `https://${url}`).hostname === passkey.rpId;1223+        } catch {1224+          return false;12801225         }1281-      }1282-      merged = true;1283-    } else if (group.length > 1) {1284-      for (let i = 1; i < group.length; i += 1) {1285-        const dup = group[i]!;1286-        if (!dup.deletedAt) {1287-          dup.deletedAt = now;1288-          dup.modifiedAt = now;1289-        }1290-      }1291-      merged = true;1226+      });1227+    });1228+    if (targets.length !== 1) continue;1229+    const target = targets[0]!;1230+    if (source.totp && target.totp && (source.totp !== target.totp || source.totpAlgorithm !== target.totpAlgorithm || source.totpDigits !== target.totpDigits || source.totpPeriod !== target.totpPeriod)) continue;1231+    target.passkey = passkey;1232+    if (source.totp && !target.totp) {1233+      target.totp = source.totp;1234+      target.totpAlgorithm = source.totpAlgorithm;1235+      target.totpDigits = source.totpDigits;1236+      target.totpPeriod = source.totpPeriod;12921237     }1238+    const stamp = monotonicEntryTimestamp(Math.max(source.modifiedAt, target.modifiedAt));1239+    target.modifiedAt = stamp;1240+    source.modifiedAt = stamp;1241+    source.deletedAt = stamp;1242+    merged = true;12931243   }1294-12951244   return { merged };12961245 }12971246 @@ -2715,17 +2664,25 @@27152664   return nextEntry;27162665 }27172666 2718-/**2719- * Run the passkey-merge pass on the live in-memory entries and persist if2720- * anything changed. Called immediately after any passkey registration so that2721- * a same-domain TOTP-only entry already in the vault gets consolidated right2722- * away instead of waiting until the next lock/unlock cycle.2723- */2667+/// Attach unambiguous account credentials without discarding other entry data.27242668 export async function consolidatePasskeyEntries(): Promise<void> {27252669   if (!derivedKey || vaultCreatesInFlight) return;2726-  const { merged } = mergePasskeyOnlyIntoLogins(entries);2727-  if (merged) {2670+  const epoch = vaultEpoch;2671+  const rollback = entries;2672+  const next = entries.map((entry) => ({ ...entry }));2673+  if (!mergePasskeyOnlyIntoLogins(next).merged) return;2674+  const unchanged = next.map((entry) => ({ entry, modifiedAt: entry.modifiedAt }));2675+  entries = next;2676+  try {27282677     await persistEntries();2678+  } catch (err) {2679+    // Other writers can replace entries or mutate a deletion in this array.2680+    if (epoch === vaultEpoch && entries === next && entries.length === unchanged.length &&2681+      unchanged.every(({ entry, modifiedAt }, index) => entries[index] === entry && entry.modifiedAt === modifiedAt)) {2682+      entries = rollback;2683+      buildDomainIndexSync(entries);2684+    }2685+    throw err;27292686   }27302687 }27312688 @@ -3156,7 +3113,8 @@31563113   // Reconcile direct soft-delete callers while restoring the previous map if31573114   // storage rejects the save.31583115   const previousTombstones = tombstones;3159-  tombstones = new Map(tombstones);3116+  const pendingTombstones = new Map(tombstones);3117+  tombstones = pendingTombstones;31603118   reconcileTombstones();31613119   try {31623120     if (vaultMode === "decoy") {@@ -3165,7 +3123,7 @@31653123       await persistSlotA(reason);31663124     }31673125   } catch (err) {3168-    tombstones = previousTombstones;3126+    if (tombstones === pendingTombstones) tombstones = previousTombstones;31693127     throw err;31703128   }31713129   buildDomainIndexSync(entries);@@ -3442,14 +3400,14 @@34423400 // ---------------------------------------------------------------------------34433401 34443402 function entryDupeKey(e: VaultEntry): string {3445-  if (e.type === "note") return `note|${e.title.toLowerCase()}`;3446-  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins3447-  // on different sites that happen to share a username are still distinct;3448-  // two passkey credentials for the same RP+user are duplicates regardless3449-  // of any login fields they may also carry.34503403   if (e.passkey) {3451-    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;3404+    // Equal identities can still carry different passwords, notes or TOTP data.3405+    const content = Object.fromEntries(Object.entries(e)3406+      .filter(([key]) => key !== "id" && key !== "createdAt" && key !== "modifiedAt")3407+      .sort(([a], [b]) => a.localeCompare(b)));3408+    return `passkey|${e.passkey.rpId}|${e.passkey.credentialId}|${JSON.stringify(content)}`;34523409   }3410+  if (e.type === "note") return `note|${e.title.toLowerCase()}`;34533411   return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;34543412 }34553413 

view file

src/content/passkeys-firefox.test.ts+18 −1
@@ -135,6 +135,7 @@135135 136136 describe("PB-26-209: exportFunction privileged bridge", () => {137137   let nativeGet: ReturnType<typeof vi.fn>;138+  let nativeCreate: ReturnType<typeof vi.fn>;138139   beforeEach(async () => {139140     vi.resetModules();140141     setupChromeMock();@@ -150,7 +151,7 @@150151 151152     // jsdom doesn't have navigator.credentials by default — install a152153     // native stub that the bridge will replace via exportFunction.153-    const nativeCreate = vi.fn(async () => null);154+    nativeCreate = vi.fn(async () => null);154155     nativeGet = vi.fn(async () => null);155156     Object.defineProperty(navigator, "credentials", {156157       value: { create: nativeCreate, get: nativeGet },@@ -162,6 +163,22 @@162163 163164   afterEach(() => {164165     vi.unstubAllGlobals();166+  });167+168+169+  it("serializes exclusion IDs from sliced BufferSource descriptors", async () => {170+    mockSendMessage.mockResolvedValue({ ok: false, error: "not_applicable" });171+    const options = makeCreateOptions();172+    const bytes = new Uint8Array([9, 1, 2, 3, 9]);173+    options.publicKey!.excludeCredentials = [{ type: "public-key", id: new DataView(bytes.buffer, 1, 3), transports: ["internal"] }];174+    await navigator.credentials.create(options);175+    expect(mockSendMessage).toHaveBeenCalledWith(expect.objectContaining({ payload: expect.objectContaining({ excludeCredentials: [{ type: "public-key", id: "AQID", transports: ["internal"] }] }) }));176+  });177+178+  it("preserves InvalidStateError without native fallback", async () => {179+    mockSendMessage.mockResolvedValue({ ok: false, error: "credential_excluded" });180+    await expect(navigator.credentials.create(makeCreateOptions())).rejects.toMatchObject({ name: "InvalidStateError" });181+    expect(nativeCreate).not.toHaveBeenCalled();165182   });166183 167184   describe("no forgeable response channel", () => {

view file

src/content/passkeys-firefox.ts+9 −1
@@ -121,6 +121,11 @@121121               clientDataJSON: Array.from(clientDataJSON),122122               origin: window.location.origin,123123               pubKeyCredParams: publicKey.pubKeyCredParams,124+              excludeCredentials: (publicKey.excludeCredentials ?? []).map((descriptor) => ({125+                type: descriptor.type,126+                id: bufferToBase64url(toArrayBuffer(descriptor.id)),127+                transports: descriptor.transports,128+              })),124129               authenticatorSelection: publicKey.authenticatorSelection,125130               timeout: publicKey.timeout,126131               attestation: publicKey.attestation,@@ -129,6 +134,9 @@129134 130135           if (!response?.ok) {131136             const error = response?.error;137+            if (error === "credential_excluded") {138+              throw new window.DOMException("A listed credential already exists.", "InvalidStateError");139+            }132140             if (error === "user_cancelled") {133141               throw new window.DOMException(134142                 "The operation either timed out or was not allowed.",@@ -149,7 +157,7 @@149157           const cred = validateCreateCredential(response.credential);150158           return buildPublicKeyCredential(cred);151159         } catch (err) {152-          if (err instanceof DOMException && err.name === "NotAllowedError") throw err;160+          if (err instanceof DOMException && (err.name === "NotAllowedError" || err.name === "InvalidStateError")) throw err;153161           // Validation failure or unexpected error — fail closed, fall through.154162           return originalCreate(options);155163         }

view file