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: make the snapshot pull gate honor per-category consent (#5663)

Adam Eivya13af15bb677
diff --git a/server/routes/dataSync.js b/server/routes/dataSync.js
index fd4fe19c06..0e0756fc08 100644
--- a/server/routes/dataSync.js
+++ b/server/routes/dataSync.js
@@ -22,9 +22,17 @@
* 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.
+ * Consent is per-category, not just per-peer: the gate resolves the caller's
+ * `syncCategories` map (`peerAllowsCategoryPull`) rather than only asking
+ * whether the peer may receive anything at all. A peer the user enabled for
+ * `universe` must not be able to ask for `digitalTwin` — that is the same
+ * shape of hole #3659 closed for records. Resolving through
+ * `resolveEffectiveCategories` also keeps a default-ON category (`usage`)
+ * flowing for a peer whose other sync the user switched off.
+ *
+ * Scope: what a category CONTAINS is unchanged, and a user federating their own
+ * two machines keeps working as long as the SOURCE machine has that category
+ * ticked for the peer asking — which is exactly what its sharing config means.
*/
import { Router } from 'express';
@@ -50,6 +58,7 @@ 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, {
+ syncCategory: category,
route: `sync ${category}`,
alwaysEnforce: PII_CATEGORIES.has(category),
});
diff --git a/server/routes/dataSync.test.js b/server/routes/dataSync.test.js
index 55ac035a87..4e708ee679 100644
--- a/server/routes/dataSync.test.js
+++ b/server/routes/dataSync.test.js
@@ -23,9 +23,12 @@ vi.mock('../services/dataSync.js', () => ({
// 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', () => ({
+vi.mock('../services/instances.js', async () => ({
+ // Keep the REAL resolveEffectiveCategories + shipped category defaults: a
+ // hand-written stand-in would let the gate's idea of "enabled for this peer"
+ // drift from the sync loop's and the settings UI's.
+ ...(await vi.importActual('../services/instances.js')),
getPeers: async () => peers,
- UNKNOWN_INSTANCE_ID: 'unknown',
}));
let settings = {};
vi.mock('../services/settings.js', () => ({
@@ -38,13 +41,16 @@ import { PEER_INSTANCE_ID_HEADER, __resetPullWarnThrottleForTests } from '../ser
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).
+// Obviously-fake peer record. `fullSync` stands in for "the user ticked every
+// category for this peer" — the snapshot gate's unit of consent is the sync
+// CATEGORY, so a fixture without one would be denied on category grounds and
+// the identity assertions below would pass for the wrong reason.
const allowedPeer = (overrides = {}) => ({
instanceId: PEER_ID,
name: 'Example Peer',
enabled: true,
syncEnabled: true,
+ fullSync: true,
directions: ['outbound', 'inbound'],
...overrides,
});
@@ -195,7 +201,7 @@ describe('GET /api/sync/:category — peer-pull authorization', () => {
});
it('403s the digitalTwin snapshot for a peer the user disabled sync for', async () => {
- setPeers(allowedPeer({ syncEnabled: false }));
+ setPeers(allowedPeer({ fullSync: false, syncEnabled: false, syncCategories: { digitalTwin: true } }));
const res = await request(buildApp())
.get('/api/sync/digitalTwin/snapshot')
.set(PEER_INSTANCE_ID_HEADER, PEER_ID);
@@ -203,6 +209,37 @@ describe('GET /api/sync/:category — peer-pull authorization', () => {
expect(getSnapshot).not.toHaveBeenCalled();
});
+ it('403s the digitalTwin snapshot for a peer the user only enabled for universe', async () => {
+ // Per-category consent, not just per-peer: this is the record-side hole
+ // #3659 closed, applied to the snapshot transport's unit of sharing.
+ setPeers(allowedPeer({ fullSync: false, syncCategories: { universe: true } }));
+ 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('403s a peer that only ANNOUNCED itself (inbound-only, never approved here)', async () => {
+ setPeers(allowedPeer({ directions: ['inbound'] }));
+ const res = await request(buildApp())
+ .get('/api/sync/digitalTwin/snapshot')
+ .set(PEER_INSTANCE_ID_HEADER, PEER_ID);
+ expect(res.status).toBe(403);
+ });
+
+ it('keeps serving the default-ON usage category to a peer whose other sync is off', async () => {
+ // `usage` survives the master switch by design; folding the switch into the
+ // resolved category map (rather than checking it separately) is what keeps
+ // that true here. Non-PII, so this is the warn-first tier.
+ settings = { federation: { strictPullAuthorization: true } };
+ setPeers(allowedPeer({ fullSync: false, syncEnabled: false }));
+ const res = await request(buildApp())
+ .get('/api/sync/usage/snapshot')
+ .set(PEER_INSTANCE_ID_HEADER, PEER_ID);
+ expect(res.status).toBe(200);
+ });
+
it.each(['digitalTwin', 'meatspace', 'character'])(
'403s the %s checksum too — a checksum must not be the weaker door',
async (category) => {
diff --git a/server/services/sharing/peerPullAuthorization.js b/server/services/sharing/peerPullAuthorization.js
index d151d2aeab..3a404a53f0 100644
--- a/server/services/sharing/peerPullAuthorization.js
+++ b/server/services/sharing/peerPullAuthorization.js
@@ -36,7 +36,7 @@
* covers shipping an identity record to a host we cannot name.
*/
import { ServerError } from '../../lib/errorHandler.js';
-import { findPeerById, peerAllowsOutbound, peerHasCategory } from './peerSyncShared.js';
+import { findPeerById, peerAllowsOutbound, peerAllowsCategoryPull, peerHasCategory } from './peerSyncShared.js';
import { getSettings } from '../settings.js';
import { UNKNOWN_INSTANCE_ID } from '../instances.js';
@@ -84,16 +84,28 @@ export function readCallerInstanceId(req) {
* setting or logging — the pure-ish decision half, so tests can assert it
* agrees with the push path for a given peer/kind pair.
*
- * `recordKind` is optional: the manifest routes (`/library-manifest`,
- * `/cos-history-manifest`, `/cos-tasks`) aren't scoped to one record kind, so
- * they gate on `peerAllowsOutbound` alone.
+ * Scope, at most one of:
+ * - `recordKind` — a per-record `/api/peer-sync/*` read. Gated on
+ * `peerAllowsOutbound` + `peerHasCategory`, the predicates the push path uses.
+ * - `syncCategory` — a whole-category `/api/sync/*` snapshot read. Gated on
+ * `peerAllowsCategoryPull`, which folds the master switch into the resolved
+ * category map instead of checking it separately, so a default-ON category
+ * still flows for a peer whose other sync the user turned off.
+ * - neither — the manifest routes (`/library-manifest`, `/cos-history-manifest`,
+ * `/cos-tasks`) aren't scoped to one kind, so they gate on
+ * `peerAllowsOutbound` alone.
*
* Returns `{ allowed, reason, peer, callerId }`.
*/
-export async function decidePeerPull({ callerId, recordKind = null }) {
+export async function decidePeerPull({ callerId, recordKind = null, syncCategory = null }) {
if (!callerId) return { allowed: false, reason: PULL_DENY_UNIDENTIFIED, peer: null, callerId: null };
const peer = await findPeerById(callerId);
if (!peer) return { allowed: false, reason: PULL_DENY_UNKNOWN_PEER, peer: null, callerId };
+ if (syncCategory) {
+ return peerAllowsCategoryPull(peer, syncCategory)
+ ? { allowed: true, reason: null, peer, callerId }
+ : { allowed: false, reason: PULL_DENY_CATEGORY, peer, callerId };
+ }
if (!peerAllowsOutbound(peer)) return { allowed: false, reason: PULL_DENY_OUTBOUND, peer, callerId };
if (recordKind && !peerHasCategory(peer, recordKind)) {
return { allowed: false, reason: PULL_DENY_CATEGORY, peer, callerId };
@@ -144,8 +156,8 @@ const pullForbidden = (decision) => new ServerError('peer not authorized for thi
*
* Returns the decision so a caller can branch further if it ever needs to.
*/
-export async function authorizePeerPull(req, { recordKind = null, route, alwaysEnforce = false } = {}) {
- const decision = await decidePeerPull({ callerId: readCallerInstanceId(req), recordKind });
+export async function authorizePeerPull(req, { recordKind = null, syncCategory = null, route, alwaysEnforce = false } = {}) {
+ const decision = await decidePeerPull({ callerId: readCallerInstanceId(req), recordKind, syncCategory });
if (decision.allowed) return decision;
const label = route || 'pull';
// `alwaysEnforce` short-circuits the settings read: the answer cannot change.
diff --git a/server/services/sharing/peerPullAuthorization.test.js b/server/services/sharing/peerPullAuthorization.test.js
index 4a96a2a568..52e2fa9f6c 100644
--- a/server/services/sharing/peerPullAuthorization.test.js
+++ b/server/services/sharing/peerPullAuthorization.test.js
@@ -6,9 +6,12 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
// `peerAllowsOutbound` / `peerHasCategory` run — which is the point: the test
// asserts pull agrees with push because both use those same predicates.
const peers = [];
-vi.mock('../instances.js', () => ({
+vi.mock('../instances.js', async () => ({
+ // Real `resolveEffectiveCategories` + shipped defaults, for the same reason:
+ // the category-scoped pull decision must agree with what the sync loop and
+ // the settings UI resolve for that peer.
+ ...(await vi.importActual('../instances.js')),
getPeers: async () => peers,
- UNKNOWN_INSTANCE_ID: 'unknown',
}));
let settings = {};
@@ -184,6 +187,40 @@ describe('peerPullAuthorization', () => {
});
});
+ // #5663 — the snapshot transport's unit of consent is a whole sync CATEGORY,
+ // not a record kind, so it resolves the peer's category map directly.
+ describe('syncCategory scope', () => {
+ it('allows a category the user ticked for this peer', async () => {
+ setPeers(universePeer());
+ const decision = await decidePeerPull({ callerId: PEER_A, syncCategory: 'universe' });
+ expect(decision.allowed).toBe(true);
+ });
+
+ it('denies a category the user did NOT tick, even for an outbound-allowed peer', async () => {
+ setPeers(universePeer());
+ const decision = await decidePeerPull({ callerId: PEER_A, syncCategory: 'digitalTwin' });
+ expect(decision).toMatchObject({ allowed: false, reason: PULL_DENY_CATEGORY });
+ });
+
+ it('allows anything for a full-sync ("mirror everything") peer', async () => {
+ setPeers(universePeer({ fullSync: true, syncCategories: {} }));
+ expect((await decidePeerPull({ callerId: PEER_A, syncCategory: 'digitalTwin' })).allowed).toBe(true);
+ });
+
+ it('keeps a default-ON category flowing when the master sync switch is off', async () => {
+ // `usage` is retained by resolveEffectiveCategories' master-switch mask;
+ // gating on peerAllowsOutbound instead would refuse it outright.
+ setPeers(universePeer({ syncEnabled: false }));
+ expect((await decidePeerPull({ callerId: PEER_A, syncCategory: 'usage' })).allowed).toBe(true);
+ expect((await decidePeerPull({ callerId: PEER_A, syncCategory: 'universe' })).allowed).toBe(false);
+ });
+
+ it('denies a peer that only announced itself (inbound-only, never approved here)', async () => {
+ setPeers(universePeer({ directions: ['inbound'] }));
+ expect((await decidePeerPull({ callerId: PEER_A, syncCategory: 'universe' })).allowed).toBe(false);
+ });
+ });
+
// #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.
diff --git a/server/services/sharing/peerSyncShared.js b/server/services/sharing/peerSyncShared.js
index 1a8e1832f1..91d6ba3dab 100644
--- a/server/services/sharing/peerSyncShared.js
+++ b/server/services/sharing/peerSyncShared.js
@@ -13,7 +13,7 @@
import { join } from 'path';
import { EventEmitter } from 'events';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';
-import { getPeers } from '../instances.js';
+import { getPeers, resolveEffectiveCategories } from '../instances.js';
export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']);
@@ -106,8 +106,19 @@ export const KIND_TO_CATEGORY = Object.freeze({
creativeCommission: 'creativeCommissions',
});
-export function peerAllowsOutbound(peer) {
+// The half every outbound predicate shares: the peer exists, the user has not
+// disabled it, and the relationship was established FROM here. An absent/empty
+// `directions` is a legacy record (permissive); `['inbound']` is a peer that
+// merely announced itself to us and was auto-created with no approval step, so
+// nothing may flow back out to it.
+function peerOutboundEligible(peer) {
if (!peer || peer.enabled === false) return false;
+ const directions = Array.isArray(peer.directions) ? peer.directions : [];
+ return directions.length === 0 || directions.includes('outbound');
+}
+
+export function peerAllowsOutbound(peer) {
+ if (!peerOutboundEligible(peer)) return false;
// `syncEnabled` is the global "sync this peer at all" toggle (separate from
// per-category `syncCategories.*`). When the user has globally disabled sync
// for a peer, auto-subscribe MUST NOT create subscriptions or fire pushes —
@@ -115,11 +126,26 @@ export function peerAllowsOutbound(peer) {
// per-category check (peerHasCategory) is necessary but not sufficient on
// its own, because syncCategories can be set independently.
if (peer.syncEnabled === false) return false;
- const directions = Array.isArray(peer.directions) ? peer.directions : [];
- if (directions.length > 0 && !directions.includes('outbound')) return false;
return true;
}
+/**
+ * Category-level counterpart of `peerHasCategory`, for the snapshot transport
+ * (`server/routes/dataSync.js`) whose unit of consent is a whole sync CATEGORY
+ * rather than one record kind.
+ *
+ * Resolves through `resolveEffectiveCategories` — the single definition of
+ * "what syncs with this peer" — so the pull gate agrees with the sync loop and
+ * the settings UI on fullSync, on the shipped defaults, and on the master
+ * `syncEnabled` switch masking down to the default-ON categories (which is
+ * what keeps `usage` flowing for a peer the user otherwise silenced, instead of
+ * `peerAllowsOutbound` refusing it outright).
+ */
+export function peerAllowsCategoryPull(peer, category) {
+ if (!peerOutboundEligible(peer)) return false;
+ return resolveEffectiveCategories(peer)[category] === true;
+}
+
export function peerHasCategory(peer, recordKind) {
const cat = KIND_TO_CATEGORY[recordKind];
if (!cat) return false;
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index 39fa195cff..188a62db47 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -82,14 +82,18 @@ async function withCursors(fn) {
// 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.
+//
+// The timeout bounds the REQUEST only, not the body read — `withAbortTimeout`
+// clears its timer as soon as the callback settles, which reproduces what
+// `fetchWithTimeout` did here. Bounding the body too would abort a large
+// snapshot mid-download on a slow link, every cycle, forever.
// Contract is unchanged: null on transport failure, non-2xx, or bad JSON.
async function fetchPeer(peer, path) {
const url = `${peerBaseUrl(peer)}${path}`;
- return withAbortTimeout(FETCH_TIMEOUT_MS, async (signal) => {
- const res = await peerFetch(url, { signal }, peer);
- if (!res.ok) return null;
- return await res.json();
- }).catch(() => null);
+ const res = await withAbortTimeout(FETCH_TIMEOUT_MS, (signal) => peerFetch(url, { signal }, peer))
+ .catch(() => null);
+ if (!res?.ok) return null;
+ return res.json().catch(() => null);
}
/**
@@ -108,16 +112,19 @@ async function syncImageFromPeer(peer, avatarPath) {
if (exists) return;
const url = `${peerBaseUrl(peer)}${avatarPath}`;
- // 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(() => {});
+ // Same `peerFetch` hop as fetchPeer, and the same request-only timeout — an
+ // avatar download must not be aborted mid-body. Non-critical either way: a
+ // failure just retries next cycle.
+ const res = await withAbortTimeout(FETCH_TIMEOUT_MS, (signal) => peerFetch(url, { signal }, peer))
+ .catch(() => null);
+ if (!res?.ok) return;
+ await res.arrayBuffer()
+ .then(async (bytes) => {
+ await ensureDir(PATHS.images);
+ await writeFile(localPath, Buffer.from(bytes));
+ console.log(`🔄 Synced avatar image: ${filename}`);
+ })
+ .catch(() => {});
}
// --- Status ---