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: code the peer-sync payload-size failure instead of matching "exceed" (#5662)

Adam Eivye7dd889a2b83
diff --git a/server/lib/README.md b/server/lib/README.md
index eb6aa78951..ebc038c272 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -295,7 +295,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
-| `httpClient.js` | Fetch-based HTTP client factory (axios.create replacement). |
+| `httpClient.js` | Fetch-based HTTP client factory (axios.create replacement). `insecureFetch` size-cap rejections carry `code: RESPONSE_TOO_LARGE`. |
| `abortTimeout.js` | `withAbortTimeout(timeoutMs, fn)` — runs `fn(signal)` under an `AbortController` that aborts after `timeoutMs` and always clears the timer on settle. Generic lifecycle helper for callers that need the insecure-agent `peerFetch` (so can't use `fetchWithTimeout`) or one signal across parallel fetches. |
| `fetchWithTimeout.js` | `fetch` wrapper with AbortController timeout. |
| `tailnetPeer.js` | `isTailnetPeer(peer)` — fail-closed security predicate for "is this peer reachable only over the tailnet". Deliberately separate from `instances.js`'s `peerRequiresTailscale()` probe-deferral heuristic so a polling-noise tweak can't widen a privacy boundary; required by the unattended-routing gate in ADR 2026-08-20-federated-visual-prompts. |
diff --git a/server/lib/httpClient.js b/server/lib/httpClient.js
index 6c2631fde5..2744c47429 100644
--- a/server/lib/httpClient.js
+++ b/server/lib/httpClient.js
@@ -5,6 +5,19 @@
import https from 'https';
+/**
+ * `err.code` stamped on every rejection from the `insecureFetch` size cap —
+ * both the declared-Content-Length pre-check and the streamed-body accumulator.
+ * Callers (peer-sync record + asset pulls) discriminate the oversize failure
+ * from a generic transport failure on this code, NOT on the English message
+ * text: rewording a message must never silently reclassify a rejected oversize
+ * payload as `peer-unreachable`. A `code` string (rather than an Error
+ * subclass) matches how the rest of the server discriminates service errors
+ * (see `createServiceErrorMapper` in lib/errorHandler.js) and survives
+ * structured-clone / serialization boundaries.
+ */
+export const RESPONSE_TOO_LARGE = 'RESPONSE_TOO_LARGE';
+
// Wraps https.request as fetch-compatible for self-signed cert support
export function insecureFetch(agent) {
return async (url, { method = 'GET', headers = {}, body, signal, maxBytes } = {}) => {
@@ -39,7 +52,10 @@ export function insecureFetch(agent) {
if (Number.isFinite(declared) && declared > maxBytes) {
cleanup();
req.destroy();
- reject(new Error(`Response declared Content-Length ${declared} exceeds maxBytes ${maxBytes}`));
+ reject(Object.assign(
+ new Error(`Response declared Content-Length ${declared} exceeds maxBytes ${maxBytes}`),
+ { code: RESPONSE_TOO_LARGE }
+ ));
return;
}
}
@@ -61,7 +77,10 @@ export function insecureFetch(agent) {
capTripped = true;
cleanup();
req.destroy();
- reject(new Error(`Response body exceeded maxBytes ${maxBytes} (got ${bytesSoFar})`));
+ reject(Object.assign(
+ new Error(`Response body exceeded maxBytes ${maxBytes} (got ${bytesSoFar})`),
+ { code: RESPONSE_TOO_LARGE }
+ ));
return;
}
}
diff --git a/server/lib/peerHttpClient.test.js b/server/lib/peerHttpClient.test.js
index df06d23a36..ae61085e6a 100644
--- a/server/lib/peerHttpClient.test.js
+++ b/server/lib/peerHttpClient.test.js
@@ -83,6 +83,7 @@ import {
peerAuthHeaders,
__resetSelfInstanceIdForTests,
} from './peerHttpClient.js';
+import { RESPONSE_TOO_LARGE } from './httpClient.js';
describe('peerHttpClient', () => {
it('peerSocketOptions disables cert validation for Socket.IO peer connections', () => {
@@ -202,8 +203,15 @@ describe('peerHttpClient', () => {
res.once('close', responseClosed);
});
+ // Assert the machine-readable code, not just the prose: peer-sync's
+ // record and asset pullers discriminate an oversize response from a dead
+ // peer on err.code, so a reworded message must not silently reclassify
+ // the failure as `peer-unreachable` (#5662).
await expect(peerFetch(`${fixture.url}/stream`, { maxBytes: 8 }))
- .rejects.toThrow('Response body exceeded maxBytes 8');
+ .rejects.toMatchObject({
+ code: RESPONSE_TOO_LARGE,
+ message: expect.stringContaining('Response body exceeded maxBytes 8'),
+ });
await responseClosedPromise;
});
@@ -225,7 +233,10 @@ describe('peerHttpClient', () => {
});
await expect(peerFetch(`${fixture.url}/declared-size`, { maxBytes: 32 }))
- .rejects.toThrow('Response declared Content-Length 1024 exceeds maxBytes 32');
+ .rejects.toMatchObject({
+ code: RESPONSE_TOO_LARGE,
+ message: expect.stringContaining('Response declared Content-Length 1024 exceeds maxBytes 32'),
+ });
await responseClosedPromise;
expect(bodyStarted).toBe(false);
});
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index a70224c185..2dc36de558 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -22,6 +22,7 @@
*/
import { peerBaseUrl } from '../../lib/peerUrl.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
+import { RESPONSE_TOO_LARGE } from '../../lib/httpClient.js';
import { withAbortTimeout } from '../../lib/abortTimeout.js';
import { flushBaseHashes, withBaseHashFlushBatch } from '../../lib/conflictJournal.js';
import { recordEvents, registerSubscriptionAdapter } from './recordEvents.js';
@@ -865,12 +866,13 @@ export async function pullRecordFromPeer(peerId, recordKind, recordId) {
// 'peer-unreachable'.
// maxBytes caps the HTTPS shim's in-memory buffering (see lib/httpClient.js);
// a buggy/misbehaving peer streaming an oversized body is aborted mid-stream
- // rather than buffered whole. The shim rejects with an "exceed" Error.
+ // rather than buffered whole. The shim rejects with a RESPONSE_TOO_LARGE-coded
+ // Error so an oversize body stays distinguishable from a dead peer.
let tooLarge = false;
const res = await withAbortTimeout(PUSH_TIMEOUT_MS, (signal) =>
peerFetch(url, { signal, maxBytes: RECORD_PAYLOAD_MAX_BYTES }, peer))
.catch((err) => {
- if (err?.message?.includes('exceed')) {
+ if (err?.code === RESPONSE_TOO_LARGE) {
tooLarge = true; // HTTPS shim tripped the cap — same condition as the Content-Length check
console.log(`⚠️ peerSync: pull-record ${recordKind}/${recordId} exceeded payload cap — ${err.message}`);
}
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index c1474de674..fb1867f475 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -253,6 +253,7 @@ import { listWorksForSync, listFoldersForSync, listExercisesForSync } from '../w
import { listCommissionFeedbackForSync } from '../creativeCommissions/feedbackStore.js';
import { listCommissionsForSync } from '../creativeCommissions/store.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
+import { RESPONSE_TOO_LARGE } from '../../lib/httpClient.js';
import { reconcileMediaAssets } from '../mediaAssetIndex/index.js';
import { getBackendName } from '../memoryBackend.js';
import { getCatalogBundleForRef } from '../catalogDB.js';
@@ -1408,13 +1409,25 @@ describe('peerSync', () => {
});
it('payload-too-large (not peer-unreachable) when the HTTPS shim trips the maxBytes cap', async () => {
- // The shim rejects with an "exceed" Error — must map to payload-too-large,
- // consistent with the Content-Length path, not be misread as offline.
- vi.mocked(peerFetch).mockRejectedValue(new Error('Response body exceeded maxBytes 16777216 (got 99999999)'));
+ // The shim rejects with a RESPONSE_TOO_LARGE-coded Error — must map to
+ // payload-too-large, consistent with the Content-Length path, not be
+ // misread as offline.
+ vi.mocked(peerFetch).mockRejectedValue(
+ Object.assign(new Error('Response body exceeded maxBytes 16777216 (got 99999999)'), { code: RESPONSE_TOO_LARGE })
+ );
expect(await pullRecordFromPeer('peer-a', 'universe', 'u-pull'))
.toEqual({ pulled: false, reason: 'payload-too-large' });
});
+ it('peer-unreachable for an uncoded transport error that merely says "exceed"', async () => {
+ // Discrimination is on err.code, not on message prose: an unrelated
+ // transport failure whose text happens to contain "exceed" must stay
+ // peer-unreachable rather than being reported as an oversize payload.
+ vi.mocked(peerFetch).mockRejectedValue(new Error('socket hang up: retries exceeded'));
+ expect(await pullRecordFromPeer('peer-a', 'universe', 'u-pull'))
+ .toEqual({ pulled: false, reason: 'peer-unreachable' });
+ });
+
it('invalid-payload when the returned record is not the one we requested', async () => {
// Asked for universe/u-pull but the peer returned a different record id —
// applying it would merge unexpected data under the requested key.
diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.js
index f5c4ce0683..7bfdaafab3 100644
--- a/server/services/sharing/peerSyncAssets.js
+++ b/server/services/sharing/peerSyncAssets.js
@@ -17,6 +17,7 @@ import { isStr } from '../../lib/storyBible.js';
import { isPlainObject } from '../../lib/objects.js';
import { peerBaseUrl } from '../../lib/peerUrl.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
+import { RESPONSE_TOO_LARGE } from '../../lib/httpClient.js';
import { withAbortTimeout } from '../../lib/abortTimeout.js';
import { getOrComputeImageSha256, sidecarGenParamsHash } from '../../lib/assetHash.js';
import { generateThumbnail } from '../../lib/ffmpeg.js';
@@ -810,12 +811,13 @@ export async function pullMissingAssetsFromPeer(senderInstanceId, missingAssets)
*/
export async function fetchCappedAssetBuffer(peer, url, label, maxBytes, { allowEmpty = false } = {}) {
// maxBytes propagates into the HTTPS shim's streaming cap (see
- // server/lib/httpClient.js); the plain-HTTP path falls back to the
- // post-resolve content-length checks below (serve-static always sets it).
+ // server/lib/httpClient.js), which rejects with a RESPONSE_TOO_LARGE-coded
+ // Error; the plain-HTTP path falls back to the post-resolve content-length
+ // checks below (serve-static always sets it).
const res = await withAbortTimeout(ASSET_PULL_TIMEOUT_MS, (signal) =>
peerFetch(url, { signal, maxBytes }, peer))
.catch((err) => {
- if (err?.message?.includes('exceed')) {
+ if (err?.code === RESPONSE_TOO_LARGE) {
console.log(`⚠️ peerSync: ${label} exceeded asset size cap — ${err.message}`);
}
return null;