// Small helper to keep a secret value encrypted at rest (AES-256-GCM, key derived from the server secret). const crypto = require('crypto'); const auth = require('./auth'); module.exports = label => { let key; const k = () => key || (key = crypto.scryptSync(auth.secret, label, 32)); return { seal(obj) { const iv = crypto.randomBytes(12), c = crypto.createCipheriv('aes-256-gcm', k(), iv); const d = Buffer.concat([c.update(JSON.stringify(obj), 'utf8'), c.final()]); return Buffer.concat([iv, c.getAuthTag(), d]).toString('base64'); }, unseal(s) { try { const b = Buffer.from(s, 'base64'), d = crypto.createDecipheriv('aes-256-gcm', k(), b.subarray(0, 12)); d.setAuthTag(b.subarray(12, 28)); return JSON.parse(Buffer.concat([d.update(b.subarray(28)), d.final()]).toString('utf8')); } catch { return null; } }, }; };