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(storage): route generated thumbnail and GLB URLs through /cdn/ instead of raw r2.dev
nirholas6c11ef944dd8
diff --git a/api/_lib/agent-earnings.js b/api/_lib/agent-earnings.jsindex 87d0a4755..fc566626b 100644--- a/api/_lib/agent-earnings.js+++ b/api/_lib/agent-earnings.js@@ -30,14 +30,16 @@import { sql } from './db.js';import { solPriceUsd } from './sol-price.js';import { SOLANA_USDC_MINT } from '../payments/_config.js';-import { publicUrl as r2PublicUrl } from './r2.js';+import { cdnUrl } from './r2.js';-// A portrait is decoration: a misconfigured public-URL resolver degrades it to-// null instead of failing the board.+// A portrait is decoration: a misconfigured URL resolver degrades it to null+// instead of failing the board. Routed through /cdn/ (not a raw publicUrl())+// so a thumbnail here gets the same signed-read-then-public-fallback+// protection every other API-facing thumbnail now gets.function safeR2Url(key) {if (!key) return null;try {- return r2PublicUrl(key);+ return cdnUrl(key);} catch {return null;}diff --git a/api/_lib/agent-economy.js b/api/_lib/agent-economy.jsindex fea8fc6e9..91a9b00a6 100644--- a/api/_lib/agent-economy.js+++ b/api/_lib/agent-economy.js@@ -13,7 +13,7 @@// it can be queried, rated, and audited.import { sql } from './db.js';-import { publicUrl as r2PublicUrl } from './r2.js';+import { cdnUrlOrNull } from './r2.js';export function atomicsToUsdc(atomics) {return Number(atomics || 0) / 1_000_000;@@ -24,7 +24,7 @@ export function atomicsToUsdc(atomics) {// avatar render.function avatarThumb(thumbKey, visibility) {const visible = visibility === 'public' || visibility === 'unlisted';- return thumbKey && visible ? r2PublicUrl(thumbKey) : null;+ return thumbKey && visible ? cdnUrlOrNull(thumbKey) : null;}function shapeProvider(row) {diff --git a/api/_lib/avatars.js b/api/_lib/avatars.jsindex d6b4f920c..bd7f3aeb9 100644--- a/api/_lib/avatars.js+++ b/api/_lib/avatars.js@@ -4,7 +4,7 @@import { createHash } from 'node:crypto';import { sql } from './db.js';import { cacheWrap } from './cache.js';-import { publicUrl, thumbnailUrl, presignGet, deleteObject } from './r2.js';+import { cdnUrl, thumbnailUrl, presignGet, deleteObject } from './r2.js';import { defaultStorageMode } from './storage-mode.js';import { isUuid } from './validate.js';@@ -516,7 +516,7 @@ export async function listForks({ avatarId, limit = 24, cursor }) {thumbnail_url: thumbnailUrl(r.thumbnail_key),model_url:r.visibility === 'public' || r.visibility === 'unlisted'- ? publicUrl(r.storage_key)+ ? cdnUrl(r.storage_key): null,})),next_cursor: hasMore ? new Date(page[page.length - 1].created_at).toISOString() : null,@@ -543,7 +543,7 @@ export async function listForks({ avatarId, limit = 24, cursor }) {export async function resolveAvatarUrl(row, { expiresIn = 600, browser = false } = {}) {const key = _servedStorageKey(row);if (row.visibility === 'public' || row.visibility === 'unlisted') {- return { url: publicUrl(key), cdn: true };+ return { url: cdnUrl(key), cdn: true };}if (browser) {return { url: `${SITE_ORIGIN}/api/avatars/${row.id}/glb`, cdn: false };@@ -667,16 +667,16 @@ function decorate(row) {updated_at: row.updated_at,model_url:row.visibility === 'public' || row.visibility === 'unlisted'- ? publicUrl(servedStorageKey)+ ? cdnUrl(servedStorageKey): null,base_model_url:row.visibility === 'public' || row.visibility === 'unlisted'- ? publicUrl(row.storage_key)+ ? cdnUrl(row.storage_key): null,parent_avatar_id: row.parent_avatar_id || null,thumbnail_url: thumbnailUrl(row.thumbnail_key),- usdz_url: row.usdz_key ? publicUrl(row.usdz_key) : null,- halfbody_url: row.halfbody_key ? publicUrl(row.halfbody_key) : null,+ usdz_url: row.usdz_key ? cdnUrl(row.usdz_key) : null,+ halfbody_url: row.halfbody_key ? cdnUrl(row.halfbody_key) : null,appearance: row.appearance || null,appearance_hash: row.appearance_hash || null,baked: bakedFresh,diff --git a/api/_lib/persona-store.js b/api/_lib/persona-store.jsindex 8d8f223e5..490ecdeb5 100644--- a/api/_lib/persona-store.js+++ b/api/_lib/persona-store.js@@ -27,7 +27,7 @@ import os from 'node:os';import path from 'node:path';import { sql } from './db.js';import { databaseConfigured } from './env.js';-import { putObject, copyObject, publicUrl } from './r2.js';+import { putObject, copyObject, cdnUrl } from './r2.js';import { fetchUpstream } from './upstream-fetch.js';const dbConfigured = () => databaseConfigured();@@ -132,7 +132,7 @@ export async function persistPersonaGlb(sourceUrl, personaId, buffer = null) {} else {return { glbUrl: sourceUrl, glbKey: null };}- return { glbUrl: publicUrl(key), glbKey: key };+ return { glbUrl: cdnUrl(key), glbKey: key };} catch {// Durable copy failed — keep the source URL rather than losing the persona.return { glbUrl: sourceUrl, glbKey: null };diff --git a/api/_lib/r2.js b/api/_lib/r2.jsindex 42ae1ea2a..0a1804fc6 100644--- a/api/_lib/r2.js+++ b/api/_lib/r2.js@@ -398,9 +398,35 @@ export function isLegacyOgThumbnailKey(thumbnailKey) {// not bare publicUrl(). See docs/avatar-thumbnails.md.export function thumbnailUrl(thumbnailKey) {if (!thumbnailKey || isLegacyOgThumbnailKey(thumbnailKey)) return null;- return publicUrlOrNull(thumbnailKey);+ return cdnUrlOrNull(thumbnailKey);}-function encodeR2Key(key) {+export function encodeR2Key(key) {return key.split('/').map(encodeURIComponent).join('/');}++// URL for an object served through the first-party /cdn/<key> proxy+// (api/cdn-object.js) instead of the raw public *.r2.dev domain publicUrl()+// returns. The proxy already streams the signed read and falls back to the+// public domain on its own (see isStorageInfrastructureError's callers+// there), so routing API responses through it gives every caller that+// failover and the rate-limit-avoiding edge cache for free, not just the+// handful of callers that happened to link to /cdn/ directly. publicUrl()+// stays the low-level primitive /cdn/ itself calls internally; this is what+// gets handed to a browser or API consumer instead.+export function cdnUrl(key) {+ if (isAbsoluteUrl(key)) return key;+ return `${env.APP_ORIGIN}/cdn/${encodeR2Key(key)}`;+}++// cdnUrl() for a READ path, same null-degrades-gracefully contract as+// publicUrlOrNull(): a missing key is a designed empty state, not a thrown+// error that takes down the rest of a list response.+export function cdnUrlOrNull(key) {+ if (!key) return null;+ try {+ return cdnUrl(key);+ } catch {+ return null;+ }+}diff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex d6d496fe8..85d8d0d78 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -20,7 +20,7 @@import { sql, isDbUnavailableError } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';-import { publicUrl, thumbnailUrl } from '../_lib/r2.js';+import { thumbnailUrl, cdnUrlOrNull } from '../_lib/r2.js';import { pedigreeScore } from '../_lib/genome.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';@@ -285,7 +285,7 @@ async function handleTheme(req, res) {rating_avg: Number(row.rating_avg || 0),rating_count: row.rating_count || 0,thumbnail_url: thumbnailUrl(row.thumbnail_key),- avatar_glb_url: row.avatar_storage_key ? publicUrl(row.avatar_storage_key) : null,+ avatar_glb_url: row.avatar_storage_key ? cdnUrlOrNull(row.avatar_storage_key) : null,published_at: row.published_at,}));@@ -1510,7 +1510,7 @@ function toCard(row) {tags: row.tags || [],avatar_id: row.avatar_id,thumbnail_url: thumbnailUrl(row.thumbnail_key),- avatar_glb_url: row.avatar_storage_key && avatarPublic ? publicUrl(row.avatar_storage_key) : null,+ avatar_glb_url: row.avatar_storage_key && avatarPublic ? cdnUrlOrNull(row.avatar_storage_key) : null,author_id: row.user_id,skills: row.skills || [],forks_count: row.forks_count || 0,diff --git a/tests/agent-economy-platform.test.js b/tests/agent-economy-platform.test.jsindex 7c4e0d6f7..8510522da 100644--- a/tests/agent-economy-platform.test.js+++ b/tests/agent-economy-platform.test.js@@ -14,10 +14,10 @@ vi.mock('../api/_lib/db.js', () => {const sql = vi.fn(async () => (queue.length ? queue.shift() : []));return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };});-// avatarThumb pulls in r2 publicUrl — stub it so a thumbnail key resolves to a-// deterministic URL without real R2 config.+// avatarThumb pulls in r2 cdnUrlOrNull, so stub it to resolve a thumbnail key to+// a deterministic URL without real R2 config.vi.mock('../api/_lib/r2.js', () => ({- publicUrl: (key) => (key ? `https://cdn.test/${key}` : null),+ cdnUrlOrNull: (key) => (key ? `https://cdn.test/${key}` : null),}));import { sql } from '../api/_lib/db.js';diff --git a/tests/api/avatars-resolve-url-audience.test.js b/tests/api/avatars-resolve-url-audience.test.jsindex 85e21228f..d1ec97bf0 100644--- a/tests/api/avatars-resolve-url-audience.test.js+++ b/tests/api/avatars-resolve-url-audience.test.js@@ -20,8 +20,8 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';vi.mock('../../api/_lib/db.js', () => ({ sql: async () => [] }));vi.mock('../../api/_lib/cache.js', () => ({ cacheWrap: (_k, fn) => fn() }));vi.mock('../../api/_lib/r2.js', () => ({- publicUrl: (key) => `https://pub-test.r2.dev/${key}`,- thumbnailUrl: (key) => (key ? `https://pub-test.r2.dev/${key}` : null),+ cdnUrl: (key) => `https://three.ws/cdn/${key}`,+ thumbnailUrl: (key) => (key ? `https://three.ws/cdn/${key}` : null),presignGet: async ({ key, expiresIn }) =>`https://bucket.r2.cloudflarestorage.com/${key}?X-Amz-Signature=deadbeef&X-Amz-Expires=${expiresIn}`,deleteObject: async () => {},@@ -54,7 +54,7 @@ describe('resolveAvatarUrl audience', () => {const row = { ...PRIVATE, visibility };for (const opts of [{ browser: true }, {}]) {const r = await resolveAvatarUrl(row, opts);- expect(r.url).toBe('https://pub-test.r2.dev/u/o/a.glb');+ expect(r.url).toBe('https://three.ws/cdn/u/o/a.glb');expect(r.cdn).toBe(true);}}diff --git a/tests/r2-public-url-or-null.test.js b/tests/r2-public-url-or-null.test.jsindex 233894a14..41cc05e36 100644--- a/tests/r2-public-url-or-null.test.js+++ b/tests/r2-public-url-or-null.test.js@@ -33,7 +33,7 @@ afterAll(() => {else process.env.S3_PUBLIC_DOMAIN = savedPublicDomain;});-const { publicUrlOrNull, thumbnailUrl, publicUrl } = await import('../api/_lib/r2.js');+const { publicUrlOrNull, thumbnailUrl, publicUrl, cdnUrl, cdnUrlOrNull } = await import('../api/_lib/r2.js');// Load a second, independent instance of the module with storage unconfigured.async function withStorageUnset(fn) {@@ -67,18 +67,52 @@ describe('publicUrlOrNull with object storage configured', () => {expect(publicUrlOrNull('')).toBeNull();});- it('still resolves thumbnails, and still drops legacy poisoned OG keys', () => {- expect(thumbnailUrl('u/42/thumb.png')).toBe('https://cdn.example.com/u/42/thumb.png');+ it('still resolves thumbnails, now through the /cdn/ proxy instead of the raw bucket domain, and still drops legacy poisoned OG keys', () => {+ expect(thumbnailUrl('u/42/thumb.png')).toBe('https://three.ws/cdn/u/42/thumb.png');expect(thumbnailUrl('https://three.ws/avatar/x_og.png')).toBeNull();});});+describe('cdnUrl / cdnUrlOrNull', () => {+ it('builds a same-origin /cdn/<key> URL instead of the raw bucket domain', () => {+ expect(cdnUrl('u/42/avatar.glb')).toBe('https://three.ws/cdn/u/42/avatar.glb');+ expect(cdnUrl('u/42/avatar.glb')).not.toBe(publicUrl('u/42/avatar.glb'));+ });++ it('percent-encodes each key segment, same as publicUrl', () => {+ expect(cdnUrl('u/42/file name.png')).toBe('https://three.ws/cdn/u/42/file%20name.png');+ });++ it('passes an already-absolute storage key through untouched', () => {+ expect(cdnUrl('https://three.ws/avatars/realistic-male.glb')).toBe('https://three.ws/avatars/realistic-male.glb');+ });++ it('cdnUrlOrNull returns null for an absent key rather than throwing', () => {+ expect(cdnUrlOrNull(null)).toBeNull();+ expect(cdnUrlOrNull(undefined)).toBeNull();+ expect(cdnUrlOrNull('')).toBeNull();+ expect(cdnUrlOrNull('u/42/avatar.glb')).toBe('https://three.ws/cdn/u/42/avatar.glb');+ });++ it('never throws when object storage is unconfigured, since /cdn/ needs no bucket domain to build the URL', async () => {+ await withStorageUnset((r2) => {+ expect(r2.cdnUrl('u/42/avatar.glb')).toBe('https://three.ws/cdn/u/42/avatar.glb');+ expect(r2.thumbnailUrl('u/42/thumb.png')).toBe('https://three.ws/cdn/u/42/thumb.png');+ });+ });+});+describe('publicUrlOrNull without object storage', () => {it('degrades to null where publicUrl throws', async () => {await withStorageUnset((r2) => {expect(() => r2.publicUrl('u/42/avatar.glb')).toThrow(/S3_PUBLIC_DOMAIN/);expect(r2.publicUrlOrNull('u/42/avatar.glb')).toBeNull();- expect(r2.thumbnailUrl('u/42/thumb.png')).toBeNull();+ });+ });++ it('thumbnailUrl still resolves without object storage configured, since /cdn/ needs no bucket domain', async () => {+ await withStorageUnset((r2) => {+ expect(r2.thumbnailUrl('u/42/thumb.png')).toBe('https://three.ws/cdn/u/42/thumb.png');});});