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
security: phase 1 hardening (subset of #36, credits @jtbrennan-git) (#40)
Tashfeen8415820b5a28
diff --git a/README.md b/README.mdindex 0dc2636e..4608ceea 100644--- a/README.md+++ b/README.md@@ -295,6 +295,7 @@ Thanks to everyone who's helped improve FreeLLMAPI:- [@lukasulc](https://github.com/lukasulc) — better-sqlite3 bump to fix npm install on Node 24+ (#12)- [@VinhPhamAI](https://github.com/VinhPhamAI) — root `.env` PORT now propagates to server + Vite dev proxy + UI base URL (#27)- [@deadc](https://github.com/deadc) — preserve Gemini `thoughtSignature` so multi-turn function calling stops 400-ing (#32)+- [@jtbrennan-git](https://github.com/jtbrennan-git) — security review (#35) and Phase 1 hardening: parameterized analytics queries, sort-preset whitelist, timing-safe API key compare, mid-stream error sanitization## Terms of Service reviewdiff --git a/server/src/routes/analytics.ts b/server/src/routes/analytics.tsindex ed912c89..3f4ecbb4 100644--- a/server/src/routes/analytics.ts+++ b/server/src/routes/analytics.ts@@ -4,19 +4,25 @@ import { getDb } from '../db/index.js';export const analyticsRouter = Router();-function getTimeFilter(range: string): string {+// Map range to a JS-computed ISO timestamp passed as a bind parameter,+// so the SQL string never includes user-controlled fragments.+function getSinceTimestamp(range: string): string {+ const now = Date.now();switch (range) {- case '24h': return "datetime('now', '-1 day')";- case '7d': return "datetime('now', '-7 days')";- case '30d': return "datetime('now', '-30 days')";- default: return "datetime('now', '-7 days')";+ case '24h':+ return new Date(now - 24 * 60 * 60 * 1000).toISOString();+ case '30d':+ return new Date(now - 30 * 24 * 60 * 60 * 1000).toISOString();+ case '7d':+ default:+ return new Date(now - 7 * 24 * 60 * 60 * 1000).toISOString();}}// Summary statsanalyticsRouter.get('/summary', (req: Request, res: Response) => {const range = (req.query.range as string) ?? '7d';- const since = getTimeFilter(range);+ const since = getSinceTimestamp(range);const db = getDb();const stats = db.prepare(`@@ -27,8 +33,8 @@ analyticsRouter.get('/summary', (req: Request, res: Response) => {SUM(output_tokens) as total_output_tokens,AVG(latency_ms) as avg_latency_msFROM requests- WHERE created_at >= ${since}- `).get() as any;+ WHERE created_at >= ?+ `).get(since) as any;const totalRequests = stats.total_requests ?? 0;const successRate = totalRequests > 0 ? (stats.success_count / totalRequests) * 100 : 0;@@ -51,7 +57,7 @@ analyticsRouter.get('/summary', (req: Request, res: Response) => {// Stats grouped by modelanalyticsRouter.get('/by-model', (req: Request, res: Response) => {const range = (req.query.range as string) ?? '7d';- const since = getTimeFilter(range);+ const since = getSinceTimestamp(range);const db = getDb();const rows = db.prepare(`@@ -66,10 +72,10 @@ analyticsRouter.get('/by-model', (req: Request, res: Response) => {SUM(r.output_tokens) as total_output_tokensFROM requests rLEFT JOIN models m ON m.platform = r.platform AND m.model_id = r.model_id- WHERE r.created_at >= ${since}+ WHERE r.created_at >= ?GROUP BY r.platform, r.model_idORDER BY requests DESC- `).all() as any[];+ `).all(since) as any[];res.json(rows.map(r => ({platform: r.platform,@@ -86,7 +92,7 @@ analyticsRouter.get('/by-model', (req: Request, res: Response) => {// Stats grouped by platformanalyticsRouter.get('/by-platform', (req: Request, res: Response) => {const range = (req.query.range as string) ?? '7d';- const since = getTimeFilter(range);+ const since = getSinceTimestamp(range);const db = getDb();const rows = db.prepare(`@@ -98,10 +104,10 @@ analyticsRouter.get('/by-platform', (req: Request, res: Response) => {SUM(input_tokens) as total_input_tokens,SUM(output_tokens) as total_output_tokensFROM requests- WHERE created_at >= ${since}+ WHERE created_at >= ?GROUP BY platformORDER BY requests DESC- `).all() as any[];+ `).all(since) as any[];res.json(rows.map(r => ({platform: r.platform,@@ -117,9 +123,10 @@ analyticsRouter.get('/by-platform', (req: Request, res: Response) => {analyticsRouter.get('/timeline', (req: Request, res: Response) => {const range = (req.query.range as string) ?? '7d';const interval = (req.query.interval as string) ?? (range === '24h' ? 'hour' : 'day');- const since = getTimeFilter(range);+ const since = getSinceTimestamp(range);const db = getDb();+ // dateFormat is a hardcoded whitelist — never user-controlled.const dateFormat = interval === 'hour' ? '%Y-%m-%dT%H:00:00' : '%Y-%m-%d';const rows = db.prepare(`@@ -129,10 +136,10 @@ analyticsRouter.get('/timeline', (req: Request, res: Response) => {SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success_count,SUM(CASE WHEN status = 'error' THEN 1 ELSE 0 END) as failure_countFROM requests- WHERE created_at >= ${since}+ WHERE created_at >= ?GROUP BY strftime('${dateFormat}', created_at)ORDER BY timestamp ASC- `).all() as any[];+ `).all(since) as any[];res.json(rows.map(r => ({timestamp: r.timestamp,@@ -145,7 +152,7 @@ analyticsRouter.get('/timeline', (req: Request, res: Response) => {// Error distribution (grouped by error type and platform)analyticsRouter.get('/error-distribution', (req: Request, res: Response) => {const range = (req.query.range as string) ?? '7d';- const since = getTimeFilter(range);+ const since = getSinceTimestamp(range);const db = getDb();// Group errors by category (extract the key part of the error message)@@ -165,10 +172,10 @@ analyticsRouter.get('/error-distribution', (req: Request, res: Response) => {END as error_category,COUNT(*) as countFROM requests- WHERE status = 'error' AND created_at >= ${since}+ WHERE status = 'error' AND created_at >= ?GROUP BY platform, error_categoryORDER BY count DESC- `).all() as any[];+ `).all(since) as any[];// Also get totals by categoryconst byCategory = db.prepare(`@@ -185,19 +192,19 @@ analyticsRouter.get('/error-distribution', (req: Request, res: Response) => {END as category,COUNT(*) as countFROM requests- WHERE status = 'error' AND created_at >= ${since}+ WHERE status = 'error' AND created_at >= ?GROUP BY categoryORDER BY count DESC- `).all() as any[];+ `).all(since) as any[];// Errors by platformconst byPlatform = db.prepare(`SELECT platform, COUNT(*) as countFROM requests- WHERE status = 'error' AND created_at >= ${since}+ WHERE status = 'error' AND created_at >= ?GROUP BY platformORDER BY count DESC- `).all() as any[];+ `).all(since) as any[];res.json({byCategory,@@ -209,16 +216,16 @@ analyticsRouter.get('/error-distribution', (req: Request, res: Response) => {// Recent errorsanalyticsRouter.get('/errors', (req: Request, res: Response) => {const range = (req.query.range as string) ?? '7d';- const since = getTimeFilter(range);+ const since = getSinceTimestamp(range);const db = getDb();const rows = db.prepare(`SELECT id, platform, model_id, error, latency_ms, created_atFROM requests- WHERE status = 'error' AND created_at >= ${since}+ WHERE status = 'error' AND created_at >= ?ORDER BY created_at DESCLIMIT 50- `).all() as any[];+ `).all(since) as any[];res.json(rows.map(r => ({id: r.id,diff --git a/server/src/routes/fallback.ts b/server/src/routes/fallback.tsindex dfe3816a..ebf8b3d3 100644--- a/server/src/routes/fallback.ts+++ b/server/src/routes/fallback.ts@@ -83,30 +83,24 @@ fallbackRouter.put('/', (req: Request, res: Response) => {res.json({ success: true });});-// Sort presets-fallbackRouter.post('/sort/:preset', (req: Request, res: Response) => {- const { preset } = req.params;- const db = getDb();+// Sort presets — `orderBy` is selected from a fixed whitelist, never from+// user input directly, so the interpolation below is safe.+const SORT_PRESETS: Record<string, string> = {+ intelligence: 'm.intelligence_rank ASC',+ speed: 'm.speed_rank ASC',+ budget: "CASE m.monthly_token_budget WHEN '~120M' THEN 1 WHEN '~50-100M' THEN 2 WHEN '~30M' THEN 3 WHEN '~18-45M' THEN 4 WHEN '~18M' THEN 5 WHEN '~15M' THEN 6 WHEN '~12M' THEN 7 WHEN '~6M' THEN 8 WHEN '~5-10M' THEN 9 WHEN '~4M' THEN 10 ELSE 11 END ASC",+};- let orderBy: string;- switch (preset) {- case 'intelligence':- orderBy = 'm.intelligence_rank ASC';- break;- case 'speed':- orderBy = 'm.speed_rank ASC';- break;- case 'budget':- orderBy = "CASE m.monthly_token_budget WHEN '~120M' THEN 1 WHEN '~50-100M' THEN 2 WHEN '~30M' THEN 3 WHEN '~18-45M' THEN 4 WHEN '~18M' THEN 5 WHEN '~15M' THEN 6 WHEN '~12M' THEN 7 WHEN '~6M' THEN 8 WHEN '~5-10M' THEN 9 WHEN '~4M' THEN 10 ELSE 11 END ASC";- break;- default:- res.status(400).json({ error: { message: `Unknown preset: ${preset}. Use: intelligence, speed, budget` } });- return;+fallbackRouter.post('/sort/:preset', (req: Request, res: Response) => {+ const preset = String(req.params.preset);+ const orderBy = SORT_PRESETS[preset];+ if (!orderBy) {+ res.status(400).json({ error: { message: `Unknown preset: ${preset}. Use: intelligence, speed, budget` } });+ return;}- const models = db.prepare(`- SELECT m.id FROM models m ORDER BY ${orderBy}- `).all() as { id: number }[];+ const db = getDb();+ const models = db.prepare(`SELECT m.id FROM models m ORDER BY ${orderBy}`).all() as { id: number }[];const update = db.prepare('UPDATE fallback_config SET priority = ? WHERE model_db_id = ?');const reorder = db.transaction(() => {diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 0136d776..3c6e30fe 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -9,6 +9,19 @@ import { getDb, getUnifiedApiKey } from '../db/index.js';export const proxyRouter = Router();+// Constant-time string comparison for the unified API key. Plain `===` leaks+// length and per-character timing, which a network attacker could in principle+// use to recover the key one byte at a time.+function timingSafeStringEqual(provided: string, expected: string): boolean {+ const a = Buffer.from(provided);+ const b = Buffer.from(expected);+ // Compare against a same-length buffer regardless of input length so the+ // comparison itself runs in constant time; the explicit length check at the+ // end is what actually decides equality when lengths differ.+ const compareA = a.length === b.length ? a : Buffer.alloc(b.length);+ return crypto.timingSafeEqual(compareA, b) && a.length === b.length;+}+// Sticky sessions: track which model served each "session"// Key: hash of first user message → model_db_id// This prevents model switching mid-conversation which causes hallucination@@ -172,11 +185,16 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {// Authenticate with unified API key. Local requests (127.0.0.1) skip the check// since they came from the same machine running the server. Non-local requests// MUST present a valid Bearer token — missing or wrong → 401.+ //+ // Note: req.ip is the actual TCP socket peer because we never set+ // `trust proxy`, so X-Forwarded-For cannot spoof a localhost identity.+ // If a future change enables `trust proxy`, this localhost bypass MUST be+ // re-evaluated.const isLocal = req.ip === '127.0.0.1' || req.ip === '::1' || req.ip === '::ffff:127.0.0.1';if (!isLocal) {const token = req.headers.authorization?.replace(/^Bearer\s+/i, '');const unifiedKey = getUnifiedApiKey();- if (!token || token !== unifiedKey) {+ if (!token || !timingSafeStringEqual(token, unifiedKey)) {res.status(401).json({error: { message: 'Invalid API key', type: 'authentication_error' },});@@ -337,7 +355,10 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {if (streamStarted) {// Mid-stream error — finish the SSE response cleanly instead of leaving// the client hanging or letting Express's default handler take over.- const payload = { error: { message: `Provider error (${route.displayName}): ${streamErr.message}`, type: 'stream_error' } };+ // Full upstream message goes to the log; the client sees a generic+ // message so we don't leak provider internals into a partial stream.+ console.error(`[Proxy] Mid-stream error from ${route.displayName}:`, streamErr.message);+ const payload = { error: { message: `Provider error (${route.displayName}): stream interrupted`, type: 'stream_error' } };try { res.write(`data: ${JSON.stringify(payload)}\n\n`); } catch { /* socket gone */ }try { res.write('data: [DONE]\n\n'); res.end(); } catch { /* socket gone */ }logRequest(route.platform, route.modelId, 'error', estimatedInputTokens, totalOutputTokens, Date.now() - start, streamErr.message);