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): close open-redirect + revoke stale Socket.IO sessions

Adam Eivy17387cb76e28
diff --git a/client/src/pages/Login.jsx b/client/src/pages/Login.jsx
index 871b9fd863..a5d2f24d82 100644
--- a/client/src/pages/Login.jsx
+++ b/client/src/pages/Login.jsx
@@ -1,14 +1,29 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { getAuthStatus, loginWithPassword } from '../services/api';
+// Constrain the `?next=` redirect target to a same-origin in-app path.
+// Reject absolute URLs (`https://attacker.example`), protocol-relative
+// (`//attacker.example`), and non-http schemes (`javascript:alert(1)`).
+// Anything else falls back to `/` — a crafted login link can't bounce the
+// user off-origin after sign-in, and can't execute script via the
+// auth-disabled auto-redirect branch in the effect below. Exported for
+// unit tests.
+export const sanitizeNext = (raw) => {
+ if (typeof raw !== 'string' || raw.length === 0) return '/';
+ if (!raw.startsWith('/')) return '/';
+ if (raw.startsWith('//')) return '/'; // protocol-relative URL
+ if (raw.startsWith('/\\')) return '/'; // some browsers normalize `\\` → `//`
+ return raw;
+};
+
// Single-password sign-in. Shown when settings.secrets.auth.enabled is true
// and the request has no valid session token. When auth is off, the page
// auto-redirects to "next" (or `/`) so a stale bookmark to /login doesn't
// become a dead end.
export default function Login() {
const [search] = useSearchParams();
- const next = search.get('next') || '/';
+ const next = useMemo(() => sanitizeNext(search.get('next')), [search]);
const [password, setPassword] = useState('');
const [error, setError] = useState(null);
const [submitting, setSubmitting] = useState(false);
diff --git a/client/src/pages/Login.test.jsx b/client/src/pages/Login.test.jsx
new file mode 100644
index 0000000000..7dd56cc64c
--- /dev/null
+++ b/client/src/pages/Login.test.jsx
@@ -0,0 +1,39 @@
+import { describe, it, expect } from 'vitest';
+import { sanitizeNext } from './Login';
+
+// Open-redirect regression: an attacker who can craft a /login URL must not
+// be able to bounce the signed-in user off-origin or execute script.
+describe('Login sanitizeNext', () => {
+ it('accepts a same-origin app path', () => {
+ expect(sanitizeNext('/')).toBe('/');
+ expect(sanitizeNext('/brain/inbox')).toBe('/brain/inbox');
+ expect(sanitizeNext('/settings/security?tab=password')).toBe('/settings/security?tab=password');
+ });
+
+ it('rejects absolute URLs', () => {
+ expect(sanitizeNext('https://attacker.example')).toBe('/');
+ expect(sanitizeNext('http://attacker.example')).toBe('/');
+ });
+
+ it('rejects protocol-relative URLs', () => {
+ expect(sanitizeNext('//attacker.example')).toBe('/');
+ expect(sanitizeNext('//evil.com/path')).toBe('/');
+ });
+
+ it('rejects non-http schemes', () => {
+ expect(sanitizeNext('javascript:alert(1)')).toBe('/');
+ expect(sanitizeNext('data:text/html,<script>...</script>')).toBe('/');
+ expect(sanitizeNext('file:///etc/passwd')).toBe('/');
+ });
+
+ it('rejects empty / non-string inputs', () => {
+ expect(sanitizeNext(null)).toBe('/');
+ expect(sanitizeNext(undefined)).toBe('/');
+ expect(sanitizeNext('')).toBe('/');
+ expect(sanitizeNext(123)).toBe('/');
+ });
+
+ it('rejects backslash-prefixed paths some browsers normalize to //', () => {
+ expect(sanitizeNext('/\\attacker.example')).toBe('/');
+ });
+});
diff --git a/server/services/auth.js b/server/services/auth.js
index 90d57cdfde..381d0c329f 100644
--- a/server/services/auth.js
+++ b/server/services/auth.js
@@ -1,4 +1,5 @@
import { join } from 'path';
+import { EventEmitter } from 'events';
import { createHash, randomBytes, scrypt, timingSafeEqual } from 'crypto';
import { promisify } from 'util';
import { atomicWrite, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
@@ -13,6 +14,14 @@ import { ServerError } from '../lib/errorHandler.js';
const scryptAsync = promisify(scrypt);
+// Event bus so the Socket.IO layer can react to auth-state changes (first-time
+// enable, password rotation, full disable) without coupling the auth service
+// to `io`. Consumers should kick every currently-connected socket and let
+// clients re-handshake — the gate then re-validates each one against the
+// fresh session store.
+export const authEvents = new EventEmitter();
+authEvents.setMaxListeners(50);
+
const SESSIONS_FILE = join(PATHS.data, 'auth-sessions.json');
const TOKEN_BYTES = 32;
const SALT_BYTES = 16;
@@ -204,6 +213,11 @@ export const revokeAllSessions = async () => {
await ensureLoaded();
sessions.clear();
await writeSessions();
+ // Notify the socket layer so connections established before the revoke
+ // (e.g. a tab open before auth was enabled, or before a password rotation)
+ // get kicked. Otherwise they'd keep emitting privileged events on the
+ // already-accepted handshake until the page reloads.
+ authEvents.emit('sessions:revoked-all');
};
// 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 0865177cf7..13d8c4c0b2 100644
--- a/server/services/auth.test.js
+++ b/server/services/auth.test.js
@@ -155,4 +155,15 @@ describe('auth service', () => {
expect(raw).not.toContain(token);
expect(raw).toContain('tokenHash');
});
+
+ it('emits sessions:revoked-all on every auth-state change so the socket layer can kick connections', async () => {
+ const auth = await import('./auth.js');
+ const events = [];
+ auth.authEvents.on('sessions:revoked-all', () => events.push('event'));
+ await auth.setPassword({ newPassword: 'correct-horse' }); // first-time enable
+ await auth.setPassword({ newPassword: 'new-horse', currentPassword: 'correct-horse' }); // rotate
+ await auth.clearPassword({ currentPassword: 'new-horse' }); // disable
+ // setPassword/clearPassword both call revokeAllSessions internally.
+ expect(events.length).toBe(3);
+ });
});
diff --git a/server/services/socket.js b/server/services/socket.js
index 0a5da6c140..972d207a86 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -44,6 +44,7 @@ import * as appUpdater from './appUpdater.js';
import * as appDeployer from './appDeployer.js';
import { registerVoiceHandlers } from '../sockets/voice.js';
import { getBuildId } from '../lib/buildId.js';
+import { authEvents, extractToken, isAuthEnabled, verifySession } from './auth.js';
// Store active log streams per socket
const activeStreams = new Map();
@@ -83,8 +84,34 @@ function registerSubscriber(socket, namespace, set) {
}
export function initSocket(io) {
+ // Auth-state changes (first-time enable, rotation, disable) all funnel
+ // through revokeAllSessions in services/auth.js, which fires this event.
+ // Disconnect every currently-connected socket so clients re-handshake
+ // against the fresh session store — sockets accepted before the change
+ // would otherwise keep emitting privileged events on their stale
+ // handshake-time auth grant.
+ authEvents.on('sessions:revoked-all', () => {
+ console.log(`🔐 Auth state changed — disconnecting all sockets`);
+ if (typeof io.disconnectSockets === 'function') io.disconnectSockets(true);
+ });
+
io.on('connection', (socket) => {
console.log(`🔌 Client connected: ${socket.id}`);
+ // Per-event auth re-check: the handshake gate (lib/authGate.js
+ // socketAuthGate) only runs once at connection time. If a session
+ // expires or is revoked while the socket is open, the next inbound
+ // event re-verifies and kicks the socket. Cheap (hashed-Map lookup),
+ // and no-op when auth is off. Guarded for tests that pass a mock
+ // socket without the `use` middleware hook.
+ if (typeof socket.use === 'function') {
+ socket.use(async ([_event, ..._args], next) => {
+ if (!(await isAuthEnabled())) return next();
+ const token = extractToken({ headers: socket.handshake?.headers || {} });
+ if (await verifySession(token)) return next();
+ socket.disconnect(true);
+ // Don't call next — the event is dropped along with the connection.
+ });
+ }
registerVoiceHandlers(socket);
// Tell the client what build the server is on. The client compares this