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
fix(security): require API key on loopback + restrict CORS to dashboard origins (#55)
Ricardo8dd913096bf3
diff --git a/server/src/__tests__/integration/full-flow.test.ts b/server/src/__tests__/integration/full-flow.test.tsindex bbf5465f..9ce9cc2f 100644--- a/server/src/__tests__/integration/full-flow.test.ts+++ b/server/src/__tests__/integration/full-flow.test.ts@@ -1,16 +1,16 @@import { describe, it, expect, beforeAll, vi } from 'vitest';import type { Express } from 'express';import { createApp } from '../../app.js';-import { initDb, getDb } from '../../db/index.js';+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';-async function req(app: Express, method: string, path: string, body?: any) {+async function req(app: Express, method: string, path: string, body?: any, headers: Record<string, string> = {}) {const server = app.listen(0);const addr = server.address() as any;const url = `http://127.0.0.1:${addr.port}${path}`;const res = await fetch(url, {method,- headers: body ? { 'Content-Type': 'application/json' } : {},+ headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...headers },body: body ? JSON.stringify(body) : undefined,});@@ -23,6 +23,10 @@ async function req(app: Express, method: string, path: string, body?: any) {return { status: res.status, body: json, headers: res.headers, raw: data };}+function authHeaders() {+ return { Authorization: `Bearer ${getUnifiedApiKey()}` };+}+describe('Full Integration Flow', () => {let app: Express;@@ -58,10 +62,10 @@ describe('Full Integration Flow', () => {expect(body[0]).toHaveProperty('enabled');});- it('Step 3: Proxy returns 429 with no keys', async () => {+ it('Step 3: Authenticated proxy returns 429 with no keys', async () => {const { status, body } = await req(app, 'POST', '/v1/chat/completions', {messages: [{ role: 'user', content: 'hello' }],- });+ }, authHeaders());// 429 (all exhausted) or 502 (provider error) or 503 (no route)expect([429, 502, 503]).toContain(status);expect(body.error).toBeDefined();@@ -98,7 +102,7 @@ describe('Full Integration Flow', () => {const { status, body } = await req(app, 'POST', '/v1/chat/completions', {messages: [{ role: 'user', content: 'hello' }],- });+ }, authHeaders());// 502 (provider error) or 429 (all exhausted after retries)expect([502, 429]).toContain(status);@@ -145,12 +149,12 @@ describe('Full Integration Flow', () => {it('Step 10: Validate request schema', async () => {const { status } = await req(app, 'POST', '/v1/chat/completions', {messages: [], // empty- });+ }, authHeaders());expect(status).toBe(400);const { status: s2 } = await req(app, 'POST', '/v1/chat/completions', {// missing messages entirely- });+ }, authHeaders());expect(s2).toBe(400);});@@ -158,7 +162,7 @@ describe('Full Integration Flow', () => {const { status, body } = await req(app, 'POST', '/v1/chat/completions', {model: 'definitely-not-a-real-model',messages: [{ role: 'user', content: 'hi' }],- });+ }, authHeaders());expect(status).toBe(400);expect(body.error.code).toBe('model_not_found');expect(body.error.message).toContain('not in the catalog');@@ -169,7 +173,7 @@ describe('Full Integration Flow', () => {const { status, body } = await req(app, 'POST', '/v1/chat/completions', {model: 'gemini-2.5-pro',messages: [{ role: 'user', content: 'hi' }],- });+ }, authHeaders());expect(status).toBe(400);expect(body.error.code).toBe('model_not_found');expect(body.error.message).toContain('is disabled');diff --git a/server/src/__tests__/routes/proxy-auth-cors.test.ts b/server/src/__tests__/routes/proxy-auth-cors.test.tsnew file mode 100644index 00000000..3f43b3ce--- /dev/null+++ b/server/src/__tests__/routes/proxy-auth-cors.test.ts@@ -0,0 +1,61 @@+import { describe, it, expect, beforeAll } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb } from '../../db/index.js';++async function request(app: Express, method: string, path: string, body?: any, headers: Record<string, string> = {}) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const url = `http://127.0.0.1:${addr.port}${path}`;++ const res = await fetch(url, {+ method,+ headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...headers },+ body: body ? JSON.stringify(body) : undefined,+ });++ const data = await res.text();+ server.close();++ let json: any = null;+ try { json = JSON.parse(data); } catch {}++ return { status: res.status, body: json, headers: res.headers, raw: data };+}++describe('Proxy authentication and CORS', () => {+ let app: Express;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ });++ it('requires the unified API key for loopback chat completions', async () => {+ const { status, body } = await request(app, 'POST', '/v1/chat/completions', {+ messages: [{ role: 'user', content: 'hello' }],+ });++ expect(status).toBe(401);+ expect(body.error.type).toBe('authentication_error');+ });++ it('does not grant CORS access to arbitrary browser origins', async () => {+ const { status, headers } = await request(app, 'GET', '/api/ping', undefined, {+ Origin: 'https://attacker.example',+ });++ expect(status).toBe(200);+ expect(headers.get('access-control-allow-origin')).toBeNull();+ });++ it('allows the local dashboard origin through CORS', async () => {+ const { status, headers } = await request(app, 'GET', '/api/ping', undefined, {+ Origin: 'http://localhost:5173',+ });++ expect(status).toBe(200);+ expect(headers.get('access-control-allow-origin')).toBe('http://localhost:5173');+ });+});diff --git a/server/src/__tests__/routes/proxy-tools.test.ts b/server/src/__tests__/routes/proxy-tools.test.tsindex 7bfdcc10..0d91f2f8 100644--- a/server/src/__tests__/routes/proxy-tools.test.ts+++ b/server/src/__tests__/routes/proxy-tools.test.ts@@ -1,16 +1,16 @@import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';import type { Express } from 'express';import { createApp } from '../../app.js';-import { initDb, getDb } from '../../db/index.js';+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';-async function request(app: Express, method: string, path: string, body?: any) {+async function request(app: Express, method: string, path: string, body?: any, headers: Record<string, string> = {}) {const server = app.listen(0);const addr = server.address() as any;const url = `http://127.0.0.1:${addr.port}${path}`;const res = await fetch(url, {method,- headers: body ? { 'Content-Type': 'application/json' } : {},+ headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...headers },body: body ? JSON.stringify(body) : undefined,});@@ -23,6 +23,10 @@ async function request(app: Express, method: string, path: string, body?: any) {return { status: res.status, body: json, headers: res.headers, raw: data };}+function authHeaders() {+ return { Authorization: `Bearer ${getUnifiedApiKey()}` };+}+describe('Proxy tool-calling support', () => {let app: Express;@@ -103,7 +107,7 @@ describe('Proxy tool-calling support', () => {},}],tool_choice: 'required',- });+ }, authHeaders());expect(status).toBe(200);expect(providerBody.tools).toHaveLength(1);@@ -163,7 +167,7 @@ describe('Proxy tool-calling support', () => {content: '{"temp_c":30}',},],- });+ }, authHeaders());expect(status).toBe(200);expect(providerBody.messages[1].role).toBe('assistant');diff --git a/server/src/app.ts b/server/src/app.tsindex 4b1a0d50..c3725e5e 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -14,8 +14,24 @@ import { errorHandler } from './middleware/errorHandler.js';const __dirname = path.dirname(fileURLToPath(import.meta.url));+const DEFAULT_DASHBOARD_ORIGINS = [+ 'http://localhost:5173',+ 'http://127.0.0.1:5173',+ 'http://[::1]:5173',+];++function getAllowedCorsOrigins() {+ const configuredOrigins = (process.env.DASHBOARD_ORIGINS ?? '')+ .split(',')+ .map(origin => origin.trim())+ .filter(Boolean);++ return new Set([...DEFAULT_DASHBOARD_ORIGINS, ...configuredOrigins]);+}+export function createApp() {const app = express();+ const allowedCorsOrigins = getAllowedCorsOrigins();// CSP intentionally disabled — the SPA bundles inline styles and the OG// image is loaded from the same origin; enabling helmet's default CSP@@ -24,7 +40,11 @@ export function createApp() {// stay disabled unless someone serves the proxy over HTTPS publicly// (which is also not a supported deployment — see README).app.use(helmet({ contentSecurityPolicy: false, hsts: false }));- app.use(cors());+ app.use(cors({+ origin(origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) {+ callback(null, !origin || allowedCorsOrigins.has(origin));+ },+ }));app.use(express.json({ limit: '1mb' }));// API routesdiff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 3c6e30fe..35c91974 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -182,24 +182,16 @@ function isRetryableError(err: any): boolean {proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {const start = Date.now();- // 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 || !timingSafeStringEqual(token, unifiedKey)) {- res.status(401).json({- error: { message: 'Invalid API key', type: 'authentication_error' },- });- return;- }+ // Authenticate with the unified API key for every proxy request, including+ // loopback callers. Browser pages can reach localhost, so socket locality is+ // not a reliable authorization boundary.+ const token = req.headers.authorization?.replace(/^Bearer\s+/i, '');+ const unifiedKey = getUnifiedApiKey();+ if (!token || !timingSafeStringEqual(token, unifiedKey)) {+ res.status(401).json({+ error: { message: 'Invalid API key', type: 'authentication_error' },+ });+ return;}// Validate request