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
fix(ssrf): fetch remote avatar-stream, NFT metadata and model-check URLs through the pinned guard
nirholasad776da674e0
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 2dedbf96a..b5e93f96f 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -1389,6 +1389,9 @@ export const limits = {// still stops a scripted flood. Page-load-critical clusters additionally get// their own dedicated buckets below so one surface can never starve another.publicIp: (ip) => getLimiter('public:ip', { limit: 240, window: '1 m', local: true }).limit(ip),+ // /api/avatar-stream with a remote ?src: one download (up to 64 MB) and one+ // CPU-bound pack per distinct URL, so it is held well under publicIp.+ avatarStreamRemoteIp: (ip) => getLimiter('avatar-stream:remote:ip', { limit: 20, window: '1 m' }).limit(ip),// Fiat onramp checkout links (/api/onramp/link). Unlike the generic public read,// each configured call mints a single-use session token against Coinbase's CDP// API, so an unauthenticated flood here is upstream quota burn, not just our CPU.diff --git a/api/avatar-stream.js b/api/avatar-stream.jsindex fb7c7f0e3..5486ab9f5 100644--- a/api/avatar-stream.js+++ b/api/avatar-stream.js@@ -18,7 +18,9 @@ import { createHash } from 'node:crypto';import { readFile } from 'node:fs/promises';import { join, normalize } from 'node:path';-import { cors, error, json, method, wrap } from './_lib/http.js';+import { cors, error, json, method, rateLimited, wrap } from './_lib/http.js';+import { clientIp, limits } from './_lib/rate-limit.js';+import { fetchModel } from './_lib/fetch-model.js';import { pack } from '../packages/avatar-stream/src/pack.js';import { decodeHeader, decodePreamble } from '../packages/avatar-stream/src/format.js';@@ -43,21 +45,33 @@ function cacheSet(key, value) {while (cache.size > CACHE_LIMIT) cache.delete(cache.keys().next().value);}+// Remote sources are avatars, not archives: anything past this is refused+// mid-stream rather than buffered.+const MAX_REMOTE_BYTES = 64 * 1024 * 1024;+const CALLER_FAULT_CODES = new Set(['invalid_url', 'scheme_not_allowed', 'private_address', 'host_pin_mismatch']);+/*** Resolve `src` to GLB bytes.** A site-relative path is read off disk, which keeps the platform's own avatars- * off the network. An absolute URL is fetched, and is restricted to https so- * this endpoint cannot be pointed at a private address by a caller.+ * off the network. An absolute URL must be https and is fetched through the+ * SSRF-guarded model fetcher (api/_lib/fetch-model.js).*/async function loadSource(src) {if (/^https:\/\//i.test(src)) {- // Caller-supplied source URL: bounded so a host that accepts the connection- // and then stalls cannot hold the frame request open until the platform- // kills it. SSRF validation happens above; this is the time budget.- const response = await fetch(src, { redirect: 'follow', signal: AbortSignal.timeout(20_000) });- if (!response.ok) throw Object.assign(new Error(`upstream ${response.status}`), { status: 502 });- return new Uint8Array(await response.arrayBuffer());+ // Caller-supplied source URL, so it goes through fetchModel: the host is+ // resolved on our side and refused if any address is private, loopback+ // or metadata, the socket is pinned to the validated address, every+ // redirect hop is re-checked, and the body is capped while streaming.+ // The timeout keeps a stalled host from holding the request open.+ try {+ const { bytes } = await fetchModel(src, { maxBytes: MAX_REMOTE_BYTES, timeoutMs: 20_000 });+ return bytes;+ } catch (err) {+ const code = err?.code || 'fetch_failed';+ const status = code === 'file_too_large' ? 413 : CALLER_FAULT_CODES.has(code) ? 400 : 502;+ throw Object.assign(new Error(err?.message || 'could not fetch src'), { status });+ }}if (!src.startsWith('/')) {throw Object.assign(new Error('src must be a site-relative path or an https URL'), { status: 400 });@@ -128,6 +142,12 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://localhost');const src = url.searchParams.get('src') || '';if (!src) return error(res, 400, 'missing_src', 'pass ?src=<path or https url to a .glb>');+ // A remote source costs a download plus a CPU-bound pack per distinct URL,+ // and the cache holds only a dozen, so remote packs get their own budget.+ if (/^https:\/\//i.test(src)) {+ const rl = await limits.avatarStreamRemoteIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl, 'too many remote avatar packs; try again shortly');+ }let entry;try {diff --git a/api/nft/resolve.js b/api/nft/resolve.jsindex 1823b19f9..87132ac7b 100644--- a/api/nft/resolve.js+++ b/api/nft/resolve.js@@ -4,6 +4,7 @@ import { cacheGet, cacheSet } from '../_lib/cache.js';import { dasRpcUrl } from '../_lib/nft-gate.js';import { resolveGateway } from '../_lib/solana-agents-normalize.js';import { fetchTokenMeta } from '../_lib/solana-token-meta.js';+import { fetchSafePublicUrlPinned } from '../_lib/ssrf-guard.js';import {evmFallbackProvider,evmRpcEndpoints,@@ -68,11 +69,14 @@ async function fetchMetadataDoc(uri) {if (!url || !/^https?:\/\//i.test(url)) return null;let resp;try {- resp = await fetch(url, {- redirect: 'follow',- headers: { accept: 'application/json' },- signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),- });+ // tokenURI is whatever the contract (anyone's contract) returns, so the+ // document is read through the pinned SSRF guard: private and metadata+ // addresses are refused on every redirect hop, bytes capped in-stream.+ resp = await fetchSafePublicUrlPinned(+ url,+ { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) },+ { allowHttp: true, maxBytes: MAX_METADATA_BYTES },+ );} catch {return null;}diff --git a/api/x402/model-check.js b/api/x402/model-check.jsindex de36e806e..14704e35e 100644--- a/api/x402/model-check.js+++ b/api/x402/model-check.js@@ -29,7 +29,12 @@ import {buildBazaarSchema,} from '../_lib/x402-spec.js';import { inspectModel, suggestOptimizations } from '../_lib/model-inspect.js';-import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';+import {+ assertSafePublicUrl,+ fetchSafePublicUrlPinned,+ MaxBytesExceededError,+ SsrfBlockedError,+} from '../_lib/ssrf-guard.js';import {PAYMENT_IDENTIFIER,checkCache,@@ -197,14 +202,32 @@ async function fetchAndInspect(targetUrl) {}throw err;}+ // Pinned fetch: each redirect hop is re-validated and the socket connects to+ // the checked address, so a public URL that 302s (or rebinds) to an+ // internal host is refused instead of followed. Bytes are capped in-stream.let upstream;try {- upstream = await fetch(parsed.toString(), {- redirect: 'follow',- headers: { accept: 'model/gltf-binary,model/gltf+json,application/octet-stream' },- signal: AbortSignal.timeout(20_000),- });+ upstream = await fetchSafePublicUrlPinned(+ parsed.toString(),+ {+ headers: { accept: 'model/gltf-binary,model/gltf+json,application/octet-stream' },+ signal: AbortSignal.timeout(20_000),+ },+ { allowHttp: true, maxBytes: MAX_FETCH_BYTES },+ );} catch (err) {+ if (err instanceof SsrfBlockedError) {+ const e = new Error(err.message);+ e.code = 'invalid_url';+ e.status = 400;+ throw e;+ }+ if (err instanceof MaxBytesExceededError) {+ const e = new Error(`model is ${err.observed} bytes; max is ${MAX_FETCH_BYTES}`);+ e.code = 'too_large';+ e.status = 413;+ throw e;+ }const e = new Error(`could not fetch model: ${err.message}`);e.code = 'fetch_failed';e.status = 502;