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

fix: keep peer relay sockets connected through cos:subscribe (#8386)

[._.]/ Adam Eivyc37b29a14607
diff --git a/server/services/authGate.js b/server/services/authGate.js
index bad921fb1e..a38948e2c5 100644
--- a/server/services/authGate.js
+++ b/server/services/authGate.js
@@ -204,6 +204,16 @@ export const requireHostControl = (req, res, next) => {
// API surface (apiRegistry) is HTTP-only — external callers hit REST endpoints,
// not the interactive socket. The socket carries the authenticated UI session
// (voice streaming, live updates) and must stay fully gated when auth is on.
+// Records which credential passed the handshake so the per-event re-check in
+// socket.js (registerAuthHandlers) can tell a real operator session from a
+// peer relay connection. `socket.data` always exists on a real Socket.IO
+// socket; guarded here only so the plain `{ handshake }` fixtures this
+// module's own tests pass in don't throw.
+const markAuthMethod = (socket, method) => {
+ if (!socket.data) socket.data = {};
+ socket.data.portosAuthMethod = method;
+};
+
export const socketAuthGate = async (socket, next) => {
const enabled = await isAuthEnabled();
if (!enabled) return next();
@@ -214,12 +224,23 @@ export const socketAuthGate = async (socket, next) => {
return next(err);
}
const token = extractToken(fakeReq);
- if (await verifySession(token)) return next();
+ if (await verifySession(token)) {
+ markAuthMethod(socket, 'session');
+ return next();
+ }
// Peer relay connections: the paired peer token, else legacy Basic. Neither
- // can emit events — socket.js re-checks for a real session on every event.
- if (await verifyPeerToken(fakeReq.headers)) return next();
+ // grants operator authority — socket.js re-checks every inbound event and
+ // allows a peer-authenticated socket only the minimal read-only
+ // subscription events it needs (PEER_RELAY_ALLOWED_EVENTS).
+ if (await verifyPeerToken(fakeReq.headers)) {
+ markAuthMethod(socket, 'peer');
+ return next();
+ }
const basicPassword = extractBasicPassword(fakeReq);
- if (basicPassword && await verifyBasicPassword(basicPassword)) return next();
+ if (basicPassword && await verifyBasicPassword(basicPassword)) {
+ markAuthMethod(socket, 'basic');
+ return next();
+ }
const err = new Error('Authentication required');
err.data = { code: 'AUTH_REQUIRED' };
next(err);
diff --git a/server/services/peerSocketRelayAuth.test.js b/server/services/peerSocketRelayAuth.test.js
new file mode 100644
index 0000000000..7d518d5ae3
--- /dev/null
+++ b/server/services/peerSocketRelayAuth.test.js
@@ -0,0 +1,167 @@
+/**
+ * Integration test for #8386: a peer relay socket (server/services/
+ * peerSocketRelay.js) authenticates the handshake with the paired peer
+ * token or the legacy Basic password, never a session. Before this fix,
+ * `registerAuthHandlers`'s per-event re-check in socket.js disconnected it
+ * the moment it emitted `cos:subscribe`, because that check only recognizes
+ * a real operator session.
+ *
+ * Drives a REAL Socket.IO server (socketAuthGate + registerAuthHandlers, the
+ * two files this fix touches) and a REAL socket.io-client over a loopback
+ * HTTP server, so the handshake and per-event middleware run unmocked.
+ */
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createServer } from 'http';
+import { Server } from 'socket.io';
+import { io as ioClient } from 'socket.io-client';
+import { writeFileSync } from 'fs';
+import { join } from 'path';
+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
+import { bindSettingsFile } from '../lib/settingsTestUtil.js';
+
+const { tempRoot, makeProxy, cleanup: cleanupDataRoot } = mockPathsDataRoot({ prefix: 'portos-peer-relay-auth-' });
+
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return makeProxy(actual);
+});
+
+// Cheap scrypt params so setPassword()/verifyPassword() don't burn the test
+// budget — same override authGate.test.js uses.
+vi.mock('../../lib/portosAuthCore.js', async () => {
+ const actual = await vi.importActual('../../lib/portosAuthCore.js');
+ const testParams = { N: 1024, r: 8, p: 1, maxmem: 8 * 1024 * 1024 };
+ const hashPassword = (password, salt) =>
+ actual.__hashPasswordWithParamsForTests(password, salt, testParams);
+ return {
+ ...actual,
+ hashPassword,
+ verifyPasswordAgainst: async (auth, password) => {
+ if (!auth?.enabled || !auth.passwordHash || !auth.salt || typeof password !== 'string' || password.length === 0) return false;
+ return actual.constantEqual(await hashPassword(password, auth.salt), auth.passwordHash);
+ },
+ };
+});
+
+const PEER_ID = 'peer-example-instance';
+const PAIR_SECRET = 'p'.repeat(40);
+const instanceRegistry = vi.hoisted(() => ({ data: { self: null, peers: [] } }));
+vi.mock('./instanceIdentity.js', async () => ({
+ ...(await vi.importActual('./instanceIdentity.js')),
+ loadData: async () => instanceRegistry.data,
+}));
+
+const resetSettings = () => {
+ writeFileSync(join(tempRoot, 'settings.json'), '{}\n');
+ writeFileSync(join(tempRoot, 'auth-sessions.json'), '{"tokens":[]}\n');
+};
+
+let httpServer;
+let ioServer;
+let port;
+let clients = [];
+
+const startServer = async () => {
+ const { socketAuthGate } = await import('./authGate.js');
+ const { __testing } = await import('./socket.js');
+ httpServer = createServer();
+ ioServer = new Server(httpServer);
+ ioServer.use(socketAuthGate);
+ ioServer.on('connection', (socket) => {
+ __testing.registerAuthHandlers(socket, ioServer);
+ __testing.registerSubscriptionHandlers(socket, ioServer);
+ // Stand-in for a host-control-shaped event (server/sockets/shell.js);
+ // never actually reached by a peer-authenticated socket once the auth
+ // middleware above disconnects it first.
+ socket.on('shell:list', () => socket.emit('shell:sessions', { sessions: [] }));
+ });
+ await new Promise((resolve) => httpServer.listen(0, resolve));
+ port = httpServer.address().port;
+};
+
+const stopServer = async () => {
+ for (const client of clients) client.close();
+ clients = [];
+ await new Promise((resolve) => ioServer.close(resolve));
+ await new Promise((resolve) => httpServer.close(resolve));
+};
+
+const connectClient = (extraHeaders) => {
+ const client = ioClient(`http://127.0.0.1:${port}`, {
+ reconnection: false,
+ timeout: 2000,
+ transports: ['websocket'],
+ extraHeaders,
+ });
+ clients.push(client);
+ return client;
+};
+
+const waitFor = (emitter, event) => new Promise((resolve) => emitter.once(event, resolve));
+
+describe('peer socket relay stays connected through cos:subscribe on a password-gated peer (#8386)', () => {
+ beforeEach(async () => {
+ vi.resetModules();
+ resetSettings();
+ instanceRegistry.data = { self: null, peers: [] };
+ });
+
+ afterEach(async () => {
+ await stopServer();
+ });
+
+ afterAll(() => {
+ cleanupDataRoot();
+ });
+
+ it('a peer-token-authenticated socket survives cos:subscribe but is disconnected by a shell:* event', async () => {
+ const auth = await import('./auth.js');
+ await auth.setPassword({ newPassword: 'instance-secret' });
+ instanceRegistry.data.peers = [{ id: 'peer-record', name: 'Example Peer', instanceId: PEER_ID, enabled: true, syncSecret: PAIR_SECRET }];
+ const { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } = await import('../lib/peerHttpClient.js');
+
+ await startServer();
+ const client = connectClient({
+ [PEER_INSTANCE_HEADER]: PEER_ID,
+ [PEER_AUTH_HEADER]: derivePeerAuthToken(PAIR_SECRET, PEER_ID),
+ });
+
+ await waitFor(client, 'connect');
+ client.emit('cos:subscribe');
+ await waitFor(client, 'cos:subscribed');
+ expect(client.connected).toBe(true);
+
+ client.emit('shell:list');
+ await waitFor(client, 'disconnect');
+ expect(client.connected).toBe(false);
+ });
+
+ it('a Basic-authenticated socket also survives cos:subscribe but is disconnected by a shell:* event', async () => {
+ const auth = await import('./auth.js');
+ await auth.setPassword({ newPassword: 'instance-secret' });
+
+ await startServer();
+ const client = connectClient({
+ Authorization: `Basic ${Buffer.from(':instance-secret').toString('base64')}`,
+ });
+
+ await waitFor(client, 'connect');
+ client.emit('cos:subscribe');
+ await waitFor(client, 'cos:subscribed');
+ expect(client.connected).toBe(true);
+
+ client.emit('shell:list');
+ await waitFor(client, 'disconnect');
+ expect(client.connected).toBe(false);
+ });
+
+ it('an unauthenticated socket is rejected at the handshake', async () => {
+ const auth = await import('./auth.js');
+ await auth.setPassword({ newPassword: 'instance-secret' });
+
+ await startServer();
+ const client = connectClient({});
+ const err = await waitFor(client, 'connect_error');
+ expect(err.data?.code).toBe('AUTH_REQUIRED');
+ });
+});
diff --git a/server/services/socket.js b/server/services/socket.js
index f416c4c83e..0c7b86911b 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -95,15 +95,30 @@ function registerSubscriber(socket, namespace, set) {
});
}
+// A peer relay (server/services/peerSocketRelay.js) authenticates the socket
+// handshake with the paired peer token or the legacy Basic password (#8386) —
+// never a session — so it can never satisfy the per-event re-check below on
+// its own. This is the ONLY carve-out: a minimal, read-only allowlist of the
+// subscribe/unsubscribe events the relay needs to receive `cos:agent:*`
+// broadcasts. Every other event, including any `shell:*`/host-control event,
+// still requires a real operator session and disconnects a peer-authenticated
+// socket exactly as it did before. Keep this list minimal — do not add a
+// mutating or host-affecting event here.
+const PEER_RELAY_ALLOWED_EVENTS = new Set(['cos:subscribe', 'cos:unsubscribe']);
+
function registerAuthHandlers(socket, _io) {
// Per-event auth re-check: the handshake gate only runs once at connection
// time, so every inbound event re-verifies an enabled session.
if (typeof socket.use === 'function') {
- socket.use(async ([_event, ..._args], next) => {
+ 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();
+ const peerAuthMethod = socket.data?.portosAuthMethod;
+ if ((peerAuthMethod === 'peer' || peerAuthMethod === 'basic') && PEER_RELAY_ALLOWED_EVENTS.has(event)) {
+ return next();
+ }
socket.disconnect(true);
} catch (err) {
console.error(`❌ Socket auth middleware error: ${err?.message ?? err}`);
@@ -339,6 +354,11 @@ export function broadcast(io, event, data) {
io.emit(event, data);
}
+// Test-only seam (mirrors the `__testing` convention in authGate.js): lets an
+// integration test wire the real per-event auth re-check onto a live
+// Socket.IO server without pulling in every other registrar's dependencies.
+export const __testing = { registerAuthHandlers, PEER_RELAY_ALLOWED_EVENTS, registerSubscriptionHandlers };
+
// Broadcast to CoS subscribers only
function broadcastToCos(event, data) {
if (!['cos:tasks:user:changed', 'cos:tasks:cos:changed', 'cos:tasks:changed'].includes(event)) {