Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(render): apply the requested pose on every rig and reject markup in the render background

nirholas69f3519e8ab6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index da9cddc90..afa351d7e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -33,10 +33,12 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Pinning an avatar to IPFS works for real avatars, not just tiny ones**: Minting an avatar from the Avatar Studio pins the model and its metadata to IPFS, and the whole file is sent through the platform so the storage credential never has to reach your browser. The endpoint said it accepted files up to 10 MB, but it was actually rejecting anything over roughly 730 KB, which is smaller than almost any real avatar. The error it gave back was a bare 'payload too large' that named no limit, so there was nothing to act on. The cause was two size limits that had never been reconciled: files are sent as text, which makes them a third larger in transit, and the transport limit was left at its default while the documented limit was set eight times higher. The limits now agree. Inline uploads are accepted up to 5 MB, which is what the request size can actually carry, and anything larger has a clear path: upload it to storage first and pin it by URL, a lane that has always accepted 50 MB. Over-sized uploads now say which ceiling was crossed. Two smaller fixes came with it: the filename you send is now the filename filed with the storage provider, instead of every avatar being stored as 'avatar.glb' and every metadata file as 'manifest.json', which made a pin list impossible to read; and a request with a genuine mistake in it, such as a file from somewhere the platform does not own, now gets an error explaining the mistake rather than a generic 'service unavailable' that hid it. The endpoint is now documented in the API reference. `[fix, docs]`
- **Plan checkout: a paid upgrade can only ever settle on real mainnet, and a late payment is no longer stranded**: Paying for a plan creates a quote, you send the funds, then the server checks the chain before it upgrades you. Three things in that path were wrong. The checkout side has always refused test-network quotes in production, because test-network dollars are free from a faucet, but the confirm side still let a caller name the test network itself, and it is the confirm side that decides which chain it looks at and which dollar it accepts. Both ends now read the same setting, so a production upgrade can only ever be settled by real funds on mainnet. Second, an Ethereum-side payment has to wait twelve blocks before it counts, which meant funds sent near the end of a session could land on-chain and then be refused for arriving late, with the money already gone; that lane now honors the same one-hour grace window the Solana lane has, so an on-chain payment is always claimable. Third, confirming an Ethereum payment could reach a Solana quote and mark it expired, and asking to buy a skill from a malformed agent id answered a generic server error instead of telling you what was wrong with the request. (`/pricing`) `[fix, security]`
- **Portfolio token pages price Base and Arbitrum holdings correctly**: Opening a token from your portfolio asked Ethereum for the price no matter which chain the token was actually on. Almost every agent wallet runs on Base, so the most common holdings came back with no price, no chart and a shortened contract address instead of a ticker, even though the balance was right there in the list. Each token is now priced on its own chain, labelled with its real symbol and decimals, and native gas tokens use the right coin per chain (POL on Polygon, BNB on BNB Chain, AVAX on Avalanche) instead of always quoting ETH. Chains nobody prices, such as testnets, now say so plainly rather than showing another chain's number. `[fix]`
+- **Posed avatar renders finally come out posed**: Asking the public avatar renderer for a pose returned a T-pose on most models: it matched bone names against a short hand-written list, and any rig that did not use those exact names (including every Mixamo export) was silently left in its bind pose while the response still claimed the pose had been applied. The renderer now uses the same posing engine the pose studio uses, so a preset now lands whatever naming convention the model's skeleton uses, and the camera frames the posed figure rather than the unposed one. The background colour on both public renderers is now checked before it is used, and the per-render budget is counted across the whole fleet instead of per server. (`/docs/api-reference`) `[fix, security]`
- **Private avatars no longer show their picture in registry lookups**: The registry lookup that turns an agent id, avatar id, slug, or Solana mint into one record already refused to hand out the 3D model of a private avatar, but it still returned the rendered preview image of that same avatar, so anyone holding the id could see what a private creation looked like. The preview is now gated on exactly the same visibility as the model: a private avatar returns its name and identity and no imagery at all. The embeddable widget read did the same thing with its avatar thumbnail and got the same gate. Separately, every read path that turns a stored thumbnail into a URL now goes through the one resolver that drops the old broken image keys, so agent manifests, token metadata, and launch feeds stop publishing image links that answer 404. `[security, fix]`
- **Push notification sign-up now only accepts a real push service address**: Turning on browser notifications hands the platform the address your browser wants alerts delivered to, and that address is one the platform later calls from its own servers. It was stored exactly as given, so a crafted sign-up could point it at an internal address instead of a push service and use the delivery job as a way to knock on doors inside our own network. Sign-up now checks the address before storing it: it has to be an ordinary secure web address on a genuinely public host, or it is refused with a clear reason. If the check cannot finish because name lookup is briefly down, the browser is told to try again rather than being turned away for good. Delivery re-checks every stored address at send time too, so anything registered before this landed can never be dialed, and an address that could never be legal is dropped from the list the way an expired one already was. `[security]`
- **Rotating or revoking an x402 API key now requires a proof the request came from you**: The billing page's rotate and revoke buttons destroy a live API credential, but the endpoint behind them accepted any request that carried your session cookie. A page on another site could have posted to it and killed a working key without you ever seeing the response. Both actions now require a single-use token the page fetches for each write, and the page tells you plainly when a token has gone stale or you have tried too often. Rotating also mints the replacement key before retiring the old one, so a failure part way through can no longer leave you with no key at all. (`/billing/keys`) `[security, fix]`
- **Saving a big build no longer re-downloads the whole world first**: Every time you saved a world, the service fetched and re-parsed the entire previous version of that world just to check who owns it. On a large build that meant a full extra download and parse on each autosave, for a single ownership field. The check now reads only the small index record, so saves on big worlds are noticeably quicker and the storage layer does half the work. Two error replies also got honest labels: a build that exceeds the size cap now answers "payload too large" and a request sent with the wrong content type answers "unsupported media type", instead of both arriving as a generic validation error that gave a client nothing to act on. `[improvement, fix]`
+- **Scanning a skill purchase QR tells you when your wallet is short**: Paying for a skill from a phone handed the wallet a transfer even when the wallet held none of the token being asked for, so the buyer signed and watched it fail with whatever cryptic message their wallet chose to print. The checkout now checks the paying wallet first and answers with the exact shortfall, so a wallet that is 0.35 short says so and a wallet that has never held the token says that instead of failing at signing time. The same checkout also stopped pinning the busiest public Solana node ahead of the platform's own faster ones, so building the payment is quicker and survives a throttled node. `[improvement, fix]`
- **Scanning for trade candidates is faster on creator-filtered rules and honest about how much it looked at**: The Trading Brain's "Scan for matches" preview shows the live launches your rule would buy right now, each with a real quote and a real safety verdict, and it never trades on its own. Three fixes. A rule that filters on the creator's track record has to look that record up over the network, and the scan was buying that lookup for every launch in the feed page, including ones it had already rejected for being too old or too small; it now pays for a creator lookup only when the rest of the rule already likes the coin, which is the difference between a scan that returns and one that crawls. The result said it had scanned the whole feed page even though it stops as soon as it has priced six matches, so the count overstated the work behind the answer; it now reports what it actually examined alongside the size of the page it read from. And an agent's Solana address is a field you can edit, so a value that is not a real address turned the preview into a server error rather than a scan; the safety check now resolves that address itself and the scan completes. The scan also gained its own per-owner limit, because every match it prices costs a live on-chain quote and a safety simulation. Separately, when the Trading Brain refuses something, the panel now shows the reason the server sent instead of a generic "Scan failed", so a rate limit, a kill switch, or an unreachable launch feed each read as themselves. `[fix, improvement]`
- **Seeding an agent from GitHub is locked to your own click, and a mistyped pick no longer costs you six hours**: Three fixes to the GitHub memory lane, the one that reads the profile, repositories, and READMEs you tick and distills them into what your agent knows about your work. First: writing or deleting those memories now requires the one-time token the site attaches to your own actions, so another site cannot make your browser re-seed or wipe an agent behind your back. Every neighbouring memory action already worked this way; this one did not. Second: seeding is allowed once every six hours per agent, and that window used to be spent by attempts that never read anything, so ticking nothing and pressing Seed, or picking a repository that had been renamed since the list loaded, locked you out for six hours over a correctable mistake. The window is now taken only once your selection checks out, immediately before anything is actually read. Third: when every model provider is busy at once, the seed used to fail with a bare internal error and a support reference; it now says plainly that nothing was read, that your existing memories are untouched, and roughly how long until you can try again. (`/docs/github-memory-seeding`) `[security, fix]`
- **Self-hosting docs no longer hand you a command that wipes your environment**: The deployment guide told self-hosters to set Cloud Run environment variables with `gcloud run services update --set-env-vars`. That flag replaces the service environment wholesale, so following the instruction for a single key silently deletes every other variable the service had. The guide now uses `--update-env-vars` and says plainly why. Four more corrections landed in the same sweep across the deployment, configuration and contributing pages: the Avaturn signup link and the GitHub Discussions links were dead (Discussions are not enabled on the repository, so bug reports and design questions both go to Issues); the in-browser avatar builder was documented as needing its own hosted origin in production when the normal build already serves it same-origin at /avatar-studio; and three counts that had drifted from the code (cron jobs, MCP server packages, contract tests) were replaced with pointers to the files that hold the real numbers. (`/docs/deployment`) `[docs, fix]`
diff --git a/api/_lib/avatar-render.js b/api/_lib/avatar-render.js
index b98db2198..4d2d93954 100644
--- a/api/_lib/avatar-render.js
+++ b/api/_lib/avatar-render.js
@@ -5,12 +5,13 @@
// duplicated chromium code anywhere else.
import { createHash } from 'node:crypto';
-import { readFileSync } from 'node:fs';
// puppeteer-core + @sparticuz/chromium-min are loaded lazily inside getBrowser()
// so Vercel's NFT does not statically trace the chromium binary tree on every
// route in a function package, that trace was the 45-min build timeout.
import { env } from './env.js';
import { publicUrl, putObject, headObject } from './r2.js';
+import { poseRuntimeModules } from './pose-runtime.js';
+import { scriptJson, safeCssColor } from './render-safe.js';
import { PRESETS } from '../../src/pose-presets.js';
export const MIN_DIM = 64;
@@ -151,7 +152,22 @@ export function resolveRenderParams(input = {}) {
const size = clamp(toInt(input.size, DEFAULT_SIZE), MIN_DIM, MAX_DIM);
const width = clamp(toInt(input.width, size), MIN_DIM, MAX_DIM);
const height = clamp(toInt(input.height, size), MIN_DIM, MAX_DIM);
- const bg = input.bg || 'transparent';
+ // `bg` is interpolated into the render page's script block, and that page has
+ // container network egress, so an unvalidated string here is caller JS with an
+ // internal-network view. Reject anything that is not a CSS color rather than
+ // silently swapping in a default the caller did not ask for.
+ let bg = 'transparent';
+ if (input.bg && input.bg !== 'transparent') {
+ bg = safeCssColor(input.bg);
+ if (!bg) {
+ return {
+ error: {
+ code: 'invalid_bg',
+ message: 'bg must be "transparent" or a CSS color (hex, rgb()/rgba(), hsl()/hsla(), or a named color)',
+ },
+ };
+ }
+ }
const format = FORMAT_TYPES[input.format] ? input.format : 'png';
const quality = clamp(toInt(input.quality, 90), 1, 100);
@@ -305,47 +321,21 @@ async function getBrowser() {
return _browserPromise;
}
-// The pose studio's posing stack (src/pose-rig.js + src/glb-canonicalize.js +
-// src/pose-mannequin.js) is pure three.js ESM, so the headless page runs the
-// EXACT same code the client does: canonical bone-name mapping for every rig
-// convention, and world-delta preset retargeting (poseFromMannequinPreset →
-// GltfRig.applyPose) that lands presets on top of any bind stance. The
-// sources are shipped to the page as data: URL modules in its import map,
-// with pose-rig's relative imports rewritten to the bare specifiers the map
-// defines. Never reintroduce a hand-rolled alias table here, it silently
-// missed every Mixamo rig (GLTFLoader strips ':' from node names) and stomped
-// absolute local Eulers over bind rotations on the rest.
-const SRC_DIR = new URL('../../src/', import.meta.url);
-
-function poseModuleDataUrl(file, rewrites = []) {
- let code = readFileSync(new URL(file, SRC_DIR), 'utf8');
- for (const [from, to] of rewrites) code = code.replaceAll(from, to);
- if (/from\s+['"]\.{1,2}\//.test(code)) {
- throw new Error(`avatar-render: ${file} still has relative imports after rewrite, update poseRuntimeModules()`);
- }
- return 'data:text/javascript;base64,' + Buffer.from(code, 'utf8').toString('base64');
-}
-
-let _poseRuntimeModules = null;
-export function poseRuntimeModules() {
- if (_poseRuntimeModules) return _poseRuntimeModules;
- _poseRuntimeModules = {
- 'glb-canonicalize': poseModuleDataUrl('glb-canonicalize.js'),
- 'pose-mannequin': poseModuleDataUrl('pose-mannequin.js'),
- 'pose-rig': poseModuleDataUrl('pose-rig.js', [
- ["from './glb-canonicalize.js'", "from 'glb-canonicalize'"],
- ["from './pose-mannequin.js'", "from 'pose-mannequin'"],
- ]),
- };
- return _poseRuntimeModules;
-}
+// The posing stack the render page runs lives in ./pose-runtime.js, shared with
+// api/_lib/render-clip.js so the two chromium renderers can never disagree about
+// which rigs a preset lands on. Re-exported for callers that already import it
+// from here.
+export { poseRuntimeModules };
export function sceneViewerHtml({ glbUrl, width, height, background, pose, cameraOrbit, expression, scenePreset }) {
- const bg = background === 'transparent' ? 'null' : JSON.stringify(background || '#0a0a0a');
- const poseJson = pose ? JSON.stringify(pose) : 'null';
- const orbitJson = JSON.stringify(cameraOrbit || { theta: 0, phi: 80, radius: null });
- const expressionJson = JSON.stringify(expression || null);
- const presetJson = JSON.stringify(scenePreset);
+ // Every value below is interpolated into a <script> block. scriptJson (not
+ // JSON.stringify) is what keeps a caller-supplied string from closing the tag
+ // and running its own code in a page with container network egress.
+ const bg = background === 'transparent' ? 'null' : scriptJson(safeCssColor(background) || '#0a0a0a');
+ const poseJson = pose ? scriptJson(pose) : 'null';
+ const orbitJson = scriptJson(cameraOrbit || { theta: 0, phi: 80, radius: null });
+ const expressionJson = scriptJson(expression || null);
+ const presetJson = scriptJson(scenePreset);
const poseModules = poseRuntimeModules();
return `<!doctype html>
@@ -465,7 +455,7 @@ loader.setDRACOLoader(dracoLoader);
loader.setKTX2Loader(ktx2Loader);
loader.setMeshoptDecoder(MeshoptDecoder);
-loader.load(${JSON.stringify(glbUrl)}, (gltf) => {
+loader.load(${scriptJson(glbUrl)}, (gltf) => {
try {
const root = gltf.scene;
scene.add(root);
diff --git a/api/_lib/pose-runtime.js b/api/_lib/pose-runtime.js
new file mode 100644
index 000000000..c20c1cf1b
--- /dev/null
+++ b/api/_lib/pose-runtime.js
@@ -0,0 +1,47 @@
+// The client posing stack, shipped into a headless-chromium render page.
+//
+// src/pose-rig.js + src/glb-canonicalize.js + src/pose-mannequin.js are pure
+// three.js ESM, so a render page can run the EXACT code the browser runs:
+// canonical bone-name mapping for every rig convention we support, and
+// world-delta preset retargeting (poseFromMannequinPreset then
+// GltfRig.applyPose) that lands a preset on top of any bind stance.
+//
+// The sources go to the page as data: URL modules in its import map, with
+// pose-rig's relative imports rewritten to the bare specifiers the map
+// defines. Never reintroduce a hand-rolled alias table in a renderer: one
+// silently missed every Mixamo rig (GLTFLoader strips ':' from node names) and
+// stomped absolute local Eulers over bind rotations on the rest, so
+// /api/render/avatar-clip answered 200 with an unposed model.
+
+import { readFileSync } from 'node:fs';
+
+const SRC_DIR = new URL('../../src/', import.meta.url);
+
+function poseModuleDataUrl(file, rewrites = []) {
+ let code = readFileSync(new URL(file, SRC_DIR), 'utf8');
+ for (const [from, to] of rewrites) code = code.replaceAll(from, to);
+ if (/from\s+['"]\.{1,2}\//.test(code)) {
+ throw new Error(`pose-runtime: ${file} still has relative imports after rewrite, update poseRuntimeModules()`);
+ }
+ return 'data:text/javascript;base64,' + Buffer.from(code, 'utf8').toString('base64');
+}
+
+let _poseRuntimeModules = null;
+
+/**
+ * Import-map entries for the posing stack, built once per container.
+ *
+ * @returns {{['glb-canonicalize']:string,['pose-mannequin']:string,['pose-rig']:string}}
+ */
+export function poseRuntimeModules() {
+ if (_poseRuntimeModules) return _poseRuntimeModules;
+ _poseRuntimeModules = {
+ 'glb-canonicalize': poseModuleDataUrl('glb-canonicalize.js'),
+ 'pose-mannequin': poseModuleDataUrl('pose-mannequin.js'),
+ 'pose-rig': poseModuleDataUrl('pose-rig.js', [
+ ["from './glb-canonicalize.js'", "from 'glb-canonicalize'"],
+ ["from './pose-mannequin.js'", "from 'pose-mannequin'"],
+ ]),
+ };
+ return _poseRuntimeModules;
+}
diff --git a/api/_lib/render-clip.js b/api/_lib/render-clip.js
index 7a3f967ef..8f52ecf3e 100644
--- a/api/_lib/render-clip.js
+++ b/api/_lib/render-clip.js
@@ -19,6 +19,8 @@
// that transitively imports this module, that trace caused 45-min build hangs.
import { env } from './env.js';
import { fetchModel } from './fetch-model.js';
+import { scriptJson, safeCssColor } from './render-safe.js';
+import { poseRuntimeModules } from './pose-runtime.js';
import { PRESETS } from '../../src/pose-presets.js';
// Cap on GLB bytes pulled into the renderer (OOM / render-budget guard).
@@ -57,25 +59,16 @@ function poseById(id) {
return found ? { id: found.id, label: found.label, pose: found.pose } : null;
}
-// JSON.stringify is not enough to embed a value inside a <script> block: it
-// leaves "</script" and the JS line terminators U+2028/U+2029 intact, so any
-// caller-supplied string (a background color, a pose label) could close the tag
-// and run its own code inside the render page. That page has network access, so
-// injected script can fetch internal endpoints and paint them into the
-// screenshot we hand back. Escape here, once, so no caller has to remember to.
-export function scriptJson(value) {
- return JSON.stringify(value === undefined ? null : value)
- .replace(/</g, '\\u003c')
- .replace(/>/g, '\\u003e')
- .replace(/\u2028/g, '\\u2028')
- .replace(/\u2029/g, '\\u2029');
-}
+// Re-exported so callers that already import the escaper from this module keep
+// working; the implementation is shared with render-glb.js in ./render-safe.js.
+export { scriptJson };
function viewerHtml({ glbBase64, width, height, background, pose, cameraOrbit, expression }) {
- const bg = background === 'transparent' ? 'null' : scriptJson(background || '#0a0a0a');
+ const bg = background === 'transparent' ? 'null' : scriptJson(safeCssColor(background) || '#0a0a0a');
const poseJson = pose ? scriptJson(pose.pose) : 'null';
const orbitJson = scriptJson(cameraOrbit || { theta: 0, phi: 80, radius: null });
const expressionJson = scriptJson(expression || null);
+ const poseModules = poseRuntimeModules();
return `<!doctype html>
<html><head><meta charset="utf-8" />
<style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}</style>
@@ -84,7 +77,10 @@ function viewerHtml({ glbBase64, width, height, background, pose, cameraOrbit, e
<script>window.__GLB_B64=${scriptJson(glbBase64)};</script>
<script type="importmap">{ "imports": {
"three": "https://unpkg.com/three@${THREE_VERSION}/build/three.module.js",
- "three/addons/": "https://unpkg.com/three@${THREE_VERSION}/examples/jsm/"
+ "three/addons/": "https://unpkg.com/three@${THREE_VERSION}/examples/jsm/",
+ "glb-canonicalize": "${poseModules['glb-canonicalize']}",
+ "pose-mannequin": "${poseModules['pose-mannequin']}",
+ "pose-rig": "${poseModules['pose-rig']}"
}}</script>
<script type="module">
import * as THREE from 'three';
@@ -93,6 +89,7 @@ import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import { makeGltfRig, poseFromMannequinPreset } from 'pose-rig';
window.__renderDone = false;
window.__renderError = null;
@@ -128,42 +125,17 @@ const key = new THREE.DirectionalLight(0xffffff, 1.6); key.position.set(2.5, 3.5
const fill = new THREE.DirectionalLight(0xdfeaff, 0.5); fill.position.set(-3, 1.2, 2.5); scene.add(fill);
const rim = new THREE.DirectionalLight(0xecdcff, 0.7); rim.position.set(-0.5, 2.5, -4); scene.add(rim);
-const aliases = {
- shoulderl: ['leftshoulder','shoulder_l','l_shoulder','mixamorig:leftshoulder'],
- shoulderr: ['rightshoulder','shoulder_r','r_shoulder','mixamorig:rightshoulder'],
- elbowl: ['leftforearm','leftelbow','elbow_l','mixamorig:leftforearm','mixamorig:leftelbow'],
- elbowr: ['rightforearm','rightelbow','elbow_r','mixamorig:rightforearm','mixamorig:rightelbow'],
- wristl: ['lefthand','wrist_l','mixamorig:lefthand'],
- wristr: ['righthand','wrist_r','mixamorig:righthand'],
- hipl: ['leftupleg','hip_l','mixamorig:leftupleg'],
- hipr: ['rightupleg','hip_r','mixamorig:rightupleg'],
- kneel: ['leftleg','knee_l','mixamorig:leftleg'],
- kneer: ['rightleg','knee_r','mixamorig:rightleg'],
- anklel: ['leftfoot','ankle_l','mixamorig:leftfoot'],
- ankler: ['rightfoot','ankle_r','mixamorig:rightfoot'],
- head: ['head','mixamorig:head'],
- neck: ['neck','mixamorig:neck'],
- spine: ['spine','spine1','mixamorig:spine','mixamorig:spine1'],
- hips: ['hips','mixamorig:hips'],
-};
-
+// Preset poses are authored in the mannequin convention (src/pose-presets.js);
+// poseFromMannequinPreset converts them to canonical world-frame deltas and
+// GltfRig.applyPose replays those on the avatar's OWN rest pose, the same path
+// the /pose studio uses. A preset therefore lands identically whether the rig
+// binds T-pose or A-pose and whatever naming convention its bones use. Rigs
+// with no recognizable humanoid skeleton stay in bind pose (nothing safe to map).
function applyPose(root, poseMap) {
if (!poseMap) return;
- const byName = new Map();
- root.traverse((o) => { if (o.name) byName.set(o.name.toLowerCase(), o); });
- function findJoint(k) {
- const key = k.toLowerCase();
- const direct = byName.get(key);
- if (direct) return direct;
- const list = aliases[key] || [];
- for (const a of list) { const j = byName.get(a); if (j) return j; }
- return null;
- }
- for (const [key, rot] of Object.entries(poseMap)) {
- const joint = findJoint(key);
- if (!joint) continue;
- joint.rotation.set(rot.x || 0, rot.y || 0, rot.z || 0);
- }
+ const rig = makeGltfRig(root);
+ if (!rig) return;
+ rig.applyPose(poseFromMannequinPreset(poseMap));
}
function applyExpression(root, expression) {
@@ -178,6 +150,14 @@ function applyExpression(root, expression) {
}
function frameCamera(root, orbit) {
+ // Frame the POSED skin, not the bind-pose geometry: Box3.setFromObject defers
+ // to SkinnedMesh.computeBoundingBox (CPU skinning), which reads current bone
+ // matrices, so the graph and each skeleton must be updated first or a raised
+ // arm frames as if it were still at the model's side. (Never reset rigs via
+ // THREE.Skeleton.pose(): it rebuilds bind from inverse-bind matrices and
+ // collapses Mixamo rigs.)
+ root.updateMatrixWorld(true);
+ root.traverse((o) => { if (o.isSkinnedMesh && o.skeleton) o.skeleton.update(); });
const box = new THREE.Box3().setFromObject(root);
const size = new THREE.Vector3(); box.getSize(size);
const center = new THREE.Vector3(); box.getCenter(center);
diff --git a/api/_lib/render-glb.js b/api/_lib/render-glb.js
index ac2420fac..e293b8dfe 100644
--- a/api/_lib/render-glb.js
+++ b/api/_lib/render-glb.js
@@ -14,6 +14,7 @@
// that transitively imports this module — that trace caused 45-min build hangs.
import { env } from './env.js';
import { fetchModel } from './fetch-model.js';
+import { scriptJson, safeCssColor } from './render-safe.js';
// Cap on GLB bytes pulled into the renderer. Anything larger risks OOM /
// blowing the render budget; callers may tighten this via `maxBytes`.
@@ -133,17 +134,24 @@ function releaseRenderSlot() {
function viewerHtml({ glbBase64, width, height, background, backdrop }) {
// A gradient backdrop renders as page CSS behind a transparent canvas: the
// screenshot composites the two, so the scene itself stays background-free.
- const useGradient = backdrop && backdrop.inner && backdrop.outer;
- const bg = useGradient || background === 'transparent' ? 'null' : JSON.stringify(background || '#0a0a0a');
+ // `background` reaches here straight from a public handler, and both slots
+ // below are string interpolations into markup: the <style> block would take a
+ // "</style><script>" breakout and the <script> block a "</script>" one, which
+ // would run caller JS inside a page that has container network egress. Colors
+ // are validated (safeCssColor) and script values escaped (scriptJson).
+ const inner = safeCssColor(backdrop?.inner);
+ const outer = safeCssColor(backdrop?.outer);
+ const useGradient = Boolean(inner && outer);
+ const bg = useGradient || background === 'transparent' ? 'null' : scriptJson(safeCssColor(background) || '#0a0a0a');
const bodyBg = useGradient
- ? `radial-gradient(ellipse 90% 70% at 50% 38%, ${backdrop.inner}, ${backdrop.outer})`
+ ? `radial-gradient(ellipse 90% 70% at 50% 38%, ${inner}, ${outer})`
: 'transparent';
return `<!doctype html>
<html><head><meta charset="utf-8" />
<style>html,body{margin:0;padding:0;background:${bodyBg};overflow:hidden}</style>
</head><body>
<canvas id="c" width="${width}" height="${height}" style="display:block;width:${width}px;height:${height}px"></canvas>
-<script>window.__GLB_B64=${JSON.stringify(glbBase64)};</script>
+<script>window.__GLB_B64=${scriptJson(glbBase64)};</script>
<script type="importmap">{ "imports": {
"three": "https://unpkg.com/three@${THREE_VERSION}/build/three.module.js",
"three/addons/": "https://unpkg.com/three@${THREE_VERSION}/examples/jsm/"
diff --git a/api/_lib/render-safe.js b/api/_lib/render-safe.js
new file mode 100644
index 000000000..8b10a4740
--- /dev/null
+++ b/api/_lib/render-safe.js
@@ -0,0 +1,41 @@
+// Escaping helpers shared by every headless-chromium renderer.
+//
+// The render pages are built by string interpolation, and their inputs
+// (a background color, a pose label, a base64 GLB) come from public,
+// unauthenticated HTTP handlers. The render page has full network egress from
+// the container, so a caller who lands script into it can fetch internal
+// endpoints and paint the response into the PNG we hand back. Every renderer
+// interpolates through these two functions so no caller has to remember to.
+
+// JSON.stringify alone is not enough to embed a value inside a <script> block:
+// it leaves "</script" and the JS line terminators U+2028/U+2029 intact, so a
+// caller-supplied string could close the tag and run its own code.
+export function scriptJson(value) {
+ return JSON.stringify(value === undefined ? null : value)
+ .replace(/</g, '\\u003c')
+ .replace(/>/g, '\\u003e')
+ .replace(/\u2028/g, '\\u2028')
+ .replace(/\u2029/g, '\\u2029');
+}
+
+// The CSS-color grammar the renderers accept, and the only shape allowed to
+// reach a <style> block or a THREE.Color(). Anything outside it (a "</style>"
+// breakout, a url(), a CSS expression) is rejected at the boundary rather than
+// escaped, because no legitimate caller needs it.
+const HEX = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
+const FUNCTIONAL = /^(?:rgba?|hsla?)\(\s*[0-9a-z.,%\s/+-]{1,64}\)$/i;
+const NAMED = /^[a-z]{3,20}$/i;
+
+/**
+ * Validate a caller-supplied CSS color.
+ *
+ * @param {unknown} value
+ * @returns {string|null} the trimmed color, or null if it is not a CSS color.
+ */
+export function safeCssColor(value) {
+ if (typeof value !== 'string') return null;
+ const v = value.trim();
+ if (!v || v.length > 72) return null;
+ if (HEX.test(v) || FUNCTIONAL.test(v) || NAMED.test(v)) return v;
+ return null;
+}
diff --git a/api/render/avatar-clip.js b/api/render/avatar-clip.js
index 00e69f72b..c62b70a0b 100644
--- a/api/render/avatar-clip.js
+++ b/api/render/avatar-clip.js
@@ -6,7 +6,7 @@
// glbUrl: "https://...", // required
// width: 1024, height: 1024, // default 1024, max 2048
// background: "#0a0a0a" | "transparent",
-// posePresetId: "wave" | "tpose" | ..., // see GET /api/render/poses
+// posePresetId: "wave" | "tpose" | ..., // GET this URL for the catalog
// cameraOrbit: { theta: 0, phi: 80, radius: null }, // degrees + meters
// expression: { jawOpen: 0.4, mouthSmileLeft: 0.6, ... } // ARKit-52 morphs
// }
@@ -15,29 +15,26 @@ import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/
import { renderClip } from '../_lib/render-clip.js';
import { PRESETS } from '../../src/pose-presets.js';
import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';
-import { clientIp } from '../_lib/rate-limit.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { safeCssColor } from '../_lib/render-safe.js';
export const maxDuration = 30;
const MAX_DIM = 2048;
const MIN_DIM = 64;
const MAX_GLB_BYTES = 10 * 1024 * 1024;
-const RATE_LIMIT_WINDOW_MS = 10 * 60 * 1000;
-const RATE_LIMIT_MAX = 60;
-
-const rateMap = new Map();
-function rateCheck(ip) {
- const now = Date.now();
- if (!ip)
- return { success: true, limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX, reset: now + RATE_LIMIT_WINDOW_MS };
- const arr = (rateMap.get(ip) || []).filter((t) => now - t < RATE_LIMIT_WINDOW_MS);
- if (arr.length >= RATE_LIMIT_MAX) {
- rateMap.set(ip, arr);
- return { success: false, limit: RATE_LIMIT_MAX, remaining: 0, reset: arr[0] + RATE_LIMIT_WINDOW_MS };
+
+// Number() is too permissive for orbit fields: it turns null, '', and [] into a
+// finite 0, so an explicit `radius: null` (the documented auto-frame value) and
+// `phi: null` would read as real angles and silently reframe the shot. Only an
+// actual number or a numeric string counts; everything else falls back.
+function num(v) {
+ if (typeof v === 'number') return Number.isFinite(v) ? v : null;
+ if (typeof v === 'string' && v.trim() !== '') {
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
}
- arr.push(now);
- rateMap.set(ip, arr);
- return { success: true, limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX - arr.length, reset: now + RATE_LIMIT_WINDOW_MS };
+ return null;
}
export default wrap(async function handler(req, res) {
@@ -55,10 +52,11 @@ export default wrap(async function handler(req, res) {
if (!method(req, res, ['POST'])) return;
- const ip = clientIp(req);
- const rl = rateCheck(ip);
+ // Shared across both public renderers and distributed (see limits.renderIp):
+ // they share one chromium, so they share one budget.
+ const rl = await limits.renderIp(clientIp(req) || 'anon');
if (!rl.success) {
- return rateLimited(res, rl, `Too many render requests. Limit: ${RATE_LIMIT_MAX} per ${RATE_LIMIT_WINDOW_MS / 60000}m.`);
+ return rateLimited(res, rl, `Too many render requests. Limit: ${rl.limit} per 10m.`);
}
let body;
@@ -81,7 +79,18 @@ export default wrap(async function handler(req, res) {
const width = Math.max(MIN_DIM, Math.min(MAX_DIM, Number(body.width) || 1024));
const height = Math.max(MIN_DIM, Math.min(MAX_DIM, Number(body.height) || 1024));
- const background = body.background === 'transparent' ? 'transparent' : (typeof body.background === 'string' && body.background ? body.background : '#0a0a0a');
+ // The color is interpolated into the render page, so it is validated here
+ // rather than escaped downstream: a caller who wants a color gets one, and a
+ // caller who wants markup gets a 400 they can act on.
+ let background = '#0a0a0a';
+ if (body.background === 'transparent') {
+ background = 'transparent';
+ } else if (body.background !== undefined && body.background !== null && body.background !== '') {
+ background = safeCssColor(body.background);
+ if (!background) {
+ return error(res, 400, 'bad_request', 'background must be "transparent" or a CSS color (hex, rgb()/rgba(), hsl()/hsla(), or a named color)');
+ }
+ }
let posePresetId = null;
if (body.posePresetId) {
@@ -94,9 +103,11 @@ export default wrap(async function handler(req, res) {
const cameraOrbit = body.cameraOrbit && typeof body.cameraOrbit === 'object'
? {
- theta: Number(body.cameraOrbit.theta) || 0,
- phi: Number.isFinite(Number(body.cameraOrbit.phi)) ? Number(body.cameraOrbit.phi) : 80,
- radius: Number.isFinite(Number(body.cameraOrbit.radius)) ? Number(body.cameraOrbit.radius) : null,
+ theta: num(body.cameraOrbit.theta) ?? 0,
+ phi: num(body.cameraOrbit.phi) ?? 80,
+ // null means "auto-frame from the bounding box", which is what the docs
+ // show and what an omitted radius does. A positive number overrides it.
+ radius: (num(body.cameraOrbit.radius) ?? 0) > 0 ? num(body.cameraOrbit.radius) : null,
}
: null;
diff --git a/api/render/glb.js b/api/render/glb.js
index 14aed1f1c..9128f8886 100644
--- a/api/render/glb.js
+++ b/api/render/glb.js
@@ -21,46 +21,34 @@
//
// Safety:
// - Only http(s) URLs accepted (no file://, data://, internal IPs).
+// - `background` must parse as a CSS color. It is interpolated into the
+// render page, and that page has container network egress, so markup in
+// this field would be script execution with an internal-network view.
// - GLB HEAD-fetched first to enforce a 10 MB cap before chromium boots.
-// - In-memory IP rate limit (60 renders / 10 min / IP) to keep chromium
-// warm-up costs bounded under abuse.
+// - Distributed IP rate limit (60 renders / 10 min / IP, shared with
+// /api/render/avatar-clip) to keep chromium costs bounded under abuse.
import { cors, error, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { renderGlbToPng } from '../_lib/render-glb.js';
import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';
-import { clientIp } from '../_lib/rate-limit.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { safeCssColor } from '../_lib/render-safe.js';
export const maxDuration = 30;
const MAX_DIM = 2048;
const MIN_DIM = 64;
const MAX_GLB_BYTES = 10 * 1024 * 1024;
-const RATE_LIMIT_WINDOW_MS = 10 * 60 * 1000;
-const RATE_LIMIT_MAX = 60;
-
-const rateMap = new Map();
-function rateCheck(ip) {
- const now = Date.now();
- const full = { limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX, reset: now + RATE_LIMIT_WINDOW_MS };
- if (!ip) return { success: true, ...full };
- const arr = (rateMap.get(ip) || []).filter((t) => now - t < RATE_LIMIT_WINDOW_MS);
- if (arr.length >= RATE_LIMIT_MAX) {
- rateMap.set(ip, arr);
- return { success: false, limit: RATE_LIMIT_MAX, remaining: 0, reset: arr[0] + RATE_LIMIT_WINDOW_MS };
- }
- arr.push(now);
- rateMap.set(ip, arr);
- return { success: true, limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX - arr.length, reset: now + RATE_LIMIT_WINDOW_MS };
-}
export default wrap(async function handler(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
if (!method(req, res, ['GET', 'POST'])) return;
- const ip = clientIp(req);
- const rl = rateCheck(ip);
+ // Shared across both public renderers and distributed (see limits.renderIp):
+ // they share one chromium, so they share one budget.
+ const rl = await limits.renderIp(clientIp(req) || 'anon');
if (!rl.success) {
- return rateLimited(res, rl, `Too many render requests. Limit: ${RATE_LIMIT_MAX} per ${RATE_LIMIT_WINDOW_MS / 60000}m.`);
+ return rateLimited(res, rl, `Too many render requests. Limit: ${rl.limit} per 10m.`);
}
// GET carries the same fields as query params; POST keeps the JSON body.
@@ -96,7 +84,18 @@ export default wrap(async function handler(req, res) {
const width = Math.max(MIN_DIM, Math.min(MAX_DIM, Number(body.width) || 1024));
const height = Math.max(MIN_DIM, Math.min(MAX_DIM, Number(body.height) || 1024));
- const background = body.background === 'transparent' ? 'transparent' : (typeof body.background === 'string' && body.background ? body.background : '#0a0a0a');
+ // The color is interpolated into the render page, so it is validated here
+ // rather than escaped downstream: a caller who wants a color gets one, and a
+ // caller who wants markup gets a 400 they can act on.
+ let background = '#0a0a0a';
+ if (body.background === 'transparent') {
+ background = 'transparent';
+ } else if (body.background !== undefined && body.background !== null && body.background !== '') {
+ background = safeCssColor(body.background);
+ if (!background) {
+ return error(res, 400, 'bad_request', 'background must be "transparent" or a CSS color (hex, rgb()/rgba(), hsl()/hsla(), or a named color)');
+ }
+ }
let png;
try {
diff --git a/data/changelog.json b/data/changelog.json
index e63b34dec..23a09fa83 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -3,11 +3,13 @@
"entries": [
{
"date": "2026-08-15",
- "title": "Portfolio token pages price Base and Arbitrum holdings correctly",
- "summary": "Opening a token from your portfolio asked Ethereum for the price no matter which chain the token was actually on. Almost every agent wallet runs on Base, so the most common holdings came back with no price, no chart and a shortened contract address instead of a ticker, even though the balance was right there in the list. Each token is now priced on its own chain, labelled with its real symbol and decimals, and native gas tokens use the right coin per chain (POL on Polygon, BNB on BNB Chain, AVAX on Avalanche) instead of always quoting ETH. Chains nobody prices, such as testnets, now say so plainly rather than showing another chain's number.",
+ "title": "Posed avatar renders finally come out posed",
+ "summary": "Asking the public avatar renderer for a pose returned a T-pose on most models: it matched bone names against a short hand-written list, and any rig that did not use those exact names (including every Mixamo export) was silently left in its bind pose while the response still claimed the pose had been applied. The renderer now uses the same posing engine the pose studio uses, so a preset now lands whatever naming convention the model's skeleton uses, and the camera frames the posed figure rather than the unposed one. The background colour on both public renderers is now checked before it is used, and the per-render budget is counted across the whole fleet instead of per server.",
"tags": [
- "fix"
- ]
+ "fix",
+ "security"
+ ],
+ "link": "/docs/api-reference"
},
{
"date": "2026-08-15",
diff --git a/docs/api-reference.md b/docs/api-reference.md
index f3f0c0fbd..3f7d00b0b 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -1319,7 +1319,37 @@ render URL-addressable for `og:image` unfurls, `<img>` tags, and markdown
embeds; responses CDN-cache for a day so crawlers hit chromium once per
model. Dimensions clamp to 64-2048; GLBs over 10 MB are rejected before the
browser boots; only public http(s) sources are fetched (SSRF-guarded);
-60 renders / 10 min / IP.
+60 renders / 10 min / IP, a budget shared with `/api/render/avatar-clip`.
+
+`background` is `transparent` or a CSS color (`#0a0a0a`, `#fff`,
+`rgb()`/`rgba()`, `hsl()`/`hsla()`, or a named color such as `midnightblue`).
+Anything else is `400 bad_request`: the value is composited into the render
+page, so it is validated rather than escaped.
+
+### Posed avatar renderer: `GET|POST /api/render/avatar-clip`
+
+```
+GET /api/render/avatar-clip → the pose catalog (id, label, group)
+POST /api/render/avatar-clip
+{
+ "glbUrl": "https://...", # required, public http(s)
+ "width": 1024, "height": 1024, # default 1024, clamped 64-2048
+ "background": "transparent", # or a CSS color, as above
+ "posePresetId": "wave", # any id from the GET catalog
+ "cameraOrbit": { "theta": 25, "phi": 75, "radius": null },
+ "expression": { "jawOpen": 0.4 } # ARKit-52 morph targets
+}
+→ image/png, plus x-render-pose / x-render-pose-label headers
+```
+
+The same renderer with a pose stage in front of it. `posePresetId` is retargeted
+onto the model's own rest pose through the studio's posing stack, so a preset
+lands the same way whatever naming convention the rig's skeleton uses, and a
+model with no recognizable humanoid skeleton renders in its bind pose instead of
+failing. `cameraOrbit.theta`/`phi` are degrees (yaw, and pitch from the top);
+`radius` is meters, or `null` to auto-frame from the bounding box. An unknown
+`posePresetId` is `400 unknown_pose`. Same 10 MB cap, SSRF guard, and render
+budget as `/api/render/glb`.
### Forge-Off votes — `POST /api/forge-vote`
diff --git a/docs/security/SECURITY_AUDIT.md b/docs/security/SECURITY_AUDIT.md
index 737fd723b..9dcbb515c 100644
--- a/docs/security/SECURITY_AUDIT.md
+++ b/docs/security/SECURITY_AUDIT.md
@@ -380,7 +380,9 @@ read-only assets. **Status: fixed (audited + migrated authenticated handlers).**
- **L9 — agents/solana-trade.js weaker per-IP limiter** vs twin's `tradePerUser`.
Gate on `tradePerUser`. **Status: fixed.**
- **L10 — render/glb.js + render/avatar-clip.js per-process limiter.** Use shared
- Upstash limiter. **Status: fixed.**
+ Upstash limiter. **Status: fixed (2026-08-15).** Both handlers had kept their own
+ in-file `rateMap`, so the 60/10m ceiling multiplied by however many Cloud Run
+ instances were up. They now share the distributed `limits.renderIp` bucket.
---
diff --git a/prompts/swarm-100/api-render-01.md b/prompts/swarm-100/api-render-01.md
deleted file mode 100644
index 3eaa80d77..000000000
--- a/prompts/swarm-100/api-render-01.md
+++ /dev/null
@@ -1,102 +0,0 @@
-# API audit: api/render batch 01 (2 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/render/avatar-clip.js
-- api/render/glb.js
-
-For every routed handler:
-
-1. Exercise it with curl against the local server: the success path returns
- real data with the correct status; malformed input returns a 4xx JSON
- error, never a stack trace or an HTML error page; auth is enforced where
- the code intends it; CORS matches neighboring handlers.
-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
- responses, no unfinished markers. Errors are handled at the boundary and
- internal code trusts itself.
-3. Do not spend funds or sign anything on-chain while probing. Payment and
- trading handlers get their validation and error paths exercised, never a
- live settlement.
-
-For every internal (non-routed) module:
-
-4. Something must import it; if nothing does, delete it as dead code (verify
- with a repo-wide grep first).
-5. Its main path and one failure path must be covered in tests/; add the
- missing test if not.
-
-## Definition of done
-
-- [ ] Every listed file has recorded evidence: a curl transcript for routed
- handlers, a passing test or a deletion for internal modules.
-- [ ] Zero hard-rule violations remain in these files.
-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
- exits 0.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/api-render-01.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/public/changelog.json b/public/changelog.json
index 9cb2620f8..857f8e4f5 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-15T16:35:13.884Z",
+ "generated_at": "2026-08-15T17:01:09.266Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -295,6 +295,17 @@
"fix"
]
},
+ {
+ "date": "2026-08-15",
+ "type": "update",
+ "title": "Posed avatar renders finally come out posed",
+ "summary": "Asking the public avatar renderer for a pose returned a T-pose on most models: it matched bone names against a short hand-written list, and any rig that did not use those exact names (including every Mixamo export) was silently left in its bind pose while the response still claimed the pose had been applied. The renderer now uses the same posing engine the pose studio uses, so a preset now lands whatever naming convention the model's skeleton uses, and the camera frames the posed figure rather than the unposed one. The background colour on both public renderers is now checked before it is used, and the per-render budget is counted across the whole fleet instead of per server.",
+ "link": "/docs/api-reference",
+ "tags": [
+ "fix",
+ "security"
+ ]
+ },
{
"date": "2026-08-15",
"type": "update",
@@ -338,6 +349,17 @@
"fix"
]
},
+ {
+ "date": "2026-08-15",
+ "type": "update",
+ "title": "Scanning a skill purchase QR tells you when your wallet is short",
+ "summary": "Paying for a skill from a phone handed the wallet a transfer even when the wallet held none of the token being asked for, so the buyer signed and watched it fail with whatever cryptic message their wallet chose to print. The checkout now checks the paying wallet first and answers with the exact shortfall, so a wallet that is 0.35 short says so and a wallet that has never held the token says that instead of failing at signing time. The same checkout also stopped pinning the busiest public Solana node ahead of the platform's own faster ones, so building the payment is quicker and survives a throttled node.",
+ "link": null,
+ "tags": [
+ "improvement",
+ "fix"
+ ]
+ },
{
"date": "2026-08-15",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 69bed59b2..038a69e35 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -222,6 +222,14 @@
<category>fix</category>
<description>Opening a token from your portfolio asked Ethereum for the price no matter which chain the token was actually on. Almost every agent wallet runs on Base, so the most common holdings came back with no price, no chart and a shortened contract address instead of a ticker, even though the balance was right there in the list. Each token is now priced on its own chain, labelled with its real symbol and decimals, and native gas tokens use the right coin per chain (POL on Polygon, BNB on BNB Chain, AVAX on Avalanche) instead of always quoting ETH. Chains nobody prices, such as testnets, now say so plainly rather than showing another chain's number.</description>
</item>
+ <item>
+ <title>Posed avatar renders finally come out posed</title>
+ <link>https://three.ws/docs/api-reference</link>
+ <guid isPermaLink="false">2026-08-15:Posed avatar renders finally come out posed</guid>
+ <pubDate>Sat, 15 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Asking the public avatar renderer for a pose returned a T-pose on most models: it matched bone names against a short hand-written list, and any rig that did not use those exact names (including every Mixamo export) was silently left in its bind pose while the response still claimed the pose had been applied. The renderer now uses the same posing engine the pose studio uses, so a preset now lands whatever naming convention the model's skeleton uses, and the camera frames the posed figure rather than the unposed one. The background colour on both public renderers is now checked before it is used, and the per-render budget is counted across the whole fleet instead of per server.</description>
+ </item>
<item>
<title>Private avatars no longer show their picture in registry lookups</title>
<link>https://three.ws/changelog</link>
@@ -254,6 +262,14 @@
<category>improvement</category>
<description>Every time you saved a world, the service fetched and re-parsed the entire previous version of that world just to check who owns it. On a large build that meant a full extra download and parse on each autosave, for a single ownership field. The check now reads only the small index record, so saves on big worlds are noticeably quicker and the storage layer does half the work. Two error replies also got honest labels: a build that exceeds the size cap now answers &quot;payload too large&quot; and a request sent with the wrong content type answers &quot;unsupported media type&quot;, instead of both arriving as a generic validation error that gave a client nothing to act on.</description>
</item>
+ <item>
+ <title>Scanning a skill purchase QR tells you when your wallet is short</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-08-15:Scanning a skill purchase QR tells you when your wallet is short</guid>
+ <pubDate>Sat, 15 Aug 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Paying for a skill from a phone handed the wallet a transfer even when the wallet held none of the token being asked for, so the buyer signed and watched it fail with whatever cryptic message their wallet chose to print. The checkout now checks the paying wallet first and answers with the exact shortfall, so a wallet that is 0.35 short says so and a wallet that has never held the token says that instead of failing at signing time. The same checkout also stopped pinning the busiest public Solana node ahead of the platform's own faster ones, so building the payment is quicker and survives a throttled node.</description>
+ </item>
<item>
<title>Scanning for trade candidates is faster on creator-filtered rules and honest about how much it looked at</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index cd78fc72a..2cb823747 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-15T16:35:13.711Z",
+ "generated_at": "2026-08-15T17:01:09.222Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/api/avatar-render-framing.test.js b/tests/api/avatar-render-framing.test.js
index bfb80eaed..0eb9508c4 100644
--- a/tests/api/avatar-render-framing.test.js
+++ b/tests/api/avatar-render-framing.test.js
@@ -175,4 +175,32 @@ describe('sceneViewerHtml wiring', () => {
expect(resolveRenderParams({ pose: 'wave' }).params.posePresetId).toBe('wave');
expect(resolveRenderParams({ pose: 'nope' }).error.code).toBe('unknown_pose');
});
+
+ // `bg` is interpolated into the render page's script block, and that page can
+ // reach the container's network, so a markup-carrying value is caller JS with
+ // an internal view. It is rejected at the param layer, not escaped later.
+ it('rejects a bg that is not a CSS color, and keeps the ones that are', () => {
+ expect(resolveRenderParams({ bg: '#0a0a0a' }).params.bg).toBe('#0a0a0a');
+ expect(resolveRenderParams({ bg: 'midnightblue' }).params.bg).toBe('midnightblue');
+ expect(resolveRenderParams({ bg: 'rgba(1,2,3,0.5)' }).params.bg).toBe('rgba(1,2,3,0.5)');
+ expect(resolveRenderParams({}).params.bg).toBe('transparent');
+ expect(resolveRenderParams({ bg: 'transparent' }).params.bg).toBe('transparent');
+ expect(resolveRenderParams({ bg: '#000</script><script>x</script>' }).error.code).toBe('invalid_bg');
+ expect(resolveRenderParams({ bg: 'url(https://x/y)' }).error.code).toBe('invalid_bg');
+ });
+
+ it('escapes every page value it interpolates, so no input can close the script tag', () => {
+ const html = sceneViewerHtml({
+ glbUrl: 'https://three.ws/a.glb?x=</script><script>y</script>',
+ width: 64,
+ height: 64,
+ background: '#0a0a0a',
+ pose: null,
+ cameraOrbit: null,
+ expression: null,
+ scenePreset: SCENE_PRESETS['portrait'],
+ });
+ // Exactly the tags the page opens itself, none smuggled in by a caller.
+ expect(html.split('</script>').length - 1).toBe((html.match(/<script[ >]/g) || []).length);
+ });
});
diff --git a/tests/api/render-endpoints.test.js b/tests/api/render-endpoints.test.js
new file mode 100644
index 000000000..5761f7fdb
--- /dev/null
+++ b/tests/api/render-endpoints.test.js
@@ -0,0 +1,206 @@
+// Boundary coverage for the two public headless-chromium renderers,
+// /api/render/glb and /api/render/avatar-clip.
+//
+// The renderers themselves are exercised against real GLBs by hand (they need
+// chromium); what is pinned here is everything a caller can reach WITHOUT
+// booting a browser: method + input validation, the SSRF pre-check, the render
+// page's escaping contract, and the pose catalog. The escaping cases are
+// regression tests for a real defect: `background` reached the render page
+// through a bare JSON.stringify, so `#000</script><script>…</script>` executed
+// caller JS inside a page with container network egress.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+import { scriptJson, safeCssColor } from '../../api/_lib/render-safe.js';
+
+const GLB = 'https://three.ws/avatars/default.glb';
+const INJECTION = '#000</script><script>window.__renderError="pwned"</script>';
+
+const renderGlbToPng = vi.fn(async () => Buffer.from('89504e470d0a1a0a', 'hex'));
+const renderClip = vi.fn(async () => ({ png: Buffer.from('89504e470d0a1a0a', 'hex'), pose: { id: 'wave', label: 'Wave hello' } }));
+
+vi.mock('../../api/_lib/render-glb.js', () => ({ renderGlbToPng: (...a) => renderGlbToPng(...a) }));
+vi.mock('../../api/_lib/render-clip.js', () => ({ renderClip: (...a) => renderClip(...a) }));
+
+function makeReq(method, url, body) {
+ const req = { method, url, headers: { host: 'three.ws', 'x-forwarded-for': '203.0.113.9' } };
+ if (body !== undefined) {
+ req.headers['content-type'] = 'application/json';
+ req.body = body;
+ }
+ return req;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ writableEnded: false,
+ headersSent: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ removeHeader(k) { delete this._h[k.toLowerCase()]; },
+ end(body) { this._body = body; this.writableEnded = true; },
+ };
+}
+
+async function callGlb(req) {
+ const { default: handler } = await import('../../api/render/glb.js');
+ const res = makeRes();
+ await handler(req, res);
+ return res;
+}
+
+async function callClip(req) {
+ const { default: handler } = await import('../../api/render/avatar-clip.js');
+ const res = makeRes();
+ await handler(req, res);
+ return res;
+}
+
+beforeEach(() => {
+ renderGlbToPng.mockClear();
+ renderClip.mockClear();
+});
+
+describe('render-safe escaping contract', () => {
+ it('scriptJson neutralises a <script> breakout and the JS line terminators', () => {
+ const out = scriptJson('a</script><script>x</script>b
c
d');
+ expect(out).not.toContain('</script>');
+ expect(out).not.toContain('<');
+ expect(out).not.toContain('>');
+ expect(out).not.toContain('
');
+ expect(out).not.toContain('
');
+ expect(JSON.parse(out)).toBe('a</script><script>x</script>b
c
d');
+ });
+
+ it('scriptJson maps undefined to null so an omitted value never emits a bare hole', () => {
+ expect(scriptJson(undefined)).toBe('null');
+ });
+
+ it('safeCssColor accepts the color forms the renderers document', () => {
+ for (const ok of ['#0a0a0a', '#fff', '#0a0a0aff', 'rgb(10, 10, 10)', 'rgba(1,2,3,0.5)', 'hsl(210, 30%, 17%)', 'rgb(10 10 10 / 50%)', 'midnightblue']) {
+ expect(safeCssColor(ok)).toBe(ok);
+ }
+ });
+
+ it('safeCssColor rejects markup, CSS breakouts, and non-strings', () => {
+ for (const bad of [INJECTION, '</style><script>x', '#000;}</style><x', 'url(https://x/y)', 'expression(alert(1))', '', ' ', 42, null, undefined, {}]) {
+ expect(safeCssColor(bad)).toBeNull();
+ }
+ });
+});
+
+describe('GET|POST /api/render/glb', () => {
+ it('400s without a glbUrl instead of booting chromium', async () => {
+ const res = await callGlb(makeReq('GET', '/api/render/glb'));
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res._body).error).toBe('bad_request');
+ expect(renderGlbToPng).not.toHaveBeenCalled();
+ });
+
+ it('400s a private-address glbUrl on both the GET and the POST form', async () => {
+ expect((await callGlb(makeReq('GET', '/api/render/glb?glbUrl=' + encodeURIComponent('https://10.0.0.8/a.glb')))).statusCode).toBe(400);
+ expect((await callGlb(makeReq('POST', '/api/render/glb', { glbUrl: 'http://169.254.169.254/meta' }))).statusCode).toBe(400);
+ expect(renderGlbToPng).not.toHaveBeenCalled();
+ });
+
+ it('400s a background carrying markup, so nothing injectable reaches the render page', async () => {
+ const res = await callGlb(makeReq('POST', '/api/render/glb', { glbUrl: GLB, background: INJECTION }));
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res._body).error).toBe('bad_request');
+ expect(renderGlbToPng).not.toHaveBeenCalled();
+ });
+
+ it('405s a method the renderer does not serve', async () => {
+ const res = await callGlb(makeReq('PUT', '/api/render/glb'));
+ expect(res.statusCode).toBe(405);
+ });
+
+ it('renders a PNG with the clamped dimensions echoed back', async () => {
+ const res = await callGlb(makeReq('POST', '/api/render/glb', { glbUrl: GLB, width: 99999, height: 1, background: 'transparent' }));
+ expect(res.statusCode).toBe(200);
+ expect(res._h['content-type']).toBe('image/png');
+ expect(res._h['x-render-width']).toBe('2048');
+ expect(res._h['x-render-height']).toBe('64');
+ expect(res._h['x-render-background']).toBe('transparent');
+ expect(renderGlbToPng).toHaveBeenCalledWith(expect.objectContaining({ glbUrl: GLB, width: 2048, height: 64, background: 'transparent' }));
+ });
+
+ it('surfaces a renderer failure as its own status, not a stack trace', async () => {
+ renderGlbToPng.mockRejectedValueOnce(Object.assign(new Error('glb too large'), { status: 413, code: 'file_too_large' }));
+ const res = await callGlb(makeReq('POST', '/api/render/glb', { glbUrl: GLB }));
+ expect(res.statusCode).toBe(413);
+ expect(JSON.parse(res._body).error).toBe('file_too_large');
+ });
+});
+
+describe('GET|POST /api/render/avatar-clip', () => {
+ it('GET returns the pose catalog so a caller never has to scrape the source', async () => {
+ const res = await callClip(makeReq('GET', '/api/render/avatar-clip'));
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res._body);
+ expect(body.poses.length).toBeGreaterThan(10);
+ expect(body.poses.map((p) => p.id)).toContain('wave');
+ for (const p of body.poses) expect(p).toEqual({ id: expect.any(String), label: expect.any(String), group: expect.any(String) });
+ });
+
+ it('400s an unknown pose preset and names where the catalog lives', async () => {
+ const res = await callClip(makeReq('POST', '/api/render/avatar-clip', { glbUrl: GLB, posePresetId: 'nope' }));
+ expect(res.statusCode).toBe(400);
+ const body = JSON.parse(res._body);
+ expect(body.error).toBe('unknown_pose');
+ expect(body.error_description).toMatch(/catalog/i);
+ expect(renderClip).not.toHaveBeenCalled();
+ });
+
+ it('400s a background carrying markup', async () => {
+ const res = await callClip(makeReq('POST', '/api/render/avatar-clip', { glbUrl: GLB, background: INJECTION }));
+ expect(res.statusCode).toBe(400);
+ expect(renderClip).not.toHaveBeenCalled();
+ });
+
+ it('400s a private-address glbUrl before chromium boots', async () => {
+ const res = await callClip(makeReq('POST', '/api/render/avatar-clip', { glbUrl: 'http://127.0.0.1:8080/a.glb' }));
+ expect(res.statusCode).toBe(400);
+ expect(renderClip).not.toHaveBeenCalled();
+ });
+
+ it('405s a method the renderer does not serve', async () => {
+ expect((await callClip(makeReq('DELETE', '/api/render/avatar-clip'))).statusCode).toBe(405);
+ });
+
+ it('keeps an explicit null orbit field as auto-frame instead of coercing it to 0', async () => {
+ const res = await callClip(makeReq('POST', '/api/render/avatar-clip', {
+ glbUrl: GLB,
+ cameraOrbit: { theta: null, phi: null, radius: null },
+ }));
+ expect(res.statusCode).toBe(200);
+ expect(renderClip).toHaveBeenCalledWith(expect.objectContaining({
+ cameraOrbit: { theta: 0, phi: 80, radius: null },
+ }));
+ });
+
+ it('passes pose, orbit, and expression through and reports the applied pose in headers', async () => {
+ const res = await callClip(makeReq('POST', '/api/render/avatar-clip', {
+ glbUrl: GLB,
+ width: 512,
+ height: 512,
+ posePresetId: 'wave',
+ cameraOrbit: { theta: 25, phi: 75, radius: null },
+ expression: { jawOpen: 0.4 },
+ }));
+ expect(res.statusCode).toBe(200);
+ expect(res._h['content-type']).toBe('image/png');
+ expect(res._h['x-render-pose']).toBe('wave');
+ expect(res._h['x-render-pose-label']).toBe('Wave hello');
+ expect(renderClip).toHaveBeenCalledWith(expect.objectContaining({
+ glbUrl: GLB,
+ width: 512,
+ height: 512,
+ posePresetId: 'wave',
+ cameraOrbit: { theta: 25, phi: 75, radius: null },
+ expression: { jawOpen: 0.4 },
+ }));
+ });
+});