Skip to content

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.

fix(upstream): put a deadline on the last uploads, saves, launches and hires that could hang

nirholascc7ff9d1880d
diff --git a/api/_lib/diorama-build.js b/api/_lib/diorama-build.js
index 275c93616..ebd2e9244 100644
--- a/api/_lib/diorama-build.js
+++ b/api/_lib/diorama-build.js
@@ -28,6 +28,7 @@ import { llmComplete, llmConfigured } from './llm.js';
import { putObject, publicUrl } from './r2.js';
import { composeSceneGlb } from './scene-graph-compose.js';
import { normalizeDiorama, MIN_OBJECTS, MAX_OBJECTS, MAX_PROMPT_LEN, ISLAND_RADIUS } from '../../src/diorama/schema.js';
+import { fetchUpstream } from './upstream-fetch.js';
const SITE = process.env.PUBLIC_BASE_URL || 'https://three.ws';
@@ -205,11 +206,14 @@ export async function forgeDioramaObjects(diorama, { clientKey } = {}) {
}
async function runForge(prompt, clientKey) {
- const res = await fetch(`${SITE}/api/forge`, {
+ // One attempt, bounded: this POST queues a paid generation, so a retry would
+ // forge (and bill) the same prop twice. Forge's own error payload is read
+ // below, so a non-2xx has to arrive as a Response rather than as a throw.
+ const res = await fetchUpstream(`${SITE}/api/forge`, {
method: 'POST',
headers: { 'content-type': 'application/json', 'x-forge-client': clientKey },
body: JSON.stringify({ prompt, tier: 'draft', path: 'image' }),
- });
+ }, { name: 'self:forge-submit', timeoutMs: 30_000, attempts: 1, okWhen: () => true });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data?.message || data?.error || `forge returned HTTP ${res.status}`);
if (data.status === 'done' && data.glb_url) return data.glb_url;
@@ -222,10 +226,19 @@ async function pollForge(jobId, clientKey) {
const deadline = Date.now() + FORGE_DEADLINE_MS;
while (Date.now() < deadline) {
await sleep(POLL_INTERVAL_MS);
- const res = await fetch(`${SITE}/api/forge?job=${encodeURIComponent(jobId)}`, {
- headers: { 'x-forge-client': clientKey },
- });
- const data = await res.json().catch(() => ({}));
+ let data;
+ try {
+ // A status read is idempotent and cheap, so a stalled or failed poll is
+ // worth exactly one thing: skipping this tick. Before it was bounded, a
+ // single hung poll held the whole diorama build open past its deadline;
+ // now the loop keeps its own deadline as the only limit.
+ const res = await fetchUpstream(`${SITE}/api/forge?job=${encodeURIComponent(jobId)}`, {
+ headers: { 'x-forge-client': clientKey },
+ }, { name: 'self:forge-poll', timeoutMs: 10_000, attempts: 1 });
+ data = await res.json().catch(() => ({}));
+ } catch {
+ continue;
+ }
if (data.status === 'done' && data.glb_url) return data.glb_url;
if (data.status === 'failed') throw new Error(data.error || 'forge failed');
}
diff --git a/api/_lib/x402/pipelines/forge-content.js b/api/_lib/x402/pipelines/forge-content.js
index 77e727b4e..009a0e767 100644
--- a/api/_lib/x402/pipelines/forge-content.js
+++ b/api/_lib/x402/pipelines/forge-content.js
@@ -49,6 +49,7 @@ import {
cosine,
} from '../../embeddings.js';
import { kmeans, suggestClusterCount, unit } from '../../embedding-math.js';
+import { fetchUpstream } from '../../upstream-fetch.js';
import { PROP_CATALOG, STYLES, FINISHES, CATEGORIES } from './forge-catalog.js';
const log = logger('x402-forge-content');
@@ -236,9 +237,11 @@ async function resolveQueuedJobs(origin) {
let resolved = 0;
for (const row of rows) {
try {
- const res = await fetch(`${origin}/api/forge?job=${encodeURIComponent(row.job_id)}`, {
+ // Bounded: this resolver runs inside a cron tick over a batch of rows, so
+ // one hung status read used to cost every remaining row its resolution.
+ const res = await fetchUpstream(`${origin}/api/forge?job=${encodeURIComponent(row.job_id)}`, {
headers: { 'user-agent': 'threews-x402-autonomous/1.0' },
- });
+ }, { name: 'self:forge-poll', timeoutMs: 10_000, attempts: 1, okWhen: () => true });
if (!res.ok) continue;
const job = await res.json();
if (job?.status === 'done' && job.glb_url) {
diff --git a/api/_mcp/tools/animations.js b/api/_mcp/tools/animations.js
index 3a11729c2..30f2f8b35 100644
--- a/api/_mcp/tools/animations.js
+++ b/api/_mcp/tools/animations.js
@@ -704,7 +704,20 @@ async function generateMotionClip(provider, { prompt, duration_seconds }) {
}
if (!clipUrl) throw rpcError(-32000, 'motion generation timed out');
- const res = await fetch(clipUrl);
+ // The clip URL comes back from the provider's own status payload, so reading
+ // it is idempotent: bound it and retry once, rather than letting a stalled
+ // delivery host consume what is left of the tool call after the poll loop.
+ let res;
+ try {
+ res = await fetchUpstream(clipUrl, {}, {
+ name: 'provider:motion-clip',
+ timeoutMs: 20_000,
+ attempts: 2,
+ okWhen: () => true,
+ });
+ } catch (err) {
+ throw rpcError(-32000, `could not fetch generated clip (${err?.message || 'unreachable'})`);
+ }
if (!res.ok) throw rpcError(-32000, `could not fetch generated clip (HTTP ${res.status})`);
return res.json();
}
diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.js
index ad90d1ed5..fc7218393 100644
--- a/api/_mcp3d/tools/studio.js
+++ b/api/_mcp3d/tools/studio.js
@@ -18,7 +18,7 @@
import { createHash } from 'node:crypto';
import { limits } from '../../_lib/rate-limit.js';
-import { assertSafePublicUrl } from '../../_lib/ssrf-guard.js';
+import { assertSafePublicUrl, fetchSafePublicUrlPinned, MaxBytesExceededError } from '../../_lib/ssrf-guard.js';
import { createRegenProvider as createReplicateProvider } from '../../_providers/replicate.js';
import { createRegenProvider as createGcpProvider } from '../../_providers/gcp.js';
import { BYOK_PROVIDER_FACTORIES, isByokGeometryBackend } from '../../_providers/byok-registry.js';
@@ -164,10 +164,35 @@ function pollHint(etaSeconds, fallback) {
// reconstruct + forge pipelines so a runaway model can't ingest an unbounded blob.
const MAX_GLB_BYTES = 64 * 1024 * 1024;
-// Fetch a provider GLB into a Buffer with a hard size cap, so save_avatar can
-// persist its own durable copy before the provider's delivery URL expires.
+// How long save_avatar will wait for one GLB download. A model URL that accepts
+// the connection and then stalls used to hold the MCP call open for the whole
+// invocation and return nothing; bounded, it fails with an answer the caller can
+// act on.
+const GLB_FETCH_TIMEOUT_MS = 30_000;
+
+// Fetch a caller-supplied GLB into a Buffer, so save_avatar can persist its own
+// durable copy before the provider's delivery URL expires. Routed through the
+// pinned SSRF guard rather than a bare fetch for three reasons: the hostname is
+// re-resolved and IP-pinned, closing the DNS-rebinding window that the
+// isPublicHttpsUrl() check at the call site leaves open; the size ceiling is
+// enforced WHILE streaming, so an oversized or lying host is torn down instead
+// of buffered; and redirects are re-validated hop by hop. The declared-length
+// and post-read checks stay as defense in depth.
async function fetchGlbBuffer(url) {
- const resp = await fetch(url);
+ let resp;
+ try {
+ resp = await fetchSafePublicUrlPinned(
+ url,
+ { signal: AbortSignal.timeout(GLB_FETCH_TIMEOUT_MS) },
+ { allowHttp: false, maxBytes: MAX_GLB_BYTES },
+ );
+ } catch (err) {
+ if (err instanceof MaxBytesExceededError) {
+ throw rpcError(-32000, `GLB too large to save (max ${MAX_GLB_BYTES} bytes).`);
+ }
+ const reason = err?.name === 'TimeoutError' ? 'timed out' : err?.message || 'unreachable';
+ throw rpcError(-32000, `Could not fetch the GLB (${reason}).`);
+ }
if (!resp.ok) throw rpcError(-32000, `Could not fetch the GLB (${resp.status}).`);
const declared = Number(resp.headers.get('content-length') || 0);
if (declared && declared > MAX_GLB_BYTES) {
diff --git a/api/agent-collab.js b/api/agent-collab.js
index 952de8b16..b0b9e7e2e 100644
--- a/api/agent-collab.js
+++ b/api/agent-collab.js
@@ -26,6 +26,7 @@ import { env } from './_lib/env.js';
import { runAgentDelegation, AgentNotFoundError } from './_lib/agent-delegate.js';
import { listOffersWithStats } from './_lib/agent-economy.js';
import { writeScreenFrame } from './_lib/agent-screen-frame.js';
+import { fetchUpstream } from './_lib/upstream-fetch.js';
import {
orchestrateGoal,
clampBudget,
@@ -118,14 +119,19 @@ export default wrap(async (req, res) => {
const runHire = async ({ hirerAgentId, serviceSlug, input, maxUsd: nodeMax }) => {
if (!hireToken) throw Object.assign(new Error('agent spending unavailable'), { code: 'spend_disabled' });
- const resp = await fetch(`${hireBase}/api/agents/a2a-hire`, {
+ // A hire is a real, paid call into another agent's service, so it is bounded
+ // but NEVER retried: a replay would pay twice for one node. 120s sits well
+ // under the 230s orchestration budget, so a teammate that stops answering
+ // costs this node and not the rest of the team task. The hire endpoint's
+ // own error payload is read below, so a non-2xx must return, not throw.
+ const resp = await fetchUpstream(`${hireBase}/api/agents/a2a-hire`, {
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: `Bearer ${hireToken}`,
},
body: JSON.stringify({ hirerAgentId, serviceSlug, input, maxUsd: nodeMax }),
- });
+ }, { name: 'self:a2a-hire', timeoutMs: 120_000, attempts: 1, okWhen: () => true });
const data = await resp.json().catch(() => ({}));
if (!resp.ok) {
throw Object.assign(new Error(data.error_description || data.error || 'hire failed'), {
diff --git a/api/avatar-og.js b/api/avatar-og.js
index 0a820cd79..3ef08c102 100644
--- a/api/avatar-og.js
+++ b/api/avatar-og.js
@@ -131,7 +131,14 @@ async function renderAndCache({ avatar }) {
const promise = (async () => {
// Size precheck. A 50 MB GLB would blow the render budget and risk
// OOM; kick those out to the fallback before launching chromium.
- const head = await fetch(avatar.model_url, { method: 'HEAD' }).catch(() => null);
+ // The precheck exists to save the render budget, so it must not spend it:
+ // a model host that accepts the connection and stalls fails the HEAD fast
+ // and the render proceeds without the size hint, exactly as it does when a
+ // host omits content-length.
+ const head = await fetch(avatar.model_url, {
+ method: 'HEAD',
+ signal: AbortSignal.timeout(8_000),
+ }).catch(() => null);
const contentLength = Number(head?.headers?.get('content-length') || 0);
if (head?.ok && contentLength > MAX_GLB_BYTES) {
throw Object.assign(new Error(`glb too large: ${contentLength} bytes`), {
diff --git a/api/avatars/[id]/[action].js b/api/avatars/[id]/[action].js
index 1daa974bf..4aaa58b47 100644
--- a/api/avatars/[id]/[action].js
+++ b/api/avatars/[id]/[action].js
@@ -16,6 +16,7 @@ import { readStorageMode, storageModeSchema, defaultStorageMode } from '../../_l
import { getAvatar, resolveAvatarUrl } from '../../_lib/avatars.js';
import { r2, publicUrl, thumbnailUrl } from '../../_lib/r2.js';
import { env } from '../../_lib/env.js';
+import { fetchUpstream } from '../../_lib/upstream-fetch.js';
import { pinToIPFS, ipfsPinningConfigured } from '../../_lib/ipfs-pin.js';
export default wrap(async (req, res) => {
@@ -362,15 +363,26 @@ async function createAvaturnEditSession({ apiKey, apiUrl, userId, avatarUrl }) {
avatar_url: avatarUrl,
};
- const upstream = await fetch(url, {
- method: 'POST',
- headers: {
- authorization: `Bearer ${apiKey}`,
- 'content-type': 'application/json',
- accept: 'application/json',
- },
- body: JSON.stringify(payload),
- });
+ // Bounded, single attempt: opening an edit session is a create, so a retry
+ // would leave a second session behind. The status mapping below needs the
+ // Response itself, so a non-2xx returns rather than throws.
+ let upstream;
+ try {
+ upstream = await fetchUpstream(url, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${apiKey}`,
+ 'content-type': 'application/json',
+ accept: 'application/json',
+ },
+ body: JSON.stringify(payload),
+ }, { name: 'avaturn:sessions', timeoutMs: 20_000, attempts: 1, okWhen: () => true });
+ } catch (e) {
+ const err = new Error(`avaturn unreachable: ${e?.message || 'network error'}`);
+ err.status = 502;
+ err.code = 'upstream_error';
+ throw err;
+ }
if (!upstream.ok) {
const text = await upstream.text().catch(() => '');
diff --git a/api/cron/forge-seed-cron.js b/api/cron/forge-seed-cron.js
index 9f49585a9..19c87248e 100644
--- a/api/cron/forge-seed-cron.js
+++ b/api/cron/forge-seed-cron.js
@@ -64,6 +64,7 @@ import { isFreeBackend } from '../_lib/forge-tiers.js';
import { circuitState, circuitRecordFailure, circuitRecordSuccess } from '../_lib/forge-scale.js';
import { randomUUID } from 'node:crypto';
import { requireCron } from '../_lib/cron-auth.js';
+import { fetchUpstream } from '../_lib/upstream-fetch.js';
const ORIGIN = () => env.APP_ORIGIN || 'https://three.ws';
// Must be comfortably shorter than the function's maxDuration (70 s in vercel.json)
@@ -225,11 +226,17 @@ async function loadGlbBytes({ creationId, glbUrl }) {
if (key && !/^https?:\/\//i.test(key)) {
return { buf: await getObjectBuffer(key), key };
}
- if (key) return { buf: Buffer.from(await (await fetch(key)).arrayBuffer()), key: null };
+ // An absolute key is a lane's public URL, so it is read like one: bounded,
+ // and rejected on a non-2xx. Unbounded and unchecked, a slow host stalled
+ // the gate for the rest of the tick and an error page was handed to the GLB
+ // parser as if it were mesh bytes.
+ if (key) {
+ const res = await fetchUpstream(key, {}, { name: 'lane:glb-read', timeoutMs: 30_000, attempts: 2 });
+ return { buf: Buffer.from(await res.arrayBuffer()), key: null };
+ }
}
if (!glbUrl) throw new Error('no glb key or url to gate');
- const res = await fetch(glbUrl, { signal: AbortSignal.timeout(30_000) });
- if (!res.ok) throw new Error(`glb fetch ${res.status}`);
+ const res = await fetchUpstream(glbUrl, {}, { name: 'lane:glb-read', timeoutMs: 30_000, attempts: 2 });
return { buf: Buffer.from(await res.arrayBuffer()), key: null };
}
diff --git a/api/forever/status.js b/api/forever/status.js
index 281fbbced..39274e5be 100644
--- a/api/forever/status.js
+++ b/api/forever/status.js
@@ -27,6 +27,7 @@
import { cors, error, json, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { getTransactionStatus, getTipHeight, isPlausibleTxid } from '../_lib/esplora.js';
+import { fetchUpstream } from '../_lib/upstream-fetch.js';
const ORDINALSBOT_BASE_URL =
process.env.ORDINALSBOT_BASE_URL || 'https://api.ordinalsbot.com';
@@ -148,7 +149,24 @@ async function fetchOrdinalsBotOrder(orderId) {
headers['x-api-key'] = process.env.ORDINALSBOT_API_KEY;
}
const url = `${ORDINALSBOT_BASE_URL}/order?id=${encodeURIComponent(orderId)}`;
- const res = await fetch(url, { headers });
+ // An order lookup is a read, so it retries once, but it is bounded either way:
+ // unbounded, one slow OrdinalsBot response held a status poll open until the
+ // platform killed it, which reads to the caller as our endpoint being dead.
+ // Every status code below is still classified here, so a non-2xx must arrive
+ // as a Response rather than as a throw.
+ let res;
+ try {
+ res = await fetchUpstream(url, { headers }, {
+ name: 'ordinalsbot:order',
+ timeoutMs: 15_000,
+ attempts: 2,
+ okWhen: () => true,
+ });
+ } catch (e) {
+ const err = new Error(`OrdinalsBot unreachable: ${e?.message || 'network error'}`);
+ err.status = 502;
+ throw err;
+ }
const text = await res.text();
let data;
try {
diff --git a/api/forge-gameready.js b/api/forge-gameready.js
index c9c12c4de..f50117c8a 100644
--- a/api/forge-gameready.js
+++ b/api/forge-gameready.js
@@ -31,6 +31,7 @@ import { limits, clientIp } from './_lib/rate-limit.js';
import { assertPublicHttpsUrl, SsrfError } from './_lib/ssrf.js';
import { createRegenProvider } from './_providers/gcp.js';
import { putObject, publicUrl } from './_lib/r2.js';
+import { fetchUpstream } from './_lib/upstream-fetch.js';
import { requireFeatureAccess } from './_lib/require-three.js';
import {
assertForgePurchase,
@@ -280,8 +281,14 @@ async function startJob(req, res) {
// the copy fails — a real, working result either way, never a faked one.
async function mirrorToR2(sourceUrl, key, format) {
try {
- const resp = await fetch(sourceUrl);
- if (!resp.ok) throw new Error(`fetch result ${resp.status}`);
+ // Bounded, with one retry: the artifact is a fresh worker upload, so a
+ // transient read failure is worth retrying, and a stalled one must not hold
+ // the poll open. Any failure falls through to the worker URL below.
+ const resp = await fetchUpstream(sourceUrl, {}, {
+ name: 'worker:gameready-artifact',
+ timeoutMs: 30_000,
+ attempts: 2,
+ });
const buf = Buffer.from(await resp.arrayBuffer());
await putObject({
key,
diff --git a/api/input-multiview.js b/api/input-multiview.js
index b388e84b8..8a6d06b6d 100644
--- a/api/input-multiview.js
+++ b/api/input-multiview.js
@@ -37,6 +37,7 @@ import { limits, clientIp } from './_lib/rate-limit.js';
import { visionConfigured, describeImage } from './_lib/vision.js';
import { deleteObject } from './_lib/r2.js';
import { env } from './_lib/env.js';
+import { fetchUpstream } from './_lib/upstream-fetch.js';
export const maxDuration = 90; // vision validation × N images + generation submit
@@ -166,7 +167,10 @@ export default wrap(async (req, res) => {
const forgeOrigin = env.APP_ORIGIN;
let forgeResp;
try {
- forgeResp = await fetch(`${forgeOrigin}/api/forge`, {
+ // Bounded, and deliberately never retried: this POST enqueues a generation,
+ // so a replay would queue a second job against the same photos. Forge's own
+ // error codes are mapped below, so a non-2xx returns rather than throws.
+ forgeResp = await fetchUpstream(`${forgeOrigin}/api/forge`, {
method: 'POST',
headers: {
'content-type': 'application/json',
@@ -174,7 +178,7 @@ export default wrap(async (req, res) => {
'x-forge-client': req.headers['x-forge-client'] || '',
},
body: JSON.stringify(forgeBody),
- });
+ }, { name: 'self:forge-submit', timeoutMs: 30_000, attempts: 1, okWhen: () => true });
} catch {
return error(res, 502, 'generation_unreachable',
'Could not reach the generation service. Please try again.');
diff --git a/api/input-photo.js b/api/input-photo.js
index 1c696a0ca..04444798c 100644
--- a/api/input-photo.js
+++ b/api/input-photo.js
@@ -40,6 +40,7 @@ import { limits, clientIp } from './_lib/rate-limit.js';
import { visionConfigured, describeImage } from './_lib/vision.js';
import { deleteObject } from './_lib/r2.js';
import { env } from './_lib/env.js';
+import { fetchUpstream } from './_lib/upstream-fetch.js';
export const maxDuration = 60;
@@ -141,7 +142,13 @@ export default wrap(async (req, res) => {
const forgeOrigin = env.APP_ORIGIN;
let forgeResp;
try {
- forgeResp = await fetch(`${forgeOrigin}/api/forge`, {
+ // The self-call is cheap (forge queues a job and answers with its id), but
+ // unbounded it could hold this handler until the platform killed it, which
+ // the client reads as a dead endpoint rather than a slow one. One attempt
+ // only: this POST enqueues a generation, so replaying it would queue a
+ // second job and bill the user twice. Forge's own status codes are handled
+ // below, so a non-2xx must come back as a Response rather than throw.
+ forgeResp = await fetchUpstream(`${forgeOrigin}/api/forge`, {
method: 'POST',
headers: {
'content-type': 'application/json',
@@ -150,7 +157,7 @@ export default wrap(async (req, res) => {
'x-forge-client': req.headers['x-forge-client'] || '',
},
body: JSON.stringify(forgeBody),
- });
+ }, { name: 'self:forge-submit', timeoutMs: 30_000, attempts: 1, okWhen: () => true });
} catch {
return error(res, 502, 'generation_unreachable',
'Could not reach the generation service. Please try again.');
diff --git a/api/onboarding/[action].js b/api/onboarding/[action].js
index 9a32978a7..325452437 100644
--- a/api/onboarding/[action].js
+++ b/api/onboarding/[action].js
@@ -8,6 +8,7 @@ import { requireCsrf } from '../_lib/csrf.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { parse } from '../_lib/validate.js';
import { env } from '../_lib/env.js';
+import { fetchUpstream } from '../_lib/upstream-fetch.js';
// ── avaturn-session ───────────────────────────────────────────────────────────
@@ -111,11 +112,19 @@ async function handleAvaturnSession(req, res) {
const CALLER_FIXABLE_UPSTREAM = new Set([400, 413, 415, 422]);
async function createProviderSession(userId, body) {
- const upstream = await fetch(`${env.AVATURN_API_URL}/api/v1/sessions`, {
- method: 'POST',
- headers: { authorization: `Bearer ${env.AVATURN_API_KEY}`, 'content-type': 'application/json', accept: 'application/json' },
- body: JSON.stringify({ external_user_id: userId, photos: body.photos, body_type: body.body_type, version: body.avatar_type }),
- });
+ // Bounded and never retried: this POST opens a provider session against the
+ // user's photos, so a replay would open a second one on the same upload. Every
+ // status below is classified here, so a non-2xx has to arrive as a Response.
+ let upstream;
+ try {
+ upstream = await fetchUpstream(`${env.AVATURN_API_URL}/api/v1/sessions`, {
+ method: 'POST',
+ headers: { authorization: `Bearer ${env.AVATURN_API_KEY}`, 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify({ external_user_id: userId, photos: body.photos, body_type: body.body_type, version: body.avatar_type }),
+ }, { name: 'avaturn:sessions', timeoutMs: 20_000, attempts: 1, okWhen: () => true });
+ } catch (e) {
+ throw Object.assign(new Error(`avaturn unreachable: ${e?.message || 'network error'}`), { status: 502 });
+ }
if (!upstream.ok) {
const detail = (await upstream.text().catch(() => '')).slice(0, 200);
if (CALLER_FIXABLE_UPSTREAM.has(upstream.status)) {
diff --git a/api/pump/[action].js b/api/pump/[action].js
index eb71510e5..2826e866c 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -106,6 +106,7 @@ import {
releaseSpend,
} from '../_lib/agent-spend-policy.js';
import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET, toUsdcAtomics } from '../payments/_config.js';
+import { fetchUpstream } from '../_lib/upstream-fetch.js';
import {
classifyLaunchQuote,
usdcMintFor,
@@ -1019,7 +1020,15 @@ async function handleBuildMetadata(req, res) {
// Fetch the stored thumbnail so it too lands on IPFS; if that fails,
// fall back to referencing the R2 URL directly (still a valid image).
try {
- const resp = await fetch(thumbUrl);
+ // Bounded: a launch waits on this download, and an unbounded read of a
+ // stalled object held the whole mint request open instead of falling
+ // through to the R2 URL below, which is a perfectly good answer.
+ const resp = await fetchUpstream(thumbUrl, {}, {
+ name: 'r2:thumbnail',
+ timeoutMs: 15_000,
+ attempts: 2,
+ okWhen: () => true,
+ });
if (resp.ok) {
imageBuf = Buffer.from(await resp.arrayBuffer());
imageContentType = resp.headers.get('content-type') || 'image/png';
diff --git a/tests/api/mcp-avatar-persist.test.js b/tests/api/mcp-avatar-persist.test.js
index 8d1cc241b..366195f87 100644
--- a/tests/api/mcp-avatar-persist.test.js
+++ b/tests/api/mcp-avatar-persist.test.js
@@ -9,18 +9,28 @@ process.env.S3_PUBLIC_DOMAIN ||= 'https://cdn.test';
process.env.S3_BUCKET ||= 'test-bucket';
// ── SSRF guard (DNS resolution breaks on fake test hostnames) ───────────────
+// save_avatar downloads the GLB through the guard's pinned fetch, which resolves
+// the hostname and opens a raw socket: neither works for `cdn.test` in a unit
+// test. Both entry points are stubbed to keep the guard's CONTRACT (https only,
+// no private hosts) while the transport falls through to the stubbed global
+// fetch below.
vi.mock('../../api/_lib/ssrf-guard.js', async (importOriginal) => {
const mod = await importOriginal();
const { SsrfBlockedError } = mod;
+ const assertSafePublicUrl = vi.fn(async (url, opts = {}) => {
+ const parsed = new URL(url);
+ if (parsed.protocol === 'http:' && !opts.allowHttp)
+ throw new SsrfBlockedError('http:// not allowed — use https://');
+ if (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1')
+ throw new SsrfBlockedError('host resolves to a blocked range');
+ return parsed;
+ });
return {
...mod,
- assertSafePublicUrl: vi.fn(async (url, opts = {}) => {
- const parsed = new URL(url);
- if (parsed.protocol === 'http:' && !opts.allowHttp)
- throw new SsrfBlockedError('http:// not allowed — use https://');
- if (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1')
- throw new SsrfBlockedError('host resolves to a blocked range');
- return parsed;
+ assertSafePublicUrl,
+ fetchSafePublicUrlPinned: vi.fn(async (url, init = {}, opts = {}) => {
+ await assertSafePublicUrl(String(url), opts);
+ return fetch(String(url), init);
}),
};
});