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: let paired peers reciprocate sync and admit local password-free peer CRUD (#13092)
Adam Eivy9bfcdc536478
diff --git a/docs/COMPANION_APP_API.md b/docs/COMPANION_APP_API.mdindex 5fa9fa8e17..8b4f5a9ea9 100644--- a/docs/COMPANION_APP_API.md+++ b/docs/COMPANION_APP_API.md@@ -101,9 +101,11 @@ not satisfy it, no matter how correct the password is:- **Peer management** (`POST/PUT/DELETE /api/instances/peers/*`, except`POST /peers/announce` and the one-time `POST /peers/pair-secret` Basic- bootstrap — see [§3](#3-instance-management)) requires an operator session.- A Basic-only request gets `403 PEER_SETTINGS_OPERATOR_REQUIRED`, whether or- not a password is set.+ bootstrap — see [§3](#3-instance-management)) requires an operator session,+ or a local connection on a password-free install. A Basic-only request gets+ `403 PEER_SETTINGS_OPERATOR_REQUIRED`, as does a remote caller on a+ password-free install. `POST /peers/sync-categories` additionally accepts a+ paired peer's scoped credential acting for its own instance id.- **Host control** (`/api/commands/*` and the routes audited in`server/lib/hostControlRoutes.js` — app lifecycle, CoS agent queueing, git,scaffold, provider/runtime installs, autopilot start, and the matchingdiff --git a/server/routes/instances.js b/server/routes/instances.jsindex bb25a4c853..102451e920 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -21,22 +21,29 @@ import { getTailscaleStatus } from '../lib/tailscale.js';import { federatedMediaPeerSettingsSchema, optionalBooleanMap, validateRequest } from '../lib/validation.js';import { PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';import { isPeerBasicBootstrapRequest } from '../lib/apiAccessPolicy.js';+import { requestHasHostControl } from '../services/authGate.js';const router = Router();-// Peer admission is local authority even when the instance password is off.-// Announcements remain discoverable. Reciprocal category changes also require-// local authority: an anonymous callback cannot admit a discovery-only peer.+// Peer admission is local authority: an operator session, or a local connection+// on a password-free install (requestHasHostControl, the policy every other+// operator route uses). Announcements remain discoverable. The reciprocal+// category callback additionally accepts a paired peer's scoped credential+// (PEER_API_SURFACE), bound to its own instance id in the route; anonymous and+// Basic callers cannot admit a discovery-only peer.router.use(asyncHandler(async (req, _res, next) => {if (!req.path.toLowerCase().startsWith('/peers') || ['GET', 'HEAD', 'OPTIONS'].includes(req.method)|| req.path.toLowerCase().replace(/\/$/, '') === '/peers/announce') return 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 verifyRequestSession(req)) {+ if (!isCrossOrigin(req) && (await verifyRequestSession(req)+ || (req.portosAuthContext?.method !== 'peer' && requestHasHostControl(req)))) {req.peerSettingsOperator = true;return next();}+ if (req.method === 'POST' && req.path.toLowerCase().replace(/\/$/, '') === '/peers/sync-categories'+ && req.portosAuthContext?.authenticated === true && req.portosAuthContext.method === 'peer') return next();// The pairing callback is the only peer-settings mutation accepted with// Basic auth. It is bound to the caller's existing peer identity below and// installs only a peer-scoped secret; peer tokens still cannot reach it.@@ -394,6 +401,13 @@ router.post('/peers/:id/connect', asyncHandler(async (req, res) => {// instanceId in the body (we may not know its local-peer-id mapping).router.post('/peers/sync-categories', asyncHandler(async (req, res) => {const data = validateRequest(reciprocalSyncSchema, req.body);+ // authGate verified the credential against the instance id in this header;+ // a peer may only reciprocate for itself, never for another registered peer.+ if (req.peerSettingsOperator !== true && req.get(PEER_INSTANCE_HEADER) !== data.instanceId) {+ throw new ServerError('A peer may only change its own reciprocal sync settings', {+ status: 403, code: 'PEER_SETTINGS_OPERATOR_REQUIRED',+ });+ }const { changed } = await instances.applyReciprocalSync(data.instanceId, data.syncCategories, { fullSync: data.fullSync });// 200 even when the peer is unknown to us / nothing changed — this is a// best-effort convergence signal, not a command that must succeed. We returndiff --git a/server/routes/instances.test.js b/server/routes/instances.test.jsindex a6dec94727..77600b112d 100644--- a/server/routes/instances.test.js+++ b/server/routes/instances.test.js@@ -511,12 +511,73 @@ describe('local peer admission configuration', () => {expect(res.status).toBe(403);expect(instances.updatePeer).not.toHaveBeenCalled();});- it('rejects apparent loopback access without an operator session', async () => {+ it('rejects a request the auth gate never classified, even over loopback', async () => {const res = await request(buildApp()).put('/api/instances/peers/peer-a').send({ syncSecret: 'synthetic-pair-secret-32-characters-long' });expect(res.status).toBe(403);expect(instances.updatePeer).not.toHaveBeenCalled();});++ const buildAppWithAuth = (auth) => {+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => { req.portosAuthContext = auth; next(); });+ app.use('/api/instances', instancesRoutes);+ app.use(errorMiddleware);+ return app;+ };+ const passwordFree = { enabled: false, authenticated: false, method: null };++ it('admits a local caller on a password-free install to peer CRUD', async () => {+ instances.updatePeer.mockResolvedValue({ id: 'peer-a' });+ const res = await request(buildAppWithAuth(passwordFree)).put('/api/instances/peers/peer-a')+ .send({ name: 'Peer A' });+ expect(res.status).toBe(200);+ expect(instances.updatePeer).toHaveBeenCalledWith('peer-a', { name: 'Peer A' });+ });++ it('still refuses a remote password-free caller and a peer credential on peer CRUD', async () => {+ const remote = await request(remoteRequestHandler(buildAppWithAuth(passwordFree))).put('/api/instances/peers/peer-a')+ .send({ name: 'Peer A' });+ expect(remote.status).toBe(403);+ const peer = await request(buildAppWithAuth({ enabled: false, authenticated: true, method: 'peer', peerId: 'peer-a' }))+ .put('/api/instances/peers/peer-a').send({ name: 'Peer A' });+ expect(peer.status).toBe(403);+ expect(instances.updatePeer).not.toHaveBeenCalled();+ });++ describe('reciprocal sync callback', () => {+ const instanceId = '191aaece-a492-41ee-a66d-d4661eadc132';+ const body = { instanceId, syncCategories: { universe: true } };+ const peerAuth = (enabled) => ({ enabled, authenticated: true, method: 'peer', peerId: 'peer-a' });++ it('accepts a paired peer credential acting for its own instance id', async () => {+ instances.applyReciprocalSync.mockResolvedValue({ changed: true });+ for (const enabled of [true, false]) {+ const res = await request(remoteRequestHandler(buildAppWithAuth(peerAuth(enabled))))+ .post('/api/instances/peers/sync-categories').set('X-PortOS-Instance-Id', instanceId).send(body);+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ applied: true });+ }+ });++ it('refuses a peer credential reciprocating for a different instance id', async () => {+ const res = await request(remoteRequestHandler(buildAppWithAuth(peerAuth(true))))+ .post('/api/instances/peers/sync-categories')+ .set('X-PortOS-Instance-Id', '291aaece-a492-41ee-a66d-d4661eadc132').send(body);+ expect(res.status).toBe(403);+ expect(instances.applyReciprocalSync).not.toHaveBeenCalled();+ });++ it('refuses Basic and anonymous remote callers', async () => {+ for (const auth of [{ enabled: true, authenticated: true, method: 'basic' }, passwordFree]) {+ const res = await request(remoteRequestHandler(buildAppWithAuth(auth)))+ .post('/api/instances/peers/sync-categories').set('X-PortOS-Instance-Id', instanceId).send(body);+ expect(res.status).toBe(403);+ }+ expect(instances.applyReciprocalSync).not.toHaveBeenCalled();+ });+ });it('refuses anonymous reciprocal admission of discovery peers', async () => {const res = await request(remoteRequestHandler(buildApp())).post('/api/instances/peers/sync-categories').send({ instanceId: '191aaece-a492-41ee-a66d-d4661eadc132', syncCategories: { universe: true }, fullSync: true });