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(analytics): record caller IP + User-Agent per request; "Recent calls" table (#474)
Myles Brophy84255d8e89be
diff --git a/.env.example b/.env.exampleindex f06fa2f6..f45827b4 100644--- a/.env.example+++ b/.env.example@@ -39,6 +39,11 @@ PORT=3001REQUEST_ANALYTICS_RETENTION_DAYS=90REQUEST_ANALYTICS_MAX_ROWS=100000+# Per-request caller identity (client IP + User-Agent) recorded into request+# analytics and shown in the dashboard's "Recent calls" table. Set to false+# to store nulls instead (aggregate analytics are unaffected).+# REQUEST_ANALYTICS_LOG_CLIENT=true+# Optional SQLite location. Useful on hosts where only one directory is mounted# persistently, or when you want to keep the DB outside server/data.# FREEAPI_DB_PATH=/app/server/data/freellmapi.dbdiff --git a/client/src/i18n/locales/en.json b/client/src/i18n/locales/en.jsonindex 6ef574ba..0be69031 100644--- a/client/src/i18n/locales/en.json+++ b/client/src/i18n/locales/en.json@@ -62,7 +62,8 @@"provider": "Provider","success": "Success","failures": "Failures",- "dismiss": "Dismiss"+ "dismiss": "Dismiss",+ "status": "Status"},"models": {"title": "Models",@@ -396,7 +397,11 @@"keyLabelFallback": "Key #{id}","errorsByProvider": "Errors by provider","recentErrors": "Recent errors",- "noErrors": "No errors"+ "noErrors": "No errors",+ "recentCalls": "Recent calls",+ "clientIp": "Client IP",+ "clientAgent": "Client app",+ "requestedModelHint": "Requested {model}, served by fallback"},"playground": {"title": "Playground",diff --git a/client/src/i18n/locales/es.json b/client/src/i18n/locales/es.jsonindex 810c339b..f8b33f6e 100644--- a/client/src/i18n/locales/es.json+++ b/client/src/i18n/locales/es.json@@ -62,7 +62,8 @@"provider": "Proveedor","success": "Aciertos","failures": "Fallos",- "dismiss": "Descartar"+ "dismiss": "Descartar",+ "status": "Estado"},"models": {"title": "Modelos",@@ -382,7 +383,11 @@"keyLabelFallback": "Clave n.º {id}","errorsByProvider": "Errores por proveedor","recentErrors": "Errores recientes",- "noErrors": "Sin errores"+ "noErrors": "Sin errores",+ "recentCalls": "Llamadas recientes",+ "clientIp": "IP del cliente",+ "clientAgent": "Aplicación cliente",+ "requestedModelHint": "Se solicitó {model}, servido por respaldo"},"playground": {"title": "Entorno de pruebas",diff --git a/client/src/i18n/locales/fr.json b/client/src/i18n/locales/fr.jsonindex 3840f862..30bda74c 100644--- a/client/src/i18n/locales/fr.json+++ b/client/src/i18n/locales/fr.json@@ -62,7 +62,8 @@"provider": "Fournisseur","success": "Réussite","failures": "Échecs",- "dismiss": "Fermer"+ "dismiss": "Fermer",+ "status": "Statut"},"models": {"title": "Modèles",@@ -382,7 +383,11 @@"keyLabelFallback": "Clé n° {id}","errorsByProvider": "Erreurs par fournisseur","recentErrors": "Erreurs récentes",- "noErrors": "Aucune erreur"+ "noErrors": "Aucune erreur",+ "recentCalls": "Appels récents",+ "clientIp": "IP du client",+ "clientAgent": "Application cliente",+ "requestedModelHint": "{model} demandé, servi par repli"},"playground": {"title": "Bac à sable",diff --git a/client/src/i18n/locales/it.json b/client/src/i18n/locales/it.jsonindex 33746736..8ced551c 100644--- a/client/src/i18n/locales/it.json+++ b/client/src/i18n/locales/it.json@@ -62,7 +62,8 @@"provider": "Fornitore","success": "Successo","failures": "Fallimenti",- "dismiss": "Chiudi"+ "dismiss": "Chiudi",+ "status": "Stato"},"models": {"title": "Modelli",@@ -382,7 +383,11 @@"keyLabelFallback": "Chiave n. {id}","errorsByProvider": "Errori per fornitore","recentErrors": "Errori recenti",- "noErrors": "Nessun errore"+ "noErrors": "Nessun errore",+ "recentCalls": "Chiamate recenti",+ "clientIp": "IP del client",+ "clientAgent": "App client",+ "requestedModelHint": "Richiesto {model}, servito dal fallback"},"playground": {"title": "Playground",diff --git a/client/src/i18n/locales/pt-BR.json b/client/src/i18n/locales/pt-BR.jsonindex 180720c6..0c312d8d 100644--- a/client/src/i18n/locales/pt-BR.json+++ b/client/src/i18n/locales/pt-BR.json@@ -62,7 +62,8 @@"provider": "Provedor","success": "Sucessos","failures": "Falhas",- "dismiss": "Dispensar"+ "dismiss": "Dispensar",+ "status": "Status"},"models": {"title": "Modelos",@@ -382,7 +383,11 @@"keyLabelFallback": "Chave nº {id}","errorsByProvider": "Erros por provedor","recentErrors": "Erros recentes",- "noErrors": "Sem erros"+ "noErrors": "Sem erros",+ "recentCalls": "Chamadas recentes",+ "clientIp": "IP do cliente",+ "clientAgent": "Aplicativo cliente",+ "requestedModelHint": "Solicitado {model}, servido por fallback"},"playground": {"title": "Playground",diff --git a/client/src/i18n/locales/zh-CN.json b/client/src/i18n/locales/zh-CN.jsonindex 8134a051..ff63760d 100644--- a/client/src/i18n/locales/zh-CN.json+++ b/client/src/i18n/locales/zh-CN.json@@ -62,7 +62,8 @@"provider": "提供方","success": "成功","failures": "失败",- "dismiss": "关闭"+ "dismiss": "关闭",+ "status": "状态"},"models": {"title": "模型",@@ -382,7 +383,11 @@"keyLabelFallback": "密钥 #{id}","errorsByProvider": "按提供方统计错误","recentErrors": "最近的错误",- "noErrors": "无错误"+ "noErrors": "无错误",+ "recentCalls": "最近调用",+ "clientIp": "客户端 IP",+ "clientAgent": "客户端应用",+ "requestedModelHint": "请求了 {model},由回退模型提供"},"playground": {"title": "试玩台",diff --git a/client/src/pages/AnalyticsPage.tsx b/client/src/pages/AnalyticsPage.tsxindex 308996e5..7ebb2c7a 100644--- a/client/src/pages/AnalyticsPage.tsx+++ b/client/src/pages/AnalyticsPage.tsx@@ -95,6 +95,35 @@ interface RecentErrorRow {createdAt: string}+interface RecentCallRow {+ id: number+ platform: string+ modelId: string+ requestedModel: string | null+ requestType: string+ status: string+ inputTokens: number+ outputTokens: number+ latencyMs: number+ error: string | null+ clientIp: string | null+ clientUserAgent: string | null+ createdAt: string+}++interface RecentCallsResponse {+ total: number+ rows: RecentCallRow[]+}++// First product token of the UA ("python-requests/2.32.3", "curl/8.6.0", …)+// is enough to tell callers apart in a narrow cell; full string on hover.+function shortUserAgent(ua: string | null): string {+ if (!ua) return '—'+ const first = ua.split(' ')[0]+ return first.length > 32 ? first.slice(0, 32) + '…' : first+}+function formatTokens(n?: number): string {if (!n) return '0'if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`@@ -185,6 +214,11 @@ export default function AnalyticsPage() {queryFn: () => apiFetch<ErrorDistribution>(`/api/analytics/error-distribution?range=${range}`),})+ const { data: recentCalls } = useQuery({+ queryKey: ['analytics', 'requests', range],+ queryFn: () => apiFetch<RecentCallsResponse>(`/api/analytics/requests?range=${range}&limit=100`),+ })+// Savings card shows ONE stable monthly figure regardless of the selected// range: the last-30-days data projected to a full month from its actual// span (a young install with 2 days of data shows 15x its 2-day total).@@ -443,6 +477,59 @@ export default function AnalyticsPage() {)}</Panel>+ {/* Recent calls: one line per proxied request with the caller's IP ++ user agent. All local clients share the unified key, so this is+ the only view that answers "who is hitting the router". */}+ <div className="lg:col-span-2">+ <Panel title={t('analytics.recentCalls')}>+ {!recentCalls?.rows?.length ? (+ <p className="text-sm text-muted-foreground text-center py-8">{t('common.noData')}</p>+ ) : (+ <div className="max-h-[420px] overflow-y-auto -mx-4">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="pl-4">{t('analytics.time')}</TableHead>+ <TableHead>{t('analytics.clientIp')}</TableHead>+ <TableHead>{t('analytics.clientAgent')}</TableHead>+ <TableHead>{t('common.model')}</TableHead>+ <TableHead>{t('common.provider')}</TableHead>+ <TableHead>{t('common.status')}</TableHead>+ <TableHead className="text-right">{t('analytics.inTokens')}</TableHead>+ <TableHead className="text-right">{t('analytics.outTokens')}</TableHead>+ <TableHead className="text-right pr-4">{t('analytics.latency')}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {recentCalls.rows.map((r) => (+ <TableRow key={r.id}>+ <TableCell className="pl-4 text-xs text-muted-foreground tabular-nums whitespace-nowrap">+ {formatSqliteUtcToLocalTime(r.createdAt, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' })}+ </TableCell>+ <TableCell className="text-xs font-medium tabular-nums">{r.clientIp ?? '—'}</TableCell>+ <TableCell className="text-xs text-muted-foreground" title={r.clientUserAgent ?? undefined}>+ {shortUserAgent(r.clientUserAgent)}+ </TableCell>+ <TableCell className="text-xs max-w-[220px] truncate" title={r.requestedModel && r.requestedModel !== r.modelId ? t('analytics.requestedModelHint', { model: r.requestedModel }) : undefined}>+ {r.modelId}+ {r.requestedModel && r.requestedModel !== r.modelId ? ' *' : ''}+ </TableCell>+ <TableCell className="text-xs text-muted-foreground">{r.platform}</TableCell>+ <TableCell className={`text-xs ${r.status === 'success' ? 'text-muted-foreground' : 'text-destructive'}`} title={r.error ?? undefined}>+ {r.status}+ </TableCell>+ <TableCell className="text-right text-xs tabular-nums">{formatTokens(r.inputTokens)}</TableCell>+ <TableCell className="text-right text-xs tabular-nums">{formatTokens(r.outputTokens)}</TableCell>+ <TableCell className="text-right text-xs tabular-nums pr-4">{r.latencyMs} ms</TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ )}+ </Panel>+ </div>+<div className="lg:col-span-2"><Panel title={t('analytics.perModelBreakdown')}>{byModel.length === 0 ? (diff --git a/package-lock.json b/package-lock.jsonindex 0f50e064..bbad2d0b 100644--- a/package-lock.json+++ b/package-lock.json@@ -12,6 +12,10 @@],"devDependencies": {"concurrently": "^9.1.2"+ },+ "engines": {+ "node": ">=20.18.0 <25.0.0",+ "npm": ">=10.0.0"}},"client": {@@ -53,6 +57,10 @@"typescript": "~6.0.2","typescript-eslint": "^8.58.0","vite": "^8.0.4"+ },+ "engines": {+ "node": ">=20.18.0 <25.0.0",+ "npm": ">=10.0.0"}},"node_modules/@babel/code-frame": {@@ -1238,6 +1246,7 @@"os": ["aix"],+ "peer": true,"engines": {"node": ">=18"}@@ -1254,6 +1263,7 @@"os": ["android"],+ "peer": true,"engines": {"node": ">=18"}@@ -1270,6 +1280,7 @@"os": ["android"],+ "peer": true,"engines": {"node": ">=18"}@@ -1286,6 +1297,7 @@"os": ["android"],+ "peer": true,"engines": {"node": ">=18"}@@ -1302,6 +1314,7 @@"os": ["darwin"],+ "peer": true,"engines": {"node": ">=18"}@@ -1318,6 +1331,7 @@"os": ["darwin"],+ "peer": true,"engines": {"node": ">=18"}@@ -1334,6 +1348,7 @@"os": ["freebsd"],+ "peer": true,"engines": {"node": ">=18"}@@ -1350,6 +1365,7 @@"os": ["freebsd"],+ "peer": true,"engines": {"node": ">=18"}@@ -1366,6 +1382,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=18"}@@ -1382,6 +1399,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=18"}@@ -1398,6 +1416,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=18"}@@ -1414,6 +1433,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=18"}@@ -1430,6 +1450,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=18"}@@ -1446,6 +1467,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=18"}@@ -1462,6 +1484,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=18"}@@ -1478,6 +1501,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=18"}@@ -1494,6 +1518,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=18"}@@ -1510,6 +1535,7 @@"os": ["netbsd"],+ "peer": true,"engines": {"node": ">=18"}@@ -1526,6 +1552,7 @@"os": ["netbsd"],+ "peer": true,"engines": {"node": ">=18"}@@ -1542,6 +1569,7 @@"os": ["openbsd"],+ "peer": true,"engines": {"node": ">=18"}@@ -1558,6 +1586,7 @@"os": ["openbsd"],+ "peer": true,"engines": {"node": ">=18"}@@ -1574,6 +1603,7 @@"os": ["openharmony"],+ "peer": true,"engines": {"node": ">=18"}@@ -1590,6 +1620,7 @@"os": ["sunos"],+ "peer": true,"engines": {"node": ">=18"}@@ -1606,6 +1637,7 @@"os": ["win32"],+ "peer": true,"engines": {"node": ">=18"}@@ -1622,6 +1654,7 @@"os": ["win32"],+ "peer": true,"engines": {"node": ">=18"}@@ -1638,6 +1671,7 @@"os": ["win32"],+ "peer": true,"engines": {"node": ">=18"}@@ -13199,6 +13233,10 @@"tsx": "^4.19.4","typescript": "^5.8.3","vitest": "^3.1.3"+ },+ "engines": {+ "node": ">=20.18.0 <25.0.0",+ "npm": ">=10.0.0"}},"server/node_modules/@types/node": {diff --git a/server/src/__tests__/db/migrate/roundtrip.test.ts b/server/src/__tests__/db/migrate/roundtrip.test.tsindex 95a70c17..1835da7e 100644--- a/server/src/__tests__/db/migrate/roundtrip.test.ts+++ b/server/src/__tests__/db/migrate/roundtrip.test.ts@@ -9,6 +9,7 @@ const CUSTOM_PROVIDER_MODALITIES_FILENAME = '20260627_000001_custom_provider_modconst CATALOG_MODEL_STATE_FILENAME = '20260627_000002_catalog_model_state.ts';const REQUEST_AGGREGATES_FILENAME = '20260628_120000_request_aggregates.ts';const GITHUB_GPT41_CONTEXT_FILENAME = '20260630_000001_github_gpt41_context.ts';+const REQUEST_CLIENT_INFO_FILENAME = '20260706_000001_request_client_info.ts';interface SchemaRow {type: string;@@ -64,6 +65,7 @@ describe('migration round trip', () => {CATALOG_MODEL_STATE_FILENAME,REQUEST_AGGREGATES_FILENAME,GITHUB_GPT41_CONTEXT_FILENAME,+ REQUEST_CLIENT_INFO_FILENAME,]);} finally {db.close();diff --git a/server/src/__tests__/lib/client-context.test.ts b/server/src/__tests__/lib/client-context.test.tsnew file mode 100644index 00000000..2a1ab95e--- /dev/null+++ b/server/src/__tests__/lib/client-context.test.ts@@ -0,0 +1,55 @@+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;+}++// Run the middleware and capture the context visible to downstream code+// (i.e. what logRequest would read inside the request's async scope).+function contextFor(req: Request): ReturnType<typeof getClientContext> {+ let seen = getClientContext();+ clientContextMiddleware(req, {} as Response, (() => { seen = getClientContext(); }) as NextFunction);+ return seen;+}++describe('clientContextMiddleware', () => {+ afterEach(() => {+ delete process.env.REQUEST_ANALYTICS_LOG_CLIENT;+ });++ it('captures the socket peer address and user agent', () => {+ const ctx = contextFor(fakeReq({ 'user-agent': 'curl/8.6.0' }, '192.168.0.42'));+ expect(ctx).toEqual({ ip: '192.168.0.42', userAgent: 'curl/8.6.0' });+ });++ it('prefers the first X-Forwarded-For hop over the socket address', () => {+ const ctx = contextFor(fakeReq(+ { 'x-forwarded-for': '10.1.2.3, 172.16.0.1', 'user-agent': 'ua' },+ '127.0.0.1',+ ));+ expect(ctx.ip).toBe('10.1.2.3');+ });++ it('normalizes IPv4-mapped IPv6 addresses', () => {+ const ctx = contextFor(fakeReq({}, '::ffff:192.168.0.5'));+ expect(ctx.ip).toBe('192.168.0.5');+ });++ it('truncates oversized user agents to 256 chars', () => {+ const ctx = contextFor(fakeReq({ 'user-agent': 'x'.repeat(1000) }, '1.2.3.4'));+ expect(ctx.userAgent).toHaveLength(256);+ });++ it('stores nulls when REQUEST_ANALYTICS_LOG_CLIENT=false', () => {+ process.env.REQUEST_ANALYTICS_LOG_CLIENT = 'false';+ const ctx = contextFor(fakeReq({ 'user-agent': 'curl/8.6.0' }, '192.168.0.42'));+ expect(ctx).toEqual({ ip: null, userAgent: null });+ });++ it('returns nulls outside any request scope', () => {+ expect(getClientContext()).toEqual({ ip: null, userAgent: null });+ });+});diff --git a/server/src/__tests__/routes/analytics-requests.test.ts b/server/src/__tests__/routes/analytics-requests.test.tsnew file mode 100644index 00000000..753b69a6--- /dev/null+++ b/server/src/__tests__/routes/analytics-requests.test.ts@@ -0,0 +1,93 @@+import { beforeAll, beforeEach, describe, expect, it } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { getDb, initDb } from '../../db/index.js';+import { logRequest } from '../../lib/request-log.js';+import { mintDashboardToken } from '../helpers/auth.js';++let dashToken = '';++async function request(app: Express, path: 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, {+ headers: { Authorization: `Bearer ${dashToken}` },+ });+ const data = await res.json().catch(() => null);+ server.close();++ return { status: res.status, body: data };+}++function insertCall(createdAt: string, clientIp: string | null, clientUserAgent: string | null, status = 'success') {+ getDb().prepare(`+ INSERT INTO requests (platform, model_id, status, input_tokens, output_tokens, latency_ms, error, created_at, client_ip, client_user_agent)+ VALUES ('test', 'test-model', ?, 10, 5, 42, NULL, ?, ?, ?)+ `).run(status, createdAt, clientIp, clientUserAgent);+}++describe('GET /api/analytics/requests', () => {+ let app: Express;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ dashToken = mintDashboardToken();+ });++ beforeEach(() => {+ getDb().prepare('DELETE FROM requests').run();+ });++ it('returns one row per call, newest first, with caller identity', async () => {+ insertCall('2026-07-06 10:00:00', '192.168.0.3', 'curl/8.6.0');+ insertCall('2026-07-06 11:00:00', '192.168.0.15', 'python-httpx/0.27');+ insertCall('2026-07-06 12:00:00', null, null);++ const { status, body } = await request(app, '/api/analytics/requests?range=7d');+ expect(status).toBe(200);+ expect(body.total).toBe(3);+ expect(body.rows.map((r: any) => r.clientIp)).toEqual([null, '192.168.0.15', '192.168.0.3']);+ expect(body.rows[1]).toMatchObject({+ platform: 'test',+ modelId: 'test-model',+ status: 'success',+ inputTokens: 10,+ outputTokens: 5,+ latencyMs: 42,+ clientIp: '192.168.0.15',+ clientUserAgent: 'python-httpx/0.27',+ });+ // created_at is emitted as ISO-8601 UTC so the dashboard localizes it.+ expect(body.rows[1].createdAt).toBe('2026-07-06T11:00:00Z');+ });++ it('paginates with limit/offset and clamps limit to 500', async () => {+ for (let i = 0; i < 5; i++) insertCall(`2026-07-06 0${i}:00:00`, '10.0.0.1', 'ua');++ const page = await request(app, '/api/analytics/requests?range=7d&limit=2&offset=2');+ expect(page.body.total).toBe(5);+ expect(page.body.rows).toHaveLength(2);+ expect(page.body.rows[0].createdAt).toBe('2026-07-06T02:00:00Z');++ const clamped = await request(app, '/api/analytics/requests?range=7d&limit=99999');+ expect(clamped.body.rows).toHaveLength(5);+ });++ it('records the request-scoped caller identity through logRequest', async () => {+ const { clientContextMiddleware } = await import('../../lib/client-context.js');+ const req = { headers: { 'user-agent': 'vitest-client/1.0' }, socket: { remoteAddress: '192.168.0.99' } } as any;+ await new Promise<void>(resolve => {+ clientContextMiddleware(req, {} as any, () => {+ logRequest('test', 'test-model', 1, 'success', 1, 2, 3, null);+ resolve();+ });+ });++ const row = getDb().prepare('SELECT client_ip, client_user_agent FROM requests ORDER BY id DESC LIMIT 1').get() as any;+ expect(row).toEqual({ client_ip: '192.168.0.99', client_user_agent: 'vitest-client/1.0' });+ });+});diff --git a/server/src/app.ts b/server/src/app.tsindex 371eaefb..d54fd12a 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -20,6 +20,7 @@ import { authRouter } from './routes/auth.js';import { requireAuth } from './middleware/requireAuth.js';import { createProxyRateLimiter } from './middleware/rateLimit.js';import { errorHandler } from './middleware/errorHandler.js';+import { clientContextMiddleware } from './lib/client-context.js';import type { Config } from './lib/config.js';import { loadConfig } from './lib/config.js';@@ -56,6 +57,10 @@ export function createApp(config?: Config) {// mid-conversation with an opaque 413. (#200)app.use(express.json({ limit: '10mb' }));+ // Caller identity (IP + User-Agent) for request analytics, carried in+ // AsyncLocalStorage so logRequest() can read it from any depth.+ app.use(clientContextMiddleware);+// Dashboard auth (#35): /api/auth/{status,setup,login} bootstrap without a// session; everything else under /api/* requires a logged-in dashboard user.// The /v1 proxy keeps its own unified-API-key auth and is NOT gated here.diff --git a/server/src/db/migrate/defaults.ts b/server/src/db/migrate/defaults.tsindex 0d88b52d..f3d60059 100644--- a/server/src/db/migrate/defaults.ts+++ b/server/src/db/migrate/defaults.ts@@ -4,6 +4,7 @@ import * as customProviderModalities from '../migrations/20260627_000001_custom_import * as catalogModelState from '../migrations/20260627_000002_catalog_model_state.js';import * as requestAggregates from '../migrations/20260628_120000_request_aggregates.js';import * as githubGpt41Context from '../migrations/20260630_000001_github_gpt41_context.js';+import * as requestClientInfo from '../migrations/20260706_000001_request_client_info.js';export interface MigrationModule {up(db: Database.Database): void;@@ -20,6 +21,7 @@ export const CUSTOM_PROVIDER_MODALITIES_FILENAME = '20260627_000001_custom_proviexport const CATALOG_MODEL_STATE_FILENAME = '20260627_000002_catalog_model_state.ts';export const REQUEST_AGGREGATES_FILENAME = '20260628_120000_request_aggregates.ts';export const GITHUB_GPT41_CONTEXT_FILENAME = '20260630_000001_github_gpt41_context.ts';+export const REQUEST_CLIENT_INFO_FILENAME = '20260706_000001_request_client_info.ts';export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: LEGACY_BASELINE_FILENAME, module: legacyBaseline },@@ -27,4 +29,5 @@ export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: CATALOG_MODEL_STATE_FILENAME, module: catalogModelState },{ filename: REQUEST_AGGREGATES_FILENAME, module: requestAggregates },{ filename: GITHUB_GPT41_CONTEXT_FILENAME, module: githubGpt41Context },+ { filename: REQUEST_CLIENT_INFO_FILENAME, module: requestClientInfo },];diff --git a/server/src/db/migrations/20260706_000001_request_client_info.ts b/server/src/db/migrations/20260706_000001_request_client_info.tsnew file mode 100644index 00000000..27c5b0af--- /dev/null+++ b/server/src/db/migrations/20260706_000001_request_client_info.ts@@ -0,0 +1,33 @@+import type Database from 'better-sqlite3';++/**+ * Record WHO made each proxied call. All local clients share the single+ * unified API key, so the key can't distinguish callers — the client IP+ * (plus User-Agent for tunneled clients that all arrive as loopback) is the+ * only per-caller signal available to the analytics "Recent calls" view.+ *+ * Guarded like the baseline's column adds: catalog-sync re-runs migrations+ * over a live schema, so ALTERs must be idempotent.+ */+function hasColumn(db: Database.Database, table: string, column: string): boolean {+ const columns = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];+ return columns.some(col => col.name === column);+}++export function up(db: Database.Database): void {+ if (!hasColumn(db, 'requests', 'client_ip')) {+ db.prepare('ALTER TABLE requests ADD COLUMN client_ip TEXT').run();+ }+ if (!hasColumn(db, 'requests', 'client_user_agent')) {+ db.prepare('ALTER TABLE requests ADD COLUMN client_user_agent TEXT').run();+ }+}++export function down(db: Database.Database): void {+ if (hasColumn(db, 'requests', 'client_user_agent')) {+ db.prepare('ALTER TABLE requests DROP COLUMN client_user_agent').run();+ }+ if (hasColumn(db, 'requests', 'client_ip')) {+ db.prepare('ALTER TABLE requests DROP COLUMN client_ip').run();+ }+}diff --git a/server/src/lib/client-context.ts b/server/src/lib/client-context.tsnew file mode 100644index 00000000..23740816--- /dev/null+++ b/server/src/lib/client-context.ts@@ -0,0 +1,43 @@+import { AsyncLocalStorage } from 'async_hooks';+import type { NextFunction, Request, Response } from 'express';++export interface ClientContext {+ ip: string | null;+ userAgent: string | null;+}++// Request-scoped caller identity, readable from anywhere below the middleware+// without threading parameters through every logRequest() call site (the chat+// 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.+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;+ // Normalize IPv4-mapped IPv6 ("::ffff:192.168.0.5" -> "192.168.0.5").+ return raw?.replace(/^::ffff:/i, '') ?? null;+}++// Privacy opt-out: REQUEST_ANALYTICS_LOG_CLIENT=false stores nulls instead of+// the caller's IP/UA. Read per request (not at module load) so tests and+// embedders can toggle it without re-importing.+function clientLoggingEnabled(): boolean {+ return process.env.REQUEST_ANALYTICS_LOG_CLIENT !== 'false';+}++export function clientContextMiddleware(req: Request, _res: Response, next: NextFunction): void {+ if (!clientLoggingEnabled()) {+ storage.run({ ip: null, userAgent: null }, next);+ return;+ }+ const ua = req.headers['user-agent'];+ storage.run({ ip: resolveClientIp(req), userAgent: typeof ua === 'string' ? ua.slice(0, 256) : null }, next);+}++export function getClientContext(): ClientContext {+ return storage.getStore() ?? { ip: null, userAgent: null };+}diff --git a/server/src/lib/request-log.ts b/server/src/lib/request-log.tsindex 27cb4817..bceafa76 100644--- a/server/src/lib/request-log.ts+++ b/server/src/lib/request-log.ts@@ -1,5 +1,6 @@import { getDb } from '../db/index.js';import { pruneRequestAnalytics } from '../services/request-retention.js';+import { getClientContext } from './client-context.js';type LogTx = ReturnType<typeof getDb>;@@ -56,11 +57,14 @@ export function logRequest() {try {const db = getDb();+ // Caller identity from the request-scoped context (set by the express+ // middleware); null when logging happens outside an HTTP request.+ const client = getClientContext();const tx = db.transaction(() => {const insert = db.prepare(`- INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms, error, ttfb_ms, requested_model)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)- `).run(platform, modelId, keyId, status, inputTokens, outputTokens, latencyMs, error, ttfbMs, requestedModel);+ INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms, error, ttfb_ms, requested_model, client_ip, client_user_agent)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `).run(platform, modelId, keyId, status, inputTokens, outputTokens, latencyMs, error, ttfbMs, requestedModel, client.ip, client.userAgent);const createdAt = db.prepare(`SELECT created_at FROM requests WHERE id = ?`).get(insert.lastInsertRowid) as { created_at: string } | undefined;const hour = hourKey(createdAt?.created_at ?? new Date().toISOString().slice(0, 19).replace('T', ' '));diff --git a/server/src/routes/analytics.ts b/server/src/routes/analytics.tsindex 7a073082..5ce69a2a 100644--- a/server/src/routes/analytics.ts+++ b/server/src/routes/analytics.ts@@ -457,3 +457,49 @@ analyticsRouter.get('/errors', (req: Request, res: Response) => {createdAt: r.created_at,})));});++// Recent calls — one row per proxied request, newest first, with the caller's+// IP and User-Agent (all local clients share the unified key, so client_ip is+// the only per-caller discriminator; UA disambiguates tunneled loopback calls).+// Reads the raw `requests` table, so history is bounded by the retention prune.+analyticsRouter.get('/requests', (req: Request, res: Response) => {+ const range = (req.query.range as string) ?? '7d';+ const since = getSinceTimestamp(range);+ const limit = Math.min(Math.max(parseInt(req.query.limit as string, 10) || 100, 1), 500);+ const offset = Math.max(parseInt(req.query.offset as string, 10) || 0, 0);+ const db = getDb();++ const total = (db.prepare(+ 'SELECT COUNT(*) as c FROM requests WHERE created_at >= ?'+ ).get(since) as { c: number }).c;++ const rows = db.prepare(`+ SELECT id, platform, model_id, requested_model, request_type, status,+ input_tokens, output_tokens, latency_ms, error,+ client_ip, client_user_agent,+ strftime('%Y-%m-%dT%H:%M:%SZ', created_at) as created_at_iso+ FROM requests+ WHERE created_at >= ?+ ORDER BY created_at DESC, id DESC+ LIMIT ? OFFSET ?+ `).all(since, limit, offset) as any[];++ res.json({+ total,+ rows: rows.map(r => ({+ id: r.id,+ platform: r.platform,+ modelId: r.model_id,+ requestedModel: r.requested_model,+ requestType: r.request_type,+ status: r.status,+ inputTokens: r.input_tokens,+ outputTokens: r.output_tokens,+ latencyMs: r.latency_ms,+ error: r.error,+ clientIp: r.client_ip,+ clientUserAgent: r.client_user_agent,+ createdAt: r.created_at_iso,+ })),+ });+});diff --git a/server/src/services/embeddings.ts b/server/src/services/embeddings.tsindex 4138513a..d3a3b284 100644--- a/server/src/services/embeddings.ts+++ b/server/src/services/embeddings.ts@@ -8,6 +8,7 @@// always works: with one provider it just uses that one, with several it gets// cross-provider redundancy for free.import { getDb, getSetting } from '../db/index.js';+import { getClientContext } from '../lib/client-context.js';import { decrypt } from '../lib/crypto.js';import { proxyFetch } from '../lib/proxy.js';@@ -234,10 +235,11 @@ function logEmbeddingRequest(error: string | null,): void {try {+ const client = getClientContext();getDb().prepare(`- INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms, error, request_type)- VALUES (?, ?, ?, ?, ?, 0, ?, ?, 'embedding')- `).run(row.platform, row.model_id, keyId, status, inputTokens, latencyMs, error);+ INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms, error, request_type, client_ip, client_user_agent)+ VALUES (?, ?, ?, ?, ?, 0, ?, ?, 'embedding', ?, ?)+ `).run(row.platform, row.model_id, keyId, status, inputTokens, latencyMs, error, client.ip, client.userAgent);} catch (e) {console.error('Failed to log embedding request:', e);}diff --git a/server/src/services/media.ts b/server/src/services/media.tsindex bed99141..4104e689 100644--- a/server/src/services/media.ts+++ b/server/src/services/media.ts@@ -8,6 +8,7 @@// published catalog and arrive via catalog-sync (premium on the live tier within// ~12h, free once each model is 30 days old) — never seeded by migrations.import { getDb } from '../db/index.js';+import { getClientContext } from '../lib/client-context.js';import { decrypt } from '../lib/crypto.js';import { proxyFetch } from '../lib/proxy.js';@@ -370,10 +371,11 @@ function resolveMediaChain(model: string | undefined, modality: MediaModality):function logMedia(row: MediaModelRow, keyId: number | null, status: 'success' | 'error', latencyMs: number, error: string | null): void {try {+ const client = getClientContext();getDb()- .prepare(`INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms, error, request_type)- VALUES (?, ?, ?, ?, 0, 0, ?, ?, ?)`)- .run(row.platform, row.model_id, keyId, status, latencyMs, error, row.modality);+ .prepare(`INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms, error, request_type, client_ip, client_user_agent)+ VALUES (?, ?, ?, ?, 0, 0, ?, ?, ?, ?, ?)`)+ .run(row.platform, row.model_id, keyId, status, latencyMs, error, row.modality, client.ip, client.userAgent);} catch (e) {console.error('Failed to log media request:', e);}