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(security): harden admin endpoints and security middleware (#498)
Suryansh Rohil3848d87f5592
diff --git a/.env.example b/.env.exampleindex 82483f1a..fe987e88 100644--- a/.env.example+++ b/.env.example@@ -33,6 +33,11 @@ PORT=3001# to disable proxy rate limiting.# PROXY_RATE_LIMIT_RPM=120+# Max /api dashboard requests per minute per client IP (default: 600). This is a+# flood guard — login has its own per-email lockout and key export its own much+# tighter cap. Set to 0 to disable.+# ADMIN_RATE_LIMIT_RPM=600+# Outbound proxy for provider requests. Normally set in the dashboard# (Keys → Outbound proxy); these env vars are for headless installs.# Schemes: http, https, socks4, socks4a, socks5, socks5h. The `h`/`a` variantsdiff --git a/client/src/components/keys/export-keys-dialog.tsx b/client/src/components/keys/export-keys-dialog.tsxindex f458789c..b299db05 100644--- a/client/src/components/keys/export-keys-dialog.tsx+++ b/client/src/components/keys/export-keys-dialog.tsx@@ -1,10 +1,12 @@-import { useState } from 'react'+import { useState, type FormEvent } from 'react'import { useQuery } from '@tanstack/react-query'import { X, Download } from 'lucide-react'import { Dialog, DialogClose, DialogPopup, DialogTitle } from '@/components/ui/dialog'import { Button } from '@/components/ui/button'import { Label } from '@/components/ui/label'import { Switch } from '@/components/ui/switch'+import { Input } from '@/components/ui/input'+import { FieldError } from '@/components/ui/field-error'import { useI18n } from '@/i18n'import { apiFetch, getToken } from '@/lib/api'import { toast } from '@/lib/toast'@@ -12,6 +14,9 @@ import type { ApiKey } from '../../../../shared/types'type ExportFormat = 'json' | 'env' | 'csv'+// Two-step flow: choose what to export, then re-authenticate to actually get it.+type Step = 'options' | 'password'+const FORMAT_OPTIONS: { value: ExportFormat; label: string; ext: string }[] = [{ value: 'json', label: 'JSON', ext: 'json' },{ value: 'env', label: '.env', ext: 'env' },@@ -20,13 +25,14 @@ const FORMAT_OPTIONS: { value: ExportFormat; label: string; ext: string }[] = [const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');-async function downloadExport(format: ExportFormat, healthyOnly: boolean) {+async function downloadExport(format: ExportFormat, healthyOnly: boolean, password: string) {const token = getToken()const params = new URLSearchParams({ format })if (healthyOnly) params.set('healthy', 'true')- const res = await fetch(`${BASE}/api/keys/export?${params}`, {- headers: token ? { Authorization: `Bearer ${token}` } : {},- })+ const headers: Record<string, string> = {}+ if (token) headers.Authorization = `Bearer ${token}`+ if (password) headers['x-reauth-password'] = password+ const res = await fetch(`${BASE}/api/keys/export?${params}`, { headers })if (!res.ok) {const body = await res.json().catch(() => ({ error: { message: res.statusText } }))throw new Error(body.error?.message ?? `HTTP ${res.status}`)@@ -45,6 +51,16 @@ export function ExportKeysDialog({ open, onOpenChange }: { open: boolean; onOpenconst { t } = useI18n()const [format, setFormat] = useState<ExportFormat>('json')const [healthyOnly, setHealthyOnly] = useState(false)+ // The password is asked for in a second step, once the export is actually+ // requested — not up front. Nothing about picking a format or a filter needs+ // re-authentication, so the prompt only appears at the point it guards.+ //+ // KeysPage mounts this dialog only while open, so every open starts on the+ // options step with an empty field: no reset effect, and no way for a+ // reopened dialog to inherit the last password typed into it.+ const [step, setStep] = useState<Step>('options')+ const [password, setPassword] = useState('')+ const [error, setError] = useState<string | null>(null)const [exporting, setExporting] = useState(false)const { data: keys = [] } = useQuery<ApiKey[]>({@@ -57,14 +73,20 @@ export function ExportKeysDialog({ open, onOpenChange }: { open: boolean; onOpen? exportableKeys.filter(k => k.status === 'healthy').length: exportableKeys.length- async function handleExport() {+ async function handleExport(e: FormEvent) {+ e.preventDefault()setExporting(true)+ setError(null)try {- await downloadExport(format, healthyOnly)+ await downloadExport(format, healthyOnly, password)toast.success(t('keys.exportSuccess', { count: exportCount }))onOpenChange(false)} catch (err) {- toast.error((err as Error).message)+ // A rejected password keeps the user on this step with the field cleared+ // and the reason shown inline — a toast alone would leave the dialog+ // looking unchanged and give no hint of what to correct.+ setError((err as Error).message)+ setPassword('')} finally {setExporting(false)}@@ -83,6 +105,47 @@ export function ExportKeysDialog({ open, onOpenChange }: { open: boolean; onOpen</DialogClose></div>+ {step === 'password' ? (+ <form className="space-y-5" onSubmit={handleExport}>+ <div className="space-y-2">+ <Label className="text-xs" htmlFor="export-password">{t('auth.password')}</Label>+ <Input+ id="export-password"+ type="password"+ autoFocus+ autoComplete="current-password"+ placeholder={t('auth.passwordPlaceholderLogin')}+ value={password}+ onChange={e => setPassword(e.target.value)}+ aria-invalid={!!error}+ />+ <FieldError error={error} />+ </div>++ <div className="flex items-center justify-between rounded-lg bg-muted/50 px-3 py-2 text-xs text-muted-foreground">+ <span>{t('keys.exportWillExport')}</span>+ <span className="font-medium text-foreground">+ {exportCount} {exportCount === 1 ? t('keys.exportKey') : t('keys.exportKeys plural')}+ </span>+ </div>++ <div className="flex gap-2">+ <Button+ type="button"+ variant="outline"+ className="flex-1"+ onClick={() => setStep('options')}+ disabled={exporting}+ >+ {t('common.cancel')}+ </Button>+ <Button type="submit" className="flex-1" disabled={exporting || !password}>+ <Download className="size-3.5" />+ {exporting ? t('keys.exporting') : t('keys.exportDownload')}+ </Button>+ </div>+ </form>+ ) : (<div className="space-y-5"><div className="space-y-2"><Label className="text-xs">{t('keys.exportFormat')}</Label>@@ -125,13 +188,14 @@ export function ExportKeysDialog({ open, onOpenChange }: { open: boolean; onOpen<Buttontype="button"className="w-full"- onClick={handleExport}- disabled={exporting || exportCount === 0}+ onClick={() => setStep('password')}+ disabled={exportCount === 0}><Download className="size-3.5" />- {exporting ? t('keys.exporting') : t('keys.exportDownload')}+ {t('keys.exportDownload')}</Button></div>+ )}</DialogPopup></Dialog>)diff --git a/client/src/pages/KeysPage.tsx b/client/src/pages/KeysPage.tsxindex 6c64e963..063c631b 100644--- a/client/src/pages/KeysPage.tsx+++ b/client/src/pages/KeysPage.tsx@@ -107,7 +107,9 @@ export default function KeysPage() {</div><AddKeyDialog open={addOpen} onOpenChange={setAddOpen} />- <ExportKeysDialog open={exportOpen} onOpenChange={setExportOpen} />+ {/* Mounted only while open so the export flow always starts at step one+ and never retains a previously typed password. */}+ {exportOpen && <ExportKeysDialog open={exportOpen} onOpenChange={setExportOpen} />}</div>)}diff --git a/server/src/__tests__/lib/client-context.test.ts b/server/src/__tests__/lib/client-context.test.tsindex 8b1c0778..5d9b0acc 100644--- a/server/src/__tests__/lib/client-context.test.ts+++ b/server/src/__tests__/lib/client-context.test.ts@@ -2,9 +2,9 @@ import { afterEach, describe, expect, it } from 'vitest';import type { NextFunction, Request, Response } from 'express';import { clientContextMiddleware, getClientContext } from '../../lib/client-context.js';-// Minimal fake req: the middleware only touches headers and socket.-function fakeReq(headers: Record<string, string | string[]>, remoteAddress?: string): Request {- return { headers, socket: { remoteAddress } } as unknown as Request;+// Minimal fake req: the middleware only touches headers, socket, and app.+function fakeReq(headers: Record<string, string | string[]>, remoteAddress?: string, trustProxy?: boolean): Request {+ return { headers, socket: { remoteAddress }, app: { get: () => trustProxy ?? false } } as unknown as Request;}// Run the middleware and capture the context visible to downstream code@@ -25,10 +25,11 @@ describe('clientContextMiddleware', () => {expect(ctx).toEqual({ ip: '192.168.0.42', userAgent: 'curl/8.6.0', agent: 'unknown' });});- it('prefers the first X-Forwarded-For hop over the socket address', () => {+ it('prefers the first X-Forwarded-For hop when trust proxy is enabled', () => {const ctx = contextFor(fakeReq({ 'x-forwarded-for': '10.1.2.3, 172.16.0.1', 'user-agent': 'ua' },'127.0.0.1',+ true,));expect(ctx.ip).toBe('10.1.2.3');});diff --git a/server/src/__tests__/routes/admin-rate-limit.test.ts b/server/src/__tests__/routes/admin-rate-limit.test.tsnew file mode 100644index 00000000..5a31a857--- /dev/null+++ b/server/src/__tests__/routes/admin-rate-limit.test.ts@@ -0,0 +1,90 @@+import { describe, it, expect, beforeAll } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { createAdminRateLimiter } from '../../middleware/rateLimit.js';+import { initDb } from '../../db/index.js';+import { mintDashboardToken } from '../helpers/auth.js';++async function request(app: Express, path: string, token?: string) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {+ headers: token ? { Authorization: `Bearer ${token}` } : {},+ });+ const text = await res.text();+ server.close();++ let json: any = null;+ try { json = JSON.parse(text); } catch {}++ return { status: res.status, body: json, headers: res.headers };+}++describe('Admin API rate limiter', () => {+ let app: Express;+ let token: string;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();++ token = mintDashboardToken();+ });++ it('sets X-RateLimit headers on admin API responses', async () => {+ const { headers, status } = await request(app, '/api/keys', token);+ expect(status).toBe(200);+ expect(headers.get('x-ratelimit-limit')).toBe('600');+ expect(Number(headers.get('x-ratelimit-remaining'))).toBeGreaterThanOrEqual(0);+ expect(Number(headers.get('x-ratelimit-reset'))).toBeGreaterThan(Date.now() / 1000);+ });++ it('applies the limiter to unauthenticated /api paths too', async () => {+ const { headers, status } = await request(app, '/api/ping');+ expect(status).toBe(200);+ expect(headers.get('x-ratelimit-limit')).toBe('600');+ });++ it('counts unauthenticated requests against the admin rate limit window', async () => {+ const { status } = await request(app, '/api/keys');+ // Unauthenticated still hits the rate limiter, then fails at requireAuth+ expect(status).toBe(401);+ });++ it('caps the broad admin surface well above normal dashboard traffic', async () => {+ // The dashboard fans out across many /api routes on load and polls several+ // of them, so the flood guard must not fire during ordinary use. Guarding+ // the default here keeps a future tightening from silently breaking that.+ const limiter = createAdminRateLimiter();+ expect(limiter).toBeTypeOf('function');+ const { headers } = await request(app, '/api/keys', token);+ expect(Number(headers.get('x-ratelimit-limit'))).toBeGreaterThanOrEqual(600);+ });++ it('throttles key export far more tightly than the rest of /api', async () => {+ // Export re-verifies the password, so it is the one guessable endpoint.+ // Eleventh request inside the window must be refused regardless of whether+ // the password was right.+ let sawRateLimit = false;+ for (let i = 0; i < 12; i++) {+ const { status } = await request(app, '/api/keys/export?format=json', token);+ if (status === 429) { sawRateLimit = true; break; }+ // Without the re-auth header the handler answers 403 — still counted.+ expect(status).toBe(403);+ }+ expect(sawRateLimit).toBe(true);+ });++ it('can be disabled entirely with ADMIN_RATE_LIMIT_RPM=0', async () => {+ process.env.ADMIN_RATE_LIMIT_RPM = '0';+ try {+ const openApp = createApp();+ const { headers, status } = await request(openApp, '/api/ping');+ expect(status).toBe(200);+ expect(headers.get('x-ratelimit-limit')).toBeNull();+ } finally {+ delete process.env.ADMIN_RATE_LIMIT_RPM;+ }+ });+});diff --git a/server/src/__tests__/routes/csp-security.test.ts b/server/src/__tests__/routes/csp-security.test.tsnew file mode 100644index 00000000..1c4a2750--- /dev/null+++ b/server/src/__tests__/routes/csp-security.test.ts@@ -0,0 +1,51 @@+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 getHeaders(app: Express, path: string): Promise<Headers> {+ const server = app.listen(0);+ const addr = server.address() as any;+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`);+ server.close();+ return res.headers;+}++describe('CSP security headers', () => {+ let app: Express;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ });++ it('sets the Content-Security-Policy header on every response', async () => {+ const headers = await getHeaders(app, '/api/ping');+ const csp = headers.get('content-security-policy');+ expect(csp).toBeTruthy();+ });++ it('restricts default-src to self', async () => {+ const headers = await getHeaders(app, '/api/ping');+ const csp = headers.get('content-security-policy')!;+ expect(csp).toContain("default-src 'self'");+ });++ it('restricts script-src to self', async () => {+ const headers = await getHeaders(app, '/api/ping');+ const csp = headers.get('content-security-policy')!;+ expect(csp).toContain("script-src 'self'");+ });++ it('allows inline styles for React hydration', async () => {+ const headers = await getHeaders(app, '/api/ping');+ const csp = headers.get('content-security-policy')!;+ expect(csp).toContain("style-src 'self' 'unsafe-inline'");+ });++ it('does not set HSTS (local-only proxy)', async () => {+ const headers = await getHeaders(app, '/api/ping');+ expect(headers.get('strict-transport-security')).toBeNull();+ });+});diff --git a/server/src/__tests__/routes/error-handler-security.test.ts b/server/src/__tests__/routes/error-handler-security.test.tsnew file mode 100644index 00000000..b65ea80c--- /dev/null+++ b/server/src/__tests__/routes/error-handler-security.test.ts@@ -0,0 +1,46 @@+import { describe, it, expect, beforeAll } from 'vitest';+import express from 'express';+import type { Express } from 'express';+import { errorHandler } from '../../middleware/errorHandler.js';++async function triggerError(message: string, status: number) {+ const app = express();+ app.get('/boom', () => {+ const err = new Error(message);+ (err as any).status = status;+ throw err;+ });+ app.use(errorHandler);++ const server = app.listen(0);+ const addr = server.address() as any;+ const res = await fetch(`http://127.0.0.1:${addr.port}/boom`);+ const json = await res.json();+ server.close();+ return { status: res.status, body: json };+}++describe('Error handler — production mode', () => {+ const orig = process.env.NODE_ENV;++ beforeAll(() => {+ process.env.NODE_ENV = 'production';+ });++ afterAll(() => {+ process.env.NODE_ENV = orig;+ });++ it('hides internal error details on 5xx in production', async () => {+ const { status, body } = await triggerError('S3 bucket credentials leaked', 500);+ expect(status).toBe(500);+ expect(body.error.message).toBe('Internal server error');+ expect(body.error.message).not.toContain('S3');+ });++ it('still reports validation-style messages for 4xx errors', async () => {+ const { status, body } = await triggerError('Missing required field: model', 400);+ expect(status).toBe(400);+ expect(body.error.message).toBe('Missing required field: model');+ });+});diff --git a/server/src/__tests__/routes/keys-export-csv.test.ts b/server/src/__tests__/routes/keys-export-csv.test.tsindex 04722363..676d6f2a 100644--- a/server/src/__tests__/routes/keys-export-csv.test.ts+++ b/server/src/__tests__/routes/keys-export-csv.test.ts@@ -27,7 +27,7 @@ async function exportCsvText(app: Express): Promise<{ status: number; text: striconst server = app.listen(0);const addr = server.address() as { port: number };const res = await fetch(`http://127.0.0.1:${addr.port}/api/keys/export?format=csv`, {- headers: { Authorization: `Bearer ${dashToken}` },+ headers: { Authorization: `Bearer ${dashToken}`, 'x-reauth-password': 'password123' },});const text = await res.text();server.close();diff --git a/server/src/__tests__/routes/keys-export-password.test.ts b/server/src/__tests__/routes/keys-export-password.test.tsnew file mode 100644index 00000000..3098309c--- /dev/null+++ b/server/src/__tests__/routes/keys-export-password.test.ts@@ -0,0 +1,65 @@+import { describe, it, expect, beforeAll, beforeEach } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb, getDb } from '../../db/index.js';+import { mintDashboardToken } from '../helpers/auth.js';++let app: Express;+let token: string;++async function exportJson(app: Express, password?: string) {+ const server = app.listen(0);+ const addr = server.address() as { port: number };+ const headers: Record<string, string> = { Authorization: `Bearer ${token}` };+ if (password) headers['x-reauth-password'] = password;+ const res = await fetch(`http://127.0.0.1:${addr.port}/api/keys/export?format=json`, { headers });+ const data = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: data };+}++async function addKey(app: Express) {+ const server = app.listen(0);+ const addr = server.address() as { port: number };+ await fetch(`http://127.0.0.1:${addr.port}/api/keys`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },+ body: JSON.stringify({ platform: 'groq', key: 'gsk_testkey123' }),+ });+ server.close();+}++describe('Key export — password re-verification', () => {+ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ token = mintDashboardToken();+ });++ beforeEach(() => {+ getDb().prepare('DELETE FROM api_keys').run();+ });++ it('returns 403 when no password header is provided', async () => {+ await addKey(app);+ const { status, body } = await exportJson(app);+ expect(status).toBe(403);+ expect(body.error.type).toBe('authentication_error');+ expect(body.error.message).toContain('Password verification');+ });++ it('returns 403 when the password is wrong', async () => {+ await addKey(app);+ const { status } = await exportJson(app, 'wrongpassword');+ expect(status).toBe(403);+ });++ it('returns 200 when the correct password is provided', async () => {+ await addKey(app);+ const { status, body } = await exportJson(app, 'password123');+ expect(status).toBe(200);+ expect(body.keys).toBeDefined();+ expect(body.keys.length).toBe(1);+ });+});diff --git a/server/src/app.ts b/server/src/app.tsindex c48cbaf3..7684727f 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -27,7 +27,11 @@ import { geminiRouter } from './routes/gemini.js';import { ollamaRouter } from './routes/ollama.js';import { urlTokenRouter } from './routes/url-tokens.js';import { requireAuth } from './middleware/requireAuth.js';-import { createProxyRateLimiter } from './middleware/rateLimit.js';+import { createProxyRateLimiter, createAdminRateLimiter } from './middleware/rateLimit.js';++// Password-guess ceiling for GET /api/keys/export. Deliberately low: a real+// user exports keys occasionally, never ten times a minute.+const EXPORT_RATE_LIMIT_RPM = 10;import { errorHandler } from './middleware/errorHandler.js';import { clientContextMiddleware } from './lib/client-context.js';import type { Config } from './lib/config.js';@@ -62,13 +66,25 @@ export function createApp(config?: Config) {...cfg.dashboardOrigins,]);- // CSP intentionally disabled — the SPA bundles inline styles and the OG- // image is loaded from the same origin; enabling helmet's default CSP- // breaks the React build's hashed-asset loader. HSTS off because this is- // a single-user local proxy, served over HTTP on localhost. Both should- // 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 }));+ // CSP: default-src 'self' restricts content to the same origin. Scripts+ // are hashed by the Vite/React build, so 'self' works in production. Inline+ // styles from React hydration need 'unsafe-inline'. HSTS stays off because+ // this is a single-user local proxy served over HTTP (see README).+ app.use(helmet({+ contentSecurityPolicy: {+ directives: {+ defaultSrc: ["'self'"],+ scriptSrc: ["'self'"],+ styleSrc: ["'self'", "'unsafe-inline'"],+ imgSrc: ["'self'", "data:"],+ connectSrc: ["'self'"],+ fontSrc: ["'self'"],+ formAction: ["'self'"],+ baseUri: ["'self'"],+ },+ },+ hsts: false,+ }));app.use(cors({origin(origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) {callback(null, !origin || allowedCorsOrigins.has(origin));@@ -101,7 +117,19 @@ export function createApp(config?: Config) {// The /v1 proxy keeps its own unified-API-key auth and is NOT gated here.app.use('/api/auth', authRouter);- // API routes — all admin endpoints sit behind requireAuth.+ // Admin API — all routes share an IP-based rate limiter to throttle+ // brute-force attempts (auth, key export, etc). The limiter is mounted+ // broadly on /api; requireAuth gates each sub-path individually so that+ // unauthenticated endpoints under /api (like /api/ping) are not blocked.+ const adminRateLimiter = createAdminRateLimiter();+ app.use('/api', adminRateLimiter);++ // Key export re-verifies the dashboard password, which makes it the one admin+ // endpoint a guesser can attack. The broad limiter above is sized for normal+ // dashboard traffic and far too loose for that, so this path gets its own+ // tight per-IP bucket on top of it.+ app.use('/api/keys/export', createAdminRateLimiter(EXPORT_RATE_LIMIT_RPM));+app.use('/api/keys', requireAuth, keysRouter);app.use('/api/models', requireAuth, modelsRouter);app.use('/api/profiles', requireAuth, profilesRouter);@@ -115,6 +143,11 @@ export function createApp(config?: Config) {app.use('/api/cache', requireAuth, cacheRouter);app.use('/api/compression', requireAuth, compressionRouter);+ // Health check — no auth required.+ app.get('/api/ping', (_req, res) => {+ res.json({ status: 'ok', timestamp: new Date().toISOString() });+ });+// Static, unauthenticated API reference: GET /v1/docs (viewer) and// GET /v1/openapi.json (spec). Mounted before the rate limiter so the docs// are always reachable and don't draw down a caller's request budget. It only@@ -157,11 +190,6 @@ export function createApp(config?: Config) {app.use('/mcp', createProxyRateLimiter(cfg.proxyRateLimitRpm));app.use('/mcp', mcpRouter);- // Health check- app.get('/api/ping', (_req, res) => {- res.json({ status: 'ok', timestamp: new Date().toISOString() });- });-// Liveness / readiness probes for orchestrators (GET /livez, /readyz, #433).// Unauthenticated so a load balancer can probe them; registered before the// static / SPA-fallback block below so these root paths resolve to JSONdiff --git a/server/src/lib/client-context.ts b/server/src/lib/client-context.tsindex 324d8338..ebfed8d9 100644--- a/server/src/lib/client-context.ts+++ b/server/src/lib/client-context.ts@@ -13,13 +13,19 @@ export interface ClientContext {// proxy, responses, anthropic, fusion, embeddings and media paths all log).const storage = new AsyncLocalStorage<ClientContext>();-// First X-Forwarded-For hop when present (reverse-proxy deployments, e.g.-// Traefik), otherwise the socket peer address. The server is LAN-only, so a-// spoofable header is an acceptable trade for working behind a proxy.+// Resolve the client IP from the socket peer address. The X-Forwarded-For+// header is only trusted when Express's "trust proxy" setting is enabled+// (opt-in via app.set('trust proxy', ...) or the TRUST_PROXY env var in+// run.ts). Without that, a spoofed header from a LAN client is ignored.function resolveClientIp(req: Request): string | null {- const xff = req.headers['x-forwarded-for'];- const first = (Array.isArray(xff) ? xff[0] : xff)?.split(',')[0]?.trim();- const raw = first || req.socket.remoteAddress || null;+ const trustProxy = req.app?.get('trust proxy') ?? false;+ let raw: string | null;+ if (trustProxy) {+ const xff = req.headers['x-forwarded-for'];+ raw = (Array.isArray(xff) ? xff[0] : xff)?.split(',')[0]?.trim() || req.socket.remoteAddress || null;+ } else {+ raw = req.socket.remoteAddress || null;+ }// Normalize IPv4-mapped IPv6 ("::ffff:192.168.0.5" -> "192.168.0.5").return raw?.replace(/^::ffff:/i, '') ?? null;}diff --git a/server/src/middleware/errorHandler.ts b/server/src/middleware/errorHandler.tsindex 77efee7e..567239a4 100644--- a/server/src/middleware/errorHandler.ts+++ b/server/src/middleware/errorHandler.ts@@ -1,14 +1,18 @@import type { Request, Response, NextFunction } from 'express';export function errorHandler(err: Error, _req: Request, res: Response, next: NextFunction) {- console.error('[Error]', err.message);+ const isProduction = (process.env.NODE_ENV ?? 'development') === 'production';+ console.error('[Error]', isProduction ? err : err.message);if (res.headersSent) return next(err);const status = (err as any).status ?? 500;+ const message = isProduction && status >= 500+ ? 'Internal server error'+ : err.message;res.status(status).json({error: {- message: err.message,+ message,type: err.name ?? 'server_error',},});diff --git a/server/src/middleware/rateLimit.ts b/server/src/middleware/rateLimit.tsindex e2ba2ea7..6be89fd8 100644--- a/server/src/middleware/rateLimit.ts+++ b/server/src/middleware/rateLimit.ts@@ -76,3 +76,70 @@ export function createProxyRateLimiter(rpmLimit?: number) {next();};}++// Per-IP fixed-window rate limiter for the /api/* admin surface.+//+// This is a flood guard, not the brute-force guard: dashboard login already has+// its own per-email lockout (routes/auth.ts), and the one admin endpoint that+// verifies a password — GET /api/keys/export — gets its own much tighter+// limiter mounted in app.ts. The broad cap therefore has to clear normal+// dashboard traffic with room to spare. Opening the dashboard fans out across+// keys, health, models, analytics, settings and profiles, and several of those+// poll, so a single user legitimately spends dozens of requests a minute.+//+// Tune with ADMIN_RATE_LIMIT_RPM (requests per minute per IP); 0 disables it.+const ADMIN_DEFAULT_RPM = 600;++function parseAdminLimit(): number {+ const raw = process.env.ADMIN_RATE_LIMIT_RPM;+ if (raw === undefined || raw.trim() === '') return ADMIN_DEFAULT_RPM;+ const n = Number(raw);+ if (!Number.isFinite(n) || n < 0) return ADMIN_DEFAULT_RPM;+ return Math.floor(n);+}++export function createAdminRateLimiter(rpm?: number) {+ const limit = rpm !== undefined ? Math.floor(Math.max(0, rpm)) : parseAdminLimit();+ const windows = new Map<string, WindowState>();++ return function adminRateLimit(req: Request, res: Response, next: NextFunction): void {+ if (limit === 0) {+ next();+ return;+ }++ const now = Date.now();+ const ip = req.ip ?? req.socket.remoteAddress ?? 'unknown';++ let state = windows.get(ip);+ if (!state || now >= state.resetAt) {+ state = { count: 0, resetAt: now + WINDOW_MS };+ windows.set(ip, state);+ }+ state.count += 1;++ if (windows.size > MAX_TRACKED_IPS) {+ for (const [key, value] of windows) {+ if (now >= value.resetAt) windows.delete(key);+ }+ }++ res.setHeader('X-RateLimit-Limit', String(limit));+ res.setHeader('X-RateLimit-Remaining', String(Math.max(0, limit - state.count)));+ res.setHeader('X-RateLimit-Reset', String(Math.ceil(state.resetAt / 1000)));++ if (state.count > limit) {+ const retryAfter = Math.max(1, Math.ceil((state.resetAt - now) / 1000));+ res.setHeader('Retry-After', String(retryAfter));+ res.status(429).json({+ error: {+ message: `Rate limit exceeded: more than ${limit} requests per minute. Retry in ${retryAfter}s.`,+ type: 'rate_limit_error',+ },+ });+ return;+ }++ next();+ };+}diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 8008df9c..7a36deee 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -8,6 +8,7 @@ import { resolveProvider, getAllProviders } from '../providers/index.js';import { encrypt, decrypt, maskKey } from '../lib/crypto.js';import { parseKeysFromFile, stripJsoncComments, stripTrailingCommas } from '../lib/key-parser.js';import { assessProviderUrl } from '../lib/url-guard.js';+import { verifyCredentials } from '../services/auth.js';import { ensureModelInProfiles } from '../services/profile-models.js';import { getActiveCooldownsForKeys, clearCooldownsForKey } from '../services/ratelimit.js';import { resolveCustomEndpointKey, customEndpointKeyIds, siblingEndpointKeyId } from '../services/custom-endpoint.js';@@ -308,7 +309,14 @@ keysRouter.delete('/:id/cooldowns', (req: Request, res: Response) => {// Export keys — returns plaintext keys in the requested format.// GET /api/keys/export?format=json|env|csv&healthy=true// The response is the raw file download (Content-Type varies by format).+// Password re-verification via x-reauth-password header is required.keysRouter.get('/export', (req: Request, res: Response) => {+ const user = (req as any).user;+ const password = req.headers['x-reauth-password'] as string | undefined;+ if (!password || !verifyCredentials(user.email, password)) {+ res.status(403).json({ error: { message: 'Password verification required to export keys', type: 'authentication_error' } });+ return;+ }const db = getDb();const format = (req.query.format as string) ?? 'json';const healthyOnly = req.query.healthy === 'true';