33f62848e569
refuse accidental vault replacement (v5.3.14)
- time
- 2026-11-13 02:14 UTC · 2 weeks ago
- machine
- Junes-MacBook-Pro.local
- agent
- gpt-6
- session
- remediate interim audit findings
- parent
- 712a87ff1772
↓ peach-browser-33f62848.tar.gzatlas at this save
files changed14 files
manifest.firefox.json+1 −1manifest.json+1 −1package.json+1 −1src/background/messages.test.ts+16 −0src/background/messages.ts+17 −7src/background/recovery-words.test.ts+2 −2src/background/vault.test.ts+241 −0src/background/vault.ts+181 −74src/popup/App.boot.test.tsx+95 −0src/popup/App.tsx+25 −10src/popup/styles/popup.css+8 −0src/popup/views/Import.tsx+6 −2src/popup/views/Lock.tsx+12 −1src/popup/views/contracts.test.tsx+51 −4manifest.firefox.json+1 −1
@@ -1,7 +1,7 @@11 {22 "manifest_version": 3,33 "name": "Peach Password Manager",4- "version": "5.3.13",4+ "version": "5.3.14",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.13",5+ "version": "5.3.14",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.13",3+ "version": "5.3.14",44 "description": "Zero-knowledge password manager",55 "license": "GPL-3.0-only",66 "type": "module",src/background/messages.test.ts+16 −0
@@ -1084,6 +1084,22 @@10841084 await expect(pending).resolves.toMatchObject({ ok: true, data: true });10851085 });10861086 1087+ it.each([null, true, false, 1, {}, "replace", "warned-import "])("CREATE_VAULT rejects malformed replacement intent %j", async (replacement) => {1088+ const result = await dispatch({ type: "CREATE_VAULT", payload: { password: "new-password", replacement } });1089+ expect(result).toMatchObject({ ok: false, error: "invalid_payload" });1090+ expect(storage.peach_vault_a).toBeUndefined();1091+ });1092+1093+ it("CREATE_VAULT refuses ordinary replacement of an existing locked vault", async () => {1094+ const vault = await import("./vault");1095+ await vault.createVault("original-password");1096+ await vault.lock();1097+ const before = structuredClone(storage);1098+ expect(await dispatch({ type: "CREATE_VAULT", payload: { password: "new-password" } })).toMatchObject({ ok: false, error: "vault_already_exists" });1099+ expect(storage).toEqual(before);1100+ expect(await vault.unlock("original-password")).toBe(true);1101+ });1102+10871103 it("CREATE_VAULT rejects an empty master password (audit HIGH — no empty-key vault)", async () => {10881104 const res = await dispatch({ type: "CREATE_VAULT", payload: { password: "" } });10891105 expect(res.ok).toBe(false);src/background/messages.ts+17 −7
@@ -419,19 +419,29 @@419419 420420 switch (msg.type) {421421 case "CREATE_VAULT": {422- const { password } = msg.payload as { password: string };422+ const { password, replacement } = (msg.payload ?? {}) as { password?: unknown; replacement?: unknown };423423 // Refuse to create a vault under an empty master password — the derived424424 // key would be publicly known and the at-rest AES-GCM protection void425425 // (audit HIGH; the CSV-import path previously passed ""). Length/strength426426 // policy lives in the onboarding UI; this is the non-negotiable floor.427- if (typeof password !== "string" || password.length === 0) {427+ if (typeof password !== "string" || password.length === 0 || (replacement !== undefined && replacement !== "warned-import")) {428428 return { ok: false, error: "invalid_payload" };429429 }430- await vault.createVault(password);431- await setupAutoLock();432- broadcastToContentScripts({ type: "VAULT_UNLOCKED" });433- onVaultUnlocked();434- return { ok: true };430+ const created = await vault.createVault(password, replacement);431+ if (!created.unlocked) return { ok: true, data: created };432+ try {433+ await setupAutoLock();434+ const unlocked = vault.isUnlocked();435+ if (unlocked) {436+ broadcastToContentScripts({ type: "VAULT_UNLOCKED" });437+ onVaultUnlocked();438+ }439+ return { ok: true, data: { ...created, unlocked } };440+ } catch (error) {441+ console.warn("[Peach] vault saved; unlock setup failed:", error);442+ await vault.lock().catch((lockError) => console.warn("[Peach] creation cleanup failed:", lockError));443+ return { ok: true, data: { ...created, unlocked: false } };444+ }435445 }436446 case "CREATE_VAULT_FROM_ROOT_KEY": {437447 const { password, rootKeyHex } = (msg.payload ?? {}) as {src/background/recovery-words.test.ts+2 −2
@@ -503,7 +503,7 @@503503 const spy = vi.spyOn(argon, 'deriveKey').mockImplementationOnce(async (...args) => {504504 const key = await derive(...args); await paused; return key;505505 });506- const creating = vault.createVault('concurrent-creation-password').then(() => 'created', (error: Error) => error.message);506+ const creating = vault.createVault('concurrent-creation-password', 'warned-import').then(() => 'created', (error: Error) => error.message);507507 const recovering = await vault.recoverWithWords(words, 'recovered-password').then(() => 'recovered', (error: Error) => error.message);508508 const before = JSON.stringify(storage);509509 await vault.lock();@@ -529,7 +529,7 @@529529 const spy = vi.spyOn(crypto.subtle, 'encrypt').mockImplementationOnce(async (...args) => {530530 const value = await encrypt(...args); started(); await paused; return value;531531 });532- const creating = vault.createVault('concurrent-creation-password').then(() => 'created', (error: Error) => error.message);532+ const creating = vault.createVault('concurrent-creation-password', 'warned-import').then(() => 'created', (error: Error) => error.message);533533 await ready;534534 await vault.lock();535535 const recovering = await vault.recoverWithWords(words, 'recovered-password').then(() => 'recovered', (error: Error) => error.message);src/background/vault.test.ts+241 −0
@@ -90,6 +90,247 @@9090 }));9191 });9292 93+ it.each(["peach_vault_a", "peach_vault_b"].flatMap((slot) => [null, false, 0, {}, "broken"].map((value) => ({ slot, value }))))("refuses existing $slot value $value before deriving a password", async ({ slot, value }) => {94+ storage[slot] = value;95+ const argon = await import("../crypto/argon2");96+ const derive = vi.spyOn(argon, "deriveKey");97+ const vault = await import("./vault");98+ await expect(vault.createVault("replacement-password")).rejects.toThrow("vault_already_exists");99+ expect(derive).not.toHaveBeenCalled();100+ expect(await vault.hasVault()).toBe(true);101+ expect(storage[slot]).toEqual(value);102+ derive.mockRestore();103+ });104+105+ it("keeps the unlocked vault intact when a warned replacement commit fails", async () => {106+ const vault = await import("./vault");107+ await vault.createVault("original-password");108+ await vault.addEntry({ type: "note", title: "Preserve me", notes: "original" });109+ await vault.lock();110+ await vault.unlock("original-password");111+ const before = structuredClone(storage);112+ const beforeSession = structuredClone(sessionStorage);113+ const argon = await import("../crypto/argon2");114+ const derive = argon.deriveKey;115+ const stagedKeys: Uint8Array[] = [];116+ const spy = vi.spyOn(argon, "deriveKey").mockImplementation(async (...args) => {117+ const key = await derive(...args); stagedKeys.push(key); return key;118+ });119+ const root = vault.getRootKeyHex();120+ const set = vi.mocked(chrome.storage.local.set);121+ const write = set.getMockImplementation()!;122+ set.mockImplementation(async (value) => {123+ if ("peach_vault_a" in value) throw new Error("storage unavailable");124+ return (write as (next: Record<string, unknown>) => Promise<void>)(value);125+ });126+ await expect(vault.createVault("replacement-password", "warned-import")).rejects.toThrow();127+ for (const key of ["peach_vault_a", "peach_vault_b", "peach_vault_history", "peach_last_modified_at"]) expect(storage[key]).toEqual(before[key]);128+ expect(vault.getEntries().map((entry) => entry.title)).toEqual(["Preserve me"]);129+ expect(vault.getRootKeyHex()).toBe(root);130+ expect(sessionStorage).toEqual(beforeSession);131+ expect(stagedKeys).toHaveLength(1);132+ expect(stagedKeys[0]!.every((byte) => byte === 0)).toBe(true);133+ spy.mockRestore();134+ });135+136+ it("reports saved-but-locked if auto-lock setup fails after the commit", async () => {137+ const vault = await import("./vault");138+ vi.mocked(chrome.alarms.create).mockImplementationOnce(() => { throw new Error("alarms unavailable"); });139+ expect(await vault.createVault("new-password")).toEqual({ committed: true, unlocked: false });140+ expect(vault.isUnlocked()).toBe(false);141+ expect(storage.peach_vault_a).toBeDefined();142+ expect(await vault.unlock("new-password")).toBe(true);143+ });144+145+ it("commits warned replacement slots and their original snapshot together", async () => {146+ const vault = await import("./vault");147+ await vault.createVault("original-password");148+ const oldA = JSON.stringify(storage.peach_vault_a);149+ const oldB = JSON.stringify(storage.peach_vault_b);150+ vi.mocked(chrome.storage.local.set).mockClear();151+ await vault.createVault("replacement-password", "warned-import");152+ const writes = vi.mocked(chrome.storage.local.set).mock.calls.filter(([value]) => "peach_vault_a" in value);153+ expect(writes).toHaveLength(1);154+ expect(writes[0]![0]).toMatchObject({155+ peach_vault_b: expect.any(Object), peach_last_modified_at: expect.any(String),156+ peach_vault_history: { snapshots: [expect.objectContaining({ vault_a: oldA, vault_b: oldB })] },157+ });158+ });159+160+ it.each(["ordinary", "adoption"])("excludes concurrent creation while %s creation owns the vault", async (kind) => {161+ const vault = await import("./vault");162+ const first = kind === "ordinary" ? vault.createVault("first-password") : vault.createVaultFromRootKey("first-password", "42".repeat(32));163+ await expect(vault.createVault("second-password")).rejects.toThrow("vault_changed");164+ await first;165+ await vault.lock();166+ expect(await vault.unlock("first-password")).toBe(true);167+ expect(await vault.verifyMainPassword("second-password")).toBe(false);168+ });169+170+ it("fails closed when the initial vault lookup fails", async () => {171+ const vault = await import("./vault");172+ vi.mocked(chrome.storage.local.get).mockRejectedValueOnce(new Error("storage unavailable"));173+ await expect(vault.createVault("new-password")).rejects.toThrow("storage unavailable");174+ expect(storage).toEqual({});175+ expect(vault.isUnlocked()).toBe(false);176+ });177+178+ it("excludes creation while an earlier password unlock is deriving", async () => {179+ const vault = await import("./vault");180+ await vault.createVault("original-password");181+ await vault.lock();182+ const argon = await import("../crypto/argon2");183+ const started = deferred();184+ const release = deferred();185+ const derive = argon.deriveKey;186+ const spy = vi.spyOn(argon, "deriveKey").mockImplementationOnce(async (...args) => {187+ started.resolve(); await release.promise; return derive(...args);188+ });189+ const unlocking = vault.unlock("original-password");190+ await started.promise;191+ await expect(vault.createVault("replacement-password", "warned-import")).rejects.toThrow("vault_changed");192+ release.resolve();193+ expect(await unlocking).toBe(true);194+ spy.mockRestore();195+ });196+197+ it("reports a committed vault as locked when lock races its issued write", async () => {198+ const vault = await import("./vault");199+ const started = deferred();200+ const release = deferred();201+ vi.mocked(chrome.storage.local.set).mockImplementation(async (value) => {202+ if ("peach_vault_a" in value) { started.resolve(); await release.promise; }203+ Object.assign(storage, value);204+ });205+ const creating = vault.createVault("new-password");206+ await started.promise;207+ await vault.lock();208+ release.resolve();209+ expect(await creating).toEqual({ committed: true, unlocked: false });210+ expect(vault.isUnlocked()).toBe(false);211+ expect(await vault.unlock("new-password")).toBe(true);212+ });213+214+ it("orders removal after an issued creation commit", async () => {215+ const vault = await import("./vault");216+ const started = deferred();217+ const release = deferred();218+ const set = vi.mocked(chrome.storage.local.set);219+ set.mockImplementation(async (value) => {220+ if ("peach_vault_a" in value) { started.resolve(); await release.promise; }221+ Object.assign(storage, value);222+ });223+ const creating = vault.createVault("new-password").catch((error: Error) => error.message);224+ await started.promise;225+ let removed = false;226+ const removing = vault.withVaultRemoval(async () => { storage = {}; removed = true; });227+ await Promise.resolve();228+ expect(removed).toBe(false);229+ release.resolve();230+ expect(await creating).toEqual({ committed: true, unlocked: false });231+ await removing;232+ expect(storage).toEqual({});233+ expect(vault.isUnlocked()).toBe(false);234+ });235+236+ it("excludes creation while an earlier entry write is staged", async () => {237+ const vault = await import("./vault");238+ await vault.createVault("original-password");239+ const started = deferred();240+ const release = deferred();241+ const get = vi.mocked(chrome.storage.local.get);242+ const read = get.getMockImplementation()!;243+ get.mockImplementationOnce(async (...args) => { started.resolve(); await release.promise; return read(...args); });244+ const writing = vault.addEntry({ type: "note", title: "Preserve me", notes: "original" });245+ await started.promise;246+ await expect(vault.createVault("replacement-password", "warned-import")).rejects.toThrow("vault_changed");247+ release.resolve();248+ await writing;249+ expect(vault.getEntries()[0]?.title).toBe("Preserve me");250+ });251+252+ it("rejects sibling entry mutations before they change a staged replacement session", async () => {253+ const vault = await import("./vault");254+ await vault.createVault("original-password");255+ await vault.addEntry({ type: "note", title: "Original", notes: "original" });256+ const originalEntries = structuredClone(vault.getEntries());257+ const argon = await import("../crypto/argon2");258+ const started = deferred();259+ const release = deferred();260+ const derive = argon.deriveKey;261+ const spy = vi.spyOn(argon, "deriveKey").mockImplementationOnce(async (...args) => {262+ started.resolve(); await release.promise; return derive(...args);263+ });264+ const creating = vault.createVault("new-password", "warned-import").catch((error: Error) => error.message);265+ await started.promise;266+ await expect(vault.restoreEntries([{ ...originalEntries[0]!, id: "replacement", title: "Wrong session" }], "replace")).rejects.toThrow();267+ await expect(vault.addEntry({ type: "note", title: "Rejected", notes: "no" })).rejects.toThrow();268+ expect(vault.getEntries()).toEqual(originalEntries);269+ await vault.lock();270+ release.resolve();271+ expect(await creating).toBe("vault_changed");272+ spy.mockRestore();273+ });274+275+ it("prevents a rejected sibling write from restoring old entries after creation commits", async () => {276+ const vault = await import("./vault");277+ await vault.createVault("original-password");278+ await vault.addEntry({ type: "note", title: "Old vault", notes: "original" });279+ const started = deferred();280+ const release = deferred();281+ vi.mocked(chrome.storage.local.set).mockImplementation(async (value) => {282+ if ("peach_vault_a" in value) { started.resolve(); await release.promise; }283+ Object.assign(storage, value);284+ });285+ const creating = vault.createVault("new-password", "warned-import");286+ await started.promise;287+ release.resolve();288+ const writing = vault.addEntry({ type: "note", title: "Rejected", notes: "no" }).catch((error: Error) => error.message);289+ await creating;290+ await writing;291+ expect(vault.getEntries()).toEqual([]);292+ });293+294+ it("removes an adopted vault when lock cancels its issued creation commit", async () => {295+ const vault = await import("./vault");296+ const started = deferred();297+ const release = deferred();298+ vi.mocked(chrome.storage.local.set).mockImplementation(async (value) => {299+ if ("peach_vault_a" in value) { started.resolve(); await release.promise; }300+ Object.assign(storage, value);301+ });302+ const creating = vault.createVaultFromRootKey("new-password", "42".repeat(32)).catch((error: Error) => error.message);303+ await started.promise;304+ await vault.lock();305+ release.resolve();306+ expect(await creating).toBe("vault_changed");307+ expect(vault.isUnlocked()).toBe(false);308+ expect(await vault.hasVault()).toBe(false);309+ expect(storage.peach_last_modified_at).toBeUndefined();310+ expect((await vault.createVaultFromRootKey("new-password", "42".repeat(32))).vaultId).toBeTruthy();311+ });312+313+ it("reports a saved password change consistently when lock races the final stamp read", async () => {314+ const vault = await import("./vault");315+ await vault.createVault("original-password");316+ const started = deferred();317+ const release = deferred();318+ const get = vi.mocked(chrome.storage.local.get);319+ const read = get.getMockImplementation()!;320+ get.mockImplementation(async (...args) => {321+ if (args[0] === "peach_last_modified_at") { started.resolve(); await release.promise; }322+ return read(...args);323+ });324+ const changing = vault.changePassword("original-password", "new-password");325+ await started.promise;326+ await vault.lock();327+ release.resolve();328+ expect(await changing).toBe(true);329+ expect(vault.isUnlocked()).toBe(false);330+ expect(await vault.unlock("new-password")).toBe(true);331+ expect(await vault.verifyMainPassword("original-password")).toBe(false);332+ });333+93334 it("creates a vault and stores encrypted payload", async () => {94335 const vault = await import("./vault");95336 src/background/vault.ts+181 −74
@@ -87,6 +87,8 @@8787 let vaultRemovalsInFlight = 0;8888 let vaultWritesInFlight = 0;8989 let vaultCreatesInFlight = 0;90+let creationSettled: Promise<void> = Promise.resolve();91+let vaultUnlocksInFlight = 0;9092 let vaultReplacementInFlight = false;9193 let entries: VaultEntry[] = [];9294 // Tombstones outlive their full entry records so a peer that was offline@@ -225,6 +227,9 @@225227 226228 /** Set up a local PIN wrapper after proving the current master password. */227229 export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {230+ if (vaultCreatesInFlight) return false;231+ vaultWritesInFlight++;232+ try {228233 if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;229234 if (!(await verifyMainPassword(currentPassword))) return false;230235 @@ -238,6 +243,7 @@238243 } finally {239244 zeroKey(pinKey);240245 }246+ } finally { vaultWritesInFlight--; }241247 }242248 243249 async function clearPinUnlockStorage(): Promise<void> {@@ -252,15 +258,21 @@252258 253259 /** Remove the PIN wrapper after proving the current master password. */254260 export async function disablePinUnlock(currentPassword: string): Promise<boolean> {261+ if (vaultCreatesInFlight) return false;262+ vaultWritesInFlight++;263+ try {255264 if (!derivedKey || vaultMode !== "real") return false;256265 if (!(await verifyMainPassword(currentPassword))) return false;257266 await clearPinUnlockStorage();258267 return true;268+ } finally { vaultWritesInFlight--; }259269 }260270 261271 /** Unlock the real vault from its locally stored PIN-wrapped derived key. */262272 export async function unlockWithPin(pin: string): Promise<boolean> {263- if (recoveryInFlight || vaultRemovalsInFlight) return false;273+ vaultUnlocksInFlight++;274+ try {275+ if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;264276 if (!isValidPin(pin)) return false;265277 await loadSettings();266278 if (!settings.pinEnabled) return false;@@ -299,6 +311,7 @@299311 zeroKey(pinKey);300312 if (unwrappedKey) zeroKey(unwrappedKey);301313 }314+ } finally { vaultUnlocksInFlight--; }302315 }303316 304317 async function savePinWrap(stored: StoredPinWrap): Promise<void> {@@ -603,6 +616,7 @@603616 wrappedTag: string;604617 }> {605618 const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));619+ try {606620 607621 // Derive the recovery key from the BIP39 words encoding of the root key.608622 const words = await rootKeyToWords(rootKeyBytes);@@ -636,6 +650,7 @@636650 wrappedNonce: hex(nonce),637651 wrappedTag: tag,638652 };653+ } finally { zeroKey(rootKeyBytes); }639654 }640655 641656 async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{@@ -824,6 +839,7 @@824839 try {825840 await lock();826841 await recoverySettled;842+ await creationSettled;827843 return await remove();828844 } finally {829845 vaultRemovalsInFlight--;@@ -965,7 +981,7 @@965981 }966982 967983 async function writeSlot(key: string, vault: StoredVault): Promise<void> {968- if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");984+ if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");969985 vaultWritesInFlight++;970986 try {971987 await chrome.storage.local.set({ [key]: vault });@@ -1045,6 +1061,7 @@10451061 }10461062 10471063 async function stampLocalVaultMutation(): Promise<void> {1064+ if (vaultCreatesInFlight) throw new Error("vault_changed");10481065 const raw = await chrome.storage.local.get("peach_last_modified_at");10491066 const previous = Number(10501067 (raw as Record<string, unknown>).peach_last_modified_at,@@ -1053,6 +1070,7 @@10531070 Date.now(),10541071 Number.isFinite(previous) ? previous + 1 : 0,10551072 );1073+ if (vaultCreatesInFlight) throw new Error("vault_changed");10561074 await chrome.storage.local.set({10571075 peach_last_modified_at: String(next),10581076 });@@ -1411,65 +1429,97 @@14111429 }14121430 }14131431 1414-export async function createVault(password: string): Promise<void> {1415- if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1432+export async function createVault(password: string, replacement?: "warned-import"): Promise<{ committed: true; unlocked: boolean }> {1433+ if (replacement !== undefined && replacement !== "warned-import") throw new Error("invalid_payload");1434+ if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");14161435 vaultCreatesInFlight++;1436+ let settle!: () => void;1437+ creationSettled = new Promise<void>((resolve) => { settle = resolve; });1438+ let nextKey: Uint8Array | null = null;1439+ let nextRoot: Uint8Array | null = null;1440+ let committed = false;1441+ let publishedEpoch: number | null = null;1442+ const epoch = vaultEpoch;1443+ const check = () => {1444+ if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1445+ };14171446 try {1418- const epoch = vaultEpoch;1447+ const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1448+ check();1449+ const occupied = raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1450+ if (occupied && replacement !== "warned-import") throw new Error("vault_already_exists");14191451 const salt = generateSalt();1420- const key = await deriveKey(password, salt);1421- if (epoch !== vaultEpoch) { zeroKey(key); throw new Error("vault_changed"); }1422- if (recoveryInFlight || vaultRemovalsInFlight) { zeroKey(key); throw new Error("recovery_in_progress"); }1423- derivedKey = key;1452+ nextKey = await deriveKey(password, salt);1453+ check();1454+ const recovery = await generateAndWrapRootKey();1455+ nextRoot = unhex(recovery.rawRootKey);1456+ check();1457+ const encrypted = await encrypt(nextKey, encodePayload([], false, 0), "slot_a_v1");1458+ const pwRoot = await wrapRootKeyForDerivedKey(nextKey, nextRoot);1459+ const recoveryVaultKey = await encrypt(nextRoot, hex(nextKey), "recovery_vault_key_v1");1460+ check();1461+ const slotA: StoredVault = {1462+ ...encrypted, ...pwRoot, version: 1, salt: hex(salt),1463+ recovery_vault_key: recoveryVaultKey,1464+ recovery_salt: recovery.recoverySalt,1465+ recovery_wrapped_root_key: recovery.wrappedRootKey,1466+ recovery_nonce: recovery.wrappedNonce,1467+ recovery_tag: recovery.wrappedTag,1468+ };1469+ const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1470+ check();1471+ if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1472+ const previous = Number(raw.peach_last_modified_at);1473+ const update: Record<string, unknown> = {1474+ [SLOT_A]: slotA, [SLOT_B]: generateNoiseBlob(encrypted.ciphertext.length / 2),1475+ peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previous) ? previous + 1 : 0)),1476+ };1477+ if (occupied) {1478+ const history = raw[HISTORY_KEY] as VaultHistory | undefined;1479+ const snapshot: VaultSnapshot = {1480+ id: crypto.randomUUID(), savedAt: Date.now(), reason: "restore", entryCount: null,1481+ vault_a: JSON.stringify(raw[SLOT_A] ?? null), vault_b: JSON.stringify(raw[SLOT_B] ?? null),1482+ };1483+ update[HISTORY_KEY] = { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) };1484+ }1485+ try { await chrome.storage.local.set(update); }1486+ catch (error) { throw mapStorageError(error); }1487+ committed = true;1488+ if (epoch !== vaultEpoch || vaultRemovalsInFlight) return { committed: true, unlocked: false };1489+ const previousKey = derivedKey;1490+ const previousRoot = rootKey;1491+ publishedEpoch = ++vaultEpoch;1492+ derivedKey = nextKey;1493+ rootKey = nextRoot;1494+ nextKey = null;1495+ nextRoot = null;14241496 entries = [];14251497 tombstones = new Map();14261498 vaultMode = "real";14271499 duressConfigured = false;14281500 buildDomainIndexSync(entries);1429-1430- // Generate and wrap the root key for recovery word escrow.1431- const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =1432- await generateAndWrapRootKey();1433- if (epoch !== vaultEpoch) throw new Error("vault_changed");1434- rootKey = unhex(rawRootKey);1435-1436- const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);1437- const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");1438-1439- // Second wrapping of rootKey under derivedKey so future unlocks can rehydrate1440- // it without recovery words (H2/COR-006).1441- const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);1442-1443- const slotA: StoredVault = {1444- recovery_vault_key: await encrypt(rootKey, hex(derivedKey), "recovery_vault_key_v1"),1445- version: 1,1446- salt: hex(salt),1447- nonce,1448- ciphertext,1449- tag,1450- recovery_salt: recoverySalt,1451- recovery_wrapped_root_key: wrappedRootKey,1452- recovery_nonce: wrappedNonce,1453- recovery_tag: wrappedTag,1454- ...pwRoot,1455- };1456- if (epoch !== vaultEpoch) throw new Error("vault_changed");1457- await writeSlot(SLOT_A, slotA);1458-1459- // Matching-size noise blob for slot B, so a fresh install shows two1460- // similarly-shaped records regardless of whether duress is ever set up.1461- await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1462- await stampLocalVaultMutation();1463-1464- // An identity created while this install had no vault was sealed under the1465- // password alone; the vault keys exist now, so re-seal it under them.1501+ if (previousKey) zeroKey(previousKey);1502+ if (previousRoot) zeroKey(previousRoot);1503+ await clearSessionKey();1504+ if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };14661505 await identityHooks?.onVaultCreated(password).catch((error) => {14671506 console.warn("[Peach] local identity promotion failed:", error);14681507 });1469-1508+ if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };14701509 touchAutoLock();1510+ return { committed: true, unlocked: true };1511+ } catch (error) {1512+ if (!committed) throw error;1513+ console.warn("[Peach] vault saved; unlock required:", error);1514+ if (publishedEpoch === vaultEpoch) {1515+ await lock().catch((lockError) => console.warn("[Peach] creation session cleanup failed:", lockError));1516+ }1517+ return { committed: true, unlocked: false };14711518 } finally {1519+ if (nextKey) zeroKey(nextKey);1520+ if (nextRoot) zeroKey(nextRoot);14721521 vaultCreatesInFlight--;1522+ settle();14731523 }14741524 }14751525 @@ -1482,7 +1532,7 @@14821532 password: string,14831533 rootKeyHex: string,14841534 ): Promise<{ vaultId: string }> {1485- if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1535+ if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");14861536 if (typeof password !== "string" || password.length === 0) {14871537 throw new Error("ADOPT_INVALID_PASSWORD");14881538 }@@ -1490,16 +1540,22 @@14901540 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");14911541 }14921542 1543+ if (vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");14931544 const rootKeyBytes = unhex(rootKeyHex);14941545 if (rootKeyBytes.length !== 32) {14951546 rootKeyBytes.fill(0);14961547 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");14971548 }14981549 1550+ vaultCreatesInFlight++;1551+ let settle!: () => void;1552+ creationSettled = new Promise<void>((resolve) => { settle = resolve; });1553+ const epoch = vaultEpoch;14991554 let nextDerivedKey: Uint8Array | null = null;15001555 let sessionRootKey: Uint8Array | null = null;1556+ let committed = false;15011557 try {1502- if ((await loadSlot(SLOT_A)) !== null) {1558+ if (await hasVault()) {15031559 throw new Error("ADOPT_VAULT_ALREADY_EXISTS");15041560 }15051561 @@ -1528,7 +1584,11 @@15281584 ...pwRoot,15291585 };15301586 const slotB = generateNoiseBlob(ciphertext.length / 2);1587+ if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");15311588 await commitCreatedVaultSlots(slotA, slotB);1589+ committed = true;1590+ if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1591+ vaultEpoch++;15321592 15331593 const previousDerivedKey = derivedKey;15341594 const previousRootKey = rootKey;@@ -1552,7 +1612,16 @@15521612 });15531613 15541614 return { vaultId };1615+ } catch (error) {1616+ if (committed) {1617+ // Removal cannot use withVaultRemoval while this operation owns creationSettled.1618+ try { await lock(); }1619+ finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, "peach_last_modified_at"]); }1620+ }1621+ throw error;15551622 } finally {1623+ vaultCreatesInFlight--;1624+ settle();15561625 rootKeyBytes.fill(0);15571626 if (nextDerivedKey) zeroKey(nextDerivedKey);15581627 if (sessionRootKey) sessionRootKey.fill(0);@@ -1560,7 +1629,8 @@15601629 }15611630 15621631 export async function hasVault(): Promise<boolean> {1563- return (await loadSlot(SLOT_A)) !== null;1632+ const raw = await chrome.storage.local.get([SLOT_A, SLOT_B]);1633+ return raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;15641634 }15651635 15661636 /**@@ -1573,6 +1643,9 @@15731643 }15741644 15751645 export async function setupDuress(duressPassword: string): Promise<void> {1646+ if (vaultCreatesInFlight) throw new Error("vault_changed");1647+ vaultWritesInFlight++;1648+ try {15761649 if (!derivedKey || vaultMode !== "real") {15771650 throw new Error("vault must be unlocked in real mode");15781651 }@@ -1606,9 +1679,13 @@16061679 // flag is written — the bit lives inside the encrypted envelope.16071680 duressConfigured = true;16081681 await persistSlotA();1682+ } finally { vaultWritesInFlight--; }16091683 }16101684 16111685 export async function disableDuress(): Promise<void> {1686+ if (vaultCreatesInFlight) throw new Error("vault_changed");1687+ vaultWritesInFlight++;1688+ try {16121689 if (!derivedKey || vaultMode !== "real") {16131690 throw new Error("vault must be unlocked in real mode");16141691 }@@ -1622,6 +1699,7 @@16221699 16231700 duressConfigured = false;16241701 await persistSlotA();1702+ } finally { vaultWritesInFlight--; }16251703 }16261704 16271705 // L14/COR-015: this function intentionally checks slot A (real vault) only.@@ -1649,7 +1727,9 @@16491727 password: string,16501728 derive: typeof deriveKey,16511729 ): Promise<boolean> {1652- if (recoveryInFlight || vaultRemovalsInFlight) return false;1730+ vaultUnlocksInFlight++;1731+ try {1732+ if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;16531733 const epoch = vaultEpoch;16541734 const stale = () => epoch !== vaultEpoch;16551735 // Load both current-format slots in parallel. Both exist on a supported@@ -1807,6 +1887,7 @@18071887 lastUnlockFailureReason = resultB.reason;18081888 }18091889 return false;1890+ } finally { vaultUnlocksInFlight--; }18101891 }18111892 18121893 // ---------------------------------------------------------------------------@@ -1886,7 +1967,9 @@18861967 * No-ops if the vault is already unlocked.18871968 */18881969 export async function restoreFromSession(): Promise<boolean> {1889- if (recoveryInFlight || vaultRemovalsInFlight) return false;1970+ vaultUnlocksInFlight++;1971+ try {1972+ if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;18901973 if (derivedKey !== null) return true;18911974 if (restoreInFlight) return restoreInFlight;18921975 const task = restoreFromSessionInner();@@ -1896,6 +1979,7 @@18961979 } finally {18971980 restoreInFlight = null;18981981 }1982+ } finally { vaultUnlocksInFlight--; }18991983 }19001984 19011985 async function restoreFromSessionInner(): Promise<boolean> {@@ -2014,7 +2098,9 @@20142098 export async function unlockWithKey(20152099 masterKeyHex: string,20162100 ): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2017- if (recoveryInFlight || vaultRemovalsInFlight) return { ok: false, error: "recovery_in_progress" };2101+ vaultUnlocksInFlight++;2102+ try {2103+ if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };20182104 const epoch = vaultEpoch;20192105 const stale = () => epoch !== vaultEpoch;20202106 let masterKeyBytes: Uint8Array | null = null;@@ -2054,6 +2140,7 @@20542140 if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);20552141 return { ok: false, error: "invalid_key" };20562142 }2143+ } finally { vaultUnlocksInFlight--; }20572144 }20582145 20592146 // --- Adoption duress-slot helpers (passthrough, no decrypt) ---@@ -2077,6 +2164,9 @@20772164 * it as a non-fatal snapshot failure. Never decrypts.20782165 */20792166 export async function installAdoptedDuressSlot(json: string): Promise<void> {2167+ if (vaultCreatesInFlight) throw new Error("vault_changed");2168+ vaultWritesInFlight++;2169+ try {20802170 let parsed: StoredVault;20812171 try {20822172 const raw = JSON.parse(json) as unknown;@@ -2091,6 +2181,7 @@20912181 throw err;20922182 }20932183 await writeSlot(SLOT_B, parsed);2184+ } finally { vaultWritesInFlight--; }20942185 }20952186 20962187 /**@@ -2120,7 +2211,7 @@21202211 | { ok: true; entryCount: number }21212212 | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }21222213 > {2123- if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight) throw new Error("vault_changed");2214+ if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");21242215 vaultReplacementInFlight = true;21252216 try {21262217 let parsedSlotA: StoredVault;@@ -2280,7 +2371,7 @@22802371 }22812372 22822373 export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2283- if (!derivedKey) throw new Error("vault_locked");2374+ if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");22842375 22852376 const now = Date.now();22862377 const added: VaultEntry[] = [];@@ -2318,7 +2409,7 @@23182409 incoming: VaultEntry[],23192410 mode: "replace" | "merge"23202411 ): Promise<{ added: number; updated: number; skipped: number }> {2321- if (!derivedKey) throw new Error("vault_locked");2412+ if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");23222413 23232414 // A replace with zero incoming entries is almost certainly a caller bug23242415 // (e.g. an import that silently dropped everything). Refuse rather than@@ -2562,7 +2653,7 @@25622653 if (confirmation !== "REPLACE_ALL") {25632654 throw new Error("clearVaultEntries requires explicit confirmation");25642655 }2565- if (!derivedKey) throw new Error("vault_locked");2656+ if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");25662657 for (const entry of entries) {25672658 if (!entry.deletedAt) {25682659 const stamp = monotonicEntryTimestamp(Math.max(@@ -2578,7 +2669,7 @@25782669 }25792670 25802671 export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {2581- if (!derivedKey) throw new Error("vault_locked");2672+ if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");25822673 25832674 const sanitized = sanitizeEntryDraft(entry);25842675 const now = Date.now();@@ -2607,8 +2698,9 @@26072698 26082699 // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)26092700 if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {2701+ const breachEpoch = vaultEpoch;26102702 checkBreach(nextEntry.password).then(async (count) => {2611- if (count > 0) {2703+ if (count > 0 && breachEpoch === vaultEpoch && !vaultCreatesInFlight) {26122704 const idx = entries.findIndex((e) => e.id === nextEntry.id);26132705 if (idx !== -1) {26142706 entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };@@ -2630,7 +2722,7 @@26302722 * away instead of waiting until the next lock/unlock cycle.26312723 */26322724 export async function consolidatePasskeyEntries(): Promise<void> {2633- if (!derivedKey) return;2725+ if (!derivedKey || vaultCreatesInFlight) return;26342726 const { merged } = mergePasskeyOnlyIntoLogins(entries);26352727 if (merged) {26362728 await persistEntries();@@ -2641,7 +2733,7 @@26412733 id: string,26422734 patch: Partial<VaultEntry>26432735 ): Promise<void> {2644- if (!derivedKey) throw new Error("vault_locked");2736+ if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");26452737 26462738 const idx = entries.findIndex((entry) => entry.id === id);26472739 if (idx === -1 || entries[idx].deletedAt) {@@ -2724,7 +2816,7 @@27242816 }27252817 27262818 export async function deleteEntry(id: string): Promise<void> {2727- if (!derivedKey) throw new Error("vault_locked");2819+ if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");27282820 27292821 const entry = entries.find((item) => item.id === id);27302822 if (!entry || entry.deletedAt) {@@ -2806,7 +2898,7 @@28062898 // are dropped silently. This is the deliberate trade-off for a simple,28072899 // conflict-free merge — per-field CRDT merge is out of scope. Guidance for28082900 // users: edit a given entry on one device at a time.2809- if (!derivedKey || vaultMode === "decoy") throw new Error("vault_locked");2901+ if (!derivedKey || vaultCreatesInFlight || vaultMode === "decoy") throw new Error("vault_locked");28102902 28112903 const received = remoteEntries.length + Object.keys(remoteTombstones).length;28122904 let applied = 0;@@ -2898,7 +2990,7 @@28982990 }28992991 29002992 export async function restoreEntry(id: string): Promise<void> {2901- if (!derivedKey) throw new Error("vault_locked");2993+ if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");29022994 const entry = entries.find((e) => e.id === id && e.deletedAt);29032995 if (!entry) throw new Error("deleted entry not found");29042996 const previousDeletedAt = entry.deletedAt;@@ -2922,7 +3014,7 @@29223014 }29233015 29243016 export async function purgeEntry(id: string): Promise<void> {2925- if (!derivedKey) throw new Error("vault_locked");3017+ if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");29263018 const idx = entries.findIndex((e) => e.id === id && e.deletedAt);29273019 if (idx === -1) throw new Error("deleted entry not found");29283020 const entry = entries[idx]!;@@ -2933,7 +3025,7 @@29333025 29343026 /** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */29353027 export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2936- if (!derivedKey || retentionMs === 0) return 0;3028+ if (!derivedKey || vaultCreatesInFlight || retentionMs === 0) return 0;29373029 const cutoff = Date.now() - retentionMs;29383030 const before = entries.length;29393031 for (const entry of entries) {@@ -3056,6 +3148,9 @@30563148 async function persistEntries(30573149 reason: VaultSnapshot["reason"] = "local_save",30583150 ): Promise<void> {3151+ if (vaultCreatesInFlight) throw new Error("vault_changed");3152+ vaultWritesInFlight++;3153+ try {30593154 if (!derivedKey) throw new Error("vault_locked");30603155 30613156 // Reconcile direct soft-delete callers while restoring the previous map if@@ -3075,6 +3170,7 @@30753170 }30763171 buildDomainIndexSync(entries);30773172 await refreshLockedSyncState();3173+ } finally { vaultWritesInFlight--; }30783174 }30793175 30803176 // PB-26-011: drop URLs whose parsed scheme is not http(s) at the storage@@ -3382,7 +3478,7 @@33823478 * each group. Returns the number of entries moved to trash.33833479 */33843480 export async function deduplicateEntries(): Promise<number> {3385- if (!derivedKey) throw new Error("vault_locked");3481+ if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");33863482 // Dedup reshapes slot B permanently under the decoy key, which is33873483 // forensically distinguishable from a freshly-seeded decoy vault. Refuse.33883484 if (vaultMode === "decoy") {@@ -3453,11 +3549,12 @@34533549 export async function takeVaultSnapshot(34543550 reason: VaultSnapshot["reason"],34553551 ): Promise<void> {3456- if (recoveryInFlight) return;3552+ if (recoveryInFlight || vaultCreatesInFlight) return;34573553 // The history store is real-mode state by construction, so it must not be34583554 // written from a decoy session either. The guard lives here rather than only34593555 // at the call sites so the invariant survives a new caller (PB-26-915).34603556 if (vaultMode === "decoy") return;3557+ vaultWritesInFlight++;34613558 try {34623559 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);34633560 const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];@@ -3509,7 +3606,7 @@35093606 };35103607 35113608 history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);3512- if (recoveryInFlight) return;3609+ if (recoveryInFlight || vaultCreatesInFlight) return;35133610 await chrome.storage.local.set({ [HISTORY_KEY]: history });35143611 } catch (err) {35153612 // Non-fatal — history must never block a save. A failed snapshot just@@ -3524,17 +3621,18 @@35243621 // popup may be closed; surfaced via console.warn above35253622 }35263623 }3527- }3624+ } finally { vaultWritesInFlight--; }35283625 }35293626 35303627 /** Wipe all vault history. Called by Panic / DESTROY_VAULT. */35313628 export async function clearVaultHistory(): Promise<void> {3532- if (recoveryInFlight) throw new Error("recovery_in_progress");3629+ if (recoveryInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");3630+ vaultWritesInFlight++;35333631 try {35343632 await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });35353633 } catch {35363634 // Non-fatal — DESTROY_VAULT also runs storage.local.clear().3537- }3635+ } finally { vaultWritesInFlight--; }35383636 }35393637 35403638 /** Read all snapshots, newest first, for the Settings vault history view. */@@ -3552,7 +3650,7 @@35523650 export async function restoreVaultSnapshot(35533651 snapshotId: string,35543652 ): Promise<{ ok: true } | { ok: false; error: string }> {3555- if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight) return { ok: false, error: "vault_changed" };3653+ if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "vault_changed" };35563654 vaultReplacementInFlight = true;35573655 try {35583656 if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };@@ -3569,7 +3667,7 @@35693667 const previousA = (current as Record<string, unknown>)[SLOT_A];35703668 const previousB = (current as Record<string, unknown>)[SLOT_B];35713669 try {3572- if (recoveryInFlight || vaultRemovalsInFlight) return { ok: false, error: "recovery_in_progress" };3670+ if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };35733671 await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });35743672 await stampLocalVaultMutation();35753673 } catch {@@ -3602,6 +3700,9 @@36023700 * confirmation, same as the initial recovery-word confirmation path.36033701 */36043702 export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {3703+ if (vaultCreatesInFlight) throw new Error("vault_changed");3704+ vaultWritesInFlight++;3705+ try {36053706 if (!derivedKey || vaultMode !== "real") {36063707 return { ok: false, error: "vault_locked" };36073708 }@@ -3652,6 +3753,7 @@36523753 36533754 await stampLocalVaultMutation();36543755 return { ok: true };3756+ } finally { vaultWritesInFlight--; }36553757 }36563758 36573759 /**@@ -3664,6 +3766,10 @@36643766 currentPassword: string,36653767 newPassword: string36663768 ): Promise<boolean> {3769+ if (vaultCreatesInFlight) throw new Error("vault_changed");3770+ vaultWritesInFlight++;3771+ try {3772+36673773 const epoch = vaultEpoch;36683774 const stale = () => epoch !== vaultEpoch;36693775 if (!derivedKey || vaultMode !== "real") return false;@@ -3752,4 +3858,5 @@37523858 await stampLocalVaultMutation();37533859 37543860 return true;3861+ } finally { vaultWritesInFlight--; }37553862 }src/popup/App.boot.test.tsx+95 −0
@@ -0,0 +1,95 @@1+// @vitest-environment jsdom2+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";3+import type { Message } from "../shared/types";4+import App from "./App";5+import { flushView, renderView } from "./views/view-test-utils";6+7+const { send } = vi.hoisted(() => ({ send: vi.fn() }));8+vi.mock("../shared/bridge", () => ({ sendMessage: send }));9+vi.mock("./views/Lock", () => ({10+ RESTORE_SOURCE_STORAGE_KEY: "restore-source",11+ LockView: (props: { hasVault: boolean }) => <div>{props.hasVault ? "locked-vault" : "create-vault"}</div>,12+}));13+vi.mock("./views/Onboarding", () => ({14+ ONBOARDING_CARD_STORAGE_KEY: "onboarding-card", ONBOARDING_LAST_CARD: 3,15+ Onboarding: () => <div>new-user-onboarding</div>,16+}));17+18+let dispose: (() => void) | undefined;19+beforeEach(() => {20+ const event = { addListener: vi.fn(), removeListener: vi.fn() };21+ vi.stubGlobal("chrome", {22+ permissions: { contains: vi.fn(async () => true) },23+ runtime: { getURL: (path: string) => path, onMessage: event, connect: () => ({ disconnect: vi.fn() }) },24+ tabs: { query: vi.fn(async () => []), onActivated: event, onUpdated: event },25+ storage: { local: { get: vi.fn(async () => ({})), set: vi.fn(async () => undefined), remove: vi.fn(async () => undefined) }, onChanged: event },26+ });27+ send.mockReset();28+ send.mockImplementation(async (message: Message) => {29+ if (message.type === "IS_UNLOCKED") return { ok: true, data: false };30+ if (message.type === "HAS_VAULT") return { ok: false, error: "storage unavailable" };31+ return { ok: true, data: null };32+ });33+});34+afterEach(() => { dispose?.(); vi.restoreAllMocks(); });35+36+describe("popup boot vault status", () => {37+ it.each([{ ok: false }, { ok: true }, { ok: true, data: "false" }, undefined])("offers retry for invalid vault status %j", async (response) => {38+ send.mockImplementation(async (message: Message) => message.type === "HAS_VAULT" ? response : { ok: true, data: false });39+ const view = renderView(() => <App />);40+ dispose = view.dispose;41+ await flushView();42+ expect(view.container.textContent).toContain("Retry");43+ expect(view.container.textContent).not.toContain("new-user-onboarding");44+ expect(view.container.textContent).not.toContain("create-vault");45+ });46+47+ it.each(["IS_UNLOCKED", "HAS_VAULT"])("offers retry when %s rejects", async (type) => {48+ send.mockImplementation(async (message: Message) => {49+ if (message.type === type) throw new Error("worker unavailable");50+ return { ok: true, data: false };51+ });52+ const view = renderView(() => <App />);53+ dispose = view.dispose;54+ await flushView();55+ expect(view.container.textContent).toContain("Retry");56+ expect(view.container.textContent).not.toContain("create-vault");57+ });58+59+ it("refuses a malformed unlocked response even with valid vault status", async () => {60+ send.mockImplementation(async (message: Message) => ({ ok: true, data: message.type === "IS_UNLOCKED" ? "true" : true }));61+ const view = renderView(() => <App />);62+ dispose = view.dispose;63+ await flushView();64+ expect(view.container.textContent).toContain("Retry");65+ });66+67+ it("retries into an unlocked existing vault", async () => {68+ const view = renderView(() => <App />);69+ dispose = view.dispose;70+ await flushView();71+ send.mockImplementation(async (message: Message) => {72+ if (message.type === "IS_UNLOCKED" || message.type === "HAS_VAULT") return { ok: true, data: true };73+ if (message.type === "GET_ENTRIES") return { ok: true, data: [] };74+ return { ok: true, data: null };75+ });76+ view.container.querySelector<HTMLButtonElement>("button")!.click();77+ await flushView();78+ await flushView();79+ expect(send).toHaveBeenCalledWith({ type: "GET_ENTRIES" });80+ expect(view.container.textContent).not.toContain("create-vault");81+ expect(view.container.textContent).not.toContain("locked-vault");82+ expect(view.container.textContent).not.toContain("Retry");83+ });84+85+ it.each([true, false])("retries into the correct state when vault existence is %s", async (exists) => {86+ const view = renderView(() => <App />);87+ dispose = view.dispose;88+ await flushView();89+ send.mockImplementation(async (message: Message) => ({ ok: true, data: message.type === "HAS_VAULT" ? exists : false }));90+ view.container.querySelector<HTMLButtonElement>("button")!.click();91+ await flushView();92+ await flushView();93+ expect(view.container.textContent).toContain(exists ? "locked-vault" : "new-user-onboarding");94+ });95+});src/popup/App.tsx+25 −10
@@ -80,7 +80,7 @@8080 | "initial-sync"8181 | "codex-generate"8282 | "codex-restore";83-type BootState = "loading" | "ready";83+type BootState = "loading" | "ready" | "error";8484 8585 const INITIAL_SYNC_POLL_MS = 500;8686 const INITIAL_SYNC_SLOW_MS = 15_000;@@ -540,7 +540,9 @@540540 void chrome.permissions.contains(ALL_SITES).then((granted) => setSiteAccessMissing(!granted));541541 });542542 543- onMount(async () => {543+ async function boot() {544+ setBootState("loading");545+ try {544546 // Resolve the active tab in parallel with the unlock/has-vault queries —545547 // openVault()'s smart selection picks the entry matching currentTabDomain,546548 // so it must be populated before openVault runs. Previously refreshCurrentTab@@ -552,14 +554,15 @@552554 refreshCurrentTab(),553555 sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),554556 ]);555- const unlocked = Boolean(556- (unlockResponse as { ok: boolean; data?: boolean }).data557- );558- const vaultExists = Boolean(559- (vaultResponse as { ok: boolean; data?: boolean }).data560- );557+ if (!unlockResponse || unlockResponse.ok !== true || typeof unlockResponse.data !== "boolean" ||558+ !vaultResponse || vaultResponse.ok !== true || typeof vaultResponse.data !== "boolean") {559+ setBootState("error");560+ return;561+ }562+ const unlocked = unlockResponse.data;563+ const vaultExists = vaultResponse.data;561564 const shouldCelebrate = Boolean(562- (celebrationResponse as { ok: boolean; data?: boolean }).data565+ celebrationResponse?.ok === true && celebrationResponse.data === true563566 );564567 setHasVault(vaultExists);565568 // Onboarding gate — show once on first install, never again. Existing@@ -962,8 +965,14 @@962965 };963966 chrome.storage.onChanged.addListener(handleStorageChanged);964967 onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));965- });968+ } catch (error) {969+ if (bootState() === "ready") console.warn("[Peach] popup setup failed:", error);970+ else setBootState("error");971+ }972+ }966973 974+ onMount(() => { void boot(); });975+967976 async function refreshCurrentTab() {968977 try {969978 const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });@@ -1380,6 +1389,12 @@13801389 >13811390 Allow13821391 </button>1392+ </div>1393+ </Show>1394+ <Show when={bootState() === "error"}>1395+ <div class="peach-loading peach-boot-error" role="alert">1396+ <p>Peach couldn’t check your vault. Try again.</p>1397+ <button class="peach-btn peach-btn--accent peach-btn--md" onClick={() => void boot()}>Retry</button>13831398 </div>13841399 </Show>13851400 <Show when={bootState() === "ready"}>src/popup/styles/popup.css+8 −0
@@ -3614,6 +3614,14 @@36143614 animation: peach-loading-pulse 1.2s ease-in-out infinite;36153615 }36163616 3617+.peach-loading.peach-boot-error {3618+ flex-direction: column;3619+ gap: 16px;3620+ padding: 24px;3621+ text-align: center;3622+ animation: none;3623+}3624+36173625 @keyframes peach-loading-pulse {36183626 0%, 100% { opacity: 0.6; }36193627 50% { opacity: 1; }src/popup/views/Import.tsx+6 −2
@@ -264,9 +264,10 @@264264 }265265 const createRes = await sendMessage({266266 type: "CREATE_VAULT",267- payload: { password: masterPassword() },267+ payload: { password: masterPassword(), ...(isOnboarding && props.replacesExistingVault === true ? { replacement: "warned-import" } : {}) },268268 });269269 if (!(createRes as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");270+ if ((createRes.data as { unlocked?: boolean } | undefined)?.unlocked === false) throw new Error("VAULT_CREATED_LOCKED");270271 }271272 272273 const restoreRes = await sendMessage({@@ -546,11 +547,12 @@546547 if (needsMasterPassword()) {547548 const createResponse = await sendMessage({548549 type: "CREATE_VAULT",549- payload: { password: masterPassword() },550+ payload: { password: masterPassword(), ...(isOnboarding && props.replacesExistingVault === true ? { replacement: "warned-import" } : {}) },550551 });551552 if (!(createResponse as { ok: boolean }).ok) {552553 throw new Error("CREATE_VAULT_FAILED");553554 }555+ if ((createResponse.data as { unlocked?: boolean } | undefined)?.unlocked === false) throw new Error("VAULT_CREATED_LOCKED");554556 }555557 556558 if (!isOnboarding && mergeMode() === "replace") {@@ -844,6 +846,8 @@844846 return "This PeachScript was created by a different version of Peach.";845847 case "CHECKSUM_FAILED":846848 return "PeachScript appears corrupted. Re-copy from the source device.";849+ case "VAULT_CREATED_LOCKED":850+ return "Your new vault and password were saved. Unlock Peach, then import your backup.";847851 case "CREATE_VAULT_FAILED":848852 return "Peach couldn't create a new local vault before importing.";849853 case "CLEAR_VAULT_FAILED":src/popup/views/Lock.tsx+12 −1
@@ -231,7 +231,12 @@231231 type: "CREATE_VAULT",232232 payload: { password: password() },233233 });234- const result = response as { ok: boolean; error?: string };234+ const result = response as { ok: boolean; error?: string; data?: { unlocked?: boolean } };235+ if (result.ok && result.data?.unlocked === false) {236+ setError(getDisplayError("vault_created_locked", ""));237+ setLoading(false);238+ return;239+ }235240 if (result.ok) {236241 // Don't unlock yet — show the recovery words screen first. The237242 // background owns this session-scoped exemption so content scripts@@ -955,6 +960,7 @@955960 if (!props.hasVault) {956961 const cr = await sendMessage({ type: "CREATE_VAULT", payload: { password: backupPass() } });957962 if (!(cr as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");963+ if ((cr.data as { unlocked?: boolean } | undefined)?.unlocked === false) throw new Error("vault_created_locked");958964 }959965 960966 const rr = await sendMessage({@@ -987,6 +993,8 @@987993 setError(988994 code === "INVALID_PASSPHRASE"989995 ? "That passphrase didn't work."996+ : code === "vault_created_locked"997+ ? getDisplayError(code, "")990998 : code === "CREATE_VAULT_FAILED"991999 ? "Couldn't create a new local vault."9921000 : "Could not read this backup.",@@ -1155,6 +1163,7 @@11551163 // empty one (an empty key derives a publicly-known vault key).11561164 const cr = await sendMessage({ type: "CREATE_VAULT", payload: { password: newPass() } });11571165 if (!(cr as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");1166+ if ((cr.data as { unlocked?: boolean } | undefined)?.unlocked === false) throw new Error("vault_created_locked");11581167 }11591168 11601169 const res = await sendMessage({ type: "BATCH_ADD_ENTRIES", payload: { entries: parsed.entries } });@@ -1164,6 +1173,7 @@11641173 const code = err instanceof Error ? err.message : String(err);11651174 setError(11661175 code === "NO_ENTRIES" ? "No entries found in this file." :1176+ code === "vault_created_locked" ? getDisplayError(code, "") :11671177 code === "CREATE_VAULT_FAILED" ? "Couldn't create a new local vault." :11681178 "Import failed. Check the file format and try again."11691179 );@@ -1299,6 +1309,7 @@12991309 13001310 function getDisplayError(error: string | undefined, fallback: string): string {13011311 if (!error) return fallback;1312+ if (error === "vault_created_locked") return "Your new vault and password were saved. Reopen Peach and unlock it with your new password.";13021313 if (13031314 error === "SERVICE_WORKER_UNAVAILABLE" ||13041315 error.includes("Receiving end does not exist") ||src/popup/views/contracts.test.tsx+51 −4
@@ -56,6 +56,8 @@5656 GeneratorDrawer: () => null,5757 }));5858 59+vi.mock("../components/RuneCanvas", () => ({ RuneCanvas: () => null }));60+5961 vi.mock("../components/RuneBackground", () => ({6062 RuneBackground: () => null,6163 }));@@ -445,6 +447,51 @@445447 expect(onUnlock).not.toHaveBeenCalled();446448 });447449 450+ it("Lock reports saved-but-locked creation before requesting recovery words", async () => {451+ sendMessageMock.mockResolvedValue({ ok: true, data: { committed: true, unlocked: false } });452+ zxcvbnMock.mockImplementation(() => ({ score: 3 }));453+ const container = mount(<LockView hasVault={false} ready={true} onUnlock={vi.fn()} />);454+ inputText(container.querySelector<HTMLInputElement>("#master-password")!, "correct horse battery staple");455+ inputText(container.querySelector<HTMLInputElement>("#confirm-password")!, "correct horse battery staple");456+ await flushView();457+ pressEnter(container.querySelector<HTMLInputElement>("#confirm-password")!);458+ await flushView();459+ expect(container.textContent).toContain("Your new vault and password were saved");460+ expect(sendMessageMock).not.toHaveBeenCalledWith({ type: "SET_RECOVERY_CONFIRM_PENDING" });461+ });462+463+ it("Lock CSV restore stops when creation saved a locked vault", async () => {464+ parseImportSourceMock.mockResolvedValue(sampleImportResult());465+ sendMessageMock.mockResolvedValue({ ok: true, data: { committed: true, unlocked: false } });466+ const container = mount(<LockView hasVault={false} ready={true} initialRestore={true} initialRestoreSource="csv" onUnlock={vi.fn()} />);467+ await flushView();468+ inputText(container.querySelector<HTMLInputElement>("#restore-csv-pass")!, "new-master-password");469+ inputText(container.querySelector<HTMLInputElement>("#restore-csv-confirm")!, "new-master-password");470+ const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;471+ Object.defineProperty(input, "files", { configurable: true, value: [new File(["csv"], "backup.csv")] });472+ input.dispatchEvent(new Event("change", { bubbles: true }));473+ await flushView();474+ expect(container.textContent).toContain("Your new vault and password were saved");475+ expect(sendMessageMock.mock.calls.some(([msg]) => (msg as { type: string }).type === "BATCH_ADD_ENTRIES")).toBe(false);476+ });477+478+ it("Lock PeachScript restore stops when creation saved a locked vault", async () => {479+ const script = await import("../../crypto/peachScript");480+ const payload = await import("../../crypto/peachPayload");481+ vi.spyOn(script, "isPeachScript").mockImplementation((value) => value === "backup");482+ vi.spyOn(script, "decodePeachScript").mockReturnValue(new Uint8Array());483+ vi.spyOn(payload, "parsePayload").mockResolvedValue({ entries: [sampleEntry()], settings: {} });484+ sendMessageMock.mockResolvedValue({ ok: true, data: { committed: true, unlocked: false } });485+ const container = mount(<LockView hasVault={false} ready={true} initialRestore={true} initialRestoreSource="symbols" onUnlock={vi.fn()} />);486+ await flushView();487+ inputText(container.querySelector<HTMLTextAreaElement>(".peach-restore-script")!, "backup");488+ inputText(container.querySelector<HTMLInputElement>("#restore-backup-pass")!, "new-master-password");489+ container.querySelector<HTMLButtonElement>(".peach-restore-submit")!.click();490+ await flushView();491+ expect(container.textContent).toContain("Your new vault and password were saved");492+ expect(sendMessageMock.mock.calls.some(([msg]) => (msg as { type: string }).type === "RESTORE_ENTRIES")).toBe(false);493+ });494+448495 it("recovery display asks for three distinct randomized word positions and confirms", async () => {449496 const words12 = [450497 "abandon", "ability", "able", "about", "above", "absent",@@ -1731,7 +1778,7 @@17311778 expect(onImport).toHaveBeenCalled();17321779 });17331780 1734- it("Import onboarding mode waits for a matching master password before creating a vault", async () => {1781+ it.each([true, false])("Import onboarding mode creates only after matching passwords (replacement %s)", async (replacesExistingVault) => {17351782 parseImportSourceMock.mockResolvedValue(sampleImportResult());17361783 sendMessageMock.mockImplementation(async (msg: unknown) => {17371784 const type = (msg as { type?: string }).type;@@ -1745,7 +1792,7 @@17451792 const container = mount(17461793 <ImportView17471794 mode="onboarding"1748- replacesExistingVault={true}1795+ replacesExistingVault={replacesExistingVault}17491796 onBack={vi.fn()}17501797 onImport={onImport}17511798 />@@ -1755,7 +1802,7 @@17551802 17561803 const createButton = findButton(container, "Create vault + import 1");17571804 expect(createButton.disabled).toBe(true);1758- expect(container.textContent).toContain("Restoring now replaces the locked local vault");1805+ expect(container.textContent?.includes("Restoring now replaces the locked local vault")).toBe(replacesExistingVault);17591806 expect(container.textContent).toContain("Use at least 8 characters");17601807 17611808 const masterInput = container.querySelector(@@ -1783,7 +1830,7 @@17831830 17841831 expect(sendMessageMock).toHaveBeenCalledWith({17851832 type: "CREATE_VAULT",1786- payload: { password: "fresh-master-password" },1833+ payload: { password: "fresh-master-password", ...(replacesExistingVault ? { replacement: "warned-import" } : {}) },17871834 });17881835 expect(sendMessageMock).toHaveBeenCalledWith({17891836 type: "BATCH_ADD_ENTRIES",