recovery-words.test.ts

49.3 KB · raw

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';67// Every unlock/GET_RECOVERY_WORDS here runs real Argon2id (m=64MiB, t=3, p=4).8// The lock/unlock-cycle cases do seven derivations, which lands just past9// vitest's 5s default once the full suite is competing for CPU — the failures10// clustered at 5.0-5.1s, not at random points. Raised for the whole file11// because every case in it is Argon2-bound, not just the ones that flaked.12vi.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  });157158159  describe("PB-26-945 recovery authority", () => {160    it("rejects arbitrary exemption requests", async () => {161      await setupUnlockedVault();162      expect(await dispatch({ type: "SET_RECOVERY_CONFIRM_PENDING" })).toMatchObject({ ok: false, error: "invalid_sender" });163      expect(await dispatch({ type: "GET_RECOVERY_WORDS" })).toMatchObject({ ok: false, error: "password_required" });164    });165166    it("rejected creation cannot grant an existing vault a reveal", async () => {167      await setupUnlockedVault();168      expect(await dispatch({ type: "CREATE_VAULT", payload: { password: "replacement-password" } })).toMatchObject({ ok: false });169      expect(await dispatch({ type: "GET_RECOVERY_CONFIRM_PENDING" })).toMatchObject({ data: false });170      expect(await dispatch({ type: "GET_RECOVERY_WORDS" })).toMatchObject({ error: "password_required" });171    });172173    it("onboarding creation grants exactly one concurrent password-free read", async () => {174      expect(await dispatch({ type: "CREATE_VAULT", payload: { password: "test-pass-12345", purpose: "onboarding" } })).toMatchObject({ ok: true });175      const results = await Promise.all([dispatch({ type: "GET_RECOVERY_WORDS" }), dispatch({ type: "GET_RECOVERY_WORDS" })]);176      expect(results.filter((result) => result.ok)).toHaveLength(1);177      expect(results.filter((result) => result.error === "password_required")).toHaveLength(1);178      expect(await dispatch({ type: "GET_RECOVERY_CONFIRM_PENDING" })).toMatchObject({ ok: true, data: true });179    });180181    it.each([undefined, "warned-import"])("import/restore creation has no recovery grant or route (%s)", async (replacement) => {182      if (replacement) await setupUnlockedVault();183      expect(await dispatch({ type: "CREATE_VAULT", payload: { password: "test-pass-12345", ...(replacement ? { replacement } : {}) } })).toMatchObject({ ok: true });184      expect(await dispatch({ type: "GET_RECOVERY_CONFIRM_PENDING" })).toMatchObject({ data: false });185      expect(await dispatch({ type: "GET_RECOVERY_WORDS" })).toMatchObject({ error: "password_required" });186    });187188    it.each([{ purpose: "unexpected" }, { purpose: "onboarding", replacement: "warned-import" }])("rejects unsupported creation purpose combinations %j", async (extra) => {189      expect(await dispatch({ type: "CREATE_VAULT", payload: { password: "test-pass-12345", ...extra } })).toMatchObject({ ok: false, error: "invalid_payload" });190      expect(storage.peach_vault_a).toBeUndefined();191    });192193    it.each([undefined, "incorrect-password"])("rotation rejects missing or wrong proof (%s)", async (password) => {194      await setupUnlockedVault();195      const vault = await import("./vault");196      const root = vault.getRootKeyHex();197      expect(await dispatch({ type: "ROTATE_SYNC_IDENTITY", payload: { password } })).toMatchObject({ ok: false, error: password ? "wrong_password" : "password_required" });198      expect(vault.getRootKeyHex()).toBe(root);199      expect(await dispatch({ type: "GET_RECOVERY_CONFIRM_PENDING" })).toMatchObject({ data: false });200    });201202    it("rotation rejects proof from an ended session", async () => {203      await setupUnlockedVault();204      const vault = await import("./vault");205      let release!: (value: boolean) => void;206      const verify = vi.spyOn(vault, "verifyMainPassword").mockReturnValueOnce(new Promise((resolve) => { release = resolve; }));207      const rotation = dispatch({ type: "ROTATE_SYNC_IDENTITY", payload: { password: "test-pass-12345" } });208      await vi.waitFor(() => expect(verify).toHaveBeenCalled());209      await vault.lock();210      await vault.unlock("test-pass-12345");211      const root = vault.getRootKeyHex();212      release(true);213      expect(await rotation).toMatchObject({ ok: false, error: "vault_locked" });214      expect(vault.getRootKeyHex()).toBe(root);215    });216217    it("rotation with fresh proof grants one initial reveal", async () => {218      await setupUnlockedVault();219      expect(await dispatch({ type: "ROTATE_SYNC_IDENTITY", payload: { password: "test-pass-12345" } })).toMatchObject({ ok: true });220      expect(await dispatch({ type: "GET_RECOVERY_WORDS" })).toMatchObject({ ok: true });221      expect(await dispatch({ type: "GET_RECOVERY_WORDS" })).toMatchObject({ error: "password_required" });222    });223224    it("completed destruction cannot be followed by stale rotation routing", async () => {225      await setupUnlockedVault();226      const vault = await import("./vault");227      let release!: () => void;228      let committed!: () => void;229      const blocked = new Promise<void>((resolve) => { release = resolve; });230      const issued = new Promise<void>((resolve) => { committed = resolve; });231      vi.mocked(chrome.storage.local.set).mockImplementation(async (values) => {232        Object.assign(storage, values);233        if (Object.hasOwn(values, "peach_vault_a")) { committed(); await blocked; }234      });235      const rotation = vault.rotateSyncIdentity();236      await issued;237      expect(await dispatch({ type: "DESTROY_VAULT" })).toMatchObject({ ok: true });238      release();239      expect(await rotation).toMatchObject({ ok: true });240      expect(await dispatch({ type: "GET_RECOVERY_CONFIRM_PENDING" })).toMatchObject({ data: false });241      await vault.createVaultFromRootKey("adopted-password", "11".repeat(32));242      expect(await dispatch({ type: "GET_RECOVERY_CONFIRM_PENDING" })).toMatchObject({ data: false });243    });244245    it("discards a reveal after lock overtakes its awaited grant", async () => {246      await setupUnlockedVault();247      const vault = await import("./vault");248      const pending = await import("./recovery-pending");249      let release!: (value: boolean) => void;250      const consume = vi.spyOn(pending, "consumeRecoveryReveal").mockReturnValueOnce(new Promise((resolve) => { release = resolve; }));251      const reading = dispatch({ type: "GET_RECOVERY_WORDS" });252      await vi.waitFor(() => expect(consume).toHaveBeenCalled());253      await vault.lock();254      await vault.unlock("test-pass-12345");255      release(true);256      expect(await reading).toMatchObject({ ok: false, error: "vault_locked" });257    });258259    it("discards words generated for an unlock session that ended", async () => {260      await setupUnlockedVault();261      const vault = await import("./vault");262      const pending = await import("./recovery-pending");263      await pending.setRecoveryConfirmPending();264      let release!: (value: string[]) => void;265      const words = vi.spyOn(vault, "getRecoveryWords").mockReturnValueOnce(new Promise((resolve) => { release = resolve; }));266      const reading = dispatch({ type: "GET_RECOVERY_WORDS" });267      await vi.waitFor(() => expect(words).toHaveBeenCalled());268      await vault.lock();269      await vault.unlock("test-pass-12345");270      release(WORD_LIST.slice(0, 12));271      expect(await reading).toMatchObject({ ok: false, error: "vault_locked" });272    });273274    it("reports committed creation when grant storage fails and requires proof", async () => {275      vi.mocked(chrome.storage.session.set).mockRejectedValue(new Error("session unavailable"));276      expect(await dispatch({ type: "CREATE_VAULT", payload: { password: "test-pass-12345", purpose: "onboarding" } })).toMatchObject({ ok: true, data: { committed: true } });277      expect(await dispatch({ type: "GET_RECOVERY_WORDS" })).toMatchObject({ ok: false, error: "password_required" });278      expect(await dispatch({ type: "GET_RECOVERY_CONFIRM_PENDING" })).toMatchObject({ data: true });279    });280281    it.each(["password", "key"])("lock cancels %s unlock while recovery revocation waits", async (kind) => {282      await setupUnlockedVault();283      const vault = await import("./vault");284      const key = vault.getDerivedKeyHex();285      await vault.lock();286      const pending = await import("./recovery-pending");287      await pending.setRecoveryConfirmPending();288      let release!: () => void;289      const blocked = new Promise<void>((resolve) => { release = resolve; });290      const set = vi.mocked(chrome.storage.session.set);291      set.mockClear();292      set.mockImplementationOnce(async () => { await blocked; });293      const unlocking = kind === "password" ? vault.unlock("test-pass-12345") : vault.unlockWithKey(key);294      await vi.waitFor(() => expect(set).toHaveBeenCalled());295      const locking = vault.lock();296      release();297      await Promise.all([unlocking, locking]);298      expect(vault.isUnlocked()).toBe(false);299    });300301    it("rejects password proof from a session that was locked and reopened", async () => {302      await setupUnlockedVault();303      const vault = await import("./vault");304      let release!: (value: boolean) => void;305      const proof = new Promise<boolean>((resolve) => { release = resolve; });306      const verify = vi.spyOn(vault, "verifyMainPassword").mockReturnValueOnce(proof);307      const reading = dispatch({ type: "GET_RECOVERY_WORDS", payload: { password: "test-pass-12345" } });308      await vi.waitFor(() => expect(verify).toHaveBeenCalled());309      await vault.lock();310      await vault.unlock("test-pass-12345");311      release(true);312      expect(await reading).toMatchObject({ ok: false, error: "vault_locked" });313    });314  });315316  describe('VALIDATE_RECOVERY_WORDS handler', () => {317    beforeEach(async () => { await setupUnlockedVault(); });318319    it('returns no invalid words for correct list', async () => {320      const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });321      const words = (r as { data: string[] }).data;322      const result = await dispatch({323        type: 'VALIDATE_RECOVERY_WORDS',324        payload: { words },325      });326      const data = (result as { data: { invalid: Array<{ index: number; word: string }> } }).data;327      expect(data.invalid).toEqual([]);328    });329330    it('returns invalid words for unknown words', async () => {331      const result = await dispatch({332        type: 'VALIDATE_RECOVERY_WORDS',333        payload: { words: ['notaword', 'alsonotaword'] },334      });335      const data = (result as { data: { invalid: Array<{ index: number; word: string }> } }).data;336      const invalidWords = data.invalid.map((x) => x.word);337      expect(invalidWords).toContain('notaword');338      expect(invalidWords).toContain('alsonotaword');339    });340341    it('is case-insensitive for validation', async () => {342      const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });343      const words = (r as { data: string[] }).data;344      const uppercased = words.map((w: string) => w.toUpperCase());345      const result = await dispatch({346        type: 'VALIDATE_RECOVERY_WORDS',347        payload: { words: uppercased },348      });349      const data = (result as { data: { invalid: Array<{ index: number; word: string }> } }).data;350      expect(data.invalid).toEqual([]);351    });352  });353354  describe('RECOVER_WITH_WORDS handler', () => {355    it('reports a committed password change when identity maintenance fails', async () => {356      const vault = await import('./vault');357      await setupUnlockedVault();358      await vault.addEntry({ type: 'note', title: 'Retained after hook failure', notes: 'saved' });359      const words = await vault.getRecoveryWords();360      vault.setIdentityHooks({ onSessionEnded: async () => {}, onVaultCreated: async () => {},361        onKeysRotated: async () => { throw new Error('identity storage unavailable'); } });362      await vault.lock();363      const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });364      const oldPasswordWorks = await vault.verifyMainPassword('test-pass-12345');365      const newPasswordWorks = await vault.verifyMainPassword('recovered-password');366      expect(oldPasswordWorks).toBe(false);367      expect(newPasswordWorks).toBe(true);368      expect(result).toMatchObject({ ok: true, data: { committed: true, unlocked: false } });369      expect(vault.isUnlocked()).toBe(false);370      expect(vi.mocked(chrome.tabs.sendMessage)).not.toHaveBeenCalledWith(expect.anything(), { type: 'VAULT_UNLOCKED' });371      expect(await vault.unlock('recovered-password')).toBe(true);372      expect(vault.getEntries()[0]?.notes).toBe('saved');373    });374375    it.each(['session', 'pair-secrets', 'PIN', 'auto-lock'] as const)('reports saved password and requires unlock after %s maintenance fails', async (maintenance) => {376      const vault = await import('./vault');377      await setupUnlockedVault();378      const words = await vault.getRecoveryWords();379      await vault.lock();380      if (maintenance === 'session') vi.mocked(chrome.storage.session.set).mockRejectedValueOnce(new Error('session unavailable'));381      if (maintenance === 'pair-secrets') {382        storage.peach_paired_devices_v3 = [{ deviceId: 'phone', pairedAt: Date.now(), rendezvousSecretHex: 'ab'.repeat(32) }];383        const set = vi.mocked(chrome.storage.local.set);384        const original = set.getMockImplementation()!;385        let failed = false;386        set.mockImplementation(async (...args) => {387          if (!failed && 'peach_pair_secrets_v1' in args[0]) { failed = true; throw new Error('pair store unavailable'); }388          return original(...args);389        });390      }391      if (maintenance === 'PIN') {392        const remove = vi.mocked(chrome.storage.session.remove);393        const original = remove.getMockImplementation()!;394        remove.mockImplementation(async (...args) => {395          if (Array.isArray(args[0])) throw new Error('PIN store unavailable');396          return original(...args);397        });398      }399      if (maintenance === 'auto-lock') vi.mocked(chrome.idle.setDetectionInterval).mockImplementationOnce(() => { throw new Error('idle API unavailable'); });400      const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });401      expect(result).toMatchObject({ ok: true, data: { committed: true, unlocked: false } });402      expect(vault.isUnlocked()).toBe(false);403      expect(vault.getRootKeyHex()).toBeNull();404      expect(sessionStorage.peach_session_dk).toBeUndefined();405      expect(await vault.verifyMainPassword('test-pass-12345')).toBe(false);406      expect(await vault.unlock('recovered-password')).toBe(true);407    });408    it('preserves existing entries and the decoy slot during locked recovery', async () => {409      const vault = await import('./vault');410      await setupUnlockedVault();411      await vault.addEntry({ type: 'login', title: 'Existing account', password: 'keep-me' });412      const removed = await vault.addEntry({ type: 'note', title: 'Purged note', notes: 'deleted' });413      await vault.deleteEntry(removed.id);414      await vault.purgeEntry(removed.id);415      await vault.setupDuress('decoy-password');416      const before = vault.getEntries();417      const tombstones = vault.getTombstoneManifest();418      const root = vault.getRootKeyHex();419      const words = await vault.getRecoveryWords();420      const slotA = JSON.stringify(storage.peach_vault_a);421      const slotB = JSON.stringify(storage.peach_vault_b);422      await vault.lock();423      const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });424      expect(result.ok).toBe(true);425      expect(vault.getEntries()).toEqual(before);426      expect(vault.getTombstoneManifest()).toEqual(tombstones);427      expect(vault.getRootKeyHex()).toBe(root);428      expect(JSON.stringify(storage.peach_vault_b)).toBe(slotB);429      const history = storage.peach_vault_history as { snapshots: Array<{ vault_a: string; vault_b: string }> };430      expect(history.snapshots[0]).toMatchObject({ vault_a: slotA, vault_b: slotB });431      await vault.lock();432      expect(await vault.unlock('recovered-password')).toBe(true);433      expect(vault.getEntries()).toEqual(before);434      expect(vault.getTombstoneManifest()).toEqual(tombstones);435      await vault.lock();436      expect(await vault.unlock('decoy-password')).toBe(true);437      expect(vault.isDecoyMode()).toBe(true);438    });439440    it.each(['created', 'adopted', 'password-changed', 'root-rotated'] as const)('recovers a %s vault after a cold worker restart', async (kind) => {441      let vault = await import('./vault');442      if (kind === 'adopted') await vault.createVaultFromRootKey('test-pass-12345', '42'.repeat(32));443      else await setupUnlockedVault();444      await vault.addEntry({ type: 'note', title: 'Before restart', notes: 'retained' });445      if (kind === 'password-changed') expect(await vault.changePassword('test-pass-12345', 'changed-password')).toBe(true);446      if (kind === 'root-rotated') expect((await vault.rotateSyncIdentity()).ok).toBe(true);447      const words = await vault.getRecoveryWords();448      const root = vault.getRootKeyHex();449      await vault.lock();450      vi.resetModules();451      vault = await import('./vault');452      await vault.recoverWithWords(words, 'cold-recovery-password');453      expect(vault.getEntries()[0]?.notes).toBe('retained');454      expect(vault.getRootKeyHex()).toBe(root);455      await vault.lock();456      expect(await vault.unlock('cold-recovery-password')).toBe(true);457      expect(vault.getEntries()[0]?.notes).toBe('retained');458    });459460    it.each(['aad', 'payload'] as const)('refuses mismatched %s authentication without writes', async (kind) => {461      const vault = await import('./vault');462      await setupUnlockedVault();463      const words = await vault.getRecoveryWords();464      const slot = rawSlotA();465      if (kind === 'aad') {466        const { encrypt } = await import('./aes');467        const root = Uint8Array.from(vault.getRootKeyHex()!.match(/../g)!, (byte) => Number.parseInt(byte, 16));468        slot.recovery_vault_key = await encrypt(root, vault.getDerivedKeyHex(), 'pw_root_v1');469      } else slot.tag = '00'.repeat(16);470      await vault.lock();471      const before = JSON.stringify(storage);472      expect((await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } })).ok).toBe(false);473      expect(JSON.stringify(storage)).toBe(before);474      expect(vault.getRootKeyHex()).toBeNull();475    });476477    it.each(['missing', 'corrupt', 'stale'] as const)('refuses %s escrow unchanged and repairs it through real password unlock', async (kind) => {478      const vault = await import('./vault');479      await setupUnlockedVault();480      await vault.addEntry({ type: 'note', title: 'Keep this note', notes: 'original' });481      const words = await vault.getRecoveryWords();482      const slot = rawSlotA();483      if (kind === 'missing') delete slot.recovery_vault_key;484      if (kind === 'corrupt') slot.recovery_vault_key = { nonce: '00', ciphertext: '00', tag: '00' };485      if (kind === 'stale') {486        const { encrypt } = await import('./aes');487        const root = Uint8Array.from(vault.getRootKeyHex()!.match(/../g)!, (byte) => Number.parseInt(byte, 16));488        slot.recovery_vault_key = await encrypt(root, '00'.repeat(32), 'recovery_vault_key_v1');489      }490      await vault.lock();491      const before = JSON.stringify(storage);492      const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });493      expect(result.ok).toBe(false);494      expect(JSON.stringify(storage)).toBe(before);495      expect(vault.getRootKeyHex()).toBeNull();496      expect(vault.isUnlocked()).toBe(false);497      expect(await vault.unlock('test-pass-12345')).toBe(true);498      await vault.lock();499      expect((await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } })).ok).toBe(true);500      expect(vault.getEntries()[0]?.notes).toBe('original');501    });502503    it('refuses unlocked real and decoy recovery without changing storage', async () => {504      const vault = await import('./vault');505      await setupUnlockedVault();506      const words = await vault.getRecoveryWords();507      await vault.setupDuress('decoy-password');508      for (const decoy of [false, true]) {509        if (decoy) { await vault.lock(); await vault.unlock('decoy-password'); }510        const before = JSON.stringify(storage);511        const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });512        expect(result.ok).toBe(false);513        expect(JSON.stringify(storage)).toBe(before);514        expect(vault.isDecoyMode()).toBe(decoy);515      }516    });517518    it('keeps original slots and stays locked when the recovery transaction fails', 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      vi.mocked(chrome.storage.local.set).mockRejectedValueOnce(new Error('storage unavailable'));525      expect((await dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } })).ok).toBe(false);526      expect(JSON.stringify(storage)).toBe(before);527      expect(vault.isUnlocked()).toBe(false);528      expect(vault.getRootKeyHex()).toBeNull();529      expect(await vault.unlock('test-pass-12345')).toBe(true);530    });531532    it('cancels recovery on manual lock and refuses concurrent unlock', async () => {533      const vault = await import('./vault');534      await setupUnlockedVault();535      const words = await vault.getRecoveryWords();536      await vault.lock();537      const before = JSON.stringify(storage);538      const get = vi.mocked(chrome.storage.local.get);539      const original = get.getMockImplementation()!;540      let release!: () => void;541      let started!: () => void;542      const paused = new Promise<void>((resolve) => { release = resolve; });543      const ready = new Promise<void>((resolve) => { started = resolve; });544      get.mockImplementationOnce(async (...args) => { started(); await paused; return original(...args); });545      const recovering = dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });546      await ready;547      expect(await vault.unlock('test-pass-12345')).toBe(false);548      await vault.lock();549      release();550      expect((await recovering).ok).toBe(false);551      expect(JSON.stringify(storage)).toBe(before);552      expect(vault.getRootKeyHex()).toBeNull();553      expect(vault.isUnlocked()).toBe(false);554    });555556    it('keeps a cancelled in-flight commit consistent and does not unlock', async () => {557      const vault = await import('./vault');558      await setupUnlockedVault();559      await vault.addEntry({ type: 'note', title: 'Retain on cancellation', notes: 'saved' });560      const words = await vault.getRecoveryWords();561      await vault.lock();562      const before = JSON.stringify(storage.peach_vault_a);563      let release!: () => void;564      let started!: () => void;565      const paused = new Promise<void>((resolve) => { release = resolve; });566      const ready = new Promise<void>((resolve) => { started = resolve; });567      const set = vi.mocked(chrome.storage.local.set);568      const original = set.getMockImplementation()!;569      set.mockImplementationOnce(async (...args) => {570        expect(Object.keys(args[0]).sort()).toEqual(['peach_last_modified_at', 'peach_vault_a', 'peach_vault_history']);571        started(); await paused; return original(...args);572      });573      const recovering = dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });574      await ready;575      await vault.lock();576      release();577      expect(await recovering).toMatchObject({ ok: true, data: { committed: true, unlocked: false } });578      expect(vault.isUnlocked()).toBe(false);579      expect(vault.getRootKeyHex()).toBeNull();580      const history = storage.peach_vault_history as { snapshots: Array<{ vault_a: string }> };581      expect(history.snapshots[0]?.vault_a).toBe(before);582      expect(await vault.unlock('recovered-password')).toBe(true);583      expect(vault.getEntries()[0]?.notes).toBe('saved');584    });585586    it('does not enroll legacy escrow through a pre-derived key, session restore, or decoy unlock', async () => {587      let vault = await import('./vault');588      await setupUnlockedVault();589      await vault.setupDuress('decoy-password');590      const key = vault.getDerivedKeyHex();591      delete rawSlotA().recovery_vault_key;592      await vault.lock();593      expect((await vault.unlockWithKey(key)).ok).toBe(true);594      expect(rawSlotA().recovery_vault_key).toBeUndefined();595      vi.resetModules();596      vault = await import('./vault');597      expect(await vault.restoreFromSession()).toBe(true);598      expect(rawSlotA().recovery_vault_key).toBeUndefined();599      await vault.lock();600      expect(await vault.unlock('decoy-password')).toBe(true);601      expect(rawSlotA().recovery_vault_key).toBeUndefined();602      await vault.lock();603      expect(await vault.unlock('test-pass-12345')).toBe(true);604      expect(rawSlotA().recovery_vault_key).toBeDefined();605    });606607    it('preserves the local identity and paired reconnect secret', async () => {608      const vault = await import('./vault');609      const pairs = await import('./pair-secrets');610      const devices = await import('./paired-devices');611      await setupUnlockedVault();612      const rootHex = vault.getRootKeyHex()!;613      const root = Uint8Array.from(rootHex.match(/../g)!, (byte) => Number.parseInt(byte, 16));614      await devices.upsertPairedDevice({ deviceId: 'paired-phone', deviceName: 'Phone', deviceType: 'android', longTermPublicKeyHex: '43'.repeat(32), pairedAt: Date.now() });615      await pairs.setPairSecret('paired-phone', 'ab'.repeat(32), root);616      const identityKey = new Uint8Array(32).fill(7);617      let identity = await vault.sealIdentityKeyUnderVault(identityKey);618      vault.setIdentityHooks({619        onSessionEnded: async () => {},620        onVaultCreated: async () => {},621        onKeysRotated: async () => {622          const opened = await vault.openIdentityKey(identity);623          expect(opened).toEqual(identityKey);624          identity = await vault.sealIdentityKeyUnderVault(opened!);625        },626      });627      const words = await vault.getRecoveryWords();628      await vault.lock();629      await vault.recoverWithWords(words, 'recovered-password');630      expect(await vault.openIdentityKey(identity)).toEqual(identityKey);631      expect(await pairs.getPairSecret('paired-phone', vault.getRootKeyHex())).toBe('ab'.repeat(32));632      await vault.lock();633      expect(await vault.unlock('recovered-password')).toBe(true);634      expect(await vault.openIdentityKey(identity)).toEqual(identityKey);635      expect(await pairs.getPairSecret('paired-phone', vault.getRootKeyHex())).toBe('ab'.repeat(32));636    });637638    it('refuses recovery while a Codex replacement is staged', async () => {639      const vault = await import('./vault');640      await setupUnlockedVault();641      const words = await vault.getRecoveryWords();642      const slotA = JSON.stringify(storage.peach_vault_a);643      const slotB = JSON.stringify(storage.peach_vault_b);644      await vault.lock();645      const importing = vault.unlockFromCodex({ slotA, slotB, timestamp: Date.now(), masterPassphrase: 'test-pass-12345' });646      await expect(vault.recoverWithWords(words, 'recovered-password')).rejects.toThrow('vault_changed');647      expect((await importing).ok).toBe(true);648      expect(await vault.verifyMainPassword('test-pass-12345')).toBe(true);649    });650651    it('refuses recovery while an earlier creation derives its password', async () => {652      const vault = await import('./vault');653      const argon = await import('../crypto/argon2');654      await setupUnlockedVault();655      await vault.addEntry({ type: 'note', title: 'Keep recovered data', notes: 'original' });656      const words = await vault.getRecoveryWords();657      await vault.lock();658      let release!: () => void;659      const paused = new Promise<void>((resolve) => { release = resolve; });660      const derive = argon.deriveKey;661      const spy = vi.spyOn(argon, 'deriveKey').mockImplementationOnce(async (...args) => {662        const key = await derive(...args); await paused; return key;663      });664      const creating = vault.createVault('concurrent-creation-password', 'warned-import').then(() => 'created', (error: Error) => error.message);665      const recovering = await vault.recoverWithWords(words, 'recovered-password').then(() => 'recovered', (error: Error) => error.message);666      const before = JSON.stringify(storage);667      await vault.lock();668      release();669      expect(await creating).toBe('vault_changed');670      spy.mockRestore();671      expect(recovering).toBe('vault_changed');672      expect(JSON.stringify(storage)).toBe(before);673      expect(vault.getRootKeyHex()).toBeNull();674    });675676    it('refuses recovery while creation is paused after its password derivation', async () => {677      const vault = await import('./vault');678      await setupUnlockedVault();679      const words = await vault.getRecoveryWords();680      await vault.lock();681      const before = JSON.stringify(storage);682      const encrypt = crypto.subtle.encrypt.bind(crypto.subtle);683      let release!: () => void;684      let started!: () => void;685      const paused = new Promise<void>((resolve) => { release = resolve; });686      const ready = new Promise<void>((resolve) => { started = resolve; });687      const spy = vi.spyOn(crypto.subtle, 'encrypt').mockImplementationOnce(async (...args) => {688        const value = await encrypt(...args); started(); await paused; return value;689      });690      const creating = vault.createVault('concurrent-creation-password', 'warned-import').then(() => 'created', (error: Error) => error.message);691      await ready;692      await vault.lock();693      const recovering = await vault.recoverWithWords(words, 'recovered-password').then(() => 'recovered', (error: Error) => error.message);694      release();695      const created = await creating;696      spy.mockRestore();697      expect(recovering).toBe('vault_changed');698      expect(created).toBe('vault_changed');699      expect(JSON.stringify(storage)).toBe(before);700      expect(vault.getRootKeyHex()).toBeNull();701    });702703    it.each([null, undefined, 42, 'words'])('rejects malformed recovery payload %s explicitly', async (payload) => {704      const result = await dispatch({ type: 'RECOVER_WITH_WORDS', payload } as unknown as Message);705      expect(result).toMatchObject({ ok: false, error: 'invalid_recovery_payload' });706    });707708    it.each(['panic', 'adoption-rollback'] as const)('orders %s after a previously issued recovery write', async (kind) => {709      const vault = await import('./vault');710      await setupUnlockedVault();711      const words = await vault.getRecoveryWords();712      await vault.lock();713      const set = vi.mocked(chrome.storage.local.set);714      const original = set.getMockImplementation()!;715      let release!: () => void;716      let started!: () => void;717      const paused = new Promise<void>((resolve) => { release = resolve; });718      const ready = new Promise<void>((resolve) => { started = resolve; });719      set.mockImplementationOnce(async (...args) => { started(); await paused; return original(...args); });720      const recovering = dispatch({ type: 'RECOVER_WITH_WORDS', payload: { words, newPassword: 'recovered-password' } });721      await ready;722      let removed = false;723      const removing = (kind === 'panic'724        ? dispatch({ type: 'DESTROY_VAULT' })725        : vault.rollbackAdoptedVault().then(() => ({ ok: true }), () => ({ ok: false }))).then((result) => { removed = true; return result; });726      await new Promise((resolve) => setTimeout(resolve, 0));727      const removedBeforeRecoverySettled = removed;728      release();729      const recoveryResult = await recovering;730      const removalResult = await removing;731      expect(storage.peach_vault_a).toBeUndefined();732      expect(storage.peach_vault_b).toBeUndefined();733      expect(removedBeforeRecoverySettled).toBe(false);734      expect(recoveryResult).toMatchObject({ ok: true, data: { committed: true, unlocked: false } });735      expect(removalResult.ok).toBe(true);736      expect(vault.isUnlocked()).toBe(false);737      if (kind === 'panic') {738        const history = storage.peach_vault_history as { snapshots: unknown[] };739        expect(history.snapshots).toEqual([]);740      }741    });742743    it('recovery succeeds with correct words and new passphrase', async () => {744      await setupUnlockedVault();745      const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });746      const words = (r as { data: string[] }).data;747      await lockVault();748749      const result = await dispatch({750        type: 'RECOVER_WITH_WORDS',751        payload: { words, newPassword: 'new-passphrase' },752      });753      expect(result.ok).toBe(true);754      const unlocked = await dispatch({ type: 'IS_UNLOCKED' });755      expect((unlocked as { data: boolean }).data).toBe(true);756    });757758    it('fails with wrong recovery words', async () => {759      await setupUnlockedVault();760      await lockVault();761      const fakeWords = Array(12).fill('abandon');762      const result = await dispatch({763        type: 'RECOVER_WITH_WORDS',764        payload: { words: fakeWords, newPassword: 'new-pass' },765      });766      expect(result.ok).toBe(false);767      expect((result as { error: string }).error).toMatch(/invalid/);768    });769770    it('fails with partial word list (fewer than 12)', async () => {771      await setupUnlockedVault();772      const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });773      const words = (r as { data: string[] }).data;774      await lockVault();775      const partial = words.slice(0, 6);776      const result = await dispatch({777        type: 'RECOVER_WITH_WORDS',778        payload: { words: partial, newPassword: 'new-pass' },779      });780      expect(result.ok).toBe(false);781    });782783    it('new passphrase works after recovery', async () => {784      await setupUnlockedVault();785      const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });786      const words = (r as { data: string[] }).data;787      await lockVault();788      await dispatch({789        type: 'RECOVER_WITH_WORDS',790        payload: { words, newPassword: 'brand-new-password' },791      });792      await lockVault();793      const unlock = await dispatch({794        type: 'UNLOCK',795        payload: { password: 'brand-new-password' },796      });797      expect(unlock.ok).toBe(true);798    });799800    it('old passphrase does not work after recovery', async () => {801      await setupUnlockedVault();802      const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });803      const words = (r as { data: string[] }).data;804      await lockVault();805      await dispatch({806        type: 'RECOVER_WITH_WORDS',807        payload: { words, newPassword: 'brand-new-password' },808      });809      await lockVault();810      const unlock = await dispatch({811        type: 'UNLOCK',812        payload: { password: 'test-pass-12345' },813      });814      expect(unlock.ok).toBe(false);815    });816817    it('preserves recovery escrow fields after recovery password rewrap', async () => {818      await setupUnlockedVault();819      const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });820      const words = (r as { data: string[] }).data;821      const before = { ...rawSlotA() };822      await lockVault();823824      const result = await dispatch({825        type: 'RECOVER_WITH_WORDS',826        payload: { words, newPassword: 'new-passphrase' },827      });828      expect(result.ok).toBe(true);829830      const after = rawSlotA();831      expect(after.recovery_wrapped_root_key).toBe(before.recovery_wrapped_root_key);832      expect(after.recovery_nonce).toBe(before.recovery_nonce);833      expect(after.recovery_tag).toBe(before.recovery_tag);834      expect(after.recovery_salt).toBe(before.recovery_salt);835      expect(after.ciphertext).not.toBe(before.ciphertext);836      expect(after.salt).not.toBe(before.salt);837    });838839    it('same recovery words succeed on a second recovery', async () => {840      await setupUnlockedVault();841      const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });842      const words = (r as { data: string[] }).data;843844      await lockVault();845      const first = await dispatch({846        type: 'RECOVER_WITH_WORDS',847        payload: { words, newPassword: 'pass-1' },848      });849      expect(first.ok).toBe(true);850851      await lockVault();852      const second = await dispatch({853        type: 'RECOVER_WITH_WORDS',854        payload: { words, newPassword: 'pass-2' },855      });856      expect(second.ok).toBe(true);857858      await lockVault();859      const unlock = await dispatch({860        type: 'UNLOCK',861        payload: { password: 'pass-2' },862      });863      expect(unlock.ok).toBe(true);864    });865866    it('same recovery words succeed on a third recovery', async () => {867      await setupUnlockedVault();868      const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });869      const words = (r as { data: string[] }).data;870871      for (let i = 0; i < 3; i += 1) {872        await lockVault();873        const result = await dispatch({874          type: 'RECOVER_WITH_WORDS',875          payload: { words, newPassword: `pass-${i}` },876        });877        expect(result.ok).toBe(true);878      }879    });880881    it('vault remains usable after recovery', async () => {882      await setupUnlockedVault();883      const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });884      const words = (r as { data: string[] }).data;885886      await lockVault();887      const recovered = await dispatch({888        type: 'RECOVER_WITH_WORDS',889        payload: { words, newPassword: 'new-passphrase' },890      });891      expect(recovered.ok).toBe(true);892893      await dispatch({894        type: 'ADD_ENTRY',895        payload: { title: 'Check me', username: '', password: 'p', url: '' },896      });897      const entries = (await dispatch({ type: 'GET_ENTRIES' }) as { data: Array<{ title: string }> }).data;898      expect(entries.some((entry) => entry.title === 'Check me')).toBe(true);899    });900901    // H4/COR-002: changePassword MUST preserve the root key so the user's902    // existing recovery words continue to work. Rotating the root key on903    // every password change would silently brick recovery.904    it('recovery words are preserved across CHANGE_PASSWORD', async () => {905      await setupUnlockedVault();906      const before = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data;907      await dispatch({908        type: 'CHANGE_PASSWORD',909        payload: { currentPassword: 'test-pass-12345', newPassword: 'new-pass-67890' },910      });911      const after = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'new-pass-67890' } }) as { data: string[] }).data;912      expect(after).toEqual(before);913    });914915    it('recovery is not Pro-gated', async () => {916      await setupUnlockedVault();917      await mockNoPro();918      const r = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });919      const words = (r as { data: string[] }).data;920      await lockVault();921      const result = await dispatch({922        type: 'RECOVER_WITH_WORDS',923        payload: { words, newPassword: 'new-pass' },924      });925      expect((result as { error?: string }).error ?? '').not.toMatch(/pro_required/);926    });927  });928929  // H4/COR-002 — changePassword must re-wrap the existing root key, not mint930  // a new one. The recovery words derived from rootKey must remain valid931  // after any password change.932  describe('changePassword preserves root key and recovery words', () => {933    it('recovery words work to unlock after password change', async () => {934      await setupUnlockedVault();935      const words = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data;936      const ch = await dispatch({937        type: 'CHANGE_PASSWORD',938        payload: { currentPassword: 'test-pass-12345', newPassword: 'new-pass-aaa' },939      });940      expect(ch.ok).toBe(true);941      await lockVault();942      const r = await dispatch({943        type: 'RECOVER_WITH_WORDS',944        payload: { words, newPassword: 'recovered-pass' },945      });946      expect(r.ok).toBe(true);947    });948949    it('recovery words are identical before and after password change', async () => {950      await setupUnlockedVault();951      const before = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data;952      await dispatch({953        type: 'CHANGE_PASSWORD',954        payload: { currentPassword: 'test-pass-12345', newPassword: 'another-pass-bbb' },955      });956      const after = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'another-pass-bbb' } }) as { data: string[] }).data;957      expect(after).toEqual(before);958    });959960    it('vault unlocks with the new password after change', async () => {961      await setupUnlockedVault();962      await dispatch({963        type: 'CHANGE_PASSWORD',964        payload: { currentPassword: 'test-pass-12345', newPassword: 'brand-new-pass' },965      });966      await lockVault();967      const r = await dispatch({968        type: 'UNLOCK',969        payload: { password: 'brand-new-pass' },970      });971      expect(r.ok).toBe(true);972    });973974    it('the old password no longer unlocks after change', async () => {975      await setupUnlockedVault();976      await dispatch({977        type: 'CHANGE_PASSWORD',978        payload: { currentPassword: 'test-pass-12345', newPassword: 'brand-new-pass' },979      });980      await lockVault();981      const r = await dispatch({982        type: 'UNLOCK',983        payload: { password: 'test-pass-12345' },984      });985      expect(r.ok).toBe(false);986    });987988    it('GET_RECOVERY_WORDS still works after a password change + lock + unlock', async () => {989      await setupUnlockedVault();990      const before = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data;991      await dispatch({992        type: 'CHANGE_PASSWORD',993        payload: { currentPassword: 'test-pass-12345', newPassword: 'pass-after-cycle' },994      });995      await lockVault();996      await dispatch({997        type: 'UNLOCK',998        payload: { password: 'pass-after-cycle' },999      });1000      const after = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'pass-after-cycle' } }) as { data: string[] }).data;1001      expect(after).toEqual(before);1002    });1003  });10041005  // H2/COR-006/SEC-006/CRYPTO-11 — rootKey must survive lock/unlock cycles1006  // so the user's 12 recovery words are stable across sessions. The fix is1007  // a pw_root_* second wrapping under the password-derived key.1008  describe('deriveRootKeyFromDerivedKey and recovery persistence', () => {1009    it('GET_RECOVERY_WORDS works after lock and re-unlock', async () => {1010      await setupUnlockedVault();1011      const r1 = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });1012      const words1 = (r1 as { data: string[] }).data;1013      expect(words1).toHaveLength(12);1014      await lockVault();1015      const unlocked = await dispatch({1016        type: 'UNLOCK',1017        payload: { password: 'test-pass-12345' },1018      });1019      expect(unlocked.ok).toBe(true);1020      const r2 = await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } });1021      const words2 = (r2 as { data: string[] }).data;1022      expect(words2).toEqual(words1);1023    });10241025    it('GET_RECOVERY_WORDS works after multiple lock/unlock cycles', async () => {1026      await setupUnlockedVault();1027      const original = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data;1028      for (let i = 0; i < 5; i++) {1029        await lockVault();1030        await dispatch({1031          type: 'UNLOCK',1032          payload: { password: 'test-pass-12345' },1033        });1034      }1035      const after = (await dispatch({ type: 'GET_RECOVERY_WORDS', payload: { password: 'test-pass-12345' } }) as { data: string[] }).data;1036      expect(after).toEqual(original);1037    });10381039  });1040});