Study/server/config.ts
Elijah c595e0ff2c
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s
Third revision: web search, MCP sign-in, exams, intelligent UI, clarifying questions
- Built-in Parallel web search (keyless; optional sign-in for higher limits and research)
  with its own settings page; OAuth sign-in (RFC 9728/8414/7591, PKCE, RFC 8707) for any
  MCP server, with token refresh and pre-registered client support
- Friendly tool steps (icon, name, status; details on click) and ids stripped from results;
  per-chat tool switches; taller thinking box
- Exams within classes: exam tabs, scoped lists, uploads, imports and Generate; exam-only
  material for generation; class setting for what the groups are called
- Assistant can ask clarifying questions in an inline form before generating
- OpenUI blocks (charts, questions, flashcards, inputs) in assistant, Explain and share chats
- Explain beside the quiz on wide screens, grounded in the cited source pages
- Quiz results: percentage ring coloured by score band, rainbow at 100
- Share links: assistant button like the owner's, hidden during quizzes; documents readable
  in the browser
- Live draft and library updates over server-sent events

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:30:00 -07:00

106 lines
4.3 KiB
TypeScript

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;
/**
* Use the built-in embedding model for semantic search when no embedding provider has been
* chosen. On by default; off in tests. LOCAL_EMBEDDINGS=off disables it.
*/
localEmbeddings: boolean;
/**
* Endpoint of the built-in web search (Parallel's MCP server). WEB_SEARCH_URL overrides it;
* the feature starts switched off in tests so they never reach the internet.
*/
webSearchUrl: 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<Config> = {}, 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,
localEmbeddings: bool(envVars.LOCAL_EMBEDDINGS, env !== 'test'),
webSearchUrl: envVars.WEB_SEARCH_URL?.trim() || 'https://mcp.parallel.ai/mcp',
...overrides,
};
}