import fs from 'node:fs'; import path from 'node:path'; import crypto from 'node:crypto'; export interface Config { env: 'development' | 'production' | 'test'; host: string; port: number; dataDir: string; dbPath: string; uploadsDir: string; mediaDir: string; backupsDir: string; /** Directory with the built web app, or null when the Vite dev server serves it. */ webDir: string | null; /** 32-byte key used to encrypt provider API keys at rest. */ secretKey: Buffer; /** 'auto' marks the cookie Secure whenever the request arrived over HTTPS (directly or via proxy). */ cookieSecure: 'auto' | boolean; trustProxy: boolean; adminPassword: string | null; resetAdminPassword: string | null; maxUploadBytes: number; backupKeep: number; timezone: string; } function bool(v: string | undefined, fallback: boolean): boolean { if (v === undefined || v === '') return fallback; return ['1', 'true', 'yes', 'on'].includes(v.toLowerCase()); } function loadSecret(dataDir: string, fromEnv: string | undefined): Buffer { if (fromEnv && fromEnv.trim().length < 16) throw new Error('APP_SECRET must contain at least 16 characters.'); if (fromEnv) { return crypto.createHash('sha256').update(`studydesk:${fromEnv.trim()}`).digest(); } const file = path.join(dataDir, 'secret.key'); if (fs.existsSync(file)) { const raw = Buffer.from(fs.readFileSync(file, 'utf8').trim(), 'base64'); if (raw.length === 32) return raw; throw new Error('secret.key is damaged. Restore the original key from your backup; refusing to replace it.'); } if (fs.existsSync(path.join(dataDir, 'study.db'))) { throw new Error('Existing database has no secret.key. Restore its original key or set the original APP_SECRET; refusing to generate a replacement.'); } const key = crypto.randomBytes(32); fs.writeFileSync(file, key.toString('base64'), { mode: 0o600, flag: 'wx' }); return key; } export function loadConfig(overrides: Partial = {}, envVars: NodeJS.ProcessEnv = process.env): Config { const env = (overrides.env ?? (envVars.NODE_ENV === 'production' ? 'production' : envVars.NODE_ENV === 'test' ? 'test' : 'development')) as Config['env']; const dataDir = path.resolve(overrides.dataDir ?? envVars.DATA_DIR ?? (env === 'production' ? '/data' : './data')); const uploadsDir = path.join(dataDir, 'uploads'); const mediaDir = path.join(dataDir, 'media'); const backupsDir = path.join(dataDir, 'backups'); for (const dir of [dataDir, uploadsDir, mediaDir, backupsDir]) fs.mkdirSync(dir, { recursive: true }); const secure = (envVars.COOKIE_SECURE ?? 'auto').toLowerCase(); let webDir: string | null = overrides.webDir ?? envVars.WEB_DIR ?? null; if (webDir === null) { const candidate = path.resolve('dist/web'); if (fs.existsSync(path.join(candidate, 'index.html'))) webDir = candidate; } let timezone = envVars.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; try { new Intl.DateTimeFormat('en-US', { timeZone: timezone }); } catch { timezone = 'UTC'; } return { env, host: envVars.HOST ?? '0.0.0.0', port: Number(envVars.PORT ?? 3726), dataDir, dbPath: path.join(dataDir, 'study.db'), uploadsDir, mediaDir, backupsDir, webDir, secretKey: loadSecret(dataDir, envVars.APP_SECRET), cookieSecure: secure === 'auto' ? 'auto' : bool(secure, false), trustProxy: bool(envVars.TRUST_PROXY, true), adminPassword: envVars.ADMIN_PASSWORD?.trim() || null, resetAdminPassword: envVars.RESET_ADMIN_PASSWORD?.trim() || null, maxUploadBytes: Math.max(1, Number(envVars.MAX_UPLOAD_MB ?? 100)) * 1024 * 1024, backupKeep: Math.max(1, Number(envVars.BACKUP_KEEP ?? 7)), timezone, ...overrides, }; }