settings/src/crypto.js
jtricerolph e7b08ccf31 Initial settings service
Fastify API for storing third-party integration credentials (Newbook, Resos,
Nextcloud, Azure, SambaPOS) with AES-256-GCM encryption for sensitive fields.
Includes Newbook room sync endpoint and global_config store for shared app data.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 18:56:19 +00:00

28 lines
917 B
JavaScript

import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'node:crypto'
const ALG = 'aes-256-gcm'
const IV_LEN = 12
const TAG_LEN = 16
function key() {
const s = process.env.SETTINGS_SECRET
if (!s) throw new Error('SETTINGS_SECRET env var not set')
return scryptSync(s, 'hnf-settings-v1', 32)
}
export function encrypt(plaintext) {
const iv = randomBytes(IV_LEN)
const c = createCipheriv(ALG, key(), iv)
const enc = Buffer.concat([c.update(plaintext, 'utf8'), c.final()])
return Buffer.concat([iv, c.getAuthTag(), enc]).toString('base64')
}
export function decrypt(b64) {
const buf = Buffer.from(b64, 'base64')
const iv = buf.subarray(0, IV_LEN)
const tag = buf.subarray(IV_LEN, IV_LEN + TAG_LEN)
const enc = buf.subarray(IV_LEN + TAG_LEN)
const d = createDecipheriv(ALG, key(), iv)
d.setAuthTag(tag)
return Buffer.concat([d.update(enc), d.final()]).toString('utf8')
}