41 lines
1.5 KiB
JavaScript
41 lines
1.5 KiB
JavaScript
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'
|
|
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
import path from 'node:path'
|
|
function key() {
|
|
if (process.env.SMTP_ENCRYPTION_KEY) {
|
|
if (!/^[a-f0-9]{64}$/i.test(process.env.SMTP_ENCRYPTION_KEY))
|
|
throw Error('SMTP_ENCRYPTION_KEY muss 32 Byte in Hex enthalten.')
|
|
return Buffer.from(process.env.SMTP_ENCRYPTION_KEY, 'hex')
|
|
}
|
|
const file =
|
|
process.env.SMTP_KEY_FILE ||
|
|
path.join(path.dirname(process.env.DB_PATH || 'data/syncova.db'), 'smtp.key')
|
|
mkdirSync(path.dirname(file), { recursive: true })
|
|
try {
|
|
return readFileSync(file)
|
|
} catch (e) {
|
|
if (e.code !== 'ENOENT') throw e
|
|
}
|
|
const value = randomBytes(32)
|
|
try {
|
|
writeFileSync(file, value, { flag: 'wx', mode: 0o600 })
|
|
return value
|
|
} catch (e) {
|
|
if (e.code === 'EEXIST') return readFileSync(file)
|
|
throw e
|
|
}
|
|
}
|
|
export function encryptSecret(value) {
|
|
const iv = randomBytes(12),
|
|
cipher = createCipheriv('aes-256-gcm', key(), iv)
|
|
const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()])
|
|
return [iv, cipher.getAuthTag(), encrypted].map((b) => b.toString('base64')).join('.')
|
|
}
|
|
export function decryptSecret(value) {
|
|
if (!value) return ''
|
|
const [iv, tag, data] = value.split('.').map((s) => Buffer.from(s, 'base64'))
|
|
const cipher = createDecipheriv('aes-256-gcm', key(), iv)
|
|
cipher.setAuthTag(tag)
|
|
return Buffer.concat([cipher.update(data), cipher.final()]).toString('utf8')
|
|
}
|