import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'; const ALGO = 'aes-256-gcm'; const IV_LEN = 12; const TAG_LEN = 16; function getMasterKey(): Buffer { const key = process.env.SECRETS_MASTER_KEY; if (!key) throw new Error('SECRETS_MASTER_KEY is not set'); // Accepte 64 hex chars (32 bytes) ou base64 (44 chars). const buf = Buffer.from(key, key.length === 64 ? 'hex' : 'base64'); if (buf.length !== 32) { throw new Error('SECRETS_MASTER_KEY must decode to 32 bytes'); } return buf; } /** Chiffre un secret (format retourné : `iv:tag:ciphertext`, base64). */ export function encryptSecret(plaintext: string): string { const key = getMasterKey(); const iv = randomBytes(IV_LEN); const cipher = createCipheriv(ALGO, key, iv); const enc = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]); const tag = cipher.getAuthTag(); return [iv.toString('base64'), tag.toString('base64'), enc.toString('base64')].join(':'); } /** Déchiffre un secret chiffré par `encryptSecret`. */ export function decryptSecret(encrypted: string): string { const key = getMasterKey(); const [ivB64, tagB64, dataB64] = encrypted.split(':'); if (!ivB64 || !tagB64 || !dataB64) throw new Error('invalid encrypted secret format'); const iv = Buffer.from(ivB64, 'base64'); const tag = Buffer.from(tagB64, 'base64'); const data = Buffer.from(dataB64, 'base64'); const decipher = createDecipheriv(ALGO, key, iv); decipher.setAuthTag(tag); return Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8'); }