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: extend the peer-sync pull gate to GET /manifest and the CoS agent-archive bytes, and never send a duplicate injected header (#3659)

[._.]/ Adam Eivydf862b575827
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 72d7c74f95..a3c832c40e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -43,4 +43,4 @@
- **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.
+- **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 record/library/CoS-history/CoS-task manifests and the CoS agent-archive bytes 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/server/lib/peerHttpClient.js b/server/lib/peerHttpClient.js
index f94c998632..2acf919546 100644
--- a/server/lib/peerHttpClient.js
+++ b/server/lib/peerHttpClient.js
@@ -64,17 +64,28 @@ export function __resetSelfInstanceIdForTests() {
* keep working.
*/
export async function peerFetch(url, options = {}, peer = null) {
+ const callerHeaders = options.headers || {};
const finalOptions = {
...options,
headers: {
- ...await selfInstanceHeader(),
- ...(peer ? peerAuthHeaders(peer) : {}),
- ...(options.headers || {}),
+ ...dropOverridden({ ...await selfInstanceHeader(), ...(peer ? peerAuthHeaders(peer) : {}) }, callerHeaders),
+ ...callerHeaders,
},
};
return url.startsWith('https://') ? httpsFetch(url, finalOptions) : fetch(url, finalOptions);
}
+/**
+ * Drop injected headers the caller already set under ANY casing. Object spread
+ * is case-sensitive, so `{ 'X-PortOS-Instance-Id': a, 'x-portos-instance-id': b }`
+ * survives as two keys and fetch sends the value twice — which Express then
+ * hands the receiver as `"a, b"`, matching no registered peer.
+ */
+function dropOverridden(injected, callerHeaders) {
+ const callerKeys = new Set(Object.keys(callerHeaders).map((k) => k.toLowerCase()));
+ return Object.fromEntries(Object.entries(injected).filter(([k]) => !callerKeys.has(k.toLowerCase())));
+}
+
/**
* Socket.IO client options for a peer connection, with the peer's Basic-auth
* credential injected as `extraHeaders` so the handshake survives a 401-gating
diff --git a/server/lib/peerHttpClient.test.js b/server/lib/peerHttpClient.test.js
index 25b0817c3d..d2661bdaf1 100644
--- a/server/lib/peerHttpClient.test.js
+++ b/server/lib/peerHttpClient.test.js
@@ -64,6 +64,19 @@ describe('peerHttpClient', () => {
expect(calls[0].options.headers['X-PortOS-Instance-Id']).toBe('explicit');
});
+ it('does not send the header twice when the caller overrides it in another casing', async () => {
+ await peerFetch('http://peer.example/x', { headers: { 'x-portos-instance-id': 'explicit' } });
+ const sent = Object.keys(calls[0].options.headers).filter((k) => k.toLowerCase() === 'x-portos-instance-id');
+ expect(sent).toEqual(['x-portos-instance-id']);
+ expect(calls[0].options.headers['x-portos-instance-id']).toBe('explicit');
+ });
+
+ it('does not send the Basic credential twice when the caller sets its own', async () => {
+ await peerFetch('http://peer.example/x', { headers: { authorization: 'Bearer t' } }, { auth: { password: 'pw' } });
+ const sent = Object.keys(calls[0].options.headers).filter((k) => k.toLowerCase() === 'authorization');
+ expect(sent).toEqual(['authorization']);
+ });
+
it('omits the header entirely when this install has no identity yet', async () => {
selfInstanceId = 'unknown';
__resetSelfInstanceIdForTests();
diff --git a/server/routes/peerSync.js b/server/routes/peerSync.js
index 911dece6ee..2a5d9c01a5 100644
--- a/server/routes/peerSync.js
+++ b/server/routes/peerSync.js
@@ -153,6 +153,9 @@ router.get('/manifest', asyncHandler(async (req, res) => {
if (!validKind(kind)) {
throw new ServerError('invalid kind', { status: 400, code: 'VALIDATION_ERROR' });
}
+ // Same per-peer gate as /record — a manifest for a category the peer isn't
+ // allowed to sync still leaks every record id + asset hash for that kind.
+ await authorizePeerPull(req, { recordKind: kind, route: `manifest ${kind}` });
res.json({ records: await buildLocalManifest(kind) });
}));
@@ -214,6 +217,10 @@ router.get('/cos-agent-archive', asyncHandler(async (req, res) => {
if (!COS_ARCHIVE_DATE_RE.test(date) || !COS_AGENT_ID_RE.test(agentId) || !COS_ARCHIVE_FILES.includes(file)) {
throw new ServerError('invalid archive path', { status: 400, code: 'VALIDATION_ERROR' });
}
+ // Gate the bytes the same way /cos-history-manifest gates the listing —
+ // otherwise a peer denied the manifest could still fetch archives by guessing
+ // (or remembering) a path.
+ await authorizePeerPull(req, { route: 'cos-agent-archive' });
const abs = join(PATHS.cos, 'agents', date, agentId, file);
if (!existsSync(abs)) {
throw new ServerError('archive not found', { status: 404, code: 'NOT_FOUND' });
diff --git a/server/routes/peerSync.test.js b/server/routes/peerSync.test.js
index 2a031d4ed0..2c19d764ca 100644
--- a/server/routes/peerSync.test.js
+++ b/server/routes/peerSync.test.js
@@ -815,6 +815,25 @@ describe('peer-sync routes', () => {
expect(svc[fn]).not.toHaveBeenCalled();
});
+ it('gates GET /manifest on the requested record kind', 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/manifest?kind=series');
+ expect(res.status).toBe(403);
+ expect(integritySvc.buildLocalManifest).not.toHaveBeenCalled();
+ expect(authorizePeerPull).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ recordKind: 'series' }));
+ });
+
+ it('gates the CoS agent archive bytes, not just the manifest listing', 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/cos-agent-archive?date=2026-01-01&agentId=agent-1&file=metadata.json');
+ expect(res.status).toBe(403);
+ });
+
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');
diff --git a/server/services/sharing/peerPullAuthorization.js b/server/services/sharing/peerPullAuthorization.js
index 7bd7b41aca..9b5461be80 100644
--- a/server/services/sharing/peerPullAuthorization.js
+++ b/server/services/sharing/peerPullAuthorization.js
@@ -58,8 +58,13 @@ const WARNED_CALLERS_MAX = 500;
* "unidentified" shape instead of three.
*/
export function readCallerInstanceId(req) {
- const raw = req?.headers?.[PEER_INSTANCE_ID_HEADER];
- const value = typeof raw === 'string' ? raw.trim() : '';
+ const header = req?.headers?.[PEER_INSTANCE_ID_HEADER];
+ // A header sent twice (a proxy re-adding it, a caller overriding under a
+ // different casing) reaches Express as an array or a `"a, b"` string. Read
+ // the first value rather than collapsing to "unidentified" — the id is
+ // self-asserted either way, so nothing is gained by being strict here.
+ const raw = Array.isArray(header) ? header[0] : header;
+ const value = typeof raw === 'string' ? raw.split(',')[0].trim() : '';
if (!value || value === UNKNOWN_INSTANCE_ID) return null;
return value;
}
diff --git a/server/services/sharing/peerPullAuthorization.test.js b/server/services/sharing/peerPullAuthorization.test.js
index fa853d5772..f1afc5835a 100644
--- a/server/services/sharing/peerPullAuthorization.test.js
+++ b/server/services/sharing/peerPullAuthorization.test.js
@@ -65,6 +65,11 @@ describe('peerPullAuthorization', () => {
expect(readCallerInstanceId({ headers: { [PEER_INSTANCE_ID_HEADER]: 'unknown' } })).toBeNull();
expect(readCallerInstanceId({ headers: { [PEER_INSTANCE_ID_HEADER]: ` ${PEER_A} ` } })).toBe(PEER_A);
});
+
+ it('reads the first value when the header arrived twice', () => {
+ expect(readCallerInstanceId({ headers: { [PEER_INSTANCE_ID_HEADER]: [PEER_A, 'other'] } })).toBe(PEER_A);
+ expect(readCallerInstanceId({ headers: { [PEER_INSTANCE_ID_HEADER]: `${PEER_A}, other` } })).toBe(PEER_A);
+ });
});
describe('decidePeerPull', () => {