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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (codex + claude): fix races, dev-proxy 403, logout CSRF
Adam Eivyb56f202b06ce
diff --git a/server/lib/authGate.js b/server/lib/authGate.jsindex 316adf976d..d3311e388a 100644--- a/server/lib/authGate.js+++ b/server/lib/authGate.js@@ -47,6 +47,21 @@ const isPublicPath = (path) => {// mismatch is a cross-origin attempt and gets 403 before the session is// even consulted. Requests with no `Origin` header (server-to-server,// curl, the loopback mirror) pass through.+// Hostnames are case-insensitive (RFC 3986 §3.2.2). Node's `URL` already+// lowercases the parsed authority; lowercase the raw `Host` header too so a+// client that sends mixed-case isn't 403'd as cross-origin.+const stripPort = (hostHeader) => {+ // Bracketed IPv6 host: `[::1]:port` → `[::1]`.+ if (hostHeader.startsWith('[')) {+ const close = hostHeader.indexOf(']');+ return close === -1 ? hostHeader : hostHeader.slice(0, close + 1);+ }+ const colon = hostHeader.indexOf(':');+ return colon === -1 ? hostHeader : hostHeader.slice(0, colon);+};+const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);+const isLoopback = (hostname) => LOOPBACK_HOSTS.has(hostname.toLowerCase());+const isCrossOrigin = (req) => {const origin = req.headers?.origin;if (!origin || origin === 'null') return false;@@ -57,7 +72,15 @@ const isCrossOrigin = (req) => {let parsed;try { parsed = new URL(origin); }catch { return true; }- return parsed.host !== host;+ if (parsed.host.toLowerCase() === host.toLowerCase()) return false;+ // Dev workflow exemption: Vite proxies :5554 → :5555 with changeOrigin,+ // so a real same-origin browser request arrives as+ // `Origin: http://localhost:5554` / `Host: localhost:5555`. Treat any+ // loopback-to-loopback pairing as same-origin regardless of port — the+ // CSRF threat is from attackers on OTHER machines, not from a local+ // dev server on the same loopback interface.+ if (isLoopback(stripPort(parsed.host)) && isLoopback(stripPort(host))) return false;+ return true;};// Express middleware. Bypasses everything when auth is off. When it's on,@@ -66,16 +89,16 @@ const isCrossOrigin = (req) => {export const authGate = async (req, res, next) => {const enabled = await isAuthEnabled();if (!enabled) return next();- const path = req.path;- if (isPublicPath(path)) return next();- // CSRF guard runs BEFORE the cookie check — a cross-origin request must- // be rejected even if it carries a valid session, otherwise an attacker- // with no cookie still triggers side effects whose response the browser- // hides but whose mutations have already landed.+ // CSRF guard runs FIRST, before isPublicPath — public endpoints like+ // /api/auth/logout still mutate state (clear the cookie + revoke the+ // session), so a same-tailnet attacker could force-logout a user+ // cross-origin if the guard sat behind the public-path bypass.if (isCrossOrigin(req)) {res.status(403).json({ error: 'Cross-origin request rejected', code: 'CROSS_ORIGIN_BLOCKED' });return;}+ const path = req.path;+ if (isPublicPath(path)) return next();const token = extractToken(req);if (await verifySession(token)) return next();// /data/* is hit directly by <img>/<audio>/<video> tags which don't show adiff --git a/server/lib/authGate.test.js b/server/lib/authGate.test.jsindex f2e81af700..f858a0f4f3 100644--- a/server/lib/authGate.test.js+++ b/server/lib/authGate.test.js@@ -172,6 +172,52 @@ describe('authGate middleware', () => {expect(result.called).toBe(true);});+ it('allows mixed-case same-origin hostnames (RFC 3986 case-insensitive)', async () => {+ const auth = await import('../services/auth.js');+ const { token } = await auth.setPassword({ newPassword: 'correct-horse' });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, {+ path: '/api/cos',+ headers: {+ host: 'PortOS.Tailnet.ts.net',+ origin: 'https://portos.tailnet.ts.net',+ cookie: `portos_auth=${token}`,+ },+ });+ expect(result.called).toBe(true);+ });++ it('allows loopback↔loopback cross-port (Vite dev proxy)', async () => {+ const auth = await import('../services/auth.js');+ const { token } = await auth.setPassword({ newPassword: 'correct-horse' });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, {+ path: '/api/cos',+ headers: {+ host: 'localhost:5555',+ origin: 'http://localhost:5554',+ cookie: `portos_auth=${token}`,+ },+ });+ expect(result.called).toBe(true);+ });++ it('rejects a cross-origin logout (public path still gets the CSRF check)', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, {+ path: '/api/auth/logout',+ headers: {+ host: 'portos.tailnet.ts.net',+ origin: 'https://evil.tailnet.ts.net',+ },+ });+ expect(result.called).toBe(false);+ expect(result.res.statusCode).toBe(403);+ expect(result.res.body.code).toBe('CROSS_ORIGIN_BLOCKED');+ });+it('treats a malformed Origin header as cross-origin', async () => {const auth = await import('../services/auth.js');const { token } = await auth.setPassword({ newPassword: 'correct-horse' });diff --git a/server/services/auth.js b/server/services/auth.jsindex f98aac4e3a..d328279532 100644--- a/server/services/auth.js+++ b/server/services/auth.js@@ -47,7 +47,10 @@ const SCRYPT_PARAMS = { N: 131072, r: 8, p: 1, maxmem: 256 * 1024 * 1024 };// `auth-sessions.json` (e.g. from a backup or peer-sync mirror) doesn't yield// usable credentials.const sessions = new Map();-let loaded = false;+// Single in-flight load promise — both callers await the SAME promise so a+// burst of concurrent verifySession calls after a restart can't observe an+// empty Map while the first call is still reading auth-sessions.json.+let loadPromise = null;const now = () => Date.now();@@ -77,11 +80,12 @@ const writeSessions = async () => {};const ensureLoaded = async () => {- if (loaded) return;- loaded = true;- await readSessions().catch((err) => {- console.error(`❌ Failed to load auth sessions: ${err.message}`);- });+ if (!loadPromise) {+ loadPromise = readSessions().catch((err) => {+ console.error(`❌ Failed to load auth sessions: ${err.message}`);+ });+ }+ return loadPromise;};const hashPassword = async (password, salt) => {@@ -115,7 +119,15 @@ const recomputeEnabledCache = (settings) => {settingsEvents.on('settings:updated', recomputeEnabledCache);export const isAuthEnabled = async () => {- if (enabledCache === null) recomputeEnabledCache(await getSettings());+ if (enabledCache === null) {+ const settings = await getSettings();+ // Double-check after the await — a concurrent updateSettings firing+ // settings:updated between the null check and this point would have+ // primed the cache already; clobbering it with the stale pre-write+ // snapshot would open a fail-open window if the concurrent write+ // was a first-time auth enable.+ if (enabledCache === null) recomputeEnabledCache(settings);+ }return enabledCache;};@@ -219,8 +231,9 @@ export const revokeSession = async (token) => {await writeSessions();// Logging-out one tab kicks every connected socket too — the// single-user model means broadcast events shouldn't keep streaming- // to a tab whose cookie was just cleared.- authEvents.emit('sessions:revoked-all');+ // 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'));}};@@ -232,7 +245,14 @@ export const revokeAllSessions = async () => {// (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');+ //+ // 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'));};// Parse the `Cookie` header for our token. Express doesn't ship a cookiediff --git a/server/services/auth.test.js b/server/services/auth.test.jsindex cb0eeacd2e..2b8fc397e6 100644--- a/server/services/auth.test.js+++ b/server/services/auth.test.js@@ -168,10 +168,40 @@ describe('auth service', () => {await auth.setPassword({ newPassword: 'correct-horse' }); // first-time enableawait auth.setPassword({ newPassword: 'new-horse', currentPassword: 'correct-horse' }); // rotateawait auth.clearPassword({ currentPassword: 'new-horse' }); // disable- // setPassword/clearPassword both call revokeAllSessions internally.+ // 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));expect(events.length).toBe(3);});+ 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+ // so it survives the resetModules below — setPassword would otherwise+ // overwrite anything we wrote before it.+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ const { writeFileSync } = await import('fs');+ const { join } = await import('path');+ const { createHash } = await import('crypto');+ const fakeToken = 'a'.repeat(64);+ const fakeHash = createHash('sha256').update(fakeToken).digest('hex');+ writeFileSync(join(tempRoot, 'auth-sessions.json'), JSON.stringify({+ tokens: [{ tokenHash: fakeHash, expiresAt: Date.now() + 60_000 }],+ }) + '\n');+ // Simulate a server restart — fresh module = empty in-memory sessions Map.+ vi.resetModules();+ const fresh = await import('./auth.js');+ // Burst of concurrent calls — without coalescing, calls 2+ would see+ // the load-flag set but the Map still empty and return false.+ const results = await Promise.all([+ fresh.verifySession(fakeToken),+ fresh.verifySession(fakeToken),+ fresh.verifySession(fakeToken),+ ]);+ expect(results).toEqual([true, true, true]);+ });+it('emits sessions:revoked-all on single-token logout too (kicks the tab\'s sockets)', async () => {const auth = await import('./auth.js');await auth.setPassword({ newPassword: 'correct-horse' });@@ -179,9 +209,11 @@ describe('auth service', () => {const events = [];auth.authEvents.on('sessions:revoked-all', () => events.push('event'));await auth.revokeSession(token);+ await new Promise((resolve) => setImmediate(resolve));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));expect(events.length).toBe(1);});});