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
feat(avatars): bone-mounted attachments with a trusted-host allowlist on both sides
nirholasa1aefac21fc7
diff --git a/api/_lib/accessories.js b/api/_lib/accessories.jsindex 0b3572b76..b911d438e 100644--- a/api/_lib/accessories.js+++ b/api/_lib/accessories.js@@ -28,6 +28,30 @@ const COLOR_SLOT_IDS = new Set(['skin', 'hair', 'outfit']);const HIDEABLE_SLOT_IDS = new Set(['hair', 'outfit', 'glasses']);const HEX_RE = /^#[0-9a-f]{6}$/i;+// Hosts an `attachments[].url` may point at. A stored attachment is loaded by+// every browser that renders the avatar, including viewers who do not own it,+// so an unrestricted URL would turn a public avatar into an open relay for+// third-party bytes. Anchored the same way as TRUSTED_ASSET_HOST_RE in+// src/shared/safe-model-url.js (the client-side twin of this check), so+// `three.ws.evil.com` never matches; keep the two lists in step.+const TRUSTED_ATTACHMENT_HOST_RE =+ /(^|\.)(three\.ws|r2\.dev|storage\.googleapis\.com|mypinata\.cloud|pinata\.cloud|ipfs\.io|dweb\.link|arweave\.net)$/i;++/** Whether a custom attachment URL is safe to store and re-serve to viewers. */+export function isTrustedAttachmentUrl(raw) {+ if (typeof raw !== 'string' || !raw) return false;+ // Same-origin relative path (a bundled prop under /accessories/…).+ if (raw.startsWith('/') && !raw.startsWith('//')) return true;+ let u;+ try {+ u = new URL(raw);+ } catch {+ return false;+ }+ if (u.protocol !== 'https:') return false;+ return TRUSTED_ATTACHMENT_HOST_RE.test(u.hostname);+}+export function validateAppearance(appearance) {if (!appearance) return null;@@ -87,5 +111,23 @@ export function validateAppearance(appearance) {}}+ if (appearance.attachments !== undefined && appearance.attachments !== null) {+ if (!Array.isArray(appearance.attachments)) {+ return 'appearance.attachments must be an array';+ }+ if (appearance.attachments.length > 8) return 'appearance.attachments max 8 entries';+ for (const item of appearance.attachments) {+ if (!item || typeof item !== 'object' || Array.isArray(item)) {+ return 'appearance.attachments entries must be objects';+ }+ if (typeof item.bone !== 'string' || !item.bone.trim()) {+ return 'appearance.attachments[].bone must be a non-empty string';+ }+ if (!isTrustedAttachmentUrl(item.url)) {+ return `appearance.attachments[].url must be an https URL on a three.ws asset host: ${item.url}`;+ }+ }+ }+return null;}diff --git a/api/_lib/validate.js b/api/_lib/validate.jsindex ab3b1cc43..60f58271e 100644--- a/api/_lib/validate.js+++ b/api/_lib/validate.js@@ -46,6 +46,24 @@ export const avatarAppearance = z).max(8).optional(),+ // Custom bone-mounted props: a forged GLB parented to a named bone+ // (Scene Composer's "Save outfit"). Unlike `accessories`, whose entries+ // name presets in the curated catalog, these carry their own URL, so the+ // host allowlist in validateAppearance() (accessories.js) is what keeps+ // one owner's avatar from pointing every viewer's browser at an+ // arbitrary third-party host.+ attachments: z+ .array(+ z+ .object({+ bone: z.string().min(1).max(64),+ url: z.string().min(1).max(512),+ name: z.string().min(1).max(80).optional(),+ })+ .strict(),+ )+ .max(8)+ .optional(),}).strict().superRefine((val, ctx) => {diff --git a/src/agent-accessories.js b/src/agent-accessories.jsindex e192f1d0c..eb4ba37ee 100644--- a/src/agent-accessories.js+++ b/src/agent-accessories.js@@ -13,6 +13,7 @@ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { getMeshoptDecoder } from './viewer/internal.js';import { resolveURI } from './ipfs.js';import { collectSlotTargets } from './avatar-wardrobe.js';+import { isSafeQueryModelUrl } from './shared/safe-model-url.js';import { log } from './shared/log.js';const SINGLE_SLOT_KINDS = new Set(['outfit', 'hat', 'glasses']);@@ -108,6 +109,16 @@ export class AccessoryManager {log.warn(`[accessories] unknown preset id on boot: ${id}`);}}++ // Custom bone-mounted props (Scene Composer's saved outfit). These carry+ // their own URL instead of naming a catalog preset, so they become+ // synthetic presets and ride the same load-and-attach path. The URL was+ // host-checked when it was stored (api/_lib/accessories.js); re-checking+ // here keeps a record written before that guard from loading a stranger's+ // bytes into this page.+ for (const preset of attachmentPresets(appearance.attachments)) {+ await this.applyPreset(preset);+ }}/**@@ -380,6 +391,35 @@ function _disposeObject(obj) {});}+/**+ * Turn stored `appearance.attachments` into synthetic presets the normal+ * apply path understands. Ids are namespaced (`attach:<i>:<bone>`) so they can+ * never collide with a catalog preset id, and `kind` is 'accessory' because+ * these stack rather than replacing a single slot the way a hat does.+ *+ * @param {Array<{bone: string, url: string, name?: string}> | undefined} attachments+ * @returns {Array<{id: string, kind: string, glbUrl: string, attachBone: string, label: string}>}+ */+export function attachmentPresets(attachments) {+ if (!Array.isArray(attachments)) return [];+ const out = [];+ attachments.forEach((a, i) => {+ if (!a || typeof a.bone !== 'string' || !a.bone) return;+ if (!isSafeQueryModelUrl(a.url)) {+ log.warn(`[accessories] attachment url rejected: ${a.url}`);+ return;+ }+ out.push({+ id: `attach:${i}:${a.bone}`,+ kind: 'accessory',+ glbUrl: a.url,+ attachBone: a.bone,+ label: a.name || 'Attachment',+ });+ });+ return out;+}+let _presetsCache = null;async function _fetchPresets() {if (_presetsCache) return _presetsCache;diff --git a/src/scene-compose.js b/src/scene-compose.jsindex 9cad34ef6..cbb3e02ef 100644--- a/src/scene-compose.js+++ b/src/scene-compose.js@@ -229,12 +229,22 @@ const sceneObjects = new Map(); // id → { group, name, glbUrl, visible, boneAtlet nextId = 1;let selectedId = null;let avatarId = null;+// The three.ws avatar record the loaded model came from, when it came from one.+// "Save outfit" writes back to this record, so it has to be the id the API+// answered with, not something parsed out of the model URL: a saved avatar is+// served from the asset CDN (…r2.dev/u/<owner>/<slug>.glb), a path that carries+// no record id at all.+let avatarRecordId = null;+let avatarAppearance = null; // the record's stored appearance, so a save extends itlet avatarBones = []; // { name, bone }let xformMode = 'translate';let xformSpace = 'world';let snapEnabled = false;let scaleLocked = false;const SNAP_SIZE = 0.25;+// Mirrors the `attachments` cap in api/_lib/validate.js, checked here so the+// studio says which limit was hit instead of surfacing a raw 400.+const MAX_SAVED_ATTACHMENTS = 8;let forgeJobId = null;let forgePollTimer = null;let forgePollStart = 0;@@ -910,7 +920,13 @@ function detachFromBone(itemId, updateUI = true) {}// ── Avatar loading ────────────────────────────────────────────────────────────-async function loadAvatar(url, name = 'Avatar') {+/**+ * @param {string} url model URL to load+ * @param {string} name display name in the hierarchy+ * @param {object} [record] the avatar record this model came from, when any:+ * { id, appearance }: what "Save outfit" writes to+ */+async function loadAvatar(url, name = 'Avatar', record = null) {showLoading('Loading avatar…');avatarPrompt.classList.add('h');canvasHint.classList.remove('h');@@ -919,6 +935,8 @@ async function loadAvatar(url, name = 'Avatar') {if (avatarId !== null) removeObject(avatarId);const id = addToScene(group, name, url, 'avatar', false);avatarId = id;+ avatarRecordId = record?.id || null;+ avatarAppearance = record?.appearance || null;avatarBones = bones;// Set up AnimationMixer if avatar has animationsif (gltf.animations && gltf.animations.length > 0) {@@ -965,9 +983,17 @@ async function loadAvatar(url, name = 'Avatar') {} else {const res = await fetch(`/api/avatars/${encodeURIComponent(avatarParam)}`);const data = await res.json().catch(() => ({}));- const u = data.glbUrl || data.glb_url;- if (u) await loadAvatar(u, data.name || 'Avatar');- else hideLoading();+ // GET /api/avatars/:id answers { avatar: { …, model_url } }. Reading+ // a bare `glbUrl` off the envelope found nothing, so every+ // ?avatar=<id> deep link opened an empty stage instead of the avatar.+ const record = data.avatar || data;+ const u = record.model_url || record.glbUrl || record.glb_url;+ if (u) await loadAvatar(u, record.name || 'Avatar', record);+ else {+ toast(`Avatar ${avatarParam} not found`);+ avatarPrompt.classList.remove('h');+ hideLoading();+ }}} catch { hideLoading(); }} else {@@ -1022,7 +1048,13 @@ async function openAvatarModal() {lbl.style.cssText = 'position:absolute;bottom:0;left:0;right:0;padding:4px 6px;background:rgba(0,0,0,.65);font-size:10px;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;';lbl.textContent = av.name || 'Avatar';card.appendChild(lbl);- card.addEventListener('click', () => { closeAvatarModal(); loadAvatar(glbUrl, av.name || 'Avatar'); });+ // /api/explore names the avatar record `avatarId`; carrying it through+ // is what lets "Save outfit" write back to the browsed avatar.+ const recordId = av.avatarId || av.id || null;+ card.addEventListener('click', () => {+ closeAvatarModal();+ loadAvatar(glbUrl, av.name || 'Avatar', recordId ? { id: recordId } : null);+ });avatarModalBody.appendChild(card);}} catch {@@ -1327,23 +1359,33 @@ btnSaveOutfit.addEventListener('click', saveOutfit);async function saveOutfit() {if (avatarId === null) { toast('Load an avatar first'); return; }- const avatarObj = sceneObjects.get(avatarId);const attached = [];sceneObjects.forEach((obj, id) => {- if (id !== avatarId && obj.boneAttached) attached.push({ bone: obj.boneName, glbUrl: obj.glbUrl, name: obj.name });+ if (id !== avatarId && obj.boneAttached) attached.push({ bone: obj.boneName, url: obj.glbUrl, name: obj.name });});if (!attached.length) { toast('Attach at least one item to a bone first'); return; }- const urlMatch = avatarObj?.glbUrl?.match(/\/avatars\/([^/?]+)/);- const avatarApiId = urlMatch?.[1];- if (!avatarApiId) { toast('Use Export GLB to save this scene'); return; }+ if (attached.length > MAX_SAVED_ATTACHMENTS) {+ toast(`Save outfit keeps up to ${MAX_SAVED_ATTACHMENTS} attached items; use Export GLB for more`);+ return;+ }+ if (!avatarRecordId) { toast('Use Export GLB to save this scene'); return; }showLoading('Saving outfit…');try {- const res = await apiFetch(`/api/avatars/${encodeURIComponent(avatarApiId)}`, {+ // Extend the record's existing appearance rather than replacing it: an+ // avatar dressed in Avatar Studio carries colours, morphs and layers here+ // too, and PATCH replaces the whole appearance document.+ const appearance = { ...(avatarAppearance || {}), attachments: attached };+ const res = await apiFetch(`/api/avatars/${encodeURIComponent(avatarRecordId)}`, {method: 'PATCH',headers: { 'Content-Type': 'application/json', ...CH },- body: JSON.stringify({ accessories: attached }),+ body: JSON.stringify({ appearance }),});- if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || `HTTP ${res.status}`); }+ if (!res.ok) {+ const e = await res.json().catch(() => ({}));+ throw new Error(e.error_description || e.message || e.error || `HTTP ${res.status}`);+ }+ const saved = await res.json().catch(() => ({}));+ avatarAppearance = saved.avatar?.appearance || appearance;flashSave('Outfit saved ✓');} catch (err) {toast(`Save failed: ${err.message}`);