1import { describe, it, expect, beforeEach } from 'vitest';2import { vi } from 'vitest';34import type { Message, MessageResponse, StoredVault } from '../shared/types';5import { WORD_LIST } from '../shared/recovery-word-list';6789101112vi.setConfig({ testTimeout: 30_000 });1314type StorageShape = Record<string, unknown>;15type MessageListener = (16 msg: unknown,17 sender: chrome.runtime.MessageSender,18 sendResponse: (response: MessageResponse) => void19) => boolean;2021describe('recovery words handlers', () => {22 let storage: StorageShape;23 let sessionStorage: StorageShape;24 let listener: MessageListener;2526 beforeEach(async () => {27 vi.resetModules();28 vi.useRealTimers();29 storage = { peach_settings: { breachMonitoring: false } };30 sessionStorage = {};3132 vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, text: async () => '' })));33 vi.stubGlobal('__PEACH_E2E_PASSKEYS__', false);3435 const chromeMock = {36 runtime: {37 id: 'peach-extension',38 getURL: (path = '') => `chrome-extension://peach-extension/${path}`,39 onMessage: { addListener: vi.fn((fn: MessageListener) => { listener = fn; }) },40 sendMessage: vi.fn(async () => ({ ok: true })),41 },42 tabs: {43 query: vi.fn((_, cb?: (tabs: unknown[]) => void) => {44 if (typeof cb === 'function') { cb([{ id: 1 }]); return; }45 return Promise.resolve([{ id: 1 }]);46 }),47 sendMessage: vi.fn(async () => ({ ok: true })),48 },49 storage: {50 local: {51 get: vi.fn(async (key?: string | string[]) => {52 if (!key) return storage;53 if (typeof key === 'string') return { [key]: storage[key] };54 return key.reduce<Record<string, unknown>>((acc, k) => { acc[k] = storage[k]; return acc; }, {});55 }),56 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]; }),58 remove: vi.fn(async (keys: string | string[]) => {59 const list = Array.isArray(keys) ? keys : [keys];60 for (const key of list) delete storage[key];61 }),62 },63 session: {64 get: vi.fn(async (key?: string | string[]) => {65 if (!key) return sessionStorage;66 if (typeof key === 'string') return { [key]: sessionStorage[key] };67 return key.reduce<Record<string, unknown>>((acc, k) => { acc[k] = sessionStorage[k]; return acc; }, {});68 }),69 set: vi.fn(async (next: Record<string, unknown>) => { Object.assign(sessionStorage, next); }),70 remove: vi.fn(async (keys: string | string[]) => {71 const list = Array.isArray(keys) ? keys : [keys];72 for (const key of list) delete sessionStorage[key];73 }),74 clear: vi.fn(async () => { for (const k of Object.keys(sessionStorage)) delete sessionStorage[k]; }),75 },76 },77 alarms: {78 clear: vi.fn(), create: vi.fn(),79 onAlarm: { addListener: vi.fn() },80 },81 idle: {82 setDetectionInterval: vi.fn(),83 onStateChanged: { addListener: vi.fn() },84 },85 scripting: { executeScript: vi.fn(async () => []) },86 } as unknown as typeof chrome;8788 (globalThis as { chrome?: typeof chrome }).chrome = chromeMock;8990 const messages = await import('./messages');91 messages.setupMessageHandler();92 const vault = await import('./vault');93 await vault.ensureSettingsLoaded();94 });9596 async function dispatch(message: Message): Promise<MessageResponse> {97 return new Promise<MessageResponse>((resolve) => {98 const keepOpen = listener(message, {99 id: 'peach-extension',100 url: 'chrome-extension://peach-extension/popup.html',101 }, resolve);102 expect(keepOpen).toBe(true);103 });104 }105106 async function setupUnlockedVault(): Promise<void> {107 const vault = await import('./vault');108 await vault.createVault('test-pass-12345');109 }110111 async function lockVault(): Promise<void> {112 const vault = await import('./vault');113 vault.lock();114 }115116 function rawSlotA(): StoredVault {117 const slot = storage.peach_vault_a as StoredVault | undefined;118 if (!slot) throw new Error('missing slot A');119 return slot;120 }121122 async function mockNoPro(): Promise<void> {123 const license = await import('./license');124 vi.spyOn(license, 'isProUser').mockResolvedValue(false);125 }126127 describe('GET_RECOVERY_WORDS handler', () => {128 beforeEach(async () => { await setupUnlockedVault(); });129130 it('returns 12 words', async () => {131 const result = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });132 expect(result.ok).toBe(true);133 const words = (result as { data: string[] }).data;134 expect(words).toHaveLength(12);135 });136137 it('all words are from the BIP39 word list', async () => {138 const result = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });139 const words = (result as { data: string[] }).data;140 for (const word of words) {141 expect(WORD_LIST).toContain(word);142 }143 });144145 it('returns same words on subsequent calls (deterministic)', async () => {146 const r1 = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });147 const r2 = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });148 expect((r1 as { data: string[] }).data).toEqual((r2 as { data: string[] }).data);149 });150151 it('returns error when vault is locked', async () => {152 await lockVault();153 const result = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });154 expect(result.ok).toBe(false);155 });156 });157158 describe('VALIDATE_RECOVERY_WORDS handler', () => {159 beforeEach(async () => { await setupUnlockedVault(); });160161 it('returns no invalid words for correct list', async () => {162 const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });163 const words = (r as { data: string[] }).data;164 const result = await dispatch({165 type: 'VALIDATE_RECOVERY_WORDS',166 payload: { words },167 });168 const data = (result as { data: { invalid: Array<{ index: number; word: string }> } }).data;169 expect(data.invalid).toEqual([]);170 });171172 it('returns invalid words for unknown words', async () => {173 const result = await dispatch({174 type: 'VALIDATE_RECOVERY_WORDS',175 payload: { words: ['notaword', 'alsonotaword'] },176 });177 const data = (result as { data: { invalid: Array<{ index: number; word: string }> } }).data;178 const invalidWords = data.invalid.map((x) => x.word);179 expect(invalidWords).toContain('notaword');180 expect(invalidWords).toContain('alsonotaword');181 });182183 it('is case-insensitive for validation', async () => {184 const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });185 const words = (r as { data: string[] }).data;186 const uppercased = words.map((w: string) => w.toUpperCase());187 const result = await dispatch({188 type: 'VALIDATE_RECOVERY_WORDS',189 payload: { words: uppercased },190 });191 const data = (result as { data: { invalid: Array<{ index: number; word: string }> } }).data;192 expect(data.invalid).toEqual([]);193 });194 });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 });216217 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 });281282 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 });301302 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 });318319 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 });344345 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 });359360 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 });373374 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 });397398 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 });427428 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 });448449 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 });479480 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 });492493 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', 'warned-import').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 });517518 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', 'warned-import').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 });544545 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 });549550 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 });584585 it('recovery succeeds with correct words and new passphrase', async () => {586 await setupUnlockedVault();587 const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });588 const words = (r as { data: string[] }).data;589 await lockVault();590591 const result = await dispatch({592 type: 'RECOVER_WITH_WORDS',593 payload: { words, newPassword: 'new-passphrase' },594 });595 expect(result.ok).toBe(true);596 const unlocked = await dispatch({ type: 'IS_UNLOCKED' });597 expect((unlocked as { data: boolean }).data).toBe(true);598 });599600 it('fails with wrong recovery words', async () => {601 await setupUnlockedVault();602 await lockVault();603 const fakeWords = Array(12).fill('abandon');604 const result = await dispatch({605 type: 'RECOVER_WITH_WORDS',606 payload: { words: fakeWords, newPassword: 'new-pass' },607 });608 expect(result.ok).toBe(false);609 expect((result as { error: string }).error).toMatch(/invalid/);610 });611612 it('fails with partial word list (fewer than 12)', async () => {613 await setupUnlockedVault();614 const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });615 const words = (r as { data: string[] }).data;616 await lockVault();617 const partial = words.slice(0, 6);618 const result = await dispatch({619 type: 'RECOVER_WITH_WORDS',620 payload: { words: partial, newPassword: 'new-pass' },621 });622 expect(result.ok).toBe(false);623 });624625 it('new passphrase works after recovery', async () => {626 await setupUnlockedVault();627 const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });628 const words = (r as { data: string[] }).data;629 await lockVault();630 await dispatch({631 type: 'RECOVER_WITH_WORDS',632 payload: { words, newPassword: 'brand-new-password' },633 });634 await lockVault();635 const unlock = await dispatch({636 type: 'UNLOCK',637 payload: { password: 'brand-new-password' },638 });639 expect(unlock.ok).toBe(true);640 });641642 it('old passphrase does not work after recovery', async () => {643 await setupUnlockedVault();644 const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });645 const words = (r as { data: string[] }).data;646 await lockVault();647 await dispatch({648 type: 'RECOVER_WITH_WORDS',649 payload: { words, newPassword: 'brand-new-password' },650 });651 await lockVault();652 const unlock = await dispatch({653 type: 'UNLOCK',654 payload: { password: 'test-pass-12345' },655 });656 expect(unlock.ok).toBe(false);657 });658659 it('preserves recovery escrow fields after recovery password rewrap', async () => {660 await setupUnlockedVault();661 const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });662 const words = (r as { data: string[] }).data;663 const before = { ...rawSlotA() };664 await lockVault();665666 const result = await dispatch({667 type: 'RECOVER_WITH_WORDS',668 payload: { words, newPassword: 'new-passphrase' },669 });670 expect(result.ok).toBe(true);671672 const after = rawSlotA();673 expect(after.recovery_wrapped_root_key).toBe(before.recovery_wrapped_root_key);674 expect(after.recovery_nonce).toBe(before.recovery_nonce);675 expect(after.recovery_tag).toBe(before.recovery_tag);676 expect(after.recovery_salt).toBe(before.recovery_salt);677 expect(after.ciphertext).not.toBe(before.ciphertext);678 expect(after.salt).not.toBe(before.salt);679 });680681 it('same recovery words succeed on a second recovery', async () => {682 await setupUnlockedVault();683 const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });684 const words = (r as { data: string[] }).data;685686 await lockVault();687 const first = await dispatch({688 type: 'RECOVER_WITH_WORDS',689 payload: { words, newPassword: 'pass-1' },690 });691 expect(first.ok).toBe(true);692693 await lockVault();694 const second = await dispatch({695 type: 'RECOVER_WITH_WORDS',696 payload: { words, newPassword: 'pass-2' },697 });698 expect(second.ok).toBe(true);699700 await lockVault();701 const unlock = await dispatch({702 type: 'UNLOCK',703 payload: { password: 'pass-2' },704 });705 expect(unlock.ok).toBe(true);706 });707708 it('same recovery words succeed on a third recovery', async () => {709 await setupUnlockedVault();710 const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });711 const words = (r as { data: string[] }).data;712713 for (let i = 0; i < 3; i += 1) {714 await lockVault();715 const result = await dispatch({716 type: 'RECOVER_WITH_WORDS',717 payload: { words, newPassword: `pass-${i}` },718 });719 expect(result.ok).toBe(true);720 }721 });722723 it('vault remains usable after recovery', async () => {724 await setupUnlockedVault();725 const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });726 const words = (r as { data: string[] }).data;727728 await lockVault();729 const recovered = await dispatch({730 type: 'RECOVER_WITH_WORDS',731 payload: { words, newPassword: 'new-passphrase' },732 });733 expect(recovered.ok).toBe(true);734735 await dispatch({736 type: 'ADD_ENTRY',737 payload: { title: 'Check me', username: '', password: 'p', url: '' },738 });739 const entries = (await dispatch({ type: 'GET_ENTRIES' }) as { data: Array<{ title: string }> }).data;740 expect(entries.some((entry) => entry.title === 'Check me')).toBe(true);741 });742743 744 745 746 it('recovery words are preserved across CHANGE_PASSWORD', async () => {747 await setupUnlockedVault();748 const before = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data;749 await dispatch({750 type: 'CHANGE_PASSWORD',751 payload: { currentPassword: 'test-pass-12345', newPassword: 'new-pass-67890' },752 });753 const after = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'new-pass-67890' } }) as { data: string[] }).data;754 expect(after).toEqual(before);755 });756757 it('recovery is not Pro-gated', async () => {758 await setupUnlockedVault();759 await mockNoPro();760 const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });761 const words = (r as { data: string[] }).data;762 await lockVault();763 const result = await dispatch({764 type: 'RECOVER_WITH_WORDS',765 payload: { words, newPassword: 'new-pass' },766 });767 expect((result as { error?: string }).error ?? '').not.toMatch(/pro_required/);768 });769 });770771 772 773 774 describe('changePassword preserves root key and recovery words', () => {775 it('recovery words work to unlock after password change', async () => {776 await setupUnlockedVault();777 const words = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data;778 const ch = await dispatch({779 type: 'CHANGE_PASSWORD',780 payload: { currentPassword: 'test-pass-12345', newPassword: 'new-pass-aaa' },781 });782 expect(ch.ok).toBe(true);783 await lockVault();784 const r = await dispatch({785 type: 'RECOVER_WITH_WORDS',786 payload: { words, newPassword: 'recovered-pass' },787 });788 expect(r.ok).toBe(true);789 });790791 it('recovery words are identical before and after password change', async () => {792 await setupUnlockedVault();793 const before = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data;794 await dispatch({795 type: 'CHANGE_PASSWORD',796 payload: { currentPassword: 'test-pass-12345', newPassword: 'another-pass-bbb' },797 });798 const after = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'another-pass-bbb' } }) as { data: string[] }).data;799 expect(after).toEqual(before);800 });801802 it('vault unlocks with the new password after change', async () => {803 await setupUnlockedVault();804 await dispatch({805 type: 'CHANGE_PASSWORD',806 payload: { currentPassword: 'test-pass-12345', newPassword: 'brand-new-pass' },807 });808 await lockVault();809 const r = await dispatch({810 type: 'UNLOCK',811 payload: { password: 'brand-new-pass' },812 });813 expect(r.ok).toBe(true);814 });815816 it('the old password no longer unlocks after change', async () => {817 await setupUnlockedVault();818 await dispatch({819 type: 'CHANGE_PASSWORD',820 payload: { currentPassword: 'test-pass-12345', newPassword: 'brand-new-pass' },821 });822 await lockVault();823 const r = await dispatch({824 type: 'UNLOCK',825 payload: { password: 'test-pass-12345' },826 });827 expect(r.ok).toBe(false);828 });829830 it('GET_RECOVERY_WORDS still works after a password change + lock + unlock', async () => {831 await setupUnlockedVault();832 const before = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data;833 await dispatch({834 type: 'CHANGE_PASSWORD',835 payload: { currentPassword: 'test-pass-12345', newPassword: 'pass-after-cycle' },836 });837 await lockVault();838 await dispatch({839 type: 'UNLOCK',840 payload: { password: 'pass-after-cycle' },841 });842 const after = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'pass-after-cycle' } }) as { data: string[] }).data;843 expect(after).toEqual(before);844 });845 });846847 848 849 850 describe('deriveRootKeyFromDerivedKey and recovery persistence', () => {851 it('GET_RECOVERY_WORDS works after lock and re-unlock', async () => {852 await setupUnlockedVault();853 const r1 = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });854 const words1 = (r1 as { data: string[] }).data;855 expect(words1).toHaveLength(12);856 await lockVault();857 const unlocked = await dispatch({858 type: 'UNLOCK',859 payload: { password: 'test-pass-12345' },860 });861 expect(unlocked.ok).toBe(true);862 const r2 = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });863 const words2 = (r2 as { data: string[] }).data;864 expect(words2).toEqual(words1);865 });866867 it('GET_RECOVERY_WORDS works after multiple lock/unlock cycles', async () => {868 await setupUnlockedVault();869 const original = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data;870 for (let i = 0; i < 5; i++) {871 await lockVault();872 await dispatch({873 type: 'UNLOCK',874 payload: { password: 'test-pass-12345' },875 });876 }877 const after = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data;878 expect(after).toEqual(original);879 });880881 });882});