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: authorize peer pulls on the /api/sync snapshot transport (#5663)
Adam Eivy8aa829b1135c
diff --git a/server/routes/dataSync.js b/server/routes/dataSync.jsindex dfdc3f4458..fd4fe19c06 100644--- a/server/routes/dataSync.js+++ b/server/routes/dataSync.js@@ -3,12 +3,35 @@** Endpoints for snapshot-based data sync between PortOS peer instances.* Each category returns its full data + checksum for merge-based sync.+ *+ * Authorization (#5663). This is the OLDER of the two pull transports; the+ * per-record `/api/peer-sync/*` routes got receiver-side peer-pull+ * authorization in #3659 and these did not, so the whole of every category —+ * including the user's identity record — was served to anything that could+ * reach the port. Both reads now run the SAME `authorizePeerPull` gate, keyed+ * on the caller's `X-PortOS-Instance-Id` (which `syncOrchestrator.fetchPeer`+ * sends via `peerFetch`).+ *+ * Two tiers, deliberately:+ * - Ordinary categories keep #3659's warn-first ramp — an un-upgraded peer is+ * still served and logs one `⚠️`, because the distribution model requires+ * peers that upgrade on their own schedule to keep syncing.+ * - `PII_CATEGORIES` are refused outright (`alwaysEnforce`) whatever+ * `federation.strictPullAuthorization` says. Root `AGENTS.md` forbids PII on+ * the federation layer at all, and the privacy ADR's stated reason for+ * refusing to federate these records was precisely that "the pull path+ * carries no peer identity": docs/decisions/2026-08-08-privacy-records-machine-local.md.+ *+ * Scope: what a category CONTAINS, and whether a configured, identified peer+ * may sync it, are unchanged — a user federating their own two machines keeps+ * working. Only an unidentified/unknown/outbound-disallowed caller is refused.*/import { Router } from 'express';import { z } from 'zod';import * as dataSync from '../services/dataSync.js';import { sweepTombstones, getSweepStatus, TOMBSTONE_GRACE_MS } from '../services/sharing/tombstoneGc.js';+import { authorizePeerPull } from '../services/sharing/peerPullAuthorization.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();@@ -18,6 +41,19 @@ const router = Router();// handler can run (the latent bug #730 hit for `storyBuilder`).const categoryParam = z.enum(['goals', 'character', 'digitalTwin', 'meatspace', 'universe', 'pipeline', 'mediaCollections', 'videoHistory', 'storyBuilder', 'usage']);+// Categories whose payload is the user's own person rather than their creative+// work — `digitalTwin` alone carries identity, chronotype, longevity markers,+// taste profile, autobiography stories and social accounts. These skip the+// warn-first ramp entirely (see the header note).+const PII_CATEGORIES = new Set(['digitalTwin', 'meatspace', 'character']);++// The one gate both reads share, so the checksum can never become the weaker+// door: a checksum is a fingerprint of the same payload.+const authorizeSyncPull = (req, category) => authorizePeerPull(req, {+ route: `sync ${category}`,+ alwaysEnforce: PII_CATEGORIES.has(category),+});+// Tombstone GC manual trigger. Declared BEFORE `/:category/*` so the literal// "tombstones" segment wins Express's first-match lookup (categoryParam's// Zod enum would otherwise 400 before our handler runs). graceMs is clamped@@ -63,6 +99,7 @@ const forPeerOf = (req) => {// GET /api/sync/:category/checksum — return checksum only (lightweight)router.get('/:category/checksum', asyncHandler(async (req, res) => {const category = categoryParam.parse(req.params.category);+ await authorizeSyncPull(req, category);const result = await dataSync.getChecksum(category, { forPeerId: forPeerOf(req) });if (!result) throw new ServerError('Category not found', { status: 404 });res.json(result);@@ -71,6 +108,7 @@ router.get('/:category/checksum', asyncHandler(async (req, res) => {// GET /api/sync/:category/snapshot — return category data + checksumrouter.get('/:category/snapshot', asyncHandler(async (req, res) => {const category = categoryParam.parse(req.params.category);+ await authorizeSyncPull(req, category);const snapshot = await dataSync.getSnapshot(category, { forPeerId: forPeerOf(req) });if (!snapshot) throw new ServerError('Category not found', { status: 404 });res.json(snapshot);diff --git a/server/routes/dataSync.test.js b/server/routes/dataSync.test.jsindex 7f1c593f78..55ac035a87 100644--- a/server/routes/dataSync.test.js+++ b/server/routes/dataSync.test.js@@ -18,10 +18,41 @@ vi.mock('../services/dataSync.js', () => ({getSupportedCategories: vi.fn(() => []),}));+// Stub only the two leaves the REAL peer-pull gate reads — the peer registry+// and the settings file — so `findPeerById` / `peerAllowsOutbound` and the+// warn-first ramp all run for real here. Mocking `authorizePeerPull` itself+// would let the route and the gate drift, which is the whole bug (#5663).+const peers = [];+vi.mock('../services/instances.js', () => ({+ getPeers: async () => peers,+ UNKNOWN_INSTANCE_ID: 'unknown',+}));+let settings = {};+vi.mock('../services/settings.js', () => ({+ getSettings: async () => settings,+}));+import { sweepTombstones, getSweepStatus } from '../services/sharing/tombstoneGc.js';import { getChecksum, getSnapshot } from '../services/dataSync.js';+import { PEER_INSTANCE_ID_HEADER, __resetPullWarnThrottleForTests } from '../services/sharing/peerPullAuthorization.js';import dataSyncRoutes from './dataSync.js';+const PEER_ID = 'peer-a-instance-id';+// Obviously-fake peer record — outbound-allowed, which is all the snapshot+// gate checks (the transport is per-category, not per-record-kind).+const allowedPeer = (overrides = {}) => ({+ instanceId: PEER_ID,+ name: 'Example Peer',+ enabled: true,+ syncEnabled: true,+ directions: ['outbound', 'inbound'],+ ...overrides,+});+const setPeers = (...next) => {+ peers.length = 0;+ peers.push(...next);+};+const buildApp = () => {const app = express();app.use(express.json());@@ -92,6 +123,9 @@ describe('POST /api/sync/tombstones/sweep', () => {describe('GET /api/sync/:category/checksum — forPeer scoping', () => {beforeEach(() => {vi.clearAllMocks();+ settings = {};+ setPeers(allowedPeer());+ __resetPullWarnThrottleForTests();getChecksum.mockResolvedValue({ checksum: 'abc' });getSnapshot.mockResolvedValue({ data: {}, checksum: 'abc' });});@@ -123,7 +157,94 @@ describe('GET /api/sync/:category/checksum — forPeer scoping', () => {'goals', 'character', 'digitalTwin', 'meatspace','universe', 'pipeline', 'mediaCollections', 'videoHistory', 'storyBuilder', 'usage',])('accepts the %s category (enum parity with getSupportedCategories)', async (category) => {- const res = await request(buildApp()).get(`/api/sync/${category}/checksum`);+ // Identified as a configured peer so the PII categories clear the pull gate+ // (#5663) and this stays a test of the ENUM, not of authorization.+ const res = await request(buildApp())+ .get(`/api/sync/${category}/checksum`)+ .set(PEER_INSTANCE_ID_HEADER, PEER_ID);expect(res.status).not.toBe(400);});});++// #5663 — the snapshot transport predates the peer-pull gate #3659 added to+// `/api/peer-sync/*`, so it served the user's identity record to anything that+// could reach the port.+describe('GET /api/sync/:category — peer-pull authorization', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ settings = {};+ setPeers(allowedPeer());+ __resetPullWarnThrottleForTests();+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ getChecksum.mockResolvedValue({ checksum: 'abc' });+ getSnapshot.mockResolvedValue({ data: { identity: 'redacted' }, checksum: 'abc' });+ });++ it('403s the digitalTwin snapshot for a caller with no X-PortOS-Instance-Id', async () => {+ const res = await request(buildApp()).get('/api/sync/digitalTwin/snapshot');+ expect(res.status).toBe(403);+ expect(getSnapshot).not.toHaveBeenCalled();+ });++ it('403s the digitalTwin snapshot for an id that matches no configured peer', async () => {+ const res = await request(buildApp())+ .get('/api/sync/digitalTwin/snapshot')+ .set(PEER_INSTANCE_ID_HEADER, 'some-other-instance');+ expect(res.status).toBe(403);+ expect(getSnapshot).not.toHaveBeenCalled();+ });++ it('403s the digitalTwin snapshot for a peer the user disabled sync for', async () => {+ setPeers(allowedPeer({ syncEnabled: false }));+ const res = await request(buildApp())+ .get('/api/sync/digitalTwin/snapshot')+ .set(PEER_INSTANCE_ID_HEADER, PEER_ID);+ expect(res.status).toBe(403);+ expect(getSnapshot).not.toHaveBeenCalled();+ });++ it.each(['digitalTwin', 'meatspace', 'character'])(+ '403s the %s checksum too — a checksum must not be the weaker door',+ async (category) => {+ const res = await request(buildApp()).get(`/api/sync/${category}/checksum`);+ expect(res.status).toBe(403);+ expect(getChecksum).not.toHaveBeenCalled();+ },+ );++ it('refuses a PII category even with strictPullAuthorization explicitly off', async () => {+ settings = { federation: { strictPullAuthorization: false } };+ const res = await request(buildApp()).get('/api/sync/meatspace/snapshot');+ expect(res.status).toBe(403);+ });++ it('serves the digitalTwin snapshot to a configured, outbound-allowed peer', async () => {+ const res = await request(buildApp())+ .get('/api/sync/digitalTwin/snapshot')+ .set(PEER_INSTANCE_ID_HEADER, PEER_ID);+ expect(res.status).toBe(200);+ expect(getSnapshot).toHaveBeenCalledWith('digitalTwin', { forPeerId: undefined });+ });++ it('still serves a non-PII snapshot to an unidentified caller, warning once', async () => {+ const app = buildApp();+ expect((await request(app).get('/api/sync/universe/snapshot')).status).toBe(200);+ expect((await request(app).get('/api/sync/universe/snapshot')).status).toBe(200);+ expect(getSnapshot).toHaveBeenCalledTimes(2);+ expect(console.warn).toHaveBeenCalledTimes(1);+ });++ it('403s a non-PII snapshot once the user opts into strict enforcement', async () => {+ settings = { federation: { strictPullAuthorization: true } };+ const res = await request(buildApp()).get('/api/sync/universe/snapshot');+ expect(res.status).toBe(403);+ });++ it('leaves the write direction alone — apply is gated by its schema-version check, not this', async () => {+ const { applyRemote } = await import('../services/dataSync.js');+ applyRemote.mockResolvedValue({ applied: true, count: 1 });+ const res = await request(buildApp()).post('/api/sync/digitalTwin/apply').send({ data: { a: 1 } });+ expect(res.status).toBe(200);+ expect(applyRemote).toHaveBeenCalled();+ });+});diff --git a/server/services/sharing/peerPullAuthorization.js b/server/services/sharing/peerPullAuthorization.jsindex 69a3a2539d..d151d2aeab 100644--- a/server/services/sharing/peerPullAuthorization.js+++ b/server/services/sharing/peerPullAuthorization.js@@ -1,5 +1,9 @@/**- * Receiver-side authorization for peer-sync PULL requests (#3659).+ * Receiver-side authorization for peer PULL requests (#3659, #5663).+ *+ * Covers BOTH pull transports: the per-record `/api/peer-sync/*` routes+ * (`server/routes/peerSync.js`) and the older snapshot transport+ * `/api/sync/:category/*` (`server/routes/dataSync.js`).** The push direction has always been gated on the user's per-peer sharing* config (`peerAllowsOutbound` + `peerHasCategory`, see peerSyncPush.js). The@@ -24,6 +28,12 @@* single throttled `⚠️` per caller per boot. Only when the user opts in via* `settings.federation.strictPullAuthorization === true` does a denied pull* get a 403. The default flips in a later release once peers have upgraded.+ *+ * `alwaysEnforce` opts a route OUT of that ramp: a denial is a 403 whatever the+ * setting says. It exists for the PII snapshot categories, which root+ * `AGENTS.md` forbids on the federation layer at all — the ramp protects+ * creative-work sync from breaking mid-upgrade, and no compatibility argument+ * covers shipping an identity record to a host we cannot name.*/import { ServerError } from '../../lib/errorHandler.js';import { findPeerById, peerAllowsOutbound, peerHasCategory } from './peerSyncShared.js';@@ -96,38 +106,59 @@ async function strictPullAuthorizationEnabled() {return settings?.federation?.strictPullAuthorization === true;}-function warnOnce(decision, route) {- const key = decision.callerId || PULL_DENY_UNIDENTIFIED;+// Throttle key space is shared by the "served anyway" and "refused" lines, so+// a caller that trips both still gets one of each (distinct prefixes).+function logOnce(key, message) {if (warnedCallers.has(key)) return;if (warnedCallers.size >= WARNED_CALLERS_MAX) warnedCallers.clear();warnedCallers.add(key);- const who = decision.peer?.name- ? `peer "${decision.peer.name}"`- : (decision.callerId ? `instance ${decision.callerId.slice(0, 8)}…` : 'an unidentified caller');- console.warn(`⚠️ Serving peer-sync ${route} to ${who} that sharing config would deny (${decision.reason}) — enable federation.strictPullAuthorization to enforce`);+ console.warn(message);}+function describeCaller(decision) {+ if (decision.peer?.name) return `peer "${decision.peer.name}"`;+ return decision.callerId ? `instance ${decision.callerId.slice(0, 8)}…` : 'an unidentified caller';+}++function warnOnce(decision, route) {+ const key = decision.callerId || PULL_DENY_UNIDENTIFIED;+ logOnce(`serve:${key}`, `⚠️ Serving peer-sync ${route} to ${describeCaller(decision)} that sharing config would deny (${decision.reason}) — enable federation.strictPullAuthorization to enforce`);+}++function refuseOnce(decision, route) {+ const key = decision.callerId || PULL_DENY_UNIDENTIFIED;+ logOnce(`deny:${key}`, `🔒 Refused peer-sync ${route} for ${describeCaller(decision)} (${decision.reason}) — this data only federates to a configured, outbound-allowed peer`);+}++const pullForbidden = (decision) => new ServerError('peer not authorized for this record', {+ status: 403,+ code: 'PEER_PULL_FORBIDDEN',+ context: { reason: decision.reason },+});+/**- * Gate a pull route. Throws a 403 ServerError only when the request is denied- * AND `federation.strictPullAuthorization` is on; otherwise serves the request- * and warns at most once per caller per boot.+ * Gate a pull route. Throws a 403 ServerError when the request is denied AND+ * either `alwaysEnforce` is set for this route or+ * `federation.strictPullAuthorization` is on; otherwise serves the request and+ * warns at most once per caller per boot.** Returns the decision so a caller can branch further if it ever needs to.*/-export async function authorizePeerPull(req, { recordKind = null, route } = {}) {+export async function authorizePeerPull(req, { recordKind = null, route, alwaysEnforce = false } = {}) {const decision = await decidePeerPull({ callerId: readCallerInstanceId(req), recordKind });if (decision.allowed) return decision;- if (await strictPullAuthorizationEnabled()) {- throw new ServerError('peer not authorized for this record', {- status: 403,- code: 'PEER_PULL_FORBIDDEN',- context: { reason: decision.reason },- });+ const label = route || 'pull';+ // `alwaysEnforce` short-circuits the settings read: the answer cannot change.+ if (alwaysEnforce) {+ refuseOnce(decision, label);+ throw pullForbidden(decision);}- warnOnce(decision, route || 'pull');+ if (await strictPullAuthorizationEnabled()) throw pullForbidden(decision);+ warnOnce(decision, label);return decision;}+/** Test-support: clear the per-boot warn throttle. */export function __resetPullWarnThrottleForTests() {warnedCallers.clear();diff --git a/server/services/sharing/peerPullAuthorization.test.js b/server/services/sharing/peerPullAuthorization.test.jsindex f1afc5835a..4a96a2a568 100644--- a/server/services/sharing/peerPullAuthorization.test.js+++ b/server/services/sharing/peerPullAuthorization.test.js@@ -183,4 +183,38 @@ describe('peerPullAuthorization', () => {await expect(authorizePeerPull(req(null), { recordKind: 'universe' })).resolves.toBeDefined();});});++ // #5663 — the PII snapshot categories opt out of the warn-first ramp: root+ // AGENTS.md forbids those records on the federation layer at all, so an+ // unidentified caller must never be served one regardless of the setting.+ describe('alwaysEnforce', () => {+ it('403s a denied pull with strictPullAuthorization off', async () => {+ settings = { federation: { strictPullAuthorization: false } };+ await expect(authorizePeerPull(req(null), { route: 'sync digitalTwin', alwaysEnforce: true }))+ .rejects.toMatchObject({ status: 403, code: 'PEER_PULL_FORBIDDEN' });+ });++ it('still allows a configured, outbound-allowed peer', async () => {+ setPeers(universePeer());+ const decision = await authorizePeerPull(req(PEER_A), { route: 'sync digitalTwin', alwaysEnforce: true });+ expect(decision.allowed).toBe(true);+ expect(console.warn).not.toHaveBeenCalled();+ });++ it('logs the refusal once per caller per boot', async () => {+ const opts = { route: 'sync digitalTwin', alwaysEnforce: true };+ await expect(authorizePeerPull(req(null), opts)).rejects.toThrow();+ await expect(authorizePeerPull(req(null), opts)).rejects.toThrow();+ expect(console.warn).toHaveBeenCalledTimes(1);+ expect(console.warn.mock.calls[0][0]).toContain('🔒');+ });++ it('does not consume the served-anyway throttle slot for the same caller', async () => {+ // Distinct throttle keys: a caller refused a PII pull must still produce+ // the one compatibility ⚠️ when it pulls a creative-work category.+ await expect(authorizePeerPull(req(null), { route: 'sync digitalTwin', alwaysEnforce: true })).rejects.toThrow();+ await authorizePeerPull(req(null), { route: 'sync universe' });+ expect(console.warn).toHaveBeenCalledTimes(2);+ });+ });});diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex 1a7f76fc49..39fa195cff 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -13,7 +13,7 @@ import { createMutex } from '../lib/asyncMutex.js';import { instanceEvents } from './instanceEvents.js';import { getPeers, resolveEffectiveCategories, updatePeer, getInstanceId, UNKNOWN_INSTANCE_ID } from './instances.js';import { peerBaseUrl } from '../lib/peerUrl.js';-import { peerAuthHeaders } from '../lib/peerHttpClient.js';+import { peerFetch } from '../lib/peerHttpClient.js';import * as brainSync from './brainSync.js';import { BRAIN_ENTITY_TYPES } from './brainStorage.js';import * as brainSyncLog from './brainSyncLog.js';@@ -22,7 +22,7 @@ import * as memorySync from './memorySync.js';import * as catalogSync from './catalogSync.js';import * as dataSync from './dataSync.js';import { getBackendName } from './memoryBackend.js';-import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { withAbortTimeout } from '../lib/abortTimeout.js';const CURSORS_FILE = dataPath('instances_sync_cursors.json');const SYNC_INTERVAL_MS = 60000;@@ -76,15 +76,20 @@ async function withCursors(fn) {// --- Peer fetch helper ---+// Every outbound hop goes through `peerFetch` so it carries+// `X-PortOS-Instance-Id` (and the peer's stored Basic credential). The receiver+// keys its per-peer sharing config on that header — without it the snapshot+// transport reads as an unidentified caller and the PII categories now refuse+// it outright (#5663). `peerFetch` also carries the peer HTTPS agent, so a+// self-signed tailnet peer no longer fails TLS validation on these pulls.+// Contract is unchanged: null on transport failure, non-2xx, or bad JSON.async function fetchPeer(peer, path) {const url = `${peerBaseUrl(peer)}${path}`;- try {- const res = await fetchWithTimeout(url, { headers: peerAuthHeaders(peer) }, FETCH_TIMEOUT_MS);+ return withAbortTimeout(FETCH_TIMEOUT_MS, async (signal) => {+ const res = await peerFetch(url, { signal }, peer);if (!res.ok) return null;return await res.json();- } catch {- return null;- }+ }).catch(() => null);}/**@@ -103,16 +108,16 @@ async function syncImageFromPeer(peer, avatarPath) {if (exists) return;const url = `${peerBaseUrl(peer)}${avatarPath}`;- try {- const res = await fetchWithTimeout(url, { headers: peerAuthHeaders(peer) }, FETCH_TIMEOUT_MS);+ // Same `peerFetch` hop as fetchPeer — identifies us and survives a+ // self-signed peer cert. Non-critical: a failure just retries next cycle.+ await withAbortTimeout(FETCH_TIMEOUT_MS, async (signal) => {+ const res = await peerFetch(url, { signal }, peer);if (!res.ok) return;const buffer = Buffer.from(await res.arrayBuffer());await ensureDir(PATHS.images);await writeFile(localPath, buffer);console.log(`🔄 Synced avatar image: ${filename}`);- } catch {- // Non-critical — avatar will sync on next cycle- }+ }).catch(() => {});}// --- Status ---diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex 0fb97f2828..8994fff273 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -88,6 +88,12 @@ tryReadFile: vi.fn().mockResolvedValue(null),vi.mock('../lib/asyncMutex.js', () => ({createMutex: () => async (fn) => fn()}));+// Spy on the REAL peerFetch (not a stand-in) so the orchestrator's hops still+// go through the production client — the assertion is only that they do.+vi.mock('../lib/peerHttpClient.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, peerFetch: vi.fn(actual.peerFetch) };+});vi.mock('fs/promises', () => ({writeFile: vi.fn().mockResolvedValue(),rename: vi.fn().mockResolvedValue()@@ -103,6 +109,7 @@ import { instanceEvents } from './instanceEvents.js';import { getCurrentSeq, compactLog } from './brainSyncLog.js';import { getBrainChecksum, applyBrainSnapshot } from './brainReconcile.js';import { getMaxSequence } from './memorySync.js';+import { peerFetch } from '../lib/peerHttpClient.js';import { syncWithPeer, syncAllPeers, getSyncStatus, initSyncOrchestrator, stopSyncOrchestrator } from './syncOrchestrator.js';const mockFetch = vi.fn();@@ -324,6 +331,28 @@ describe('syncOrchestrator', () => {expect(urls.some((u) => u.includes('/api/sync/universe/'))).toBe(true);expect(urls.some((u) => u.includes('forPeer='))).toBe(false);});++ it('pulls snapshots through peerFetch, with the peer record, so the hop is identified (#5663)', async () => {+ // The receiver's peer-pull gate keys on `X-PortOS-Instance-Id`; without+ // it the PII categories now refuse us outright. Passing the peer record+ // as peerFetch's third arg is what attaches that header AND the stored+ // Basic credential (header contents themselves: peerHttpClient.test.js).+ // `forPeer` is a payload-scoping hint, NOT identity — don't confuse them.+ const dataSync = await import('./dataSync.js');+ dataSync.getSupportedCategories.mockReturnValue(['digitalTwin']);+ const peerWithCats = {+ ...mockPeer,+ syncCategories: { digitalTwin: true },+ auth: { username: 'alice', password: 'pw' },+ };+ mockFetch.mockResolvedValue({ ok: true, json: async () => ({ checksum: 'x', data: null }) });+ await syncWithPeer(peerWithCats);+ const call = peerFetch.mock.calls.find((c) => c[0].includes('/api/sync/digitalTwin/'));+ expect(call).toBeDefined();+ expect(call[2]).toBe(peerWithCats);+ // The 15s budget survived the move off fetchWithTimeout.+ expect(call[1].signal).toBeInstanceOf(AbortSignal);+ });});describe('catalog sync (delta-based, Postgres-only)', () => {