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): reject cross-origin requests when auth is on
Adam Eivye7832834a9c0
diff --git a/server/lib/authGate.js b/server/lib/authGate.jsindex 46aa1fc157..316adf976d 100644--- a/server/lib/authGate.js+++ b/server/lib/authGate.js@@ -36,6 +36,30 @@ const isPublicPath = (path) => {return true;};+// Reject cross-origin requests when auth is on. PortOS's CORS middleware+// reflects `Origin` with `Access-Control-Allow-Credentials: true` so the UI+// works from any tailnet hostname / IP — but combined with the session+// cookie that becomes a CSRF surface: a malicious page on another tailnet+// host can fetch PortOS APIs with `credentials: 'include'` after the user+// has logged in (Tailscale's `ts.net` is on the Public Suffix List, so+// SameSite=Lax doesn't help — same-tailnet hosts are same-site). Match the+// `Origin` header's host:port against the request's own `Host` header; any+// 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.+const isCrossOrigin = (req) => {+ const origin = req.headers?.origin;+ if (!origin || origin === 'null') return false;+ const host = req.headers?.host;+ if (!host) return false;+ // URL parses scheme://authority — we only compare the authority. A+ // malformed Origin (URL constructor throws) is treated as cross-origin.+ let parsed;+ try { parsed = new URL(origin); }+ catch { return true; }+ return parsed.host !== host;+};+// Express middleware. Bypasses everything when auth is off. When it's on,// allows the small public set above; gates the rest behind a valid token in// the cookie or Authorization: Bearer header.@@ -44,6 +68,14 @@ export const authGate = async (req, res, next) => {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.+ if (isCrossOrigin(req)) {+ res.status(403).json({ error: 'Cross-origin request rejected', code: 'CROSS_ORIGIN_BLOCKED' });+ return;+ }const token = extractToken(req);if (await verifySession(token)) return next();// /data/* is hit directly by <img>/<audio>/<video> tags which don't show a@@ -64,6 +96,11 @@ export const socketAuthGate = async (socket, next) => {const enabled = await isAuthEnabled();if (!enabled) return next();const fakeReq = { headers: socket.handshake?.headers || {} };+ if (isCrossOrigin(fakeReq)) {+ const err = new Error('Cross-origin request rejected');+ err.data = { code: 'CROSS_ORIGIN_BLOCKED' };+ return next(err);+ }const token = extractToken(fakeReq);if (await verifySession(token)) return next();const err = new Error('Authentication required');diff --git a/server/lib/authGate.test.js b/server/lib/authGate.test.jsindex fdf96981ab..f2e81af700 100644--- a/server/lib/authGate.test.js+++ b/server/lib/authGate.test.js@@ -122,6 +122,70 @@ describe('authGate middleware', () => {expect(result.res.statusCode).toBe(401);expect(result.res.body.code).toBe('AUTH_REQUIRED');});++ it('rejects cross-origin requests with 403 before consulting the session', async () => {+ const auth = await import('../services/auth.js');+ const { token } = await auth.setPassword({ newPassword: 'correct-horse' });+ const { authGate } = await import('./authGate.js');+ // Even a VALID session cookie can't rescue a cross-origin request —+ // the gate must reject before reading the cookie, since CSRF+ // side-effects land regardless of whether the response is visible.+ const result = await runGate(authGate, {+ path: '/api/cos',+ headers: {+ host: 'portos.tailnet.ts.net',+ origin: 'https://evil.tailnet.ts.net',+ cookie: `portos_auth=${token}`,+ },+ });+ expect(result.called).toBe(false);+ expect(result.res.statusCode).toBe(403);+ expect(result.res.body.code).toBe('CROSS_ORIGIN_BLOCKED');+ });++ it('allows same-origin requests when Origin matches Host', 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 requests without an Origin header (curl, server-to-server)', 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',+ cookie: `portos_auth=${token}`,+ },+ });+ expect(result.called).toBe(true);+ });++ 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' });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, {+ path: '/api/cos',+ headers: {+ host: 'portos.tailnet.ts.net',+ origin: 'not a valid url',+ cookie: `portos_auth=${token}`,+ },+ });+ expect(result.res.statusCode).toBe(403);+ });});describe('socketAuthGate middleware', () => {@@ -153,4 +217,23 @@ describe('socketAuthGate middleware', () => {});expect(err).toBeUndefined();});++ it('rejects a cross-origin handshake', async () => {+ const auth = await import('../services/auth.js');+ const { token } = await auth.setPassword({ newPassword: 'correct-horse' });+ const { socketAuthGate } = await import('./authGate.js');+ const err = await new Promise((resolve) => {+ socketAuthGate({+ handshake: {+ headers: {+ host: 'portos.tailnet.ts.net',+ origin: 'https://evil.tailnet.ts.net',+ cookie: `portos_auth=${token}`,+ },+ },+ }, (e) => resolve(e));+ });+ expect(err).toBeInstanceOf(Error);+ expect(err.data).toEqual({ code: 'CROSS_ORIGIN_BLOCKED' });+ });});