BillTracker/services/encryptionService.js

56 lines
2.1 KiB
JavaScript

'use strict';
const crypto = require('crypto');
const ALGORITHM = 'aes-256-gcm';
const IV_BYTES = 12;
const TAG_BYTES = 16;
// Returns a stable 256-bit key. Prefers TOKEN_ENCRYPTION_KEY env var (power-user
// override); otherwise auto-generates a random key on first startup and persists
// it in the settings table so it survives restarts without any manual config.
function getKey() {
const envRaw = process.env.TOKEN_ENCRYPTION_KEY || '';
if (envRaw) {
const buf = Buffer.from(envRaw, 'utf8');
if (buf.length < 32) throw new Error('TOKEN_ENCRYPTION_KEY must be at least 32 bytes');
return crypto.createHash('sha256').update(buf).digest();
}
// Lazy-require to avoid circular dependency at module load time
const { getSetting, setSetting } = require('../db/database');
let stored = getSetting('_auto_encryption_key');
if (!stored) {
stored = crypto.randomBytes(48).toString('hex');
setSetting('_auto_encryption_key', stored);
}
return crypto.createHash('sha256').update(stored, 'utf8').digest();
}
// No-op now that the key is always available — kept for call-site compatibility
function assertEncryptionReady() {}
function encryptSecret(plaintext) {
const key = getKey();
const iv = crypto.randomBytes(IV_BYTES);
const cipher = crypto.createCipheriv(ALGORITHM, key, iv, { authTagLength: TAG_BYTES });
const ct = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return `${iv.toString('hex')}:${tag.toString('hex')}:${ct.toString('hex')}`;
}
function decryptSecret(stored) {
const parts = stored.split(':');
if (parts.length !== 3) throw new Error('Invalid encrypted secret format');
const [ivHex, tagHex, ctHex] = parts;
const key = getKey();
const iv = Buffer.from(ivHex, 'hex');
const tag = Buffer.from(tagHex, 'hex');
const ct = Buffer.from(ctHex, 'hex');
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv, { authTagLength: TAG_BYTES });
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf8');
}
module.exports = { assertEncryptionReady, encryptSecret, decryptSecret };