/** * Site settings in `AppSetting` (key → string). Secret ones are encrypted at rest. A short cache * keeps sign-in pages from reading the table on every request. */ import type { Ctx } from '../context.js'; /** Encrypted at rest; never sent to the browser. */ export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_install_secret', 'hub_private_key', 'oidc_jwks']); /** The settings an admin may read and change through the generic settings API. */ export const ADMIN_SETTINGS = new Set([ 'signup_enabled', 'two_factor_required_for_admins', 'session_days', 'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure', 'wawp_access_token', 'wawp_instance_id', ]); const TTL_MS = 30_000; export class Settings { private cache = new Map(); constructor(private readonly ctx: Pick) {} async get(key: string): Promise { const hit = this.cache.get(key); if (hit && Date.now() - hit.at < TTL_MS) return hit.value; const row = await this.ctx.db.appSetting.findUnique({ where: { key } }); let value = row?.value ?? null; if (value !== null && SECRET_SETTINGS.has(key)) { try { value = this.ctx.secrets.decrypt(value); } catch { value = null; } } this.cache.set(key, { value, at: Date.now() }); return value; } async bool(key: string, fallback: boolean): Promise { const v = await this.get(key); return v === null || v === '' ? fallback : v === 'true'; } async json(key: string, fallback: T): Promise { const v = await this.get(key); if (!v) return fallback; try { return JSON.parse(v) as T; } catch { return fallback; } } async set(key: string, value: string | null): Promise { if (value === null) await this.ctx.db.appSetting.deleteMany({ where: { key } }); else { const stored = SECRET_SETTINGS.has(key) ? this.ctx.secrets.encrypt(value) : value; await this.ctx.db.appSetting.upsert({ where: { key }, update: { value: stored }, create: { key, value: stored } }); } this.cache.delete(key); } async setMany(values: Record): Promise { for (const [k, v] of Object.entries(values)) await this.set(k, v); } forget(): void { this.cache.clear(); } }