7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
feat(config): warn on env drift at startup (#494)
Tashfeen6982ebdc5770
diff --git a/server/src/__tests__/lib/env-drift.test.ts b/server/src/__tests__/lib/env-drift.test.tsnew file mode 100644index 00000000..b0370571--- /dev/null+++ b/server/src/__tests__/lib/env-drift.test.ts@@ -0,0 +1,103 @@+import fs from 'fs';+import os from 'os';+import path from 'path';+import { describe, expect, it, vi } from 'vitest';+import {+ compareEnvText,+ formatEnvDriftReport,+ parseEnvNames,+ warnOnEnvDrift,+} from '../../lib/env-drift.js';++describe('env drift warnings', () => {+ it('parses active env assignments and can include commented examples', () => {+ const text = [+ 'ENCRYPTION_KEY=abc',+ 'export PORT=3001',+ '# DASHBOARD_ORIGINS=http://localhost:5173',+ '# just a comment',+ 'lowercase=value',+ ].join('\n');++ expect(parseEnvNames(text)).toEqual(['ENCRYPTION_KEY', 'PORT']);+ expect(parseEnvNames(text, { includeCommented: true })).toEqual([+ 'DASHBOARD_ORIGINS',+ 'ENCRYPTION_KEY',+ 'PORT',+ ]);+ });++ it('warns about missing active defaults without flagging opt-in examples', () => {+ const report = compareEnvText(+ 'ENCRYPTION_KEY=abc\nPORT=3001\n',+ [+ 'ENCRYPTION_KEY=your-key',+ 'PORT=3001',+ 'REQUEST_ANALYTICS_RETENTION_DAYS=90',+ '# FREELLMAPI_CONTEXT_HANDOFF=on_model_switch',+ ].join('\n'),+ );++ expect(report.missingDocumentedDefaults).toEqual(['REQUEST_ANALYTICS_RETENTION_DAYS']);+ expect(report.unknownKeys).toEqual([]);+ });++ it('reports unknown keys but allows known env-only settings', () => {+ const report = compareEnvText(+ [+ 'ENCRYPTION_KEY=abc',+ 'PORT=3001',+ 'OLD_FLAG=true',+ 'NODE_ENV=production',+ 'PROVIDER_DAILY_REQUEST_CAP_GROQ=50',+ ].join('\n'),+ 'ENCRYPTION_KEY=your-key\nPORT=3001\n# HOST=::\n',+ );++ expect(report.missingDocumentedDefaults).toEqual([]);+ expect(report.unknownKeys).toEqual(['OLD_FLAG']);+ });++ it('formats a compact, non-fatal warning', () => {+ const lines = formatEnvDriftReport({+ missingDocumentedDefaults: ['REQUEST_ANALYTICS_MAX_ROWS'],+ unknownKeys: ['OLD_FLAG'],+ });++ expect(lines).toEqual([+ '[config] .env check: 1 documented default missing; 1 unrecognised key. Startup continues.',+ '[config] missing from .env: REQUEST_ANALYTICS_MAX_ROWS',+ '[config] not in .env.example: OLD_FLAG',+ '[config] Compare .env.example when you next edit your config.',+ ]);+ });++ it('logs once per formatted line when both files exist', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'freellmapi-env-drift-'));+ const envPath = path.join(dir, '.env');+ const examplePath = path.join(dir, '.env.example');+ fs.writeFileSync(envPath, 'ENCRYPTION_KEY=abc\nPORT=3001\nOLD_FLAG=true\n');+ fs.writeFileSync(examplePath, 'ENCRYPTION_KEY=your-key\nPORT=3001\nREQUEST_ANALYTICS_MAX_ROWS=100000\n');+ const logger = { warn: vi.fn() };++ const report = warnOnEnvDrift({ envPath, examplePath }, logger);++ expect(report).toEqual({+ missingDocumentedDefaults: ['REQUEST_ANALYTICS_MAX_ROWS'],+ unknownKeys: ['OLD_FLAG'],+ });+ expect(logger.warn).toHaveBeenCalledTimes(4);+ expect(logger.warn).toHaveBeenNthCalledWith(1, '[config] .env check: 1 documented default missing; 1 unrecognised key. Startup continues.');+ });++ it('stays quiet when .env is absent', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'freellmapi-env-drift-'));+ const logger = { warn: vi.fn() };++ expect(warnOnEnvDrift({+ envPath: path.join(dir, '.env'),+ examplePath: path.join(dir, '.env.example'),+ }, logger)).toBeNull();+ expect(logger.warn).not.toHaveBeenCalled();+ });+});diff --git a/server/src/index.ts b/server/src/index.tsindex ce0a129f..f9dc0e9b 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -11,10 +11,12 @@ import { applyDeclarativeConfigFromEnv } from './services/declarative-config.js'import { restoreDbBackupIfNeeded, startDbBackupPump } from './lib/db-backup.js';import { userCount } from './services/auth.js';import { generateSetupCode } from './lib/setup-code.js';+import { warnOnEnvDrift } from './lib/env-drift.js';async function main() {const config = loadConfig();const { port: PORT, host: HOST } = config;+ warnOnEnvDrift();// Install first so a late provider socket reset (undici HTTP/2 error with no// listener) can't take the proxy down. Genuine bugs still exit 1.diff --git a/server/src/lib/env-drift.ts b/server/src/lib/env-drift.tsnew file mode 100644index 00000000..3ffc573a--- /dev/null+++ b/server/src/lib/env-drift.ts@@ -0,0 +1,129 @@+import fs from 'fs';+import path from 'path';+import { fileURLToPath } from 'url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = path.resolve(__dirname, '../../..');++const ACTIVE_ENV_RE = /^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=/;+const COMMENTED_ENV_RE = /^\s*#\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=/;++const KNOWN_UNDOCUMENTED_ENV = new Set([+ 'NODE_ENV',+ 'DEV_MODE',+ 'FREELLMAPI_DIR',+ 'PROXY_URL',+ 'CATALOG_BASE_URL',+ 'CATALOG_PUBKEY',+ 'CATALOG_SYNC_DISABLED',+ 'FREEAPI_DB_BACKUP_TARGET',+ 'PREMIUM_SITE_URL',+]);++const KNOWN_UNDOCUMENTED_PATTERNS = [+ /^PROVIDER_DAILY_REQUEST_CAP_[A-Z0-9_]+$/,+];++export interface EnvDriftReport {+ missingDocumentedDefaults: string[];+ unknownKeys: string[];+}++export interface EnvDriftPaths {+ envPath?: string;+ examplePath?: string;+}++export function defaultEnvDriftPaths(): Required<EnvDriftPaths> {+ return {+ envPath: process.env.FREEAPI_ENV_PATH ?? path.join(REPO_ROOT, '.env'),+ examplePath: path.join(REPO_ROOT, '.env.example'),+ };+}++export function parseEnvNames(text: string, opts: { includeCommented?: boolean } = {}): string[] {+ const names = new Set<string>();+ for (const line of text.split(/\r?\n/)) {+ const active = ACTIVE_ENV_RE.exec(line);+ if (active) {+ names.add(active[1]);+ continue;+ }+ if (opts.includeCommented) {+ const commented = COMMENTED_ENV_RE.exec(line);+ if (commented) names.add(commented[1]);+ }+ }+ return [...names].sort();+}++function isKnownUndocumentedEnv(name: string): boolean {+ return KNOWN_UNDOCUMENTED_ENV.has(name) || KNOWN_UNDOCUMENTED_PATTERNS.some(re => re.test(name));+}++export function compareEnvText(envText: string, exampleText: string): EnvDriftReport {+ const actual = new Set(parseEnvNames(envText));+ const documentedDefaults = parseEnvNames(exampleText);+ const documented = new Set(parseEnvNames(exampleText, { includeCommented: true }));++ return {+ missingDocumentedDefaults: documentedDefaults.filter(name => !actual.has(name)),+ unknownKeys: [...actual]+ .filter(name => !documented.has(name) && !isKnownUndocumentedEnv(name))+ .sort(),+ };+}++function plural(count: number, one: string, many: string): string {+ return count === 1 ? one : many;+}++function compactList(names: string[], limit = 8): string {+ if (names.length <= limit) return names.join(', ');+ return `${names.slice(0, limit).join(', ')} +${names.length - limit} more`;+}++export function formatEnvDriftReport(report: EnvDriftReport): string[] {+ const parts: string[] = [];+ if (report.missingDocumentedDefaults.length > 0) {+ parts.push(`${report.missingDocumentedDefaults.length} documented ${plural(report.missingDocumentedDefaults.length, 'default', 'defaults')} missing`);+ }+ if (report.unknownKeys.length > 0) {+ parts.push(`${report.unknownKeys.length} unrecognised ${plural(report.unknownKeys.length, 'key', 'keys')}`);+ }+ if (parts.length === 0) return [];++ const lines = [`[config] .env check: ${parts.join('; ')}. Startup continues.`];+ if (report.missingDocumentedDefaults.length > 0) {+ lines.push(`[config] missing from .env: ${compactList(report.missingDocumentedDefaults)}`);+ }+ if (report.unknownKeys.length > 0) {+ lines.push(`[config] not in .env.example: ${compactList(report.unknownKeys)}`);+ }+ lines.push('[config] Compare .env.example when you next edit your config.');+ return lines;+}++export function checkEnvDrift(paths: EnvDriftPaths = {}): EnvDriftReport | null {+ const defaults = defaultEnvDriftPaths();+ const envPath = paths.envPath ?? defaults.envPath;+ const examplePath = paths.examplePath ?? defaults.examplePath;++ if (!fs.existsSync(envPath) || !fs.existsSync(examplePath)) return null;++ try {+ return compareEnvText(+ fs.readFileSync(envPath, 'utf8'),+ fs.readFileSync(examplePath, 'utf8'),+ );+ } catch {+ return null;+ }+}++export function warnOnEnvDrift(paths?: EnvDriftPaths, logger: Pick<Console, 'warn'> = console): EnvDriftReport | null {+ const report = checkEnvDrift(paths);+ if (!report) return null;+ for (const line of formatEnvDriftReport(report)) logger.warn(line);+ return report;+}