/** * Secrets at rest (AES-256-GCM, as Accounts' lib/crypto.ts), and tokens. The key comes from * WEBSITE_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-website-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'); } } /** A random token for a cookie (32 bytes, base64url). */ export const randomToken = () => crypto.randomBytes(32).toString('base64url'); /** What's stored for a token: only its SHA-256. */ export const hashToken = (token: string) => crypto.createHash('sha256').update(token).digest('hex');