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(forge): derive R2 preview-image content-type from extension, not upstream header
fudjia8beaebd34ca4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 84ba2568b..b522debde 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,12 +9,14 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **/play: real water at the fishing ponds, and spare rods to find on the bank** — The two fishing ponds no longer look like a flat tinted disc — they're now an animated water surface with real ripples, a sun-tracked sparkle, and a deep-to-shallow gradient that reacts to the world's day/night lighting. New alongside it: three spare fishing rods, leaning on posts around the map (both pond banks and the plaza), that any player can walk up to and pick up into their backpack — on top of the rod everyone already starts with. This also brought the chop/mine/cook gathering stations (trees, rocks, roast pits) online for the first time — they existed in the code but were never actually rendered in the world until now. Caught fish still sell for cash at the General Store, same as before. (`/play`) `[feature]`- **Agents can now hunt money drops and complete IRL quests from code** — The @three-ws/irl SDK (v0.2.0) now covers the whole IRL surface, not just pins. New functions let any script or agent discover real-money drops near where it checks in, claim them with a proof-of-presence fix (a real on-chain release to its own wallet), place self- or agent-funded drops and bounties, and run the full World Lines quest loop — find nearby quests, take the challenge at the spot, and earn the agent-signed proof-of-presence collectible, plus verify anyone's proof independently. Fully typed, zero dependencies, verified against the live API. (`/irl`) `[sdk, feature]`- **Avatars render again on seven pages that were showing an empty viewer** — Avatars made on three.ws are saved in a compressed format to keep them small and quick to download. Seven pages — Cosmos, Minted, Creations, Vault, Pitch, the embodied-agent page, and the microphone lipsync demo — never set up the matching decompressor, so instead of a 3D model you got an empty viewer and an error in the console. All seven now load the decoder before the model, and the avatars appear as they should. The fix also went into the embeddable agent widget itself, so anyone who has pasted a three.ws agent onto their own site gets working compressed avatars automatically, with nothing to change on their end. (`/cosmos`) `[fix]`+- **Coin art is back on the Oracle — every token now shows its real picture** — The Oracle was the most broken page on the site: almost none of the coin pictures loaded. It was asking public IPFS gateways for the art directly, and browsers refuse those responses on security grounds, so card after card fell back to a bare letter or an empty box. Every image now travels through three.ws itself, which fetches the art server-side, tries several storage gateways until one answers, and hands back a picture every single time. Roughly half of pump.fun coins also point at a small description file rather than the picture itself — the site now reads that file and follows it to the real artwork, instead of giving up. Coins whose art is genuinely gone get a distinctive generated gem rather than a broken-image icon, and the same fix carries across to Radar and the live pump feeds. (`/oracle`) `[fix, improvement]`- **Free 3D generation stays up when outside providers go down** — Free text-to-3D and image-to-3D now fall back to the platform's own GPU worker when every outside free provider is busy or out of quota — previously those moments returned a 'temporarily unavailable' error even though our own generator was healthy. Also fixed: the machine-readable discovery files under /.well-known (agent-card.json, ai-plugin.json, security.txt) were failing to load for agents and crawlers; they serve correctly again. `[fix, infra]`- **Homepage: agent thumbnails load, and the marketplace strip is alive again** — The avatar picker on the homepage was asking our image server for five pictures that had never been made, so the browser refused them and those slots sat blank. It now asks only for pictures that actually exist, and it leads with the avatars that have one — where an avatar has no picture yet, it draws a clean initial instead of a broken tile. Underneath it, the live marketplace strip had been silently empty: it was reading the agent list in the wrong shape and quietly gave up every time, leaving just a lone "Browse marketplace" link. It now reads the list correctly and shows ten real agents you can click straight through to. The 3D models themselves were always loading fine and are untouched. (`/`) `[fix]`- **IRL on phones: controls no longer cover each other** — The IRL screen was built up feature by feature until buttons buried the view on phones — the action pills stacked five rows deep over the walk joystick, the money-drops button floated on top of other controls, and small close buttons were easy to miss. The whole HUD is now built for thumbs: one swipeable action row hugs the bottom edge, the joystick zone floats above it so drags never hit a button, the drops button repositions itself and steps aside whenever a sheet is open, and every close button and tab meets the 44-pixel tap size. The avatar and camera view are finally unobstructed. (`/irl`) `[improvement, fix]`- **Live SOL price restored on /three-live; Flappin UFO demo retired** — Two quiet breakages, fixed. The live trade feed on /three-live now prices SOL-only trades correctly again — it was reading a price API directly from your browser, which the provider silently blocks, so those trades showed no dollar value; it now reads the same cached, multi-provider SOL/USD price the rest of the platform uses. Separately, the Flappin UFO arcade demo ran on an external deployment that has gone offline, leaving a blank screen and a leaderboard that never loaded. Rather than leave a broken page up, /play/ufo is now an honest retired notice that points you to the live experiences — the coin world, Sniper Arena, and Coin Clash. (`/three-live`) `[fix]`- **The 3D world is locked down — visitors can no longer delete the ground** — Until today, every single person who opened world.three.ws arrived with full build rights. Anyone could move or delete any object in the world, replace the scene, or fill it with broken models — no account, no password, nothing. That is what emptied the world once before, when the ground itself was deleted and everyone who joined fell into a black void. The world now starts locked: visitors can walk around, chat, and explore, but only someone holding the admin code can change anything. Builders unlock their tools in-world by typing /admin followed by the code. The server refuses to start at all if the code is missing, so the world can never quietly come back up unprotected again. `[security, infra]`- **Two broken pages fixed: vanity receipt verifier and Drive Your Avatar** — Both pages failed to load anything at all, and both are working again. The receipt verifier at /vanity/verify loads its cryptography straight into your browser so the audit runs on your machine and nothing is sent anywhere — but the browser had no way to locate those crypto libraries, so the page sat dead and no receipt could be checked. It now resolves them properly: paste a receipt and every check runs, right through to opening a sealed envelope. On /temporary, the payment widget behind the in-world "Feature your content" billboard was loaded the wrong way and crashed on arrival, taking the pay button with it. It now loads the same way it does on every other page that uses it. (`/vanity/verify`) `[fix]`+- **x402 discovery listings now render full result cards everywhere** — Seven paid services — the fact checker, mint-to-mesh (single and batch), asset remixing, agent embodiment, 3D NFT minting, and provenance anchoring — were listing on the open x402 indexers without a response example, so their catalog cards rendered empty and ranked poorly. Every one now ships a realistic sample response in the discovery document, and the build-time guard that keeps the catalog fully green is passing again so a future gap can't ship unnoticed. (`/x402`) `[fix, improvement]`- **Your agents can now be placed privately, and nobody can browse /irl locations from afar** — Two changes to how /irl handles where you are. First, reading the agents near you now requires proving you have a recent location fix for that spot — until today anyone could ask our servers what agents sat at any coordinate on earth without ever going there. Second, a placed agent can now be private: you still see it in AR exactly where you left it, but it is withheld from everyone else's nearby feed, from shared rooms, and from the World Lines quest map. New placements are private by default while /irl is still in testing, and the privacy center's unpublish button now makes a pin private instead of hiding it from you too. You can make any pin public again whenever you want. (`/irl-privacy`) `[security, feature, improvement]`## 2026-07-08diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.jsindex 98778ccc4..1344fe4a5 100644--- a/api/_lib/forge-store.js+++ b/api/_lib/forge-store.js@@ -180,7 +180,7 @@ async function scoreAndCompress(buf, { computeQuality, compress }) {return { buf: outBuf, quality, compression };}-async function copyToBucket({ sourceUrl, key, fallbackContentType, maxBytes, computeQuality = false, compress = null }) {+async function copyToBucket({ sourceUrl, key, fallbackContentType, maxBytes, computeQuality = false, compress = null, forceContentType = null }) {let lastErr;for (let attempt = 1; attempt <= COPY_MAX_ATTEMPTS; attempt++) {try {@@ -196,7 +196,15 @@ async function copyToBucket({ sourceUrl, key, fallbackContentType, maxBytes, com} else {let 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;+ // forceContentType wins over the upstream header: providers (Replicate+ // et al.) often serve ephemeral output blobs as `application/octet-stream`+ // or another generic type regardless of the actual bytes. Trusting that+ // verbatim into R2's stored Content-Type is what made every homepage+ // forge thumbnail fail Chrome's Opaque Response Blocking — the browser+ // won't render a cross-origin <img> whose declared type isn't an image+ // type. Callers that know the asset kind (e.g. the preview image, whose+ // extension is already decided by imageExtFor) should force it.+ const contentType = forceContentType || resp.headers.get('content-type') || fallbackContentType;let quality = null;let compression = null;if (computeQuality || compress) {@@ -225,6 +233,11 @@ function imageExtFor(url) {return m ? m[1].toLowerCase().replace('jpeg', 'jpg') : 'webp';}+const IMAGE_CONTENT_TYPE_BY_EXT = { png: 'image/png', jpg: 'image/jpeg', webp: 'image/webp' };+function imageContentTypeFor(ext) {+ return IMAGE_CONTENT_TYPE_BY_EXT[ext] || 'image/webp';+}+// Copy a finished generation into durable storage and flip the row to 'done'.// Copies the mesh (required) and the reference image (best-effort). Returns the// durable { id, glbUrl, previewImageUrl, quality, compression } or null on any@@ -273,6 +286,7 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl, qsourceUrl: existing.preview_image_url,key: `${keyPrefix}.${ext}`,fallbackContentType: 'image/webp',+ forceContentType: imageContentTypeFor(ext),maxBytes: MAX_IMAGE_BYTES,});preview = { key: `${keyPrefix}.${ext}`, url: copied.publicUrl };diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex cff78e699..99f0b8729 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -1138,12 +1138,51 @@ export const limits = {// 3. x-real-ip — last resort only, for non-Vercel reverse-proxy setups where// the socket address is the proxy's. Client-settable on direct hits, but// by this point there is no better signal.+// How many trailing X-Forwarded-For entries THIS deployment's own infrastructure+// appends. Google's external Application Load Balancer (three.ws prod) hands the+// backend:+//+// X-Forwarded-For: <caller-supplied…>, <real-client-ip>, <load-balancer-ip>+//+// It appends the connecting client's IP and the forwarding rule's IP. So exactly one+// trailing hop (the LB) must be skipped, and the entry before it is the real client.+// Cloud Run reached directly (no LB in front) appends nothing → set this to 0.+const TRUSTED_PROXY_HOPS = (() => {+ const n = Number.parseInt(process.env.TRUSTED_PROXY_HOPS ?? '', 10);+ return Number.isInteger(n) && n >= 0 ? n : 1;+})();++// The caller's IP, as the key for every per-IP rate limiter on the platform.+//+// Two ways to get this wrong, both of which this function used to:+//+// 1. Trust `req.socket.remoteAddress`. Behind a load balancer the socket peer is+// ALWAYS the balancer, so every visitor on earth collapses into ONE bucket key.+// After the Vercel→Cloud Run migration this was the live behaviour (the Vercel+// header below is never set on GCP), which silently turned every per-IP limit+// into a platform-wide global limit — a self-DoS, not a control. It is why+// /api/irl/privacy answered 429 to its very first caller.+//+// 2. Trust the LEFTMOST X-Forwarded-For entry, or any header a caller can set+// (`x-vercel-forwarded-for`, `x-real-ip`). Everything left of the hops our own+// infrastructure appends is attacker-controlled: a sweeper sending a random+// X-Forwarded-For on each request mints a fresh limiter bucket every time.+//+// So: read X-Forwarded-For, walk it from the RIGHT, skip the hops we append, and+// take the next address. Fall back to the socket only when there is no XFF at all+// (local dev, tests, direct container access) — there, the socket IS the client.export function clientIp(req) {- const vercel = req.headers['x-vercel-forwarded-for'];- if (vercel) return String(vercel).split(',')[0].trim();+ const xff = req.headers?.['x-forwarded-for'];+ if (xff) {+ const hops = String(xff).split(',').map((s) => s.trim()).filter(Boolean);+ if (hops.length) {+ // Clamp: a shorter-than-expected chain (direct hit, or a stripped header)+ // must degrade to the leftmost real entry, never to a negative index.+ const ip = hops[Math.max(0, hops.length - 1 - TRUSTED_PROXY_HOPS)];+ if (ip) return ip;+ }+ }const sock = req.socket?.remoteAddress;if (sock) return sock;- const real = req.headers['x-real-ip'];- if (real) return String(real).split(',')[0].trim();return '0.0.0.0';}diff --git a/api/_lib/service-catalog/services/embody.js b/api/_lib/service-catalog/services/embody.jsindex ce8b68c63..6daac035f 100644--- a/api/_lib/service-catalog/services/embody.js+++ b/api/_lib/service-catalog/services/embody.js@@ -43,5 +43,18 @@ export default {voice: { type: 'string' },},},+ // Mirrors buildBundle()'s settled 200 in api/x402/embody.js — the durable+ // persona id, its GLB + viewer/profile URLs, and the paste-anywhere embed tag.+ outputExample: {+ agent_id: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee',+ glb_url: 'https://cdn.three.ws/personas/nova-scout/rigged.glb',+ viewer_url: 'https://three.ws/viewer?src=https%3A%2F%2Fcdn.three.ws%2Fpersonas%2Fnova-scout%2Frigged.glb',+ profile_url: 'https://three.ws/embed/persona?persona=aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee&state=idle',+ embed_html: '<iframe src="https://three.ws/embed/persona?persona=aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee&state=idle" width="360" height="480" loading="lazy" style="border:0;border-radius:12px;max-width:100%" allow="autoplay; fullscreen; xr-spatial-tracking" allowfullscreen sandbox="allow-scripts allow-same-origin allow-popups"></iframe>',+ reload_url: 'https://three.ws/api/mcp3d/persona?id=aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee',+ voice: 'nova',+ rigged: true,+ name: 'Nova Scout',+ },storefronts: ['x402scan'],};diff --git a/api/_lib/service-catalog/services/fact-check.js b/api/_lib/service-catalog/services/fact-check.jsindex 91e94e762..d23456553 100644--- a/api/_lib/service-catalog/services/fact-check.js+++ b/api/_lib/service-catalog/services/fact-check.js@@ -47,5 +47,26 @@ export default {},},},+ // Mirrors OUTPUT_EXAMPLE in api/x402/fact-check.js (the handler's own 402+ // challenge carries the same example) — keep the two in sync.+ outputExample: {+ verdict: 'contradicted',+ confidence: 0.78,+ claim: 'The Eiffel Tower is 330 meters tall.',+ strictness: 'high',+ sources: [+ {+ url: 'https://en.wikipedia.org/wiki/Eiffel_Tower',+ title: 'Eiffel Tower - Wikipedia',+ excerpt: 'The tower is 330 m (1,083 ft) tall, including a 24 m (79 ft) antenna.',+ stance: 'supports',+ weight: 0.7,+ retrievedAt: '2026-05-27T00:00:00.000Z',+ },+ ],+ costBreakdown: { searchCalls: 3, llmTokens: 1420, totalUsdc: '0.100355' },+ attestation: 'sha256:abcdef1234567890...',+ lane: 'paid',+ },storefronts: ['x402scan'],};diff --git a/api/_lib/service-catalog/services/mint-to-mesh-batch.js b/api/_lib/service-catalog/services/mint-to-mesh-batch.jsindex c880fe96f..dcfd437c2 100644--- a/api/_lib/service-catalog/services/mint-to-mesh-batch.js+++ b/api/_lib/service-catalog/services/mint-to-mesh-batch.js@@ -40,5 +40,32 @@ export default {},},},+ // Mirrors the batch handler's envelope in api/x402/mint-to-mesh-batch.js —+ // per-mint ok:true/ok:false results, never a whole-batch failure. GLB base64+ // truncated to a magic-bytes stub.+ outputExample: {+ count: 2,+ results: [+ {+ ok: true,+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ theme: {+ name: 'three.ws',+ symbol: 'THREE',+ color: '#7c5cff',+ imageUrl: 'https://cdn.three.ws/tokens/three.png',+ hasImage: true,+ },+ glb: { mimeType: 'model/gltf-binary', bytes: 18432, base64: 'Z2xURgIAAAA…' },+ },+ {+ ok: false,+ mint: 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi',+ error: 'meta_fetch_failed',+ error_description: 'no Metaplex metadata account for this mint',+ },+ ],+ indexed_at: '2026-07-09T00:00:00.000Z',+ },storefronts: ['x402scan'],};diff --git a/api/_lib/service-catalog/services/mint-to-mesh.js b/api/_lib/service-catalog/services/mint-to-mesh.jsindex b0a68cd6f..fde57c3fd 100644--- a/api/_lib/service-catalog/services/mint-to-mesh.js+++ b/api/_lib/service-catalog/services/mint-to-mesh.js@@ -38,5 +38,23 @@ export default {},},},+ // Mirrors buildMesh()'s return in api/x402/mint-to-mesh.js. The base64 GLB is+ // truncated to a recognizable magic-bytes stub — a full model would bloat the+ // discovery doc for no ranking benefit.+ outputExample: {+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ theme: {+ name: 'three.ws',+ symbol: 'THREE',+ color: '#7c5cff',+ imageUrl: 'https://cdn.three.ws/tokens/three.png',+ hasImage: true,+ },+ glb: {+ mimeType: 'model/gltf-binary',+ bytes: 18432,+ base64: 'Z2xURgIAAAA…',+ },+ },storefronts: ['x402scan'],};diff --git a/api/_lib/service-catalog/services/remix-asset.js b/api/_lib/service-catalog/services/remix-asset.jsindex 0e3be6fcc..326c1c71b 100644--- a/api/_lib/service-catalog/services/remix-asset.js+++ b/api/_lib/service-catalog/services/remix-asset.js@@ -46,5 +46,33 @@ export default {},},},+ // Mirrors the settled 200 in api/x402/remix-asset.js — the new remix, its+ // source lineage, and the honest royalty split (paid or not).+ outputExample: {+ ok: true,+ remix: {+ glbUrl: 'https://cdn.three.ws/forge/example-remix/model.glb',+ viewerUrl: 'https://three.ws/viewer?src=https%3A%2F%2Fcdn.three.ws%2Fforge%2Fexample-remix%2Fmodel.glb',+ creationId: '11111111-2222-4333-8444-555555555555',+ prompt: 'a low-poly fox, but make it metallic',+ instruction: 'make it metallic',+ anchored: true,+ },+ source: {+ id: '00000000-0000-0000-0000-000000000000',+ prompt: 'a low-poly fox',+ royaltyBps: 1000,+ royaltyPercent: 10,+ },+ royalty: {+ paid: true,+ royaltyBps: 1000,+ capped: false,+ creatorUsd: 0.025,+ platformUsd: 0.225,+ creatorAtomics: '25000',+ creatorTx: '5synthetictransactionsignature1111111111111111111111111111111111111111111111111111111',+ },+ },storefronts: ['x402scan'],};diff --git a/api/cron/avatar-thumbnail-backfill.js b/api/cron/avatar-thumbnail-backfill.jsindex 535539b5a..c6bb333dd 100644--- a/api/cron/avatar-thumbnail-backfill.js+++ b/api/cron/avatar-thumbnail-backfill.js@@ -26,9 +26,15 @@//// Env:// CRON_SECRET required (Bearer)-// THUMBNAIL_BACKFILL_RENDER_BATCH models rendered per tick (default 4)+// THUMBNAIL_BACKFILL_RENDER_BATCH models rendered per tick (default 8)// THUMBNAIL_BACKFILL_ADOPT_BATCH forge previews adopted per tick (default 200)// THUMBNAIL_BACKFILL_CONCURRENCY parallel renders (default 2)+//+// Sizing: a render is ~3-6s, so 8 models at concurrency 2 lands around 25-40s —+// comfortably inside maxDuration=120 with room for a slow model. At */5 that is+// ~96 avatars/hour. A large backlog should be cleared with the bulk script+// (scripts/backfill-avatar-thumbnails.mjs --loop), which shares this claim ledger;+// the cron exists to keep coverage at 100% once it is there.import { json, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';@@ -45,7 +51,7 @@ export const maxDuration = 120;const log = logger('avatar-thumbnail-backfill');-const RENDER_BATCH = Math.max(0, Number(process.env.THUMBNAIL_BACKFILL_RENDER_BATCH || 4));+const RENDER_BATCH = Math.max(0, Number(process.env.THUMBNAIL_BACKFILL_RENDER_BATCH || 8));const ADOPT_BATCH = Math.max(0, Number(process.env.THUMBNAIL_BACKFILL_ADOPT_BATCH || 200));const CONCURRENCY = Math.max(1, Number(process.env.THUMBNAIL_BACKFILL_CONCURRENCY || 2));diff --git a/api/cron/forge-seed-cron.js b/api/cron/forge-seed-cron.jsindex 7339fe0f3..64b93f2bf 100644--- a/api/cron/forge-seed-cron.js+++ b/api/cron/forge-seed-cron.js@@ -100,7 +100,7 @@ async function insertSeedAvatar({ userId, prompt, modelCategory, creationId }) {await sql`insert into avatars(owner_id, slug, name, description, storage_key, size_bytes,- content_type, source, source_meta, visibility, tags,+ content_type, source, source_meta, thumbnail_key, visibility, tags,model_category, created_at, updated_at)select${userId},@@ -112,6 +112,13 @@ async function insertSeedAvatar({ userId, prompt, modelCategory, creationId }) {'model/gltf-binary','forge',${JSON.stringify({ forge_creation_id: creationId, prompt, seed: true })}::jsonb,+ -- The creation's preview image is already in the bucket with a correct+ -- Content-Type (it is what /forge's own gallery renders). Adopt it as the+ -- avatar's thumbnail for free, rather than leaving thumbnail_key NULL and+ -- making the backfill cron pay chromium to re-render the same model.+ -- Relative keys only: an absolute URL in thumbnail_key resolves against an+ -- origin where no object lives (see api/_lib/avatar-thumbs.js).+ case when fc.preview_key !~ '^https?://' then fc.preview_key end,'public',array[${modelCategory}]::text[],${modelCategory},diff --git a/api/img.js b/api/img.jsindex 14162fd35..0d19a8569 100644--- a/api/img.js+++ b/api/img.js@@ -15,7 +15,12 @@// per-redirect re-validation, byte cap, timeout) — see api/_lib/ssrf.js.// 2. If the source is an IPFS URL that fails, retry across alternate public// gateways so one slow gateway never blanks the art.-// 3. On total failure, serve a deterministic, on-brand SVG placeholder inline+// 3. If `?url=` turns out to address a token *metadata* document rather than an+// image (roughly half of pump.fun art is stored this way — feeds keep both+// kinds in a single `image_uri` column, indistinguishable without fetching),+// follow its `.image` field exactly one hop to the real artwork. Callers that+// already know they hold a metadata URI can say so explicitly with `?meta=`.+// 4. On total failure, serve a deterministic, on-brand SVG placeholder inline// (200, permissive CORS) so the loader ALWAYS receives a valid image and// never logs an error. The placeholder is generated here — same-origin, no// external dependency that could itself be down — and is unique per seed:diff --git a/api/wk.js b/api/wk.jsindex e61b4d651..5f9acb7a0 100644--- a/api/wk.js+++ b/api/wk.js@@ -1192,6 +1192,30 @@ const MCP_TOOL_OUTPUT_SUMMARIES = Object.freeze({mode: 'streaming',eta_seconds: 180,},+ // Mirrors mintTokenized3dAsset()'s structuredContent in api/_mcp/tools/tokenize.js.+ mint_3d_asset: {+ status: 'minted',+ idempotent: false,+ name: 'Midnight Robot',+ network: 'devnet',+ mint: 'M1ntExamp1eDoNotUse1111111111111111111111111',+ explorer_asset_url: 'https://core.metaplex.com/explorer/M1ntExamp1eDoNotUse1111111111111111111111111?env=devnet',+ explorer_tx_url: 'https://explorer.solana.com/tx/5synthetictransactionsignature111111111111111111111111111111111111111111111111111111?cluster=devnet',+ viewer_url: 'https://three.ws/viewer?src=https%3A%2F%2Fcdn.three.ws%2Favatars%2Fmidnight-robot.glb',+ royalty: { percent: 5, requested_basis_points: 500, cap_basis_points: 1000, capped: false },+ },+ // Mirrors handleAnchor()'s structuredContent in api/_mcp3d/tools/provenance.js.+ anchor_provenance: {+ status: 'anchored',+ glbSha256: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',+ credentialHash: '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824',+ issuer: 'AtteStIssuerExamp1eDoNotUse11111111111111111',+ anchor: {+ tx: '5synthetictransactionsignature111111111111111111111111111111111111111111111111111111',+ cluster: 'devnet',+ explorerUrl: 'https://explorer.solana.com/tx/5synthetictransactionsignature111111111111111111111111111111111111111111111111111111?cluster=devnet',+ },+ },});// Wrap a tool result summary in the JSON-RPC CallToolResult envelope.diff --git a/data/changelog.json b/data/changelog.jsonindex 74e4e3926..c0b00bb6c 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,26 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-09",+ "title": "x402 discovery listings now render full result cards everywhere",+ "summary": "Seven paid services — the fact checker, mint-to-mesh (single and batch), asset remixing, agent embodiment, 3D NFT minting, and provenance anchoring — were listing on the open x402 indexers without a response example, so their catalog cards rendered empty and ranked poorly. Every one now ships a realistic sample response in the discovery document, and the build-time guard that keeps the catalog fully green is passing again so a future gap can't ship unnoticed.",+ "tags": [+ "fix",+ "improvement"+ ],+ "link": "/x402"+ },+ {+ "date": "2026-07-09",+ "title": "Coin art is back on the Oracle — every token now shows its real picture",+ "summary": "The Oracle was the most broken page on the site: almost none of the coin pictures loaded. It was asking public IPFS gateways for the art directly, and browsers refuse those responses on security grounds, so card after card fell back to a bare letter or an empty box. Every image now travels through three.ws itself, which fetches the art server-side, tries several storage gateways until one answers, and hands back a picture every single time. Roughly half of pump.fun coins also point at a small description file rather than the picture itself — the site now reads that file and follows it to the real artwork, instead of giving up. Coins whose art is genuinely gone get a distinctive generated gem rather than a broken-image icon, and the same fix carries across to Radar and the live pump feeds.",+ "tags": [+ "fix",+ "improvement"+ ],+ "link": "/oracle"+ },{"date": "2026-07-09","title": "The 3D world is locked down — visitors can no longer delete the ground",diff --git a/docs/ops/gcp-production.md b/docs/ops/gcp-production.mdindex 9065004ae..b11aacab6 100644--- a/docs/ops/gcp-production.md+++ b/docs/ops/gcp-production.md@@ -111,10 +111,28 @@ deploys from a human-authed CLI (command below).npm run build:gcp# Build image on Cloud Build (32-vCPU + BuildKit layer cache) + push + deploy.-# Gated on check:dist so an incomplete dist/ can no longer ship.+# Gated on check:dist AND db:check so an incomplete dist/ or an out-of-date+# database can no longer ship.npm run deploy:gcp```+**Database migrations** live in `api/_lib/migrations/*.sql` and are tracked in+the `schema_migrations` table (filename + sha256). Nothing applies them+automatically — the flow is:++```bash+npm run db:status # dry run: list applied/pending against DATABASE_URL+npm run db:migrate # apply pending migrations (do this BEFORE deploy:gcp)+npm run db:check # what deploy:gcp runs: exits 4 if anything is pending+```++- `DATABASE_URL` comes from `.env.local` and must point at the production Neon+ DB (the same value the Cloud Run service uses).+- Never edit a migration file after it has been applied — the runner detects+ the sha256 drift and refuses (exit 3). Roll forward with a new file.+- Apply migrations before deploying the code that needs them: migrations are+ additive, so old code + new schema is safe; new code + old schema is not.+- Lockfile unchanged → layer cache skips the workspace `npm ci`: **~3–5 min**.- Lockfile changed → full install: **~12 min**.- If the pipeline's deploy step fails on IAM (see above), deploy the pushed@@ -228,8 +246,7 @@ by CLI at all. Consequences and current state:| What | Vars | Impact | Recovery ||---|---|---|---|-| x402 ring signers | `X402_TREASURY_SECRET_BASE58`, `X402_SEED_SOLANA_SECRET_BASE58` | Ring is enabled but the treasury/payer roles cannot sign — no autonomous USDC movement | Owner's gitignored `.x402-ring-secrets.json`, written by `scripts/x402-ring-setup.mjs` on whatever machine ran it. Public half: treasury/pay-to `wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU` (holds real SOL — do NOT regenerate; recover the secret). The **sponsor** role is no longer in this row — see below. |-| Rate-limiter Redis | `UPSTASH_REDIS_REST_URL`, `UPSTASH_REDIS_REST_TOKEN` | Money-moving limiters **fail closed** (already true on Vercel pre-shutdown). **Worse: the x402 idempotency module hard-throws at import** (`api/_lib/x402/idempotency-cache.js`) — so **every** paid endpoint that imports it (`/api/okx/3d/*`, `/api/x402/*`) returns **HTTP 500 at module load**, not a graceful degrade. This took the entire paid surface down on 2026-07-08 until the escape hatch below was set. | Owner's Upstash console, or provision fresh Upstash/Memorystore and set both vars. `X402_ALLOW_MEMORY_FALLBACK=1` is the sanctioned escape hatch and is **currently SET in prod (since 2026-07-08)** to keep the paid surface up on per-instance memory idempotency. Financial double-charge stays prevented on-chain regardless (EIP-3009 nonces are single-use); the flag only degrades cross-replica work/response dedup. Remove the flag once real Upstash creds land. |+| Collection authority | `SOLANA_AGENT_COLLECTION_AUTHORITY_KEY` | Agent NFT collection ops can't sign | Intentionally excluded from `scripts/wire-master-wallet.mjs` (on-chain update authority must stay its original wallet). Owner holds the key. || R2/S3 storage creds | `S3_ENDPOINT`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_BUCKET`, `S3_PUBLIC_DOMAIN` | `/api/marketplace`, `/api/explore`, `/api/avatars/:id` — every route that resolves an asset URL — 503 `not_configured` | Real values already sit in the repo's `.env.local` (never committed). Apply with `scripts/gcp/apply-s3-env.sh` (needs a human-authed `gcloud auth login` first — the 89-var apply is still blocked on reauth per above). |### Resolved: x402 sponsor co-signing key (2026-07-09)diff --git a/package.json b/package.jsonindex d0b344ba9..2c625d146 100644--- a/package.json+++ b/package.json@@ -208,12 +208,13 @@"check:dist": "node scripts/check-dist.mjs","deploy": "npm run build:all && npm run check:dist && vercel --local-config vercel.json --prod","build:gcp": "npm run build && npm run build:lib:full && npm run publish:lib && npm run check:dist",- "deploy:gcp": "npm run check:dist && gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5",+ "deploy:gcp": "npm run check:dist && npm run db:check && gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5","postversion": "git push && git push --tags","validate:cards": "node scripts/validate-agent-cards.mjs","db:bootstrap": "node scripts/db-bootstrap.mjs","db:migrate": "node scripts/apply-migrations.mjs --apply","db:status": "node scripts/apply-migrations.mjs",+ "db:check": "node scripts/apply-migrations.mjs --check","worker:oracle": "node workers/oracle/index.js","worker:sniper": "node workers/agent-sniper/index.js","worker:sniper:live": "SNIPER_MODE=live node workers/agent-sniper/index.js",diff --git a/public/changelog.json b/public/changelog.jsonindex 1becf7605..3935cb5c5 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-09T21:57:24.244Z",+ "generated_at": "2026-07-09T22:04:22.145Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -37,6 +37,17 @@"fix"]},+ {+ "date": "2026-07-09",+ "type": "update",+ "title": "Coin art is back on the Oracle — every token now shows its real picture",+ "summary": "The Oracle was the most broken page on the site: almost none of the coin pictures loaded. It was asking public IPFS gateways for the art directly, and browsers refuse those responses on security grounds, so card after card fell back to a bare letter or an empty box. Every image now travels through three.ws itself, which fetches the art server-side, tries several storage gateways until one answers, and hands back a picture every single time. Roughly half of pump.fun coins also point at a small description file rather than the picture itself — the site now reads that file and follows it to the real artwork, instead of giving up. Coins whose art is genuinely gone get a distinctive generated gem rather than a broken-image icon, and the same fix carries across to Radar and the live pump feeds.",+ "link": "/oracle",+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-07-09","type": "update",@@ -100,6 +111,17 @@"fix"]},+ {+ "date": "2026-07-09",+ "type": "update",+ "title": "x402 discovery listings now render full result cards everywhere",+ "summary": "Seven paid services — the fact checker, mint-to-mesh (single and batch), asset remixing, agent embodiment, 3D NFT minting, and provenance anchoring — were listing on the open x402 indexers without a response example, so their catalog cards rendered empty and ranked poorly. Every one now ships a realistic sample response in the discovery document, and the build-time guard that keeps the catalog fully green is passing again so a future gap can't ship unnoticed.",+ "link": "/x402",+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-07-09","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex d3302ae72..fe2a7f274 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -30,6 +30,14 @@<category>fix</category><description>Avatars made on three.ws are saved in a compressed format to keep them small and quick to download. Seven pages — Cosmos, Minted, Creations, Vault, Pitch, the embodied-agent page, and the microphone lipsync demo — never set up the matching decompressor, so instead of a 3D model you got an empty viewer and an error in the console. All seven now load the decoder before the model, and the avatars appear as they should. The fix also went into the embeddable agent widget itself, so anyone who has pasted a three.ws agent onto their own site gets working compressed avatars automatically, with nothing to change on their end.</description></item>+ <item>+ <title>Coin art is back on the Oracle — every token now shows its real picture</title>+ <link>https://three.ws/oracle</link>+ <guid isPermaLink="false">2026-07-09:Coin art is back on the Oracle — every token now shows its real picture</guid>+ <pubDate>Thu, 09 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The Oracle was the most broken page on the site: almost none of the coin pictures loaded. It was asking public IPFS gateways for the art directly, and browsers refuse those responses on security grounds, so card after card fell back to a bare letter or an empty box. Every image now travels through three.ws itself, which fetches the art server-side, tries several storage gateways until one answers, and hands back a picture every single time. Roughly half of pump.fun coins also point at a small description file rather than the picture itself — the site now reads that file and follows it to the real artwork, instead of giving up. Coins whose art is genuinely gone get a distinctive generated gem rather than a broken-image icon, and the same fix carries across to Radar and the live pump feeds.</description>+ </item><item><title>Free 3D generation stays up when outside providers go down</title><link>https://three.ws/changelog</link>@@ -78,6 +86,14 @@<category>fix</category><description>Both pages failed to load anything at all, and both are working again. The receipt verifier at /vanity/verify loads its cryptography straight into your browser so the audit runs on your machine and nothing is sent anywhere — but the browser had no way to locate those crypto libraries, so the page sat dead and no receipt could be checked. It now resolves them properly: paste a receipt and every check runs, right through to opening a sealed envelope. On /temporary, the payment widget behind the in-world "Feature your content" billboard was loaded the wrong way and crashed on arrival, taking the pay button with it. It now loads the same way it does on every other page that uses it.</description></item>+ <item>+ <title>x402 discovery listings now render full result cards everywhere</title>+ <link>https://three.ws/x402</link>+ <guid isPermaLink="false">2026-07-09:x402 discovery listings now render full result cards everywhere</guid>+ <pubDate>Thu, 09 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Seven paid services — the fact checker, mint-to-mesh (single and batch), asset remixing, agent embodiment, 3D NFT minting, and provenance anchoring — were listing on the open x402 indexers without a response example, so their catalog cards rendered empty and ranked poorly. Every one now ships a realistic sample response in the discovery document, and the build-time guard that keeps the catalog fully green is passing again so a future gap can't ship unnoticed.</description>+ </item><item><title>Your agents can now be placed privately, and nobody can browse /irl locations from afar</title><link>https://three.ws/irl-privacy</link>diff --git a/public/features.json b/public/features.jsonindex b62fb6999..605fcca5a 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-09T21:57:24.229Z",+ "generated_at": "2026-07-09T22:04:22.120Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/apply-migrations.mjs b/scripts/apply-migrations.mjsindex e997feef3..a32152873 100755--- a/scripts/apply-migrations.mjs+++ b/scripts/apply-migrations.mjs@@ -6,6 +6,7 @@** Usage:* node scripts/apply-migrations.mjs # list pending, no DB writes+ * node scripts/apply-migrations.mjs --check # like the dry run, but exit 4 if anything is pending (deploy gate)* node scripts/apply-migrations.mjs --apply # apply pending migrations* node scripts/apply-migrations.mjs --apply --file 2026-04-29-onchain-unified.sql*@@ -48,6 +49,7 @@ for (const envFile of ['.env.local', '.env']) {const args = process.argv.slice(2);const APPLY = args.includes('--apply');+const CHECK = args.includes('--check');const fileArgIdx = args.indexOf('--file');const ONLY = fileArgIdx >= 0 ? args[fileArgIdx + 1] : null;@@ -149,6 +151,14 @@ async function main() {return;}+ if (CHECK) {+ console.error(+ `\nERROR: ${pending.length} migration(s) pending — the database is behind the code.`,+ );+ console.error('Run `npm run db:migrate` before deploying.');+ process.exit(4);+ }+if (!APPLY) {console.log(`\n${pending.length} pending. Re-run with --apply to execute against ${maskUrl(process.env.DATABASE_URL)}.`,diff --git a/scripts/backfill-avatar-thumbnails.mjs b/scripts/backfill-avatar-thumbnails.mjsindex 1cde4ae3d..f8b2b0f71 100644--- a/scripts/backfill-avatar-thumbnails.mjs+++ b/scripts/backfill-avatar-thumbnails.mjs@@ -1,134 +1,158 @@#!/usr/bin/env node/**- * Backfill PNG thumbnails for public avatars that don't have one yet.+ * Backfill thumbnails for avatars that don't have one.*- * Renders each avatar's GLB in a headless Chromium via model-viewer,- * captures a 1024×1024 PNG, and POSTs it to /api/avatars/thumbnail- * (which uploads to R2 and updates the avatars row).+ * Operator-driven bulk counterpart to the steady-state cron+ * (api/cron/avatar-thumbnail-backfill.js). Both share api/_lib/avatar-thumbs.js+ * — the same claim ledger, the same "never persist a key without confirming the+ * object exists" invariant — so it is safe to run this while the cron is live.+ * Neither will claim an avatar the other is already rendering.*- * Usage:- * ADMIN_BEARER=<token> ORIGIN=https://three.ws \- * node scripts/backfill-avatar-thumbnails.mjs+ * Two phases, cheapest first:+ * 1. adopt — an avatar forged from a forge_creations row points its+ * thumbnail_key at that creation's already-uploaded preview image.+ * Free: no render, no new bytes.+ * 2. render — everything else. Boots headless chromium, renders the GLB to a+ * 768² PNG, uploads to thumb/<avatarId>.png, commits the key.+ * ~6s per model, so run it with --concurrency.*- * The bearer token must have avatars:write scope and belong to a user with- * is_admin=true (so it can update other users' avatars). Pass --limit=N to- * cap how many avatars are processed in a single run; default 25.+ * Avatars are drained most-visible-first (featured → public → view_count →+ * newest), so the surfaces users actually look at heal before the long tail.+ * A model that fails to render MAX_ATTEMPTS times is retired and stops consuming+ * budget.*- * Each avatar takes ~4-6s to render. Run nightly or after large imports.+ * Usage (needs DATABASE_URL + S3_* — they live in .env.local):+ *+ * node --env-file=.env.local scripts/backfill-avatar-thumbnails.mjs --status+ * node --env-file=.env.local scripts/backfill-avatar-thumbnails.mjs --adopt-only+ * node --env-file=.env.local scripts/backfill-avatar-thumbnails.mjs --limit=50 --concurrency=3+ * node --env-file=.env.local scripts/backfill-avatar-thumbnails.mjs --limit=2000 --concurrency=4 --loop+ *+ * Flags:+ * --status print coverage and exit+ * --limit=N render at most N avatars (default 25)+ * --concurrency=N parallel renders, shared chromium (default 2)+ * --adopt-only run phase 1 only, never boot chromium+ * --render-only skip phase 1+ * --loop keep refilling the budget until nothing is left to claim+ *+ * Unlike the previous version this talks to Postgres + R2 directly, so it needs+ * no ADMIN_BEARER and no running server.*/-import { chromium } from 'playwright';+import {+ adoptForgePreviews,+ renderBatch,+ coverage,+ ensureBackfillSchema,+ MAX_ATTEMPTS,+} from '../api/_lib/avatar-thumbs.js';-const ORIGIN = process.env.ORIGIN || 'https://three.ws';-const ADMIN_BEARER = process.env.ADMIN_BEARER;-const LIMIT = Number(process.argv.find((a) => a.startsWith('--limit='))?.split('=')[1]) || 25;-const VIEWPORT = 1024;+const argv = process.argv.slice(2);+const has = (name) => argv.includes(`--${name}`);+const num = (name, fallback) => {+ const hit = argv.find((a) => a.startsWith(`--${name}=`));+ return hit ? Number(hit.split('=')[1]) : fallback;+};-if (!ADMIN_BEARER) {- console.error('ADMIN_BEARER env var required (must have avatars:write scope on an admin account).');- process.exit(1);+const LIMIT = num('limit', 25);+const CONCURRENCY = Math.max(1, num('concurrency', 2));+const ADOPT_ONLY = has('adopt-only');+const RENDER_ONLY = has('render-only');+const LOOP = has('loop');++for (const required of ['DATABASE_URL', 'S3_BUCKET', 'S3_ACCESS_KEY_ID']) {+ if (!process.env[required]) {+ console.error(`[backfill] ${required} is unset — run with: node --env-file=.env.local ${process.argv[1]}`);+ process.exit(1);+ }}-const VIEWER_HTML = `<!doctype html>-<html><head><meta charset="utf-8">-<style>- html,body { margin:0; padding:0; background: transparent; width:${VIEWPORT}px; height:${VIEWPORT}px; }- model-viewer { width:100%; height:100%; --poster-color: transparent; background: transparent; }-</style>-<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>-</head>-<body>- <model-viewer id="mv" interaction-prompt="none" exposure="1.05" shadow-intensity="0.7" tone-mapping="aces"></model-viewer>-</body></html>`;+const pct = (n, d) => (d ? `${((n / d) * 100).toFixed(1)}%` : 'n/a');-async function fetchAvatarsNeedingThumbs() {- const url = `${ORIGIN}/api/avatars/public?limit=200`;- const r = await fetch(url);- if (!r.ok) throw new Error(`fetch ${url}: HTTP ${r.status}`);- const j = await r.json();- return (j.avatars || []).filter((a) => !a.thumbnail_url && a.model_url);+async function printCoverage(label) {+ const c = await coverage();+ console.log(+ `[backfill] ${label}: ${c.covered}/${c.total} public avatars have a thumbnail ` ++ `(${pct(c.covered, c.total)}) — ${c.missing} missing, ` ++ `${c.exhausted} retired after ${MAX_ATTEMPTS} failed renders`,+ );+ return c;}-async function captureAvatar(page, glbUrl) {- await page.evaluate(async (src) => {- const mv = document.getElementById('mv');- mv.setAttribute('src', src);- await new Promise((res, rej) => {- const t = setTimeout(() => rej(new Error('model-viewer load timeout')), 20000);- mv.addEventListener('load', () => { clearTimeout(t); res(); }, { once: true });- mv.addEventListener('error', (e) => { clearTimeout(t); rej(new Error('load error')); }, { once: true });- });- // Frame and one extra render tick to let the camera settle.- mv.cameraOrbit = '0deg 75deg auto';- mv.fieldOfView = '30deg';- await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));- }, glbUrl);+async function main() {+ await ensureBackfillSchema();+ await printCoverage('before');+ if (has('status')) return;- const dataUrl = await page.evaluate(async () => {- const mv = document.getElementById('mv');- const blob = await mv.toBlob({ idealAspect: true, mimeType: 'image/png' });- return await new Promise((res) => {- const fr = new FileReader();- fr.onloadend = () => res(fr.result);- fr.readAsDataURL(blob);- });- });- return dataUrl;-}+ // ── Phase 1: free adoption ────────────────────────────────────────────────+ if (!RENDER_ONLY) {+ let totalAdopted = 0;+ let totalMissing = 0;+ for (;;) {+ const { adopted, missing } = await adoptForgePreviews({ limit: 200 });+ totalAdopted += adopted;+ totalMissing += missing;+ if (adopted) console.log(`[backfill] adopted ${adopted} forge preview(s)`);+ // Candidates whose preview object is absent from R2 can never be adopted+ // and stay in the candidate set, so a batch of only those would spin+ // forever. Stop as soon as a pass adopts nothing.+ if (!adopted) break;+ }+ console.log(+ `[backfill] phase 1 done — ${totalAdopted} adopted` ++ (totalMissing+ ? `, ${totalMissing} preview object(s) absent from R2 (those avatars get rendered instead)`+ : ''),+ );+ }-async function uploadThumbnail(avatarId, pngDataUrl) {- const r = await fetch(`${ORIGIN}/api/avatars/thumbnail`, {- method: 'POST',- headers: {- 'content-type': 'application/json',- authorization: `Bearer ${ADMIN_BEARER}`,- },- body: JSON.stringify({ avatar_id: avatarId, png_base64: pngDataUrl }),- });- if (!r.ok) {- const text = await r.text().catch(() => '');- throw new Error(`upload ${avatarId}: HTTP ${r.status} ${text.slice(0, 200)}`);+ if (ADOPT_ONLY) {+ await printCoverage('after');+ return;}- return r.json();-}-async function main() {- console.log(`[backfill] origin=${ORIGIN} limit=${LIMIT}`);- const todo = (await fetchAvatarsNeedingThumbs()).slice(0, LIMIT);- console.log(`[backfill] ${todo.length} avatar(s) need thumbnails`);- if (!todo.length) return;+ // ── Phase 2: render ───────────────────────────────────────────────────────+ let rendered = 0;+ let failed = 0;+ let remaining = LIMIT;- const browser = await chromium.launch({ args: ['--no-sandbox', '--disable-dev-shm-usage'] });- const ctx = await browser.newContext({- viewport: { width: VIEWPORT, height: VIEWPORT },- deviceScaleFactor: 1,- });- const page = await ctx.newPage();- await page.setContent(VIEWER_HTML, { waitUntil: 'load' });- // Wait for model-viewer custom element to be defined.- await page.waitForFunction(() => !!customElements.get('model-viewer'));+ while (remaining > 0) {+ const batch = Math.min(remaining, Math.max(CONCURRENCY * 2, 4));+ const t0 = Date.now();+ const r = await renderBatch({+ limit: batch,+ concurrency: CONCURRENCY,+ onResult: (res) => {+ const tag = `${String(res.id).slice(0, 8)} (${(res.name || '?').slice(0, 28)})`;+ if (res.status === 'done') console.log(`[backfill] ✓ ${tag} — ${res.bytes}b in ${res.ms}ms`);+ else console.error(`[backfill] ✗ ${tag} — ${res.error}`);+ },+ });- let okCount = 0;- let failCount = 0;- for (const a of todo) {- const tag = `${a.id} (${a.name || a.slug || '?'})`;- try {- console.log(`[backfill] rendering ${tag}…`);- const dataUrl = await captureAvatar(page, a.model_url);- const result = await uploadThumbnail(a.id, dataUrl);- console.log(`[backfill] ✓ ${tag} → ${result?.data?.thumbnail_url} (${result?.data?.bytes} bytes)`);- okCount++;- } catch (err) {- console.error(`[backfill] ✗ ${tag}: ${err.message}`);- failCount++;+ if (!r.claimed) {+ console.log('[backfill] nothing left to claim');+ break;}+ rendered += r.rendered;+ failed += r.failed;+ remaining -= r.claimed;+ console.log(+ `[backfill] batch: ${r.rendered} rendered, ${r.failed} failed in ` ++ `${((Date.now() - t0) / 1000).toFixed(1)}s — ${rendered} rendered this run, ` ++ `${Math.max(0, remaining)} of budget left`,+ );++ if (remaining <= 0 && LOOP) remaining = LIMIT; // --loop: refill the budget}- await browser.close();- console.log(`[backfill] done — ${okCount} ok, ${failCount} failed`);+ console.log(`[backfill] phase 2 done — ${rendered} rendered, ${failed} failed`);+ await printCoverage('after');}-main().catch((err) => {- console.error('[backfill] fatal:', err);- process.exit(1);-});+main()+ .then(() => process.exit(0))+ .catch((err) => {+ console.error('[backfill] fatal:', err?.stack || err);+ process.exit(1);+ });diff --git a/src/marketplace.js b/src/marketplace.jsindex 3291226e6..7a0fcba16 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -152,6 +152,7 @@ const state = {loading: false,publicAvatars: [],publicAvatarsLoaded: false,+ publicAvatarsError: false, // last avatar-feed fetch failed → show retry, not "No public avatars"onchainItems: [],onchainCursor: null,onchainLoaded: false,@@ -574,6 +575,7 @@ async function loadPublicAvatars() {);state.publicAvatars = avatars;state.publicAvatarsLoaded = true;+ state.publicAvatarsError = false;state.stats = j?.totals || state.stats;renderGrid();updateOnchainChipCount();@@ -584,6 +586,7 @@ async function loadPublicAvatars() {// through bindEmptyStateActions (data-retry-scope="avatars").state.publicAvatars = [];state.publicAvatarsLoaded = true;+ state.publicAvatarsError = true;if (gridWouldBeEmptyWithout('avatars')) {els.grid.removeAttribute('aria-busy');els.grid.innerHTML = renderErrorState('avatars');@@ -1306,6 +1309,14 @@ function renderGrid() {(!state.onchainLoaded && state.filter === 'onchain');if (stillLoading) {els.grid.innerHTML = renderSkeletons(8);+ } else if (+ state.publicAvatarsError &&+ (state.filter === 'avatars' || state.filter === 'all') &&+ !state.q && !state.tag && !state.category+ ) {+ // The avatar feed failed (e.g. rate-limited) — "No public avatars" would+ // be a lie when the catalog has thousands. Offer a retry instead.+ els.grid.innerHTML = renderErrorState('avatars');} else {els.grid.innerHTML = renderEmptyState();}diff --git a/tests/api/token-market-single-flight.test.js b/tests/api/token-market-single-flight.test.jsindex fbeb4e38c..955d29767 100644--- a/tests/api/token-market-single-flight.test.js+++ b/tests/api/token-market-single-flight.test.js@@ -119,10 +119,16 @@ describe('token-market fleet-wide single-flight', () => {expect(md.source).toBe('dexscreener');expect(upstreamCalls).toHaveLength(1);expect(upstreamCalls[0]).toContain('dexscreener');- // Published for siblings to serve.- expect(store.has('mktdata:v1:' + MINT)).toBe(true);- // Lock released after the fetch (best-effort DEL).- expect(store.has('mktlock:v1:' + MINT)).toBe(false);+ // The publish and the lock DEL are deliberately fire-and-forget (the hot+ // path must not pay a Redis RTT before returning), so poll for them+ // instead of asserting synchronously — cacheSet's async encodeForWire step+ // means the write lands a few ticks after fetchTokenMarketData resolves.+ await vi.waitFor(() => {+ // Published for siblings to serve.+ expect(store.has('mktdata:v1:' + MINT)).toBe(true);+ // Lock released after the fetch (best-effort DEL).+ expect(store.has('mktlock:v1:' + MINT)).toBe(false);+ });});it('fresh:true bypasses the lock entirely (cron / explicit refresh path)', async () => {diff --git a/tests/avatar-thumbs.test.js b/tests/avatar-thumbs.test.jsnew file mode 100644index 000000000..0e93374e9--- /dev/null+++ b/tests/avatar-thumbs.test.js@@ -0,0 +1,200 @@+// api/_lib/avatar-thumbs.js — the module that owns avatar thumbnail coverage.+//+// The invariant under test, and the reason this module exists:+//+// A `thumbnail_key` is only ever persisted AFTER the object behind it has been+// confirmed to exist in R2.+//+// Violating it is not a cosmetic bug. A key pointing at a missing object makes R2+// answer 404 with a `text/plain` body; Chrome then refuses that response for an+// <img> request and logs net::ERR_BLOCKED_BY_ORB. That is exactly what shipped on+// the homepage until 2026-07-09. These tests pin the invariant on both write+// paths (forge-preview adoption and chromium render) so it cannot regress.++import { describe, it, expect, vi, beforeEach } from 'vitest';++// `sql` is a tagged template. Route each call by the SQL text so a test can drive+// the multi-statement flows (select candidates → update → delete claim).+const sqlCalls = [];+let sqlRoutes = [];+// Records every statement, then answers from `sqlRoutes` (first match wins).+// `sqlOrder` lets a test observe write ordering across r2 + db.+const sqlOrder = [];+const defaultSqlImpl = (strings, ...vals) => {+ const text = Array.isArray(strings) ? strings.join('?') : String(strings);+ sqlCalls.push({ text, vals });+ if (/UPDATE avatars/i.test(text)) sqlOrder.push('db');+ const handler = sqlRoutes.find((r) => r.match.test(text));+ return Promise.resolve(handler ? handler.rows : []);+};+const sqlMock = vi.fn(defaultSqlImpl);+vi.mock('../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));++const headObjectMock = vi.fn();+const putObjectMock = vi.fn();+const presignGetMock = vi.fn(async ({ key }) => `https://signed.example/${key}`);+vi.mock('../api/_lib/r2.js', () => ({+ headObject: (...a) => headObjectMock(...a),+ putObject: (...a) => putObjectMock(...a),+ presignGet: (...a) => presignGetMock(...a),+ publicUrl: (key) => `https://cdn.example/${key}`,+ isLegacyOgThumbnailKey: (k) => /^https?:\/\/.*_og\.png$/i.test(String(k || '')),+}));++const renderGlbToPngMock = vi.fn();+vi.mock('../api/_lib/render-glb.js', () => ({ renderGlbToPng: (...a) => renderGlbToPngMock(...a) }));++const { adoptForgePreviews, renderThumbnail, renderBatch, thumbKeyFor, isMissingThumbnail } =+ await import('../api/_lib/avatar-thumbs.js');++const updates = () => sqlCalls.filter((c) => /UPDATE avatars/i.test(c.text));++beforeEach(() => {+ sqlCalls.length = 0;+ sqlOrder.length = 0;+ sqlRoutes = [];+ // mockClear() leaves a previous test's mockImplementation in place — reset the+ // behaviour, not just the call log, or one test silently starves the next.+ sqlMock.mockReset().mockImplementation(defaultSqlImpl);+ headObjectMock.mockReset();+ putObjectMock.mockReset().mockResolvedValue(undefined);+ renderGlbToPngMock.mockReset();+});++describe('isMissingThumbnail — the shared predicate', () => {+ it('treats null / empty as missing', () => {+ expect(isMissingThumbnail(null)).toBe(true);+ expect(isMissingThumbnail('')).toBe(true);+ });++ it('treats an absolute URL as missing (publicUrl passes it through to an origin with no object)', () => {+ expect(isMissingThumbnail('https://three.ws/avatars/michelle_og.png')).toBe(true);+ expect(isMissingThumbnail('https://example.com/x.png')).toBe(true);+ });++ it('treats a relative bucket key as present', () => {+ expect(isMissingThumbnail('thumb/abc.png')).toBe(false);+ expect(isMissingThumbnail('forge/deadbeef/x-poster.webp')).toBe(false);+ });+});++describe('adoptForgePreviews — zero-copy adoption', () => {+ it('persists the preview key once the object is confirmed present', async () => {+ sqlRoutes = [{ match: /FROM avatars a[\s\S]*JOIN forge_creations/i, rows: [{ id: 'av-1', preview_key: 'forge/aa/bb.jpg' }] }];+ headObjectMock.mockResolvedValue({ ContentLength: 1234 });++ const res = await adoptForgePreviews({ limit: 10 });++ expect(res).toEqual({ adopted: 1, missing: 0 });+ expect(headObjectMock).toHaveBeenCalledWith('forge/aa/bb.jpg');+ const up = updates();+ expect(up).toHaveLength(1);+ expect(up[0].vals).toContain('forge/aa/bb.jpg');+ });++ it('NEVER persists a key when the preview object is absent from R2', async () => {+ sqlRoutes = [{ match: /FROM avatars a[\s\S]*JOIN forge_creations/i, rows: [{ id: 'av-1', preview_key: 'forge/gone.jpg' }] }];+ headObjectMock.mockResolvedValue(null); // object was pruned++ const res = await adoptForgePreviews({ limit: 10 });++ expect(res).toEqual({ adopted: 0, missing: 1 });+ // This is the whole point: no UPDATE, so no 404 → no ORB.+ expect(updates()).toHaveLength(0);+ });++ it('treats a headObject failure as absent rather than adopting optimistically', async () => {+ sqlRoutes = [{ match: /FROM avatars a[\s\S]*JOIN forge_creations/i, rows: [{ id: 'av-1', preview_key: 'forge/x.jpg' }] }];+ headObjectMock.mockRejectedValue(new Error('network'));++ const res = await adoptForgePreviews({ limit: 10 });++ expect(res.adopted).toBe(0);+ expect(updates()).toHaveLength(0);+ });++ it('short-circuits with no candidates', async () => {+ sqlRoutes = [];+ const res = await adoptForgePreviews({ limit: 10 });+ expect(res).toEqual({ adopted: 0, missing: 0 });+ expect(headObjectMock).not.toHaveBeenCalled();+ });+});++describe('renderThumbnail — render then commit', () => {+ it('uploads a PNG under thumb/<id>.png with an image/png content-type', async () => {+ renderGlbToPngMock.mockResolvedValue(Buffer.from('fake-png-bytes'));++ const r = await renderThumbnail({ id: 'av-9', storage_key: 'u/1/model.glb' });++ expect(putObjectMock).toHaveBeenCalledTimes(1);+ const arg = putObjectMock.mock.calls[0][0];+ expect(arg.key).toBe('thumb/av-9.png');+ expect(arg.key).toBe(thumbKeyFor('av-9'));+ // A wrong content-type here is the ORB failure mode the audit *thought* it saw.+ expect(arg.contentType).toBe('image/png');+ expect(r.key).toBe('thumb/av-9.png');+ });++ it('presigns the durable storage key rather than trusting a stale URL', async () => {+ renderGlbToPngMock.mockResolvedValue(Buffer.from('png'));+ await renderThumbnail({ id: 'av-9', storage_key: 'u/1/model.glb' });+ expect(presignGetMock).toHaveBeenCalledWith(expect.objectContaining({ key: 'u/1/model.glb' }));+ expect(renderGlbToPngMock.mock.calls[0][0].glbUrl).toBe('https://signed.example/u/1/model.glb');+ });++ it('commits thumbnail_key only after the upload resolves', async () => {+ renderGlbToPngMock.mockResolvedValue(Buffer.from('png'));+ putObjectMock.mockImplementation(async () => { sqlOrder.push('put'); });++ await renderThumbnail({ id: 'av-9', storage_key: 'k.glb' });++ // Upload first, key second. Reverse this and a failed upload leaves a+ // thumbnail_key pointing at nothing — a 404 the browser blocks as ORB.+ expect(sqlOrder).toEqual(['put', 'db']);+ });++ it('throws and writes nothing when the renderer yields no bytes', async () => {+ renderGlbToPngMock.mockResolvedValue(Buffer.alloc(0));+ await expect(renderThumbnail({ id: 'av-9', storage_key: 'k.glb' })).rejects.toThrow(/no bytes/i);+ expect(putObjectMock).not.toHaveBeenCalled();+ expect(updates()).toHaveLength(0);+ });++ it('does not commit a key when the upload fails', async () => {+ renderGlbToPngMock.mockResolvedValue(Buffer.from('png'));+ putObjectMock.mockRejectedValue(new Error('r2 down'));+ await expect(renderThumbnail({ id: 'av-9', storage_key: 'k.glb' })).rejects.toThrow(/r2 down/);+ expect(updates()).toHaveLength(0);+ });+});++describe('renderBatch — bounded drain', () => {+ it('records a failure and keeps going instead of aborting the batch', async () => {+ sqlRoutes = [+ { match: /WITH candidates/i, rows: [+ { id: 'ok-1', storage_key: 'a.glb', name: 'Ok' },+ { id: 'bad-1', storage_key: 'b.glb', name: 'Bad' },+ ] },+ ];+ renderGlbToPngMock.mockImplementation(async ({ glbUrl }) => {+ if (glbUrl.includes('b.glb')) throw new Error('corrupt glb');+ return Buffer.from('png');+ });++ const r = await renderBatch({ limit: 2, concurrency: 1 });++ expect(r.claimed).toBe(2);+ expect(r.rendered).toBe(1);+ expect(r.failed).toBe(1);+ // The failure is written to the ledger so retries stay bounded.+ expect(sqlCalls.some((c) => /avatar_thumbnail_backfill[\s\S]*last_error/i.test(c.text))).toBe(true);+ });++ it('is a no-op when nothing can be claimed', async () => {+ sqlRoutes = [];+ const r = await renderBatch({ limit: 5 });+ expect(r).toMatchObject({ claimed: 0, rendered: 0, failed: 0 });+ expect(renderGlbToPngMock).not.toHaveBeenCalled();+ });+});diff --git a/tests/client-ip-proxy.test.js b/tests/client-ip-proxy.test.jsnew file mode 100644index 000000000..b63e5c57e--- /dev/null+++ b/tests/client-ip-proxy.test.js@@ -0,0 +1,116 @@+// clientIp() — the key every per-IP rate limiter on the platform is bucketed by.+//+// Getting this wrong has two opposite failure modes, and the platform has shipped+// both:+//+// · Trusting req.socket.remoteAddress behind a load balancer collapses every+// visitor into ONE bucket. That was live after the Vercel→Cloud Run migration+// (x-vercel-forwarded-for is never set on GCP), which is why /api/irl/privacy+// answered 429 to its first caller and nobody could delete their own pins.+//+// · Trusting the LEFTMOST X-Forwarded-For entry lets a caller mint a fresh bucket+// per request by sending a random header, so the limits stop limiting.+//+// Google's external ALB appends `<real-client-ip>, <lb-ip>`. The real client is the+// second entry from the right. This file fences that, in both directions.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const REAL_CLIENT = '203.0.113.7'; // TEST-NET-3, the "real" caller+const LB = '35.191.0.1'; // the hop Google appends+const SPOOF = '198.51.100.99'; // TEST-NET-2, caller-supplied garbage++function req(headers = {}, socketAddr = '169.254.1.1') {+ return { headers, socket: { remoteAddress: socketAddr } };+}++// clientIp reads TRUSTED_PROXY_HOPS once at module load, so each hop-count case+// needs a fresh module registry.+async function loadWithHops(hops) {+ vi.resetModules();+ if (hops === undefined) delete process.env.TRUSTED_PROXY_HOPS;+ else process.env.TRUSTED_PROXY_HOPS = String(hops);+ return (await import('../api/_lib/rate-limit.js')).clientIp;+}++const ORIGINAL = process.env.TRUSTED_PROXY_HOPS;+beforeEach(() => { vi.resetModules(); });+afterEach(() => {+ if (ORIGINAL === undefined) delete process.env.TRUSTED_PROXY_HOPS;+ else process.env.TRUSTED_PROXY_HOPS = ORIGINAL;+});++describe('clientIp behind Google’s load balancer (default: 1 trusted hop)', () => {+ it('takes the entry before the load balancer, not the socket peer', async () => {+ const clientIp = await loadWithHops(undefined);+ expect(clientIp(req({ 'x-forwarded-for': `${REAL_CLIENT}, ${LB}` }))).toBe(REAL_CLIENT);+ });++ it('ignores caller-supplied entries to the LEFT of the real client', async () => {+ const clientIp = await loadWithHops(undefined);+ const forged = `${SPOOF}, 10.0.0.1, ${REAL_CLIENT}, ${LB}`;+ expect(clientIp(req({ 'x-forwarded-for': forged }))).toBe(REAL_CLIENT);+ });++ // The whole point: two different callers must land in two different buckets,+ // and one caller must not be able to escape their own bucket by spoofing.+ it('distinct callers key distinctly; a spoofer cannot mint a fresh bucket', async () => {+ const clientIp = await loadWithHops(undefined);+ const a = clientIp(req({ 'x-forwarded-for': `203.0.113.1, ${LB}` }));+ const b = clientIp(req({ 'x-forwarded-for': `203.0.113.2, ${LB}` }));+ expect(a).not.toBe(b);++ const spoof1 = clientIp(req({ 'x-forwarded-for': `1.1.1.1, ${REAL_CLIENT}, ${LB}` }));+ const spoof2 = clientIp(req({ 'x-forwarded-for': `2.2.2.2, ${REAL_CLIENT}, ${LB}` }));+ expect(spoof1).toBe(REAL_CLIENT);+ expect(spoof2).toBe(REAL_CLIENT);+ });++ it('never returns the load balancer address (the global-bucket bug)', async () => {+ const clientIp = await loadWithHops(undefined);+ for (const xff of [`${REAL_CLIENT}, ${LB}`, `${SPOOF}, ${REAL_CLIENT}, ${LB}`]) {+ const ip = clientIp(req({ 'x-forwarded-for': xff }, LB));+ expect(ip).not.toBe(LB);+ expect(ip).not.toBe('169.254.1.1');+ }+ });++ it('a single-entry chain degrades to that entry, never a negative index', async () => {+ const clientIp = await loadWithHops(undefined);+ expect(clientIp(req({ 'x-forwarded-for': REAL_CLIENT }))).toBe(REAL_CLIENT);+ });++ it('tolerates padding, empty segments and a trailing comma', async () => {+ const clientIp = await loadWithHops(undefined);+ expect(clientIp(req({ 'x-forwarded-for': ` ${REAL_CLIENT} , , ${LB} ,` }))).toBe(REAL_CLIENT);+ });+});++describe('clientIp with no load balancer (TRUSTED_PROXY_HOPS=0)', () => {+ it('takes the rightmost entry, which is the client Cloud Run observed', async () => {+ const clientIp = await loadWithHops(0);+ expect(clientIp(req({ 'x-forwarded-for': `${SPOOF}, ${REAL_CLIENT}` }))).toBe(REAL_CLIENT);+ });+});++describe('clientIp without any proxy header', () => {+ it('falls back to the socket — in local dev and tests the socket IS the client', async () => {+ const clientIp = await loadWithHops(undefined);+ expect(clientIp(req({}, '127.0.0.1'))).toBe('127.0.0.1');+ });++ it('returns a stable sentinel when there is nothing to key on', async () => {+ const clientIp = await loadWithHops(undefined);+ expect(clientIp({ headers: {}, socket: {} })).toBe('0.0.0.0');+ });++ // x-vercel-forwarded-for and x-real-ip are settable by any caller on GCP, where+ // nothing strips them. Honouring either would hand a sweeper a fresh bucket per+ // request, so neither may influence the key.+ it('ignores caller-settable x-vercel-forwarded-for and x-real-ip', async () => {+ const clientIp = await loadWithHops(undefined);+ expect(clientIp(req({ 'x-vercel-forwarded-for': SPOOF }, '127.0.0.1'))).toBe('127.0.0.1');+ expect(clientIp(req({ 'x-real-ip': SPOOF }, '127.0.0.1'))).toBe('127.0.0.1');+ expect(clientIp(req({ 'x-vercel-forwarded-for': SPOOF, 'x-forwarded-for': `${REAL_CLIENT}, ${LB}` }))).toBe(REAL_CLIENT);+ });+});diff --git a/tests/public/x402-modal-dom.test.js b/tests/public/x402-modal-dom.test.jsindex 1f35bec44..e5b49166b 100644--- a/tests/public/x402-modal-dom.test.js+++ b/tests/public/x402-modal-dom.test.js@@ -139,8 +139,12 @@ describe('x402 payment modal — trust + a11y', () => {await flush();// Click the Phantom wallet button to start the Solana flow.document.querySelector('[data-wallet="phantom"]').click();- await flush();- await flush();+ // The connect → balance-read → render chain spans several macrotask ticks+ // (rAF is stubbed to setTimeout); a fixed flush count races it under+ // full-suite CPU load, so poll for the state instead.+ await vi.waitFor(() => {+ expect(document.querySelector('.x402-insuff-title')).toBeTruthy();+ });expect(document.querySelector('.x402-insuff-title')?.textContent).toMatch(/not enough/i);expect(document.body.textContent).toContain('short by');diff --git a/tests/vanity-wasm-grinder.test.js b/tests/vanity-wasm-grinder.test.jsindex 257cf66d9..f27aea2de 100644--- a/tests/vanity-wasm-grinder.test.js+++ b/tests/vanity-wasm-grinder.test.js@@ -75,15 +75,17 @@ describe('vanity-grinder WASM', () => {it('one batch (5000) returns within budget — bounds the worker abort latency', () => {// The worker drives grind() in 5000-key batches and only checks the- // abort flag between batches. Real-browser WASM hits ~50ms per batch;- // shared CI runners (codespaces, GH Actions) can stretch to ~2s under- // load. Cap at 3s so we still catch a true regression without flaking.+ // abort flag between batches. Real-browser WASM hits ~50ms per batch.+ // This is a WALL-clock read: when the full suite saturates every core,+ // this fork gets scheduler-starved and a 3s cap flaked. 10s still fails+ // on any real regression (an accidental jumbo batch or a quadratic bug+ // is orders of magnitude, not seconds) without tripping on contention.const seed = new Uint8Array(32);crypto.getRandomValues(seed);const t0 = performance.now();grind('zzzzzz', '', false, 5000, seed); // 6-char — won't matchconst elapsed = performance.now() - t0;- expect(elapsed).toBeLessThan(3000);+ expect(elapsed).toBeLessThan(10_000);});it('returns null when no match in batch', () => {