Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
harden(ssrf): enforce streaming byte ceiling in pinned fetch
nirholas9e6234fc0be6
diff --git a/api/_lib/provider-result-url.js b/api/_lib/provider-result-url.jsindex 0430d000b..57ccff5bc 100644--- a/api/_lib/provider-result-url.js+++ b/api/_lib/provider-result-url.js@@ -170,10 +170,14 @@ export function assertProviderResultUrl(raw) {// don't churn.export async function fetchProviderGlbBuffer(url, { maxBytes = MAX_GLB_BYTES } = {}) {assertProviderResultUrl(url); // host allowlist — throws SsrfBlockedError before any socket+ // Pass maxBytes INTO the fetch so the ceiling is enforced while streaming — the+ // request is torn down the instant the body exceeds it, keeping peak memory+ // bounded. The post-fetch checks below remain as defense-in-depth (they now only+ // ever fire if a future refactor drops the streaming cap).const resp = await fetchSafePublicUrlPinned(url,{ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) },- { allowHttp: false },+ { allowHttp: false, maxBytes },);if (!resp.ok) throw new Error(`fetch glb: ${resp.status}`);const len = Number(resp.headers.get('content-length') || 0);diff --git a/api/_lib/ssrf-guard.js b/api/_lib/ssrf-guard.jsindex 618957188..cff4a9c3e 100644--- a/api/_lib/ssrf-guard.js+++ b/api/_lib/ssrf-guard.js@@ -70,6 +70,20 @@ export class SsrfBlockedError extends Error {}}+// Thrown when a pinned fetch's response exceeds opts.maxBytes — either from the+// advertised content-length or from the actual streamed bytes. Distinct from an+// SSRF block: the host was allowed, the payload was simply too large. Carries the+// observed/limit sizes so callers can log specifics.+export class MaxBytesExceededError extends Error {+ constructor(observed, limit) {+ super(`response exceeds max bytes: ${observed} > ${limit}`);+ this.code = 'max_bytes_exceeded';+ this.status = 413;+ this.observed = observed;+ this.limit = limit;+ }+}+// Resolve a hostname, validate all returned addresses, and return the first// safe address (preferring IPv4 for socket compatibility). Throws SsrfBlockedError// when any address in the answer is blocked — the entire record set must be clean.@@ -138,6 +152,35 @@ export function makePinnedLookup(pinnedIp) {};}+// Buffer a Node response stream into a single Buffer, enforcing an optional byte+// ceiling BOTH up front (advertised content-length) and continuously (actual+// streamed bytes). On breach it destroys the response + request sockets so no+// memory is buffered past the cap, then rejects with MaxBytesExceededError.+// maxBytes === null disables the cap (unbounded, the prior behavior). Extracted+// and exported so the streaming-cap contract is unit-testable without a socket.+export function collectCappedBody(nodeRes, req, maxBytes) {+ return new Promise((resolve, reject) => {+ const abort = (observed) => {+ try { nodeRes.destroy(); } catch { /* already torn down */ }+ try { req?.destroy(); } catch { /* already torn down */ }+ reject(new MaxBytesExceededError(observed, maxBytes));+ };+ if (maxBytes != null) {+ const advertised = Number(nodeRes.headers?.['content-length'] || 0);+ if (advertised > maxBytes) return abort(advertised);+ }+ const chunks = [];+ let received = 0;+ nodeRes.on('data', (c) => {+ received += c.length;+ if (maxBytes != null && received > maxBytes) return abort(received);+ chunks.push(c);+ });+ nodeRes.on('end', () => resolve(Buffer.concat(chunks)));+ nodeRes.on('error', reject);+ });+}+const MAX_REDIRECTS = 5;// Convenience: assert + fetch. Uses the global fetch. Same options as fetch,@@ -180,6 +223,15 @@ export async function fetchSafePublicUrlPinned(input, init = {}, opts = {}) {let url = await assertSafePublicUrl(input, opts);let redirects = 0;+ // Optional streaming byte ceiling. Without it, the response is buffered in+ // full before any caller can measure it — so a hostile or misbehaving host can+ // stream gigabytes and OOM the (memory-capped) instance BEFORE a post-hoc+ // size check runs. When set, we reject on an over-limit content-length header+ // up front AND abort mid-stream the instant cumulative bytes exceed the cap,+ // so peak memory stays bounded regardless of what the host sends or lies about+ // in its headers. Opt-in via opts.maxBytes so existing callers are unchanged.+ const maxBytes = Number.isFinite(opts.maxBytes) ? opts.maxBytes : null;+while (true) {const pinnedIp = await resolveAndValidate(url.hostname);@@ -201,17 +253,15 @@ export async function fetchSafePublicUrlPinned(input, init = {}, opts = {}) {agent,};const req = mod.request(reqOpts, (nodeRes) => {- const chunks = [];- nodeRes.on('data', (c) => chunks.push(c));- nodeRes.on('end', () => {- const body = Buffer.concat(chunks);- // Wrap in a fetch-compatible Response so callers use the same API.- resolve(new Response(body, {- status: nodeRes.statusCode,- headers: nodeRes.headers,- }));- });- nodeRes.on('error', reject);+ collectCappedBody(nodeRes, req, maxBytes)+ .then((body) =>+ // Wrap in a fetch-compatible Response so callers use the same API.+ resolve(new Response(body, {+ status: nodeRes.statusCode,+ headers: nodeRes.headers,+ })),+ )+ .catch(reject);});req.on('error', reject);// Honor an optional AbortSignal (e.g. AbortSignal.timeout) from init so adiff --git a/tests/ssrf-pinned-lookup.test.js b/tests/ssrf-pinned-lookup.test.jsindex fe580ffa5..a2845d901 100644--- a/tests/ssrf-pinned-lookup.test.js+++ b/tests/ssrf-pinned-lookup.test.js@@ -10,7 +10,22 @@// tests pin both lookup contracts so the array shape can never regress.import { describe, it, expect } from 'vitest';-import { makePinnedLookup } from '../api/_lib/ssrf-guard.js';+import { EventEmitter } from 'node:events';+import { makePinnedLookup, collectCappedBody, MaxBytesExceededError } from '../api/_lib/ssrf-guard.js';++// Minimal stand-ins for a Node http.IncomingMessage / ClientRequest pair. The+// response is an EventEmitter we drive manually; both record whether their+// socket was torn down so a test can assert the cap aborts the transfer.+function fakeResponse(headers = {}) {+ const res = new EventEmitter();+ res.headers = headers;+ res.destroyed = false;+ res.destroy = () => { res.destroyed = true; };+ return res;+}+function fakeRequest() {+ return { destroyed: false, destroy() { this.destroyed = true; } };+}describe('makePinnedLookup', () => {it('returns the array form when options.all is true (autoSelectFamily path)', () => {@@ -59,3 +74,59 @@ describe('makePinnedLookup', () => {}});});++describe('collectCappedBody streaming byte ceiling', () => {+ it('buffers the whole body when under the cap', async () => {+ const res = fakeResponse({ 'content-length': '6' });+ const req = fakeRequest();+ const p = collectCappedBody(res, req, 1024);+ res.emit('data', Buffer.from('foo'));+ res.emit('data', Buffer.from('bar'));+ res.emit('end');+ const body = await p;+ expect(body.toString()).toBe('foobar');+ expect(res.destroyed).toBe(false);+ });++ it('rejects up front on an over-limit content-length, before any data', async () => {+ const res = fakeResponse({ 'content-length': String(100 * 1024 * 1024) });+ const req = fakeRequest();+ await expect(collectCappedBody(res, req, 64 * 1024 * 1024)).rejects.toBeInstanceOf(MaxBytesExceededError);+ // Sockets torn down so nothing streams.+ expect(res.destroyed).toBe(true);+ expect(req.destroyed).toBe(true);+ });++ it('aborts mid-stream when actual bytes exceed the cap despite a lying/absent header', async () => {+ const res = fakeResponse({}); // no content-length advertised+ const req = fakeRequest();+ const p = collectCappedBody(res, req, 10);+ res.emit('data', Buffer.from('12345'));+ res.emit('data', Buffer.from('678901')); // crosses 10 here+ await expect(p).rejects.toBeInstanceOf(MaxBytesExceededError);+ expect(res.destroyed).toBe(true);+ expect(req.destroyed).toBe(true);+ });++ it('is unbounded when maxBytes is null (prior behavior preserved)', async () => {+ const res = fakeResponse({ 'content-length': String(5 * 1024 * 1024) });+ const req = fakeRequest();+ const p = collectCappedBody(res, req, null);+ res.emit('data', Buffer.alloc(5 * 1024 * 1024));+ res.emit('end');+ const body = await p;+ expect(body.length).toBe(5 * 1024 * 1024);+ expect(res.destroyed).toBe(false);+ });++ it('carries observed and limit sizes on the error for logging', async () => {+ const res = fakeResponse({ 'content-length': '2000' });+ const req = fakeRequest();+ const err = await collectCappedBody(res, req, 1000).catch((e) => e);+ expect(err).toBeInstanceOf(MaxBytesExceededError);+ expect(err.observed).toBe(2000);+ expect(err.limit).toBe(1000);+ expect(err.status).toBe(413);+ expect(err.code).toBe('max_bytes_exceeded');+ });+});