/** * Secrets at rest (AES-256-GCM, as Events' utils/encryption.js), tokens and codes. * The key comes from ACCOUNTS_SECRET; encrypted values start with "enc:". */ import crypto from 'node:crypto'; const SENTINEL = 'enc:'; export class Secrets { private readonly key: Buffer; constructor(secret: string) { this.key = crypto.scryptSync(secret, 'crosscode-accounts-aes256gcm-v1', 32); } encrypt(plain: string): string { if (plain.startsWith(SENTINEL)) return plain; const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', this.key, iv); const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]); return `${SENTINEL}${iv.toString('hex')}:${cipher.getAuthTag().toString('hex')}:${data.toString('hex')}`; } /** Throws if the value was changed or encrypted with another key. */ decrypt(value: string): string { if (!value.startsWith(SENTINEL)) return value; const [iv, tag, data] = value.slice(SENTINEL.length).split(':'); if (!iv || !tag || data === undefined) throw new Error('Invalid encrypted value'); const decipher = crypto.createDecipheriv('aes-256-gcm', this.key, Buffer.from(iv, 'hex')); decipher.setAuthTag(Buffer.from(tag, 'hex')); return Buffer.concat([decipher.update(Buffer.from(data, 'hex')), decipher.final()]).toString('utf8'); } /** Keys for signing cookies (oidc-provider and our own), derived so they're stable per install. */ cookieKeys(): string[] { return [crypto.createHmac('sha256', this.key).update('cookies-v1').digest('base64url')]; } } /** A random token for a link sent by email (32 bytes, base64url). */ export const randomToken = () => crypto.randomBytes(32).toString('base64url'); /** A 6-digit code sent by email or WhatsApp. */ export const randomCode = () => String(crypto.randomInt(0, 1_000_000)).padStart(6, '0'); /** What's stored for a token or code: only its SHA-256. */ export const hashToken = (token: string) => crypto.createHash('sha256').update(token).digest('hex'); export function safeEqual(a: string, b: string): boolean { const x = Buffer.from(a); const y = Buffer.from(b); return x.length === y.length && crypto.timingSafeEqual(x, y); }