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: production log sweep — first-party R2 CDN proxy, Edge TTS protocol repair, play leave() crash, WebGL fallbacks, market-source circuit breaker

nirholas4b6fb78614c3
diff --git a/api/_lib/market/token-market.js b/api/_lib/market/token-market.js
index a5f13ded4..b05de640b 100644
--- a/api/_lib/market/token-market.js
+++ b/api/_lib/market/token-market.js
@@ -24,6 +24,21 @@ const _cache = new Map(); // mint → { value, expires, fetchedAt }
const _warnedAt = new Map();
const WARN_COOLDOWN_MS = 60_000;
+// Circuit breaker: when a source reports an exhausted quota (Birdeye's monthly
+// compute units) or rate-limits us, stop hitting it for a while instead of
+// burning a doomed upstream call + warning on every read. Quota exhaustion
+// only clears on the provider's billing cycle, so it gets a long cooldown.
+const _sourceCooldown = new Map(); // source name → epoch ms to skip until
+const QUOTA_COOLDOWN_MS = 6 * 3_600_000;
+const RATE_LIMIT_COOLDOWN_MS = 10 * 60_000;
+
+function cooldownFor(err) {
+ const msg = String(err?.message || '');
+ if (/usage limit exceeded|quota exceeded/i.test(msg)) return QUOTA_COOLDOWN_MS;
+ if (/^429\b|rate ?limit/i.test(msg)) return RATE_LIMIT_COOLDOWN_MS;
+ return 0;
+}
+
function warnThrottled(key, msg) {
const now = Date.now();
if (now - (_warnedAt.get(key) || 0) < WARN_COOLDOWN_MS) return;
@@ -147,6 +162,7 @@ export async function fetchTokenMarketData(mint, { fresh = false, ttlMs = DEFAUL
if (!fresh && hit && hit.expires > now) return hit.value;
for (const src of SOURCES) {
+ if ((_sourceCooldown.get(src.name) || 0) > now) continue;
try {
const result = await src(mint);
if (result && result.price_usd > 0) {
@@ -155,7 +171,13 @@ export async function fetchTokenMarketData(mint, { fresh = false, ttlMs = DEFAUL
return result;
}
} catch (err) {
- warnThrottled(`${mint}:${src.name}`, `[market] ${src.name} failed for ${mint.slice(0, 6)}…: ${err?.message}`);
+ const cooldown = cooldownFor(err);
+ if (cooldown) {
+ _sourceCooldown.set(src.name, now + cooldown);
+ warnThrottled(`${src.name}:cooldown`, `[market] ${src.name} quota/rate-limited — skipping it for ${Math.round(cooldown / 60_000)}min: ${err?.message}`);
+ } else {
+ warnThrottled(`${mint}:${src.name}`, `[market] ${src.name} failed for ${mint.slice(0, 6)}…: ${err?.message}`);
+ }
}
}
@@ -178,4 +200,5 @@ export async function fetchTokenPriceUsd(mint, opts) {
export function __resetMarketCache() {
_cache.clear();
_warnedAt.clear();
+ _sourceCooldown.clear();
}
diff --git a/api/cdn-object.js b/api/cdn-object.js
new file mode 100644
index 000000000..e40593265
--- /dev/null
+++ b/api/cdn-object.js
@@ -0,0 +1,123 @@
+// GET /cdn/<key> — first-party CDN for R2 bucket objects (avatars, thumbnails,
+// forge GLBs). Routed via vercel.json: `/cdn/(.*)` → `/api/cdn-object?key=$1`.
+//
+// Why this exists: the bucket's public `*.r2.dev` dev domain is rate-limited by
+// Cloudflare and not meant for production traffic — gallery pages loading dozens
+// of thumbnails got throttled mid-burst, surfacing as `failed to load img /
+// model-viewer` client errors. Streaming through the authenticated S3 endpoint
+// sidesteps that limit entirely, and Vercel's CDN absorbs repeat reads via
+// `s-maxage`, so each object is fetched from R2 roughly once per region per day.
+//
+// Exposure parity: the bucket is already fully readable through the public
+// r2.dev domain, so serving the same namespace here grants nothing new.
+
+import { GetObjectCommand } from '@aws-sdk/client-s3';
+import { cors, error, wrap } from './_lib/http.js';
+import { r2 } from './_lib/r2.js';
+import { env } from './_lib/env.js';
+
+// Object keys are caller-controlled path input — keep them boring. UUID-based
+// keys, slashes, dots-in-filenames only; no traversal, no control chars.
+const KEY_RE = /^[\w!*'().@-]+(?:\/[\w!*'().@-]+)*(?:\.[\w-]+)?$/;
+const MAX_KEY_LENGTH = 512;
+
+const CONTENT_TYPES = {
+ png: 'image/png',
+ jpg: 'image/jpeg',
+ jpeg: 'image/jpeg',
+ webp: 'image/webp',
+ gif: 'image/gif',
+ svg: 'image/svg+xml',
+ glb: 'model/gltf-binary',
+ gltf: 'model/gltf+json',
+ usdz: 'model/vnd.usdz+zip',
+ bin: 'application/octet-stream',
+ json: 'application/json',
+ mp3: 'audio/mpeg',
+ wav: 'audio/wav',
+ mp4: 'video/mp4',
+ webm: 'video/webm',
+};
+
+function contentTypeFor(key, stored) {
+ // R2 objects uploaded without an explicit type default to octet-stream —
+ // prefer the extension in that case so browsers render instead of download.
+ if (stored && stored !== 'application/octet-stream') return stored;
+ const ext = key.split('.').pop()?.toLowerCase();
+ return CONTENT_TYPES[ext] || stored || 'application/octet-stream';
+}
+
+function cacheControlFor(key) {
+ // Thumbnails are regenerated under the same key, so let browsers revalidate
+ // hourly. Content keys (u/…, forge outputs) embed random segments and are
+ // write-once in practice — cache long everywhere.
+ return key.startsWith('thumb/')
+ ? 'public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800'
+ : 'public, max-age=86400, s-maxage=2592000, stale-while-revalidate=604800';
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,HEAD,OPTIONS', origins: '*' })) return;
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
+ res.setHeader('allow', 'GET, HEAD, OPTIONS');
+ return error(res, 405, 'method_not_allowed', 'GET or HEAD only');
+ }
+
+ const raw = req.query?.key;
+ const key = typeof raw === 'string' ? raw : '';
+ if (!key || key.length > MAX_KEY_LENGTH || key.includes('..') || !KEY_RE.test(key)) {
+ return error(res, 400, 'invalid_key', 'malformed object key');
+ }
+
+ const ifNoneMatch = req.headers['if-none-match'];
+ const range = req.headers.range;
+
+ try {
+ const obj = await r2.send(
+ new GetObjectCommand({
+ Bucket: env.S3_BUCKET,
+ Key: key,
+ IfNoneMatch: ifNoneMatch,
+ Range: range,
+ }),
+ );
+
+ res.statusCode = range && obj.ContentRange ? 206 : 200;
+ res.setHeader('content-type', contentTypeFor(key, obj.ContentType));
+ res.setHeader('cache-control', cacheControlFor(key));
+ res.setHeader('accept-ranges', 'bytes');
+ if (obj.ETag) res.setHeader('etag', obj.ETag);
+ if (obj.ContentLength != null) res.setHeader('content-length', String(obj.ContentLength));
+ if (obj.ContentRange) res.setHeader('content-range', obj.ContentRange);
+
+ if (req.method === 'HEAD') {
+ obj.Body?.destroy?.();
+ return res.end();
+ }
+
+ obj.Body.pipe(res);
+ obj.Body.on('error', (err) => {
+ console.error('[cdn-object] stream error:', key, err?.message);
+ try {
+ res.destroy(err);
+ } catch {}
+ });
+ } catch (err) {
+ const status = err?.$metadata?.httpStatusCode;
+ if (status === 304) {
+ res.statusCode = 304;
+ res.setHeader('cache-control', cacheControlFor(key));
+ if (ifNoneMatch) res.setHeader('etag', ifNoneMatch);
+ return res.end();
+ }
+ const code = err?.Code || err?.name;
+ if (code === 'NoSuchKey' || code === 'NotFound' || status === 404) {
+ return error(res, 404, 'not_found', 'object not found');
+ }
+ if (code === 'InvalidRange' || status === 416) {
+ return error(res, 416, 'invalid_range', 'requested range not satisfiable');
+ }
+ console.error('[cdn-object] r2 fetch failed:', key, err?.message);
+ return error(res, 502, 'upstream_error', 'failed to fetch object');
+ }
+});
diff --git a/api/tts/edge.js b/api/tts/edge.js
index d5e570b18..3f2830354 100644
--- a/api/tts/edge.js
+++ b/api/tts/edge.js
@@ -13,6 +13,7 @@
* Response: audio/mpeg
*/
+import { createHash } from 'node:crypto';
import WebSocket from 'ws';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { cors, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
@@ -21,17 +22,43 @@ import { sha256 } from '../_lib/crypto.js';
import { headObject, getObjectBuffer, putObject } from '../_lib/r2.js';
const TRUSTED_CLIENT_TOKEN = '6A5AA1D4EAFF4E9FB37E23D68491D6F4';
-const WSS_BASE = `wss://speech.microsoft.com/consumer/speech/synthesize/readaloud/edge/v1?TrustedClientToken=${TRUSTED_CLIENT_TOKEN}`;
+// speech.platform.bing.com is the host the readaloud protocol actually lives
+// on. speech.microsoft.com (used previously) serves the Speech Studio web app,
+// which answers every path with a 200 HTML page — hence the constant
+// "Unexpected server response: 200" handshake failures.
+const WSS_BASE = `wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1?TrustedClientToken=${TRUSTED_CLIENT_TOKEN}`;
const AUDIO_FORMAT = 'audio-24khz-48kbitrate-mono-mp3';
+// Must track the Edg/ version in WS_HEADERS' User-Agent below. The endpoint
+// 403s GEC versions it considers stale, so bump this alongside edge-tts
+// releases (their constants.py carries the current known-good value).
+const CHROMIUM_FULL_VERSION = '143.0.3650.75';
+
+// Sec-MS-GEC DRM token, required by the readaloud endpoint since late 2024.
+// SHA-256 of the current Windows file time (100ns ticks since 1601-01-01,
+// rounded DOWN to the nearest 5 minutes) concatenated with the client token —
+// same scheme the edge-tts reference implementation ships. Handshakes without
+// it are intermittently rejected with a non-101 response ("Unexpected server
+// response: 200").
+function secMsGecToken() {
+ const WIN_EPOCH_SECONDS = 11_644_473_600; // 1601-01-01 → 1970-01-01
+ let seconds = Math.floor(Date.now() / 1000) + WIN_EPOCH_SECONDS;
+ seconds -= seconds % 300;
+ // seconds → 100ns ticks would overflow Number; appending seven zeros is the
+ // same multiplication by 10^7 done in string space.
+ return createHash('sha256')
+ .update(`${seconds}0000000${TRUSTED_CLIENT_TOKEN}`)
+ .digest('hex')
+ .toUpperCase();
+}
const WS_HEADERS = {
Pragma: 'no-cache',
'Cache-Control': 'no-cache',
Origin: 'chrome-extension://jdiccldimpdaibmpdkjnbmckianbfold',
- 'Accept-Encoding': 'gzip, deflate, br',
+ 'Accept-Encoding': 'gzip, deflate, br, zstd',
'Accept-Language': 'en-US,en;q=0.9',
'User-Agent':
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0',
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0',
};
// e.g. "en-US-AriaNeural", "zh-CN-XiaoxiaoNeural"
@@ -60,7 +87,10 @@ function buildSsml(voice, text, rate, pitch) {
function synthesize(voice, text, rate, pitch) {
return new Promise((resolve, reject) => {
const connId = mkId();
- const ws = new WebSocket(`${WSS_BASE}&ConnectionId=${connId}`, { headers: WS_HEADERS });
+ const url =
+ `${WSS_BASE}&Sec-MS-GEC=${secMsGecToken()}` +
+ `&Sec-MS-GEC-Version=1-${CHROMIUM_FULL_VERSION}&ConnectionId=${connId}`;
+ const ws = new WebSocket(url, { headers: WS_HEADERS });
const chunks = [];
let finished = false;
diff --git a/data/changelog.json b/data/changelog.json
index d8f636ca3..4f4f089b7 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1014,6 +1014,16 @@
"feature",
"security"
]
+ },
+ {
+ "date": "2026-06-12",
+ "title": "Reliability sweep: faster galleries, working voices, sturdier pages",
+ "summary": "A pass over every error in the production logs. Avatar thumbnails and 3D models now load through three.ws itself instead of a rate-limited storage domain, so gallery pages stop dropping images under load. Text-to-speech voices are back (the upstream voice service had changed its protocol). Leaving a world on /play no longer hits a crash that could leave the session connected in the background. The homepage 3D demos politely step aside on devices without WebGL instead of breaking, payment demo requests get more time to settle on-chain, and the $THREE market stats failover stops hammering an exhausted data provider.",
+ "tags": [
+ "fix",
+ "improvement",
+ "infra"
+ ]
}
]
}
diff --git a/public/error-reporter.js b/public/error-reporter.js
index 6414efac4..628d9de5a 100644
--- a/public/error-reporter.js
+++ b/public/error-reporter.js
@@ -70,8 +70,12 @@
// control. model-viewer (served from ajax.googleapis.com) throws internally
// when the browser can't give it a WebGL context — context budget exhausted,
// GPU blocklist, headless. It degrades to its poster on its own; the throw is
- // neither our bug nor fixable from here, so it only adds noise.
- const IGNORED_THIRD_PARTY_CODE = /ajax\.googleapis\.com\/ajax\/libs\/model-viewer\//;
+ // neither our bug nor fixable from here, so it only adds noise. Vercel's
+ // insights script likewise throws in stripped-down in-app webviews (e.g.
+ // "history.pushState is undefined" inside wallet browsers) — analytics
+ // degrading on an exotic UA is not actionable.
+ const IGNORED_THIRD_PARTY_CODE =
+ /ajax\.googleapis\.com\/ajax\/libs\/model-viewer\/|\/_vercel\/(insights|speed-insights)\/script/;
// Expiring signed URLs embedded in user-generated feed data: GitHub
// private-user-images, S3/GCS presigned links, and anything carrying a
// short-lived JWT/signature. The token lapses on a timer, so the asset 404s
diff --git a/public/wallet-login.js b/public/wallet-login.js
index 949ec4223..e7a202afe 100644
--- a/public/wallet-login.js
+++ b/public/wallet-login.js
@@ -4,8 +4,31 @@
// Loaded at runtime from /public via plain `<script src>`. Imports use the
// dynamic form with @vite-ignore so Vite (which forbids static imports of
// files under /public) doesn't try to analyze these URLs at build time.
-const { createConnectWalletButton } = await import(/* @vite-ignore */ '/wallet/connect-button.js');
-const { createSolanaWalletButton } = await import(/* @vite-ignore */ '/wallet/connect-button-solana.js');
+//
+// In-app webviews (Phantom, MetaMask) drop the first fetch of a module
+// surprisingly often on flaky mobile networks, which used to kill this whole
+// module with no feedback — retry once, then degrade to a visible error.
+async function importWithRetry(url) {
+ try {
+ return await import(/* @vite-ignore */ url);
+ } catch {
+ await new Promise((r) => setTimeout(r, 400));
+ return import(/* @vite-ignore */ url);
+ }
+}
+
+let createConnectWalletButton = null;
+let createSolanaWalletButton = null;
+try {
+ ({ createConnectWalletButton } = await importWithRetry('/wallet/connect-button.js'));
+ ({ createSolanaWalletButton } = await importWithRetry('/wallet/connect-button-solana.js'));
+} catch {
+ const el = document.getElementById('err');
+ if (el) {
+ el.textContent = 'Couldn’t load the wallet sign-in modules. Check your connection and refresh the page.';
+ el.style.display = 'block';
+ }
+}
const params = new URLSearchParams(location.search);
const next = window.__loginNext || params.get('next') || sessionStorage.getItem('login_redirect') || '/dashboard';
@@ -36,7 +59,7 @@ function onSuccess(data) {
const wcProjectId = document.querySelector('meta[name="wc-project-id"]')?.content || null;
const evmMount = document.getElementById('wallet-mount');
-if (evmMount) {
+if (evmMount && createConnectWalletButton) {
const evmCtrl = createConnectWalletButton(evmMount, {
verifyUrl: '/api/auth/siwe/verify',
wcProjectId,
@@ -59,7 +82,7 @@ let solanaCtrl = null;
function mountSolanaButton(preferredWallet = null) {
const mount = document.getElementById('solana-wallet-mount');
- if (!mount) return;
+ if (!mount || !createSolanaWalletButton) return;
if (solanaCtrl) solanaCtrl.disconnect();
solanaCtrl = createSolanaWalletButton(mount, {
diff --git a/src/avatar-drop.js b/src/avatar-drop.js
index ecad3b1b4..dad47a8f9 100644
--- a/src/avatar-drop.js
+++ b/src/avatar-drop.js
@@ -23,7 +23,17 @@ export function initAvatarDrop(sectionEl) {
const ctaBtn = sectionEl.querySelector('#drop-cta-btn');
if (!canvas || !sitLine || !ctaBtn) return;
- const renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });
+ // WebGL can be unavailable (GPU blocklist, context budget exhausted,
+ // software rendering disabled) — degrade to the static section instead of
+ // crashing the whole page module.
+ let renderer;
+ try {
+ renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });
+ } catch (err) {
+ log.warn('[avatar-drop] WebGL unavailable, leaving section static:', err?.message);
+ canvas.remove();
+ return;
+ }
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.outputColorSpace = SRGBColorSpace;
renderer.toneMapping = ACESFilmicToneMapping;
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 0de2df2c4..44fb7374b 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -53,7 +53,6 @@ import { ensurePlayAccess } from './play-gate.js';
import { clearStoredPass, refreshPlayPass, loadStoredPass, storePass } from './play-auth.js';
import { PlaySystems } from './play-systems.js';
import { PlayOnboard } from './play-onboard.js';
-import { WorldHudSystem } from './hud/index.js';
import { log } from '../shared/log.js';
const WORLD_RADIUS = 58; // a touch inside the server's 60m clamp
@@ -1133,12 +1132,6 @@ export class CoinCommunities {
// Invalidate any in-flight enter() so a connect/avatar continuation that
// resolves after this teardown bails instead of rebuilding the world.
this._enterEpoch = (this._enterEpoch || 0) + 1;
- // Stand the W10 HUD down: close any open menu, hide the chrome, and forget the
- // per-world vitals so the next world doesn't pop a phantom money/damage cue.
- this.worldHud.closeMenus();
- this.hud.hide();
- this.camRig.reset();
- this._prevGold = null; this._prevHp = null;
// Tear voice down before the socket so our final "left voice" flag still
// sends, and peers' connections close cleanly.
clearTimeout(this._passRefreshTimer);
diff --git a/src/home-pose.js b/src/home-pose.js
index 467d032db..b5a9d5ec7 100644
--- a/src/home-pose.js
+++ b/src/home-pose.js
@@ -37,6 +37,7 @@ import { MannequinRig } from './pose-rig.js';
import { JOINT_LABELS, JOINT_AXIS_LABELS } from './pose-mannequin.js';
import { getPresetById } from './pose-presets.js';
import { encodePose } from './pose-share.js';
+import { log } from './shared/log.js';
// Curated spread of presets for the lite demo — one or two from each group so
// the chip row reads like a tour without overwhelming the homepage.
@@ -104,14 +105,24 @@ export function initHomePose(root) {
const canvas = el('canvas', { class: 'hp-canvas' });
stage.appendChild(canvas);
- const renderer = new WebGLRenderer({
- canvas,
- antialias: true,
- alpha: true,
- // Required so the snapshot can read the drawing buffer back as a PNG.
- preserveDrawingBuffer: true,
- powerPreference: 'high-performance',
- });
+ // WebGL can be unavailable (GPU blocklist, context budget exhausted,
+ // software rendering disabled) — surface a hint instead of crashing.
+ let renderer;
+ try {
+ renderer = new WebGLRenderer({
+ canvas,
+ antialias: true,
+ alpha: true,
+ // Required so the snapshot can read the drawing buffer back as a PNG.
+ preserveDrawingBuffer: true,
+ powerPreference: 'high-performance',
+ });
+ } catch (err) {
+ log.warn('[home-pose] WebGL unavailable, skipping pose demo:', err?.message);
+ canvas.remove();
+ if (hint) hint.textContent = 'Interactive 3D posing isn’t available on this device.';
+ return;
+ }
renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = PCFSoftShadowMap;
diff --git a/src/walk-embed-preview.js b/src/walk-embed-preview.js
index 2959879ca..cd9996836 100644
--- a/src/walk-embed-preview.js
+++ b/src/walk-embed-preview.js
@@ -63,7 +63,21 @@ export function initWalkPreview(container) {
if (!canvas || !joystickEl) return;
// ── Renderer ────────────────────────────────────────────────────
- const renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });
+ // WebGL can be unavailable (GPU blocklist, context budget exhausted,
+ // software rendering disabled) — tell the user instead of crashing.
+ let renderer;
+ try {
+ renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });
+ } catch (err) {
+ log.warn('[walk-preview] WebGL unavailable, skipping 3D preview:', err?.message);
+ const loadingEl = container.querySelector('[data-walk-loading]');
+ if (loadingEl) {
+ loadingEl.innerHTML = '';
+ loadingEl.append('3D preview isn’t available on this device.');
+ }
+ joystickEl.remove();
+ return;
+ }
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = PCFSoftShadowMap;
diff --git a/tests/api/cdn-object.test.js b/tests/api/cdn-object.test.js
new file mode 100644
index 000000000..3b3ab6371
--- /dev/null
+++ b/tests/api/cdn-object.test.js
@@ -0,0 +1,149 @@
+// Tests for /cdn/<key> → /api/cdn-object — the first-party R2 proxy that
+// replaced direct *.r2.dev URLs (Cloudflare rate-limits the public dev domain,
+// which surfaced as `failed to load img / model-viewer` client errors on
+// gallery pages).
+//
+// R2 is mocked at the client level; no network.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: async () => {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: async () => {} }));
+vi.mock('../../api/_lib/env.js', () => ({ env: { S3_BUCKET: 'test-bucket' } }));
+
+let sendImpl = async () => {
+ throw new Error('r2.send not stubbed for this test');
+};
+vi.mock('../../api/_lib/r2.js', () => ({
+ r2: { send: (...args) => sendImpl(...args) },
+}));
+
+import handler from '../../api/cdn-object.js';
+
+function makeBody() {
+ return { pipe: vi.fn(), on: vi.fn(), destroy: vi.fn() };
+}
+
+function makeReq({ key, method = 'GET', headers = {} } = {}) {
+ return { method, url: `/api/cdn-object?key=${key}`, headers, query: { key } };
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ body: undefined,
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this.body = body; this.writableEnded = true; this.headersSent = true; },
+ };
+}
+
+async function invoke(opts) {
+ const req = makeReq(opts);
+ const res = makeRes();
+ await handler(req, res);
+ return res;
+}
+
+beforeEach(() => {
+ sendImpl = async () => {
+ throw new Error('r2.send not stubbed for this test');
+ };
+});
+
+describe('GET /cdn/<key> — key validation', () => {
+ it('rejects a missing key', async () => {
+ const res = await invoke({ key: '' });
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('rejects path traversal', async () => {
+ const res = await invoke({ key: 'u/../../secrets.env' });
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('rejects keys with disallowed characters', async () => {
+ const res = await invoke({ key: 'u/owner/<script>.glb' });
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('rejects non-GET/HEAD methods', async () => {
+ const res = await invoke({ key: 'thumb/a.png', method: 'POST' });
+ expect(res.statusCode).toBe(405);
+ });
+});
+
+describe('GET /cdn/<key> — streaming', () => {
+ it('streams an object with passthrough metadata and long content-key caching', async () => {
+ const body = makeBody();
+ let gotCmd;
+ sendImpl = async (cmd) => {
+ gotCmd = cmd.input;
+ return { Body: body, ContentType: 'model/gltf-binary', ContentLength: 1234, ETag: '"abc"' };
+ };
+ const res = await invoke({ key: 'u/owner-1/draft-x/model.glb' });
+
+ expect(gotCmd.Bucket).toBe('test-bucket');
+ expect(gotCmd.Key).toBe('u/owner-1/draft-x/model.glb');
+ expect(res.statusCode).toBe(200);
+ expect(res.getHeader('content-type')).toBe('model/gltf-binary');
+ expect(res.getHeader('content-length')).toBe('1234');
+ expect(res.getHeader('etag')).toBe('"abc"');
+ expect(res.getHeader('cache-control')).toContain('s-maxage=2592000');
+ expect(body.pipe).toHaveBeenCalledWith(res);
+ });
+
+ it('uses a shorter, revalidating cache policy for regenerable thumbnails', async () => {
+ sendImpl = async () => ({ Body: makeBody(), ContentType: 'image/png', ContentLength: 10, ETag: '"t"' });
+ const res = await invoke({ key: 'thumb/abcd-1234.png' });
+ expect(res.getHeader('cache-control')).toContain('max-age=3600');
+ expect(res.getHeader('cache-control')).toContain('s-maxage=86400');
+ });
+
+ it('derives content-type from the extension when R2 stored octet-stream', async () => {
+ sendImpl = async () => ({ Body: makeBody(), ContentType: 'application/octet-stream', ContentLength: 10 });
+ const res = await invoke({ key: 'thumb/abcd.png' });
+ expect(res.getHeader('content-type')).toBe('image/png');
+ });
+
+ it('answers HEAD with headers only and releases the body stream', async () => {
+ const body = makeBody();
+ sendImpl = async () => ({ Body: body, ContentType: 'image/png', ContentLength: 10, ETag: '"h"' });
+ const res = await invoke({ key: 'thumb/abcd.png', method: 'HEAD' });
+ expect(res.statusCode).toBe(200);
+ expect(res.writableEnded).toBe(true);
+ expect(body.pipe).not.toHaveBeenCalled();
+ expect(body.destroy).toHaveBeenCalled();
+ });
+});
+
+describe('GET /cdn/<key> — error mapping', () => {
+ it('maps NoSuchKey to 404', async () => {
+ sendImpl = async () => {
+ throw Object.assign(new Error('no such key'), { Code: 'NoSuchKey' });
+ };
+ const res = await invoke({ key: 'u/owner/gone.glb' });
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('returns 304 when the client ETag still matches', async () => {
+ sendImpl = async () => {
+ throw Object.assign(new Error('not modified'), { $metadata: { httpStatusCode: 304 } });
+ };
+ const res = await invoke({ key: 'thumb/abcd.png', headers: { 'if-none-match': '"abc"' } });
+ expect(res.statusCode).toBe(304);
+ expect(res.getHeader('etag')).toBe('"abc"');
+ });
+
+ it('maps other upstream failures to 502', async () => {
+ sendImpl = async () => {
+ throw new Error('connection reset');
+ };
+ const res = await invoke({ key: 'u/owner/a.glb' });
+ expect(res.statusCode).toBe(502);
+ });
+});
diff --git a/tests/api/token-market-circuit.test.js b/tests/api/token-market-circuit.test.js
new file mode 100644
index 000000000..382f5680d
--- /dev/null
+++ b/tests/api/token-market-circuit.test.js
@@ -0,0 +1,98 @@
+// Circuit-breaker tests for api/_lib/market/token-market.js.
+//
+// When a source reports an exhausted quota (Birdeye's "Compute units usage
+// limit exceeded") or rate-limits us, the failover loop must stop calling it
+// for the cooldown window instead of burning a doomed upstream request on
+// every read. Fetch is fully mocked; no network.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+let fetchCalls = [];
+let fetchResponses = [];
+vi.stubGlobal('fetch', (url) => {
+ fetchCalls.push(String(url));
+ const resp = fetchResponses.shift();
+ if (!resp) throw new Error(`Unexpected fetch: ${url}`);
+ return Promise.resolve({
+ ok: resp.ok ?? true,
+ status: resp.status ?? 200,
+ json: async () => resp.body,
+ text: async () => (typeof resp.body === 'string' ? resp.body : JSON.stringify(resp.body)),
+ });
+});
+
+import { fetchTokenMarketData, __resetMarketCache } from '../../api/_lib/market/token-market.js';
+
+const MINT = 'THREEsynthetic111111111111111111111111111111';
+
+const QUOTA_BODY = '{"success":false,"message":"Compute units usage limit exceeded"}';
+const DEX_OK = {
+ pairs: [
+ { priceUsd: '0.5', marketCap: 500000, liquidity: { usd: 100000 }, volume: { h24: 5000 }, priceChange: { h24: 1.5 } },
+ ],
+};
+
+beforeEach(() => {
+ fetchCalls = [];
+ fetchResponses = [];
+ process.env.BIRDEYE_API_KEY = 'test-key';
+ __resetMarketCache();
+});
+
+afterEach(() => {
+ delete process.env.BIRDEYE_API_KEY;
+ if (fetchResponses.length) {
+ throw new Error(`Test left ${fetchResponses.length} unconsumed fetch mock(s)`);
+ }
+});
+
+describe('token-market source circuit breaker', () => {
+ it('skips Birdeye on subsequent reads after a quota-exhausted error', async () => {
+ // Read 1: Birdeye rejects with the quota error, DexScreener answers.
+ fetchResponses = [
+ { ok: false, status: 400, body: QUOTA_BODY },
+ { body: DEX_OK },
+ ];
+ const first = await fetchTokenMarketData(MINT, { fresh: true });
+ expect(first.source).toBe('dexscreener');
+ expect(fetchCalls.some((u) => u.includes('birdeye'))).toBe(true);
+
+ // Read 2 (cache bypassed): Birdeye is under cooldown — the only upstream
+ // call must be DexScreener.
+ fetchCalls = [];
+ fetchResponses = [{ body: DEX_OK }];
+ const second = await fetchTokenMarketData(MINT, { fresh: true });
+ expect(second.source).toBe('dexscreener');
+ expect(fetchCalls).toHaveLength(1);
+ expect(fetchCalls[0]).toContain('dexscreener');
+ });
+
+ it('keeps calling Birdeye after a non-quota failure (no false trips)', async () => {
+ fetchResponses = [
+ { ok: false, status: 500, body: 'internal error' },
+ { body: DEX_OK },
+ ];
+ await fetchTokenMarketData(MINT, { fresh: true });
+
+ fetchCalls = [];
+ fetchResponses = [
+ { ok: false, status: 500, body: 'internal error' },
+ { body: DEX_OK },
+ ];
+ await fetchTokenMarketData(MINT, { fresh: true });
+ expect(fetchCalls.some((u) => u.includes('birdeye'))).toBe(true);
+ });
+
+ it('trips the breaker on a 429 rate limit as well', async () => {
+ fetchResponses = [
+ { ok: false, status: 429, body: 'rate limited' },
+ { body: DEX_OK },
+ ];
+ await fetchTokenMarketData(MINT, { fresh: true });
+
+ fetchCalls = [];
+ fetchResponses = [{ body: DEX_OK }];
+ await fetchTokenMarketData(MINT, { fresh: true });
+ expect(fetchCalls.some((u) => u.includes('birdeye'))).toBe(false);
+ });
+});
diff --git a/vercel.json b/vercel.json
index c0e2b5a23..676de2580 100644
--- a/vercel.json
+++ b/vercel.json
@@ -23,6 +23,10 @@
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 60
},
+ "api/x402-pay.js": {
+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
+ "maxDuration": 60
+ },
"api/widgets/[id]/knowledge-process.js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 300
@@ -95,6 +99,10 @@
},
"continue": true
},
+ {
+ "src": "/cdn/(.+)",
+ "dest": "/api/cdn-object?key=$1"
+ },
{
"src": "/agent-exchange",
"dest": "/agent-exchange.html"