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 (claude): fail-closed socket auth + cache + emit on logout

Adam Eivyf1bbec48c27e
diff --git a/server/routes/auth.js b/server/routes/auth.js
index c3d3d9c45c..822b1a4494 100644
--- a/server/routes/auth.js
+++ b/server/routes/auth.js
@@ -71,7 +71,7 @@ router.post('/login', asyncHandler(async (req, res) => {
router.post('/logout', asyncHandler(async (req, res) => {
const token = extractToken(req);
if (token) await revokeSession(token);
- res.setHeader('Set-Cookie', buildClearCookie());
+ res.setHeader('Set-Cookie', buildClearCookie({ secure: isSecure(req) }));
res.json({ ok: true });
}));
@@ -99,7 +99,7 @@ router.post('/password', asyncHandler(async (req, res) => {
router.delete('/password', asyncHandler(async (req, res) => {
const { currentPassword } = validateRequest(clearPasswordSchema, req.body || {});
await clearPassword({ currentPassword });
- res.setHeader('Set-Cookie', buildClearCookie());
+ res.setHeader('Set-Cookie', buildClearCookie({ secure: isSecure(req) }));
res.json({ enabled: false });
}));
diff --git a/server/services/auth.js b/server/services/auth.js
index 381d0c329f..f98aac4e3a 100644
--- a/server/services/auth.js
+++ b/server/services/auth.js
@@ -3,7 +3,7 @@ import { EventEmitter } from 'events';
import { createHash, randomBytes, scrypt, timingSafeEqual } from 'crypto';
import { promisify } from 'util';
import { atomicWrite, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
-import { getSettings, updateSettings } from './settings.js';
+import { getSettings, settingsEvents, updateSettings } from './settings.js';
import { ServerError } from '../lib/errorHandler.js';
// Auth gates the PortOS UI + API behind a single user-set password. PortOS is
@@ -59,14 +59,12 @@ const readSessions = async () => {
if (!Array.isArray(parsed.tokens)) return;
const cutoff = now();
for (const entry of parsed.tokens) {
- // Records carry `tokenHash` (sha256 hex) — accept the legacy `token` key
- // too so a pre-hash install upgrading on the spot doesn't sign every
- // session out at boot (the in-memory + at-rest representation rewrites
- // on the next mutation).
- const stored = entry?.tokenHash ?? entry?.token;
- if (typeof stored !== 'string' || typeof entry.expiresAt !== 'number') continue;
+ // Records carry `tokenHash` (sha256 hex). Records without it are
+ // skipped — the feature ships with hashed storage from day one, so
+ // a record missing `tokenHash` is corrupted, not legacy.
+ if (typeof entry?.tokenHash !== 'string' || typeof entry.expiresAt !== 'number') continue;
if (entry.expiresAt <= cutoff) continue;
- sessions.set(stored, { expiresAt: entry.expiresAt });
+ sessions.set(entry.tokenHash, { expiresAt: entry.expiresAt });
}
};
@@ -103,9 +101,22 @@ const readAuthConfig = async () => {
return settings?.secrets?.auth ?? null;
};
+// isAuthEnabled is called on EVERY gated request and every socket event.
+// Re-reading + parsing + stripping settings.json each time is a measurable
+// I/O multiplier on active pages and high-frequency socket streams (shell
+// input, voice frames). Cache the boolean and refresh it via the
+// settings:updated event the settings service already emits on every
+// updateSettings write.
+let enabledCache = null;
+const recomputeEnabledCache = (settings) => {
+ const a = settings?.secrets?.auth;
+ enabledCache = !!(a?.enabled && a?.passwordHash && a?.salt);
+};
+settingsEvents.on('settings:updated', recomputeEnabledCache);
+
export const isAuthEnabled = async () => {
- const auth = await readAuthConfig();
- return !!(auth?.enabled && auth?.passwordHash && auth?.salt);
+ if (enabledCache === null) recomputeEnabledCache(await getSettings());
+ return enabledCache;
};
export const getAuthStatus = async () => {
@@ -206,6 +217,10 @@ export const revokeSession = async (token) => {
await ensureLoaded();
if (sessions.delete(hashToken(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');
}
};
@@ -274,5 +289,19 @@ export const buildSessionCookie = (token, { secure = false } = {}) => {
return parts.join('; ');
};
-export const buildClearCookie = () =>
- `${COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;
+export const buildClearCookie = ({ secure = false } = {}) => {
+ // 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}=`,
+ 'Path=/',
+ 'HttpOnly',
+ 'SameSite=Lax',
+ 'Max-Age=0',
+ ];
+ if (secure) parts.push('Secure');
+ return parts.join('; ');
+};
diff --git a/server/services/auth.test.js b/server/services/auth.test.js
index 13d8c4c0b2..cb0eeacd2e 100644
--- a/server/services/auth.test.js
+++ b/server/services/auth.test.js
@@ -132,6 +132,11 @@ describe('auth service', () => {
expect(insecure).not.toContain('Secure');
const clear = auth.buildClearCookie();
expect(clear).toContain('Max-Age=0');
+ expect(clear).not.toContain('Secure');
+ // Mirrors the live cookie's Secure flag so HTTPS deletion conforms
+ // to RFC 6265bis attribute matching.
+ const secureClear = auth.buildClearCookie({ secure: true });
+ expect(secureClear).toContain('Secure');
});
it('persists sessions across reloads of the module', async () => {
@@ -166,4 +171,17 @@ describe('auth service', () => {
// setPassword/clearPassword both call revokeAllSessions internally.
expect(events.length).toBe(3);
});
+
+ 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' });
+ const { token } = await auth.createSession();
+ const events = [];
+ auth.authEvents.on('sessions:revoked-all', () => events.push('event'));
+ await auth.revokeSession(token);
+ expect(events.length).toBe(1);
+ // Revoking an unknown token must NOT fire — no state changed.
+ await auth.revokeSession('not-a-real-token');
+ expect(events.length).toBe(1);
+ });
});
diff --git a/server/services/socket.js b/server/services/socket.js
index 972d207a86..aaaa1d75bb 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -105,11 +105,20 @@ export function initSocket(io) {
// 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.
+ // Fail closed: if isAuthEnabled / verifySession throw (e.g. a
+ // transient settings.json read error) we MUST disconnect rather
+ // than skip the check by neither calling next nor disconnecting,
+ // which would silently stall the event and leave the socket
+ // attached on stale credentials.
+ try {
+ if (!(await isAuthEnabled())) return next();
+ const token = extractToken({ headers: socket.handshake?.headers || {} });
+ if (await verifySession(token)) return next();
+ socket.disconnect(true);
+ } catch (err) {
+ console.error(`❌ Socket auth middleware error: ${err?.message ?? err}`);
+ socket.disconnect(true);
+ }
});
}
registerVoiceHandlers(socket);