Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix(auth): close both gaps that left login brute-force unthrottled (#1286)

tashdroid9c0842ce35a9
diff --git a/server/src/__tests__/routes/auth-login-throttle.test.ts b/server/src/__tests__/routes/auth-login-throttle.test.ts
new file mode 100644
index 00000000..1d235c94
--- /dev/null
+++ b/server/src/__tests__/routes/auth-login-throttle.test.ts
@@ -0,0 +1,79 @@
+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 { createUser } from '../../services/auth.js';
+
+// Two independent guards are supposed to stand in front of POST
+// /api/auth/login: the per-email lockout in routes/auth.ts and the per-IP
+// admin limiter mounted on /api in app.ts. Both used to miss.
+
+const EMAIL = '[email protected]';
+const PASSWORD = 'correct horse battery staple';
+
+let app: Express;
+
+async function login(email: string, password: string) {
+ const server = app.listen(0, '127.0.0.1');
+ if (!server.listening) await new Promise<void>(resolve => server.once('listening', () => resolve()));
+ const addr = server.address() as { port: number };
+ try {
+ const res = await fetch(`http://127.0.0.1:${addr.port}/api/auth/login`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ email, password }),
+ });
+ await res.text();
+ return { status: res.status, headers: res.headers };
+ } finally {
+ server.close();
+ }
+}
+
+describe('login brute-force throttling', () => {
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ app = createApp();
+ });
+
+ beforeEach(() => {
+ getDb().prepare('DELETE FROM sessions').run();
+ getDb().prepare('DELETE FROM users').run();
+ createUser(EMAIL, PASSWORD);
+ });
+
+ // The lockout bucket has to be keyed on the same spelling verifyCredentials
+ // resolves the user by (services/auth.ts normalizeEmail = trim+lowercase).
+ // Keyed on `.toLowerCase()` alone, every whitespace variant of the address
+ // authenticated against the real row from its own fresh five-try bucket, so
+ // the lockout could be side-stepped indefinitely.
+ it('counts whitespace-padded spellings of an address in one bucket', async () => {
+ for (let i = 0; i < 5; i++) {
+ const attempt = await login(EMAIL, `wrong-${i}`);
+ expect(attempt.status).toBe(401);
+ }
+ expect((await login(EMAIL, 'wrong-again')).status).toBe(429);
+
+ // Same account, padded spellings — must hit the same locked bucket.
+ for (const padded of [` ${EMAIL}`, `${EMAIL} `, `\t${EMAIL}`, `\n${EMAIL}`, ` ${EMAIL} `]) {
+ expect((await login(padded, 'wrong')).status).toBe(429);
+ }
+
+ // And the padded spelling must not be able to sign in past the lockout
+ // with the RIGHT password either — it is the same account.
+ expect((await login(` ${EMAIL}`, PASSWORD)).status).toBe(429);
+ });
+
+ // app.ts mounts createAdminRateLimiter() on /api and its comment names auth
+ // brute force as the reason. Express runs middleware in registration order,
+ // so the limiter has to be registered before the /api/auth mount or the
+ // login route answers and ends the response before the limiter is entered.
+ it('routes login through the per-IP admin limiter', async () => {
+ // A fresh address, so the lockout the previous test armed (the bucket map
+ // is module state and outlives the DB reset) cannot mask the header check.
+ const attempt = await login('[email protected]', 'wrong');
+ expect(attempt.status).toBe(401);
+ expect(attempt.headers.get('x-ratelimit-limit')).toBeTruthy();
+ });
+});
diff --git a/server/src/app.ts b/server/src/app.ts
index 86a05e0f..f0303459 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -215,18 +215,25 @@ export function createApp(config?: Config) {
);
app.use(ollamaRouter);
- // 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);
-
// 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.
+ //
+ // This MUST stay above the /api/auth mount below. Express runs middleware in
+ // registration order, so while the limiter was registered after authRouter,
+ // authRouter answered and ended /api/auth/login before the limiter was ever
+ // entered — leaving the password endpoint this comment names as the reason
+ // for the limiter as the one /api path it did not cover. It still sits below
+ // the Ollama /api/* mount above, which carries its own proxy limiter.
const adminRateLimiter = createAdminRateLimiter();
app.use('/api', adminRateLimiter);
+ // 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);
+
// 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
diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.ts
index a60ea1ff..d7a8ff93 100644
--- a/server/src/routes/auth.ts
+++ b/server/src/routes/auth.ts
@@ -11,6 +11,7 @@ import {
updateEmail,
updatePassword,
resetUserPassword,
+ normalizeEmail,
} from '../services/auth.js';
import { setupCodeMatches, clearSetupCode } from '../lib/setup-code.js';
import { generateResetCode, resetCodeMatches, clearResetCode } from '../lib/reset-code.js';
@@ -47,14 +48,26 @@ const loginSchema = z.object({
// distributed store; this just blunts online password guessing.
const MAX_ATTEMPTS = 5;
const LOCKOUT_MS = 15 * 60 * 1000;
+// Bound the map so a flood of distinct addresses cannot grow it without limit;
+// expired buckets are pruned opportunistically, mirroring the per-IP limiter in
+// middleware/rateLimit.ts.
+const MAX_TRACKED_EMAILS = 10_000;
const attempts = new Map<string, { count: number; lockedUntil: number }>();
+// The bucket key MUST be the same spelling verifyCredentials looks the user up
+// by. Keying on `.toLowerCase()` alone while the lookup also trimmed meant
+// " [email protected]" authenticated against the admin row but landed in its
+// own bucket, so every whitespace variant handed the guesser another five
+// tries and the lockout never engaged.
+function throttleKey(email: string): string {
+ return normalizeEmail(email);
+}
function isLockedOut(email: string): boolean {
- const a = attempts.get(email.toLowerCase());
+ const a = attempts.get(throttleKey(email));
return !!a && a.lockedUntil > Date.now();
}
function recordFailure(email: string): void {
- const key = email.toLowerCase();
+ const key = throttleKey(email);
const a = attempts.get(key) ?? { count: 0, lockedUntil: 0 };
a.count++;
if (a.count >= MAX_ATTEMPTS) {
@@ -62,9 +75,15 @@ function recordFailure(email: string): void {
a.count = 0;
}
attempts.set(key, a);
+ if (attempts.size > MAX_TRACKED_EMAILS) {
+ const now = Date.now();
+ for (const [tracked, state] of attempts) {
+ if (tracked !== key && state.lockedUntil <= now) attempts.delete(tracked);
+ }
+ }
}
function clearFailures(email: string): void {
- attempts.delete(email.toLowerCase());
+ attempts.delete(throttleKey(email));
}
function bearer(req: Request): string | undefined {
diff --git a/server/src/services/auth.ts b/server/src/services/auth.ts
index a7caec53..d0a74ea0 100644
--- a/server/src/services/auth.ts
+++ b/server/src/services/auth.ts
@@ -17,7 +17,11 @@ function sha256(s: string): string {
return crypto.createHash('sha256').update(s).digest('hex');
}
-function normalizeEmail(email: string): string {
+/** The one spelling of an address the DB is keyed on. Exported so callers that
+ * bucket by email (the login throttle in routes/auth.ts) key on exactly what
+ * verifyCredentials will look up — keying on anything else lets a padded
+ * address authenticate against the real row while landing in its own bucket. */
+export function normalizeEmail(email: string): string {
return email.trim().toLowerCase();
}