/** * Site settings in `AppSetting` (key → string), as Accounts' lib/settings.ts. Secret ones are * encrypted at rest and never sent to the browser. A short cache keeps pages from reading the * table on every request. */ import type { Ctx } from '../context.js'; export const SECRET_SETTINGS = new Set(['hub_install_secret', 'hub_private_key']); 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(); } }