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
// Dispatcher for /api/avatars/:id/:action
// Vercel populates req.query.id (from [id] parent dir) and req.query.action
// (from [action] filename) automatically. Each handler below is unchanged
// from its prior single-file form.
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { GetObjectCommand } from '@aws-sdk/client-s3';
import { z } from 'zod';
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';
import { sql } from '../../_lib/db.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { parse, isUuid } from '../../_lib/validate.js';
import { readStorageMode, storageModeSchema, defaultStorageMode } from '../../_lib/storage-mode.js';
import { getAvatar, resolveAvatarUrl } from '../../_lib/avatars.js';
import {
r2,
publicUrl,
publicUrlOrNull,
thumbnailUrl,
isStorageInfrastructureError,
} from '../../_lib/r2.js';
import { env } from '../../_lib/env.js';
import { fetchUpstream } from '../../_lib/upstream-fetch.js';
import { pinToIPFS, ipfsPinningConfigured } from '../../_lib/ipfs-pin.js';
export default wrap(async (req, res) => {
let action = req.query?.action;
// Expose the GLB proxy at a `.glb`-terminating URL as well. Standard glTF
// viewers, NFT marketplaces, and third-party avatar renderers sniff the URL
// extension rather than the `model/gltf-binary` Content-Type, and reject the
// bare `/api/avatars/:id/glb` for not ending in `.glb`. Routing any
// `/api/avatars/:id/<name>.glb` to the same handler makes our avatars load in
// those tools unchanged. (`glb-versions` has no `.glb` suffix, so it's never
// caught here.)
if (typeof action === 'string' && /\.glb$/i.test(action)) action = 'glb';
// Every sub-action below ends up querying `WHERE id = $1` against a uuid
// column. A malformed id leaks Postgres 22P02 to the caller as a 500;
// short-circuit with a clean 404.
const id = req.query?.id;
if (id && !isUuid(id)) {
return error(res, 404, 'not_found', 'avatar not found');
}
switch (action) {
case 'agents':
return handleAgentsByAvatar(req, res);
case 'glb':
return handleGlb(req, res);
case 'glb-versions':
return handleGlbVersions(req, res);
case 'pin-ipfs':
return handlePinIpfs(req, res);
case 'rollback':
return handleRollback(req, res);
case 'session':
return handleSession(req, res);
case 'storage-mode':
return handleStorageMode(req, res);
case 'thumb':
return handleThumb(req, res);
case 'thumbnail':
return handleThumbnail(req, res);
case 'versions':
return handleVersions(req, res);
default:
return error(res, 404, 'not_found', 'unknown avatar action');
}
});
// ── agents (public agents wearing this avatar) ────────────────────────────
// GET /api/avatars/:id/agents
// Returns up to 12 public agents (is_public = true) whose avatar_id matches.
// Public endpoint, rate-limited by IP.
async function handleAgentsByAvatar(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
if (!method(req, res, ['GET'])) return;
const id = req.query?.id;
if (!id) return error(res, 400, 'invalid_request', 'id required');
const rl = await limits.publicIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
const rows = await sql`
SELECT i.id, i.name, i.description, i.profile_image_url, i.created_at,
i.erc8004_agent_id, i.chain_id,
i.meta->>'solana_address' AS solana_address,
i.meta->>'solana_vanity_prefix' AS solana_vanity_prefix,
i.meta->>'solana_vanity_suffix' AS solana_vanity_suffix
FROM agent_identities i
WHERE i.avatar_id = ${id}
AND i.deleted_at IS NULL
AND i.is_public = true
ORDER BY (i.erc8004_agent_id IS NOT NULL) DESC, i.created_at DESC
LIMIT 12
`;
const agents = rows.map((r) => ({
id: r.id,
name: r.name,
description: r.description || '',
profileImage: r.profile_image_url || null,
onchain: r.erc8004_agent_id != null,
chainId: r.chain_id || null,
// Public wallet fields so every surface renders the shared wallet chip
// (tip for visitors, vanity entry for the owner). Mirrors api/trending.js
// + api/characters.js. Secret material is never selected.
solana_address: r.solana_address || null,
solana_vanity_prefix: r.solana_vanity_prefix || null,
solana_vanity_suffix: r.solana_vanity_suffix || null,
createdAt: r.created_at,
url: `/agents/${r.id}`,
}));
res.setHeader('cache-control', 'public, max-age=30, s-maxage=120, stale-while-revalidate=600');
return json(res, 200, { agents });
}
// ── glb-versions ───────────────────────────────────────────────────────────
async function handleGlbVersions(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
const id = req.query?.id;
if (!id) return error(res, 400, 'invalid_request', 'id required');
const session = await getSessionUser(req);
const bearer = session ? null : await authenticateBearer(extractBearer(req));
if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
const userId = session?.id ?? bearer.userId;
const [avatar] = await sql`
select id from avatars
where id = ${id} and owner_id = ${userId} and deleted_at is null
limit 1
`;
if (!avatar) return error(res, 404, 'not_found', 'avatar not found');
// Version rows are written by two paths: the GLB PATCH handler populates
// `storage_key` (an R2 key) while the rollback handler populates `glb_url`.
// Read both and resolve whichever is present to a fetchable URL — bare R2
// keys go through publicUrl(), same as the main avatar GLB read path.
const rows = await sql`
select id, glb_url, storage_key, created_at, metadata
from avatar_versions
where avatar_id = ${id}
order by created_at desc
limit 50
`;
return json(res, 200, {
versions: rows.map((v) => {
const ref = v.glb_url || v.storage_key || null;
const glbUrl = ref ? (/^https?:\/\//i.test(ref) ? ref : publicUrl(ref)) : null;
return {
id: v.id,
glbUrl,
createdAt: v.created_at,
metadata: v.metadata ?? null,
};
}),
});
}
// ── pin-ipfs ───────────────────────────────────────────────────────────────
async function handlePinIpfs(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
if (!id) return error(res, 400, 'validation_error', 'avatar id required');
const session = await getSessionUser(req);
if (!session) return error(res, 401, 'unauthorized', 'sign in required');
if (!(await requireCsrf(req, res, session.id))) return;
const [row] = await sql`
SELECT id, owner_id, checksum_sha256, storage_key, content_type, name
FROM avatars WHERE id = ${id} AND deleted_at IS NULL
`;
if (!row) return error(res, 404, 'not_found', 'avatar not found');
if (row.owner_id !== session.id) return error(res, 403, 'forbidden', 'not your avatar');
const mode = await readStorageMode(id);
if (!mode) return error(res, 500, 'internal', 'storage_mode unavailable');
let cid;
let isStub = false;
if (ipfsPinningConfigured() && row.storage_key) {
try {
cid = await pinAvatarObject({
key: row.storage_key,
name: row.name || `avatar-${id}`,
contentType: row.content_type || 'model/gltf-binary',
});
} catch (err) {
return error(res, 502, 'upstream_error', `IPFS pin failed: ${err.message}`);
}
} else {
isStub = true;
cid = row.checksum_sha256 ? `stub:sha256-${row.checksum_sha256}` : `stub:no-hash-${id}`;
}
const next = {
...mode,
ipfs: { pinned: true, cid, pinned_at: new Date().toISOString() },
};
await sql`UPDATE avatars SET storage_mode = ${JSON.stringify(next)}::jsonb WHERE id = ${id}`;
return json(res, 200, { storage_mode: next, stub: isStub });
}
// Read the stored object out of R2 and pin it through the shared provider
// chain (Pinata, then web3.storage; api/_lib/ipfs-pin.js), so one provider's
// outage fails over instead of failing the pin.
async function pinAvatarObject({ key, name, contentType }) {
const obj = await r2.send(new GetObjectCommand({ Bucket: env.S3_BUCKET, Key: key }));
const bytes = await streamToBuffer(obj.Body);
const filename = /\.(glb|gltf|vrm)$/i.test(name) ? name : `${name}.${contentType === 'model/gltf+json' ? 'gltf' : 'glb'}`;
const pinned = await pinToIPFS(bytes, filename);
if (!pinned?.cid) throw new Error('no CID in pinning response');
return pinned.cid;
}
async function streamToBuffer(stream) {
if (stream instanceof Uint8Array) return stream;
if (typeof stream?.transformToByteArray === 'function') {
return stream.transformToByteArray();
}
const chunks = [];
for await (const chunk of stream) chunks.push(chunk);
return Buffer.concat(chunks);
}
// ── rollback ───────────────────────────────────────────────────────────────
const rollbackBodySchema = z.object({
versionId: z.coerce.number().int().positive(),
});
async function handleRollback(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
const id = req.query?.id;
if (!id) return error(res, 400, 'invalid_request', 'id required');
const session = await getSessionUser(req);
const bearer = session ? null : await authenticateBearer(extractBearer(req));
if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
const userId = session?.id ?? bearer.userId;
if (!(await requireCsrf(req, res, userId))) return;
const rl = await limits.avatarRollback(userId);
if (!rl.success) return rateLimited(res, rl);
const { versionId } = parse(rollbackBodySchema, await readJson(req));
const [avatar] = await sql`
select id from avatars
where id = ${id} and owner_id = ${userId} and deleted_at is null
limit 1
`;
if (!avatar) return error(res, 404, 'not_found', 'avatar not found');
const [ver] = await sql`
select id, glb_url from avatar_versions
where id = ${versionId} and avatar_id = ${id}
limit 1
`;
if (!ver) return error(res, 404, 'not_found', 'version not found');
const [updated] = await sql`
update avatars
set storage_key = ${ver.glb_url}, updated_at = now()
where id = ${id} and owner_id = ${userId}
returning id, owner_id, slug, name, description, storage_key, size_bytes,
content_type, source, visibility, tags, version, created_at, updated_at
`;
await sql`
insert into avatar_versions (avatar_id, glb_url, metadata, created_by)
values (
${id},
${ver.glb_url},
${JSON.stringify({ rollback_of: versionId })}::jsonb,
${userId}
)
`;
return json(res, 200, { ok: true, avatar: updated });
}
// ── session ────────────────────────────────────────────────────────────────
async function handleSession(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
const id = req.query?.id;
if (!id) return error(res, 400, 'invalid_request', 'id required');
const auth = await resolveSessionAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
if (!(await requireCsrf(req, res, auth.userId))) return;
const rl = await limits.upload(auth.userId);
if (!rl.success) return rateLimited(res, rl, 'too many requests, try again later');
// 404 (not 403) when not found or not owned — mirrors [id].js.
const avatar = await getAvatar({ id, requesterId: auth.userId });
if (!avatar || avatar.owner_id !== auth.userId) {
return error(res, 404, 'not_found', 'avatar not found');
}
if (!env.AVATURN_API_KEY) {
return error(
res,
501,
'not_configured',
'Avaturn is not configured on this deployment. Set AVATURN_API_KEY.',
);
}
// Resolve a time-limited URL the Avaturn upstream can fetch (works for private too).
const { url: glbUrl } = await resolveAvatarUrl(avatar, { expiresIn: 3600 });
try {
const result = await createAvaturnEditSession({
apiKey: env.AVATURN_API_KEY,
apiUrl: env.AVATURN_API_URL,
userId: auth.userId,
avatarUrl: glbUrl,
});
return json(res, 200, result);
} catch (err) {
const status = err?.status || 502;
const code = err?.code || 'upstream_error';
const message = err?.message || 'avatar provider rejected request';
if (status >= 500) console.error('[avatars/session] upstream failure:', err);
return error(res, status >= 500 ? 502 : status, code, message);
}
}
async function resolveSessionAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
const bearer = await authenticateBearer(extractBearer(req));
if (!bearer) return null;
if (!hasScope(bearer.scope, 'avatars:write')) return null;
return { userId: bearer.userId };
}
/**
* Opens an existing avatar in Avaturn for editing.
* Passes `avatar_url` so Avaturn pre-populates the editor with the existing mesh.
* If Avaturn's API uses a different field (e.g. `avatarUrl`, `model_url`), update
* the payload mapping below and the AVATURN_API_URL env var accordingly.
*/
async function createAvaturnEditSession({ apiKey, apiUrl, userId, avatarUrl }) {
const url = `${apiUrl}/api/v1/sessions`;
const payload = {
external_user_id: userId,
avatar_url: avatarUrl,
};
// Bounded, single attempt: opening an edit session is a create, so a retry
// would leave a second session behind. The status mapping below needs the
// Response itself, so a non-2xx returns rather than throws.
let upstream;
try {
upstream = await fetchUpstream(url, {
method: 'POST',
headers: {
authorization: `Bearer ${apiKey}`,
'content-type': 'application/json',
accept: 'application/json',
},
body: JSON.stringify(payload),
}, { name: 'avaturn:sessions', timeoutMs: 20_000, attempts: 1, okWhen: () => true });
} catch (e) {
const err = new Error(`avaturn unreachable: ${e?.message || 'network error'}`);
err.status = 502;
err.code = 'upstream_error';
throw err;
}
if (!upstream.ok) {
const text = await upstream.text().catch(() => '');
const err = new Error(`avaturn upstream ${upstream.status}: ${text.slice(0, 200)}`);
err.status = upstream.status >= 500 ? 502 : upstream.status;
err.code = upstream.status === 401 ? 'upstream_auth' : 'upstream_error';
throw err;
}
const data = await upstream.json();
const sessionUrl = data?.session_url || data?.url || data?.iframe_url;
if (!sessionUrl) {
const err = new Error('avaturn response missing session_url');
err.status = 502;
err.code = 'upstream_error';
throw err;
}
return { session_url: sessionUrl, expires_at: data.expires_at ?? null };
}
// ── storage-mode ───────────────────────────────────────────────────────────
async function handleStorageMode(req, res) {
if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'PUT'])) return;
const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
if (!id) return error(res, 400, 'validation_error', 'avatar id required');
// PUT is owner-only: authenticate BEFORE any avatar lookup so an anonymous
// caller can't use the 404-vs-401 split to probe whether an id exists.
if (req.method === 'PUT') {
const session = await getSessionUser(req);
if (!session) return error(res, 401, 'unauthorized', 'sign in required');
if (!(await requireCsrf(req, res, session.id))) return;
const [row] = await sql`
SELECT id, owner_id FROM avatars WHERE id = ${id} AND deleted_at IS NULL
`;
if (!row) return error(res, 404, 'not_found', 'avatar not found');
if (session.id !== row.owner_id) return error(res, 403, 'forbidden', 'not your avatar');
const body = parse(storageModeSchema, await readJson(req));
// Read current stored mode to preserve attestation fields: clients must not
// be able to forge tx_hash / chain_id / attested_at from the UI.
const current = await readStorageMode(id);
const safeBody = {
...body,
attestation: current?.attestation ?? defaultStorageMode().attestation,
};
await sql`UPDATE avatars SET storage_mode = ${JSON.stringify(safeBody)}::jsonb WHERE id = ${id}`;
return json(res, 200, { storage_mode: safeBody });
}
// GET: public/unlisted anyone; private owner only.
const [row] = await sql`
SELECT id, owner_id, visibility FROM avatars WHERE id = ${id} AND deleted_at IS NULL
`;
if (!row) return error(res, 404, 'not_found', 'avatar not found');
if (row.visibility === 'private') {
const session = await getSessionUser(req);
if (!session || session.id !== row.owner_id)
return error(res, 403, 'forbidden', 'private avatar');
}
const mode = await readStorageMode(id);
return json(res, 200, { storage_mode: mode });
}
// ── versions ───────────────────────────────────────────────────────────────
async function handleVersions(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
const id = req.query?.id;
if (!id) return error(res, 400, 'invalid_request', 'id required');
if (!isUuid(id)) return error(res, 400, 'invalid_request', 'id must be a valid UUID');
const auth = await resolveVersionsAuth(req);
// Walk upward through parent_avatar_id to collect the full ancestor chain,
// then walk downward from the root to collect all descendants.
// Two-phase CTE keeps the query readable and avoids a self-join cycle.
const rows = await sql`
WITH RECURSIVE
ancestors AS (
SELECT id, parent_avatar_id, created_at
FROM avatars
WHERE id = ${id} AND deleted_at IS NULL
UNION ALL
SELECT a.id, a.parent_avatar_id, a.created_at
FROM avatars a
JOIN ancestors anc ON a.id = anc.parent_avatar_id
WHERE a.deleted_at IS NULL
),
root AS (
SELECT id FROM ancestors WHERE parent_avatar_id IS NULL LIMIT 1
),
chain AS (
SELECT a.id, a.parent_avatar_id, a.created_at
FROM avatars a
JOIN root r ON a.id = r.id
WHERE a.deleted_at IS NULL
UNION ALL
SELECT a.id, a.parent_avatar_id, a.created_at
FROM avatars a
JOIN chain c ON a.parent_avatar_id = c.id
WHERE a.deleted_at IS NULL
)
SELECT id, created_at FROM chain ORDER BY created_at ASC
`;
// If the seed avatar wasn't found (deleted or wrong id), the ancestor CTE
// returns empty → chain is also empty.
if (!rows.length) return error(res, 404, 'not_found', 'avatar not found');
// Determine the caller's current avatar so is_current can be set.
let currentAvatarId = null;
if (auth?.userId) {
const [agent] = await sql`
SELECT avatar_id FROM agent_identities
WHERE user_id = ${auth.userId} AND deleted_at IS NULL
ORDER BY created_at ASC LIMIT 1
`;
currentAvatarId = agent?.avatar_id ?? null;
}
const total = rows.length;
const versions = rows.map((row, i) => ({
id: row.id,
version: i + 1,
total,
created_at: row.created_at,
is_current: row.id === currentAvatarId,
}));
return json(res, 200, { versions });
}
async function resolveVersionsAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
const bearer = await authenticateBearer(extractBearer(req));
return bearer ? { userId: bearer.userId } : null;
}
// ── thumbnail ──────────────────────────────────────────────────────────────
// GET /api/avatars/:id/thumbnail — 302 to the avatar's R2-hosted PNG poster.
// Public/unlisted avatars: anyone. Private: owner (session or bearer) only.
// No thumbnail → 404.
async function handleThumbnail(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
if (!id) return error(res, 400, 'invalid_request', 'avatar id required');
const [row] = await sql`
SELECT id, owner_id, visibility, thumbnail_key
FROM avatars WHERE id = ${id} AND deleted_at IS NULL
LIMIT 1
`;
if (!row) return error(res, 404, 'not_found', 'avatar not found');
if (row.visibility === 'private') {
const auth = await resolveVersionsAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
if (auth.userId !== row.owner_id) return error(res, 403, 'forbidden', 'not your avatar');
}
if (!row.thumbnail_key) return error(res, 404, 'not_found', 'avatar has no thumbnail');
return redirect(res, thumbnailUrl(row.thumbnail_key));
}
function redirect(res, url) {
// 302 keeps the URL cacheable for short windows without sticking permanently —
// the underlying thumbnail_key can change after a re-render.
res.statusCode = 302;
res.setHeader('location', url);
res.setHeader('cache-control', 'public, max-age=60, s-maxage=300');
res.end();
}
// ── thumb (embed-friendly poster) ────────────────────────────────────────────
// GET /api/avatars/:id/thumb — 302 to the avatar's R2-hosted poster, with
// wildcard CORS so it loads from a plain <img src> in any first-party client
// (the Walk Avatar extension popup, the embed SDK) where an Authorization
// header can't be attached. Unlike `thumbnail`, this is public for every
// visibility: the poster PNG is already a public CDN object, while the GLB
// stays gated behind `glb`. No thumbnail → 404 so the client renders its
// initial-glyph fallback.
async function handleThumb(req, res) {
res.setHeader('access-control-allow-origin', '*');
res.setHeader('access-control-allow-methods', 'GET,OPTIONS');
if (req.method === 'OPTIONS') {
res.statusCode = 204;
return res.end();
}
if (!method(req, res, ['GET'])) return;
const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
if (!id) return error(res, 400, 'invalid_request', 'avatar id required');
const [row] = await sql`
SELECT thumbnail_key FROM avatars WHERE id = ${id} AND deleted_at IS NULL LIMIT 1
`;
if (!row) return error(res, 404, 'not_found', 'avatar not found');
if (!row.thumbnail_key) return error(res, 404, 'not_found', 'avatar has no thumbnail');
return redirect(res, thumbnailUrl(row.thumbnail_key));
}
// ── glb (same-origin CORS-friendly proxy) ─────────────────────────────────
// GET /api/avatars/:id/glb — streams the avatar's GLB through the API so
// hosts on any origin can fetch it without R2 CORS configuration. The R2
// public domain serves `Access-Control-Allow-Origin: https://three.ws` only,
// which breaks the embed SDK when dropped on third-party sites and the
// /walk-embed page when loaded from a dev host. Routing the bytes through
// this endpoint side-steps that — we attach `Access-Control-Allow-Origin: *`
// because the underlying GLBs are already publicly readable on the CDN.
//
// Permission rules mirror handleThumbnail:
// • public + unlisted: anyone
// • private: owner only (session or bearer with avatars:read)
async function handleGlb(req, res) {
// Reply with CORS for all origins. Browsers also need the preflight,
// which the shared `cors()` helper doesn't open up to wildcard origins,
// so we set the headers directly.
res.setHeader('access-control-allow-origin', '*');
res.setHeader('access-control-allow-methods', 'GET,OPTIONS');
res.setHeader('access-control-allow-headers', 'range,accept');
res.setHeader('access-control-expose-headers', 'content-length,content-range,etag');
if (req.method === 'OPTIONS') {
res.statusCode = 204;
return res.end();
}
if (!method(req, res, ['GET'])) return;
const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
if (!id) return error(res, 400, 'invalid_request', 'avatar id required');
// Resolve the caller BEFORE the lookup: getAvatar() drops private avatars for
// non-owners (returns null), so passing requesterId: null here made the
// private branch below dead code — an owner could never fetch their own
// private GLB with a valid session/bearer. Thread the authenticated id in so
// the documented "private: owner only" contract actually holds.
const auth = await resolveVersionsAuth(req);
const avatar = await getAvatar({ id, requesterId: auth?.userId ?? null });
if (!avatar) return error(res, 404, 'not_found', 'avatar not found');
if (avatar.visibility === 'private') {
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
if (auth.userId !== avatar.owner_id) return error(res, 403, 'forbidden', 'not your avatar');
}
// Resolve the same R2 key the canonical avatar URL serves. Streaming
// from R2 directly with the S3 SDK avoids a second hop through the
// public CDN — and gives us a Node readable stream we can pipe straight
// into res with no buffer-the-whole-thing memory blow-up.
const key =
avatar.baked_storage_key && avatar.appearance_hash
? avatar.baked_storage_key
: avatar.storage_key;
if (!key) return error(res, 404, 'not_found', 'avatar has no glb');
try {
const { Body, ContentLength, ETag } = await r2.send(
new GetObjectCommand({ Bucket: env.S3_BUCKET, Key: key }),
);
res.statusCode = 200;
res.setHeader('content-type', 'model/gltf-binary');
if (ContentLength != null) res.setHeader('content-length', String(ContentLength));
if (ETag) res.setHeader('etag', ETag);
// GLBs are content-addressed by key (rotation produces a new key), so
// long-cache the bytes — clients revalidate via the avatar metadata
// endpoint, not by re-hitting /glb.
res.setHeader('cache-control', 'public, max-age=300, s-maxage=86400, immutable');
Body.pipe(res);
Body.on('error', (err) => {
console.error('[avatars/glb] stream error:', err);
try {
res.destroy(err);
} catch {}
});
} catch (err) {
// 404 if R2 doesn't know the key (deleted out-of-band).
const code = err?.Code || err?.name;
if (code === 'NoSuchKey' || code === 'NotFound') {
return error(res, 404, 'not_found', 'avatar glb missing from storage');
}
// The signed read is broken, not the object: the credential is rejected
// or the endpoint is unreachable, and the same key is readable
// unauthenticated on the bucket's public domain. api/cdn-object.js grew
// this rung on 2026-09-07 and this route never did, so a rejected R2
// secret answered 502 for EVERY avatar GLB on the site: /pay, /walk and
// every embed swapped the user's avatar for the "robot" placeholder
// while the public domain served those same bytes with a 200 throughout.
//
// cdn-object redirects; this route must not. Its entire reason to exist
// is that the public r2.dev domain sends no access-control-allow-origin
// at all, so a 302 there turns a 502 into a CORS failure for the embed
// SDK and every cross-origin GLTFLoader. Streaming the bytes through
// keeps the wildcard CORS headers set at the top of this handler, so the
// contract callers depend on survives the degraded path unchanged.
//
// The permission gate above has already run, so this changes who may
// read nothing: it only changes which origin the bytes come from.
const fallbackUrl = isStorageInfrastructureError(err) ? publicUrlOrNull(key) : null;
if (fallbackUrl) {
console.error('[avatars/glb] signed read failed, streaming public bucket domain:', key, err?.message);
try {
const upstream = await fetchUpstream(
fallbackUrl,
{ headers: { accept: 'model/gltf-binary,*/*' } },
{ name: 'r2:public-glb', timeoutMs: 20_000, attempts: 2 },
);
res.statusCode = 200;
res.setHeader('content-type', 'model/gltf-binary');
const len = upstream.headers.get('content-length');
if (len) res.setHeader('content-length', len);
const etag = upstream.headers.get('etag');
if (etag) res.setHeader('etag', etag);
// Never cache the degraded path: the moment the credential is
// healthy again traffic has to return to the signed read with no
// stale hop pinned at the edge.
res.setHeader('cache-control', 'no-store');
await pipeline(Readable.fromWeb(upstream.body), res);
return;
} catch (fallbackErr) {
console.error('[avatars/glb] public bucket domain failed too:', key, fallbackErr?.message);
if (res.headersSent) return res.destroy(fallbackErr);
// Nothing has been written yet, so the 502 below still gets to
// answer, but only if the GLB's own length and etag come back
// off first. json() refuses to touch a committed response and
// never clears headers, so leaving content-length behind would
// pin the error body to the model's byte count and hang the
// client waiting for megabytes that are never coming.
res.removeHeader('content-length');
res.removeHeader('etag');
}
}
console.error('[avatars/glb] r2 fetch failed:', err);
return error(res, 502, 'upstream_error', 'failed to fetch avatar glb');
}
}