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
fix: port-scope the session cookie so a same-host HTTPS PortOS can't block HTTP logins
atomanticagentd2f8bfbb087b
diff --git a/lib/portosAuthCore.js b/lib/portosAuthCore.jsindex 815ed0d7dc..8c59e18a74 100644--- a/lib/portosAuthCore.js+++ b/lib/portosAuthCore.js@@ -88,22 +88,91 @@ export const parseCookie = (cookieHeader, name) => {export const parseCookieToken = (cookieHeader) => parseCookie(cookieHeader, COOKIE_NAME);-// Pull the session token from a request — cookie first, then-// `Authorization: Bearer`. Bearer support lets curl/scripts authenticate-// without juggling cookies. Header names are lowercased by both Node's HTTP-// parser and Socket.IO's handshake, so no uppercase fallback is needed.-export const extractToken = (req) => {- const cookie = parseCookieToken(req.headers?.cookie);- if (cookie) return cookie;+// Cookies are scoped by host, NOT port (RFC 6265 §8.5). Two PortOS installs a+// browser reaches on the same host — e.g. a Mac's own PortOS on+// https://127.0.0.1:5555 and a remote box tunnelled to http://127.0.0.1:15555+// by `tailcat forward` — used to share one `portos_auth` cookie slot, so each+// login clobbered the other's session. Worse: once the HTTPS install stored a+// `Secure` `portos_auth`, browsers that treat http://127.0.0.1 as insecure+// (Safari/WebKit, Firefox) refuse to let the plain-HTTP install set a cookie+// of the same name at all ("leave secure cookies alone", RFC 6265bis §5.7),+// so its login succeeded server-side and the SPA bounced straight back to+// /login with no cookie stored. The session cookie name therefore carries the+// port the browser used (from `Host`), falling back to the legacy bare name+// when the origin uses the scheme's default port. Readers accept every+// PortOS session cookie (legacy + any port-scoped one) and verify each, so+// a sidecar on another port (Autofixer UI on :5560) still inherits the main+// UI's session, and a foreign install's cookie is simply not a valid token.+const SCOPED_COOKIE_RE = /^portos_auth_(\d{1,5})$/;+// Bound the per-request work a hostile Cookie header can cause.+const MAX_SESSION_COOKIES = 8;++export const sessionCookieNameFor = (hostHeader) => {+ if (typeof hostHeader !== 'string') return COOKIE_NAME;+ const match = /:(\d{1,5})$/.exec(hostHeader.trim());+ if (!match) return COOKIE_NAME;+ const port = Number(match[1]);+ if (!Number.isInteger(port) || port < 1 || port > 65535) return COOKIE_NAME;+ return `${COOKIE_NAME}_${port}`;+};++export const isSessionCookieName = (name) => name === COOKIE_NAME || SCOPED_COOKIE_RE.test(name);++// Every PortOS session cookie value in a `Cookie` header, in header order,+// de-duplicated. `{ name, value }` so callers can tell legacy from scoped.+export const parseSessionCookies = (cookieHeader) => {+ const found = [];+ if (typeof cookieHeader !== 'string') return found;+ const seen = new Set();+ for (const part of cookieHeader.split(';')) {+ if (found.length >= MAX_SESSION_COOKIES) break;+ const eq = part.indexOf('=');+ if (eq === -1) continue;+ const name = part.slice(0, eq).trim();+ if (!isSessionCookieName(name)) continue;+ let value;+ try { value = decodeURIComponent(part.slice(eq + 1).trim()); }+ catch { continue; }+ if (!value || seen.has(`${name}=${value}`)) continue;+ seen.add(`${name}=${value}`);+ found.push({ name, value });+ }+ return found;+};++const bearerToken = (req) => {const authHeader = req.headers?.authorization;// RFC 6750: the Bearer scheme name is case-insensitive.if (typeof authHeader === 'string' && authHeader.length > 7&& authHeader.slice(0, 7).toLowerCase() === 'bearer ') {- return authHeader.slice(7).trim();+ return authHeader.slice(7).trim() || null;}return null;};+// Every candidate session token on a request: all PortOS session cookies+// (the one for this request's own port first), then `Authorization: Bearer`.+// Callers must accept the request if ANY candidate verifies — a stale or+// foreign cookie must not mask a valid one.+export const extractTokens = (req) => {+ const own = sessionCookieNameFor(req.headers?.host);+ const cookies = parseSessionCookies(req.headers?.cookie);+ const ordered = [+ ...cookies.filter((c) => c.name === own),+ ...cookies.filter((c) => c.name !== own),+ ].map((c) => c.value);+ const bearer = bearerToken(req);+ if (bearer) ordered.push(bearer);+ return [...new Set(ordered)];+};++// Pull the first candidate session token from a request — cookie first, then+// `Authorization: Bearer`. Bearer support lets curl/scripts authenticate+// without juggling cookies. Header names are lowercased by both Node's HTTP+// parser and Socket.IO's handshake, so no uppercase fallback is needed.+// Prefer `extractTokens` + verify-any for authorization decisions.+export const extractToken = (req) => extractTokens(req)[0] ?? null;+// Extract the password from an `Authorization: Basic <base64>` header. PortOS// is single-user so the username is ignored; only the password is validated.// Used by peer-to-peer federation probes and by scripts hitting a sidecar.diff --git a/lib/sidecarAuthGate.js b/lib/sidecarAuthGate.jsindex a2ddbdffd0..2a19064b0f 100644--- a/lib/sidecarAuthGate.js+++ b/lib/sidecarAuthGate.js@@ -35,7 +35,7 @@ import { join } from 'node:path';import {createLoginThrottle,extractBasicPassword,- extractToken,+ extractTokens,hashToken,isCrossOrigin,parseCookie,@@ -146,7 +146,12 @@ export const createSidecarAuthGate = ({// Corrupt settings → no usable password hash → nothing can authenticate.if (corrupt || !auth?.passwordHash || !auth.salt) return false;if (verifySidecarCookie(auth, parseCookie(req.headers?.cookie, cookieName))) return true;- if (await verifyServerSession(extractToken(req))) return true;+ // Any PortOS session cookie (legacy or port-scoped — the main UI's+ // `portos_auth_5555` rides along to :5560 because cookies ignore port) or+ // Bearer token; a foreign install's cookie simply doesn't verify.+ for (const token of extractTokens(req)) {+ if (await verifyServerSession(token)) return true;+ }const basic = extractBasicPassword(req);if (basic && await verifyPasswordAgainst(auth, basic)) return true;return false;diff --git a/lib/sidecarAuthGate.test.js b/lib/sidecarAuthGate.test.jsindex 3a5f4298ad..bfbe21ba20 100644--- a/lib/sidecarAuthGate.test.js+++ b/lib/sidecarAuthGate.test.js@@ -111,6 +111,13 @@ describe('createSidecarAuthGate', () => {expect(ok.nexted).toBe(true);});+ it('accepts the main UI\'s port-scoped cookie even behind a stale legacy one', async () => {+ await writeSessions([{ tokenHash: hashToken('tok-scoped'), expiresAt: Date.now() + 60_000 }]);+ const { gate } = makeGate();+ const ok = await run(gate, req('/api/apps', { cookie: 'portos_auth=tok-stale; portos_auth_5555=tok-scoped' }));+ expect(ok.nexted).toBe(true);+ });+it('rejects an expired or unknown session token', async () => {await writeSessions([{ tokenHash: hashToken('tok-old'), expiresAt: Date.now() - 1 }]);const { gate } = makeGate();diff --git a/server/routes/auth.js b/server/routes/auth.jsindex 8f1e1778aa..de778fffcb 100644--- a/server/routes/auth.js+++ b/server/routes/auth.js@@ -7,16 +7,19 @@ import {clearLoginFailures,clearPassword,createSession,- extractToken,+ extractTokens,getAuthStatus,isAuthEnabled,isLoginRateLimited,listSessions,+ parseSessionCookies,recordLoginFailure,revokeSession,revokeSessionById,+ sessionCookieNameFor,setPassword,verifyPassword,+ verifyRequestSession,verifySession,} from '../services/auth.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';@@ -38,6 +41,33 @@ const sessionIdParamSchema = z.object({ id: z.string().min(1).max(64).regex(/^[a// deployment topology.const isSecure = (req) => !!req.secure;+// The session cookie name is port-scoped from the browser-facing `Host` (see+// sessionCookieNameFor in lib/portosAuthCore.js) — e.g. `portos_auth_15555`+// behind a `tailcat forward 15555:5555` — so this install never shares (or is+// blocked by a `Secure`) cookie slot with another PortOS on the same host.+const sessionCookieFor = (req, token) =>+ buildSessionCookie(token, { secure: isSecure(req), name: sessionCookieNameFor(req.headers?.host) });++// Names of this install's OTHER session cookies on the request (e.g. a legacy+// bare `portos_auth` minted before the port-scoped name) — only those whose+// token is live HERE, so we never clear a sibling install's cookie that+// happens to share the host.+const ownedStaleCookieNames = async (req) => {+ const own = sessionCookieNameFor(req.headers?.host);+ const names = [];+ for (const { name, value } of parseSessionCookies(req.headers?.cookie)) {+ if (name === own || names.includes(name)) continue;+ if (await verifySession(value)) names.push(name);+ }+ return names;+};++const clearCookiesFor = (req, extraNames = []) => {+ const secure = isSecure(req);+ const names = [sessionCookieNameFor(req.headers?.host), ...extraNames];+ return [...new Set(names)].map((name) => buildClearCookie({ secure, name }));+};+// GET /api/auth/status — always reachable. The UI uses this to know whether// to render the login gate at all.router.get('/status', asyncHandler(async (_req, res) => {@@ -58,8 +88,7 @@ router.get('/whoami', asyncHandler(async (req, res) => {res.json({ authenticated: true, required: false });return;}- const token = extractToken(req);- const authenticated = await verifySession(token);+ const authenticated = !!(await verifyRequestSession(req));res.json({ authenticated, required: true });}));@@ -87,16 +116,19 @@ router.post('/login', asyncHandler(async (req, res) => {// it right isn't kept locked out.clearLoginFailures(clientIp);const { token } = await createSession();- res.setHeader('Set-Cookie', buildSessionCookie(token, { secure: isSecure(req) }));+ res.setHeader('Set-Cookie', sessionCookieFor(req, token));res.json({ authenticated: true });}));// POST /api/auth/logout — best-effort revoke + clear cookie. Idempotent so a// double-click on Sign Out doesn't 401.router.post('/logout', asyncHandler(async (req, res) => {- const token = extractToken(req);- if (token) await revokeSession(token);- res.setHeader('Set-Cookie', buildClearCookie({ secure: isSecure(req) }));+ // Revoke every live token the request carries (port-scoped cookie, a+ // pre-upgrade legacy cookie, Bearer) so signing out can't leave a second+ // valid cookie behind. revokeSession is a no-op for foreign tokens.+ const stale = await ownedStaleCookieNames(req);+ for (const token of extractTokens(req)) await revokeSession(token);+ res.setHeader('Set-Cookie', clearCookiesFor(req, stale));res.json({ ok: true });}));@@ -110,11 +142,16 @@ router.post('/password', asyncHandler(async (req, res) => {// First-time set is the ONLY public mutation here — once auth is on, the// route is gated by the API auth middleware in server/index.js, so we// reach this branch only with a valid session.+ const stale = await ownedStaleCookieNames(req);const { token } = await setPassword({newPassword: body.newPassword,currentPassword: alreadyEnabled ? body.currentPassword : null,});- res.setHeader('Set-Cookie', buildSessionCookie(token, { secure: isSecure(req) }));+ const secure = isSecure(req);+ res.setHeader('Set-Cookie', [+ sessionCookieFor(req, token),+ ...stale.map((name) => buildClearCookie({ secure, name })),+ ]);res.json({ enabled: true });}));@@ -123,8 +160,9 @@ router.post('/password', asyncHandler(async (req, res) => {// silently disable the gate.router.delete('/password', asyncHandler(async (req, res) => {const { currentPassword } = validateRequest(clearPasswordSchema, req.body || {});+ const stale = await ownedStaleCookieNames(req);await clearPassword({ currentPassword });- res.setHeader('Set-Cookie', buildClearCookie({ secure: isSecure(req) }));+ res.setHeader('Set-Cookie', clearCookiesFor(req, stale));res.json({ enabled: false });}));diff --git a/server/routes/auth.test.js b/server/routes/auth.test.jsindex e87056bcbb..facd4ce298 100644--- a/server/routes/auth.test.js+++ b/server/routes/auth.test.js@@ -4,7 +4,7 @@ import { writeFileSync } from 'fs';import { join } from 'path';import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';import { bindSettingsFile } from '../lib/settingsTestUtil.js';-import { request } from '../lib/testHelper.js';+import { closeLoopbackServer, request, startLoopbackServer } from '../lib/testHelper.js';const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-auth-routes-' });@@ -81,7 +81,8 @@ describe('auth routes', () => {expect(res.status).toBe(200);expect(res.body).toEqual({ enabled: true });const setCookie = res.headers['set-cookie'];- expect(setCookie).toMatch(/portos_auth=/);+ // Port-scoped from Host (the harness listens on a random loopback port).+ expect(setCookie).toMatch(/portos_auth_\d+=/);expect(setCookie).toMatch(/HttpOnly/);});@@ -121,7 +122,7 @@ describe('auth routes', () => {const good = await request(app).post('/api/auth/login').send({ password: 'correct-horse' });expect(good.status).toBe(200);expect(good.body).toEqual({ authenticated: true });- expect(good.headers['set-cookie']).toMatch(/portos_auth=/);+ expect(good.headers['set-cookie']).toMatch(/portos_auth_\d+=/);});it('POST /api/auth/logout always clears the cookie', async () => {@@ -132,6 +133,64 @@ describe('auth routes', () => {expect(res.headers['set-cookie']).toMatch(/Max-Age=0/);});+ it('POST /api/auth/login names the cookie after the browser-facing port and never marks plain HTTP Secure', async () => {+ let app = await buildApp();+ await request(app).post('/api/auth/password').send({ newPassword: 'correct-horse' });+ app = await buildApp();+ const res = await request(app).post('/api/auth/login').send({ password: 'correct-horse' });+ expect(res.status).toBe(200);+ const setCookie = res.headers['set-cookie'];+ // One cookie, `portos_auth_<port>`, host-only (no Domain), Path=/, Lax,+ // and NOT Secure over plain HTTP — a Secure cookie would be dropped on+ // http://127.0.0.1:15555 behind a tailcat forward.+ expect(setCookie).toMatch(/^portos_auth_\d+=[a-f0-9]{64}; Path=\/; HttpOnly; SameSite=Lax; Max-Age=\d+$/);+ expect(setCookie).not.toMatch(/Secure|Domain=/);+ });++ it('GET /api/auth/whoami accepts a valid session even when a sibling install\'s same-host cookie comes first', async () => {+ let app = await buildApp();+ await request(app).post('/api/auth/password').send({ newPassword: 'correct-horse' });+ app = await buildApp();+ const login = await request(app).post('/api/auth/login').send({ password: 'correct-horse' });+ const [, name, token] = /^(portos_auth_\d+)=([a-f0-9]+)/.exec(login.headers['set-cookie']);+ // e.g. the Mac's own PortOS on 127.0.0.1:5555 left `portos_auth` and+ // `portos_auth_5555` behind — cookies ignore port, so both ride along.+ const res = await request(app).get('/api/auth/whoami')+ .set('Cookie', `portos_auth=${'a'.repeat(64)}; portos_auth_5555=${'b'.repeat(64)}; ${name}=${token}`);+ expect(res.body).toEqual({ authenticated: true, required: true });+ const foreignOnly = await request(app).get('/api/auth/whoami')+ .set('Cookie', `portos_auth=${'a'.repeat(64)}; portos_auth_5555=${'b'.repeat(64)}`);+ expect(foreignOnly.body).toEqual({ authenticated: false, required: true });+ });++ it('POST /api/auth/logout revokes a pre-upgrade legacy cookie and leaves a sibling install\'s cookie alone', async () => {+ let app = await buildApp();+ const { token: legacy } = await (await import('../services/auth.js')).setPassword({ newPassword: 'correct-horse' });+ app = await buildApp();+ const foreign = 'c'.repeat(64);+ // A real socket + getSetCookie(): the shared request() helper collapses+ // repeated Set-Cookie headers to the last one.+ const server = await startLoopbackServer(app);+ const { port } = server.address();+ let setCookies;+ try {+ const out = await fetch(`http://127.0.0.1:${port}/api/auth/logout`, {+ method: 'POST',+ headers: { cookie: `portos_auth=${legacy}; portos_auth_5555=${foreign}` },+ });+ setCookies = out.headers.getSetCookie();+ } finally {+ await closeLoopbackServer(server);+ }+ expect(setCookies).toEqual([+ `portos_auth_${port}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`,+ // Our pre-upgrade legacy cookie is cleared; the sibling's is not.+ 'portos_auth=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0',+ ]);+ const after = await request(app).get('/api/auth/whoami').set('Cookie', `portos_auth=${legacy}`);+ expect(after.body).toEqual({ authenticated: false, required: true });+ });+it('GET /api/auth/sessions lists live sessions without leaking the token', async () => {let app = await buildApp();const setupRes = await request(app).post('/api/auth/password').send({ newPassword: 'correct-horse' });diff --git a/server/routes/commands.test.js b/server/routes/commands.test.jsindex 1245c52763..382ae26b82 100644--- a/server/routes/commands.test.js+++ b/server/routes/commands.test.js@@ -38,11 +38,16 @@ vi.mock('fs', async (importOriginal) => {});vi.mock('../services/auth.js', async () => {- const { extractToken } = await import('../../lib/portosAuthCore.js');+ const { extractToken, extractTokens } = await import('../../lib/portosAuthCore.js');+ const verifySession = vi.fn(async token => token === 'example-operator-session');return {extractToken,isAuthEnabled: vi.fn().mockResolvedValue(false),- verifySession: vi.fn(async token => token === 'example-operator-session'),+ verifySession,+ verifyRequestSession: async (req) => {+ for (const token of extractTokens(req)) if (await verifySession(token)) return token;+ return null;+ },verifyPassword: vi.fn(async password => password === 'example-peer-password'),};});diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 2c374e80d9..074c090968 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -5,7 +5,7 @@*/import { Router } from 'express';-import { extractToken, verifySession } from '../services/auth.js';+import { verifyRequestSession } from '../services/auth.js';import { isCrossOrigin } from '../../lib/portosAuthCore.js';import { z } from 'zod';import * as instances from '../services/instances.js';@@ -33,7 +33,7 @@ router.use(asyncHandler(async (req, _res, next) => {// Vite and other private transports can forward a remote request over a// loopback socket. Neither that socket nor supplied Origin/Host proves the// operator's identity. Verify the existing session even when auth is off.- if (!isCrossOrigin(req) && await verifySession(extractToken(req))) {+ if (!isCrossOrigin(req) && await verifyRequestSession(req)) {req.peerSettingsOperator = true;return next();}diff --git a/server/routes/instances.test.js b/server/routes/instances.test.jsindex 9cc51a0b94..0cedfd050f 100644--- a/server/routes/instances.test.js+++ b/server/routes/instances.test.js@@ -2,11 +2,15 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import express from 'express';import { remoteRequestHandler } from '../lib/requestOrigin.js';import { verifySession } from '../services/auth.js';-vi.mock('../services/auth.js', () => ({- extractToken: req => req.headers.authorization,- verifySession: vi.fn().mockResolvedValue(true),- isAuthEnabled: vi.fn().mockResolvedValue(false),-}));+vi.mock('../services/auth.js', () => {+ const verifySession = vi.fn().mockResolvedValue(true);+ return {+ extractToken: req => req.headers.authorization,+ verifySession,+ verifyRequestSession: async req => ((await verifySession(req.headers.authorization)) ? 'mock-session' : null),+ isAuthEnabled: vi.fn().mockResolvedValue(false),+ };+});import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';diff --git a/server/routes/managedVisitors.test.js b/server/routes/managedVisitors.test.jsindex 60f7c05f81..0ae7591b3c 100644--- a/server/routes/managedVisitors.test.js+++ b/server/routes/managedVisitors.test.js@@ -8,7 +8,9 @@ import { createManagedVisitorBroker, managedVisitorContract } from '../services/import { request } from '../lib/testHelper.js';const shared = vi.hoisted(() => ({ enabled: false, broker: null }));vi.mock('../services/auth.js', () => ({ isAuthEnabled: async () => shared.enabled, extractToken: req => req.headers.authorization?.slice(7),- verifySession: async token => token === 'owner-session', verifyPassword: async () => false }));+ verifySession: async token => token === 'owner-session',+ verifyRequestSession: async req => (req.headers.authorization?.slice(7) === 'owner-session' ? 'owner-session' : null),+ verifyPassword: async () => false }));vi.mock('../services/settings.js', () => ({ getSettings: async () => ({}), settingsEvents: new EventEmitter() }));vi.mock('../services/managedVisitors.js', async () => {const actual = await vi.importActual('../services/managedVisitors.js');diff --git a/server/services/auth.js b/server/services/auth.jsindex 33ac89b2d0..c4f6b5edee 100644--- a/server/services/auth.js+++ b/server/services/auth.js@@ -11,9 +11,12 @@ import {constantEqual,createLoginThrottle,extractToken,+ extractTokens,hashPassword,hashToken,parseCookieToken,+ parseSessionCookies,+ sessionCookieNameFor,} from '../../lib/portosAuthCore.js';import { getSettings, readSettingsStrict, settingsEvents, updateSettings } from './settings.js';import { ServerError } from '../lib/errorHandler.js';@@ -335,6 +338,17 @@ export const verifySession = async (token) => {return true;};+// Authorize a request against every candidate token it carries (all PortOS+// session cookies + Bearer — see extractTokens). Returns the first token that+// verifies, or null. A stale or foreign same-host cookie (another PortOS on a+// different port of the same host) must never mask this install's valid one.+export const verifyRequestSession = async (req) => {+ for (const token of extractTokens(req)) {+ if (await verifySession(token)) return token;+ }+ return null;+};+export const revokeSession = async (token) => {await ensureLoaded();if (sessions.delete(hashToken(token))) {@@ -376,15 +390,17 @@ export const clearLoginFailures = (ip) => loginThrottle.clear(ip);// Cookie parsing + token extraction are shared with sidecars. Re-exported here// so existing importers of this module keep working unchanged.-export { parseCookieToken, extractToken };+export { parseCookieToken, parseSessionCookies, extractToken, extractTokens, sessionCookieNameFor };-export const buildSessionCookie = (token, { secure = false } = {}) => {+export const buildSessionCookie = (token, { secure = false, name = COOKIE_NAME } = {}) => {// HttpOnly so XSS can't read it; SameSite=Lax so cross-origin GETs from the// browser address bar work but cross-site POSTs are blocked. `Secure` is// toggled by the caller based on the loopback-mirror vs HTTPS scheme of the// request — a `Secure` cookie on a plain-http request is silently dropped.+ // `name` is port-scoped by the caller (sessionCookieNameFor) so two+ // installs reached on one host never share a cookie slot.const parts = [- `${COOKIE_NAME}=${encodeURIComponent(token)}`,+ `${name}=${encodeURIComponent(token)}`,'Path=/','HttpOnly','SameSite=Lax',@@ -394,14 +410,14 @@ export const buildSessionCookie = (token, { secure = false } = {}) => {return parts.join('; ');};-export const buildClearCookie = ({ secure = false } = {}) => {+export const buildClearCookie = ({ secure = false, name = COOKIE_NAME } = {}) => {// Mirror the `Secure` attribute on the clear so RFC 6265bis-conformant// browsers can match-and-delete by full attribute set. Today most// browsers still clear by name+path+domain alone; Chrome has been// tightening this, and a future change could leave the cookie// un-deletable on HTTPS sessions if we drop the attribute here.const parts = [- `${COOKIE_NAME}=`,+ `${name}=`,'Path=/','HttpOnly','SameSite=Lax',diff --git a/server/services/auth.test.js b/server/services/auth.test.jsindex 26e29ac822..88b438175f 100644--- a/server/services/auth.test.js+++ b/server/services/auth.test.js@@ -196,6 +196,46 @@ describe('auth service', () => {expect(auth.extractToken({ headers: {} })).toBe(null);});+ it('scopes the session cookie name to the browser-facing port', async () => {+ const auth = await import('./auth.js');+ expect(auth.sessionCookieNameFor('127.0.0.1:15555')).toBe('portos_auth_15555');+ expect(auth.sessionCookieNameFor('box.tailnet.ts.net:5555')).toBe('portos_auth_5555');+ expect(auth.sessionCookieNameFor('[::1]:5553')).toBe('portos_auth_5553');+ // Default-port origins (e.g. `tailscale serve` on 443) keep the legacy name.+ expect(auth.sessionCookieNameFor('box.tailnet.ts.net')).toBe('portos_auth');+ expect(auth.sessionCookieNameFor('[::1]')).toBe('portos_auth');+ expect(auth.sessionCookieNameFor(undefined)).toBe('portos_auth');+ expect(auth.sessionCookieNameFor('host:0')).toBe('portos_auth');+ expect(auth.sessionCookieNameFor('host:99999')).toBe('portos_auth');+ expect(auth.buildSessionCookie('tok', { name: 'portos_auth_15555' })).toMatch(/^portos_auth_15555=tok; /);+ expect(auth.buildClearCookie({ name: 'portos_auth_15555' })).toMatch(/^portos_auth_15555=; .*Max-Age=0/);+ });++ it('extracts every PortOS session cookie, own port first, then Bearer', async () => {+ const auth = await import('./auth.js');+ const req = {+ headers: {+ host: '127.0.0.1:15555',+ cookie: 'portos_auth=legacy; other=x; portos_auth_5555=mac; portos_auth_15555=mine; portos_autofixer_auth=side; portos_auth_x=no',+ authorization: 'Bearer bearer-tok',+ },+ };+ expect(auth.extractTokens(req)).toEqual(['mine', 'legacy', 'mac', 'bearer-tok']);+ expect(auth.extractToken(req)).toBe('mine');+ expect(auth.parseSessionCookies('portos_auth=%E0; portos_auth_1=ok; portos_auth_1=ok')).toEqual([{ name: 'portos_auth_1', value: 'ok' }]);+ const many = Array.from({ length: 20 }, (_, i) => `portos_auth_${i + 1}=t${i}`).join('; ');+ expect(auth.parseSessionCookies(many)).toHaveLength(8);+ });++ it('verifyRequestSession accepts any live candidate so a stale same-host cookie cannot mask it', async () => {+ const auth = await import('./auth.js');+ const { token } = await auth.createSession();+ const headers = { host: '127.0.0.1:15555', cookie: `portos_auth=${'d'.repeat(64)}; portos_auth_15555=${token}` };+ expect(await auth.verifyRequestSession({ headers })).toBe(token);+ expect(await auth.verifyRequestSession({ headers: { cookie: `portos_auth=${'d'.repeat(64)}`, authorization: `Bearer ${token}` } })).toBe(token);+ expect(await auth.verifyRequestSession({ headers: { cookie: `portos_auth=${'d'.repeat(64)}` } })).toBe(null);+ });+it('builds session and clear cookies with the right flags', async () => {const auth = await import('./auth.js');const cookie = auth.buildSessionCookie('tok', { secure: true });diff --git a/server/services/authGate.js b/server/services/authGate.jsindex 051f7a6626..a0de3edad1 100644--- a/server/services/authGate.js+++ b/server/services/authGate.js@@ -1,6 +1,6 @@import { createHash, timingSafeEqual } from 'node:crypto';import { isIP } from 'node:net';-import { extractToken, isAuthEnabled, verifyPassword, verifySession } from './auth.js';+import { isAuthEnabled, verifyPassword, verifyRequestSession } from './auth.js';// Shared with sidecar processes (lib/sidecarAuthGate.js) so the Autofixer UI// on :5560 applies byte-identical credential extraction and CSRF rules.import { DEV_PROXY_CLIENT_ADDRESS_HEADER, extractBasicPassword, isCrossOrigin } from '../../lib/portosAuthCore.js';@@ -169,8 +169,7 @@ export const authGate = async (req, res, next) => {// introduced here so a Settings toggle takes effect on the very next request.const settings = await getSettings();if (isRegistryPublic(settings, path)) return next();- const token = extractToken(req);- if (await verifySession(token)) {+ if (await verifyRequestSession(req)) {req.portosAuthContext = { enabled: true, authenticated: true, method: 'session' };return next();}@@ -268,8 +267,7 @@ export const socketAuthGate = async (socket, next) => {err.data = { code: 'CROSS_ORIGIN_BLOCKED' };return next(err);}- const token = extractToken(fakeReq);- if (await verifySession(token)) {+ if (await verifyRequestSession(fakeReq)) {markAuthMethod(socket, 'session');return next();}diff --git a/server/services/authGate.test.js b/server/services/authGate.test.jsindex 4c251b453e..2e685039e4 100644--- a/server/services/authGate.test.js+++ b/server/services/authGate.test.js@@ -537,7 +537,7 @@ describe('authGate Express path matching', () => {expect(status.body).toEqual({ enabled: true });const login = await request(app).post('/API/Auth/LOGIN').send({ password: 'correct-horse' });expect(login.status).toBe(200);- expect(login.headers['set-cookie']).toMatch(/portos_auth=/);+ expect(login.headers['set-cookie']).toMatch(/portos_auth_\d+=/);const health = await request(app).get('/API/SYSTEM/HEALTH');expect(health.status).toBe(200);expect(health.body).toEqual({ status: 'ok' });diff --git a/server/services/socket.js b/server/services/socket.jsindex 0c7b86911b..c5b7b476e3 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -40,7 +40,7 @@ import { cleanupSocketStreams, registerLogHandlers } from '../sockets/logs.js';import { detachShellSocket, registerShellHandlers } from '../sockets/shell.js';import { detachItermSocket, registerItermHandlers } from '../sockets/iterm.js';import { getBuildId } from '../lib/buildId.js';-import { authEvents, extractToken, isAuthEnabled, verifySession } from './auth.js';+import { authEvents, isAuthEnabled, verifyRequestSession } from './auth.js';import { runEventLogEvents } from './agentRunEventLog.js';import { armSystemActivityWatchers, bindSystemActivityIo } from './systemActivityNotify.js';@@ -113,8 +113,7 @@ function registerAuthHandlers(socket, _io) {socket.use(async ([event, ..._args], next) => {try {if (!(await isAuthEnabled())) return next();- const token = extractToken({ headers: socket.handshake?.headers || {} });- if (await verifySession(token)) return next();+ if (await verifyRequestSession({ headers: socket.handshake?.headers || {} })) return next();const peerAuthMethod = socket.data?.portosAuthMethod;if ((peerAuthMethod === 'peer' || peerAuthMethod === 'basic') && PEER_RELAY_ALLOWED_EVENTS.has(event)) {return next();