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(auth): email+password login gating the dashboard API (#35) (#146)
Tashfeenee8c2dfbd3d0
diff --git a/client/src/App.tsx b/client/src/App.tsxindex 1b31f6c2..5525c46d 100644--- a/client/src/App.tsx+++ b/client/src/App.tsx@@ -2,6 +2,8 @@ import { useEffect, useState } from 'react'import { BrowserRouter, Routes, Route, Navigate, NavLink } from 'react-router-dom'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { Button } from '@/components/ui/button'+import { AuthGate } from '@/components/auth-gate'+import { logout } from '@/lib/api'import KeysPage from '@/pages/KeysPage'import PlaygroundPage from '@/pages/PlaygroundPage'import FallbackPage from '@/pages/FallbackPage'@@ -70,33 +72,36 @@ function App() {return (<QueryClientProvider client={queryClient}><BrowserRouter basename={import.meta.env.BASE_URL}>- <div className="min-h-screen bg-background">- <header className="sticky top-0 z-40 bg-background/80 backdrop-blur border-b">- <div className="max-w-6xl mx-auto px-6 flex items-center">- <Brand />- <nav className="flex items-center gap-6 ml-10">- <NavItem to="/playground">Playground</NavItem>- <NavItem to="/keys">Keys</NavItem>- <NavItem to="/fallback">Fallback</NavItem>- <NavItem to="/analytics">Analytics</NavItem>- </nav>- <div className="ml-auto py-2">- <DarkModeToggle />+ <AuthGate>+ <div className="min-h-screen bg-background">+ <header className="sticky top-0 z-40 bg-background/80 backdrop-blur border-b">+ <div className="max-w-6xl mx-auto px-6 flex items-center">+ <Brand />+ <nav className="flex items-center gap-6 ml-10">+ <NavItem to="/playground">Playground</NavItem>+ <NavItem to="/keys">Keys</NavItem>+ <NavItem to="/fallback">Fallback</NavItem>+ <NavItem to="/analytics">Analytics</NavItem>+ </nav>+ <div className="ml-auto py-2 flex items-center gap-1">+ <DarkModeToggle />+ <Button variant="ghost" size="sm" onClick={() => logout()}>Sign out</Button>+ </div></div>- </div>- </header>- <main className="max-w-6xl mx-auto px-6 py-8">- <Routes>- <Route path="/" element={<Navigate to="/playground" replace />} />- <Route path="/playground" element={<PlaygroundPage />} />- <Route path="/keys" element={<KeysPage />} />- <Route path="/fallback" element={<FallbackPage />} />- <Route path="/analytics" element={<AnalyticsPage />} />- <Route path="/test" element={<Navigate to="/playground" replace />} />- <Route path="/health" element={<Navigate to="/keys" replace />} />- </Routes>- </main>- </div>+ </header>+ <main className="max-w-6xl mx-auto px-6 py-8">+ <Routes>+ <Route path="/" element={<Navigate to="/playground" replace />} />+ <Route path="/playground" element={<PlaygroundPage />} />+ <Route path="/keys" element={<KeysPage />} />+ <Route path="/fallback" element={<FallbackPage />} />+ <Route path="/analytics" element={<AnalyticsPage />} />+ <Route path="/test" element={<Navigate to="/playground" replace />} />+ <Route path="/health" element={<Navigate to="/keys" replace />} />+ </Routes>+ </main>+ </div>+ </AuthGate></BrowserRouter></QueryClientProvider>)diff --git a/client/src/components/auth-gate.tsx b/client/src/components/auth-gate.tsxnew file mode 100644index 00000000..e7526487--- /dev/null+++ b/client/src/components/auth-gate.tsx@@ -0,0 +1,129 @@+import { useEffect, useState, type ReactNode } from 'react'+import { useQuery, useQueryClient } from '@tanstack/react-query'+import { apiFetch, setToken, UNAUTHORIZED_EVENT } from '@/lib/api'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'++interface AuthStatus {+ needsSetup: boolean+ authenticated: boolean+ email: string | null+}++function Centered({ children }: { children: ReactNode }) {+ return (+ <div className="min-h-screen flex items-center justify-center bg-background px-4">+ <div className="w-full max-w-sm">{children}</div>+ </div>+ )+}++function AuthForm({ mode, onAuthed }: { mode: 'setup' | 'login'; onAuthed: () => void }) {+ const [email, setEmail] = useState('')+ const [password, setPassword] = useState('')+ const [error, setError] = useState('')+ const [busy, setBusy] = useState(false)++ const isSetup = mode === 'setup'++ async function submit(e: React.FormEvent) {+ e.preventDefault()+ setBusy(true)+ setError('')+ try {+ const res = await apiFetch<{ token: string }>(isSetup ? '/api/auth/setup' : '/api/auth/login', {+ method: 'POST',+ body: JSON.stringify({ email, password }),+ })+ setToken(res.token)+ onAuthed()+ } catch (err) {+ setError((err as Error).message)+ } finally {+ setBusy(false)+ }+ }++ return (+ <Centered>+ <div className="mb-6 flex items-center gap-2">+ <span className="inline-block size-2 rounded-full bg-foreground" />+ <span className="font-semibold tracking-tight text-sm">FreeLLMAPI</span>+ </div>+ <div className="rounded-lg border bg-card p-6">+ <h1 className="text-base font-medium">{isSetup ? 'Create your account' : 'Sign in'}</h1>+ <p className="text-xs text-muted-foreground mt-1 mb-4">+ {isSetup+ ? 'Set the email and password that will protect this dashboard.'+ : 'Sign in to manage your keys, routing, and analytics.'}+ </p>+ <form onSubmit={submit} className="space-y-3">+ <div className="space-y-1.5">+ <Label className="text-xs" htmlFor="auth-email">Email</Label>+ <Input+ id="auth-email"+ type="email"+ autoComplete="username"+ value={email}+ onChange={e => setEmail(e.target.value)}+ placeholder="[email protected]"+ />+ </div>+ <div className="space-y-1.5">+ <Label className="text-xs" htmlFor="auth-password">Password</Label>+ <Input+ id="auth-password"+ type="password"+ autoComplete={isSetup ? 'new-password' : 'current-password'}+ value={password}+ onChange={e => setPassword(e.target.value)}+ placeholder={isSetup ? 'at least 8 characters' : 'your password'}+ />+ </div>+ {error && <p className="text-destructive text-xs">{error}</p>}+ <Button type="submit" className="w-full" disabled={busy || !email || !password}>+ {busy ? (isSetup ? 'Creating…' : 'Signing in…') : isSetup ? 'Create account' : 'Sign in'}+ </Button>+ </form>+ </div>+ </Centered>+ )+}++export function AuthGate({ children }: { children: ReactNode }) {+ const queryClient = useQueryClient()+ const { data, isLoading, isError, refetch } = useQuery<AuthStatus>({+ queryKey: ['auth-status'],+ queryFn: () => apiFetch('/api/auth/status'),+ retry: false,+ })++ useEffect(() => {+ const handler = () => { refetch() }+ window.addEventListener(UNAUTHORIZED_EVENT, handler)+ return () => window.removeEventListener(UNAUTHORIZED_EVENT, handler)+ }, [refetch])++ function onAuthed() {+ // New session: drop any cached (unauthenticated) data and re-check status.+ queryClient.invalidateQueries()+ refetch()+ }++ if (isLoading) return <Centered><p className="text-sm text-muted-foreground text-center">Loading…</p></Centered>+ if (isError || !data) {+ return (+ <Centered>+ <div className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2.5 text-xs text-destructive">+ Can't reach the server. Make sure the backend is running (<code className="font-mono">npm run dev</code>).+ </div>+ </Centered>+ )+ }++ if (data.needsSetup) return <AuthForm mode="setup" onAuthed={onAuthed} />+ if (!data.authenticated) return <AuthForm mode="login" onAuthed={onAuthed} />++ return <>{children}</>+}diff --git a/client/src/lib/api.ts b/client/src/lib/api.tsindex a4465412..4789a54e 100644--- a/client/src/lib/api.ts+++ b/client/src/lib/api.ts@@ -1,13 +1,44 @@const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');+const TOKEN_KEY = 'freellmapi_dashboard_token';++// Dashboard session token (#35). Stored in localStorage; sent as a Bearer on+// every /api request and cleared on a 401.+export function getToken(): string | null {+ try { return localStorage.getItem(TOKEN_KEY); } catch { return null; }+}+export function setToken(token: string): void {+ try { localStorage.setItem(TOKEN_KEY, token); } catch { /* ignore */ }+}+export function clearToken(): void {+ try { localStorage.removeItem(TOKEN_KEY); } catch { /* ignore */ }+}++export const UNAUTHORIZED_EVENT = 'freellmapi:unauthorized';export async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {+ const token = getToken();const res = await fetch(`${BASE}${path}`, {- headers: { 'Content-Type': 'application/json', ...options?.headers },+ headers: {+ 'Content-Type': 'application/json',+ ...(token ? { Authorization: `Bearer ${token}` } : {}),+ ...options?.headers,+ },...options,});+ if (res.status === 401) {+ // Session missing/expired — drop the token and let the AuthGate re-render.+ clearToken();+ window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT));+ }if (!res.ok) {const body = await res.json().catch(() => ({ error: { message: res.statusText } }));throw new Error(body.error?.message ?? `HTTP ${res.status}`);}return res.json();}++export async function logout(): Promise<void> {+ try { await apiFetch('/api/auth/logout', { method: 'POST' }); } catch { /* ignore */ }+ clearToken();+ window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT));+}diff --git a/server/src/__tests__/helpers/auth.ts b/server/src/__tests__/helpers/auth.tsnew file mode 100644index 00000000..f445e4e2--- /dev/null+++ b/server/src/__tests__/helpers/auth.ts@@ -0,0 +1,14 @@+import { createUser, createSession } from '../../services/auth.js';++// Dashboard /api/* routes are gated by requireAuth (#35). Tests mint a session+// token once (after initDb) and attach it to gated requests.++export function mintDashboardToken(email = '[email protected]'): string {+ const user = createUser(email, 'password123');+ return createSession(user.userId);+}++// Gated = under /api/ but not the public bootstrap routes (/api/auth/*, /api/ping).+export function isGatedApiPath(path: string): boolean {+ return path.startsWith('/api/') && !path.startsWith('/api/auth') && path !== '/api/ping';+}diff --git a/server/src/__tests__/integration/full-flow.test.ts b/server/src/__tests__/integration/full-flow.test.tsindex 9ce9cc2f..0265b774 100644--- a/server/src/__tests__/integration/full-flow.test.ts+++ b/server/src/__tests__/integration/full-flow.test.ts@@ -2,6 +2,9 @@ import { describe, it, expect, beforeAll, vi } from 'vitest';import type { Express } from 'express';import { createApp } from '../../app.js';import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';+import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';++let dashToken = '';async function req(app: Express, method: string, path: string, body?: any, headers: Record<string, string> = {}) {const server = app.listen(0);@@ -10,7 +13,7 @@ async function req(app: Express, method: string, path: string, body?: any, headeconst res = await fetch(url, {method,- headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...headers },+ headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...(isGatedApiPath(path) && !('Authorization' in headers) ? { Authorization: `Bearer ${dashToken}` } : {}), ...headers },body: body ? JSON.stringify(body) : undefined,});@@ -34,6 +37,7 @@ describe('Full Integration Flow', () => {process.env.ENCRYPTION_KEY = '0'.repeat(64);initDb(':memory:');app = createApp();+ dashToken = mintDashboardToken();// Cleanconst db = getDb();db.prepare('DELETE FROM api_keys').run();diff --git a/server/src/__tests__/routes/auth.test.ts b/server/src/__tests__/routes/auth.test.tsnew file mode 100644index 00000000..9a43d177--- /dev/null+++ b/server/src/__tests__/routes/auth.test.ts@@ -0,0 +1,100 @@+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 call(app: Express, method: string, path: string, body?: any, 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}`, {+ method,+ headers: {+ ...(body ? { 'Content-Type': 'application/json' } : {}),+ ...(token ? { Authorization: `Bearer ${token}` } : {}),+ },+ body: body ? JSON.stringify(body) : undefined,+ });+ const data = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: data };+}++// Tests run in definition order against one shared in-memory DB, mirroring the+// real bootstrap sequence: needs-setup → setup → gated access → login → logout.+describe('Dashboard auth (#35)', () => {+ let app: Express;+ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ });++ it('reports needsSetup before any account exists', async () => {+ const { body } = await call(app, 'GET', '/api/auth/status');+ expect(body).toMatchObject({ needsSetup: true, authenticated: false });+ });++ it('gates /api/* routes with 401 when unauthenticated', async () => {+ expect((await call(app, 'GET', '/api/keys')).status).toBe(401);+ expect((await call(app, 'GET', '/api/fallback')).status).toBe(401);+ expect((await call(app, 'GET', '/api/settings/api-key')).status).toBe(401);+ });++ it('leaves /api/ping and the /v1 proxy reachable without a dashboard session', async () => {+ expect((await call(app, 'GET', '/api/ping')).status).toBe(200);+ // /v1 has its own (unified-key) auth, so it 401s for a different reason —+ // the point is it is not gated by the dashboard session middleware.+ const proxy = await call(app, 'POST', '/v1/chat/completions', { messages: [{ role: 'user', content: 'x' }] });+ expect(proxy.body.error.type).toBe('authentication_error');+ });++ it('rejects weak setup credentials', async () => {+ expect((await call(app, 'POST', '/api/auth/setup', { email: 'bad', password: 'x' })).status).toBe(400);+ expect((await call(app, 'POST', '/api/auth/setup', { email: '[email protected]', password: 'short' })).status).toBe(400);+ });++ let token = '';+ it('creates the first account on setup and returns a working token', async () => {+ const { status, body } = await call(app, 'POST', '/api/auth/setup', { email: '[email protected]', password: 'supersecret' });+ expect(status).toBe(201);+ expect(typeof body.token).toBe('string');+ token = body.token;+ expect((await call(app, 'GET', '/api/keys', undefined, token)).status).toBe(200);+ });++ it('refuses a second setup once an account exists', async () => {+ const { status } = await call(app, 'POST', '/api/auth/setup', { email: '[email protected]', password: 'supersecret' });+ expect(status).toBe(409);+ });++ it('logs in with correct credentials and rejects wrong ones', async () => {+ const ok = await call(app, 'POST', '/api/auth/login', { email: '[email protected]', password: 'supersecret' });+ expect(ok.status).toBe(200);+ expect(typeof ok.body.token).toBe('string');++ const bad = await call(app, 'POST', '/api/auth/login', { email: '[email protected]', password: 'wrongpassword' });+ expect(bad.status).toBe(401);+ expect(bad.body.error.type).toBe('authentication_error');+ });++ it('reports authenticated status with a valid token', async () => {+ const { body } = await call(app, 'GET', '/api/auth/status', undefined, token);+ expect(body).toMatchObject({ needsSetup: false, authenticated: true, email: '[email protected]' });+ });++ it('invalidates the token on logout', async () => {+ const login = await call(app, 'POST', '/api/auth/login', { email: '[email protected]', password: 'supersecret' });+ const t = login.body.token;+ expect((await call(app, 'GET', '/api/keys', undefined, t)).status).toBe(200);+ await call(app, 'POST', '/api/auth/logout', {}, t);+ expect((await call(app, 'GET', '/api/keys', undefined, t)).status).toBe(401);+ });++ it('locks out after repeated failed attempts (separate email, no real account)', async () => {+ const creds = { email: '[email protected]', password: 'guessguess' };+ for (let i = 0; i < 5; i++) {+ expect((await call(app, 'POST', '/api/auth/login', creds)).status).toBe(401);+ }+ expect((await call(app, 'POST', '/api/auth/login', creds)).status).toBe(429);+ });+});diff --git a/server/src/__tests__/routes/custom-provider.test.ts b/server/src/__tests__/routes/custom-provider.test.tsindex bae7163f..e3f59c35 100644--- a/server/src/__tests__/routes/custom-provider.test.ts+++ b/server/src/__tests__/routes/custom-provider.test.ts@@ -4,13 +4,19 @@ import { createApp } from '../../app.js';import { initDb, getDb } from '../../db/index.js';import { routeRequest } from '../../services/router.js';import { resolveProvider, getProvider } from '../../providers/index.js';+import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';++let dashToken = '';async function post(app: Express, path: string, body: any) {const server = app.listen(0);const addr = server.address() as any;const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {method: 'POST',- headers: { 'Content-Type': 'application/json' },+ headers: {+ 'Content-Type': 'application/json',+ ...(isGatedApiPath(path) ? { Authorization: `Bearer ${dashToken}` } : {}),+ },body: JSON.stringify(body),});const data = await res.json().catch(() => null);@@ -21,7 +27,9 @@ async function post(app: Express, path: string, body: any) {async function get(app: Express, path: string) {const server = app.listen(0);const addr = server.address() as any;- const res = await fetch(`http://127.0.0.1:${addr.port}${path}`);+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {+ headers: isGatedApiPath(path) ? { Authorization: `Bearer ${dashToken}` } : {},+ });const data = await res.json().catch(() => null);server.close();return { status: res.status, body: data };@@ -52,6 +60,7 @@ describe('POST /api/keys/custom (#117)', () => {process.env.ENCRYPTION_KEY = '0'.repeat(64);initDb(':memory:');app = createApp();+ dashToken = mintDashboardToken();});it('rejects an invalid base URL', async () => {diff --git a/server/src/__tests__/routes/fallback.test.ts b/server/src/__tests__/routes/fallback.test.tsindex 66ba468f..563a043e 100644--- a/server/src/__tests__/routes/fallback.test.ts+++ b/server/src/__tests__/routes/fallback.test.ts@@ -2,6 +2,9 @@ import { describe, it, expect, beforeAll } from 'vitest';import type { Express } from 'express';import { createApp } from '../../app.js';import { initDb } from '../../db/index.js';+import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';++let dashToken = '';async function request(app: Express, method: string, path: string, body?: any) {const server = app.listen(0);@@ -10,7 +13,10 @@ async function request(app: Express, method: string, path: string, body?: any) {const res = await fetch(url, {method,- headers: body ? { 'Content-Type': 'application/json' } : {},+ headers: {+ ...(body ? { 'Content-Type': 'application/json' } : {}),+ ...(isGatedApiPath(path) ? { Authorization: `Bearer ${dashToken}` } : {}),+ },body: body ? JSON.stringify(body) : undefined,});@@ -26,6 +32,7 @@ describe('Fallback API', () => {process.env.ENCRYPTION_KEY = '0'.repeat(64);initDb(':memory:');app = createApp();+ dashToken = mintDashboardToken();});it('GET /api/fallback returns fallback chain', async () => {diff --git a/server/src/__tests__/routes/keys.test.ts b/server/src/__tests__/routes/keys.test.tsindex dbcdfdbe..db8caeed 100644--- a/server/src/__tests__/routes/keys.test.ts+++ b/server/src/__tests__/routes/keys.test.ts@@ -2,6 +2,9 @@ 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, isGatedApiPath } from '../helpers/auth.js';++let dashToken = '';async function request(app: Express, method: string, path: string, body?: any) {const server = app.listen(0);@@ -10,7 +13,10 @@ async function request(app: Express, method: string, path: string, body?: any) {const res = await fetch(url, {method,- headers: body ? { 'Content-Type': 'application/json' } : {},+ headers: {+ ...(body ? { 'Content-Type': 'application/json' } : {}),+ ...(isGatedApiPath(path) ? { Authorization: `Bearer ${dashToken}` } : {}),+ },body: body ? JSON.stringify(body) : undefined,});@@ -26,6 +32,7 @@ describe('Keys API', () => {process.env.ENCRYPTION_KEY = '0'.repeat(64);initDb(':memory:');app = createApp();+ dashToken = mintDashboardToken();});beforeEach(() => {diff --git a/server/src/__tests__/routes/proxy-array-content.test.ts b/server/src/__tests__/routes/proxy-array-content.test.tsindex c9605769..4c8a8eea 100644--- a/server/src/__tests__/routes/proxy-array-content.test.ts+++ b/server/src/__tests__/routes/proxy-array-content.test.ts@@ -2,6 +2,9 @@ import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'viteimport type { Express } from 'express';import { createApp } from '../../app.js';import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';+import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';++let dashToken = '';async function request(app: Express, method: string, path: string, body?: any, headers: Record<string, string> = {}) {const server = app.listen(0);@@ -10,7 +13,7 @@ async function request(app: Express, method: string, path: string, body?: any, hconst res = await fetch(url, {method,- headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...headers },+ headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...(isGatedApiPath(path) && !('Authorization' in headers) ? { Authorization: `Bearer ${dashToken}` } : {}), ...headers },body: body ? JSON.stringify(body) : undefined,});@@ -34,6 +37,7 @@ describe('OpenAI multimodal array content', () => {process.env.ENCRYPTION_KEY = '0'.repeat(64);initDb(':memory:');app = createApp();+ dashToken = mintDashboardToken();});beforeEach(async () => {diff --git a/server/src/__tests__/routes/proxy-auto-model.test.ts b/server/src/__tests__/routes/proxy-auto-model.test.tsindex c878c721..fac241d7 100644--- a/server/src/__tests__/routes/proxy-auto-model.test.ts+++ b/server/src/__tests__/routes/proxy-auto-model.test.ts@@ -2,6 +2,9 @@ import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'viteimport type { Express } from 'express';import { createApp } from '../../app.js';import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';+import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';++let dashToken = '';async function request(app: Express, method: string, path: string, body?: any, headers: Record<string, string> = {}) {const server = app.listen(0);@@ -10,7 +13,7 @@ async function request(app: Express, method: string, path: string, body?: any, hconst res = await fetch(url, {method,- headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...headers },+ headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...(isGatedApiPath(path) && !('Authorization' in headers) ? { Authorization: `Bearer ${dashToken}` } : {}), ...headers },body: body ? JSON.stringify(body) : undefined,});@@ -34,6 +37,7 @@ describe('Virtual "auto" model', () => {process.env.ENCRYPTION_KEY = '0'.repeat(64);initDb(':memory:');app = createApp();+ dashToken = mintDashboardToken();});beforeEach(async () => {diff --git a/server/src/__tests__/routes/proxy-tools.test.ts b/server/src/__tests__/routes/proxy-tools.test.tsindex 0d91f2f8..4493c43e 100644--- a/server/src/__tests__/routes/proxy-tools.test.ts+++ b/server/src/__tests__/routes/proxy-tools.test.ts@@ -2,6 +2,9 @@ import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'viteimport type { Express } from 'express';import { createApp } from '../../app.js';import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';+import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';++let dashToken = '';async function request(app: Express, method: string, path: string, body?: any, headers: Record<string, string> = {}) {const server = app.listen(0);@@ -10,7 +13,7 @@ async function request(app: Express, method: string, path: string, body?: any, hconst res = await fetch(url, {method,- headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...headers },+ headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...(isGatedApiPath(path) && !('Authorization' in headers) ? { Authorization: `Bearer ${dashToken}` } : {}), ...headers },body: body ? JSON.stringify(body) : undefined,});@@ -34,6 +37,7 @@ describe('Proxy tool-calling support', () => {process.env.ENCRYPTION_KEY = '0'.repeat(64);initDb(':memory:');app = createApp();+ dashToken = mintDashboardToken();});beforeEach(async () => {diff --git a/server/src/app.ts b/server/src/app.tsindex 718b1fbf..a2ab60e3 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -11,6 +11,8 @@ import { fallbackRouter } from './routes/fallback.js';import { analyticsRouter } from './routes/analytics.js';import { healthRouter } from './routes/health.js';import { settingsRouter } from './routes/settings.js';+import { authRouter } from './routes/auth.js';+import { requireAuth } from './middleware/requireAuth.js';import { errorHandler } from './middleware/errorHandler.js';const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -48,13 +50,18 @@ export function createApp() {}));app.use(express.json({ limit: '1mb' }));- // API routes- app.use('/api/keys', keysRouter);- app.use('/api/models', modelsRouter);- app.use('/api/fallback', fallbackRouter);- app.use('/api/analytics', analyticsRouter);- app.use('/api/health', healthRouter);- app.use('/api/settings', settingsRouter);+ // 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.+ app.use('/api/auth', authRouter);++ // API routes — all admin endpoints sit behind requireAuth.+ app.use('/api/keys', requireAuth, keysRouter);+ app.use('/api/models', requireAuth, modelsRouter);+ app.use('/api/fallback', requireAuth, fallbackRouter);+ app.use('/api/analytics', requireAuth, analyticsRouter);+ app.use('/api/health', requireAuth, healthRouter);+ app.use('/api/settings', requireAuth, settingsRouter);// OpenAI-compatible proxyapp.use('/v1', proxyRouter);diff --git a/server/src/db/index.ts b/server/src/db/index.tsindex 33a109bd..8d4273df 100644--- a/server/src/db/index.ts+++ b/server/src/db/index.ts@@ -135,6 +135,22 @@ function createTables(db: Database.Database) {value TEXT NOT NULL);+ -- Dashboard accounts (email + password) gating the /api/* admin surface (#35).+ CREATE TABLE IF NOT EXISTS users (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ email TEXT NOT NULL UNIQUE,+ password_hash TEXT NOT NULL,+ created_at TEXT NOT NULL DEFAULT (datetime('now'))+ );++ CREATE TABLE IF NOT EXISTS sessions (+ token_hash TEXT PRIMARY KEY,+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ expires_at_ms INTEGER NOT NULL,+ created_at TEXT NOT NULL DEFAULT (datetime('now'))+ );+ CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);+CREATE INDEX IF NOT EXISTS idx_requests_created_at ON requests(created_at);CREATE INDEX IF NOT EXISTS idx_requests_platform ON requests(platform);CREATE INDEX IF NOT EXISTS idx_rate_limit_usage_lookup ON rate_limit_usage(platform, model_id, key_id, kind, created_at_ms);diff --git a/server/src/lib/password.ts b/server/src/lib/password.tsnew file mode 100644index 00000000..2adebef2--- /dev/null+++ b/server/src/lib/password.ts@@ -0,0 +1,27 @@+import crypto from 'crypto';++// Password hashing with Node's built-in scrypt (no external dependency).+// Stored format: `scrypt$<saltHex>$<hashHex>`.+const KEYLEN = 64;+const SALT_BYTES = 16;++export function hashPassword(password: string): string {+ const salt = crypto.randomBytes(SALT_BYTES);+ const hash = crypto.scryptSync(password, salt, KEYLEN);+ return `scrypt$${salt.toString('hex')}$${hash.toString('hex')}`;+}++export function verifyPassword(password: string, stored: string): boolean {+ const parts = stored.split('$');+ if (parts.length !== 3 || parts[0] !== 'scrypt') return false;+ const salt = Buffer.from(parts[1], 'hex');+ const expected = Buffer.from(parts[2], 'hex');+ let actual: Buffer;+ try {+ actual = crypto.scryptSync(password, salt, expected.length);+ } catch {+ return false;+ }+ // Constant-time compare; lengths match by construction (both KEYLEN).+ return actual.length === expected.length && crypto.timingSafeEqual(actual, expected);+}diff --git a/server/src/middleware/requireAuth.ts b/server/src/middleware/requireAuth.tsnew file mode 100644index 00000000..ec687517--- /dev/null+++ b/server/src/middleware/requireAuth.ts@@ -0,0 +1,18 @@+import type { Request, Response, NextFunction } from 'express';+import { validateSession } from '../services/auth.js';++// Gate the /api/* admin surface behind a dashboard session (#35, item #2).+// The token is the opaque session token issued by /api/auth/login|setup, sent+// as `Authorization: Bearer <token>`. The /v1 proxy is NOT gated by this — it+// keeps its own unified-API-key auth for app clients.+export function requireAuth(req: Request, res: Response, next: NextFunction): void {+ const token = req.headers.authorization?.replace(/^Bearer\s+/i, '')+ ?? (req.headers['x-dashboard-token'] as string | undefined);+ const session = validateSession(token);+ if (!session) {+ res.status(401).json({ error: { message: 'Authentication required', type: 'authentication_error' } });+ return;+ }+ (req as Request & { user?: typeof session }).user = session;+ next();+}diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.tsnew file mode 100644index 00000000..cf3afb01--- /dev/null+++ b/server/src/routes/auth.ts@@ -0,0 +1,119 @@+import { Router } from 'express';+import type { Request, Response } from 'express';+import { z } from 'zod';+import {+ userCount,+ createUser,+ verifyCredentials,+ createSession,+ validateSession,+ deleteSession,+} from '../services/auth.js';++export const authRouter = Router();++// Dashboard auth (#35). These routes are mounted BEFORE requireAuth, so+// /status, /setup and /login are reachable without a session (bootstrap);+// /logout and /me validate the token themselves.++const credentialsSchema = z.object({+ email: z.string().email('A valid email is required'),+ password: z.string().min(8, 'Password must be at least 8 characters'),+});++// ── Brute-force throttle ──────────────────────────────────────────────────+// Simple in-memory per-email limiter. A local single-user tool doesn't need a+// distributed store; this just blunts online password guessing.+const MAX_ATTEMPTS = 5;+const LOCKOUT_MS = 15 * 60 * 1000;+const attempts = new Map<string, { count: number; lockedUntil: number }>();++function isLockedOut(email: string): boolean {+ const a = attempts.get(email.toLowerCase());+ return !!a && a.lockedUntil > Date.now();+}+function recordFailure(email: string): void {+ const key = email.toLowerCase();+ const a = attempts.get(key) ?? { count: 0, lockedUntil: 0 };+ a.count++;+ if (a.count >= MAX_ATTEMPTS) {+ a.lockedUntil = Date.now() + LOCKOUT_MS;+ a.count = 0;+ }+ attempts.set(key, a);+}+function clearFailures(email: string): void {+ attempts.delete(email.toLowerCase());+}++function bearer(req: Request): string | undefined {+ return req.headers.authorization?.replace(/^Bearer\s+/i, '')+ ?? (req.headers['x-dashboard-token'] as string | undefined);+}++// Has the dashboard been set up yet, and is this caller authenticated?+authRouter.get('/status', (req: Request, res: Response) => {+ const session = validateSession(bearer(req));+ res.json({+ needsSetup: userCount() === 0,+ authenticated: !!session,+ email: session?.email ?? null,+ });+});++// First-run account creation. Only allowed while there are zero users, so it+// can't be used to add accounts once the dashboard is claimed.+authRouter.post('/setup', (req: Request, res: Response) => {+ if (userCount() > 0) {+ res.status(409).json({ error: { message: 'Setup already completed. Use login instead.', type: 'setup_complete' } });+ return;+ }+ const parsed = credentialsSchema.safeParse(req.body);+ if (!parsed.success) {+ res.status(400).json({ error: { message: parsed.error.errors.map(e => e.message).join(', ') } });+ return;+ }+ const user = createUser(parsed.data.email, parsed.data.password);+ const token = createSession(user.userId);+ res.status(201).json({ token, email: user.email });+});++authRouter.post('/login', (req: Request, res: Response) => {+ const parsed = credentialsSchema.safeParse(req.body);+ if (!parsed.success) {+ res.status(400).json({ error: { message: parsed.error.errors.map(e => e.message).join(', ') } });+ return;+ }+ const { email, password } = parsed.data;++ if (isLockedOut(email)) {+ res.status(429).json({ error: { message: 'Too many failed attempts. Try again later.', type: 'rate_limit_error' } });+ return;+ }++ const user = verifyCredentials(email, password);+ if (!user) {+ recordFailure(email);+ // Same message whether the email exists or not — don't leak which.+ res.status(401).json({ error: { message: 'Invalid email or password', type: 'authentication_error' } });+ return;+ }++ clearFailures(email);+ const token = createSession(user.userId);+ res.json({ token, email: user.email });+});++authRouter.post('/logout', (req: Request, res: Response) => {+ deleteSession(bearer(req));+ res.json({ success: true });+});++authRouter.get('/me', (req: Request, res: Response) => {+ const session = validateSession(bearer(req));+ if (!session) {+ res.status(401).json({ error: { message: 'Authentication required', type: 'authentication_error' } });+ return;+ }+ res.json({ email: session.email });+});diff --git a/server/src/services/auth.ts b/server/src/services/auth.tsnew file mode 100644index 00000000..da310e28--- /dev/null+++ b/server/src/services/auth.ts@@ -0,0 +1,82 @@+import crypto from 'crypto';+import { getDb } from '../db/index.js';+import { hashPassword, verifyPassword } from '../lib/password.js';++// Dashboard authentication: email + password accounts with opaque session+// tokens. Distinct from the unified API key, which authenticates the /v1 proxy+// for apps — this gates the /api/* admin surface for the human operator (#35).++const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days++export interface SessionUser {+ userId: number;+ email: string;+}++function sha256(s: string): string {+ return crypto.createHash('sha256').update(s).digest('hex');+}++function normalizeEmail(email: string): string {+ return email.trim().toLowerCase();+}++export function userCount(): number {+ const row = getDb().prepare('SELECT COUNT(*) AS c FROM users').get() as { c: number };+ return row.c;+}++/** Create a user. Throws { code: 'email_taken' } if the email already exists. */+export function createUser(email: string, password: string): SessionUser {+ const db = getDb();+ const normalized = normalizeEmail(email);+ const existing = db.prepare('SELECT id FROM users WHERE email = ?').get(normalized);+ if (existing) {+ const err = new Error('An account with that email already exists') as any;+ err.code = 'email_taken';+ throw err;+ }+ const result = db.prepare('INSERT INTO users (email, password_hash) VALUES (?, ?)')+ .run(normalized, hashPassword(password));+ return { userId: Number(result.lastInsertRowid), email: normalized };+}++/** Verify credentials. Returns the user on success, null on failure. */+export function verifyCredentials(email: string, password: string): SessionUser | null {+ const db = getDb();+ const row = db.prepare('SELECT id, email, password_hash FROM users WHERE email = ?')+ .get(normalizeEmail(email)) as { id: number; email: string; password_hash: string } | undefined;+ if (!row) return null;+ if (!verifyPassword(password, row.password_hash)) return null;+ return { userId: row.id, email: row.email };+}++/** Mint a session and return the raw token (only the hash is persisted). */+export function createSession(userId: number): string {+ const token = crypto.randomBytes(32).toString('hex');+ getDb().prepare('INSERT INTO sessions (token_hash, user_id, expires_at_ms) VALUES (?, ?, ?)')+ .run(sha256(token), userId, Date.now() + SESSION_TTL_MS);+ return token;+}++/** Resolve a session token to its user, or null if missing/expired. */+export function validateSession(token: string | undefined | null): SessionUser | null {+ if (!token) return null;+ const db = getDb();+ const row = db.prepare(`+ SELECT s.user_id, s.expires_at_ms, u.email+ FROM sessions s JOIN users u ON u.id = s.user_id+ WHERE s.token_hash = ?+ `).get(sha256(token)) as { user_id: number; expires_at_ms: number; email: string } | undefined;+ if (!row) return null;+ if (row.expires_at_ms < Date.now()) {+ db.prepare('DELETE FROM sessions WHERE token_hash = ?').run(sha256(token));+ return null;+ }+ return { userId: row.user_id, email: row.email };+}++export function deleteSession(token: string | undefined | null): void {+ if (!token) return;+ getDb().prepare('DELETE FROM sessions WHERE token_hash = ?').run(sha256(token));+}