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(ssrf): resolve and pin caller-supplied image, render, metadata and facilitator URLs on every redirect hop

nirholas693b162d38cb
diff --git a/api/_lib/forge-quality-gate.js b/api/_lib/forge-quality-gate.js
index 2b7cb2ecf..312cc77d9 100644
--- a/api/_lib/forge-quality-gate.js
+++ b/api/_lib/forge-quality-gate.js
@@ -56,8 +56,8 @@ import {
providersInCooldown,
} from './provider-health.js';
import { renderAvatarScene, SCENE_PRESETS } from './avatar-render.js';
-import { validatePublicUrl, isPrivateAddress, SsrfError } from './ssrf.js';
-import { isIP } from 'node:net';
+import { assertPublicHttpsUrl, SsrfError } from './ssrf.js';
+import { fetchSafePublicUrlPinned, MaxBytesExceededError, SsrfBlockedError } from './ssrf-guard.js';
function readEnv(name) {
if (typeof process !== 'undefined' && process.env?.[name]) return process.env[name];
@@ -190,32 +190,45 @@ function score100(v) {
return Math.max(0, Math.min(100, Math.round(n)));
}
-// SSRF guard for a caller-supplied render URL we fetch server-side. Mirrors the
-// guard in vision.js: require https (http only in dev) and reject private IP
-// literals + localhost. DNS-name hosts pass (we can't pin resolution here).
-function assertSafeUrl(rawUrl) {
- let url;
+// SSRF guard for a caller-supplied render or GLB URL: https (http only in dev),
+// and the host is resolved on our side with every address checked against the
+// private/loopback/metadata blocklist. A literal-only check let any DNS name
+// that resolves inward straight through.
+async function assertSafeUrl(rawUrl) {
try {
- url = validatePublicUrl(rawUrl);
+ return await assertPublicHttpsUrl(rawUrl);
} catch (e) {
- if (e instanceof SsrfError) throw Object.assign(new Error('render URL is not a public https address'), { code: 'invalid_url' });
+ if (e instanceof SsrfError) {
+ throw Object.assign(new Error('render URL is not a public https address'), { code: 'invalid_url' });
+ }
throw e;
}
- const host = url.hostname.replace(/^\[|\]$/g, '');
- const fam = isIP(host);
- const blocked = fam ? isPrivateAddress(host, fam) : host === 'localhost' || /\.(local|internal|localdomain)$/i.test(host);
- if (blocked) throw Object.assign(new Error('render URL resolves to a non-public host'), { code: 'invalid_url' });
- return url;
}
-// Fetch an image URL and return { imageBase64, mimeType }. Guarded + size-capped.
+const MAX_RENDER_IMAGE_BYTES = 16 * 1024 * 1024;
+
+// Fetch an image URL and return { imageBase64, mimeType }. The pinned guard
+// connects only to the validated address, re-validates every redirect hop, and
+// caps the body while streaming.
async function fetchImageBase64(rawUrl, timeoutMs) {
- assertSafeUrl(rawUrl);
- const res = await fetch(rawUrl, { signal: AbortSignal.timeout(timeoutMs) });
+ await assertSafeUrl(rawUrl);
+ let res;
+ try {
+ res = await fetchSafePublicUrlPinned(
+ rawUrl,
+ { signal: AbortSignal.timeout(timeoutMs) },
+ { allowHttp: process.env.NODE_ENV !== 'production', maxBytes: MAX_RENDER_IMAGE_BYTES },
+ );
+ } catch (e) {
+ if (e instanceof SsrfBlockedError) {
+ throw Object.assign(new Error('render URL is not a public https address'), { code: 'invalid_url' });
+ }
+ if (e instanceof MaxBytesExceededError) throw new Error('render image exceeds 16 MB');
+ throw e;
+ }
if (!res.ok) throw new Error(`render fetch ${res.status}`);
const ct = (res.headers.get('content-type') || 'image/png').split(';')[0].trim();
const buf = Buffer.from(await res.arrayBuffer());
- if (buf.byteLength > 16 * 1024 * 1024) throw new Error('render image exceeds 16 MB');
return { imageBase64: buf.toString('base64'), mimeType: ct.startsWith('image/') ? ct : 'image/png' };
}
@@ -227,7 +240,7 @@ async function fetchImageBase64(rawUrl, timeoutMs) {
// pipeline's lighting is fixed, so the rubric explicitly tells the model to judge
// the mesh, not the render's exposure.
async function renderGlbBase64(glbUrl, size) {
- assertSafeUrl(glbUrl);
+ await assertSafeUrl(glbUrl);
const { png } = await renderAvatarScene({
glbUrl,
width: size,
diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.js
index aae3d79e1..728b3e5e2 100644
--- a/api/_lib/forge-store.js
+++ b/api/_lib/forge-store.js
@@ -27,7 +27,7 @@ import { compressGlb, deliveryCompressionOptions } from './glb-compress.js';
import { classifyModelCategory } from './forge-classify.js';
import { cleanupGlb } from './glb-cleanup.js';
import { derivePbrChannels } from './glb-pbr-derive.js';
-import { fetchUpstream } from './upstream-fetch.js';
+import { fetchUpstream, fetchUpstreamPublic } from './upstream-fetch.js';
import { gradeSimReadiness } from './sim-readiness.js';
import { putGrade } from './sim-readiness-store.js';
import { dispatchWebhooks } from './webhook-dispatch.js';
@@ -425,12 +425,16 @@ function mediaTypeOr(header, fallback) {
return STORABLE_TYPE_RE.test(type) ? type : fallback;
}
-async function copyToBucket({ sourceUrl, key, fallbackContentType, maxBytes, computeQuality = false, compress = null, cleanup = false, derivePbr = false, prompt = '', tier = '', materialClass = '', forceContentType = null }) {
+async function copyToBucket({ sourceUrl, key, fallbackContentType, maxBytes, computeQuality = false, compress = null, cleanup = false, derivePbr = false, prompt = '', tier = '', materialClass = '', forceContentType = null, untrustedSource = false }) {
// fetchUpstream retries network errors and 408/425/429/5xx with jittered
// backoff and gives up immediately on 404/410 (the ephemeral asset has
// already expired; no retry can recover it), rejecting with an error that
// carries `status` so callers keep classifying it the same way.
- const resp = await fetchUpstream(sourceUrl, {}, { timeoutMs: COPY_TIMEOUT_MS, attempts: COPY_MAX_ATTEMPTS, label: 'forge asset copy' });
+ // An untrusted source (a reference image the caller named) is fetched with
+ // every redirect hop SSRF-checked: the bytes land in a public bucket, so an
+ // unchecked hop would publish whatever an internal host answered.
+ const fetcher = untrustedSource ? fetchUpstreamPublic : fetchUpstream;
+ const resp = await fetcher(sourceUrl, {}, { timeoutMs: COPY_TIMEOUT_MS, attempts: COPY_MAX_ATTEMPTS, label: 'forge asset copy' });
let buf = Buffer.from(await resp.arrayBuffer());
if (buf.length > maxBytes) throw new Error(`asset too large: ${buf.length} bytes`);
// forceContentType wins over the upstream header: providers (Replicate
@@ -626,6 +630,8 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl, q
fallbackContentType: 'image/webp',
forceContentType: imageContentTypeFor(ext),
maxBytes: MAX_IMAGE_BYTES,
+ // preview_image_url can be the caller's own reference image URL.
+ untrustedSource: true,
});
preview = { key: `${keyPrefix}.${ext}`, url: copied.publicUrl };
} catch (imgErr) {
diff --git a/api/_lib/irl-bake.js b/api/_lib/irl-bake.js
index ab527ef94..3cdd9e5af 100644
--- a/api/_lib/irl-bake.js
+++ b/api/_lib/irl-bake.js
@@ -19,7 +19,7 @@
import { bakeAppearance, appearanceHash, isBakeable } from './bake.js';
import { putObject, publicUrl } from './r2.js';
import { env } from './env.js';
-import { fetchUpstream } from './upstream-fetch.js';
+import { fetchUpstream, fetchUpstreamPublic } from './upstream-fetch.js';
export { isBakeable };
@@ -29,14 +29,16 @@ const MAX_BASE_GLB_BYTES = 25 * 1024 * 1024;
// Resolve the pin's base GLB to absolute bytes. Relative URLs (the common
// `/api/avatars/:id/glb` form, or `/cdn/<key>`) resolve against the app origin —
-// the avatar lives on our own API/CDN. Absolute URLs were already SSRF-screened
-// by safeRemoteUrl() when the pin was created, so re-fetching them is safe.
+// the avatar lives on our own API/CDN. Absolute URLs are the pin owner's own
+// link: safeRemoteUrl() only screened it lexically when the pin was saved, so it
+// is fetched with DNS resolution and per-hop redirect checks here.
async function fetchBaseGlb(baseUrl) {
if (!baseUrl) throw new Error('pin has no base avatar GLB to dress');
const abs = /^https?:\/\//i.test(baseUrl)
? baseUrl
: `${env.APP_ORIGIN}${baseUrl.startsWith('/') ? '' : '/'}${baseUrl}`;
- const r = await fetchUpstream(abs, {}, { timeoutMs: 60_000, attempts: 3, okWhen: () => true });
+ const fetcher = abs === baseUrl ? fetchUpstreamPublic : fetchUpstream;
+ const r = await fetcher(abs, {}, { timeoutMs: 60_000, attempts: 3, okWhen: () => true, allowHttp: true });
if (!r.ok) throw new Error(`base GLB fetch failed: ${abs} → ${r.status}`);
const declared = Number(r.headers.get('content-length') || 0);
if (declared && declared > MAX_BASE_GLB_BYTES) {
diff --git a/api/_lib/likeness-score.js b/api/_lib/likeness-score.js
index d34396f6c..defcfb81f 100644
--- a/api/_lib/likeness-score.js
+++ b/api/_lib/likeness-score.js
@@ -24,7 +24,7 @@
// different findings and a table that conflates them is worse than no table.
import { renderAvatarScene, SCENE_PRESETS } from './avatar-render.js';
-import { fetchUpstream } from './upstream-fetch.js';
+import { fetchUpstreamPublic } from './upstream-fetch.js';
import {
SCORER_VERSION,
SFACE_SAME_IDENTITY_COSINE,
@@ -80,7 +80,8 @@ export function cosineToScore5(cosine) {
}
async function fetchImage(url, { maxBytes = 12 * 1024 * 1024 } = {}) {
- const res = await fetchUpstream(url, {}, { timeoutMs: 60_000, attempts: 3, okWhen: () => true });
+ // Reference photos are user-supplied URLs, so every hop is SSRF-checked.
+ const res = await fetchUpstreamPublic(url, {}, { timeoutMs: 60_000, attempts: 3, okWhen: () => true, allowHttp: true });
if (!res.ok) throw new Error(`capture fetch ${res.status}`);
const buf = Buffer.from(await res.arrayBuffer());
if (buf.length > maxBytes) throw new Error(`capture too large: ${buf.length} bytes`);
diff --git a/api/_lib/upstream-fetch.js b/api/_lib/upstream-fetch.js
index 64c285075..18b0917f6 100644
--- a/api/_lib/upstream-fetch.js
+++ b/api/_lib/upstream-fetch.js
@@ -37,6 +37,7 @@ import { withRetry, withBreaker, parseRetryAfter, isRetryableError } from './res
import { createCache } from './mem-cache.js';
import { recordSource } from './brownout/provenance.js';
import { applyFault, faultFor } from './brownout/chaos.js';
+import { assertSafePublicUrl, SsrfBlockedError } from './ssrf-guard.js';
export const DEFAULT_TIMEOUT_MS = 8_000;
const DEFAULT_ATTEMPTS = 3;
@@ -209,6 +210,37 @@ export async function fetchUpstream(url, init = {}, opts = {}) {
return noteFail(failure instanceof Error ? failure : new UpstreamError(`${label || name}: circuit open`, { url: shown, status: 503 }));
}
+const MAX_PUBLIC_REDIRECTS = 5;
+
+/**
+ * fetchUpstream for a URL a user, a caller, or on-chain data chose. Same retry,
+ * timeout and breaker behavior, but redirects are followed by hand and every
+ * hop is checked with assertSafePublicUrl first, so a public host cannot 302
+ * the server into a private, loopback or metadata address. Rejects with
+ * SsrfBlockedError (status 400) when a hop is refused.
+ *
+ * @param {string} url
+ * @param {RequestInit} [init]
+ * @param {object} [opts] fetchUpstream options, plus `allowHttp`
+ * @returns {Promise<Response>}
+ */
+export async function fetchUpstreamPublic(url, init = {}, opts = {}) {
+ const { allowHttp = false, okWhen = (res) => res.ok, ...rest } = opts;
+ const isRedirect = (res) => res.status >= 300 && res.status < 400 && res.headers.get('location');
+ let current = String(url);
+ for (let hop = 0; hop <= MAX_PUBLIC_REDIRECTS; hop++) {
+ await assertSafePublicUrl(current, { allowHttp });
+ const res = await fetchUpstream(
+ current,
+ { ...init, redirect: 'manual' },
+ { ...rest, okWhen: (r) => Boolean(isRedirect(r)) || okWhen(r) },
+ );
+ if (!isRedirect(res)) return res;
+ current = new URL(res.headers.get('location'), current).toString();
+ }
+ throw new SsrfBlockedError('too many redirects');
+}
+
/**
* fetchUpstream + JSON parse. A body that is not JSON rejects with an
* UpstreamError (status 502) rather than a bare SyntaxError, so a provider that
diff --git a/api/_lib/vertex-claude.js b/api/_lib/vertex-claude.js
index 9384e9d04..8a108a393 100644
--- a/api/_lib/vertex-claude.js
+++ b/api/_lib/vertex-claude.js
@@ -81,9 +81,25 @@ function vertexTarget() {
// Build the Vertex Messages endpoint URL for a model. `:streamRawPredict` for
// streaming SSE, `:rawPredict` for a single JSON response.
+//
+// The model id is spliced into the path of a request that carries the
+// platform's GCP bearer token, and on some routes it is caller-supplied (the
+// x402 LLM proxy forwards any non-alias model string). A value carrying `/`,
+// `..`, `?` or `#` would walk that authenticated POST onto a different Vertex
+// API path, so anything outside the model-id alphabet is refused here.
+const VERTEX_MODEL_ID = /^[a-z0-9][a-z0-9._-]{0,127}(@[0-9a-z._-]{1,32})?$/i;
+
+/** True when `modelId` is safe to place in a Vertex Messages URL path. */
+export function isVertexModelId(modelId) {
+ return VERTEX_MODEL_ID.test(String(toVertexModelId(modelId) || ''));
+}
+
export function vertexMessagesUrl(modelId, { stream = false } = {}) {
const { project, location, host } = vertexTarget();
const vid = toVertexModelId(modelId);
+ if (!isVertexModelId(modelId)) {
+ throw Object.assign(new Error('invalid Vertex model id'), { code: 'invalid_model', status: 400 });
+ }
const verb = stream ? 'streamRawPredict' : 'rawPredict';
return `https://${host}/v1/projects/${project}/locations/${location}/publishers/anthropic/models/${vid}:${verb}`;
}
diff --git a/api/_lib/x402/bazaar-client.js b/api/_lib/x402/bazaar-client.js
index d13ff76eb..98aba0ccf 100644
--- a/api/_lib/x402/bazaar-client.js
+++ b/api/_lib/x402/bazaar-client.js
@@ -11,6 +11,8 @@
// Multi-facilitator merging dedupes HTTP by `resource` and MCP by
// `(resource, toolName)` per spec.
+import { fetchSafePublicUrlPinned } from '../ssrf-guard.js';
+
const DEFAULT_FACILITATORS = (() => {
const list = [];
const base = process.env.X402_FACILITATOR_URL_BASE || 'https://facilitator.payai.network';
@@ -195,15 +197,26 @@ export function normalizeItem(item, facilitator) {
};
}
-async function fetchJson(url, { timeoutMs = 15000 } = {}) {
+// Ceiling on one discovery page from a caller-named facilitator.
+const UNTRUSTED_PAGE_MAX_BYTES = 8 * 1024 * 1024;
+
+async function fetchJson(url, { timeoutMs = 15000, untrusted = false } = {}) {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), timeoutMs);
try {
- const r = await fetch(url, {
+ const init = {
method: 'GET',
headers: { accept: 'application/json' },
signal: ctrl.signal,
- });
+ };
+ // A facilitator URL named by the caller (`?facilitators=` on the public
+ // bazaar routes) is fetched through the pinned SSRF guard: https only, no
+ // private or metadata address on any redirect hop, bytes capped. Without
+ // it the route was an unauthenticated proxy into internal hosts that
+ // echoed the response back in the error text.
+ const r = untrusted
+ ? await fetchSafePublicUrlPinned(url, init, { maxBytes: UNTRUSTED_PAGE_MAX_BYTES })
+ : await fetch(url, init);
if (!r.ok) {
const body = await r.text().catch(() => '');
throw Object.assign(new Error(`facilitator ${r.status} ${r.statusText}: ${body.slice(0, 200)}`), {
@@ -231,7 +244,7 @@ function rawItemKey(item) {
// Page through a facilitator's /discovery/resources. We stop at `maxItems`
// (default 500) to keep responses bounded. Operators that need everything can
// raise the cap explicitly.
-async function listOneFacilitator(facilitatorUrl, { type, limit, maxItems }) {
+async function listOneFacilitator(facilitatorUrl, { type, limit, maxItems, untrusted = false }) {
const items = [];
const seen = new Set();
const pageSize = Math.min(200, Math.max(1, limit || 200));
@@ -242,7 +255,7 @@ async function listOneFacilitator(facilitatorUrl, { type, limit, maxItems }) {
if (type) u.searchParams.set('type', type);
u.searchParams.set('limit', String(pageSize));
u.searchParams.set('offset', String(offset));
- const body = await fetchJson(u.toString());
+ const body = await fetchJson(u.toString(), { untrusted });
const got = Array.isArray(body?.items) ? body.items : Array.isArray(body) ? body : [];
if (got.length === 0) break;
let fresh = 0;
@@ -291,15 +304,19 @@ export function clearCatalogCache() {
// Bazaar client. Stateless aside from the configured facilitator list.
export class Bazaar {
- constructor({ facilitators } = {}) {
- const urls = Array.isArray(facilitators) && facilitators.length ? facilitators : DEFAULT_FACILITATORS;
+ // `untrusted: true` marks a facilitator list that came from a request rather
+ // than from configuration; every fetch to it then goes through the SSRF guard.
+ constructor({ facilitators, untrusted = false } = {}) {
+ const custom = Array.isArray(facilitators) && facilitators.length;
+ const urls = custom ? facilitators : DEFAULT_FACILITATORS;
this.facilitators = urls.filter(Boolean);
+ this.untrusted = Boolean(custom && untrusted);
}
async list({ type = 'http', limit = 200, maxItems = 500 } = {}) {
const settled = await Promise.allSettled(
this.facilitators.map(async (f) => {
- const items = await listOneFacilitator(f, { type, limit, maxItems });
+ const items = await listOneFacilitator(f, { type, limit, maxItems, untrusted: this.untrusted });
const normalized = items.map((it) => normalizeItem(it, f)).filter(Boolean);
// Some facilitators (PayAI) ignore the `type` query param and return
// HTTP items regardless. Apply the filter ourselves so callers get a
diff --git a/api/_providers/rodin.js b/api/_providers/rodin.js
index 1eb8716c3..80500b69c 100644
--- a/api/_providers/rodin.js
+++ b/api/_providers/rodin.js
@@ -19,7 +19,7 @@
// BYOK only: the caller supplies their own Rodin key. No platform key — when
// absent, the forge endpoint never reaches this module.
-import { fetchUpstream } from '../_lib/upstream-fetch.js';
+import { fetchUpstream, fetchUpstreamPublic } from '../_lib/upstream-fetch.js';
const RODIN_BASE = 'https://api.hyper3d.com/api/v2';
@@ -138,7 +138,8 @@ export function createRodinProvider(apiKey) {
async imageTo3d({ imageUrl, prompt, tier }) {
let imgRes;
try {
- imgRes = await fetchUpstream(imageUrl, {}, { timeoutMs: 20_000, attempts: 2, okWhen: () => true });
+ // The reference image URL is caller-supplied: every hop is SSRF-checked.
+ imgRes = await fetchUpstreamPublic(imageUrl, {}, { timeoutMs: 20_000, attempts: 2, okWhen: () => true });
} catch (err) {
throw Object.assign(new Error(`could not fetch reference image: ${err?.message}`), {
code: 'bad_image',
diff --git a/api/_providers/stability.js b/api/_providers/stability.js
index dac870e32..9c26b458e 100644
--- a/api/_providers/stability.js
+++ b/api/_providers/stability.js
@@ -12,7 +12,7 @@
// supplies their own Stability key (sk-…); when absent the forge endpoint never
// reaches this module.
-import { fetchUpstream } from '../_lib/upstream-fetch.js';
+import { fetchUpstream, fetchUpstreamPublic } from '../_lib/upstream-fetch.js';
const STABILITY_BASE = 'https://api.stability.ai/v2beta/3d';
const ENDPOINT = 'stable-fast-3d';
@@ -33,7 +33,8 @@ export function createStabilityProvider(apiKey) {
async imageTo3d({ imageUrl, tier }) {
let imgRes;
try {
- imgRes = await fetchUpstream(imageUrl, {}, { timeoutMs: 20_000, attempts: 2, okWhen: () => true });
+ // The reference image URL is caller-supplied: every hop is SSRF-checked.
+ imgRes = await fetchUpstreamPublic(imageUrl, {}, { timeoutMs: 20_000, attempts: 2, okWhen: () => true });
} catch (err) {
throw Object.assign(new Error(`could not fetch reference image: ${err?.message}`), {
code: 'bad_image',
diff --git a/api/agent-wallet-bridge.js b/api/agent-wallet-bridge.js
index e80c01017..2af6f696a 100644
--- a/api/agent-wallet-bridge.js
+++ b/api/agent-wallet-bridge.js
@@ -21,6 +21,7 @@
import { cors, wrap, error, serverError, setRateLimitHeaders } from './_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
+import { assertBearerMaySpend } from './_lib/spend-scope.js';
import { requireCsrf } from './_lib/csrf.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { createSolanaSigner } from './_lib/x402/a2a-client.js';
@@ -37,10 +38,14 @@ const PAYER_SECRET = env.A2A_PAYER_SOLANA_SECRET || '';
const MAX_PER_CALL_MICROS = Number(process.env.AGENT_WALLET_MAX_USDC_MICROS || 100_000);
const MAX_PER_DAY_MICROS = Number(process.env.AGENT_WALLET_DAILY_USDC_MICROS || 2_000_000);
-const ALLOWED_ENDPOINT_ORIGINS = (
- process.env.AGENT_WALLET_ALLOWED_ORIGINS ||
- 'https://three.ws,http://localhost:3000,http://127.0.0.1:3000'
-)
+// Loopback origins are a development convenience only: in production the
+// container itself listens on loopback, so leaving them in the default let an
+// unauthenticated quote call reach the instance's own internal port.
+const DEFAULT_ENDPOINT_ORIGINS = env.isProduction
+ ? 'https://three.ws'
+ : 'https://three.ws,http://localhost:3000,http://127.0.0.1:3000';
+
+const ALLOWED_ENDPOINT_ORIGINS = (process.env.AGENT_WALLET_ALLOWED_ORIGINS || DEFAULT_ENDPOINT_ORIGINS)
.split(',')
.map((s) => s.trim())
.filter(Boolean);
@@ -384,7 +389,8 @@ export default wrap(async (req, res) => {
// Real USDC leaves the shared platform wallet — require a signed-in caller.
const sessionUser = await getSessionUser(req).catch(() => null);
- const bearerUser = sessionUser ? null : await authenticateBearer(extractBearer(req)).catch(() => null);
+ // Pays real USDC from the shared platform wallet: a bearer needs wallet:write.
+ const bearerUser = sessionUser ? null : assertBearerMaySpend(await authenticateBearer(extractBearer(req)).catch(() => null), req);
if (!sessionUser && !bearerUser) {
return error(res, 401, 'unauthorized', 'Sign in to let your agent wallet make a real payment.');
}
diff --git a/api/avatar/optimize.js b/api/avatar/optimize.js
index c89be07b9..0b36cefbe 100644
--- a/api/avatar/optimize.js
+++ b/api/avatar/optimize.js
@@ -115,6 +115,29 @@ function trustedOrigin(url) {
}
}
+// Fetch a source that passed trustedOrigin, following redirects by hand so
+// every hop must stay on a trusted host. With the default redirect: 'follow',
+// any first-party route that 302s to a stored or on-chain URL (a thumbnail, an
+// agent registration URI) walked this server-side fetch to an arbitrary or
+// internal host.
+const MAX_SOURCE_REDIRECTS = 3;
+
+export async function fetchTrustedSource(sourceUrl, signal) {
+ let current = sourceUrl;
+ for (let hop = 0; ; hop++) {
+ const res = await fetch(current, { signal, redirect: 'manual' });
+ const location = res.status >= 300 && res.status < 400 ? res.headers.get('location') : null;
+ if (!location) return res;
+ const next = new URL(location, current).toString();
+ if (hop >= MAX_SOURCE_REDIRECTS || !/^https:/i.test(next) || !trustedOrigin(next)) {
+ throw Object.assign(new Error('src redirected to a host that is not allowed'), {
+ code: 'untrusted_redirect',
+ });
+ }
+ current = next;
+ }
+}
+
async function resolveSource({ src, id }) {
if (src) {
if (!trustedOrigin(src)) {
@@ -409,8 +432,12 @@ export default wrap(async (req, res) => {
const fetchTimer = setTimeout(() => abort.abort(), SOURCE_FETCH_TIMEOUT_MS);
let upstream;
try {
- upstream = await fetch(sourceUrl, { signal: abort.signal });
+ upstream = await fetchTrustedSource(sourceUrl, abort.signal);
} catch (err) {
+ if (err?.code === 'untrusted_redirect') {
+ clearTimeout(fetchTimer);
+ return error(res, 400, 'untrusted_src', err.message);
+ }
clearTimeout(fetchTimer);
if (err?.name === 'AbortError') {
return error(res, 504, 'source_timeout', `source did not respond within ${SOURCE_FETCH_TIMEOUT_MS} ms`);
diff --git a/api/bazaar/list.js b/api/bazaar/list.js
index d2a44955f..0568eee73 100644
--- a/api/bazaar/list.js
+++ b/api/bazaar/list.js
@@ -52,7 +52,7 @@ async function handler(req, res) {
? facilitatorsCsv.split(',').map((s) => s.trim()).filter(Boolean)
: undefined;
- const baz = new Bazaar({ facilitators });
+ const baz = new Bazaar({ facilitators, untrusted: true });
let result;
try {
result = await baz.listCached({ type, limit, maxItems });
diff --git a/api/bazaar/search.js b/api/bazaar/search.js
index c27e78cbe..794c6ef7e 100644
--- a/api/bazaar/search.js
+++ b/api/bazaar/search.js
@@ -47,7 +47,7 @@ async function handler(req, res) {
? facilitatorsCsv.split(',').map((s) => s.trim()).filter(Boolean)
: undefined;
- const baz = new Bazaar({ facilitators });
+ const baz = new Bazaar({ facilitators, untrusted: true });
let result;
try {
result = await baz.search({ query, type, maxItems });
diff --git a/api/cron/coin-intel-observe.js b/api/cron/coin-intel-observe.js
index d1b7fe65c..2282b6639 100644
--- a/api/cron/coin-intel-observe.js
+++ b/api/cron/coin-intel-observe.js
@@ -22,6 +22,7 @@ import { finalizeObservation } from '../../workers/agent-sniper/intel/finalize.j
import { pumpPortalWsUrl, handlePumpPortalAck } from '../_lib/pumpportal.js';
import { subscribePumpOnchainTrades } from '../_lib/pump-onchain-trades.js';
import { requireCron } from '../_lib/cron-auth.js';
+import { fetchSafePublicUrlPinned } from '../_lib/ssrf-guard.js';
const LAMPORTS_PER_SOL = 1_000_000_000;
const NETWORK = 'mainnet';
@@ -42,7 +43,13 @@ async function fetchMeta(uri) {
try {
const ctrl = new AbortController();
const tid = setTimeout(() => ctrl.abort(), META_TIMEOUT_MS);
- const r = await fetch(uri, { signal: ctrl.signal });
+ // The uri is chosen by whoever launched the coin, so it is read through
+ // the pinned SSRF guard (no private or metadata address on any hop).
+ const r = await fetchSafePublicUrlPinned(
+ uri,
+ { signal: ctrl.signal, headers: { accept: 'application/json' } },
+ { allowHttp: true, maxBytes: 256 * 1024 },
+ );
clearTimeout(tid);
if (!r.ok) return null;
const d = await r.json();
diff --git a/tests/ssrf-hardening-guards.test.js b/tests/ssrf-hardening-guards.test.js
new file mode 100644
index 000000000..921867d6c
--- /dev/null
+++ b/tests/ssrf-hardening-guards.test.js
@@ -0,0 +1,262 @@
+// SSRF and open-redirect regressions closed in the October 2026 audit.
+//
+// Each case here was a live path: an IPv6 spelling of loopback that the
+// classifiers waved through, a metadata URI fetched with no guard, a forge
+// self-call whose host came from `x-forwarded-host`, the NVIDIA key sent to a
+// caller-chosen NIM, a headless browser that followed redirects into the VPC,
+// and a Vertex model id that could walk an authenticated POST to another API.
+// Everything runs offline: blocked targets are refused before a socket opens.
+
+import { Readable } from 'node:stream';
+import { describe, it, expect, vi, afterEach } from 'vitest';
+
+import { isPrivateIPv6, isPrivateAddress, parseIPv6Groups } from '../api/_lib/ssrf.js';
+import { fetchSafePublicUrlPinned, SsrfBlockedError } from '../api/_lib/ssrf-guard.js';
+import { fetchOgImage } from '../api/_lib/og-avatar.js';
+import { fetchTokenImage } from '../api/_lib/solana-token-meta.js';
+import { selfOrigin } from '../api/_lib/self-origin.js';
+import { guardPageRequests } from '../api/_lib/embed-doctor.js';
+import { vertexMessagesUrl, isVertexModelId } from '../api/_lib/vertex-claude.js';
+
+const realFetch = globalThis.fetch;
+afterEach(() => {
+ globalThis.fetch = realFetch;
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+});
+
+describe('IPv6 classification judges the address, not its spelling', () => {
+ it('blocks every spelling of an internal IPv4 carried in IPv6', () => {
+ for (const ip of [
+ '::ffff:7f00:1', // hex-mapped loopback, the form the URL parser emits
+ '::ffff:127.0.0.1',
+ '::ffff:a9fe:a9fe', // 169.254.169.254
+ '::ffff:0:7f00:1', // IPv4-translated
+ '::127.0.0.1', // IPv4-compatible
+ '64:ff9b::a9fe:a9fe', // NAT64 of the metadata server
+ '2002:7f00:1::1', // 6to4 of loopback
+ '[::ffff:7f00:1]',
+ ]) {
+ expect(isPrivateIPv6(ip), ip).toBe(true);
+ }
+ });
+
+ it('blocks the native internal ranges and anything unparseable', () => {
+ for (const ip of ['::1', '::', 'fe80::1%eth0', 'fd00:ec2::254', 'fc00::1', 'ff02::1', '2001:db8::1', 'not-an-ip', '1:2:3:4:5:6:7:8:9']) {
+ expect(isPrivateIPv6(ip), ip).toBe(true);
+ }
+ });
+
+ it('leaves public addresses alone', () => {
+ for (const ip of ['2606:4700::1111', '2001:4860:4860::8888', '64:ff9b::808:808', '2002:808:808::1', '::ffff:8.8.8.8']) {
+ expect(isPrivateIPv6(ip), ip).toBe(false);
+ }
+ expect(isPrivateAddress('8.8.8.8', 4)).toBe(false);
+ });
+
+ it('expands compressed forms to eight groups', () => {
+ expect(parseIPv6Groups('::ffff:127.0.0.1')).toEqual([0, 0, 0, 0, 0, 0xffff, 0x7f00, 1]);
+ expect(parseIPv6Groups('fe80::1')).toEqual([0xfe80, 0, 0, 0, 0, 0, 0, 1]);
+ });
+});
+
+describe('pinned guard refuses internal literals before connecting', () => {
+ it.each(['http://127.0.0.1/', 'http://169.254.169.254/computeMetadata/v1/', 'https://10.0.0.5/x', 'http://0.0.0.0/'])(
+ '%s',
+ async (url) => {
+ await expect(fetchSafePublicUrlPinned(url, {}, { allowHttp: true })).rejects.toBeInstanceOf(SsrfBlockedError);
+ },
+ );
+});
+
+describe('creator-chosen image and metadata URLs go through the guard', () => {
+ it('fetchOgImage refuses an internal URL without touching the network', async () => {
+ const spy = vi.fn();
+ globalThis.fetch = spy;
+ expect(await fetchOgImage('http://169.254.169.254/latest/meta-data/')).toBeNull();
+ expect(await fetchOgImage('http://127.0.0.1:8080/api/healthz')).toBeNull();
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ it('fetchTokenImage refuses an internal URL without touching the network', async () => {
+ const spy = vi.fn();
+ globalThis.fetch = spy;
+ expect(await fetchTokenImage('http://10.0.0.5/logo.png')).toBeNull();
+ expect(spy).not.toHaveBeenCalled();
+ });
+});
+
+describe('selfOrigin never trusts a forwarded host', () => {
+ it('ignores x-forwarded-host and a foreign Host header', () => {
+ vi.stubEnv('PUBLIC_APP_ORIGIN', 'https://three.ws');
+ expect(selfOrigin({ headers: { host: 'three.ws', 'x-forwarded-host': 'attacker.example' } })).toBe('https://three.ws');
+ expect(selfOrigin({ headers: { host: '169.254.169.254' } })).toBe('https://three.ws');
+ });
+
+ it('honors a loopback Host only outside production', () => {
+ vi.stubEnv('PUBLIC_APP_ORIGIN', 'https://three.ws');
+ vi.stubEnv('NODE_ENV', 'development');
+ expect(selfOrigin({ headers: { host: 'localhost:3000' } })).toBe('http://localhost:3000');
+ vi.stubEnv('NODE_ENV', 'production');
+ expect(selfOrigin({ headers: { host: '127.0.0.1:8080' } })).toBe('https://three.ws');
+ });
+});
+
+describe('forge-nim never sends the platform key to a caller-chosen NIM', () => {
+ function makeReq(url) {
+ const stream = Readable.from([]);
+ stream.method = 'GET';
+ stream.url = url;
+ stream.headers = { host: 'three.ws' };
+ return stream;
+ }
+ function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ setHeader(k, v) {
+ this._h[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this._h[k.toLowerCase()];
+ },
+ end(body) {
+ this._body = body;
+ this.writableEnded = true;
+ },
+ };
+ }
+
+ it('health against a caller baseUrl uses the guard with no authorization header', async () => {
+ vi.stubEnv('NVIDIA_API_KEY', 'nvapi-secret-should-not-leak');
+ const plain = vi.fn();
+ globalThis.fetch = plain;
+ const pinned = vi.fn(async () => new Response('', { status: 200 }));
+ vi.resetModules();
+ vi.doMock('../api/_lib/ssrf-guard.js', async (orig) => ({ ...(await orig()), fetchSafePublicUrlPinned: pinned }));
+ const { default: handler } = await import('../api/forge-nim.js');
+ const res = makeRes();
+ await handler(makeReq('/api/forge-nim?action=health&baseUrl=https://attacker.example'), res);
+ vi.doUnmock('../api/_lib/ssrf-guard.js');
+
+ expect(plain).not.toHaveBeenCalled();
+ expect(pinned).toHaveBeenCalledOnce();
+ const [url, init] = pinned.mock.calls[0];
+ expect(url).toBe('https://attacker.example/v1/health/ready');
+ expect(JSON.stringify(init.headers || {})).not.toContain('nvapi-secret-should-not-leak');
+ });
+});
+
+describe('embed doctor routes every page request through the guard', () => {
+ function fakePage() {
+ const handlers = [];
+ return {
+ handlers,
+ setRequestInterception: vi.fn(async () => {}),
+ on(event, fn) {
+ if (event === 'request') handlers.push(fn);
+ },
+ };
+ }
+ function fakeReq(url) {
+ return { url: () => url, continue: vi.fn(async () => {}), abort: vi.fn(async () => {}) };
+ }
+
+ it('aborts internal hosts, redirects included, and lets the platform origin through', async () => {
+ const page = fakePage();
+ await guardPageRequests(page, { platformOrigin: 'http://localhost:3000' });
+ expect(page.setRequestInterception).toHaveBeenCalledWith(true);
+ const [handler] = page.handlers;
+
+ const metadata = fakeReq('http://169.254.169.254/computeMetadata/v1/');
+ await handler(metadata);
+ expect(metadata.abort).toHaveBeenCalled();
+ expect(metadata.continue).not.toHaveBeenCalled();
+
+ const internal = fakeReq('http://10.0.0.5:8080/admin');
+ await handler(internal);
+ expect(internal.abort).toHaveBeenCalled();
+
+ const file = fakeReq('file:///etc/passwd');
+ await handler(file);
+ expect(file.abort).toHaveBeenCalled();
+
+ const platform = fakeReq('http://localhost:3000/agent-3d/latest/agent-3d.js');
+ await handler(platform);
+ expect(platform.continue).toHaveBeenCalled();
+
+ const inline = fakeReq('data:image/png;base64,AAAA');
+ await handler(inline);
+ expect(inline.continue).toHaveBeenCalled();
+ });
+
+ it('lets a caller-provided responder claim a request first', async () => {
+ const page = fakePage();
+ const respond = vi.fn((req) => req.url() === 'https://three.ws/__embed-doctor-sandbox');
+ await guardPageRequests(page, { platformOrigin: 'https://three.ws', respond });
+ const req = fakeReq('https://three.ws/__embed-doctor-sandbox');
+ await page.handlers[0](req);
+ expect(respond).toHaveBeenCalled();
+ expect(req.continue).not.toHaveBeenCalled();
+ expect(req.abort).not.toHaveBeenCalled();
+ });
+});
+
+describe('Vertex model ids cannot leave the model path', () => {
+ it('accepts real model ids', () => {
+ expect(isVertexModelId('claude-haiku-4-5-20251001')).toBe(true);
+ expect(isVertexModelId('claude-sonnet-4-5')).toBe(true);
+ });
+
+ it('refuses traversal, query and fragment injection', () => {
+ vi.stubEnv('GOOGLE_CLOUD_PROJECT', 'p');
+ for (const bad of ['../../../../datasets?a=', 'x/../../y', 'claude#frag', 'claude?x=1', '']) {
+ expect(isVertexModelId(bad), bad).toBe(false);
+ expect(() => vertexMessagesUrl(bad)).toThrow(/invalid Vertex model id/);
+ }
+ });
+});
+
+describe('avatar optimize keeps every redirect hop on a trusted host', () => {
+ it('refuses a first-party URL that redirects off the allowlist', async () => {
+ vi.stubEnv('PUBLIC_APP_ORIGIN', 'https://three.ws');
+ const { fetchTrustedSource } = await import('../api/avatar/optimize.js');
+ const spy = vi.fn(async () => new Response(null, { status: 302, headers: { location: 'http://169.254.169.254/computeMetadata/v1/' } }));
+ globalThis.fetch = spy;
+ await expect(fetchTrustedSource('https://three.ws/api/agent-og?id=x', undefined)).rejects.toMatchObject({
+ code: 'untrusted_redirect',
+ });
+ expect(spy).toHaveBeenCalledOnce();
+ expect(spy.mock.calls[0][1]).toMatchObject({ redirect: 'manual' });
+ });
+
+ it('follows a redirect that stays on the platform origin', async () => {
+ vi.stubEnv('PUBLIC_APP_ORIGIN', 'https://three.ws');
+ const { fetchTrustedSource } = await import('../api/avatar/optimize.js');
+ globalThis.fetch = vi
+ .fn()
+ .mockResolvedValueOnce(new Response(null, { status: 301, headers: { location: '/cdn/u/1/a.glb' } }))
+ .mockResolvedValueOnce(new Response('glb', { status: 200 }));
+ const res = await fetchTrustedSource('https://three.ws/cdn/u/1/a.glb/', undefined);
+ expect(res.status).toBe(200);
+ });
+});
+
+describe('fetchUpstreamPublic re-checks every redirect hop', () => {
+ it('refuses a public URL that 302s to the metadata server', async () => {
+ const { fetchUpstreamPublic } = await import('../api/_lib/upstream-fetch.js');
+ const spy = vi.fn(async () => new Response(null, { status: 302, headers: { location: 'http://169.254.169.254/computeMetadata/v1/' } }));
+ globalThis.fetch = spy;
+ await expect(fetchUpstreamPublic('https://8.8.8.8/logo.png', {}, { attempts: 1, allowHttp: true })).rejects.toMatchObject({ code: 'ssrf_blocked' });
+ expect(spy).toHaveBeenCalledOnce();
+ expect(spy.mock.calls[0][1]).toMatchObject({ redirect: 'manual' });
+ });
+
+ it('refuses an internal first hop before any request', async () => {
+ const { fetchUpstreamPublic } = await import('../api/_lib/upstream-fetch.js');
+ const spy = vi.fn();
+ globalThis.fetch = spy;
+ await expect(fetchUpstreamPublic('http://10.1.2.3/x', {}, { allowHttp: true })).rejects.toMatchObject({ code: 'ssrf_blocked' });
+ expect(spy).not.toHaveBeenCalled();
+ });
+});