Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (codex iter 4): rate-limit login, gate before parser, longer kick delay

Adam Eivy44d0e1672d69
diff --git a/server/index.js b/server/index.js
index ca0c8a5e71..a4916ee143 100644
--- a/server/index.js
+++ b/server/index.js
@@ -374,20 +374,24 @@ app.use((req, res, next) => {
if (req.method === 'OPTIONS') return res.sendStatus(204);
next();
});
-// Body limit is set slightly above the 50MB combined base64 cap enforced by sendMessageSchema
-// so the Zod validation (not the body parser) is the binding constraint for attachment payloads.
-app.use(express.json({ limit: '55mb' }));
-app.use(express.urlencoded({ limit: '55mb', extended: true }));
-
// Make io available to routes
app.set('io', io);
-// Auth gate runs before any /api/* or /sdapi/* route. When
+// Auth gate runs BEFORE the body parsers so unauthenticated requests to
+// gated routes are rejected from the headers alone, without forcing the
+// server to read and parse a 55 MB JSON body first (DoS surface).
+// Public routes (login, status, health) still need a parsed body / no body,
+// and they flow through to the parsers below normally. When
// settings.secrets.auth.enabled is true the gate returns 401 for everything
// except the small public set in lib/authGate.js (auth status/whoami/login/
// logout + /api/system/health). No-op when auth is off.
app.use(authGate);
+// Body limit is set slightly above the 50MB combined base64 cap enforced by sendMessageSchema
+// so the Zod validation (not the body parser) is the binding constraint for attachment payloads.
+app.use(express.json({ limit: '55mb' }));
+app.use(express.urlencoded({ limit: '55mb', extended: true }));
+
// API Routes
app.use('/api/auth', authRoutes);
app.use('/api/alerts', alertsRoutes);
diff --git a/server/routes/auth.js b/server/routes/auth.js
index 822b1a4494..e0fbf3479b 100644
--- a/server/routes/auth.js
+++ b/server/routes/auth.js
@@ -3,11 +3,14 @@ import { z } from 'zod';
import {
buildClearCookie,
buildSessionCookie,
+ clearLoginFailures,
clearPassword,
createSession,
extractToken,
getAuthStatus,
isAuthEnabled,
+ isLoginRateLimited,
+ recordLoginFailure,
revokeSession,
setPassword,
verifyPassword,
@@ -58,9 +61,23 @@ router.post('/login', asyncHandler(async (req, res) => {
if (!(await isAuthEnabled())) {
throw new ServerError('Authentication is not enabled', { status: 400, code: 'AUTH_NOT_ENABLED' });
}
+ // Throttle check runs BEFORE scrypt so a sidecar can't pin the CPU by
+ // looping bad guesses. The IP comes from Express's `req.ip` (we don't
+ // sit behind a reverse proxy in normal PortOS deployments).
+ const clientIp = req.ip || req.socket?.remoteAddress || 'unknown';
+ if (isLoginRateLimited(clientIp)) {
+ throw new ServerError('Too many login attempts — try again in a minute', {
+ status: 429,
+ code: 'AUTH_RATE_LIMITED',
+ });
+ }
if (!(await verifyPassword(password))) {
+ recordLoginFailure(clientIp);
throw new ServerError('Invalid password', { status: 401, code: 'AUTH_BAD_PASSWORD' });
}
+ // Success clears the throttle so a user who mistyped a few times then got
+ // it right isn't kept locked out.
+ clearLoginFailures(clientIp);
const { token } = await createSession();
res.setHeader('Set-Cookie', buildSessionCookie(token, { secure: isSecure(req) }));
res.json({ authenticated: true });
diff --git a/server/routes/auth.test.js b/server/routes/auth.test.js
index c4b7b1dff7..7ece4818e7 100644
--- a/server/routes/auth.test.js
+++ b/server/routes/auth.test.js
@@ -69,6 +69,23 @@ describe('auth routes', () => {
expect(res.body.code).toBe('AUTH_NOT_ENABLED');
});
+ it('POST /api/auth/login throttles after the failure-window cap', async () => {
+ let app = await buildApp();
+ await request(app).post('/api/auth/password').send({ newPassword: 'correct-horse' });
+
+ app = await buildApp();
+ // Burn through the 10-failure window with bad passwords from one IP.
+ for (let i = 0; i < 10; i++) {
+ await request(app).post('/api/auth/login').send({ password: `wrong-${i}` });
+ }
+ // Next attempt should be throttled with 429 — and crucially WITHOUT
+ // running scrypt (we can't easily assert that here, but the status
+ // code confirms the throttle path fired).
+ const throttled = await request(app).post('/api/auth/login').send({ password: 'correct-horse' });
+ expect(throttled.status).toBe(429);
+ expect(throttled.body.code).toBe('AUTH_RATE_LIMITED');
+ });
+
it('POST /api/auth/login rejects bad passwords and accepts correct ones', async () => {
let app = await buildApp();
await request(app).post('/api/auth/password').send({ newPassword: 'correct-horse' });
diff --git a/server/services/auth.js b/server/services/auth.js
index d328279532..3f30431f41 100644
--- a/server/services/auth.js
+++ b/server/services/auth.js
@@ -28,6 +28,12 @@ const SALT_BYTES = 16;
const HASH_BYTES = 64;
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
const COOKIE_NAME = 'portos_auth';
+// Login throttle — auth is normally tailnet-only so this is defense in depth
+// against a sidecar burning server CPU on scrypt verifications. Per-IP
+// sliding window: at most LOGIN_MAX_ATTEMPTS failed POSTs in
+// LOGIN_WINDOW_MS, then 401s with no scrypt work until the window clears.
+const LOGIN_MAX_ATTEMPTS = 10;
+const LOGIN_WINDOW_MS = 60 * 1000;
// scrypt cost parameters per OWASP 2023 password-storage guidance for
// interactive logins. PortOS has no rate limiting and the password hash +
// salt persist in `settings.json` (single-user trust model — local
@@ -39,6 +45,15 @@ const COOKIE_NAME = 'portos_auth';
// params), so allocate 256 MiB.
const SCRYPT_PARAMS = { N: 131072, r: 8, p: 1, maxmem: 256 * 1024 * 1024 };
+// Delay before kicking sockets on auth-state change. `setImmediate` fires in
+// the same tick as the HTTP response flush — close enough that the
+// disconnect frame can reach the browser before the new Set-Cookie header
+// has been processed, bouncing the initiating tab to /login mid-change. A
+// half-second tradeoff: long enough for the response round-trip + cookie
+// application on a tailnet (typically <50ms), short enough to not feel
+// laggy when a sibling tab needs to log out.
+const KICK_DELAY_MS = 500;
+
// In-memory session store. Keyed by `sha256(token)` → { expiresAt }. Persisted
// to disk on every mutation so tokens survive server restarts (handy when PM2
// reloads on update). A single-user install rarely has more than a handful of
@@ -233,7 +248,7 @@ export const revokeSession = async (token) => {
// single-user model means broadcast events shouldn't keep streaming
// to a tab whose cookie was just cleared. Deferred so the logout
// response's clear-cookie reaches the browser first.
- setImmediate(() => authEvents.emit('sessions:revoked-all'));
+ setTimeout(() => authEvents.emit('sessions:revoked-all'), KICK_DELAY_MS);
}
};
@@ -246,13 +261,47 @@ export const revokeAllSessions = async () => {
// get kicked. Otherwise they'd keep emitting privileged events on the
// already-accepted handshake until the page reloads.
//
- // Defer with `setImmediate` so the HTTP response that triggered this
- // revoke (POST /api/auth/password) has time to flush its new Set-Cookie
- // header before we kick the requesting tab's socket. Without the defer,
- // the user's own password-change request kicks their own socket, which
- // reconnects with the OLD cookie (the new one hasn't arrived yet) and
- // bounces them to /login mid-change.
- setImmediate(() => authEvents.emit('sessions:revoked-all'));
+ // Defer the kick so the HTTP response that triggered this revoke (POST
+ // /api/auth/password) has time to flush its new Set-Cookie header and
+ // round-trip to the browser BEFORE we kick the requesting tab's socket.
+ // Without the defer, the user's own password-change request kicks their
+ // own socket, which reconnects with the OLD cookie (the new one hasn't
+ // arrived yet) and bounces them to /login mid-change.
+ setTimeout(() => authEvents.emit('sessions:revoked-all'), KICK_DELAY_MS);
+};
+
+// Sliding-window login-throttle map. Keys are client IPs; values are arrays
+// of recent failed-attempt timestamps. Trimmed lazily on each call so it
+// never grows unbounded. In-memory only (a sidecar restart resets the
+// counters — acceptable for a defense-in-depth control on a single-user
+// install, not the primary auth boundary).
+const loginAttempts = new Map();
+
+const trimLoginWindow = (timestamps, cutoff) => {
+ let i = 0;
+ while (i < timestamps.length && timestamps[i] < cutoff) i++;
+ return i === 0 ? timestamps : timestamps.slice(i);
+};
+
+export const isLoginRateLimited = (ip) => {
+ if (typeof ip !== 'string' || ip.length === 0) return false;
+ const cutoff = now() - LOGIN_WINDOW_MS;
+ const recent = trimLoginWindow(loginAttempts.get(ip) || [], cutoff);
+ if (recent.length === 0) loginAttempts.delete(ip);
+ else loginAttempts.set(ip, recent);
+ return recent.length >= LOGIN_MAX_ATTEMPTS;
+};
+
+export const recordLoginFailure = (ip) => {
+ if (typeof ip !== 'string' || ip.length === 0) return;
+ const cutoff = now() - LOGIN_WINDOW_MS;
+ const recent = trimLoginWindow(loginAttempts.get(ip) || [], cutoff);
+ recent.push(now());
+ loginAttempts.set(ip, recent);
+};
+
+export const clearLoginFailures = (ip) => {
+ if (typeof ip === 'string') loginAttempts.delete(ip);
};
// Parse the `Cookie` header for our token. Express doesn't ship a cookie
diff --git a/server/services/auth.test.js b/server/services/auth.test.js
index 2b8fc397e6..21f6ff5692 100644
--- a/server/services/auth.test.js
+++ b/server/services/auth.test.js
@@ -170,10 +170,28 @@ describe('auth service', () => {
await auth.clearPassword({ currentPassword: 'new-horse' }); // disable
// The emit is deferred via setImmediate so the response cookie can
// flush first — let the event loop tick before asserting.
- await new Promise((resolve) => setImmediate(resolve));
+ // Kick event is deferred ~500ms so the response cookie can flush first.
+ await new Promise((resolve) => setTimeout(resolve, 600));
expect(events.length).toBe(3);
});
+ it('rate-limits login attempts per IP after a burst of failures', async () => {
+ const auth = await import('./auth.js');
+ const ip = '100.64.0.5';
+ // First 10 attempts are NOT rate-limited (matches LOGIN_MAX_ATTEMPTS).
+ for (let i = 0; i < 10; i++) {
+ expect(auth.isLoginRateLimited(ip)).toBe(false);
+ auth.recordLoginFailure(ip);
+ }
+ // 11th attempt is throttled.
+ expect(auth.isLoginRateLimited(ip)).toBe(true);
+ // A different IP is unaffected.
+ expect(auth.isLoginRateLimited('100.64.0.6')).toBe(false);
+ // Clearing wipes the window for that IP.
+ auth.clearLoginFailures(ip);
+ expect(auth.isLoginRateLimited(ip)).toBe(false);
+ });
+
it('coalesces concurrent verifySession calls so a burst right after restart sees the loaded sessions', async () => {
// First enable auth (this writes both settings.json and an initial
// auth-sessions.json with one session), THEN seed our fake session
@@ -206,14 +224,19 @@ describe('auth service', () => {
const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
const { token } = await auth.createSession();
+ // Drain the setPassword's deferred-kick timer before we attach the
+ // listener so it doesn't get counted against this test's expectation.
+ await new Promise((resolve) => setTimeout(resolve, 600));
const events = [];
auth.authEvents.on('sessions:revoked-all', () => events.push('event'));
await auth.revokeSession(token);
- await new Promise((resolve) => setImmediate(resolve));
+ // Kick event is deferred ~500ms so the response cookie can flush first.
+ await new Promise((resolve) => setTimeout(resolve, 600));
expect(events.length).toBe(1);
// Revoking an unknown token must NOT fire — no state changed.
await auth.revokeSession('not-a-real-token');
- await new Promise((resolve) => setImmediate(resolve));
+ // Kick event is deferred ~500ms so the response cookie can flush first.
+ await new Promise((resolve) => setTimeout(resolve, 600));
expect(events.length).toBe(1);
});
});