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
perf(img): resize remote artwork to WebP tiles on the server so Forge gallery cards fetch 20-40 KB instead of full renders
nirholas3e5712ce05d1
diff --git a/api/img.js b/api/img.jsindex 42b6a50c8..f7edd01cc 100644--- a/api/img.js+++ b/api/img.js@@ -35,6 +35,44 @@ import { limits, clientIp } from './_lib/rate-limit.js';import { fetchModel } from './_lib/fetch-model.js';import { safeFetchJson } from './_lib/ssrf.js';+// `?w=<px>` resizes a raster upstream to at most that width and re-encodes it+// as WebP. Gallery surfaces (the Forge showcase, the marketplace grid) paint+// full-resolution renders (a 1 MB PNG per card was normal on /forge) into+// 200-300 px boxes; served through here at the box's size they are ~20-40 KB.+// Widths snap to a fixed ladder so a gallery cannot mint an unbounded set of+// variants at the edge, and the result inherits the immutable cache below:+// the same upstream URL at the same width is the same bytes forever.+const RESIZE_WIDTHS = [64, 96, 128, 192, 256, 320, 480, 640, 960];+const RESIZE_MAX_INPUT_PIXELS = 64_000_000;+const RESIZE_WEBP_QUALITY = 82;+const RESIZABLE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/avif', 'image/tiff']);++function requestedWidth(raw) {+ const n = Number.parseInt(raw ?? '', 10);+ if (!Number.isFinite(n) || n <= 0) return 0;+ return RESIZE_WIDTHS.find((w) => w >= n) ?? RESIZE_WIDTHS[RESIZE_WIDTHS.length - 1];+}++// Returns { bytes, contentType } for the delivered image: the resized WebP when+// the request asked for a width and the upstream is a raster we can decode, the+// untouched upstream bytes otherwise (SVG/GIF, an undecodable file, or a+// resizer failure all fall back to the original so the loader still gets a 200).+async function deliverable(image, width) {+ const contentType = String(image.contentType || '').split(';')[0].trim().toLowerCase();+ if (!width || !RESIZABLE_TYPES.has(contentType)) return { bytes: image.bytes, contentType: image.contentType };+ try {+ const sharp = (await import('sharp')).default;+ const bytes = await sharp(Buffer.from(image.bytes), { limitInputPixels: RESIZE_MAX_INPUT_PIXELS })+ .rotate()+ .resize({ width, withoutEnlargement: true })+ .webp({ quality: RESIZE_WEBP_QUALITY })+ .toBuffer();+ return { bytes, contentType: 'image/webp' };+ } catch {+ return { bytes: image.bytes, contentType: image.contentType };+ }+}+const MAX_BYTES = 8 * 1024 * 1024; // 8 MB: generous for token art, bounded for abuse// 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@@ -248,6 +286,7 @@ export default wrap(async function handler(req, res) {const directUrl = url.searchParams.get('url');const metaUri = url.searchParams.get('meta');const seed = url.searchParams.get('seed') || directUrl || metaUri || '';+ const width = requestedWidth(url.searchParams.get('w'));// Accept one of: ?url=<image>, ?meta=<metadata-json>, or ?seed=<x> (placeholder// only). Callers streaming launch feeds pass `meta` so the real artwork is@@ -320,11 +359,12 @@ export default wrap(async function handler(req, res) {return;}+ const out = await deliverable(image, width);res.statusCode = 200;- res.setHeader('content-type', image.contentType);+ res.setHeader('content-type', out.contentType);res.setHeader('access-control-allow-origin', '*');// Immutable: a given upstream URL is content-addressed (IPFS) or a fixed CDN// asset, so the bytes never change. Cache hard at the browser and the edge.res.setHeader('cache-control', 'public, max-age=86400, s-maxage=604800, immutable');- res.end(Buffer.from(image.bytes));+ res.end(Buffer.from(out.bytes));});diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 1b845cb83..00d5985de 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -6668,6 +6668,42 @@ partial answer is still a partial answer.---+## Image proxy API++```+GET /api/img?url=<https-or-ipfs-image-url>+GET /api/img?url=<image-url>&w=480+GET /api/img?meta=<token-metadata-json-url>+GET /api/img?seed=<any-string>+```++Same-origin delivery for remote artwork, so the browser only ever talks to+three.ws. The upstream is fetched server-side through the SSRF-hardened+fetcher (public hosts only, 8 MB cap, one shared 25 s budget); an IPFS URL is+raced across several public gateways and the first valid image wins; a+`?url=` that turns out to be a token *metadata* document is followed one hop to+its `image` field (`?meta=` says so explicitly). When every source fails the+endpoint still answers `200` with a deterministic, on-brand SVG placeholder+derived from the seed, so an `<img>` or a Three.js texture loader never logs an+error.++`w` asks for a resized copy: the image is scaled to at most that width (never+enlarged) and re-encoded as WebP at quality 82. Widths snap up to a fixed+ladder (`64, 96, 128, 192, 256, 320, 480, 640, 960`), so a gallery cannot mint+an unbounded set of variants at the edge. Only rasters are resized (PNG, JPEG,+WebP, AVIF, TIFF); an SVG or GIF, or a file the resizer cannot decode, comes+back as the original bytes. Ask for the width the box paints at 2x: the Forge+showcase requests `w=480` for a card that renders at roughly 240 px, which+turns a 1 MB stored render into a 20-40 KB tile+([src/shared/image-url.js](../src/shared/image-url.js) builds the URL and+leaves same-origin, `data:` and `blob:` sources untouched).++Real images are cached immutably (`max-age=86400, s-maxage=604800, immutable`):+the same upstream URL at the same width is the same bytes forever, so route a+URL through here only when its content never changes in place. Placeholders+cache for 5 minutes at the browser and an hour at the edge so a transiently+down source can recover. Rate limit: 300 requests per 5 minutes per IP.+## Subscriptions APIRecurring creator subscriptions. A creator publishes one or more **plans**diff --git a/src/forge-showcase.js b/src/forge-showcase.jsindex 2386c1851..83f3b5cc3 100644--- a/src/forge-showcase.js+++ b/src/forge-showcase.js@@ -12,6 +12,7 @@// The section stays hidden when the deployment has no durable store or the// feed is empty — a first-time visitor never sees a broken or hollow strip.+import { resizedImageUrl } from './shared/image-url.js';import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';ensureStateKitStyles();ensureShowcaseVoteStyles();@@ -391,7 +392,8 @@ function buildCard(c) {// deferring the decode cannot shift layout.img.decoding = 'async';img.alt = '';- img.src = c.preview_image_url;+ // Full-resolution render, 200px-tall box: fetch it at the box's size.+ img.src = resizedImageUrl(c.preview_image_url, 480);img.onerror = () => {// Drop the broken <img> the moment it fails. GLB capture is queued one// at a time behind a 20s timeout, so leaving it in place parks a row ofdiff --git a/src/forge.js b/src/forge.jsindex 83d585a2b..95c791197 100644--- a/src/forge.js+++ b/src/forge.js@@ -1,4 +1,5 @@// Forge — text / image / multi-view → 3D generator (browser client).+import { resizedImageUrl } from './shared/image-url.js';import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';import {sleepUntilVisibleOrElapsed,@@ -2087,8 +2088,11 @@ async function loadGallery() {const img = document.createElement('img');img.className = 'thumb';img.loading = 'lazy';+ img.decoding = 'async';img.alt = '';- img.src = c.preview_image_url;+ // The stored preview is a full-resolution render; the card box is a+ // few hundred pixels wide. Fetch it at the box's size (2x for retina).+ img.src = resizedImageUrl(c.preview_image_url, 480);img.onerror = () => {// Thumbnail URL broken — show gradient fallback.img.replaceWith(makeGradientThumb(c.prompt));diff --git a/src/shared/image-url.js b/src/shared/image-url.jsnew file mode 100644index 000000000..8e9ebe426--- /dev/null+++ b/src/shared/image-url.js@@ -0,0 +1,27 @@+// Same-origin, size-bounded URLs for remote artwork.+//+// Gallery cards paint stored renders (forge previews, marketplace art) into+// boxes a few hundred pixels wide, but the stored file is the full-resolution+// render: a 1 MB PNG per card was normal on /forge. /api/img resizes on the+// server (snapped to a fixed width ladder, re-encoded as WebP, cached+// immutably at the edge), so a card fetches ~20-40 KB instead. Pass the width+// the box paints at 2x; the endpoint rounds up to its ladder.+//+// Only remote http(s) sources go through the proxy. Same-origin paths,+// data: and blob: URLs are returned untouched: they are already local, or+// they are a capture the page just produced.+const PROXY_PATH = '/api/img';++export function resizedImageUrl(url, width) {+ if (typeof url !== 'string' || !url) return url;+ if (!/^https?:\/\//i.test(url)) return url;+ try {+ if (typeof location !== 'undefined' && new URL(url).origin === location.origin) return url;+ } catch {+ return url;+ }+ const w = Math.max(1, Math.round(Number(width) || 0));+ const params = new URLSearchParams({ url });+ if (w > 1) params.set('w', String(w));+ return `${PROXY_PATH}?${params}`;+}