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: limit the peer query proxy to the federation surface (#10099)
Adam Eivy5a807a31a628
diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 6f3151a973..bb25a4c853 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -489,7 +489,7 @@ router.get('/peers/:id/full-sync-coverage', asyncHandler(async (req, res) => {router.get('/peers/:id/query', asyncHandler(async (req, res) => {const { path } = validateRequest(querySchema, req.query);const result = await instances.queryPeer(req.params.id, path);- if (result.error) throw new ServerError(result.error, { status: 502 });+ if (result.error) throw new ServerError(result.error, { status: result.status ?? 502 });res.json(result.data);}));diff --git a/server/services/instances.js b/server/services/instances.jsindex dc2a5d45f1..01e940d974 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -17,6 +17,7 @@ import { instanceEvents } from './instanceEvents.js';import { connectToPeer, disconnectFromPeer } from './peerSocketRelay.js';import { DEFAULT_PEER_PORT } from '../lib/ports.js';import { peerBaseUrl } from '../lib/peerUrl.js';+import { isPeerApiRequestAllowed } from '../lib/apiAccessPolicy.js';import { peerFetch, peerAuthHeaders, PEER_AUTH_HEADER } from '../lib/peerHttpClient.js';import { withAbortTimeout } from '../lib/abortTimeout.js';import { ServerError } from '../lib/errorHandler.js';@@ -1038,12 +1039,43 @@ export async function probeAllPeers() {// --- Query Proxy ---+const PEER_PLACEHOLDER_ORIGIN = 'http://peer.invalid';++// Resolve a caller-supplied proxy path to "pathname + query" that is guaranteed+// to stay on the peer origin and on the documented federation surface+// (PEER_API_SURFACE), or null. The allowlist runs on the path exactly as it will+// be sent, so a segment a URL parser would normalize away (`..`, tabs, `\`) is+// refused rather than argued past.+function resolvePeerQueryTarget(apiPath) {+ if (typeof apiPath !== 'string' || !apiPath.startsWith('/') || /[\s\\#]/.test(apiPath)) return null;+ const queryAt = apiPath.indexOf('?');+ const rawPath = queryAt === -1 ? apiPath : apiPath.slice(0, queryAt);+ const search = queryAt === -1 ? '' : apiPath.slice(queryAt);+ let parsed;+ try {+ parsed = new URL(rawPath, PEER_PLACEHOLDER_ORIGIN);+ } catch {+ return null;+ }+ if (parsed.origin !== PEER_PLACEHOLDER_ORIGIN || parsed.username || parsed.password) return null;+ if (parsed.pathname !== rawPath) return null;+ const lower = rawPath.toLowerCase();+ // The `/api/peer-sync/` read prefix also spans the POST-only push endpoint,+ // which carries the sync secret; a GET proxy never has a reason to name it.+ if (lower.replace(/\/$/, '') === '/api/peer-sync/push') return null;+ if (!isPeerApiRequestAllowed('GET', lower)) return null;+ return `${rawPath}${search}`;+}+export async function queryPeer(id, apiPath) {const data = await loadData();const peer = data.peers.find(p => p.id === id);if (!peer) return { error: 'Peer not found' };- const url = `${peerBaseUrl(peer)}${apiPath}`;+ const target = resolvePeerQueryTarget(apiPath);+ if (!target) return { error: 'Path is not on the peer federation surface', status: 400 };++ const url = `${peerBaseUrl(peer)}${target}`;return withAbortTimeout(PROBE_TIMEOUT_MS, async (signal) => {const res = await peerFetch(url, { signal }, peer);return { success: true, data: await res.json() };diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex b7bb87d531..2ae4b872d7 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -1513,12 +1513,39 @@ describe('instances.js', () => {fetch.mockRejectedValue(new Error('Connection refused'));- const result = await queryPeer('peer-1', '/api/health');+ const result = await queryPeer('peer-1', '/api/apps');expect(result).toEqual({ error: 'Failed to query peer: Connection refused' });});});+ describe('queryPeer federation-surface allowlist', () => {+ beforeEach(() => {+ readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'peer-1', address: '10.0.0.1', port: 5555 }] });+ fetch.mockResolvedValue({ json: () => Promise.resolve({}) });+ });++ it.each([+ '/api/settings', '/api/commands/execute', '/api/peer-sync/push', '/api/apps/../settings',+ 'https://example.test/api/apps', '//example.test/api/apps', '/api/apps/%2e%2e/settings',+ '/api/apps%2fx', 'api/apps', '/api/apps\\..\\settings', '/api/apps#x', '/api/apps\t/x',+ 'http://user:[email protected]/api/apps', '/api/settings?next=/api/apps', '/api/brain/sync/../../settings',+ ])('refuses %j before any network call', async (p) => {+ const result = await queryPeer('peer-1', p);+ expect(result).toMatchObject({ status: 400 });+ expect(fetch).not.toHaveBeenCalled();+ });++ it('proxies allowlisted paths and forwards the query on the peer origin', async () => {+ await queryPeer('peer-1', '/api/brain/reconcile/snapshot');+ await queryPeer('peer-1', '/api/apps?x=1&y=/../z');+ expect(fetch.mock.calls.map(c => c[0])).toEqual([+ 'http://10.0.0.1:5555/api/brain/reconcile/snapshot',+ 'http://10.0.0.1:5555/api/apps?x=1&y=/../z',+ ]);+ });+ });+// --- Announce (Bidirectional Registration) ---it('keeps tailcat routing managed while applying ordinary peer settings', async () => {