Files
pn-new-crm/tests/unit/encryption.test.ts
Matt 67d7e6e3d5
Some checks failed
Build & Push Docker Images / build-and-push (push) Has been cancelled
Build & Push Docker Images / deploy (push) Has been cancelled
Build & Push Docker Images / lint (push) Has been cancelled
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00

74 lines
2.3 KiB
TypeScript

import { describe, it, expect, beforeAll } from 'vitest';
import { encrypt, decrypt } from '@/lib/utils/encryption';
const VALID_KEY = 'a'.repeat(64); // 64 hex chars = 32 bytes
beforeAll(() => {
process.env.EMAIL_CREDENTIAL_KEY = VALID_KEY;
});
describe('encrypt / decrypt', () => {
it('round-trips plaintext correctly', () => {
const plaintext = 'super secret password';
expect(decrypt(encrypt(plaintext))).toBe(plaintext);
});
it('different plaintexts produce different ciphertexts', () => {
const a = encrypt('hello');
const b = encrypt('world');
expect(a).not.toBe(b);
});
it('same plaintext produces different ciphertext on each call (random IV)', () => {
const a = encrypt('hello');
const b = encrypt('hello');
expect(a).not.toBe(b);
});
it('tampered data field throws on decrypt', () => {
const stored = JSON.parse(encrypt('tamper me'));
// Flip the first hex byte of data
const originalByte = stored.data.slice(0, 2);
const flipped = originalByte === 'ff' ? '00' : 'ff';
stored.data = flipped + stored.data.slice(2);
expect(() => decrypt(JSON.stringify(stored))).toThrow();
});
it('tampered auth tag throws on decrypt', () => {
const stored = JSON.parse(encrypt('tamper tag'));
const originalByte = stored.tag.slice(0, 2);
const flipped = originalByte === 'ff' ? '00' : 'ff';
stored.tag = flipped + stored.tag.slice(2);
expect(() => decrypt(JSON.stringify(stored))).toThrow();
});
it('round-trips an empty string', () => {
expect(decrypt(encrypt(''))).toBe('');
});
it('round-trips unicode text', () => {
const unicode = '日本語テスト 🚢 αβγ';
expect(decrypt(encrypt(unicode))).toBe(unicode);
});
it('throws when EMAIL_CREDENTIAL_KEY is missing', () => {
const savedKey = process.env.EMAIL_CREDENTIAL_KEY;
delete process.env.EMAIL_CREDENTIAL_KEY;
expect(() => encrypt('test')).toThrow('EMAIL_CREDENTIAL_KEY');
process.env.EMAIL_CREDENTIAL_KEY = savedKey;
});
it('throws when EMAIL_CREDENTIAL_KEY is wrong length', () => {
const savedKey = process.env.EMAIL_CREDENTIAL_KEY;
process.env.EMAIL_CREDENTIAL_KEY = 'tooshort';
expect(() => encrypt('test')).toThrow('EMAIL_CREDENTIAL_KEY');
process.env.EMAIL_CREDENTIAL_KEY = savedKey;
});
});