import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto"; import { env } from "./env.js"; const ALGO = "aes-256-gcm"; function getKey(): Buffer { if (!env.credentialsEncryptionEnabled) { throw new Error( "CREDENTIALS_ENCRYPTION_KEY is not configured (must be a 64-character hex string)", ); } return Buffer.from(env.credentialsEncryptionKey, "hex"); } /** Encrypts a plaintext secret for storage. Returns "iv:authTag:ciphertext" as hex. */ export function encryptSecret(plaintext: string): string { const iv = randomBytes(12); const cipher = createCipheriv(ALGO, getKey(), iv); const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]); const authTag = cipher.getAuthTag(); return [iv.toString("hex"), authTag.toString("hex"), ciphertext.toString("hex")].join(":"); } /** Reverses encryptSecret(). Throws if the key changed or the data was tampered with. */ export function decryptSecret(stored: string): string { const [ivHex, authTagHex, ciphertextHex] = stored.split(":"); if (!ivHex || !authTagHex || !ciphertextHex) { throw new Error("Malformed encrypted credential"); } const decipher = createDecipheriv(ALGO, getKey(), Buffer.from(ivHex, "hex")); decipher.setAuthTag(Buffer.from(authTagHex, "hex")); const plaintext = Buffer.concat([ decipher.update(Buffer.from(ciphertextHex, "hex")), decipher.final(), ]); return plaintext.toString("utf8"); }