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
Profile fields + user-follows migration; SSRF/http/forge-store hardening
nirholas86548c9ceb9f
diff --git a/api/_lib/a2a/reputation-gate.js b/api/_lib/a2a/reputation-gate.jsindex cc2ff1e72..2f2017687 100644--- a/api/_lib/a2a/reputation-gate.js+++ b/api/_lib/a2a/reputation-gate.js@@ -3,13 +3,11 @@//// Trust is the missing half of autonomous payments: budget caps stop an agent// overspending, but they don't stop it paying a scammer. ERC-8004's Reputation-// Registry is the standard trust signal; this module reads it server-side and-// enforces a minimum average score and/or minimum review count before a-// mandate-authorized payment is allowed to proceed. It is the throwing wrapper-// around the shared open-network bouncer (../trust/agent-bouncer.js) — same-// canonical, correctly-decoded read the public /api/x402/agent-bouncer endpoint-// uses, so the autonomous-payment door and the public door can never drift on-// who is trustworthy.+// Registry is the standard EVM trust signal; this module reads it server-side+// and enforces a minimum average score and/or minimum review count before a+// mandate-authorized payment is allowed to proceed. (Its Solana counterpart —+// vetting a three.ws agent by its on-chain Solana track record — is+// ../trust/solana-bouncer.js, exposed publicly at /api/x402/agent-bouncer.)//// The read goes through the curated multi-RPC failover in api/_lib/evm/rpc.js// (honoring A2A_REPUTATION_RPC_URL as the pinned primary when set), so the gatediff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.jsindex 5bee64f03..a4f33ba6c 100644--- a/api/_lib/forge-store.js+++ b/api/_lib/forge-store.js@@ -128,14 +128,45 @@ export async function findByJob({ replicateJobId, clientKey }) {}}+// Provider asset URLs are frequently short-lived (HuggingFace Spaces serve the+// mesh from an ephemeral gradio /tmp path; CDNs hiccup). Pull the bytes with a+// few quick retries so a transient network error or 5xx/429 — the dominant cause+// of "materializeCreation failed: 404/5xx" in the logs — doesn't permanently lose+// a generation. A hard 404/410 means the file is already gone, so retrying is+// pointless: fail fast on those and let the caller fall back to the provider URL.+const COPY_MAX_ATTEMPTS = 3;+const COPY_RETRY_BASE_MS = 400;+async function copyToBucket({ sourceUrl, key, fallbackContentType, maxBytes }) {- const resp = await fetch(sourceUrl);- if (!resp.ok) throw new Error(`fetch ${sourceUrl}: ${resp.status}`);- const buf = Buffer.from(await resp.arrayBuffer());- if (buf.length > maxBytes) throw new Error(`asset too large: ${buf.length} bytes`);- const contentType = resp.headers.get('content-type') || fallbackContentType;- await putObject({ key, body: buf, contentType, metadata: { source: 'forge' } });- return { bytes: buf.length, publicUrl: publicUrl(key) };+ let lastErr;+ for (let attempt = 1; attempt <= COPY_MAX_ATTEMPTS; attempt++) {+ try {+ const resp = await fetch(sourceUrl);+ if (!resp.ok) {+ const err = new Error(`fetch ${sourceUrl}: ${resp.status}`);+ err.status = resp.status;+ // 404/410 = the ephemeral asset has already expired; no retry can recover it.+ if (resp.status === 404 || resp.status === 410) throw err;+ // 408/425/429/5xx are transient — retry within the loop.+ if (attempt < COPY_MAX_ATTEMPTS) { lastErr = err; }+ else throw err;+ } else {+ const buf = Buffer.from(await resp.arrayBuffer());+ if (buf.length > maxBytes) throw new Error(`asset too large: ${buf.length} bytes`);+ const contentType = resp.headers.get('content-type') || fallbackContentType;+ await putObject({ key, body: buf, contentType, metadata: { source: 'forge' } });+ return { bytes: buf.length, publicUrl: publicUrl(key) };+ }+ } catch (err) {+ // Permanent (404/410) or too-large: surface immediately. Network errors+ // (fetch throw) are transient and retried until attempts are exhausted.+ if (err?.status === 404 || err?.status === 410 || /asset too large/.test(err?.message || '')) throw err;+ lastErr = err;+ if (attempt >= COPY_MAX_ATTEMPTS) throw err;+ }+ await new Promise((r) => setTimeout(r, COPY_RETRY_BASE_MS * attempt));+ }+ throw lastErr;}function imageExtFor(url) {@@ -213,7 +244,14 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl })});return { id: existing.id, glbUrl: glb.publicUrl, previewImageUrl: preview.url };} catch (err) {- console.error('[forge-store] materializeCreation failed:', err?.message);+ // A 404/410 means the provider's ephemeral asset (e.g. a HuggingFace Space's+ // gradio /tmp mesh) expired before we could copy it — expected and fully+ // handled here by returning null so the caller falls back to the provider+ // URL. Log it at WARN so it doesn't flood the actionable-error view; genuine+ // failures (storage write, oversize, 5xx after retries) stay at ERROR.+ const recoverable = err?.status === 404 || err?.status === 410;+ const log = recoverable ? console.warn : console.error;+ log('[forge-store] materializeCreation failed:', err?.message);return null;}}diff --git a/api/_lib/http.js b/api/_lib/http.jsindex 489d3c17f..cabe4ee1e 100644--- a/api/_lib/http.js+++ b/api/_lib/http.js@@ -26,6 +26,15 @@ function applyCacheControl(res, headers) {}export function json(res, status, body, headers = {}) {+ // Once the response is committed (a handler already streamed/wrote a head, or+ // an error path fires after a success path), setting headers again throws+ // ERR_HTTP_HEADERS_SENT and crashes the invocation. The first response stands;+ // a second send is always a bug whose only safe outcome is a no-op. Guard here+ // so this can never escalate a benign double-send into an unhandled 500.+ if (res.headersSent || res.writableEnded) {+ if (!res.writableEnded) res.end();+ return;+ }res.statusCode = status;res.setHeader('content-type', 'application/json; charset=utf-8');applyCacheControl(res, headers);diff --git a/api/_lib/migrations/20260622000000_profile_fields_and_user_follows.sql b/api/_lib/migrations/20260622000000_profile_fields_and_user_follows.sqlnew file mode 100644index 000000000..577476840--- /dev/null+++ b/api/_lib/migrations/20260622000000_profile_fields_and_user_follows.sql@@ -0,0 +1,37 @@+-- Migration: profile free-text fields + the user_follows social graph.+--+-- These objects were defined in api/_lib/schema.sql but never carried their own+-- migration, so production databases provisioned before they were added to the+-- base schema are missing them. That surfaced as live 500s in the logs:+--+-- NeonDbError: column "bio" does not exist (api/users/:username/follows.js, profile reads)+-- NeonDbError: relation "user_follows" does not exist (follow toggle, feed fan-out, counts)+--+-- apply-migrations.mjs only runs api/_lib/migrations/*.sql — it does NOT re-apply+-- schema.sql — so the fix has to live here. Everything is `if not exists`, so this+-- is safe on databases that already have some or all of these from a schema.sql run.+begin;++-- ── Profile free-text fields (set via PATCH /api/auth/profile) ────────────────+-- All nullable; a profile with none set still renders from the user's content.+alter table users add column if not exists bio text;+alter table users add column if not exists website text;+alter table users add column if not exists location text;+alter table users add column if not exists banner_url text;++-- ── user_follows — the directed social graph ─────────────────────────────────+-- follower_id follows following_id. Composite PK makes a follow idempotent (one+-- edge per pair) and the toggle a single upsert/delete. The check blocks+-- self-follows at the storage layer. Two covering indexes back the hot reads:+-- "who follows X" and "who X follows" (incl. the feed fan-out join).+create table if not exists user_follows (+ follower_id uuid not null references users(id) on delete cascade,+ following_id uuid not null references users(id) on delete cascade,+ created_at timestamptz not null default now(),+ primary key (follower_id, following_id),+ check (follower_id <> following_id)+);+create index if not exists user_follows_following on user_follows(following_id, created_at desc);+create index if not exists user_follows_follower on user_follows(follower_id, created_at desc);++commit;diff --git a/api/_lib/ssrf.js b/api/_lib/ssrf.jsindex 9295baeea..64dab96de 100644--- a/api/_lib/ssrf.js+++ b/api/_lib/ssrf.js@@ -70,15 +70,36 @@ export function isPrivateAddress(address, family) {return true; // unknown family → unsafe}+// node:dns/promises `lookup` accepts no AbortSignal and no timeout, so a stalled+// system resolver (a dead host whose DNS hangs rather than NXDOMAINs) blocks+// forever — and because the lookup is not tied to any fetch AbortController, the+// caller's request timeout never fires either, pinning the whole serverless+// invocation to its hard kill (the root cause of mass /api/img 30s timeouts).+// Bound every resolution with our own timer so a hung resolver fails fast and+// the caller can fall through to its next candidate or placeholder.+const DNS_TIMEOUT_MS = 4_000;+// Resolve `host` once, reject if ANY resolved address is private, and return the// validated address list to pin the connection to.-export async function resolvePublicHost(host) {+export async function resolvePublicHost(host, { dnsTimeoutMs = DNS_TIMEOUT_MS } = {}) {if (!host) throw new SsrfError('missing host', 'invalid_url');let resolved;+ let timer;try {- resolved = await lookup(host, { all: true });- } catch {+ resolved = await Promise.race([+ lookup(host, { all: true }),+ new Promise((_, reject) => {+ timer = setTimeout(+ () => reject(new SsrfError(`DNS lookup timed out for ${host}`, 'dns_timeout')),+ dnsTimeoutMs,+ );+ }),+ ]);+ } catch (err) {+ if (err instanceof SsrfError) throw err;throw new SsrfError(`DNS lookup failed for ${host}`, 'dns_failed');+ } finally {+ clearTimeout(timer);}const addrs = Array.isArray(resolved) ? resolved : [resolved];if (!addrs.length) throw new SsrfError(`DNS lookup failed for ${host}`, 'dns_failed');diff --git a/api/agent-wallet-bridge.js b/api/agent-wallet-bridge.jsindex 9be985110..1d84b25b0 100644--- a/api/agent-wallet-bridge.js+++ b/api/agent-wallet-bridge.js@@ -257,8 +257,13 @@ export default wrap(async (req, res) => {// ── STATUS (public, read-only) ────────────────────────────────────────if (req.method === 'GET' && url.searchParams.get('status') === '1') {try {+ // Resolve the async payload BEFORE committing headers — writing the head+ // first and awaiting inside res.end() means a rejected walletStatus() lands+ // in the catch with headers already sent, turning a clean 503 into an+ // ERR_HTTP_HEADERS_SENT crash.+ const status = await walletStatus();res.writeHead(200, { 'content-type': 'application/json', 'access-control-allow-origin': '*' });- res.end(JSON.stringify(await walletStatus()));+ res.end(JSON.stringify(status));} catch (err) {error(res, 503, 'wallet_unavailable', err.message);}diff --git a/api/img.js b/api/img.jsindex ca6657505..7d6109003 100644--- a/api/img.js+++ b/api/img.js@@ -31,27 +31,42 @@ import { fetchModel } from './_lib/fetch-model.js';import { safeFetchJson } from './_lib/ssrf.js';const MAX_BYTES = 8 * 1024 * 1024; // 8 MB — generous for token art, bounded for abuse-const TIMEOUT_MS = 10_000;+// Per-gateway attempt cap. Each candidate fetch (DNS + connect + body) is bounded+// by this via the SSRF fetcher's own AbortController. Because the candidates are+// raced CONCURRENTLY (below), the whole resolution finishes in roughly one+// attempt's time — not the sum — so one stalled gateway never stacks toward the+// function's 30s kill, which is what produced the mass-504 storm.+const TIMEOUT_MS = 9_000;// Token launch metadata (pump.fun et al.) is a small JSON doc whose `image`// field is the real art. Resolving it server-side lets the browser load token// images same-origin without the per-host CORS failures that a client-side// `fetch(metadataUri)` hits. Kept short — the JSON is tiny.const META_TIMEOUT_MS = 5_000;-// Overall budget for ALL gateway attempts combined. The function's Vercel-// maxDuration is 30s; trying 4 IPFS gateways at 10s each can reach 40s and get-// the invocation killed BEFORE the placeholder redirect below ever runs —-// defeating the "always hand back a valid 200" contract. Cap the total spend so-// we always have time left to redirect to the placeholder.-const TOTAL_BUDGET_MS = 24_000;--// Public IPFS gateways tried in order. ipfs.io is the canonical resolver the-// rest of the platform pins to (api/_lib/onchain.js), but it is also the one-// most likely to ORB-block or stall, so we fan out to mirrors on failure.+// Overall budget for ALL upstream work combined — metadata resolution AND every+// gateway attempt. The function's Vercel maxDuration is 30s; trying 4 IPFS+// gateways at 10s each can reach 40s, and a slow metadata fetch (5s) layered on+// top of a 24s gateway budget reaches 29s + teardown and gets the invocation+// killed BEFORE the placeholder redirect below ever runs — defeating the+// "always hand back a valid 200" contract. A single deadline anchored at handler+// start, capped well under 30s, keeps meta + gateways + the placeholder response+// inside the hard kill no matter how the time is split between the two phases.+const TOTAL_BUDGET_MS = 25_000;+// Headroom reserved below the deadline so there is always time to compose and+// flush the placeholder SVG (or the real image) after the last upstream attempt.+const RESPONSE_HEADROOM_MS = 1_000;++// Public IPFS gateways. ipfs.io is the canonical resolver the rest of the platform+// pins to (api/_lib/onchain.js) but is also the one most likely to ORB-block or+// stall, so we fan out across healthy mirrors and race them — the first to return a+// valid image wins. cloudflare-ipfs.com is intentionally absent: Cloudflare sunset+// its public IPFS gateway, so every request to it is a guaranteed failure that only+// wastes a connection.const IPFS_GATEWAYS = ['https://ipfs.io/ipfs/',- 'https://cloudflare-ipfs.com/ipfs/',- 'https://gateway.pinata.cloud/ipfs/','https://dweb.link/ipfs/',+ 'https://gateway.pinata.cloud/ipfs/',+ 'https://w3s.link/ipfs/',+ 'https://4everland.io/ipfs/',];// Pull the `<cid>/<path?>` portion out of any recognised IPFS URL form so we can@@ -70,6 +85,41 @@ function candidates(rawUrl) {return [rawUrl.startsWith('ipfs://') ? IPFS_GATEWAYS[0] + rawUrl.slice(7) : rawUrl];}+// Race every candidate gateway concurrently and resolve with the FIRST one that+// returns a real image. Resolves to null when all candidates fail, OR when the+// shared `budgetMs` elapses — whichever comes first — so a stalled gateway can+// never pin the invocation toward the 30s wall. The losing fetches are each+// independently time-boxed by `perAttemptMs` (the SSRF fetcher aborts them), so+// they cannot outlive the request in any meaningful way. This concurrency is the+// fix for the sequential ipfs.io stall storm: total wall time is now ~one attempt,+// not the sum of all four.+function raceImageCandidates(urls, perAttemptMs, budgetMs) {+ if (!urls.length || budgetMs < 250) return Promise.resolve(null);+ return new Promise((resolve) => {+ let settled = false;+ let pending = urls.length;+ const finish = (img) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolve(img);+ };+ const timer = setTimeout(() => finish(null), budgetMs);+ for (const url of urls) {+ fetchModel(url, { maxBytes: MAX_BYTES, timeoutMs: Math.min(perAttemptMs, budgetMs) })+ .then((result) => {+ if (result?.contentType?.startsWith('image/')) finish(result);+ else if (--pending === 0) finish(null); // valid response but not an image+ })+ .catch(() => {+ // SSRF refusal, timeout, gateway 5xx — this candidate is out. Only+ // give up once every candidate has settled.+ if (--pending === 0) finish(null);+ });+ }+ });+}+// Deterministic, dependency-free placeholder art. The same seed always renders// the same image, so a given token's fallback is stable across loads and the// edge cache stays warm. Derives a two-tone palette + accent from a hash of the@@ -139,9 +189,9 @@ function placeholderSvg(seed) {// (b) accept only an http(s) image URL — data: images are rejected so we never// serve attacker-supplied inline content from our own origin, and (c) return// null on any failure so the caller falls through to the on-brand placeholder.-async function resolveImageFromMeta(metaUri) {+async function resolveImageFromMeta(metaUri, timeoutMs = META_TIMEOUT_MS) {try {- const { ok, data } = await safeFetchJson(metaUri, { timeoutMs: META_TIMEOUT_MS });+ const { ok, data } = await safeFetchJson(metaUri, { timeoutMs });if (!ok || !data || typeof data !== 'object') return null;const candidate = data.image || data.image_url || data.imageUrl || data.imageUri || null;if (typeof candidate !== 'string') return null;@@ -184,34 +234,30 @@ export default wrap(async function handler(req, res) {);}+ // One hard deadline for ALL upstream work — metadata resolution and every+ // gateway attempt draw from the same budget so their combined spend can never+ // exceed it and trip the function's 30s kill before we serve the placeholder.+ const deadline = Date.now() + TOTAL_BUDGET_MS - RESPONSE_HEADROOM_MS;+// Resolve the artwork URL: an explicit ?url wins; otherwise read it from the// token metadata document server-side. A null result simply falls through to- // the placeholder below — the loader always receives a valid image.+ // the placeholder below — the loader always receives a valid image. The meta+ // fetch is capped at whatever is left of the shared budget (never more than+ // META_TIMEOUT_MS) so a hung metadata host can't consume the gateway budget.let target = directUrl;if (!target && metaUri) {- target = await resolveImageFromMeta(metaUri);+ const metaBudget = Math.min(META_TIMEOUT_MS, deadline - Date.now());+ if (metaBudget > 250) target = await resolveImageFromMeta(metaUri, metaBudget);}- let image = null;- const deadline = Date.now() + TOTAL_BUDGET_MS;- for (const candidate of target ? candidates(target) : []) {- // Shrink each attempt's timeout to fit the remaining overall budget so the- // loop never overruns into the function's hard kill. Once too little time- // is left to bother, stop and fall through to the placeholder.- const remaining = deadline - Date.now();- if (remaining < 1_000) break;- try {- const result = await fetchModel(candidate, {- maxBytes: MAX_BYTES,- timeoutMs: Math.min(TIMEOUT_MS, remaining),- });- if (!result.contentType.startsWith('image/')) continue; // HTML error page etc. — try next- image = result;- break;- } catch {- // SSRF refusal, timeout, gateway 5xx — fall through to the next candidate.- }- }+ // Race all candidate gateways concurrently inside whatever is left of the shared+ // budget. The first valid image wins; if every gateway fails (or the budget+ // runs out) we fall through to the placeholder below — always within the 30s wall.+ const image = await raceImageCandidates(+ target ? candidates(target) : [],+ TIMEOUT_MS,+ deadline - Date.now(),+ );if (!image) {// Every source failed. Hand back a valid, CORS-clean placeholder inline sodiff --git a/api/pump/dex-trades.js b/api/pump/dex-trades.jsindex 218ce9b1a..49a5fa072 100644--- a/api/pump/dex-trades.js+++ b/api/pump/dex-trades.js@@ -21,15 +21,38 @@ const GT_NETWORK = 'solana';const MAX_TRADES = 50;const POOL_TTL_MS = 5 * 60_000;const FETCH_TIMEOUT_MS = 6_000;+// How long to keep serving the last good trades frame for a mint after upstream+// starts failing. A graduated coin's tape is far better stale-by-a-minute than+// blank, and it lets a crowd of pollers ride the cache through a rate-limit blip.+const TRADES_STALE_MS = 90_000;+// GeckoTerminal's keyless tier is ~30 req/min shared across the whole function.+// When we trip a 429, hammering it again immediately just extends the throttle,+// so we open a short circuit-breaker: until it elapses, skip the upstream call+// entirely and serve cached trades. Kept under the stale window so a real+// recovery is picked up on the first poll after the cooldown.+const RATELIMIT_COOLDOWN_MS = 20_000;// mint → { pool, at } — the top pool changes rarely, so caching it keeps the// per-poll cost at a single GeckoTerminal call against a tight keyless limit.const _poolCache = new Map();+// mint → { trades, pool, at } — last successful trade frame, served stale when+// upstream is unavailable so the live tape never blanks mid-session.+const _tradesCache = new Map();+// Process-wide circuit breaker: epoch ms until which we treat GeckoTerminal as+// rate-limited and skip calls. Shared across mints because the 429 is per-IP.+let _cooldownUntil = 0;function isPlausibleMint(s) {return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s);}+class RateLimitError extends Error {+ constructor() {+ super('GeckoTerminal 429');+ this.code = 'rate_limited';+ }+}+async function gtFetch(path) {const ctrl = new AbortController();const tid = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);@@ -38,6 +61,11 @@ async function gtFetch(path) {signal: ctrl.signal,headers: { accept: 'application/json', 'user-agent': 'three.ws-dex-trades/1' },});+ if (r.status === 429) {+ // Open the breaker so sibling invocations stop piling onto the throttle.+ _cooldownUntil = Date.now() + RATELIMIT_COOLDOWN_MS;+ throw new RateLimitError();+ }if (!r.ok) throw new Error(`GeckoTerminal ${r.status}`);return await r.json();} finally {@@ -116,6 +144,31 @@ export default wrap(async (req, res) => {return error(res, 400, 'bad_mint', 'mint query param must be a base58 Solana address');}+ // Serve the last good frame for this mint, capped/sorted to the request shape.+ // `stale` flags that the data is from cache rather than a fresh upstream read.+ const serveCached = (stale) => {+ const hit = _tradesCache.get(mint);+ if (!hit) return null;+ return {+ mint,+ pool: hit.pool,+ trades: hit.trades.slice(0, limit),+ ...(stale ? { stale: true } : {}),+ };+ };++ // Circuit-breaker open: GeckoTerminal recently 429'd us. Don't add to the+ // throttle — ride the cache. Empty (but 200) if we have nothing cached yet.+ if (Date.now() < _cooldownUntil) {+ const cached = serveCached(true);+ return json(+ res,+ 200,+ cached || { mint, pool: null, trades: [], stale: true, error: 'rate_limited' },+ { 'cache-control': 'public, s-maxage=10' },+ );+ }+try {const pool = await topPool(mint);if (!pool) {@@ -132,21 +185,33 @@ export default wrap(async (req, res) => {.map((t) => normalizeGtTrade(t, mint)).filter((t) => t.signature && t.timestamp).sort((a, b) => b.timestamp - a.timestamp)- .slice(0, limit);+ .slice(0, MAX_TRADES);+ _tradesCache.set(mint, { trades, pool, at: Date.now() });return json(res,200,- { mint, pool, trades },+ { mint, pool, trades: trades.slice(0, limit) },{ 'cache-control': 'public, s-maxage=8, stale-while-revalidate=30' },);} catch (err) {- // Never error a public tape: return empty so the client keeps its last good- // frame and retries on the next poll.- console.error('[pump/dex-trades]', err?.message || err);+ // Never error a public tape. Prefer the last good frame (within the stale+ // window) over a blank one so the tape survives a rate-limit/timeout blip;+ // fall back to empty only when we have nothing cached.+ const isRateLimit = err?.code === 'rate_limited';+ if (!isRateLimit) console.error('[pump/dex-trades]', err?.message || err);+ const hit = _tradesCache.get(mint);+ if (hit && Date.now() - hit.at < TRADES_STALE_MS) {+ return json(+ res,+ 200,+ { mint, pool: hit.pool, trades: hit.trades.slice(0, limit), stale: true },+ { 'cache-control': 'public, s-maxage=10' },+ );+ }return json(res,200,- { mint, pool: null, trades: [], error: 'upstream_unavailable' },+ { mint, pool: null, trades: [], error: isRateLimit ? 'rate_limited' : 'upstream_unavailable' },{ 'cache-control': 'public, s-maxage=10' },);}