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: confine paired-peer credentials to the federation API surface (#8387)
[._.]/ Adam Eivy7f876b326cf9
diff --git a/docs/PEER_PUSH_AUTH.md b/docs/PEER_PUSH_AUTH.mdindex 9283fcda57..747fe75552 100644--- a/docs/PEER_PUSH_AUTH.md+++ b/docs/PEER_PUSH_AUTH.md@@ -38,11 +38,49 @@ provider) authenticates with `X-PortOS-Peer-Auth`, an HMAC-SHA256 of the pairsecret bound to the sender's `X-PortOS-Instance-Id`. The secret itself is notsent, and each direction has a different token.-The receiver maps a verified token to `method: 'peer'`. It authenticates-`/api/*` and `/data/*` reads and pushes and the peer socket relay handshake. It-never passes `requireHostControl` (`/api/commands/*` returns-`HOST_CONTROL_FORBIDDEN`), cannot emit socket events, and cannot be exchanged-for a session, because it is not the password. A disabled peer's token is refused.+The receiver maps a verified token to `method: 'peer'`. It authenticates only+the federation surface listed below and the peer socket relay handshake. Every+other route returns `403 PEER_SCOPE_FORBIDDEN` (a plain `403` under `/data/`),+including `/api/commands/*`, even when the request also carries the password+as Basic. It cannot emit socket events and cannot be exchanged for a session,+because it is not the password. A disabled peer's token is refused.++### Peer API surface++`PEER_API_SURFACE` in `server/lib/apiAccessPolicy.js` is the contract; this+table mirrors it. `server/lib/apiAccessPolicy.test.js` scans every+`peerFetch` call site and fails when this version calls a peer path the list+does not admit.++| Methods | Path | Used by |+|---------|------|---------|+| GET | `/api/system/health/details`, `/api/apps`, `/api/instances/sync-status` | Peer probe |+| GET | `/api/apps/quality-federation` | App quality federation |+| GET | `/api/cos/agents` | Peer socket relay snapshot |+| POST | `/api/instances/peers/announce`, `/api/instances/peers/sync-categories` | Registration handshake |+| GET | `/api/brain/sync`, `/api/brain/reconcile/{checksum,snapshot,manifest}` | Brain sync and parity |+| GET | `/api/memory/sync`, `/api/catalog/sync`, `/api/sync/*` | Snapshot sync |+| GET | `/api/peer-sync/*` | Record, manifest, and archive pulls |+| POST | `/api/peer-sync/push` | Record push |+| any | `/api/federation/media/v1/*` | Federated media provider |+| GET | `/api/providers/fleet-host` | Fleet LLM host discovery |+| POST | `/api/providers/fleet-host/key` | Fleet LLM host key |+| any | `/api/eidoverse/travel/federation/*` | Eidoverse guest travel |+| GET | `/data/{images,image-refs,videos,music,audio,writers-room/works}/*` | Asset pulls |++GET includes HEAD. Paths with `.`/`..`/empty segments or encoded separators+are refused. The generic `GET /api/instances/peers/:id/query` proxy reaches only+these paths on a paired peer.++Removing an entry is a breaking change for older peers that still call it: they+receive `403 PEER_SCOPE_FORBIDDEN`, and the receiver logs one `⛔ Peer … refused+outside the federation surface` line per peer, method, and path. Adding a peer+call site means adding its entry in the same change.++Legacy HTTP Basic is the instance password itself, so it keeps operator reach+(`method: 'basic'`, still refused host control). Its holder can already sign in+at `/api/auth/login`, and the companion app uses it as a full session+(`docs/COMPANION_APP_API.md`). Pair each peer so it stops sending the password.Rollout without breaking older installs:diff --git a/server/lib/README.md b/server/lib/README.mdindex f9ed374949..91247a17d2 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -615,7 +615,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|-| `apiAccessPolicy.js` | Shared always-public path and gated non-`/api` prefix policy consumed by both `authGate` and API discovery. |+| `apiAccessPolicy.js` | Shared always-public path, gated non-`/api` prefix, and peer-credential federation surface (`PEER_API_SURFACE`, `isPeerApiRequestAllowed`) policy consumed by `authGate` and API discovery. || `apiCatalog.js` | Searchable projection of the Express route inventory (`getApiRouteCatalog()` from `apiRouteGraph.js`): domain, access, side-effect, contract coverage, summaries, and Express-to-OpenAPI path conversion. || `apiRouteGraph.js` | Static scan of the mounted HTTP route graph — `server/index.js` `app.use('/api/…', router)` mounts → route-module imports → `router.use(prefix, child)` → `router.<method>('<path>')`, including aliased mounts, local subrouters, factory returns and composed `toolkit.routes.<x>` routers. `buildApiRouteCatalog({ repoRoot? })` → `{ derivedFrom, mounts, routes: [{ method, path, mountPath, sources }], stats }`; `getApiRouteCatalog()` derives it on first use and caches it for the process (read by the API Explorer, the internal OpenAPI document and `apiRouteParity.test.js`); `scanRouteGraph()` adds `declarationKeys` / `duplicateDeclarationKeys` (`routeDeclarationKey`) for the coverage guard in `apiRouteGraph.test.js`. Never committed — see "Generated manifests" in `server/AGENTS.md`. || `socketEventCatalog.js` | Searchable projection of the cached Socket.IO inventory: direction, domain, and runtime-schema coverage. |diff --git a/server/lib/apiAccessPolicy.js b/server/lib/apiAccessPolicy.jsindex 64cd8e25b2..9e21715efa 100644--- a/server/lib/apiAccessPolicy.js+++ b/server/lib/apiAccessPolicy.js@@ -14,3 +14,63 @@ export const GATED_NON_API_PREFIXES = Object.freeze(['/sdapi/']);const alwaysPublicPathSet = new Set(ALWAYS_PUBLIC_API_PATHS);export const isAlwaysPublicApiPath = (path) => alwaysPublicPathSet.has(path);++// The federation surface a paired peer's scoped credential (`method: 'peer'`,+// #8356) may reach. Everything else — agent spawns, app lifecycle, git/file+// routes, settings writes — needs an operator session (#8387). Each entry+// matches one `path` exactly (a trailing `/` is ignored) or every path under+// `prefix`; `methods: null` admits any method. This list IS the peer contract+// across versions: dropping an entry makes an older peer that still calls it+// fail loudly with 403 PEER_SCOPE_FORBIDDEN, so keep docs/PEER_PUSH_AUTH.md in+// step with it.+const READ = Object.freeze(['GET', 'HEAD']);+const ANY_METHOD = null;++export const PEER_API_SURFACE = Object.freeze([+ // Probe (instances.probePeer) and the peer socket relay's agent snapshot.+ { path: '/api/system/health/details', methods: READ },+ { path: '/api/apps', methods: READ },+ { path: '/api/apps/quality-federation', methods: READ },+ { path: '/api/instances/sync-status', methods: READ },+ { path: '/api/cos/agents', methods: READ },+ // Registration handshake.+ { path: '/api/instances/peers/announce', methods: Object.freeze(['POST']) },+ { path: '/api/instances/peers/sync-categories', methods: Object.freeze(['POST']) },+ // Snapshot / log pulls (syncOrchestrator, brainParity).+ { path: '/api/brain/sync', methods: READ },+ { path: '/api/brain/reconcile/checksum', methods: READ },+ { path: '/api/brain/reconcile/snapshot', methods: READ },+ { path: '/api/brain/reconcile/manifest', methods: READ },+ { path: '/api/memory/sync', methods: READ },+ { path: '/api/catalog/sync', methods: READ },+ { prefix: '/api/sync/', methods: READ },+ // Record push/pull (sharing/*): reads, plus the one inbound push.+ { prefix: '/api/peer-sync/', methods: READ },+ { path: '/api/peer-sync/push', methods: Object.freeze(['POST']) },+ // Peer-facing provider APIs; each applies its own per-peer admission.+ { prefix: '/api/federation/media/v1/', methods: ANY_METHOD },+ { path: '/api/providers/fleet-host', methods: READ },+ { path: '/api/providers/fleet-host/key', methods: Object.freeze(['POST']) },+ { prefix: '/api/eidoverse/travel/federation/', methods: ANY_METHOD },+ // Static asset mounts the sync workers pull bytes from.+ { prefix: '/data/images/', methods: READ },+ { prefix: '/data/image-refs/', methods: READ },+ { prefix: '/data/videos/', methods: READ },+ { prefix: '/data/music/', methods: READ },+ { prefix: '/data/audio/', methods: READ },+ { prefix: '/data/writers-room/works/', methods: READ },+]);++// Dot segments and empty segments never appear in a URL a peer builds; refusing+// them keeps a prefix match from being argued past by a path that a later layer+// might normalize differently.+const hasAmbiguousSegment = (path) => /\/\/|\/\.\.?(?:\/|$)|%2e|%2f|%5c|\\/i.test(path);++/** Whether a peer credential may call `method path`. `path` must be lowercased. */+export const isPeerApiRequestAllowed = (method, path) => {+ if (typeof path !== 'string' || typeof method !== 'string' || hasAmbiguousSegment(path)) return false;+ const verb = method.toUpperCase();+ const exact = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;+ return PEER_API_SURFACE.some((rule) => (rule.methods === ANY_METHOD || rule.methods.includes(verb))+ && (rule.path ? rule.path === exact : path.startsWith(rule.prefix) && path.length > rule.prefix.length));+};diff --git a/server/lib/apiAccessPolicy.test.js b/server/lib/apiAccessPolicy.test.jsnew file mode 100644index 0000000000..1d8c2c4550--- /dev/null+++ b/server/lib/apiAccessPolicy.test.js@@ -0,0 +1,77 @@+import { describe, it, expect } from 'vitest';+import { readdirSync, readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { isAlwaysPublicApiPath, isPeerApiRequestAllowed } from './apiAccessPolicy.js';++const SERVER_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++const walk = (dir) => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) return entry.name === 'node_modules' ? [] : walk(path);+ return entry.name.endsWith('.js') && !entry.name.includes('.test.') ? [path] : [];+});++// Every `/api/…` or `/data/…` literal in a module that dials peers through+// peerFetch. An interpolation right after `/` is a path segment (`x`); any+// other interpolation (a query string or a caller-supplied sub-path) ends the+// literal, and the path is then checked both bare and with a sub-path.+const peerCallSitePaths = () => {+ const found = [];+ for (const file of [...walk(join(SERVER_ROOT, 'services')), ...walk(join(SERVER_ROOT, 'lib'))]) {+ const source = readFileSync(file, 'utf8');+ if (!/import[^;]*\bpeerFetch\b[^;]*from/.test(source)) continue;+ const code = source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1');+ for (const match of code.matchAll(/(?<=['`}])\/(?:api|data)\/[^'`\s?]*/g)) {+ const literal = match[0].replace(/\/\$\{[^}]*\}/g, '/x').split('${')[0];+ found.push({ file: file.slice(SERVER_ROOT.length + 1), path: literal.toLowerCase() });+ }+ }+ return found;+};++const reachable = (path) => ['GET', 'POST'].some((method) => isAlwaysPublicApiPath(path)+ || isPeerApiRequestAllowed(method, path)+ || isPeerApiRequestAllowed(method, `${path}${path.endsWith('/') ? '' : '/'}x`));++describe('peer API surface (#8387)', () => {+ it('admits every endpoint this version of PortOS calls on a peer', () => {+ const sites = peerCallSitePaths();+ // Guard against a scanner that silently stops finding call sites.+ expect(sites.length).toBeGreaterThan(30);+ expect(sites.map((s) => s.path)).toContain('/api/peer-sync/push');+ expect(sites.filter((site) => !reachable(site.path))).toEqual([]);+ });++ it('scopes methods, exact paths, and prefixes', () => {+ expect(isPeerApiRequestAllowed('POST', '/api/peer-sync/push')).toBe(true);+ expect(isPeerApiRequestAllowed('GET', '/api/peer-sync/manifest')).toBe(true);+ expect(isPeerApiRequestAllowed('HEAD', '/data/images/example.png')).toBe(true);+ expect(isPeerApiRequestAllowed('GET', '/api/apps/')).toBe(true);+ // Operator mutations beside allowed reads stay closed.+ expect(isPeerApiRequestAllowed('POST', '/api/peer-sync/sync-now')).toBe(false);+ expect(isPeerApiRequestAllowed('POST', '/api/sync/brain/apply')).toBe(false);+ expect(isPeerApiRequestAllowed('POST', '/api/apps/example-app/restart')).toBe(false);+ expect(isPeerApiRequestAllowed('GET', '/api/apps/example-app')).toBe(false);+ expect(isPeerApiRequestAllowed('POST', '/api/cos/tasks')).toBe(false);+ expect(isPeerApiRequestAllowed('PUT', '/api/settings')).toBe(false);+ expect(isPeerApiRequestAllowed('POST', '/api/providers/fleet-host/stop')).toBe(false);+ expect(isPeerApiRequestAllowed('GET', '/data/voice-profiles/example.wav')).toBe(false);+ // A prefix rule never matches the bare prefix or a lookalike sibling.+ expect(isPeerApiRequestAllowed('GET', '/api/peer-sync/')).toBe(false);+ expect(isPeerApiRequestAllowed('GET', '/data/images-private/example.png')).toBe(false);+ });++ it('refuses dot, empty, and encoded separator segments', () => {+ for (const path of [+ '/api/peer-sync/../commands/execute',+ '/api/peer-sync/./manifest',+ '/api/peer-sync//manifest',+ '/data/images/%2e%2e/secret.json',+ '/data/images/a%2fb.png',+ '/data/images/..',+ ]) {+ expect(isPeerApiRequestAllowed('GET', path)).toBe(false);+ }+ });+});diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex 75a24eb5df..34b33908a7 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -109,11 +109,10 @@ router.get('/processing', asyncHandler(async (req, res) => {* path — `probePeer` reads /health/details, /api/apps and /api/instances/* sync-status only — so the stamp never leaves the machine on its own.*- * That is the guarantee being made, and the limit of it: the generic- * `queryPeer` proxy (routes/instances.js, predates this) lets an authenticated- * peer deliberately GET any /api/* path, as it can for every other endpoint on- * this server. The point here is that the stamp is not PUSHED into a payload- * that federates unprompted.+ * That is the guarantee being made, and the limit of it: a peer holding the+ * legacy Basic password can still deliberately GET this path (a paired peer's+ * scoped token cannot — it is outside PEER_API_SURFACE, #8387). The point here+ * is that the stamp is not PUSHED into a payload that federates unprompted.* See the root AGENTS.md privacy rules and #4694 ("local-only diagnostic data* — must not join a sync payload"). `health.test.js` pins both halves.*/diff --git a/server/services/authGate.js b/server/services/authGate.jsindex a38948e2c5..1132a2ecc1 100644--- a/server/services/authGate.js+++ b/server/services/authGate.js@@ -6,7 +6,7 @@ import { extractToken, isAuthEnabled, verifyPassword, verifySession } from './auimport { DEV_PROXY_CLIENT_ADDRESS_HEADER, extractBasicPassword, isCrossOrigin } from '../../lib/portosAuthCore.js';import { getSettings, settingsEvents } from './settings.js';import { isRegistryPublic } from '../lib/apiRegistry.js';-import { GATED_NON_API_PREFIXES, isAlwaysPublicApiPath } from '../lib/apiAccessPolicy.js';+import { GATED_NON_API_PREFIXES, isAlwaysPublicApiPath, isPeerApiRequestAllowed } from '../lib/apiAccessPolicy.js';import { sendErrorResponse, ServerError } from '../lib/errorHandler.js';import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';import { loadData as loadInstances } from './instanceIdentity.js';@@ -74,6 +74,27 @@ const warnIfPairedPeerUsedBasic = async (headers) => {console.warn(`⚠️ Paired peer ${peer.name || peer.id} authenticated with the instance password instead of its pair credential — update it, re-pair with the same sync secret, then remove the stored password on that machine`);};+// Logged once per peer + method + path per process (bounded): an older or+// newer peer calling outside the contract should be diagnosable without+// flooding the log.+const warnedPeerScope = new Set();+const WARNED_PEER_SCOPE_MAX = 256;+const refusePeerScope = (req, res, path, peer) => {+ const key = `${peer.id} ${req.method} ${path}`;+ if (!warnedPeerScope.has(key)) {+ if (warnedPeerScope.size >= WARNED_PEER_SCOPE_MAX) warnedPeerScope.clear();+ warnedPeerScope.add(key);+ console.warn(`⛔ Peer ${peer.name || peer.id} refused outside the federation surface: ${req.method} ${path}`);+ }+ if (path.startsWith('/data/')) {+ res.status(403).type('text/plain').send('Forbidden');+ return;+ }+ sendErrorResponse(res, new ServerError('A peer credential only reaches the federation API.', {+ status: 403, code: 'PEER_SCOPE_FORBIDDEN',+ }));+};+export const __testing = { verifyBasicPassword };const isPublicPath = (path) => {@@ -140,8 +161,15 @@ export const authGate = async (req, res, next) => {}// A paired peer's scoped credential. Checked before Basic so a sender that// presents both during the upgrade handshake is identified as the peer.+ // Its authority ends at the federation surface (#8387): operator routes+ // refuse it outright rather than falling through to Basic, so a peer that+ // sends both never borrows the password's reach.const peer = await verifyPeerToken(req.headers);if (peer) {+ if (!isPeerApiRequestAllowed(req.method, path)) {+ refusePeerScope(req, res, path, peer);+ return;+ }req.portosAuthContext = { enabled: true, authenticated: true, method: 'peer', peerId: peer.id };return next();}diff --git a/server/services/authGate.test.js b/server/services/authGate.test.jsindex 546c538bf5..256a462214 100644--- a/server/services/authGate.test.js+++ b/server/services/authGate.test.js@@ -674,6 +674,10 @@ describe('paired peer credential (#8356)', () => {app.use(express.json());app.use('/api/auth', authRoutes);app.get('/api/example', (req, res) => res.json({ auth: req.portosAuthContext }));+ app.get('/api/peer-sync/manifest', (req, res) => res.json({ auth: req.portosAuthContext }));+ app.post('/api/cos/tasks', (req, res) => res.json({ auth: req.portosAuthContext }));+ app.post('/api/apps/:id/restart', (req, res) => res.json({ auth: req.portosAuthContext }));+ app.put('/api/settings', (req, res) => res.json({ auth: req.portosAuthContext }));app.post('/api/peer-sync/push', (req, res) => res.json({ auth: req.portosAuthContext }));app.post('/api/commands/execute', requireHostControl, (_req, res) => res.json({ ran: true }));return app;@@ -692,14 +696,15 @@ describe('paired peer credential (#8356)', () => {const app = await buildApp();const headers = await peerHeaders();- const read = await withHeaders(request(app).get('/api/example'), headers);+ const read = await withHeaders(request(app).get('/api/peer-sync/manifest'), headers);expect(read.status).toBe(200);expect(read.body.auth).toEqual({ enabled: true, authenticated: true, method: 'peer', peerId: 'peer-record' });expect((await withHeaders(request(app).post('/api/peer-sync/push').send({}), headers)).body.auth.method).toBe('peer');const exec = await withHeaders(request(app).post('/api/commands/execute').send({}), headers);expect(exec.status).toBe(403);- expect(exec.body.code).toBe('HOST_CONTROL_FORBIDDEN');+ // The gate's peer scope refuses it before requireHostControl is reached.+ expect(exec.body.code).toBe('PEER_SCOPE_FORBIDDEN');// The token is not the password, so it cannot be exchanged for a session.const login = await request(app).post('/api/auth/login').send({ password: headers['X-PortOS-Peer-Auth'] });@@ -713,6 +718,36 @@ describe('paired peer credential (#8356)', () => {expect((await withHeaders(request(app).post('/api/commands/execute').send({}), basic)).status).toBe(403);});+ it('confines the peer credential to the federation surface (#8387)', async () => {+ const auth = await import('./auth.js');+ const { token } = await auth.setPassword({ newPassword: 'example-password' });+ writePeers([pairedPeer()]);+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const app = await buildApp();+ const headers = await peerHeaders();+ const basic = { Authorization: basicHeader('example-password') };+ const operatorMutations = [+ () => request(app).post('/api/cos/tasks').send({}),+ () => request(app).post('/api/apps/example-app/restart').send({}),+ () => request(app).put('/api/settings').send({}),+ () => request(app).get('/api/example'),+ ];+ for (const send of operatorMutations) {+ const refused = await withHeaders(send(), headers);+ expect(refused.status).toBe(403);+ expect(refused.body.code).toBe('PEER_SCOPE_FORBIDDEN');+ // Presenting the password alongside the token does not widen the peer's reach.+ expect((await withHeaders(send(), { ...headers, ...basic })).status).toBe(403);+ expect((await send().set('Cookie', `portos_auth=${token}`)).body.auth.method).toBe('session');+ // Basic is the operator password (the companion-app contract), not a peer scope.+ expect((await withHeaders(send(), basic)).body.auth.method).toBe('basic');+ }+ const asset = await withHeaders(request(app).get('/data/voice-profiles/example.wav'), headers);+ expect(asset.status).toBe(403);+ expect(asset.text).toBe('Forbidden');+ expect(warn.mock.calls.some(([line]) => line.includes('POST /api/cos/tasks'))).toBe(true);+ });+it('rejects a token for another instance, a wrong secret, a disabled peer, or an unpaired peer', async () => {const auth = await import('./auth.js');await auth.setPassword({ newPassword: 'example-password' });