/** * Small AES-256-GCM helper for credentials stored in SQLite (SMTP app password, * bridge service tokens). Values written before this file existed are plain * strings and are still readable; they are sealed the next time they are saved. */ import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { DATA_DIR, SECRET_KEY } from './config.mjs'; const PREFIX = 'enc:v1:'; let cachedKey = null; function loadKey() { if (cachedKey) return cachedKey; if (SECRET_KEY) { cachedKey = crypto.createHash('sha256').update(SECRET_KEY).digest(); return cachedKey; } // Without an explicit key, keep one beside the database. It protects copies // of the database (backups, dumps) but not an attacker who has the whole // data directory. const file = path.join(DATA_DIR, 'secret.key'); const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').trim() : ''; if (existing) { cachedKey = crypto.createHash('sha256').update(existing).digest(); return cachedKey; } const generated = crypto.randomBytes(32).toString('hex'); fs.mkdirSync(DATA_DIR, { recursive: true }); try { fs.writeFileSync(file, generated, { mode: 0o600, flag: 'wx' }); cachedKey = crypto.createHash('sha256').update(generated).digest(); } catch { cachedKey = crypto .createHash('sha256') .update(fs.readFileSync(file, 'utf8').trim()) .digest(); } return cachedKey; } export function isSealed(value) { return typeof value === 'string' && value.startsWith(PREFIX); } export function seal(value) { if (typeof value !== 'string' || !value) return value; if (isSealed(value)) return value; const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', loadKey(), iv); const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]); return `${PREFIX}${iv.toString('base64url')}.${cipher.getAuthTag().toString('base64url')}.${ciphertext.toString('base64url')}`; } export function open(value) { if (!isSealed(value)) return value; const [iv, tag, ciphertext] = String(value).slice(PREFIX.length).split('.'); const decipher = crypto.createDecipheriv( 'aes-256-gcm', loadKey(), Buffer.from(iv, 'base64url'), ); decipher.setAuthTag(Buffer.from(tag, 'base64url')); return Buffer.concat([ decipher.update(Buffer.from(ciphertext, 'base64url')), decipher.final(), ]).toString('utf8'); }