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: cap streamed peer response bodies so a peer cannot exhaust server memory (#8404)
[._.]/ Adam Eivyd7caa11acbfa
diff --git a/server/lib/README.md b/server/lib/README.mdindex 288b7a586c..53dd87c73b 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -437,7 +437,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `xPostMedia.js` | Pure x.com/twitter.com post helpers: `parseXPostUrl(input)` (post URL → `{ statusId, canonicalUrl }`, host-gated) + `buildSyndicationUrl`/`syndicationToken` (Twitter's public unauthenticated tweet-syndication endpoint) + `extractXPostMedia(json)` (→ `{ images, video }`). Feeds the mood-board X post importer. || `requestAbort.js` | `abortSignalFromResponse(res)` — AbortSignal that fires only when an Express client disconnects *before the response finishes* (keyed off `res` close + `writableEnded`). Plus `anyAbortSignal(signals)` — combine several signals into one (native `AbortSignal.any` with a Node-18 fallback). || `readResponseJson.js` | Read a `Response` body as JSON, tolerating a non-JSON/HTML error page (no `Unexpected token <` crash). Object callers need no opts; pass `{ fallback, emptyValue }` for arrays or to surface the raw error text. |-| `peerHttpClient.js` | Federation HTTP/Socket.IO client (TLS validation off — Tailnet is the trust boundary); attaches the peer credential (`derivePeerAuthToken` pair token, legacy Basic until the receiver confirms it); `readPeerBody(response, method, { idleTimeoutMs? })` bounds native response body stalls and reports `PEER_BODY_IDLE_TIMEOUT`. |+| `peerHttpClient.js` | Federation HTTP/Socket.IO client (TLS validation off — Tailnet is the trust boundary); attaches the peer credential (`derivePeerAuthToken` pair token, legacy Basic until the receiver confirms it); `readPeerBody(response, method, { idleTimeoutMs?, maxBytes? })` bounds native response body stalls (`PEER_BODY_IDLE_TIMEOUT`) and streamed size (default `PEER_BODY_DEFAULT_MAX_BYTES` = 256 MiB, rejects with `RESPONSE_TOO_LARGE` like the HTTPS shim). || `peerProbeDiagnostics.js` | Classify federated peer probe failures (`local_refused` / `tunnel_dial` / `probe_http` / timeout / auth / DNS) so Instances UI and logs can tell a dead local forward from a tunnel dial miss from a PortOS health-details failure; messages stay redacted (no full `tc…` capabilities). || `peerSelfHost.js` | Tailscale-issued hostname this PortOS sends in federation. || `peerUrl.js` | Build the base URL for a peer. |diff --git a/server/lib/peerHttpClient.js b/server/lib/peerHttpClient.jsindex 1eb986f538..4c9bcf486b 100644--- a/server/lib/peerHttpClient.js+++ b/server/lib/peerHttpClient.js@@ -1,7 +1,7 @@// Federation HTTP/Socket.IO client — TLS validation off (Tailnet is the trust boundary).import https from 'node:https';import { createHmac } from 'node:crypto';-import { insecureFetch } from './httpClient.js';+import { insecureFetch, RESPONSE_TOO_LARGE } from './httpClient.js';const peerHttpsAgent = new https.Agent({ rejectUnauthorized: false, keepAlive: true });const httpsFetch = insecureFetch(peerHttpsAgent);@@ -127,17 +127,26 @@ export async function peerFetch(url, options = {}, peer = null) {}export const PEER_BODY_IDLE_TIMEOUT = 'PEER_BODY_IDLE_TIMEOUT';+// Well above any legitimate snapshot; a body past it is a broken or hostile peer.+export const PEER_BODY_DEFAULT_MAX_BYTES = 256 * 1024 * 1024;/**- * Consume a peer response with a deadline between received body chunks. Native- * fetch resolves at headers; HTTPS already buffers under the caller's request- * timeout, so its response methods keep their existing behavior.+ * Consume a peer response with a deadline between received body chunks and a+ * running byte cap. Native fetch resolves at headers and ignores `maxBytes`, so+ * a chunked body with no Content-Length is only bounded here; overflow cancels+ * the reader and rejects with the HTTPS shim's `RESPONSE_TOO_LARGE` code. HTTPS+ * already buffers under the caller's request timeout and `maxBytes`, so its+ * response methods keep their existing behavior.*/-export async function readPeerBody(response, method, { idleTimeoutMs = 60000 } = {}) {+export async function readPeerBody(response, method, {+ idleTimeoutMs = 60000,+ maxBytes = PEER_BODY_DEFAULT_MAX_BYTES,+} = {}) {if (!response.body) return response[method]();const reader = response.body.getReader();const chunks = [];+ let total = 0;let timer;let rejectIdle;const idle = new Promise((_, reject) => { rejectIdle = reject; });@@ -155,6 +164,13 @@ export async function readPeerBody(response, method, { idleTimeoutMs = 60000 } =const { done, value } = await reader.read();if (done) break;if (value.byteLength) {+ total += value.byteLength;+ if (total > maxBytes) {+ throw Object.assign(+ new Error(`Peer response body exceeded ${maxBytes} bytes`),+ { code: RESPONSE_TOO_LARGE }+ );+ }chunks.push(value);resetIdle();}@@ -165,7 +181,7 @@ export async function readPeerBody(response, method, { idleTimeoutMs = 60000 } =return new Response(Buffer.concat(chunks))[method]();} finally {clearTimeout(timer);- // Cancel a stalled native fetch to release its socket; do not let transport+ // Cancel a stalled or oversized native fetch to release its socket; do not let transport// cleanup hold the sync lock after the deadline has already fired.reader.cancel().catch(() => {});reader.releaseLock();diff --git a/server/lib/peerHttpClient.test.js b/server/lib/peerHttpClient.test.jsindex 5f5c804827..a3e61daabd 100644--- a/server/lib/peerHttpClient.test.js+++ b/server/lib/peerHttpClient.test.js@@ -384,6 +384,21 @@ describe('peerHttpClient', () => {expect(vi.getTimerCount()).toBe(0);});+ it('rejects a streamed body past maxBytes and cancels its reader', async () => {+ let pulled = 0;+ const cancel = vi.fn();+ const response = new Response(new ReadableStream({+ pull(controller) { pulled++; controller.enqueue(new Uint8Array(4)); },+ cancel,+ }));+ await expect(readPeerBody(response, 'arrayBuffer', { maxBytes: 10 }))+ .rejects.toMatchObject({ code: RESPONSE_TOO_LARGE });+ expect(cancel).toHaveBeenCalledOnce();+ expect(pulled).toBeLessThanOrEqual(4);+ // A body exactly at the cap still resolves unchanged.+ expect(await readPeerBody(new Response('{"a":12}'), 'json', { maxBytes: 8 })).toEqual({ a: 12 });+ });+it('preserves buffered HTTPS binary and bad-JSON response behavior', async () => {const bytes = Buffer.from([0, 255, 128]);const response = { arrayBuffer: async () => bytes, json: async () => JSON.parse('{') };diff --git a/server/services/sharing/cosHistorySync.test.js b/server/services/sharing/cosHistorySync.test.jsindex 9142344904..847c22b8bb 100644--- a/server/services/sharing/cosHistorySync.test.js+++ b/server/services/sharing/cosHistorySync.test.js@@ -34,7 +34,10 @@ vi.mock('../mediaCollections.js', async () => ({findCollectionBySeriesId: vi.fn(), mergeMediaCollectionsFromSync: vi.fn(),}));vi.mock('../mediaAssetIndex/index.js', () => ({ reconcileMediaAssets: vi.fn().mockResolvedValue(undefined) }));-vi.mock('../../lib/peerHttpClient.js', async () => ({ peerFetch: vi.fn() }));+vi.mock('../../lib/peerHttpClient.js', async (importOriginal) => ({+ peerFetch: vi.fn(),+ readPeerBody: (await importOriginal()).readPeerBody,+}));// cosAgentIndex is dynamic-imported by the receiver to merge the agentId→date index.// Spy it so the merge is observable AND can't write the real data/cos index.vi.mock('../cosAgentIndex.js', () => ({ addAgentArchivesToIndex: vi.fn().mockResolvedValue(0) }));@@ -48,6 +51,12 @@ import { getPeers } from '../instances.js';import { peerFetch } from '../../lib/peerHttpClient.js';import { addAgentArchivesToIndex } from '../cosAgentIndex.js';+// A chunked body with no Content-Length that never ends; only the streaming+// cap in readPeerBody can stop it.+const endlessChunkedRes = () => {+ const chunk = new Uint8Array(8 * 1024 * 1024);+ return new Response(new ReadableStream({ pull(controller) { controller.enqueue(chunk); } }));+};const sha = (s) => createHash('sha256').update(s).digest('hex');function byteRes(content) {@@ -174,6 +183,12 @@ describe('syncCosHistoryFromPeer', () => {expect(peerFetch).not.toHaveBeenCalled();});+ it('skips a chunked manifest that streams past the byte cap', async () => {+ vi.mocked(peerFetch).mockResolvedValue(endlessChunkedRes());+ expect(await syncCosHistoryFromPeer(PEER)).toEqual({ pulled: 0, skipped: 'too-large' });+ expect(peerFetch).toHaveBeenCalledOnce();+ });+it('gently skips a sender whose manifest schema is ahead', async () => {vi.mocked(peerFetch).mockResolvedValue(manifestRes({ schemaVersion: 999, manifestHash: sha('x'), entries: [] }));const r = await syncCosHistoryFromPeer(PEER);diff --git a/server/services/sharing/cosTasksSync.test.js b/server/services/sharing/cosTasksSync.test.jsindex 36d5c8c70a..7c4b384474 100644--- a/server/services/sharing/cosTasksSync.test.js+++ b/server/services/sharing/cosTasksSync.test.js@@ -29,7 +29,10 @@ vi.mock('../mediaCollections.js', async () => ({findCollectionBySeriesId: vi.fn(), mergeMediaCollectionsFromSync: vi.fn(),}));vi.mock('../mediaAssetIndex/index.js', () => ({ reconcileMediaAssets: vi.fn().mockResolvedValue(undefined) }));-vi.mock('../../lib/peerHttpClient.js', async () => ({ peerFetch: vi.fn() }));+vi.mock('../../lib/peerHttpClient.js', async (importOriginal) => ({+ peerFetch: vi.fn(),+ readPeerBody: (await importOriginal()).readPeerBody,+}));// cosTaskStore is dynamic-imported by both the sender (getUserTasks/getCosTasks)// and the receiver (mergePeerTasks). Spy it so the wire build + merge are// observable AND can't read/write the real task files.@@ -46,6 +49,12 @@ import {import { PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';import { getPeers } from '../instances.js';import { peerFetch } from '../../lib/peerHttpClient.js';+// A chunked body with no Content-Length that never ends; only the streaming+// cap in readPeerBody can stop it.+const endlessChunkedRes = () => {+ const chunk = new Uint8Array(8 * 1024 * 1024);+ return new Response(new ReadableStream({ pull(controller) { controller.enqueue(chunk); } }));+};import { getUserTasks, getCosTasks, mergePeerTasks } from '../cosTaskStore.js';const sha = (s) => createHash('sha256').update(s).digest('hex');@@ -144,6 +153,12 @@ describe('syncCosTasksFromPeer', () => {expect(mergePeerTasks).not.toHaveBeenCalled();});+ it('skips a chunked payload that streams past the byte cap', async () => {+ vi.mocked(peerFetch).mockResolvedValue(endlessChunkedRes());+ expect(await syncCosTasksFromPeer(PEER)).toEqual({ merged: 0, skipped: 'too-large' });+ expect(mergePeerTasks).not.toHaveBeenCalled();+ });+it('skips a malformed payload (failed validation)', async () => {vi.mocked(peerFetch).mockResolvedValue(payloadRes({ schemaVersion: 1, listHash: 'not-hex', tasks: [] }));const r = await syncCosTasksFromPeer(PEER);diff --git a/server/services/sharing/peerCosSync.js b/server/services/sharing/peerCosSync.jsindex e876340af1..6fb837766a 100644--- a/server/services/sharing/peerCosSync.js+++ b/server/services/sharing/peerCosSync.js@@ -17,7 +17,8 @@ import { PATHS, atomicWrite, ensureDir, sha256File, tryReadFile, safeJSONParse }import { isPlainObject } from '../../lib/objects.js';import { logFailureWithStack } from '../../lib/failureLogging.js';import { peerBaseUrl } from '../../lib/peerUrl.js';-import { peerFetch } from '../../lib/peerHttpClient.js';+import { peerFetch, readPeerBody } from '../../lib/peerHttpClient.js';+import { RESPONSE_TOO_LARGE } from '../../lib/httpClient.js';import { withAbortTimeout } from '../../lib/abortTimeout.js';import { PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';import { getPeers } from '../instances.js';@@ -75,6 +76,8 @@ function cosAgentsDir() {const COS_HISTORY_MANIFEST_CAP = 150_000;// The manifest JSON itself (not the archive bytes — those ride the per-file cap).const COS_HISTORY_MANIFEST_MAX_BYTES = 32 * 1024 * 1024;+// readPeerBody outcome for a body that streamed past its cap, distinct from invalid JSON.+const TOO_LARGE = Symbol('too-large');// Per-archive-file hard cap. Agent transcripts (output.txt) can be large; 64MB is// generous while still bounding a hostile/runaway peer. An oversized file is// logged + skipped (it stays "missing" and is retried, never silently dropped).@@ -253,7 +256,12 @@ export async function syncCosHistoryFromPeer(peer) {console.error(`⚠️ peerSync: cos-history manifest from ${peer.name || peer.instanceId} too large (${declaredLen} > ${COS_HISTORY_MANIFEST_MAX_BYTES}) — skipping`);return { pulled: 0, skipped: 'too-large' };}- const body = await res.json().catch(() => null);+ const body = await readPeerBody(res, 'json', { maxBytes: COS_HISTORY_MANIFEST_MAX_BYTES })+ .catch((err) => (err?.code === RESPONSE_TOO_LARGE ? TOO_LARGE : null));+ if (body === TOO_LARGE) {+ console.error(`⚠️ peerSync: cos-history manifest from ${peer.name || peer.instanceId} streamed past ${COS_HISTORY_MANIFEST_MAX_BYTES} bytes — skipping`);+ return { pulled: 0, skipped: 'too-large' };+ }const parsed = peerCosHistoryManifestSchema.safeParse(body);if (!parsed.success) {console.error(`⚠️ peerSync: cos-history manifest from ${peer.name || peer.instanceId} failed validation — skipping`);@@ -472,7 +480,12 @@ export async function syncCosTasksFromPeer(peer) {console.error(`⚠️ peerSync: cos-tasks payload from ${peer.name || peer.instanceId} too large (${declaredLen} > ${COS_TASKS_MAX_BYTES}) — skipping`);return { merged: 0, skipped: 'too-large' };}- const body = await res.json().catch(() => null);+ const body = await readPeerBody(res, 'json', { maxBytes: COS_TASKS_MAX_BYTES })+ .catch((err) => (err?.code === RESPONSE_TOO_LARGE ? TOO_LARGE : null));+ if (body === TOO_LARGE) {+ console.error(`⚠️ peerSync: cos-tasks payload from ${peer.name || peer.instanceId} streamed past ${COS_TASKS_MAX_BYTES} bytes — skipping`);+ return { merged: 0, skipped: 'too-large' };+ }const parsed = peerCosTasksSchema.safeParse(body);if (!parsed.success) {console.error(`⚠️ peerSync: cos-tasks payload from ${peer.name || peer.instanceId} failed validation — skipping`);diff --git a/server/services/sharing/peerMediaLibrarySync.js b/server/services/sharing/peerMediaLibrarySync.jsindex b09190c907..953f99a637 100644--- a/server/services/sharing/peerMediaLibrarySync.js+++ b/server/services/sharing/peerMediaLibrarySync.js@@ -16,7 +16,8 @@ import { PATHS } from '../../lib/fileUtils.js';import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';import { isPlainObject } from '../../lib/objects.js';import { peerBaseUrl } from '../../lib/peerUrl.js';-import { peerFetch } from '../../lib/peerHttpClient.js';+import { peerFetch, readPeerBody } from '../../lib/peerHttpClient.js';+import { RESPONSE_TOO_LARGE } from '../../lib/httpClient.js';import { withAbortTimeout } from '../../lib/abortTimeout.js';import { sanitizeAssetFilename } from './buckets.js';import { PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';@@ -259,15 +260,23 @@ export async function syncMediaLibraryFromPeer(peer) {// only streams-caps the HTTPS (host) shim; for a plain-HTTP (address) peer it// delegates to native fetch, which ignores `maxBytes`, so `res.json()` would// otherwise buffer an unbounded body. Express on the sender sets Content-Length- // for the JSON response, so a content-length check here is the real cap (mirrors- // the record-pull path's RECORD_PAYLOAD_MAX_BYTES guard). A peer that omits it- // is a trusted tailnet peer per the threat model.+ // for the JSON response, so the declared-length check is a fast path; a chunked+ // body that declares none is capped while streaming by readPeerBody below.const declaredLen = Number(res.headers?.get?.('content-length'));if (Number.isFinite(declaredLen) && declaredLen > MEDIA_LIBRARY_MANIFEST_MAX_BYTES) {console.log(`⚠️ peerSync: media-library manifest from ${peer.name || peer.instanceId} too large (${declaredLen} > ${MEDIA_LIBRARY_MANIFEST_MAX_BYTES}) — skipping`);return { pulled: 0, skipped: 'too-large' };}- const body = await res.json().catch(() => null);+ let tooLarge = false;+ const body = await readPeerBody(res, 'json', { maxBytes: MEDIA_LIBRARY_MANIFEST_MAX_BYTES })+ .catch((err) => {+ tooLarge = err?.code === RESPONSE_TOO_LARGE;+ return null;+ });+ if (tooLarge) {+ console.log(`⚠️ peerSync: media-library manifest from ${peer.name || peer.instanceId} streamed past ${MEDIA_LIBRARY_MANIFEST_MAX_BYTES} bytes — skipping`);+ return { pulled: 0, skipped: 'too-large' };+ }const parsed = peerLibraryManifestSchema.safeParse(body);if (!parsed.success) {console.log(`⚠️ peerSync: media-library manifest from ${peer.name || peer.instanceId} failed validation — skipping`);diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 6b8965d998..32c1f14e14 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -22,7 +22,7 @@* back over the sender's `/data/{images,image-refs,videos}/` static mounts.*/import { peerBaseUrl } from '../../lib/peerUrl.js';-import { peerFetch } from '../../lib/peerHttpClient.js';+import { peerFetch, readPeerBody } from '../../lib/peerHttpClient.js';import { RESPONSE_TOO_LARGE } from '../../lib/httpClient.js';import { withAbortTimeout } from '../../lib/abortTimeout.js';import { logFailureWithStack } from '../../lib/failureLogging.js';@@ -685,15 +685,24 @@ export async function pullRecordFromPeer(peerId, recordKind, recordId) {if (!res) return { pulled: false, reason: 'peer-unreachable' };if (res.status === 404) return { pulled: false, reason: 'not-on-peer' };if (!res.ok) return { pulled: false, reason: `http-${res.status}` };- // Plain-HTTP path: Node's fetch ignores maxBytes, but Express sets- // Content-Length on JSON — reject an oversized declared body before buffering.+ // Plain-HTTP path: Node's fetch ignores maxBytes. Express sets Content-Length+ // on JSON, so reject an oversized declared body before buffering (fast path);+ // readPeerBody still caps a chunked body that declares no length.const declaredLen = Number(res.headers?.get?.('content-length'));if (Number.isFinite(declaredLen) && declaredLen > RECORD_PAYLOAD_MAX_BYTES) {console.error(`⚠️ peerSync: pull-record ${recordKind}/${recordId} declared ${declaredLen} bytes > cap`);return { pulled: false, reason: 'payload-too-large' };}- const body = await res.json().catch(() => null);+ const body = await readPeerBody(res, 'json', { maxBytes: RECORD_PAYLOAD_MAX_BYTES })+ .catch((err) => {+ if (err?.code === RESPONSE_TOO_LARGE) tooLarge = true;+ return null;+ });+ if (tooLarge) {+ console.error(`⚠️ peerSync: pull-record ${recordKind}/${recordId} streamed past the payload cap`);+ return { pulled: false, reason: 'payload-too-large' };+ }// The peer response is untrusted — validate with the SAME schema the inbound// /push route uses before handing it to applyIncomingPush.const parsed = peerSyncPushSchema.safeParse(body);diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 6cd5bf4545..3afa33e589 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -211,8 +211,9 @@ vi.mock('../decks.js', () => ({pruneTombstonedDecks: vi.fn().mockResolvedValue({ pruned: 0, ids: [] }),}));-vi.mock('../../lib/peerHttpClient.js', async () => ({+vi.mock('../../lib/peerHttpClient.js', async (importOriginal) => ({peerFetch: vi.fn(),+ readPeerBody: (await importOriginal()).readPeerBody,peerSocketOptions: {},}));@@ -318,6 +319,13 @@ import { applyRemoteChanges as applyCatalogRemoteChanges } from '../catalogSync.import { listCursors, __drainForTests as __drainCursors } from './peerTombstoneCursors.js';import { contentHashForRecord, __resetBaseHashCacheForTests } from '../../lib/conflictJournal.js';+// A chunked body with no Content-Length that never ends; only the streaming+// cap in readPeerBody can stop it.+const endlessChunkedRes = () => {+ const chunk = new Uint8Array(8 * 1024 * 1024);+ return new Response(new ReadableStream({ pull(controller) { controller.enqueue(chunk); } }));+};+let originalDataPath;let originalImagesPath;let originalImageRefsPath;@@ -1570,6 +1578,12 @@ describe('peerSync', () => {.toEqual({ pulled: false, reason: 'payload-too-large' });});+ it('payload-too-large when a chunked body with no Content-Length streams past the cap', async () => {+ vi.mocked(peerFetch).mockResolvedValue(endlessChunkedRes());+ expect(await pullRecordFromPeer('peer-a', 'universe', 'u-pull'))+ .toEqual({ pulled: false, reason: 'payload-too-large' });+ });+it('payload-too-large (not peer-unreachable) when the HTTPS shim trips the maxBytes cap', async () => {// The shim rejects with a RESPONSE_TOO_LARGE-coded Error — must map to// payload-too-large, consistent with the Content-Length path, not be@@ -5123,6 +5137,12 @@ describe('media-library federation (#1566)', () => {expect(res.skipped).toBe('too-large');});+ it('skips a chunked manifest with no Content-Length that streams past the cap', async () => {+ vi.mocked(peerFetch).mockResolvedValue(endlessChunkedRes());+ const res = await syncMediaLibraryFromPeer(mkPeer('fs-chunked'));+ expect(res.skipped).toBe('too-large');+ });+it('forces a re-diff after repeated unchanged ticks so a local file loss self-heals', async () => {const peer = mkPeer('fs-selfheal');vi.mocked(getPeers).mockResolvedValue([peer]);diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex fe48a0b9b2..ba5bf96692 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -15,7 +15,7 @@ import { instanceEvents } from './instanceEvents.js';import { getPeers, peerLogLabel, resolveEffectiveCategories, updatePeer } from './instances.js';import { getInstanceId, UNKNOWN_INSTANCE_ID } from './instanceIdentity.js';import { peerBaseUrl } from '../lib/peerUrl.js';-import { peerFetch, readPeerBody, PEER_BODY_IDLE_TIMEOUT } from '../lib/peerHttpClient.js';+import { peerFetch, readPeerBody, PEER_BODY_IDLE_TIMEOUT, PEER_BODY_DEFAULT_MAX_BYTES } from '../lib/peerHttpClient.js';import * as brainSync from './brainSync.js';import { BRAIN_ENTITY_TYPES } from './brainStorage.js';import * as brainSyncLog from './brainSyncLog.js';@@ -105,7 +105,12 @@ async function withCursors(fn) {// Headers retain their 15s budget. HTTP body reads get a separate 60s idle// deadline so large, progressing downloads may finish; HTTPS is already// buffered within the request budget. Body stalls must reach the cycle's-// failure path instead of becoming a successful no-op.+// failure path instead of becoming a successful no-op. Bodies are also capped+// while streaming (a chunked body carries no Content-Length to pre-check), so an+// endless peer response fails this pull (null) instead of exhausting the heap.+// Avatar images share the per-asset pull cap (ASSET_PULL_MAX_BYTES).+const AVATAR_IMAGE_MAX_BYTES = 100 * 1024 * 1024;+function handlePeerBodyError(error) {if (error.code === PEER_BODY_IDLE_TIMEOUT) throw error;return null;@@ -113,10 +118,12 @@ function handlePeerBodyError(error) {async function fetchPeer(peer, path) {const url = `${peerBaseUrl(peer)}${path}`;- const res = await withAbortTimeout(FETCH_TIMEOUT_MS, (signal) => peerFetch(url, { signal }, peer))+ // maxBytes caps the HTTPS shim; readPeerBody caps a native-fetch stream.+ const maxBytes = PEER_BODY_DEFAULT_MAX_BYTES;+ const res = await withAbortTimeout(FETCH_TIMEOUT_MS, (signal) => peerFetch(url, { signal, maxBytes }, peer)).catch(() => null);if (!res?.ok) return null;- return readPeerBody(res, 'json').catch(handlePeerBodyError);+ return readPeerBody(res, 'json', { maxBytes }).catch(handlePeerBodyError);}/**@@ -136,10 +143,11 @@ async function syncImageFromPeer(peer, avatarPath) {const url = `${peerBaseUrl(peer)}${avatarPath}`;// Use the same request and body-idle budgets as JSON snapshots.- const res = await withAbortTimeout(FETCH_TIMEOUT_MS, (signal) => peerFetch(url, { signal }, peer))+ const res = await withAbortTimeout(FETCH_TIMEOUT_MS, (signal) =>+ peerFetch(url, { signal, maxBytes: AVATAR_IMAGE_MAX_BYTES }, peer)).catch(() => null);if (!res?.ok) return;- await readPeerBody(res, 'arrayBuffer')+ await readPeerBody(res, 'arrayBuffer', { maxBytes: AVATAR_IMAGE_MAX_BYTES }).then(async (bytes) => {await ensureDir(PATHS.images);await writeFileGuarded(localPath, Buffer.from(bytes));diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex 68c40e386d..83d3bb92a3 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -250,6 +250,43 @@ describe('syncOrchestrator', () => {applyRemote.mockResolvedValue({ applied: false, count: 0 });});+ // An endless chunked body (no Content-Length) must fail the pull at the cap+ // rather than grow the heap. One shared chunk keeps the test cheap.+ const endlessBody = () => {+ const chunk = new Uint8Array(16 * 1024 * 1024);+ const state = { pulled: 0, cancel: vi.fn() };+ state.response = new Response(new ReadableStream({+ pull(controller) { state.pulled++; controller.enqueue(chunk); },+ cancel: state.cancel,+ }));+ return state;+ };++ it('drops a snapshot that streams past the body cap without buffering it all', async () => {+ const body = endlessBody();+ mockFetch.mockImplementation(async () => body.response);+ const result = await syncWithPeer({ ...mockPeer, syncCategories: { brain: true, memory: false } });+ expect(result.brain.totalApplied).toBe(0);+ expect(applyBrainChanges).not.toHaveBeenCalled();+ expect(body.cancel).toHaveBeenCalledOnce();+ // 256 MiB default cap / 16 MiB chunks, plus the stream's read-ahead.+ expect(body.pulled).toBeLessThanOrEqual(18);+ });++ it('skips an avatar that streams past the asset cap', async () => {+ const { applyRemote } = await import('./dataSync.js');+ applyRemote.mockResolvedValue({ applied: true, count: 1 });+ const body = endlessBody();+ mockFetch.mockImplementation(async (url) => (url.includes('/data/images/')+ ? body.response+ : { ok: true, json: async () => ({ data: { avatarPath: '/data/images/example.png' }, checksum: 'avatar' }) }));+ await syncWithPeer({ ...mockPeer, syncCategories: { brain: false, memory: false, character: true } });+ expect(writeFileGuarded).not.toHaveBeenCalled();+ expect(body.cancel).toHaveBeenCalledOnce();+ expect(body.pulled).toBeLessThanOrEqual(8);+ applyRemote.mockResolvedValue({ applied: false, count: 0 });+ });+it('does not fetch or store a peer-supplied SVG avatar', async () => {const { applyRemote } = await import('./dataSync.js');applyRemote.mockResolvedValue({ applied: true, count: 1 });