import { describe, it, expect, beforeEach } from 'vitest'; import { vi } from 'vitest'; import type { Message, MessageResponse, StoredVault } from '../shared/types'; import { WORD_LIST } from '../shared/recovery-word-list'; // Every unlock/GET_RECOVERY_WORDS here runs real Argon2id (m=64MiB, t=3, p=4). // The lock/unlock-cycle cases do seven derivations, which lands just past // vitest's 5s default once the full suite is competing for CPU — the failures // clustered at 5.0-5.1s, not at random points. Raised for the whole file // because every case in it is Argon2-bound, not just the ones that flaked. vi.setConfig({ testTimeout: 30_000 }); type StorageShape = Record; type MessageListener = ( msg: unknown, sender: chrome.runtime.MessageSender, sendResponse: (response: MessageResponse) => void ) => boolean; describe('recovery words handlers', () => { let storage: StorageShape; let sessionStorage: StorageShape; let listener: MessageListener; beforeEach(async () => { vi.resetModules(); vi.useRealTimers(); storage = { peach_settings: { breachMonitoring: false } }; sessionStorage = {}; vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, text: async () => '' }))); vi.stubGlobal('__PEACH_E2E_PASSKEYS__', false); const chromeMock = { runtime: { id: 'peach-extension', getURL: (path = '') => `chrome-extension://peach-extension/${path}`, onMessage: { addListener: vi.fn((fn: MessageListener) => { listener = fn; }) }, sendMessage: vi.fn(async () => ({ ok: true })), }, tabs: { query: vi.fn((_, cb?: (tabs: unknown[]) => void) => { if (typeof cb === 'function') { cb([{ id: 1 }]); return; } return Promise.resolve([{ id: 1 }]); }), sendMessage: vi.fn(async () => ({ ok: true })), }, storage: { local: { get: vi.fn(async (key?: string | string[]) => { if (!key) return storage; if (typeof key === 'string') return { [key]: storage[key] }; return key.reduce>((acc, k) => { acc[k] = storage[k]; return acc; }, {}); }), set: vi.fn(async (next: Record) => { Object.assign(storage, next); }), clear: vi.fn(async () => { for (const key of Object.keys(storage)) delete storage[key]; }), remove: vi.fn(async (keys: string | string[]) => { const list = Array.isArray(keys) ? keys : [keys]; for (const key of list) delete storage[key]; }), }, session: { get: vi.fn(async (key?: string | string[]) => { if (!key) return sessionStorage; if (typeof key === 'string') return { [key]: sessionStorage[key] }; return key.reduce>((acc, k) => { acc[k] = sessionStorage[k]; return acc; }, {}); }), set: vi.fn(async (next: Record) => { Object.assign(sessionStorage, next); }), remove: vi.fn(async (keys: string | string[]) => { const list = Array.isArray(keys) ? keys : [keys]; for (const key of list) delete sessionStorage[key]; }), clear: vi.fn(async () => { for (const k of Object.keys(sessionStorage)) delete sessionStorage[k]; }), }, }, alarms: { clear: vi.fn(), create: vi.fn(), onAlarm: { addListener: vi.fn() }, }, idle: { setDetectionInterval: vi.fn(), onStateChanged: { addListener: vi.fn() }, }, scripting: { executeScript: vi.fn(async () => []) }, } as unknown as typeof chrome; (globalThis as { chrome?: typeof chrome }).chrome = chromeMock; const messages = await import('./messages'); messages.setupMessageHandler(); const vault = await import('./vault'); await vault.ensureSettingsLoaded(); }); async function dispatch(message: Message): Promise { return new Promise((resolve) => { const keepOpen = listener(message, { id: 'peach-extension', url: 'chrome-extension://peach-extension/popup.html', }, resolve); expect(keepOpen).toBe(true); }); } async function setupUnlockedVault(): Promise { const vault = await import('./vault'); await vault.createVault('test-pass-12345'); } async function lockVault(): Promise { const vault = await import('./vault'); vault.lock(); } function rawSlotA(): StoredVault { const slot = storage.peach_vault_a as StoredVault | undefined; if (!slot) throw new Error('missing slot A'); return slot; } async function mockNoPro(): Promise { const license = await import('./license'); vi.spyOn(license, 'isProUser').mockResolvedValue(false); } describe('GET_RECOVERY_WORDS handler', () => { beforeEach(async () => { await setupUnlockedVault(); }); it('returns 12 words', async () => { const result = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); expect(result.ok).toBe(true); const words = (result as { data: string[] }).data; expect(words).toHaveLength(12); }); it('all words are from the BIP39 word list', async () => { const result = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const words = (result as { data: string[] }).data; for (const word of words) { expect(WORD_LIST).toContain(word); } }); it('returns same words on subsequent calls (deterministic)', async () => { const r1 = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const r2 = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); expect((r1 as { data: string[] }).data).toEqual((r2 as { data: string[] }).data); }); it('returns error when vault is locked', async () => { await lockVault(); const result = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); expect(result.ok).toBe(false); }); }); describe('VALIDATE_RECOVERY_WORDS handler', () => { beforeEach(async () => { await setupUnlockedVault(); }); it('returns no invalid words for correct list', async () => { const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const words = (r as { data: string[] }).data; const result = await dispatch({ type: 'VALIDATE_RECOVERY_WORDS', payload: { words }, }); const data = (result as { data: { invalid: Array<{ index: number; word: string }> } }).data; expect(data.invalid).toEqual([]); }); it('returns invalid words for unknown words', async () => { const result = await dispatch({ type: 'VALIDATE_RECOVERY_WORDS', payload: { words: ['notaword', 'alsonotaword'] }, }); const data = (result as { data: { invalid: Array<{ index: number; word: string }> } }).data; const invalidWords = data.invalid.map((x) => x.word); expect(invalidWords).toContain('notaword'); expect(invalidWords).toContain('alsonotaword'); }); it('is case-insensitive for validation', async () => { const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const words = (r as { data: string[] }).data; const uppercased = words.map((w: string) => w.toUpperCase()); const result = await dispatch({ type: 'VALIDATE_RECOVERY_WORDS', payload: { words: uppercased }, }); const data = (result as { data: { invalid: Array<{ index: number; word: string }> } }).data; expect(data.invalid).toEqual([]); }); }); describe('RECOVER_WITH_WORDS handler', () => { it('reports a committed password change when identity maintenance fails', async () => { const vault = await import('./vault'); await setupUnlockedVault(); await vault.addEntry({ type: 'note', title: 'Retained after hook failure', notes: 'saved' }); const words = await vault.getRecoveryWords(); vault.setIdentityHooks({ onSessionEnded: async () => {}, onVaultCreated: async () => {}, onKeysRotated: async () => { throw new Error('identity storage unavailable'); } }); await vault.lock(); const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } }); const oldPasswordWorks = await vault.verifyMainPassword('test-pass-12345'); const newPasswordWorks = await vault.verifyMainPassword('recovered-password'); expect(oldPasswordWorks).toBe(false); expect(newPasswordWorks).toBe(true); expect(result).toMatchObject({ ok: true, data: { committed: true, unlocked: false } }); expect(vault.isUnlocked()).toBe(false); expect(vi.mocked(chrome.tabs.sendMessage)).not.toHaveBeenCalledWith(expect.anything(), { type: 'VAULT_UNLOCKED' }); expect(await vault.unlock('recovered-password')).toBe(true); expect(vault.getEntries()[0]?.notes).toBe('saved'); }); it.each(['session', 'pair-secrets', 'PIN', 'auto-lock'] as const)('reports saved password and requires unlock after %s maintenance fails', async (maintenance) => { const vault = await import('./vault'); await setupUnlockedVault(); const words = await vault.getRecoveryWords(); await vault.lock(); if (maintenance === 'session') vi.mocked(chrome.storage.session.set).mockRejectedValueOnce(new Error('session unavailable')); if (maintenance === 'pair-secrets') { storage.peach_paired_devices_v3 = [{ deviceId: 'phone', pairedAt: Date.now(), rendezvousSecretHex: 'ab'.repeat(32) }]; const set = vi.mocked(chrome.storage.local.set); const original = set.getMockImplementation()!; let failed = false; set.mockImplementation(async (...args) => { if (!failed && 'peach_pair_secrets_v1' in args[0]) { failed = true; throw new Error('pair store unavailable'); } return original(...args); }); } if (maintenance === 'PIN') { const remove = vi.mocked(chrome.storage.session.remove); const original = remove.getMockImplementation()!; remove.mockImplementation(async (...args) => { if (Array.isArray(args[0])) throw new Error('PIN store unavailable'); return original(...args); }); } if (maintenance === 'auto-lock') vi.mocked(chrome.idle.setDetectionInterval).mockImplementationOnce(() => { throw new Error('idle API unavailable'); }); const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } }); expect(result).toMatchObject({ ok: true, data: { committed: true, unlocked: false } }); expect(vault.isUnlocked()).toBe(false); expect(vault.getRootKeyHex()).toBeNull(); expect(sessionStorage.peach_session_dk).toBeUndefined(); expect(await vault.verifyMainPassword('test-pass-12345')).toBe(false); expect(await vault.unlock('recovered-password')).toBe(true); }); it('preserves existing entries and the decoy slot during locked recovery', async () => { const vault = await import('./vault'); await setupUnlockedVault(); await vault.addEntry({ type: 'login', title: 'Existing account', password: 'keep-me' }); const removed = await vault.addEntry({ type: 'note', title: 'Purged note', notes: 'deleted' }); await vault.deleteEntry(removed.id); await vault.purgeEntry(removed.id); await vault.setupDuress('decoy-password'); const before = vault.getEntries(); const tombstones = vault.getTombstoneManifest(); const root = vault.getRootKeyHex(); const words = await vault.getRecoveryWords(); const slotA = JSON.stringify(storage.peach_vault_a); const slotB = JSON.stringify(storage.peach_vault_b); await vault.lock(); const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } }); expect(result.ok).toBe(true); expect(vault.getEntries()).toEqual(before); expect(vault.getTombstoneManifest()).toEqual(tombstones); expect(vault.getRootKeyHex()).toBe(root); expect(JSON.stringify(storage.peach_vault_b)).toBe(slotB); const history = storage.peach_vault_history as { snapshots: Array<{ vault_a: string; vault_b: string }> }; expect(history.snapshots[0]).toMatchObject({ vault_a: slotA, vault_b: slotB }); await vault.lock(); expect(await vault.unlock('recovered-password')).toBe(true); expect(vault.getEntries()).toEqual(before); expect(vault.getTombstoneManifest()).toEqual(tombstones); await vault.lock(); expect(await vault.unlock('decoy-password')).toBe(true); expect(vault.isDecoyMode()).toBe(true); }); it.each(['created', 'adopted', 'password-changed', 'root-rotated'] as const)('recovers a %s vault after a cold worker restart', async (kind) => { let vault = await import('./vault'); if (kind === 'adopted') await vault.createVaultFromRootKey('test-pass-12345', '42'.repeat(32)); else await setupUnlockedVault(); await vault.addEntry({ type: 'note', title: 'Before restart', notes: 'retained' }); if (kind === 'password-changed') expect(await vault.changePassword('test-pass-12345', 'changed-password')).toBe(true); if (kind === 'root-rotated') expect((await vault.rotateSyncIdentity()).ok).toBe(true); const words = await vault.getRecoveryWords(); const root = vault.getRootKeyHex(); await vault.lock(); vi.resetModules(); vault = await import('./vault'); await vault.recoverWithWords(words, 'cold-recovery-password'); expect(vault.getEntries()[0]?.notes).toBe('retained'); expect(vault.getRootKeyHex()).toBe(root); await vault.lock(); expect(await vault.unlock('cold-recovery-password')).toBe(true); expect(vault.getEntries()[0]?.notes).toBe('retained'); }); it.each(['aad', 'payload'] as const)('refuses mismatched %s authentication without writes', async (kind) => { const vault = await import('./vault'); await setupUnlockedVault(); const words = await vault.getRecoveryWords(); const slot = rawSlotA(); if (kind === 'aad') { const { encrypt } = await import('./aes'); const root = Uint8Array.from(vault.getRootKeyHex()!.match(/../g)!, (byte) => Number.parseInt(byte, 16)); slot.recovery_vault_key = await encrypt(root, vault.getDerivedKeyHex(), 'pw_root_v1'); } else slot.tag = '00'.repeat(16); await vault.lock(); const before = JSON.stringify(storage); expect((await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } })).ok).toBe(false); expect(JSON.stringify(storage)).toBe(before); expect(vault.getRootKeyHex()).toBeNull(); }); it.each(['missing', 'corrupt', 'stale'] as const)('refuses %s escrow unchanged and repairs it through real password unlock', async (kind) => { const vault = await import('./vault'); await setupUnlockedVault(); await vault.addEntry({ type: 'note', title: 'Keep this note', notes: 'original' }); const words = await vault.getRecoveryWords(); const slot = rawSlotA(); if (kind === 'missing') delete slot.recovery_vault_key; if (kind === 'corrupt') slot.recovery_vault_key = { nonce: '00', ciphertext: '00', tag: '00' }; if (kind === 'stale') { const { encrypt } = await import('./aes'); const root = Uint8Array.from(vault.getRootKeyHex()!.match(/../g)!, (byte) => Number.parseInt(byte, 16)); slot.recovery_vault_key = await encrypt(root, '00'.repeat(32), 'recovery_vault_key_v1'); } await vault.lock(); const before = JSON.stringify(storage); const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } }); expect(result.ok).toBe(false); expect(JSON.stringify(storage)).toBe(before); expect(vault.getRootKeyHex()).toBeNull(); expect(vault.isUnlocked()).toBe(false); expect(await vault.unlock('test-pass-12345')).toBe(true); await vault.lock(); expect((await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } })).ok).toBe(true); expect(vault.getEntries()[0]?.notes).toBe('original'); }); it('refuses unlocked real and decoy recovery without changing storage', async () => { const vault = await import('./vault'); await setupUnlockedVault(); const words = await vault.getRecoveryWords(); await vault.setupDuress('decoy-password'); for (const decoy of [false, true]) { if (decoy) { await vault.lock(); await vault.unlock('decoy-password'); } const before = JSON.stringify(storage); const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } }); expect(result.ok).toBe(false); expect(JSON.stringify(storage)).toBe(before); expect(vault.isDecoyMode()).toBe(decoy); } }); it('keeps original slots and stays locked when the recovery transaction fails', async () => { const vault = await import('./vault'); await setupUnlockedVault(); const words = await vault.getRecoveryWords(); await vault.lock(); const before = JSON.stringify(storage); vi.mocked(chrome.storage.local.set).mockRejectedValueOnce(new Error('storage unavailable')); expect((await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } })).ok).toBe(false); expect(JSON.stringify(storage)).toBe(before); expect(vault.isUnlocked()).toBe(false); expect(vault.getRootKeyHex()).toBeNull(); expect(await vault.unlock('test-pass-12345')).toBe(true); }); it('cancels recovery on manual lock and refuses concurrent unlock', async () => { const vault = await import('./vault'); await setupUnlockedVault(); const words = await vault.getRecoveryWords(); await vault.lock(); const before = JSON.stringify(storage); const get = vi.mocked(chrome.storage.local.get); const original = get.getMockImplementation()!; let release!: () => void; let started!: () => void; const paused = new Promise((resolve) => { release = resolve; }); const ready = new Promise((resolve) => { started = resolve; }); get.mockImplementationOnce(async (...args) => { started(); await paused; return original(...args); }); const recovering = dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } }); await ready; expect(await vault.unlock('test-pass-12345')).toBe(false); await vault.lock(); release(); expect((await recovering).ok).toBe(false); expect(JSON.stringify(storage)).toBe(before); expect(vault.getRootKeyHex()).toBeNull(); expect(vault.isUnlocked()).toBe(false); }); it('keeps a cancelled in-flight commit consistent and does not unlock', async () => { const vault = await import('./vault'); await setupUnlockedVault(); await vault.addEntry({ type: 'note', title: 'Retain on cancellation', notes: 'saved' }); const words = await vault.getRecoveryWords(); await vault.lock(); const before = JSON.stringify(storage.peach_vault_a); let release!: () => void; let started!: () => void; const paused = new Promise((resolve) => { release = resolve; }); const ready = new Promise((resolve) => { started = resolve; }); const set = vi.mocked(chrome.storage.local.set); const original = set.getMockImplementation()!; set.mockImplementationOnce(async (...args) => { expect(Object.keys(args[0]).sort()).toEqual(['peach_last_modified_at', 'peach_vault_a', 'peach_vault_history']); started(); await paused; return original(...args); }); const recovering = dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } }); await ready; await vault.lock(); release(); expect(await recovering).toMatchObject({ ok: true, data: { committed: true, unlocked: false } }); expect(vault.isUnlocked()).toBe(false); expect(vault.getRootKeyHex()).toBeNull(); const history = storage.peach_vault_history as { snapshots: Array<{ vault_a: string }> }; expect(history.snapshots[0]?.vault_a).toBe(before); expect(await vault.unlock('recovered-password')).toBe(true); expect(vault.getEntries()[0]?.notes).toBe('saved'); }); it('does not enroll legacy escrow through a pre-derived key, session restore, or decoy unlock', async () => { let vault = await import('./vault'); await setupUnlockedVault(); await vault.setupDuress('decoy-password'); const key = vault.getDerivedKeyHex(); delete rawSlotA().recovery_vault_key; await vault.lock(); expect((await vault.unlockWithKey(key)).ok).toBe(true); expect(rawSlotA().recovery_vault_key).toBeUndefined(); vi.resetModules(); vault = await import('./vault'); expect(await vault.restoreFromSession()).toBe(true); expect(rawSlotA().recovery_vault_key).toBeUndefined(); await vault.lock(); expect(await vault.unlock('decoy-password')).toBe(true); expect(rawSlotA().recovery_vault_key).toBeUndefined(); await vault.lock(); expect(await vault.unlock('test-pass-12345')).toBe(true); expect(rawSlotA().recovery_vault_key).toBeDefined(); }); it('preserves the local identity and paired reconnect secret', async () => { const vault = await import('./vault'); const pairs = await import('./pair-secrets'); const devices = await import('./paired-devices'); await setupUnlockedVault(); const rootHex = vault.getRootKeyHex()!; const root = Uint8Array.from(rootHex.match(/../g)!, (byte) => Number.parseInt(byte, 16)); await devices.upsertPairedDevice({ deviceId: 'paired-phone', deviceName: 'Phone', deviceType: 'android', longTermPublicKeyHex: '43'.repeat(32), pairedAt: Date.now() }); await pairs.setPairSecret('paired-phone', 'ab'.repeat(32), root); const identityKey = new Uint8Array(32).fill(7); let identity = await vault.sealIdentityKeyUnderVault(identityKey); vault.setIdentityHooks({ onSessionEnded: async () => {}, onVaultCreated: async () => {}, onKeysRotated: async () => { const opened = await vault.openIdentityKey(identity); expect(opened).toEqual(identityKey); identity = await vault.sealIdentityKeyUnderVault(opened!); }, }); const words = await vault.getRecoveryWords(); await vault.lock(); await vault.recoverWithWords(words, 'recovered-password'); expect(await vault.openIdentityKey(identity)).toEqual(identityKey); expect(await pairs.getPairSecret('paired-phone', vault.getRootKeyHex())).toBe('ab'.repeat(32)); await vault.lock(); expect(await vault.unlock('recovered-password')).toBe(true); expect(await vault.openIdentityKey(identity)).toEqual(identityKey); expect(await pairs.getPairSecret('paired-phone', vault.getRootKeyHex())).toBe('ab'.repeat(32)); }); it('refuses recovery while a Codex replacement is staged', async () => { const vault = await import('./vault'); await setupUnlockedVault(); const words = await vault.getRecoveryWords(); const slotA = JSON.stringify(storage.peach_vault_a); const slotB = JSON.stringify(storage.peach_vault_b); await vault.lock(); const importing = vault.unlockFromCodex({ slotA, slotB, timestamp: Date.now(), masterPassphrase: 'test-pass-12345' }); await expect(vault.recoverWithWords(words, 'recovered-password')).rejects.toThrow('vault_changed'); expect((await importing).ok).toBe(true); expect(await vault.verifyMainPassword('test-pass-12345')).toBe(true); }); it('refuses recovery while an earlier creation derives its password', async () => { const vault = await import('./vault'); const argon = await import('../crypto/argon2'); await setupUnlockedVault(); await vault.addEntry({ type: 'note', title: 'Keep recovered data', notes: 'original' }); const words = await vault.getRecoveryWords(); await vault.lock(); let release!: () => void; const paused = new Promise((resolve) => { release = resolve; }); const derive = argon.deriveKey; const spy = vi.spyOn(argon, 'deriveKey').mockImplementationOnce(async (...args) => { const key = await derive(...args); await paused; return key; }); const creating = vault.createVault('concurrent-creation-password', 'warned-import').then(() => 'created', (error: Error) => error.message); const recovering = await vault.recoverWithWords(words, 'recovered-password').then(() => 'recovered', (error: Error) => error.message); const before = JSON.stringify(storage); await vault.lock(); release(); expect(await creating).toBe('vault_changed'); spy.mockRestore(); expect(recovering).toBe('vault_changed'); expect(JSON.stringify(storage)).toBe(before); expect(vault.getRootKeyHex()).toBeNull(); }); it('refuses recovery while creation is paused after its password derivation', async () => { const vault = await import('./vault'); await setupUnlockedVault(); const words = await vault.getRecoveryWords(); await vault.lock(); const before = JSON.stringify(storage); const encrypt = crypto.subtle.encrypt.bind(crypto.subtle); let release!: () => void; let started!: () => void; const paused = new Promise((resolve) => { release = resolve; }); const ready = new Promise((resolve) => { started = resolve; }); const spy = vi.spyOn(crypto.subtle, 'encrypt').mockImplementationOnce(async (...args) => { const value = await encrypt(...args); started(); await paused; return value; }); const creating = vault.createVault('concurrent-creation-password', 'warned-import').then(() => 'created', (error: Error) => error.message); await ready; await vault.lock(); const recovering = await vault.recoverWithWords(words, 'recovered-password').then(() => 'recovered', (error: Error) => error.message); release(); const created = await creating; spy.mockRestore(); expect(recovering).toBe('vault_changed'); expect(created).toBe('vault_changed'); expect(JSON.stringify(storage)).toBe(before); expect(vault.getRootKeyHex()).toBeNull(); }); it.each([null, undefined, 42, 'words'])('rejects malformed recovery payload %s explicitly', async (payload) => { const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload } as unknown as Message); expect(result).toMatchObject({ ok: false, error: 'invalid_recovery_payload' }); }); it.each(['panic', 'adoption-rollback'] as const)('orders %s after a previously issued recovery write', async (kind) => { const vault = await import('./vault'); await setupUnlockedVault(); const words = await vault.getRecoveryWords(); await vault.lock(); const set = vi.mocked(chrome.storage.local.set); const original = set.getMockImplementation()!; let release!: () => void; let started!: () => void; const paused = new Promise((resolve) => { release = resolve; }); const ready = new Promise((resolve) => { started = resolve; }); set.mockImplementationOnce(async (...args) => { started(); await paused; return original(...args); }); const recovering = dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } }); await ready; let removed = false; const removing = (kind === 'panic' ? dispatch({ type: 'DESTROY_VAULT' }) : vault.rollbackAdoptedVault().then(() => ({ ok: true }), () => ({ ok: false }))).then((result) => { removed = true; return result; }); await new Promise((resolve) => setTimeout(resolve, 0)); const removedBeforeRecoverySettled = removed; release(); const recoveryResult = await recovering; const removalResult = await removing; expect(storage.peach_vault_a).toBeUndefined(); expect(storage.peach_vault_b).toBeUndefined(); expect(removedBeforeRecoverySettled).toBe(false); expect(recoveryResult).toMatchObject({ ok: true, data: { committed: true, unlocked: false } }); expect(removalResult.ok).toBe(true); expect(vault.isUnlocked()).toBe(false); if (kind === 'panic') { const history = storage.peach_vault_history as { snapshots: unknown[] }; expect(history.snapshots).toEqual([]); } }); it('recovery succeeds with correct words and new passphrase', async () => { await setupUnlockedVault(); const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const words = (r as { data: string[] }).data; await lockVault(); const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'new-passphrase' }, }); expect(result.ok).toBe(true); const unlocked = await dispatch({ type: 'IS_UNLOCKED' }); expect((unlocked as { data: boolean }).data).toBe(true); }); it('fails with wrong recovery words', async () => { await setupUnlockedVault(); await lockVault(); const fakeWords = Array(12).fill('abandon'); const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words: fakeWords, newPassword: 'new-pass' }, }); expect(result.ok).toBe(false); expect((result as { error: string }).error).toMatch(/invalid/); }); it('fails with partial word list (fewer than 12)', async () => { await setupUnlockedVault(); const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const words = (r as { data: string[] }).data; await lockVault(); const partial = words.slice(0, 6); const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words: partial, newPassword: 'new-pass' }, }); expect(result.ok).toBe(false); }); it('new passphrase works after recovery', async () => { await setupUnlockedVault(); const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const words = (r as { data: string[] }).data; await lockVault(); await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'brand-new-password' }, }); await lockVault(); const unlock = await dispatch({ type: 'UNLOCK', payload: { password: 'brand-new-password' }, }); expect(unlock.ok).toBe(true); }); it('old passphrase does not work after recovery', async () => { await setupUnlockedVault(); const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const words = (r as { data: string[] }).data; await lockVault(); await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'brand-new-password' }, }); await lockVault(); const unlock = await dispatch({ type: 'UNLOCK', payload: { password: 'test-pass-12345' }, }); expect(unlock.ok).toBe(false); }); it('preserves recovery escrow fields after recovery password rewrap', async () => { await setupUnlockedVault(); const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const words = (r as { data: string[] }).data; const before = { ...rawSlotA() }; await lockVault(); const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'new-passphrase' }, }); expect(result.ok).toBe(true); const after = rawSlotA(); expect(after.recovery_wrapped_root_key).toBe(before.recovery_wrapped_root_key); expect(after.recovery_nonce).toBe(before.recovery_nonce); expect(after.recovery_tag).toBe(before.recovery_tag); expect(after.recovery_salt).toBe(before.recovery_salt); expect(after.ciphertext).not.toBe(before.ciphertext); expect(after.salt).not.toBe(before.salt); }); it('same recovery words succeed on a second recovery', async () => { await setupUnlockedVault(); const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const words = (r as { data: string[] }).data; await lockVault(); const first = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'pass-1' }, }); expect(first.ok).toBe(true); await lockVault(); const second = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'pass-2' }, }); expect(second.ok).toBe(true); await lockVault(); const unlock = await dispatch({ type: 'UNLOCK', payload: { password: 'pass-2' }, }); expect(unlock.ok).toBe(true); }); it('same recovery words succeed on a third recovery', async () => { await setupUnlockedVault(); const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const words = (r as { data: string[] }).data; for (let i = 0; i < 3; i += 1) { await lockVault(); const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: `pass-${i}` }, }); expect(result.ok).toBe(true); } }); it('vault remains usable after recovery', async () => { await setupUnlockedVault(); const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const words = (r as { data: string[] }).data; await lockVault(); const recovered = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'new-passphrase' }, }); expect(recovered.ok).toBe(true); await dispatch({ type: 'ADD_ENTRY', payload: { title: 'Check me', username: '', password: 'p', url: '' }, }); const entries = (await dispatch({ type: 'GET_ENTRIES' }) as { data: Array<{ title: string }> }).data; expect(entries.some((entry) => entry.title === 'Check me')).toBe(true); }); // H4/COR-002: changePassword MUST preserve the root key so the user's // existing recovery words continue to work. Rotating the root key on // every password change would silently brick recovery. it('recovery words are preserved across CHANGE_PASSWORD', async () => { await setupUnlockedVault(); const before = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data; await dispatch({ type: 'CHANGE_PASSWORD', payload: { currentPassword: 'test-pass-12345', newPassword: 'new-pass-67890' }, }); const after = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'new-pass-67890' } }) as { data: string[] }).data; expect(after).toEqual(before); }); it('recovery is not Pro-gated', async () => { await setupUnlockedVault(); await mockNoPro(); const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const words = (r as { data: string[] }).data; await lockVault(); const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'new-pass' }, }); expect((result as { error?: string }).error ?? '').not.toMatch(/pro_required/); }); }); // H4/COR-002 — changePassword must re-wrap the existing root key, not mint // a new one. The recovery words derived from rootKey must remain valid // after any password change. describe('changePassword preserves root key and recovery words', () => { it('recovery words work to unlock after password change', async () => { await setupUnlockedVault(); const words = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data; const ch = await dispatch({ type: 'CHANGE_PASSWORD', payload: { currentPassword: 'test-pass-12345', newPassword: 'new-pass-aaa' }, }); expect(ch.ok).toBe(true); await lockVault(); const r = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-pass' }, }); expect(r.ok).toBe(true); }); it('recovery words are identical before and after password change', async () => { await setupUnlockedVault(); const before = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data; await dispatch({ type: 'CHANGE_PASSWORD', payload: { currentPassword: 'test-pass-12345', newPassword: 'another-pass-bbb' }, }); const after = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'another-pass-bbb' } }) as { data: string[] }).data; expect(after).toEqual(before); }); it('vault unlocks with the new password after change', async () => { await setupUnlockedVault(); await dispatch({ type: 'CHANGE_PASSWORD', payload: { currentPassword: 'test-pass-12345', newPassword: 'brand-new-pass' }, }); await lockVault(); const r = await dispatch({ type: 'UNLOCK', payload: { password: 'brand-new-pass' }, }); expect(r.ok).toBe(true); }); it('the old password no longer unlocks after change', async () => { await setupUnlockedVault(); await dispatch({ type: 'CHANGE_PASSWORD', payload: { currentPassword: 'test-pass-12345', newPassword: 'brand-new-pass' }, }); await lockVault(); const r = await dispatch({ type: 'UNLOCK', payload: { password: 'test-pass-12345' }, }); expect(r.ok).toBe(false); }); it('GET_RECOVERY_WORDS still works after a password change + lock + unlock', async () => { await setupUnlockedVault(); const before = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data; await dispatch({ type: 'CHANGE_PASSWORD', payload: { currentPassword: 'test-pass-12345', newPassword: 'pass-after-cycle' }, }); await lockVault(); await dispatch({ type: 'UNLOCK', payload: { password: 'pass-after-cycle' }, }); const after = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'pass-after-cycle' } }) as { data: string[] }).data; expect(after).toEqual(before); }); }); // H2/COR-006/SEC-006/CRYPTO-11 — rootKey must survive lock/unlock cycles // so the user's 12 recovery words are stable across sessions. The fix is // a pw_root_* second wrapping under the password-derived key. describe('deriveRootKeyFromDerivedKey and recovery persistence', () => { it('GET_RECOVERY_WORDS works after lock and re-unlock', async () => { await setupUnlockedVault(); const r1 = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const words1 = (r1 as { data: string[] }).data; expect(words1).toHaveLength(12); await lockVault(); const unlocked = await dispatch({ type: 'UNLOCK', payload: { password: 'test-pass-12345' }, }); expect(unlocked.ok).toBe(true); const r2 = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }); const words2 = (r2 as { data: string[] }).data; expect(words2).toEqual(words1); }); it('GET_RECOVERY_WORDS works after multiple lock/unlock cycles', async () => { await setupUnlockedVault(); const original = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data; for (let i = 0; i < 5; i++) { await lockVault(); await dispatch({ type: 'UNLOCK', payload: { password: 'test-pass-12345' }, }); } const after = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data; expect(after).toEqual(original); }); }); });