- Remove ~60 unused imports and variables across 88 files - Replace ~80 `any` type annotations with proper types (unknown, Record<string, unknown>, or specific types) - Prefix unused callback args with underscore - Fix unescaped JSX entities - Lint now passes cleanly (0 errors, 2 intentional img warnings) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
54 lines
1.4 KiB
TypeScript
54 lines
1.4 KiB
TypeScript
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
|
|
|
const ALGORITHM = 'aes-256-gcm';
|
|
const IV_LENGTH = 12;
|
|
|
|
function getKey(): Buffer {
|
|
const hex = process.env.EMAIL_CREDENTIAL_KEY;
|
|
if (!hex || hex.length !== 64) {
|
|
throw new Error('EMAIL_CREDENTIAL_KEY must be a 64-character hex string');
|
|
}
|
|
return Buffer.from(hex, 'hex');
|
|
}
|
|
|
|
/**
|
|
* Encrypts plaintext using AES-256-GCM.
|
|
* Returns a JSON string containing hex-encoded iv, tag, and data.
|
|
*/
|
|
export function encrypt(plaintext: string): string {
|
|
const key = getKey();
|
|
const iv = randomBytes(IV_LENGTH);
|
|
const cipher = createCipheriv(ALGORITHM, key, iv);
|
|
|
|
let encrypted = cipher.update(plaintext, 'utf8', 'hex');
|
|
encrypted += cipher.final('hex');
|
|
const tag = cipher.getAuthTag();
|
|
|
|
return JSON.stringify({
|
|
iv: iv.toString('hex'),
|
|
tag: tag.toString('hex'),
|
|
data: encrypted,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Decrypts a stored encrypted value (JSON string with iv, tag, data).
|
|
* Returns the original plaintext.
|
|
*/
|
|
export function decrypt(stored: string): string {
|
|
const key = getKey();
|
|
const { iv, tag, data } = JSON.parse(stored) as {
|
|
iv: string;
|
|
tag: string;
|
|
data: string;
|
|
};
|
|
|
|
const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(iv, 'hex'));
|
|
decipher.setAuthTag(Buffer.from(tag, 'hex'));
|
|
|
|
let decrypted = decipher.update(data, 'hex', 'utf8');
|
|
decrypted += decipher.final('utf8');
|
|
|
|
return decrypted;
|
|
}
|