712a87ff1772

preserve existing vault data during word recovery (v5.3.13)

time
2026-11-10 21:41 UTC · 2 weeks ago
machine
Junes-MacBook-Pro.local
agent
gpt-6
session
remediate interim audit findings
parent
370ea40f4e4e
10 files manifest.firefox.json+1 −1manifest.json+1 −1package.json+1 −1src/background/messages.ts+34 −43src/background/recovery-words.test.ts+389 −0src/background/vault.session-escrow.test.ts+8 −9src/background/vault.ts+345 −255src/popup/views/RecoveryWordEntry.tsx+31 −5src/popup/views/contracts.test.tsx+13 −4src/shared/types.ts+4 −0
manifest.firefox.json+1 −1
@@ -1,7 +1,7 @@11 {22   "manifest_version": 3,33   "name": "Peach Password Manager",4-  "version": "5.3.12",4+  "version": "5.3.13",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.12",5+  "version": "5.3.13",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.12",3+  "version": "5.3.13",44   "description": "Zero-knowledge password manager",55   "license": "GPL-3.0-only",66   "type": "module",

view file

src/background/messages.ts+34 −43
@@ -555,38 +555,28 @@555555       case "RECOVER_WITH_WORDS": {556556         // User has lost their password but has their 12 recovery words.557557         // We: (1) validate the words, (2) re-encrypt vault with new password.558+        if (!msg.payload || typeof msg.payload !== "object" || Array.isArray(msg.payload)) {559+          return { ok: false, error: "invalid_recovery_payload" };560+        }558561         const { words, newPassword } = msg.payload as {559562           words: string[];560563           newPassword: string;561564         };562-        const stored = await vault.loadSlotA();563-        if (!stored) return { ok: false, error: "no_vault" };564-        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {565-          return { ok: false, error: "recovery_not_setup" };565+        if (!Array.isArray(words) || words.some((word) => typeof word !== "string") || typeof newPassword !== "string") {566+          return { ok: false, error: "invalid_recovery_payload" };566567         }567-        // Unwrap the root key from the recovery escrow.568-        try {569-          await vault.unwrapRootKeyForRecovery(570-            stored.recovery_wrapped_root_key,571-            stored.recovery_nonce ?? "",572-            stored.recovery_tag ?? "",573-            stored.recovery_salt,574-            words575-          );576-        } catch {577-          return { ok: false, error: "invalid_recovery_words" };568+        const recovered = await vault.recoverWithWords(words, newPassword);569+        if (recovered.unlocked) {570+          try { await setupAutoLock(); }571+          catch (error) {572+            console.warn("[Peach] recovery password saved; auto-lock setup failed:", error);573+            try { await vault.lock(); }574+            catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }575+          }578576         }579-        // Re-key: derive fresh salt + key from new password.580-        const newSalt = vault.generateSalt();581-        const newKey = await vault.deriveKey(newPassword, newSalt);582-        // Re-wrap root key under the new password's derived key so the same583-        // recovery words continue to work after the password change.584-        await vault.rewrapRootKeyForPassword(newKey);585-        // Re-encrypt vault entries with the new key.586-        await vault.changePasswordWithNewKey(newSalt, newKey);587-        await setupAutoLock();588-        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });589-        return { ok: true };577+        const unlocked = recovered.unlocked && vault.isUnlocked();578+        if (unlocked) broadcastToContentScripts({ type: "VAULT_UNLOCKED" });579+        return { ok: true, data: { ...recovered, unlocked } };590580       }591581       case "LOCK":592582         await vault.lock();@@ -1580,23 +1570,24 @@15801570         // it, and destroying a vault (panic wipe, fresh start) is not a refund.15811571         // Capture it before the clear and restore it after. peach_pro_celebrated15821572         // rides along so the Pro celebration doesn't replay on the next unlock.1583-        const preserved = await chrome.storage.local.get([1584-          "peach_license",1585-          "peach_pro_celebrated",1586-        ]);1587-        await vault.lock();1588-        await storageClear();1589-        await vault.clearVaultHistory();1590-        const toRestore: Record<string, unknown> = {};1591-        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1592-        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1593-        if (Object.keys(toRestore).length > 0) {1594-          await chrome.storage.local.set(toRestore);1595-        }1596-        if (chrome.storage.session) {1597-          await chrome.storage.session.clear();1598-        }1599-        await clearRecoveryConfirmPending();1573+        await vault.withVaultRemoval(async () => {1574+          const preserved = await chrome.storage.local.get([1575+            "peach_license",1576+            "peach_pro_celebrated",1577+          ]);1578+          await storageClear();1579+          await vault.clearVaultHistory();1580+          const toRestore: Record<string, unknown> = {};1581+          if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1582+          if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1583+          if (Object.keys(toRestore).length > 0) {1584+            await chrome.storage.local.set(toRestore);1585+          }1586+          if (chrome.storage.session) {1587+            await chrome.storage.session.clear();1588+          }1589+          await clearRecoveryConfirmPending();1590+        });16001591         return { ok: true };16011592       }16021593 

view file

src/background/recovery-words.test.ts+389 −0
@@ -54,6 +54,7 @@5454             return key.reduce<Record<string, unknown>>((acc, k) => { acc[k] = storage[k]; return acc; }, {});5555           }),5656           set: vi.fn(async (next: Record<string, unknown>) => { Object.assign(storage, next); }),57+          clear: vi.fn(async () => { for (const key of Object.keys(storage)) delete storage[key]; }),5758           remove: vi.fn(async (keys: string | string[]) => {5859             const list = Array.isArray(keys) ? keys : [keys];5960             for (const key of list) delete storage[key];@@ -193,6 +194,394 @@193194   });194195 195196   describe('RECOVER_WITH_WORDS handler', () => {197+    it('reports a committed password change when identity maintenance fails', async () => {198+      const vault = await import('./vault');199+      await setupUnlockedVault();200+      await vault.addEntry({ type: 'note', title: 'Retained after hook failure', notes: 'saved' });201+      const words = await vault.getRecoveryWords();202+      vault.setIdentityHooks({ onSessionEnded: async () => {}, onVaultCreated: async () => {},203+        onKeysRotated: async () => { throw new Error('identity storage unavailable'); } });204+      await vault.lock();205+      const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });206+      const oldPasswordWorks = await vault.verifyMainPassword('test-pass-12345');207+      const newPasswordWorks = await vault.verifyMainPassword('recovered-password');208+      expect(oldPasswordWorks).toBe(false);209+      expect(newPasswordWorks).toBe(true);210+      expect(result).toMatchObject({ ok: true, data: { committed: true, unlocked: false } });211+      expect(vault.isUnlocked()).toBe(false);212+      expect(vi.mocked(chrome.tabs.sendMessage)).not.toHaveBeenCalledWith(expect.anything(), { type: 'VAULT_UNLOCKED' });213+      expect(await vault.unlock('recovered-password')).toBe(true);214+      expect(vault.getEntries()[0]?.notes).toBe('saved');215+    });216+217+    it.each(['session', 'pair-secrets', 'PIN', 'auto-lock'] as const)('reports saved password and requires unlock after %s maintenance fails', async (maintenance) => {218+      const vault = await import('./vault');219+      await setupUnlockedVault();220+      const words = await vault.getRecoveryWords();221+      await vault.lock();222+      if (maintenance === 'session') vi.mocked(chrome.storage.session.set).mockRejectedValueOnce(new Error('session unavailable'));223+      if (maintenance === 'pair-secrets') {224+        storage.peach_paired_devices_v3 = [{ deviceId: 'phone', pairedAt: Date.now(), rendezvousSecretHex: 'ab'.repeat(32) }];225+        const set = vi.mocked(chrome.storage.local.set);226+        const original = set.getMockImplementation()!;227+        let failed = false;228+        set.mockImplementation(async (...args) => {229+          if (!failed && 'peach_pair_secrets_v1' in args[0]) { failed = true; throw new Error('pair store unavailable'); }230+          return original(...args);231+        });232+      }233+      if (maintenance === 'PIN') {234+        const remove = vi.mocked(chrome.storage.session.remove);235+        const original = remove.getMockImplementation()!;236+        remove.mockImplementation(async (...args) => {237+          if (Array.isArray(args[0])) throw new Error('PIN store unavailable');238+          return original(...args);239+        });240+      }241+      if (maintenance === 'auto-lock') vi.mocked(chrome.idle.setDetectionInterval).mockImplementationOnce(() => { throw new Error('idle API unavailable'); });242+      const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });243+      expect(result).toMatchObject({ ok: true, data: { committed: true, unlocked: false } });244+      expect(vault.isUnlocked()).toBe(false);245+      expect(vault.getRootKeyHex()).toBeNull();246+      expect(sessionStorage.peach_session_dk).toBeUndefined();247+      expect(await vault.verifyMainPassword('test-pass-12345')).toBe(false);248+      expect(await vault.unlock('recovered-password')).toBe(true);249+    });250+    it('preserves existing entries and the decoy slot during locked recovery', async () => {251+      const vault = await import('./vault');252+      await setupUnlockedVault();253+      await vault.addEntry({ type: 'login', title: 'Existing account', password: 'keep-me' });254+      const removed = await vault.addEntry({ type: 'note', title: 'Purged note', notes: 'deleted' });255+      await vault.deleteEntry(removed.id);256+      await vault.purgeEntry(removed.id);257+      await vault.setupDuress('decoy-password');258+      const before = vault.getEntries();259+      const tombstones = vault.getTombstoneManifest();260+      const root = vault.getRootKeyHex();261+      const words = await vault.getRecoveryWords();262+      const slotA = JSON.stringify(storage.peach_vault_a);263+      const slotB = JSON.stringify(storage.peach_vault_b);264+      await vault.lock();265+      const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });266+      expect(result.ok).toBe(true);267+      expect(vault.getEntries()).toEqual(before);268+      expect(vault.getTombstoneManifest()).toEqual(tombstones);269+      expect(vault.getRootKeyHex()).toBe(root);270+      expect(JSON.stringify(storage.peach_vault_b)).toBe(slotB);271+      const history = storage.peach_vault_history as { snapshots: Array<{ vault_a: string; vault_b: string }> };272+      expect(history.snapshots[0]).toMatchObject({ vault_a: slotA, vault_b: slotB });273+      await vault.lock();274+      expect(await vault.unlock('recovered-password')).toBe(true);275+      expect(vault.getEntries()).toEqual(before);276+      expect(vault.getTombstoneManifest()).toEqual(tombstones);277+      await vault.lock();278+      expect(await vault.unlock('decoy-password')).toBe(true);279+      expect(vault.isDecoyMode()).toBe(true);280+    });281+282+    it.each(['created', 'adopted', 'password-changed', 'root-rotated'] as const)('recovers a %s vault after a cold worker restart', async (kind) => {283+      let vault = await import('./vault');284+      if (kind === 'adopted') await vault.createVaultFromRootKey('test-pass-12345', '42'.repeat(32));285+      else await setupUnlockedVault();286+      await vault.addEntry({ type: 'note', title: 'Before restart', notes: 'retained' });287+      if (kind === 'password-changed') expect(await vault.changePassword('test-pass-12345', 'changed-password')).toBe(true);288+      if (kind === 'root-rotated') expect((await vault.rotateSyncIdentity()).ok).toBe(true);289+      const words = await vault.getRecoveryWords();290+      const root = vault.getRootKeyHex();291+      await vault.lock();292+      vi.resetModules();293+      vault = await import('./vault');294+      await vault.recoverWithWords(words, 'cold-recovery-password');295+      expect(vault.getEntries()[0]?.notes).toBe('retained');296+      expect(vault.getRootKeyHex()).toBe(root);297+      await vault.lock();298+      expect(await vault.unlock('cold-recovery-password')).toBe(true);299+      expect(vault.getEntries()[0]?.notes).toBe('retained');300+    });301+302+    it.each(['aad', 'payload'] as const)('refuses mismatched %s authentication without writes', async (kind) => {303+      const vault = await import('./vault');304+      await setupUnlockedVault();305+      const words = await vault.getRecoveryWords();306+      const slot = rawSlotA();307+      if (kind === 'aad') {308+        const { encrypt } = await import('./aes');309+        const root = Uint8Array.from(vault.getRootKeyHex()!.match(/../g)!, (byte) => Number.parseInt(byte, 16));310+        slot.recovery_vault_key = await encrypt(root, vault.getDerivedKeyHex(), 'pw_root_v1');311+      } else slot.tag = '00'.repeat(16);312+      await vault.lock();313+      const before = JSON.stringify(storage);314+      expect((await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } })).ok).toBe(false);315+      expect(JSON.stringify(storage)).toBe(before);316+      expect(vault.getRootKeyHex()).toBeNull();317+    });318+319+    it.each(['missing', 'corrupt', 'stale'] as const)('refuses %s escrow unchanged and repairs it through real password unlock', async (kind) => {320+      const vault = await import('./vault');321+      await setupUnlockedVault();322+      await vault.addEntry({ type: 'note', title: 'Keep this note', notes: 'original' });323+      const words = await vault.getRecoveryWords();324+      const slot = rawSlotA();325+      if (kind === 'missing') delete slot.recovery_vault_key;326+      if (kind === 'corrupt') slot.recovery_vault_key = { nonce: '00', ciphertext: '00', tag: '00' };327+      if (kind === 'stale') {328+        const { encrypt } = await import('./aes');329+        const root = Uint8Array.from(vault.getRootKeyHex()!.match(/../g)!, (byte) => Number.parseInt(byte, 16));330+        slot.recovery_vault_key = await encrypt(root, '00'.repeat(32), 'recovery_vault_key_v1');331+      }332+      await vault.lock();333+      const before = JSON.stringify(storage);334+      const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });335+      expect(result.ok).toBe(false);336+      expect(JSON.stringify(storage)).toBe(before);337+      expect(vault.getRootKeyHex()).toBeNull();338+      expect(vault.isUnlocked()).toBe(false);339+      expect(await vault.unlock('test-pass-12345')).toBe(true);340+      await vault.lock();341+      expect((await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } })).ok).toBe(true);342+      expect(vault.getEntries()[0]?.notes).toBe('original');343+    });344+345+    it('refuses unlocked real and decoy recovery without changing storage', async () => {346+      const vault = await import('./vault');347+      await setupUnlockedVault();348+      const words = await vault.getRecoveryWords();349+      await vault.setupDuress('decoy-password');350+      for (const decoy of [false, true]) {351+        if (decoy) { await vault.lock(); await vault.unlock('decoy-password'); }352+        const before = JSON.stringify(storage);353+        const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });354+        expect(result.ok).toBe(false);355+        expect(JSON.stringify(storage)).toBe(before);356+        expect(vault.isDecoyMode()).toBe(decoy);357+      }358+    });359+360+    it('keeps original slots and stays locked when the recovery transaction fails', async () => {361+      const vault = await import('./vault');362+      await setupUnlockedVault();363+      const words = await vault.getRecoveryWords();364+      await vault.lock();365+      const before = JSON.stringify(storage);366+      vi.mocked(chrome.storage.local.set).mockRejectedValueOnce(new Error('storage unavailable'));367+      expect((await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } })).ok).toBe(false);368+      expect(JSON.stringify(storage)).toBe(before);369+      expect(vault.isUnlocked()).toBe(false);370+      expect(vault.getRootKeyHex()).toBeNull();371+      expect(await vault.unlock('test-pass-12345')).toBe(true);372+    });373+374+    it('cancels recovery on manual lock and refuses concurrent unlock', async () => {375+      const vault = await import('./vault');376+      await setupUnlockedVault();377+      const words = await vault.getRecoveryWords();378+      await vault.lock();379+      const before = JSON.stringify(storage);380+      const get = vi.mocked(chrome.storage.local.get);381+      const original = get.getMockImplementation()!;382+      let release!: () => void;383+      let started!: () => void;384+      const paused = new Promise<void>((resolve) => { release = resolve; });385+      const ready = new Promise<void>((resolve) => { started = resolve; });386+      get.mockImplementationOnce(async (...args) => { started(); await paused; return original(...args); });387+      const recovering = dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });388+      await ready;389+      expect(await vault.unlock('test-pass-12345')).toBe(false);390+      await vault.lock();391+      release();392+      expect((await recovering).ok).toBe(false);393+      expect(JSON.stringify(storage)).toBe(before);394+      expect(vault.getRootKeyHex()).toBeNull();395+      expect(vault.isUnlocked()).toBe(false);396+    });397+398+    it('keeps a cancelled in-flight commit consistent and does not unlock', async () => {399+      const vault = await import('./vault');400+      await setupUnlockedVault();401+      await vault.addEntry({ type: 'note', title: 'Retain on cancellation', notes: 'saved' });402+      const words = await vault.getRecoveryWords();403+      await vault.lock();404+      const before = JSON.stringify(storage.peach_vault_a);405+      let release!: () => void;406+      let started!: () => void;407+      const paused = new Promise<void>((resolve) => { release = resolve; });408+      const ready = new Promise<void>((resolve) => { started = resolve; });409+      const set = vi.mocked(chrome.storage.local.set);410+      const original = set.getMockImplementation()!;411+      set.mockImplementationOnce(async (...args) => {412+        expect(Object.keys(args[0]).sort()).toEqual(['peach_last_modified_at', 'peach_vault_a', 'peach_vault_history']);413+        started(); await paused; return original(...args);414+      });415+      const recovering = dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });416+      await ready;417+      await vault.lock();418+      release();419+      expect(await recovering).toMatchObject({ ok: true, data: { committed: true, unlocked: false } });420+      expect(vault.isUnlocked()).toBe(false);421+      expect(vault.getRootKeyHex()).toBeNull();422+      const history = storage.peach_vault_history as { snapshots: Array<{ vault_a: string }> };423+      expect(history.snapshots[0]?.vault_a).toBe(before);424+      expect(await vault.unlock('recovered-password')).toBe(true);425+      expect(vault.getEntries()[0]?.notes).toBe('saved');426+    });427+428+    it('does not enroll legacy escrow through a pre-derived key, session restore, or decoy unlock', async () => {429+      let vault = await import('./vault');430+      await setupUnlockedVault();431+      await vault.setupDuress('decoy-password');432+      const key = vault.getDerivedKeyHex();433+      delete rawSlotA().recovery_vault_key;434+      await vault.lock();435+      expect((await vault.unlockWithKey(key)).ok).toBe(true);436+      expect(rawSlotA().recovery_vault_key).toBeUndefined();437+      vi.resetModules();438+      vault = await import('./vault');439+      expect(await vault.restoreFromSession()).toBe(true);440+      expect(rawSlotA().recovery_vault_key).toBeUndefined();441+      await vault.lock();442+      expect(await vault.unlock('decoy-password')).toBe(true);443+      expect(rawSlotA().recovery_vault_key).toBeUndefined();444+      await vault.lock();445+      expect(await vault.unlock('test-pass-12345')).toBe(true);446+      expect(rawSlotA().recovery_vault_key).toBeDefined();447+    });448+449+    it('preserves the local identity and paired reconnect secret', async () => {450+      const vault = await import('./vault');451+      const pairs = await import('./pair-secrets');452+      const devices = await import('./paired-devices');453+      await setupUnlockedVault();454+      const rootHex = vault.getRootKeyHex()!;455+      const root = Uint8Array.from(rootHex.match(/../g)!, (byte) => Number.parseInt(byte, 16));456+      await devices.upsertPairedDevice({ deviceId: 'paired-phone', deviceName: 'Phone', deviceType: 'android', longTermPublicKeyHex: '43'.repeat(32), pairedAt: Date.now() });457+      await pairs.setPairSecret('paired-phone', 'ab'.repeat(32), root);458+      const identityKey = new Uint8Array(32).fill(7);459+      let identity = await vault.sealIdentityKeyUnderVault(identityKey);460+      vault.setIdentityHooks({461+        onSessionEnded: async () => {},462+        onVaultCreated: async () => {},463+        onKeysRotated: async () => {464+          const opened = await vault.openIdentityKey(identity);465+          expect(opened).toEqual(identityKey);466+          identity = await vault.sealIdentityKeyUnderVault(opened!);467+        },468+      });469+      const words = await vault.getRecoveryWords();470+      await vault.lock();471+      await vault.recoverWithWords(words, 'recovered-password');472+      expect(await vault.openIdentityKey(identity)).toEqual(identityKey);473+      expect(await pairs.getPairSecret('paired-phone', vault.getRootKeyHex())).toBe('ab'.repeat(32));474+      await vault.lock();475+      expect(await vault.unlock('recovered-password')).toBe(true);476+      expect(await vault.openIdentityKey(identity)).toEqual(identityKey);477+      expect(await pairs.getPairSecret('paired-phone', vault.getRootKeyHex())).toBe('ab'.repeat(32));478+    });479+480+    it('refuses recovery while a Codex replacement is staged', async () => {481+      const vault = await import('./vault');482+      await setupUnlockedVault();483+      const words = await vault.getRecoveryWords();484+      const slotA = JSON.stringify(storage.peach_vault_a);485+      const slotB = JSON.stringify(storage.peach_vault_b);486+      await vault.lock();487+      const importing = vault.unlockFromCodex({ slotA, slotB, timestamp: Date.now(), masterPassphrase: 'test-pass-12345' });488+      await expect(vault.recoverWithWords(words, 'recovered-password')).rejects.toThrow('vault_changed');489+      expect((await importing).ok).toBe(true);490+      expect(await vault.verifyMainPassword('test-pass-12345')).toBe(true);491+    });492+493+    it('refuses recovery while an earlier creation derives its password', async () => {494+      const vault = await import('./vault');495+      const argon = await import('../crypto/argon2');496+      await setupUnlockedVault();497+      await vault.addEntry({ type: 'note', title: 'Keep recovered data', notes: 'original' });498+      const words = await vault.getRecoveryWords();499+      await vault.lock();500+      let release!: () => void;501+      const paused = new Promise<void>((resolve) => { release = resolve; });502+      const derive = argon.deriveKey;503+      const spy = vi.spyOn(argon, 'deriveKey').mockImplementationOnce(async (...args) => {504+        const key = await derive(...args); await paused; return key;505+      });506+      const creating = vault.createVault('concurrent-creation-password').then(() => 'created', (error: Error) => error.message);507+      const recovering = await vault.recoverWithWords(words, 'recovered-password').then(() => 'recovered', (error: Error) => error.message);508+      const before = JSON.stringify(storage);509+      await vault.lock();510+      release();511+      expect(await creating).toBe('vault_changed');512+      spy.mockRestore();513+      expect(recovering).toBe('vault_changed');514+      expect(JSON.stringify(storage)).toBe(before);515+      expect(vault.getRootKeyHex()).toBeNull();516+    });517+518+    it('refuses recovery while creation is paused after its password derivation', async () => {519+      const vault = await import('./vault');520+      await setupUnlockedVault();521+      const words = await vault.getRecoveryWords();522+      await vault.lock();523+      const before = JSON.stringify(storage);524+      const encrypt = crypto.subtle.encrypt.bind(crypto.subtle);525+      let release!: () => void;526+      let started!: () => void;527+      const paused = new Promise<void>((resolve) => { release = resolve; });528+      const ready = new Promise<void>((resolve) => { started = resolve; });529+      const spy = vi.spyOn(crypto.subtle, 'encrypt').mockImplementationOnce(async (...args) => {530+        const value = await encrypt(...args); started(); await paused; return value;531+      });532+      const creating = vault.createVault('concurrent-creation-password').then(() => 'created', (error: Error) => error.message);533+      await ready;534+      await vault.lock();535+      const recovering = await vault.recoverWithWords(words, 'recovered-password').then(() => 'recovered', (error: Error) => error.message);536+      release();537+      const created = await creating;538+      spy.mockRestore();539+      expect(recovering).toBe('vault_changed');540+      expect(created).toBe('vault_changed');541+      expect(JSON.stringify(storage)).toBe(before);542+      expect(vault.getRootKeyHex()).toBeNull();543+    });544+545+    it.each([null, undefined, 42, 'words'])('rejects malformed recovery payload %s explicitly', async (payload) => {546+      const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload } as unknown as Message);547+      expect(result).toMatchObject({ ok: false, error: 'invalid_recovery_payload' });548+    });549+550+    it.each(['panic', 'adoption-rollback'] as const)('orders %s after a previously issued recovery write', async (kind) => {551+      const vault = await import('./vault');552+      await setupUnlockedVault();553+      const words = await vault.getRecoveryWords();554+      await vault.lock();555+      const set = vi.mocked(chrome.storage.local.set);556+      const original = set.getMockImplementation()!;557+      let release!: () => void;558+      let started!: () => void;559+      const paused = new Promise<void>((resolve) => { release = resolve; });560+      const ready = new Promise<void>((resolve) => { started = resolve; });561+      set.mockImplementationOnce(async (...args) => { started(); await paused; return original(...args); });562+      const recovering = dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });563+      await ready;564+      let removed = false;565+      const removing = (kind === 'panic'566+        ? dispatch({ type: 'DESTROY_VAULT' })567+        : vault.rollbackAdoptedVault().then(() => ({ ok: true }), () => ({ ok: false }))).then((result) => { removed = true; return result; });568+      await new Promise((resolve) => setTimeout(resolve, 0));569+      const removedBeforeRecoverySettled = removed;570+      release();571+      const recoveryResult = await recovering;572+      const removalResult = await removing;573+      expect(storage.peach_vault_a).toBeUndefined();574+      expect(storage.peach_vault_b).toBeUndefined();575+      expect(removedBeforeRecoverySettled).toBe(false);576+      expect(recoveryResult).toMatchObject({ ok: true, data: { committed: true, unlocked: false } });577+      expect(removalResult.ok).toBe(true);578+      expect(vault.isUnlocked()).toBe(false);579+      if (kind === 'panic') {580+        const history = storage.peach_vault_history as { snapshots: unknown[] };581+        expect(history.snapshots).toEqual([]);582+      }583+    });584+196585     it('recovery succeeds with correct words and new passphrase', async () => {197586       await setupUnlockedVault();198587       const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });

view file

src/background/vault.session-escrow.test.ts+8 −9
@@ -1,5 +1,4 @@11 import { beforeEach, describe, expect, it, vi } from "vitest";2-import { deriveKey } from "../crypto/argon2";32 43 // PCH-01-008: a password change must refresh the MV3 session-key escrow so the54 // next service-worker restore decrypts the new-key Slot A. The backing stores@@ -75,14 +74,14 @@7574     expect(v2.getEntries().some((e) => e.title === "Acct")).toBe(true);7675   });7776 78-  it("change_password_with_new_key_updates_session_escrow", async () => {77+  it("recovery_updates_session_escrow", async () => {7978     const v1 = await import("./vault");8079     await v1.createVault("orig-pass-abc123");8180     await v1.addEntry({ type: "login", title: "Recovered", password: "pw" });8281 83-    const newSalt = crypto.getRandomValues(new Uint8Array(16));84-    const newKey = await deriveKey("reset-pass-xyz789", newSalt);85-    await v1.changePasswordWithNewKey(newSalt, newKey);82+    const words = await v1.getRecoveryWords();83+    await v1.lock();84+    await v1.recoverWithWords(words, "reset-pass-xyz789");8685 8786     vi.resetModules();8887     const v2 = await import("./vault");@@ -247,11 +246,11 @@247246   it("a lock clears a recovery re-key paused while writing session escrow", async () => {248247     const vault = await import("./vault");249248     await vault.createVault("old-pass-abc123");250-    const newSalt = crypto.getRandomValues(new Uint8Array(16));251-    const newKey = await deriveKey("new-pass-xyz789", newSalt);249+    const words = await vault.getRecoveryWords();250+    await vault.lock();252251 253252     const write = pauseSessionKeyWrite(session);254-    const changing = vault.changePasswordWithNewKey(newSalt, newKey);253+    const changing = vault.recoverWithWords(words, "new-pass-xyz789");255254     await write.started;256255 257256     let lockSettled = false;@@ -263,7 +262,7 @@263262     write.release();264263 265264     expect(lockSettledBeforeWrite).toBe(false);266-    await expect(changing).rejects.toThrow("vault_locked");265+    await expect(changing).resolves.toEqual({ committed: true, unlocked: false });267266     await locking;268267     expect(vault.isUnlocked()).toBe(false);269268     expect(session.peach_session_dk).toBeUndefined();

view file

src/background/vault.ts+345 −255
@@ -27,6 +27,7 @@2727   Canary,2828   ManualSummonRecord,2929   PasskeyData,30+  RecoveryResult,3031   SavedIdentity,3132   StoredVault,3233   VaultEntry,@@ -81,6 +82,12 @@8182 // 12-word phrase. When the user changes their password, only the wrapping changes;8283 // the root key and recovery words remain stable.8384 let rootKey: Uint8Array | null = null;85+let recoveryInFlight = false;86+let recoverySettled: Promise<void> = Promise.resolve();87+let vaultRemovalsInFlight = 0;88+let vaultWritesInFlight = 0;89+let vaultCreatesInFlight = 0;90+let vaultReplacementInFlight = false;8491 let entries: VaultEntry[] = [];8592 // Tombstones outlive their full entry records so a peer that was offline8693 // during a purge cannot reintroduce an old ciphertext envelope. This map is@@ -253,6 +260,7 @@253260 254261 /** Unlock the real vault from its locally stored PIN-wrapped derived key. */255262 export async function unlockWithPin(pin: string): Promise<boolean> {263+  if (recoveryInFlight || vaultRemovalsInFlight) return false;256264   if (!isValidPin(pin)) return false;257265   await loadSettings();258266   if (!settings.pinEnabled) return false;@@ -668,20 +676,19 @@668676 /**669677  * Unwrap the root key using recovery words. Called during recovery flow when670678  * the user provides their 12-word phrase and a new password.671- * Exported for use by the RECOVER_WITH_WORDS message handler.672679  */673-export async function unwrapRootKeyForRecovery(680+async function unwrapRootKeyForRecovery(674681   wrappedRootKey: string,675682   wrappedNonce: string,676683   wrappedTag: string,677684   recoverySaltHex: string,678685   words: string[]679-): Promise<void> {686+): Promise<Uint8Array> {680687   const wordMaterial = await wordsToRootKeyMaterial(words);681688   const recoverySalt = unhex(recoverySaltHex);682689   const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);683690 684-  // Decrypt and cache the root key. The root key bytes were hex-encoded before691+  // The root key bytes were hex-encoded before685692   // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt686693   // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.687694   // Each component is stored separately in the vault slot; decode them individually@@ -701,113 +708,126 @@701708     combined702709   );703710   const decryptedHex = new TextDecoder().decode(raw);704-  rootKey = unhex(decryptedHex);711+  const recovered = unhex(decryptedHex);712+  if (recovered.length !== 32) { zeroKey(recovered); throw new Error("invalid_recovery_words"); }713+  return recovered;705714 }706715 707-/**708- * Re-wrap the cached root key under a new derived key (from the user's new709- * password). Called after password change and after recovery re-key so the710- * same recovery words continue to work with the updated password — and so711- * subsequent unlocks can rehydrate rootKey via deriveRootKeyFromDerivedKey.712- *713- * recovery_* fields are intentionally not touched: those wrap rootKey under714- * the recovery words, which do not change when the password changes.715- */716-export async function rewrapRootKeyForPassword(717-  newDerivedKey: Uint8Array,718-): Promise<void> {719-  if (!rootKey) throw new Error("root key not set");720-  const slotA = await loadSlot(SLOT_A);721-  if (!slotA) throw new Error("missing slot A");722-  const pwRoot = await wrapRootKeyForDerivedKey(newDerivedKey, rootKey);723-  await writeSlot(SLOT_A, { ...slotA, ...pwRoot });724-}725-726-/**727- * Change the vault encryption to a new derived key (already derived from728- * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.729- * Caller is responsible for key swap and snapshot.730- */731-async function reencryptVaultForNewKey(732-  newKey: Uint8Array,733-  slotA: StoredVault734-): Promise<void> {735-  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);736-  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");737-  await writeSlot(SLOT_A, {738-    ...slotA,739-    nonce,740-    ciphertext,741-    tag,742-  });743-}744-745-/**746- * Full password change with an already-derived key (used after recovery).747- * Unlike changePassword(), this skips re-verification of current password748- * since recovery flow has already validated the user's identity via words.749- */750-export async function changePasswordWithNewKey(751-  newSalt: Uint8Array,752-  newKey: Uint8Array753-): Promise<void> {754-  const epoch = vaultEpoch;755-  const throwIfStale = () => {756-    if (epoch === vaultEpoch) return;757-    zeroKey(newKey);758-    throw new Error("vault_locked");716+/// Recover a locked real vault without publishing keys before its stored payload authenticates.717+export async function recoverWithWords(words: string[], newPassword: string): Promise<RecoveryResult> {718+  if (recoveryInFlight || derivedKey) throw new Error("recovery_requires_lock");719+  if (vaultWritesInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");720+  recoveryInFlight = true;721+  let settle!: () => void;722+  recoverySettled = new Promise<void>((resolve) => { settle = resolve; });723+  const epoch = ++vaultEpoch;724+  const check = () => {725+    if (epoch !== vaultEpoch || derivedKey) throw new Error("vault_locked");759726   };760-  const slotA = await loadSlot(SLOT_A);761-  throwIfStale();762-  if (!slotA) throw new Error("missing slot A");763-  // reencryptVaultForNewKey must receive the updated salt so that subsequent764-  // UNLOCK calls with the new password can re-derive the correct key.765-  await reencryptVaultForNewKey(newKey, { ...slotA, salt: hex(newSalt) });766-  throwIfStale();767-  if (derivedKey) zeroKey(derivedKey);768-  derivedKey = newKey;769-  // PCH-01-008: re-escrow the new key (see changePassword). The recovery flow770-  // reaches this path, so a post-recovery SW restart would otherwise lock out771-  // a user who just reset their password.772-  await saveSessionKey(newKey, "real", epoch);773-  throwIfStale();774-  // Same reason as changePassword: the unlock key just changed, so the775-  // identity's local wrap has to be re-encrypted under it.776-  await notifyIdentityKeysRotated();777-  throwIfStale();778-  // Refresh pw_root_* under the new key so deriveRootKeyFromDerivedKey works779-  // on the next unlock (H2/COR-006). If rootKey is missing — recovery flow780-  // should have populated it — fall back silently rather than blowing up the781-  // recovery path; the escrow is already present on every supported vault.782-  if (rootKey) {783-    const slotAfter = await loadSlot(SLOT_A);784-    throwIfStale();785-    if (slotAfter) {786-      const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);787-      throwIfStale();788-      await writeSlot(SLOT_A, { ...slotAfter, ...pwRoot });789-      throwIfStale();727+  let recoveredRoot: Uint8Array | null = null;728+  let oldKey: Uint8Array | null = null;729+  let newKey: Uint8Array | null = null;730+  let committed = false;731+  try {732+    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);733+    check();734+    const slot = raw[SLOT_A] as StoredVault | undefined;735+    if (!slot) throw new Error("no_vault");736+    if (!slot.recovery_salt || !slot.recovery_wrapped_root_key) throw new Error("recovery_not_setup");737+    try {738+      recoveredRoot = await unwrapRootKeyForRecovery(slot.recovery_wrapped_root_key,739+        slot.recovery_nonce ?? "", slot.recovery_tag ?? "", slot.recovery_salt, words);740+    } catch {741+      throw new Error("invalid_recovery_words");790742     }743+    check();744+    if (!slot.recovery_vault_key) throw new Error("recovery_requires_password_unlock");745+    oldKey = await openSealedKey(recoveredRoot, slot.recovery_vault_key, "recovery_vault_key_v1");746+    check();747+    if (!oldKey) throw new Error("recovery_data_unavailable");748+    const result = await tryDecryptSlotResult(slot, oldKey, "slot_a_v1");749+    check();750+    if (result.status !== "ok") throw new Error("recovery_data_unavailable");751+    const payload = result.payload;752+    await loadSettings();753+    check();754+    const salt = generateSalt();755+    newKey = await deriveKey(newPassword, salt);756+    check();757+    // Preserve the authenticated plaintext, including fields unknown to this build.758+    const plaintext = await decrypt(oldKey, slot.nonce, slot.ciphertext, slot.tag, "slot_a_v1");759+    const encrypted = await encrypt(newKey, plaintext, "slot_a_v1");760+    const pwRoot = await wrapRootKeyForDerivedKey(newKey, recoveredRoot);761+    const recoveryVaultKey = await encrypt(recoveredRoot, hex(newKey), "recovery_vault_key_v1");762+    check();763+    const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);764+    check();765+    if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");766+    const history = raw[HISTORY_KEY] as VaultHistory | undefined;767+    const snapshot: VaultSnapshot = {768+      id: crypto.randomUUID(), savedAt: Date.now(), reason: "local_save",769+      vault_a: JSON.stringify(slot), vault_b: JSON.stringify(raw[SLOT_B] ?? slot), entryCount: null,770+    };771+    const previousStamp = Number(raw.peach_last_modified_at);772+    const nextSlot: StoredVault = { ...slot, ...encrypted, ...pwRoot,773+      salt: hex(salt), recovery_vault_key: recoveryVaultKey };774+    // One storage transaction keeps the rollback snapshot and all new-key fields together.775+    await chrome.storage.local.set({776+      [SLOT_A]: nextSlot,777+      [HISTORY_KEY]: { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) },778+      peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previousStamp) ? previousStamp + 1 : 0)),779+    });780+    committed = true;781+    check();782+    derivedKey = newKey;783+    rootKey = recoveredRoot;784+    newKey = null;785+    recoveredRoot = null;786+    entries = payload.entries;787+    tombstones = payload.tombstones;788+    duressConfigured = payload.duressConfigured;789+    vaultMode = "real";790+    buildDomainIndexSync(entries);791+    await saveSessionKey(derivedKey, "real", epoch);792+    if (epoch !== vaultEpoch) throw new Error("vault_locked");793+    await identityHooks?.onKeysRotated();794+    if (epoch !== vaultEpoch) throw new Error("vault_locked");795+    await reconcilePairSecrets(rootKey);796+    if (epoch !== vaultEpoch) throw new Error("vault_locked");797+    await clearPinUnlockStorage();798+    if (epoch !== vaultEpoch) throw new Error("vault_locked");799+    touchAutoLock();800+    return { committed: true, unlocked: true };801+  } catch (error) {802+    if (committed) {803+      console.warn("[Peach] recovery password saved; unlock required:", error);804+      if (derivedKey && epoch === vaultEpoch) {805+        try { await lock(); }806+        catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }807+      }808+      return { committed: true, unlocked: false };809+    }810+    if (derivedKey && epoch === vaultEpoch) await lock();811+    throw error;812+  } finally {813+    if (oldKey) zeroKey(oldKey);814+    if (newKey) zeroKey(newKey);815+    if (recoveredRoot) zeroKey(recoveredRoot);816+    recoveryInFlight = false;817+    settle();791818   }792-  if (!duressConfigured) {793-    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));794-    throwIfStale();795-  }796-  await clearPinUnlockStorage();797-  throwIfStale();798-  await stampLocalVaultMutation();799-  throwIfStale();800819 }801820 802-// ---------------------------------------------------------------------------803-// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive804-// a new key after password reset without re-importing the crypto module.805-// ---------------------------------------------------------------------------806-807-export { deriveKey, generateSalt };808-809-export async function loadSlotA(): Promise<StoredVault | null> {810-  return loadSlot(SLOT_A);821+/// Cancel recovery and finish its issued storage write before removing vault data.822+export async function withVaultRemoval<T>(remove: () => Promise<T>): Promise<T> {823+  vaultRemovalsInFlight++;824+  try {825+    await lock();826+    await recoverySettled;827+    return await remove();828+  } finally {829+    vaultRemovalsInFlight--;830+  }811831 }812832 813833 /**@@ -945,10 +965,14 @@945965 }946966 947967 async function writeSlot(key: string, vault: StoredVault): Promise<void> {968+  if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");969+  vaultWritesInFlight++;948970   try {949971     await chrome.storage.local.set({ [key]: vault });950972   } catch (err) {951973     throw mapStorageError(err);974+  } finally {975+    vaultWritesInFlight--;952976   }953977 }954978 @@ -962,35 +986,43 @@962986  * The call is idempotent: removing keys that aren't there is a no-op.963987  */964988 export async function rollbackAdoptedVault(): Promise<void> {965-  await lock();966-  try {967-    await chrome.storage.local.remove([968-      SLOT_A,969-      SLOT_B,970-      "peach_last_modified_at",971-    ]);972-  } catch (err) {973-    throw mapStorageError(err);974-  }989+  await withVaultRemoval(async () => {990+    try {991+      await chrome.storage.local.remove([992+        SLOT_A,993+        SLOT_B,994+        "peach_last_modified_at",995+      ]);996+    } catch (err) {997+      throw mapStorageError(err);998+    }999+  });9751000 }9761001 9771002 async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {978-  const raw = await chrome.storage.local.get("peach_last_modified_at");979-  const previous = Number(980-    (raw as Record<string, unknown>).peach_last_modified_at,981-  );982-  const next = Math.max(983-    Date.now(),984-    Number.isFinite(previous) ? previous + 1 : 0,985-  );1003+  if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1004+  vaultWritesInFlight++;9861005   try {987-    await chrome.storage.local.set({988-      [SLOT_A]: slotA,989-      [SLOT_B]: slotB,990-      peach_last_modified_at: String(next),991-    });992-  } catch (err) {993-    throw mapStorageError(err);1006+    const raw = await chrome.storage.local.get("peach_last_modified_at");1007+    const previous = Number(1008+      (raw as Record<string, unknown>).peach_last_modified_at,1009+    );1010+    const next = Math.max(1011+      Date.now(),1012+      Number.isFinite(previous) ? previous + 1 : 0,1013+    );1014+    try {1015+      if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1016+      await chrome.storage.local.set({1017+        [SLOT_A]: slotA,1018+        [SLOT_B]: slotB,1019+        peach_last_modified_at: String(next),1020+      });1021+    } catch (err) {1022+      throw mapStorageError(err);1023+    }1024+  } finally {1025+    vaultWritesInFlight--;9941026   }9951027 }9961028 @@ -1380,52 +1412,65 @@13801412 }13811413 13821414 export async function createVault(password: string): Promise<void> {1383-  const salt = generateSalt();1384-  derivedKey = await deriveKey(password, salt);1385-  entries = [];1386-  tombstones = new Map();1387-  vaultMode = "real";1388-  duressConfigured = false;1389-  buildDomainIndexSync(entries);1415+  if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1416+  vaultCreatesInFlight++;1417+  try {1418+    const epoch = vaultEpoch;1419+    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;1424+    entries = [];1425+    tombstones = new Map();1426+    vaultMode = "real";1427+    duressConfigured = false;1428+    buildDomainIndexSync(entries);13901429 1391-  // Generate and wrap the root key for recovery word escrow.1392-  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =1393-    await generateAndWrapRootKey();1394-  rootKey = unhex(rawRootKey);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);13951435 1396-  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);1397-  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");1436+    const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);1437+    const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");13981438 1399-  // Second wrapping of rootKey under derivedKey so future unlocks can rehydrate1400-  // it without recovery words (H2/COR-006).1401-  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);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);14021442 1403-  const slotA: StoredVault = {1404-    version: 1,1405-    salt: hex(salt),1406-    nonce,1407-    ciphertext,1408-    tag,1409-    recovery_salt: recoverySalt,1410-    recovery_wrapped_root_key: wrappedRootKey,1411-    recovery_nonce: wrappedNonce,1412-    recovery_tag: wrappedTag,1413-    ...pwRoot,1414-  };1415-  await writeSlot(SLOT_A, slotA);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);14161458 1417-  // Matching-size noise blob for slot B, so a fresh install shows two1418-  // similarly-shaped records regardless of whether duress is ever set up.1419-  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1420-  await stampLocalVaultMutation();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();14211463 1422-  // An identity created while this install had no vault was sealed under the1423-  // password alone; the vault keys exist now, so re-seal it under them.1424-  await identityHooks?.onVaultCreated(password).catch((error) => {1425-    console.warn("[Peach] local identity promotion failed:", error);1426-  });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.1466+    await identityHooks?.onVaultCreated(password).catch((error) => {1467+      console.warn("[Peach] local identity promotion failed:", error);1468+    });14271469 1428-  touchAutoLock();1470+    touchAutoLock();1471+  } finally {1472+    vaultCreatesInFlight--;1473+  }14291474 }14301475 14311476 /**@@ -1437,6 +1482,7 @@14371482   password: string,14381483   rootKeyHex: string,14391484 ): Promise<{ vaultId: string }> {1485+  if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");14401486   if (typeof password !== "string" || password.length === 0) {14411487     throw new Error("ADOPT_INVALID_PASSWORD");14421488   }@@ -1469,6 +1515,7 @@14691515     const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");14701516     const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);14711517     const slotA: StoredVault = {1518+      recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),14721519       version: 1,14731520       salt: hex(salt),14741521       nonce,@@ -1602,6 +1649,7 @@16021649   password: string,16031650   derive: typeof deriveKey,16041651 ): Promise<boolean> {1652+  if (recoveryInFlight || vaultRemovalsInFlight) return false;16051653   const epoch = vaultEpoch;16061654   const stale = () => epoch !== vaultEpoch;16071655   // Load both current-format slots in parallel. Both exist on a supported@@ -1669,6 +1717,26 @@16691717       return false;16701718     }16711719 1720+    // Repair missing or stale escrow only after a real password authenticates the slot.1721+    if (slotA) {1722+      const escrowed = slotA.recovery_vault_key1723+        ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;1724+      const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);1725+      if (escrowed) zeroKey(escrowed);1726+      if (stale()) { await lock(); return false; }1727+      if (!matches) {1728+        try {1729+          const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");1730+          if (stale()) { await lock(); return false; }1731+          await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });1732+          if (stale()) { await lock(); return false; }1733+        } catch (error) {1734+          await lock();1735+          throw error;1736+        }1737+      }1738+    }1739+16721740     // PB-26-213: adopt legacy plaintext pair secrets into the encrypted16731741     // record and refresh the trusted-session operational copy.16741742     await reconcilePairSecrets(rootKey);@@ -1818,6 +1886,7 @@18181886  * No-ops if the vault is already unlocked.18191887  */18201888 export async function restoreFromSession(): Promise<boolean> {1889+  if (recoveryInFlight || vaultRemovalsInFlight) return false;18211890   if (derivedKey !== null) return true;18221891   if (restoreInFlight) return restoreInFlight;18231892   const task = restoreFromSessionInner();@@ -1945,6 +2014,7 @@19452014 export async function unlockWithKey(19462015   masterKeyHex: string,19472016 ): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2017+  if (recoveryInFlight || vaultRemovalsInFlight) return { ok: false, error: "recovery_in_progress" };19482018   const epoch = vaultEpoch;19492019   const stale = () => epoch !== vaultEpoch;19502020   let masterKeyBytes: Uint8Array | null = null;@@ -2050,83 +2120,89 @@20502120   | { ok: true; entryCount: number }20512121   | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }20522122 > {2053-  let parsedSlotA: StoredVault;2054-  let parsedSlotB: StoredVault | null = null;2123+  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight) throw new Error("vault_changed");2124+  vaultReplacementInFlight = true;20552125   try {2056-    const rawA = JSON.parse(params.slotA) as unknown;2057-    if (!hasValidVaultSchema(rawA)) {2058-      return { ok: false, reason: "invalid_slot_format" };2059-    }2060-    parsedSlotA = rawA;2061-    if (params.slotB !== null) {2062-      const rawB = JSON.parse(params.slotB) as unknown;2063-      if (!hasValidVaultSchema(rawB)) {2126+    let parsedSlotA: StoredVault;2127+    let parsedSlotB: StoredVault | null = null;2128+    try {2129+      const rawA = JSON.parse(params.slotA) as unknown;2130+      if (!hasValidVaultSchema(rawA)) {20642131         return { ok: false, reason: "invalid_slot_format" };20652132       }2066-      parsedSlotB = rawB;2133+      parsedSlotA = rawA;2134+      if (params.slotB !== null) {2135+        const rawB = JSON.parse(params.slotB) as unknown;2136+        if (!hasValidVaultSchema(rawB)) {2137+          return { ok: false, reason: "invalid_slot_format" };2138+        }2139+        parsedSlotB = rawB;2140+      }2141+    } catch {2142+      return { ok: false, reason: "invalid_slot_format" };20672143     }2068-  } catch {2069-    return { ok: false, reason: "invalid_slot_format" };2070-  }20712144 2072-  // Verify the passphrase and the password-wrapped root escrow against the2073-  // staged Slot A WITHOUT writing anything. Payload decoding is part of the2074-  // trial decrypt, so unlock() cannot be the first place these checks run.2075-  const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2076-  const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2077-  if (!trialPayload) {2145+    // Verify the passphrase and the password-wrapped root escrow against the2146+    // staged Slot A WITHOUT writing anything. Payload decoding is part of the2147+    // trial decrypt, so unlock() cannot be the first place these checks run.2148+    const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2149+    const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2150+    if (!trialPayload) {2151+      zeroKey(trialKey);2152+      return { ok: false, reason: "wrong_passphrase" };2153+    }2154+    const hasEscrow =2155+      !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2156+    if (!hasEscrow) {2157+      zeroKey(trialKey);2158+      return { ok: false, reason: "missing_root_escrow" };2159+    }2160+    const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2161+    if (!stagedRootKey) {2162+      zeroKey(trialKey);2163+      return { ok: false, reason: "wrong_passphrase" };2164+    }2165+    zeroKey(stagedRootKey);20782166     zeroKey(trialKey);2079-    return { ok: false, reason: "wrong_passphrase" };2080-  }2081-  const hasEscrow =2082-    !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2083-  if (!hasEscrow) {2084-    zeroKey(trialKey);2085-    return { ok: false, reason: "missing_root_escrow" };2086-  }2087-  const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2088-  if (!stagedRootKey) {2089-    zeroKey(trialKey);2090-    return { ok: false, reason: "wrong_passphrase" };2091-  }2092-  zeroKey(stagedRootKey);2093-  zeroKey(trialKey);20942167 2095-  // Stage the complete candidate pair in memory before touching storage.2096-  const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);2168+    // Stage the complete candidate pair in memory before touching storage.2169+    const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);20972170 2098-  // Drop the trial key; `unlock()` below derives its own copy. Holding two2099-  // copies of the master key in memory at once would be a needless surface.2171+    // Drop the trial key; `unlock()` below derives its own copy. Holding two2172+    // copies of the master key in memory at once would be a needless surface.21002173 2101-  // Snapshot the about-to-be-overwritten on-disk state so the user can revert2102-  // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.2103-  await takeVaultSnapshot("restore");2104-  const previousSlotA = await loadSlot(SLOT_A);2105-  const previousSlotB = await loadSlot(SLOT_B);2106-  let slotACommitted = false;2107-  let slotBCommitted = false;2108-  try {2109-    await writeSlot(SLOT_A, parsedSlotA);2110-    slotACommitted = true;2111-    await writeSlot(SLOT_B, stagedSlotB);2112-    slotBCommitted = true;2113-    await chrome.storage.local.set({2114-      peach_last_modified_at: String(params.timestamp),2115-    });2116-  } catch (err) {2117-    if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2118-    if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2119-    throw err;2120-  }2174+    // Snapshot the about-to-be-overwritten on-disk state so the user can revert2175+    // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.2176+    await takeVaultSnapshot("restore");2177+    const previousSlotA = await loadSlot(SLOT_A);2178+    const previousSlotB = await loadSlot(SLOT_B);2179+    let slotACommitted = false;2180+    let slotBCommitted = false;2181+    try {2182+      await writeSlot(SLOT_A, parsedSlotA);2183+      slotACommitted = true;2184+      await writeSlot(SLOT_B, stagedSlotB);2185+      slotBCommitted = true;2186+      await chrome.storage.local.set({2187+        peach_last_modified_at: String(params.timestamp),2188+      });2189+    } catch (err) {2190+      if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2191+      if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2192+      throw err;2193+    }21212194 2122-  // Standard unlock path so domain index, settings, auto-lock, and2123-  // recovery-key state all populate exactly as a normal unlock would.2124-  const ok = await unlock(params.masterPassphrase);2125-  if (!ok) {2126-    // Should be unreachable — the staged candidate passed the same checks.2127-    return { ok: false, reason: "wrong_passphrase" };2195+    // Standard unlock path so domain index, settings, auto-lock, and2196+    // recovery-key state all populate exactly as a normal unlock would.2197+    const ok = await unlock(params.masterPassphrase);2198+    if (!ok) {2199+      // Should be unreachable — the staged candidate passed the same checks.2200+      return { ok: false, reason: "wrong_passphrase" };2201+    }2202+    return { ok: true, entryCount: getEntries().length };2203+  } finally {2204+    vaultReplacementInFlight = false;21282205   }2129-  return { ok: true, entryCount: getEntries().length };21302206 }21312207 21322208 // Returns the current in-memory derived key as a hex string. Only the PIN@@ -3377,6 +3453,7 @@33773453 export async function takeVaultSnapshot(33783454   reason: VaultSnapshot["reason"],33793455 ): Promise<void> {3456+  if (recoveryInFlight) return;33803457   // The history store is real-mode state by construction, so it must not be33813458   // written from a decoy session either. The guard lives here rather than only33823459   // at the call sites so the invariant survives a new caller (PB-26-915).@@ -3432,6 +3509,7 @@34323509     };34333510 34343511     history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);3512+    if (recoveryInFlight) return;34353513     await chrome.storage.local.set({ [HISTORY_KEY]: history });34363514   } catch (err) {34373515     // Non-fatal — history must never block a save. A failed snapshot just@@ -3451,6 +3529,7 @@34513529 34523530 /** Wipe all vault history. Called by Panic / DESTROY_VAULT. */34533531 export async function clearVaultHistory(): Promise<void> {3532+  if (recoveryInFlight) throw new Error("recovery_in_progress");34543533   try {34553534     await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });34563535   } catch {@@ -3473,33 +3552,40 @@34733552 export async function restoreVaultSnapshot(34743553   snapshotId: string,34753554 ): Promise<{ ok: true } | { ok: false; error: string }> {3476-  if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };3477-  const history = await getVaultHistory();3478-  const snapshot = history.find((s) => s.id === snapshotId);3479-  if (!snapshot) return { ok: false, error: "snapshot_not_found" };3555+  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight) return { ok: false, error: "vault_changed" };3556+  vaultReplacementInFlight = true;3557+  try {3558+    if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };3559+    const history = await getVaultHistory();3560+    const snapshot = history.find((s) => s.id === snapshotId);3561+    if (!snapshot) return { ok: false, error: "snapshot_not_found" };34803562 3481-  const restoredA = parseHistorySlot(snapshot.vault_a);3482-  const restoredB = parseHistorySlot(snapshot.vault_b);3483-  if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };3563+    const restoredA = parseHistorySlot(snapshot.vault_a);3564+    const restoredB = parseHistorySlot(snapshot.vault_b);3565+    if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };34843566 3485-  await takeVaultSnapshot("restore");3486-  const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);3487-  const previousA = (current as Record<string, unknown>)[SLOT_A];3488-  const previousB = (current as Record<string, unknown>)[SLOT_B];3489-  try {3490-    await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });3491-    await stampLocalVaultMutation();3492-  } catch {3567+    await takeVaultSnapshot("restore");3568+    const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);3569+    const previousA = (current as Record<string, unknown>)[SLOT_A];3570+    const previousB = (current as Record<string, unknown>)[SLOT_B];34933571     try {3494-      await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });3572+      if (recoveryInFlight || vaultRemovalsInFlight) return { ok: false, error: "recovery_in_progress" };3573+      await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });3574+      await stampLocalVaultMutation();34953575     } catch {3496-      // Preserve the restore failure if storage cannot complete the rollback.3576+      try {3577+        await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });3578+      } catch {3579+        // Preserve the restore failure if storage cannot complete the rollback.3580+      }3581+      return { ok: false, error: "snapshot_corrupt" };34973582     }3498-    return { ok: false, error: "snapshot_corrupt" };3499-  }35003583 3501-  await lock();3502-  return { ok: true };3584+    await lock();3585+    return { ok: true };3586+  } finally {3587+    vaultReplacementInFlight = false;3588+  }35033589 }35043590 35053591 /**@@ -3528,6 +3614,7 @@35283614 35293615   // 2. Re-wrap the new root key under the current password-derived key.35303616   const newRootKey = unhex(rawRootKey);3617+  const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");35313618   const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);35323619 35333620   // 3. Snapshot, then single atomic slot write — both escrow wrappings of@@ -3537,6 +3624,7 @@35373624   await takeVaultSnapshot("local_save");35383625   const nextSlotA: StoredVault = {35393626     ...slotA,3627+    recovery_vault_key: recoveryVaultKey,35403628     recovery_salt: recoverySalt,35413629     recovery_wrapped_root_key: wrappedRootKey,35423630     recovery_nonce: wrappedNonce,@@ -3605,8 +3693,10 @@36053693   // across password changes (H4/COR-002).36063694   const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);36073695 3696+  const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");36083697   const finalSlotA: StoredVault = {36093698     ...slotA,3699+    recovery_vault_key: recoveryVaultKey,36103700     salt: hex(newSalt),36113701     nonce,36123702     ciphertext,

view file

src/popup/views/RecoveryWordEntry.tsx+31 −5
@@ -6,6 +6,7 @@66 import { sendMessage } from "../App";77 import { RecoveryRuneBackground } from "../components/RecoveryRuneBackground";88 import { getWordSuggestions } from "../../shared/recovery-words";9+import type { RecoveryResult } from "../../shared/types";910 1011 const TOTAL_WORDS = 12;1112 @@ -23,8 +24,7 @@2324   );2425   const [error, setError] = createSignal("");2526   const [loading, setLoading] = createSignal(false);26-  // Step: "words" | "new-password"27-  const [step, setStep] = createSignal<"words" | "new-password">("words");27+  const [step, setStep] = createSignal<"words" | "new-password" | "complete-locked">("words");2828   // New password for step 22929   const [newPassword, setNewPassword] = createSignal("");3030   const [confirmPassword, setConfirmPassword] = createSignal("");@@ -184,16 +184,23 @@184184 185185     setNewPasswordLoading(true);186186     setNewPasswordError("");187+    let passwordCommitted = false;187188 188189     try {189190       const res = (await sendMessage({190191         type: "RECOVER_WITH_WORDS",191192         payload: { words: words().map((w) => w.toLowerCase().trim()), newPassword: newPassword() },192-      })) as { ok: boolean; error?: string };193+      })) as { ok: boolean; error?: string; data?: RecoveryResult };193194 194195       if (!res.ok) {195196         if (res.error === "recovery_not_setup") {196197           setNewPasswordError("this vault was created before recovery was available — restore from backup instead");198+        } else if (res.error === "recovery_requires_password_unlock") {199+          setNewPasswordError("unlock once with your current password to enable word recovery, or restore from a backup or paired device");200+        } else if (res.error === "recovery_data_unavailable") {201+          setNewPasswordError("the recovery data could not open this vault. restore from a backup or paired device");202+        } else if (res.error === "recovery_requires_lock") {203+          setNewPasswordError("lock the vault before recovering it");197204         } else if (res.error === "invalid_recovery_words") {198205           setNewPasswordError("invalid recovery words");199206         } else {@@ -202,9 +209,18 @@202209         return;203210       }204211 212+      passwordCommitted = true;213+      if (res.data?.unlocked === false) {214+        setStep("complete-locked");215+        return;216+      }205217       await Promise.resolve(props.onRecoveryComplete());206-    } catch {207-      setNewPasswordError("recovery failed");218+    } catch (error) {219+      if (passwordCommitted) {220+        console.warn("[Peach] recovery password saved; navigation failed:", error);221+        setStep("complete-locked");222+      }223+      else setNewPasswordError("recovery failed");208224     } finally {209225       setNewPasswordLoading(false);210226     }@@ -333,6 +349,16 @@333349           disabled={newPasswordLoading()}334350         >335351           {newPasswordLoading() ? "recovering..." : "recover vault"}352+        </button>353+      </Show>354+355+      <Show when={step() === "complete-locked"}>356+        <div class="peach-recovery-header">357+          <h1 class="peach-onboarding-headline">your new password is saved</h1>358+          <p class="peach-hint">use your new password to unlock your vault.</p>359+        </div>360+        <button class="peach-btn peach-btn--accent peach-btn--md" onClick={props.onCancel}>361+          back to unlock336362         </button>337363       </Show>338364     </section>

view file

src/popup/views/contracts.test.tsx+13 −4
@@ -497,13 +497,13 @@497497     }498498   });499499 500-  it("Recovery words flow submits the new master password and completes", async () => {500+  it.each([true, false])("Recovery words flow reports whether the saved password unlocked the vault (%s)", async (unlocked) => {501501     sendMessageMock.mockImplementation(async (msg: unknown) => {502502       const type = (msg as { type?: string }).type;503503       if (type === "VALIDATE_RECOVERY_WORDS") {504504         return { ok: true, data: { valid: true, invalid: [] } };505505       }506-      if (type === "RECOVER_WITH_WORDS") return { ok: true };506+      if (type === "RECOVER_WITH_WORDS") return { ok: true, data: { committed: true, unlocked } };507507       return { ok: true };508508     });509509     const canvasContext = {@@ -528,9 +528,10 @@528528     vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(() => canvasContext);529529 530530     const onRecoveryComplete = vi.fn(async () => undefined);531+    const onCancel = vi.fn();531532     const container = mount(532533       <RecoveryWordEntryView533-        onCancel={vi.fn()}534+        onCancel={onCancel}534535         onRecoveryComplete={onRecoveryComplete}535536       />536537     );@@ -563,7 +564,15 @@563564         newPassword: "fresh-recovery-password",564565       },565566     });566-    expect(onRecoveryComplete).toHaveBeenCalled();567+    if (unlocked) expect(onRecoveryComplete).toHaveBeenCalled();568+    else {569+      expect(onRecoveryComplete).not.toHaveBeenCalled();570+      expect(container.textContent).toContain("your new password is saved");571+      expect(container.textContent).toContain("use your new password to unlock your vault");572+      expect(container.textContent).not.toContain("recovery failed");573+      findButton(container, "back to unlock").click();574+      expect(onCancel).toHaveBeenCalledOnce();575+    }567576   });568577 569578   it("Export menu surfaces both backup formats", async () => {

view file

src/shared/types.ts+4 −0
@@ -170,6 +170,8 @@170170   conflict?: string;171171 }172172 173+export type RecoveryResult = { committed: true; unlocked: boolean };174+173175 export interface StoredVault {174176   // Not authenticated as AAD — the actual AES-GCM AAD is the slot's constant175177   // aadTag string (see background/aes.ts). The version field is unauthenticated@@ -191,6 +193,8 @@191193   pw_root_ciphertext?: string; // hex --- AES-256-GCM ciphertext of 32-byte root key (hex-encoded)192194   pw_root_nonce?: string; // hex --- 12-byte nonce193195   pw_root_tag?: string; // hex --- 16-byte GCM auth tag196+  /// Browser-local vault key escrow for recovery without the old password.197+  recovery_vault_key?: { nonce: string; ciphertext: string; tag: string };194198 }195199 196200 // Background-bound message types — sent from popup/content scripts,

view file