import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' import { clear, load, save } from './restoreVerificationKeyCache' const STORAGE_KEY = 'pdsmoover:restore-verification-key:v1' const DID = 'did:plc:alice' const OTHER_DID = 'did:plc:bob' const PRIVATE_KEY = 'z3u2Yy8jVqExamplePrivateKey' const PUBLIC_KEY = 'did:key:zQ3shExamplePublicKey' class MemoryStorage { #store = new Map() getItem(key: string): string | null { return this.#store.get(key) ?? null } setItem(key: string, value: string): void { this.#store.set(key, value) } removeItem(key: string): void { this.#store.delete(key) } } describe('restoreVerificationKeyCache', () => { let storage: MemoryStorage beforeAll(() => { storage = new MemoryStorage() vi.stubGlobal('localStorage', storage) }) afterAll(() => { vi.unstubAllGlobals() }) it('round-trips a saved key for its own DID', () => { save(DID, PRIVATE_KEY, PUBLIC_KEY) const loaded = load(DID) expect(loaded).not.toBeNull() expect(loaded?.did).toBe(DID) expect(loaded?.privateKey).toBe(PRIVATE_KEY) expect(loaded?.publicKey).toBe(PUBLIC_KEY) expect(typeof loaded?.savedAt).toBe('number') }) it('ignores a saved key belonging to a different DID', () => { save(DID, PRIVATE_KEY, PUBLIC_KEY) expect(load(OTHER_DID)).toBeNull() }) it('replaces the previous entry when saving for another DID', () => { save(DID, PRIVATE_KEY, PUBLIC_KEY) save(OTHER_DID, PRIVATE_KEY, PUBLIC_KEY) expect(load(DID)).toBeNull() expect(load(OTHER_DID)?.did).toBe(OTHER_DID) }) it('clears the saved key', () => { save(DID, PRIVATE_KEY, PUBLIC_KEY) clear() expect(load(DID)).toBeNull() expect(storage.getItem(STORAGE_KEY)).toBeNull() }) it('drops a corrupt entry', () => { storage.setItem(STORAGE_KEY, 'not json') expect(load(DID)).toBeNull() expect(storage.getItem(STORAGE_KEY)).toBeNull() }) it('drops an entry with an unexpected shape', () => { storage.setItem(STORAGE_KEY, JSON.stringify({ did: DID, publicKey: PUBLIC_KEY })) expect(load(DID)).toBeNull() expect(storage.getItem(STORAGE_KEY)).toBeNull() }) it('drops an entry whose private key is not a multikey', () => { storage.setItem( STORAGE_KEY, JSON.stringify({ did: DID, privateKey: 'not-a-multikey', publicKey: PUBLIC_KEY }), ) expect(load(DID)).toBeNull() expect(storage.getItem(STORAGE_KEY)).toBeNull() }) })