import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { decryptApiKey, encryptApiKey, hashApiKey } from '@/lib/crypto'; const TEST_KEY = 'a'.repeat(32); describe('crypto', () => { const prev = process.env.MASTER_ENCRYPTION_KEY; beforeEach(() => { process.env.MASTER_ENCRYPTION_KEY = TEST_KEY; }); afterEach(() => { process.env.MASTER_ENCRYPTION_KEY = prev; }); it('round-trips encrypt and decrypt', async () => { const plain = 'sk-test-byok-key-12345'; const payload = await encryptApiKey(plain); expect(payload).not.toContain(plain); expect(await decryptApiKey(payload)).toBe(plain); }); it('hashApiKey is stable', () => { const h1 = hashApiKey('sk-abc'); const h2 = hashApiKey('sk-abc'); expect(h1).toBe(h2); expect(h1).not.toBe(hashApiKey('sk-xyz')); }); it('fails decrypt with wrong master key', async () => { const payload = await encryptApiKey('secret'); process.env.MASTER_ENCRYPTION_KEY = 'b'.repeat(32); await expect(decryptApiKey(payload)).rejects.toThrow(); }); });