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: gate peer-sync pull routes on the requesting peer's sharing config, warn-first (#3659)
[._.]/ Adam Eivycb764fbb4781
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 16fee22bcd..72d7c74f95 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -42,3 +42,5 @@## Privacy Center- **Your PII vault stays on one machine — permanently, by decision.** The Privacy Center's vault, organization registry, change-of-address inventory and broker opt-out ledger were always machine-local, but that was recorded as a feature not yet built, which left the door open to syncing them to your other PortOS machines later. It is now a documented guarantee: none of it federates, and none of it ever will without a new decision record superseding this one. The reasoning is written up in full — chiefly that PortOS's peer-sync was built for creative work rather than identity data, that the display masks (`••••1234`, `j•••@example.com`) are readable even when the underlying values are encrypted, and that copying one encryption key to several machines would widen the exposure of every one of them. If you want the vault on a second machine, restore a backup and copy the key by hand — a deliberate act, rather than something that happens quietly in the background. Managing PII for other household members is unaffected and remains planned.++- **Peer-sync pull requests now honor the per-peer sharing settings the push direction already respected.** `GET /api/peer-sync/record` served any subscribable record by id with no notion of who was asking, so a peer configured for "universes only" — or one with sync switched off entirely — could still read every series, media collection, and writers-room record; the library, CoS-history, and CoS-task manifests had the same shape. Every outbound hop now identifies this install with an `X-PortOS-Instance-Id` header attached centrally in `peerFetch`, and the receiver resolves that id against its peer registry and runs the *same* `peerAllowsOutbound` + `peerHasCategory` predicates the push path uses, so the two directions can't drift apart again. Because peers upgrade independently this ships warn-first: a pull from an unidentified, unknown, or disallowed caller is still served and logs one `⚠️` per caller per restart. The new **Settings → Sharing → "Enforce per-peer sharing settings on pull requests"** toggle (`federation.strictPullAuthorization`, default off) turns those into a 403 — the default flips in a later release once peers have had time to update. Note that the instance id is *identification*, not authentication; the instance password remains the actual access control.diff --git a/client/src/components/settings/SharingTab.jsx b/client/src/components/settings/SharingTab.jsxindex ce29634657..a6b8639605 100644--- a/client/src/components/settings/SharingTab.jsx+++ b/client/src/components/settings/SharingTab.jsx@@ -1,5 +1,5 @@import { useEffect, useState } from 'react';-import { Save, Loader2, Users } from 'lucide-react';+import { Save, Loader2, Users, ShieldCheck } from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import { getSettings, updateSettings } from '../../services/api';@@ -11,6 +11,11 @@ export function SharingTab() {const [savedDisplayName, setSavedDisplayName] = useState('');const [savedBio, setSavedBio] = useState('');const [saving, setSaving] = useState(false);+ const [strictPull, setStrictPull] = useState(false);+ const [strictPullSaving, setStrictPullSaving] = useState(false);+ // The settings PATCH shallow-merges top-level keys, so `federation` is+ // replaced wholesale — carry the rest of the slice forward on every write.+ const [federationSettings, setFederationSettings] = useState({});useEffect(() => {getSettings({ silent: true })@@ -21,6 +26,9 @@ export function SharingTab() {setBio(b);setSavedDisplayName(display);setSavedBio(b);+ const federation = settings?.federation && typeof settings.federation === 'object' ? settings.federation : {};+ setFederationSettings(federation);+ setStrictPull(federation.strictPullAuthorization === true);}).catch(() => toast.error('Failed to load settings')).finally(() => setLoading(false));@@ -44,6 +52,17 @@ export function SharingTab() {toast.success('Saved');};+ const handleStrictPullToggle = async (next) => {+ setStrictPullSaving(true);+ const federation = { ...federationSettings, strictPullAuthorization: next };+ const merged = await updateSettings({ federation }).catch(() => null);+ setStrictPullSaving(false);+ if (!merged) return;+ setFederationSettings(federation);+ setStrictPull(next);+ toast.success(next ? 'Strict pull authorization on' : 'Strict pull authorization off');+ };+if (loading) return <BrailleSpinner />;return (@@ -95,6 +114,33 @@ export function SharingTab() {</div></div></div>++ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">+ <div className="flex items-center gap-2 mb-2">+ <ShieldCheck size={16} className="text-port-accent" />+ <h3 className="text-lg font-semibold text-white">Federation pull authorization</h3>+ </div>+ <p className="text-sm text-gray-400 mb-4">+ Peers that pull records from this instance are identified by the instance id they send.+ By default a pull that your per-peer sharing settings would deny is still served, and logs a+ warning once per peer per restart — so peers running an older PortOS keep syncing.+ Turn this on to reject those pulls with a 403 instead. This default flips in a future release.+ </p>+ <label htmlFor="federation-strict-pull" className="flex items-start gap-3 cursor-pointer">+ <input+ id="federation-strict-pull"+ type="checkbox"+ checked={strictPull}+ disabled={strictPullSaving}+ onChange={(e) => handleStrictPullToggle(e.target.checked)}+ className="mt-1 h-4 w-4 accent-port-accent disabled:opacity-40"+ />+ <span className="text-sm text-white">+ Enforce per-peer sharing settings on pull requests+ {strictPullSaving && <Loader2 size={12} className="inline ml-2 animate-spin" />}+ </span>+ </label>+ </div></div>);}diff --git a/client/src/components/settings/SharingTab.test.jsx b/client/src/components/settings/SharingTab.test.jsxnew file mode 100644index 0000000000..6ee7152620--- /dev/null+++ b/client/src/components/settings/SharingTab.test.jsx@@ -0,0 +1,60 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';++vi.mock('../../services/api', () => ({+ getSettings: vi.fn(),+ updateSettings: vi.fn(),+}));+vi.mock('../ui/Toast', () => ({+ default: Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ }),+}));++import { getSettings, updateSettings } from '../../services/api';+import { SharingTab } from './SharingTab';++const strictToggle = () => screen.getByLabelText(/Enforce per-peer sharing settings/i);++beforeEach(() => {+ vi.clearAllMocks();+ getSettings.mockResolvedValue({ sharingDisplayName: '', sharingBio: '' });+ updateSettings.mockResolvedValue({});+});++describe('SharingTab — federation pull authorization (#3659)', () => {+ it('defaults the strict-pull toggle off when the setting is absent', async () => {+ render(<SharingTab />);+ await waitFor(() => expect(strictToggle()).toBeInTheDocument());+ expect(strictToggle().checked).toBe(false);+ });++ it('reflects the persisted setting', async () => {+ getSettings.mockResolvedValue({ federation: { strictPullAuthorization: true } });+ render(<SharingTab />);+ await waitFor(() => expect(strictToggle().checked).toBe(true));+ });++ it('carries the rest of the federation slice forward on save (shallow top-level merge)', async () => {+ getSettings.mockResolvedValue({ federation: { strictPullAuthorization: false, somethingElse: 'keep-me' } });+ render(<SharingTab />);+ await waitFor(() => expect(strictToggle()).toBeInTheDocument());+ fireEvent.click(strictToggle());+ await waitFor(() => expect(updateSettings).toHaveBeenCalledWith({+ federation: { strictPullAuthorization: true, somethingElse: 'keep-me' },+ }));+ await waitFor(() => expect(strictToggle().checked).toBe(true));+ });++ it('leaves the toggle unchanged when the save fails', async () => {+ updateSettings.mockRejectedValue(new Error('nope'));+ render(<SharingTab />);+ await waitFor(() => expect(strictToggle()).toBeInTheDocument());+ fireEvent.click(strictToggle());+ await waitFor(() => expect(updateSettings).toHaveBeenCalled());+ await waitFor(() => expect(strictToggle().checked).toBe(false));+ });+});diff --git a/server/lib/peerHttpClient.js b/server/lib/peerHttpClient.jsindex 194fe13ecf..f94c998632 100644--- a/server/lib/peerHttpClient.js+++ b/server/lib/peerHttpClient.js@@ -33,16 +33,45 @@ export function peerAuthHeaders(peer) {return { Authorization: `Basic ${token}` };}+// Our own federation instance id, memoized after the first successful read.+// Resolved through a DYNAMIC import because `services/instances.js` imports+// this module — a static import back would close an evaluation-order cycle.+// A failed/absent identity yields no header at all rather than the+// `UNKNOWN_INSTANCE_ID` sentinel, so a receiver sees "unidentified" instead of+// a bogus id it would then fail to resolve in its peer registry.+let cachedSelfInstanceId = null;+async function selfInstanceHeader() {+ if (!cachedSelfInstanceId) {+ const instances = await import('../services/instances.js').catch(() => null);+ const id = await instances?.getInstanceId?.().catch(() => null);+ if (typeof id === 'string' && id && id !== instances?.UNKNOWN_INSTANCE_ID) cachedSelfInstanceId = id;+ }+ return cachedSelfInstanceId ? { 'X-PortOS-Instance-Id': cachedSelfInstanceId } : {};+}++/** Test-support: drop the memoized instance id. */+export function __resetSelfInstanceIdForTests() {+ cachedSelfInstanceId = null;+}+/**- * Fetch a peer URL. Pass the `peer` record (third arg) so a stored Basic-auth- * credential is attached automatically; explicit `options.headers` still win- * over the injected `Authorization` (they never collide in practice). The- * `peer` arg is optional so existing two-arg callers keep working.+ * Fetch a peer URL. Every hop identifies this install with+ * `X-PortOS-Instance-Id` so the receiver can apply the user's per-peer sharing+ * config to PULL requests (#3659) the way it already does to pushes. Pass the+ * `peer` record (third arg) so a stored Basic-auth credential is attached too;+ * explicit `options.headers` still win over both injected headers (they never+ * collide in practice). The `peer` arg is optional so existing two-arg callers+ * keep working.*/-export function peerFetch(url, options = {}, peer = null) {- const finalOptions = peer- ? { ...options, headers: { ...peerAuthHeaders(peer), ...(options.headers || {}) } }- : options;+export async function peerFetch(url, options = {}, peer = null) {+ const finalOptions = {+ ...options,+ headers: {+ ...await selfInstanceHeader(),+ ...(peer ? peerAuthHeaders(peer) : {}),+ ...(options.headers || {}),+ },+ };return url.startsWith('https://') ? httpsFetch(url, finalOptions) : fetch(url, finalOptions);}diff --git a/server/lib/peerHttpClient.test.js b/server/lib/peerHttpClient.test.jsindex 806d54a74d..25b0817c3d 100644--- a/server/lib/peerHttpClient.test.js+++ b/server/lib/peerHttpClient.test.js@@ -1,5 +1,21 @@-import { describe, it, expect } from 'vitest';-import { peerSocketOptions, peerSocketOptionsFor, peerFetch, peerAuthHeaders } from './peerHttpClient.js';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++// peerFetch resolves this install's federation identity through a dynamic+// import of the instances service; stub it so the header assertions don't+// depend on (or create) a real instance identity on disk.+let selfInstanceId = 'self-instance-id';+vi.mock('../services/instances.js', () => ({+ getInstanceId: async () => selfInstanceId,+ UNKNOWN_INSTANCE_ID: 'unknown',+}));++import {+ peerSocketOptions,+ peerSocketOptionsFor,+ peerFetch,+ peerAuthHeaders,+ __resetSelfInstanceIdForTests,+} from './peerHttpClient.js';describe('peerHttpClient', () => {it('peerSocketOptions disables cert validation for Socket.IO peer connections', () => {@@ -13,6 +29,49 @@ describe('peerHttpClient', () => {})).rejects.toBeDefined();});+ describe('peerFetch headers', () => {+ const realFetch = globalThis.fetch;+ let calls;++ beforeEach(() => {+ selfInstanceId = 'self-instance-id';+ __resetSelfInstanceIdForTests();+ calls = [];+ globalThis.fetch = async (url, options) => {+ calls.push({ url, options });+ return { ok: true };+ };+ });++ afterEach(() => {+ globalThis.fetch = realFetch;+ __resetSelfInstanceIdForTests();+ });++ it('identifies this install with X-PortOS-Instance-Id on every hop', async () => {+ await peerFetch('http://peer.example/api/peer-sync/record');+ expect(calls[0].options.headers['X-PortOS-Instance-Id']).toBe('self-instance-id');+ });++ it('sends the instance id alongside the peer Basic credential', async () => {+ await peerFetch('http://peer.example/api/peer-sync/record', {}, { auth: { username: 'alice', password: 'pw' } });+ expect(calls[0].options.headers['X-PortOS-Instance-Id']).toBe('self-instance-id');+ expect(calls[0].options.headers.Authorization).toBe(`Basic ${Buffer.from('alice:pw').toString('base64')}`);+ });++ it('lets explicit caller headers win', async () => {+ await peerFetch('http://peer.example/x', { headers: { 'X-PortOS-Instance-Id': 'explicit' } });+ expect(calls[0].options.headers['X-PortOS-Instance-Id']).toBe('explicit');+ });++ it('omits the header entirely when this install has no identity yet', async () => {+ selfInstanceId = 'unknown';+ __resetSelfInstanceIdForTests();+ await peerFetch('http://peer.example/x');+ expect(calls[0].options.headers['X-PortOS-Instance-Id']).toBeUndefined();+ });+ });+describe('peerAuthHeaders', () => {it('returns an empty object when the peer has no credential', () => {expect(peerAuthHeaders(null)).toEqual({});diff --git a/server/routes/peerSync.js b/server/routes/peerSync.jsindex bee07c8980..911dece6ee 100644--- a/server/routes/peerSync.js+++ b/server/routes/peerSync.js@@ -56,6 +56,7 @@ import {PEER_SUBSCRIBABLE_KINDS,} from '../services/sharing/peerSync.js';import { buildLocalManifest, getPeerIntegrity } from '../services/sharing/integrity.js';+import { authorizePeerPull } from '../services/sharing/peerPullAuthorization.js';const router = Router();@@ -164,7 +165,10 @@ router.get('/manifest', asyncHandler(async (req, res) => {// per the threat model); the receiver gates the PULL on its own `fullSync` flag,// so advertising the manifest to any tailnet peer is safe (it's read-only and// the bytes are already served by the /data/* static mounts).-router.get('/library-manifest', asyncHandler(async (_req, res) => {+// The manifests aren't scoped to one record kind, so they gate on+// `peerAllowsOutbound` alone (no `peerHasCategory`) — see peerPullAuthorization.js.+router.get('/library-manifest', asyncHandler(async (req, res) => {+ await authorizePeerPull(req, { route: 'library-manifest' });res.json(await buildMediaLibraryManifest());}));@@ -176,7 +180,8 @@ router.get('/library-manifest', asyncHandler(async (_req, res) => {// sha256 }] }` over data/cos/agents/<date>/<agentId>/{metadata,output,prompt}.// Unauthenticated like every peer-sync route (Tailnet-only per the threat// model); the receiver gates the PULL on its own `fullSync` flag.-router.get('/cos-history-manifest', asyncHandler(async (_req, res) => {+router.get('/cos-history-manifest', asyncHandler(async (req, res) => {+ await authorizePeerPull(req, { route: 'cos-history-manifest' });res.json(await buildCosHistoryManifest());}));@@ -190,7 +195,8 @@ router.get('/cos-history-manifest', asyncHandler(async (_req, res) => {// (#1563) the receiver respects so a peer's fresh claim is never clobbered.// Unauthenticated like every peer-sync route (Tailnet-only per the threat model);// the receiver gates the MERGE on its own `fullSync` flag.-router.get('/cos-tasks', asyncHandler(async (_req, res) => {+router.get('/cos-tasks', asyncHandler(async (req, res) => {+ await authorizePeerPull(req, { route: 'cos-tasks' });res.json(await buildCosTasksPayload());}));@@ -229,6 +235,11 @@ router.get('/record', asyncHandler(async (req, res) => {if (!id) {throw new ServerError('id required', { status: 400, code: 'VALIDATION_ERROR' });}+ // Honor the user's per-peer sharing config on the PULL direction too (#3659)+ // — same `peerAllowsOutbound` + `peerHasCategory` predicates the push path+ // uses, resolved from the caller's `X-PortOS-Instance-Id`. Warn-only until+ // `federation.strictPullAuthorization` is turned on.+ await authorizePeerPull(req, { recordKind: kind, route: `record ${kind}` });const payload = await getRecordPayloadForPeer(kind, id);if (!payload) {throw new ServerError('record not found', { status: 404, code: 'NOT_FOUND' });diff --git a/server/routes/peerSync.test.js b/server/routes/peerSync.test.jsindex 58b5bb3061..2a031d4ed0 100644--- a/server/routes/peerSync.test.js+++ b/server/routes/peerSync.test.js@@ -30,7 +30,15 @@ vi.mock('../services/sharing/sidecarSync.js', () => ({backfillMissingSidecars: vi.fn(),}));+// The pull gate (#3659) reads the peer registry + settings from disk; mock it+// so these route tests stay hermetic and can drive both the warn-only (default)+// and strict outcomes explicitly.+vi.mock('../services/sharing/peerPullAuthorization.js', () => ({+ authorizePeerPull: vi.fn(),+}));+import * as svc from '../services/sharing/peerSync.js';+import { authorizePeerPull } from '../services/sharing/peerPullAuthorization.js';import * as integritySvc from '../services/sharing/integrity.js';import * as sidecarSvc from '../services/sharing/sidecarSync.js';import peerSyncRoutes from './peerSync.js';@@ -54,6 +62,8 @@ describe('peer-sync routes', () => {vi.clearAllMocks();integritySvc.buildLocalManifest.mockResolvedValue([]);integritySvc.getPeerIntegrity.mockResolvedValue({ available: false, reason: 'peer-not-found', records: [] });+ // Default: warn-only mode resolves for every caller (nothing is blocked).+ vi.mocked(authorizePeerPull).mockResolvedValue({ allowed: true, reason: null, peer: null, callerId: null });});describe('POST /api/peer-sync/push', () => {@@ -774,6 +784,43 @@ describe('peer-sync routes', () => {expect((await request(buildApp()).get('/api/peer-sync/record?kind=universe&id=%20%20')).status).toBe(400);expect(svc.getRecordPayloadForPeer).not.toHaveBeenCalled();});++ it('runs the pull gate for the requested record kind (#3659)', async () => {+ svc.getRecordPayloadForPeer.mockResolvedValue({ kind: 'universe', record: { id: 'u1' }, assetManifest: [], sourceInstanceId: 'me' });+ await request(buildApp()).get('/api/peer-sync/record?kind=universe&id=u1');+ expect(authorizePeerPull).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ recordKind: 'universe' }));+ });++ it('403s without reading the record when the gate rejects (strict mode)', async () => {+ vi.mocked(authorizePeerPull).mockRejectedValue(+ Object.assign(new Error('peer not authorized for this record'), { status: 403, code: 'PEER_PULL_FORBIDDEN' })+ );+ const res = await request(buildApp()).get('/api/peer-sync/record?kind=series&id=s1');+ expect(res.status).toBe(403);+ expect(svc.getRecordPayloadForPeer).not.toHaveBeenCalled();+ });+ });++ describe('manifest pull gate (#3659)', () => {+ it.each([+ ['/api/peer-sync/library-manifest', 'buildMediaLibraryManifest'],+ ['/api/peer-sync/cos-history-manifest', 'buildCosHistoryManifest'],+ ['/api/peer-sync/cos-tasks', 'buildCosTasksPayload'],+ ])('403s %s without building the payload when the gate rejects', async (path, fn) => {+ vi.mocked(authorizePeerPull).mockRejectedValue(+ Object.assign(new Error('peer not authorized for this record'), { status: 403, code: 'PEER_PULL_FORBIDDEN' })+ );+ const res = await request(buildApp()).get(path);+ expect(res.status).toBe(403);+ expect(svc[fn]).not.toHaveBeenCalled();+ });++ it('gates the manifests on outbound only — no record kind', async () => {+ svc.buildMediaLibraryManifest.mockResolvedValue({ schemaVersion: 1, assets: [] });+ await request(buildApp()).get('/api/peer-sync/library-manifest');+ expect(authorizePeerPull).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ route: 'library-manifest' }));+ expect(vi.mocked(authorizePeerPull).mock.calls[0][1].recordKind).toBeUndefined();+ });});describe('POST /api/peer-sync/pull-record', () => {diff --git a/server/services/sharing/peerPullAuthorization.js b/server/services/sharing/peerPullAuthorization.jsnew file mode 100644index 0000000000..d5b94f2f58--- /dev/null+++ b/server/services/sharing/peerPullAuthorization.js@@ -0,0 +1,123 @@+/**+ * Receiver-side authorization for peer-sync PULL requests (#3659).+ *+ * The push direction has always been gated on the user's per-peer sharing+ * config (`peerAllowsOutbound` + `peerHasCategory`, see peerSyncPush.js). The+ * pull direction — `GET /api/peer-sync/record`, plus the manifest routes —+ * had no counterpart: it served any subscribable record by id to anything that+ * could reach the port, so a peer configured for "universes only" (or with+ * sync disabled entirely) could still read every series / collection /+ * writers-room record. This module closes that gap by resolving WHO is asking+ * and running the SAME predicates the push path uses. Deliberately no second+ * authorization predicate lives here — divergence between the push and pull+ * rules is exactly how the gap appeared.+ *+ * Honest framing: `X-PortOS-Instance-Id` is *identification*, not+ * authentication — it is self-asserted and spoofable on an unauthenticated+ * tailnet. The real authentication control remains the optional instance+ * password (`server/lib/authGate.js`). The value here is that the pull path+ * honors the sharing config the user actually configured.+ *+ * Compatibility (required by the distribution model — peers upgrade+ * independently): this is WARN-FIRST. A request with no id, an unknown id, or+ * an id whose peer config disallows the read is still SERVED, and logs a+ * 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.+ */+import { ServerError } from '../../lib/errorHandler.js';+import { findPeerById, peerAllowsOutbound, peerHasCategory } from './peerSyncShared.js';+import { getSettings } from '../settings.js';+import { UNKNOWN_INSTANCE_ID } from '../instances.js';++// Lower-cased because Node/Express normalize incoming header names. The+// outbound spelling (`X-PortOS-Instance-Id`) lives in lib/peerHttpClient.js.+export const PEER_INSTANCE_ID_HEADER = 'x-portos-instance-id';++// Denial reasons — deliberately the same strings the push path returns for the+// equivalent decisions, so a log line reads the same in either direction.+export const PULL_DENY_UNIDENTIFIED = 'unidentified-peer';+export const PULL_DENY_UNKNOWN_PEER = 'unknown-peer';+export const PULL_DENY_OUTBOUND = 'peer-disallows-outbound';+export const PULL_DENY_CATEGORY = 'category-disabled';++// One warning per caller per boot (the acceptance criterion). Keyed by the+// resolved peer id, or the literal `PULL_DENY_UNIDENTIFIED` bucket when there+// is no id at all — so an install with three not-yet-upgraded peers logs once+// for the absent-header case rather than once per request.+const warnedCallers = new Set();++/**+ * Read the caller's self-asserted instance id off the request headers.+ * Returns `null` for absent/blank/sentinel values so callers get one+ * "unidentified" shape instead of three.+ */+export function readCallerInstanceId(req) {+ const raw = req?.headers?.[PEER_INSTANCE_ID_HEADER];+ const value = typeof raw === 'string' ? raw.trim() : '';+ if (!value || value === UNKNOWN_INSTANCE_ID) return null;+ return value;+}++/**+ * Decide whether a pull should be served, WITHOUT consulting the strict+ * 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.+ *+ * Returns `{ allowed, reason, peer, callerId }`.+ */+export async function decidePeerPull({ callerId, recordKind = 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 (!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 };+ }+ return { allowed: true, reason: null, peer, callerId };+}++async function strictPullAuthorizationEnabled() {+ const settings = await getSettings().catch(() => null);+ return settings?.federation?.strictPullAuthorization === true;+}++function warnOnce(decision, route) {+ const key = decision.callerId || PULL_DENY_UNIDENTIFIED;+ if (warnedCallers.has(key)) return;+ 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`);+}++/**+ * 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.+ *+ * Returns the decision so a caller can branch further if it ever needs to.+ */+export async function authorizePeerPull(req, { recordKind = null, route } = {}) {+ 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 },+ });+ }+ warnOnce(decision, route || 'pull');+ 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.jsnew file mode 100644index 0000000000..fa853d5772--- /dev/null+++ b/server/services/sharing/peerPullAuthorization.test.js@@ -0,0 +1,181 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';++// `instances.js` pulls in the socket relay / Tailscale graph; the only things+// this module and `peerSyncShared` need from it are `getPeers` and the+// UNKNOWN_INSTANCE_ID sentinel. Mocking it lets the REAL `findPeerById` /+// `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', () => ({+ getPeers: async () => peers,+ UNKNOWN_INSTANCE_ID: 'unknown',+}));++let settings = {};+vi.mock('../settings.js', () => ({+ getSettings: async () => settings,+}));++const {+ authorizePeerPull,+ decidePeerPull,+ readCallerInstanceId,+ __resetPullWarnThrottleForTests,+ PEER_INSTANCE_ID_HEADER,+ PULL_DENY_UNIDENTIFIED,+ PULL_DENY_UNKNOWN_PEER,+ PULL_DENY_OUTBOUND,+ PULL_DENY_CATEGORY,+} = await import('./peerPullAuthorization.js');+const { peerAllowsOutbound, peerHasCategory } = await import('./peerSyncShared.js');++const PEER_A = 'peer-a-instance-id';+const req = (instanceId) => ({ headers: instanceId ? { [PEER_INSTANCE_ID_HEADER]: instanceId } : {} });++const setPeers = (...next) => {+ peers.length = 0;+ peers.push(...next);+};++// An obviously-fake peer record; `syncCategories.universe` mirrors what the+// push path checks for a `universe` record kind.+const universePeer = (overrides = {}) => ({+ instanceId: PEER_A,+ name: 'Example Peer',+ enabled: true,+ syncEnabled: true,+ directions: ['outbound', 'inbound'],+ syncCategories: { universe: true },+ ...overrides,+});++describe('peerPullAuthorization', () => {+ beforeEach(() => {+ settings = {};+ setPeers();+ __resetPullWarnThrottleForTests();+ vi.restoreAllMocks();+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ });++ describe('readCallerInstanceId', () => {+ it('collapses absent, blank, and sentinel ids to null', () => {+ expect(readCallerInstanceId({ headers: {} })).toBeNull();+ expect(readCallerInstanceId({ headers: { [PEER_INSTANCE_ID_HEADER]: ' ' } })).toBeNull();+ expect(readCallerInstanceId({ headers: { [PEER_INSTANCE_ID_HEADER]: 'unknown' } })).toBeNull();+ expect(readCallerInstanceId({ headers: { [PEER_INSTANCE_ID_HEADER]: ` ${PEER_A} ` } })).toBe(PEER_A);+ });+ });++ describe('decidePeerPull', () => {+ it('allows a peer whose sharing config covers the record kind', async () => {+ setPeers(universePeer());+ const decision = await decidePeerPull({ callerId: PEER_A, recordKind: 'universe' });+ expect(decision.allowed).toBe(true);+ expect(decision.reason).toBeNull();+ });++ it('denies an unidentified caller and an unregistered instance id', async () => {+ expect((await decidePeerPull({ callerId: null, recordKind: 'universe' })).reason).toBe(PULL_DENY_UNIDENTIFIED);+ expect((await decidePeerPull({ callerId: 'not-registered', recordKind: 'universe' })).reason).toBe(PULL_DENY_UNKNOWN_PEER);+ });++ it('denies a peer with sync globally disabled or set to inbound-only', async () => {+ setPeers(universePeer({ syncEnabled: false }));+ expect((await decidePeerPull({ callerId: PEER_A, recordKind: 'universe' })).reason).toBe(PULL_DENY_OUTBOUND);+ setPeers(universePeer({ directions: ['inbound'] }));+ expect((await decidePeerPull({ callerId: PEER_A, recordKind: 'universe' })).reason).toBe(PULL_DENY_OUTBOUND);+ setPeers(universePeer({ enabled: false }));+ expect((await decidePeerPull({ callerId: PEER_A, recordKind: 'universe' })).reason).toBe(PULL_DENY_OUTBOUND);+ });++ it('denies a record kind whose category the peer has turned off', async () => {+ setPeers(universePeer());+ const decision = await decidePeerPull({ callerId: PEER_A, recordKind: 'series' });+ expect(decision.reason).toBe(PULL_DENY_CATEGORY);+ });++ it('allows a full-sync peer every subscribable kind', async () => {+ setPeers(universePeer({ syncCategories: {}, fullSync: true }));+ expect((await decidePeerPull({ callerId: PEER_A, recordKind: 'series' })).allowed).toBe(true);+ });++ it('gates a kind-less manifest pull on outbound only, not on categories', async () => {+ setPeers(universePeer({ syncCategories: {} }));+ expect((await decidePeerPull({ callerId: PEER_A })).allowed).toBe(true);+ setPeers(universePeer({ syncCategories: {}, syncEnabled: false }));+ expect((await decidePeerPull({ callerId: PEER_A })).allowed).toBe(false);+ });++ // The acceptance criterion: push and pull decisions come from the SAME+ // predicates, so they can never diverge for a given peer/kind pair.+ it('agrees with the push-path gate for every peer/kind combination', async () => {+ const candidates = [+ universePeer(),+ universePeer({ syncEnabled: false }),+ universePeer({ enabled: false }),+ universePeer({ directions: ['inbound'] }),+ universePeer({ syncCategories: { pipeline: true } }),+ universePeer({ syncCategories: {}, fullSync: true }),+ ];+ for (const peer of candidates) {+ for (const kind of ['universe', 'series', 'mediaCollection']) {+ setPeers(peer);+ const pull = await decidePeerPull({ callerId: PEER_A, recordKind: kind });+ // Exactly the two checks pushRecord runs before sending (peerSyncPush.js).+ const push = peerAllowsOutbound(peer) && peerHasCategory(peer, kind);+ expect(pull.allowed).toBe(push);+ }+ }+ });+ });++ describe('authorizePeerPull compatibility', () => {+ it('serves an unidentified pull when strict mode is off (older peer keeps syncing)', async () => {+ const decision = await authorizePeerPull(req(null), { recordKind: 'universe', route: 'record universe' });+ expect(decision.allowed).toBe(false);+ expect(console.warn).toHaveBeenCalledTimes(1);+ });++ it('warns at most once per caller per boot', async () => {+ await authorizePeerPull(req(null), { recordKind: 'universe' });+ await authorizePeerPull(req(null), { recordKind: 'universe' });+ await authorizePeerPull(req(null), { recordKind: 'series' });+ expect(console.warn).toHaveBeenCalledTimes(1);++ setPeers(universePeer());+ await authorizePeerPull(req(PEER_A), { recordKind: 'series' });+ await authorizePeerPull(req(PEER_A), { recordKind: 'series' });+ expect(console.warn).toHaveBeenCalledTimes(2);+ });++ it('does not warn when the pull is allowed', async () => {+ setPeers(universePeer());+ const decision = await authorizePeerPull(req(PEER_A), { recordKind: 'universe' });+ expect(decision.allowed).toBe(true);+ expect(console.warn).not.toHaveBeenCalled();+ });++ it('403s a denied pull once strictPullAuthorization is on', async () => {+ settings = { federation: { strictPullAuthorization: true } };+ setPeers(universePeer());+ await expect(authorizePeerPull(req(PEER_A), { recordKind: 'series' }))+ .rejects.toMatchObject({ status: 403, code: 'PEER_PULL_FORBIDDEN' });+ await expect(authorizePeerPull(req(null), { recordKind: 'universe' }))+ .rejects.toMatchObject({ status: 403 });+ // Strict mode rejects instead of logging the compatibility warning.+ expect(console.warn).not.toHaveBeenCalled();+ });++ it('still allows an authorized pull under strict mode', async () => {+ settings = { federation: { strictPullAuthorization: true } };+ setPeers(universePeer());+ expect((await authorizePeerPull(req(PEER_A), { recordKind: 'universe' })).allowed).toBe(true);+ });++ it('treats an unreadable settings file as strict-off (warn, do not break sync)', async () => {+ settings = null;+ await expect(authorizePeerPull(req(null), { recordKind: 'universe' })).resolves.toBeDefined();+ });+ });+});