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(api): validate inputs, return typed error envelopes, and stop cached responses leaking across request headers

nirholas1c81d3eb9348
diff --git a/api/3d/generate.js b/api/3d/generate.js
index 49655abf2..52963160a 100644
--- a/api/3d/generate.js
+++ b/api/3d/generate.js
@@ -20,6 +20,7 @@
// → 200 { status:'pending', retryAfter } (still generating — wait retryAfter s, then poll)
// → 200 { status:'done', glbUrl, viewerUrl, arUrl } (GLB ready)
// → 200 { status:'error', error } (upstream failed; free = no charge)
+// → 503 { error:'not_configured' } (no 3D lane here; polling can never finish)
//
// Every pending/queued response carries a `retryAfter` (seconds) poll-cadence hint
// — ETA-derived on submit, echoed on each poll — and sets the standard Retry-After
@@ -356,6 +357,20 @@ async function poll(req, res, jobId, title) {
message: data?.message || 'Unknown or malformed job id.',
});
}
+ // A deployment that cannot serve this job AT ALL (the lane behind the handle is
+ // unconfigured here) is not the transient blip the pending fallback below is
+ // for: answering 'pending' would hand the agent a poll loop that can never
+ // finish. Surface the same designed not_configured the submit path returns.
+ if (
+ (upstream.status === 503 || upstream.status === 501) &&
+ (data?.error === 'unconfigured' || data?.error === 'backend_unconfigured')
+ ) {
+ return json(res, 503, {
+ error: 'not_configured',
+ message:
+ 'Free text-to-3D is not configured on this deployment, so this job cannot be polled here.',
+ });
+ }
if (upstream.status === 429) {
const retryAfter = Number(data?.retry_after) || 5;
res.setHeader('retry-after', String(retryAfter));
diff --git a/api/3d/studio.js b/api/3d/studio.js
index 1ed066939..4e948434a 100644
--- a/api/3d/studio.js
+++ b/api/3d/studio.js
@@ -307,6 +307,21 @@ async function poll(req, res, jobId, title) {
if (upstream.status === 400) {
return json(res, 400, { error: 'invalid_job', message: data?.message || 'Unknown or malformed job id.' });
}
+ // A deployment that cannot serve this job at all (the lane behind the handle is
+ // unconfigured here) is not the transient blip the pending fallback below is
+ // for: 'pending' would leave the GPT polling a job that can never finish. The
+ // published Actions contract has no 503 on this operation, so answer with its
+ // documented terminal state instead.
+ if (
+ (upstream.status === 503 || upstream.status === 501) &&
+ (data?.error === 'unconfigured' || data?.error === 'backend_unconfigured')
+ ) {
+ return json(res, 200, {
+ status: 'error',
+ job: jobId,
+ error: '3D generation is temporarily unavailable, so this job cannot be checked right now.',
+ });
+ }
if (upstream.status === 429) {
const retryAfter = Number(data?.retry_after) || 5;
res.setHeader('retry-after', String(retryAfter));
diff --git a/api/_lib/autopilot.js b/api/_lib/autopilot.js
index ca32174f7..1ac62ab42 100644
--- a/api/_lib/autopilot.js
+++ b/api/_lib/autopilot.js
@@ -38,6 +38,34 @@ const MAX_DAILY_SOL = 1000; // sane ceiling on the daily autonomous SOL spend ca
export const AUTOPILOT_ACTION_KINDS = ['create_alert', 'briefing', 'wallet_transfer'];
+// The actions /api/autopilot/proposals accepts on a POST. Kept beside the engine
+// so the handler's allowlist and its error message can never drift apart.
+export const AUTOPILOT_PROPOSAL_ACTIONS = Object.freeze([
+ 'generate', 'dryrun', 'execute', 'dismiss', 'undo', 'adjust',
+]);
+
+// ── Request-input guards for the autopilot read surfaces ─────────────────────
+// Every autopilot endpoint takes the same two user-supplied paging inputs. Both
+// reach Postgres directly, which rejects a negative LIMIT and an out-of-range
+// bigint cursor with an error that would surface to the caller as a 500. Clamp
+// and validate them here, at the boundary, so bad input reads as bad input.
+
+const MAX_BIGINT = 9223372036854775807n;
+
+export function pageLimit(raw, { fallback = 50, max = 200 } = {}) {
+ const n = Math.trunc(Number(raw));
+ if (!Number.isFinite(n) || n <= 0) return fallback;
+ return Math.min(n, max);
+}
+
+// agent_actions.id is a bigserial, so the cursor is an opaque decimal string.
+export function parseCursor(raw) {
+ if (raw == null || raw === '') return { ok: true, cursor: null };
+ if (typeof raw !== 'string' || !/^\d{1,19}$/.test(raw)) return { ok: false, reason: 'cursor must be numeric' };
+ if (BigInt(raw) > MAX_BIGINT) return { ok: false, reason: 'cursor out of range' };
+ return { ok: true, cursor: raw };
+}
+
// Action types written to the signed agent_actions log, one per executable kind.
const ACTION_TYPE = {
create_alert: 'autopilot.alert.created',
diff --git a/api/_lib/clash-store.js b/api/_lib/clash-store.js
index 325a222e0..e27d905ae 100644
--- a/api/_lib/clash-store.js
+++ b/api/_lib/clash-store.js
@@ -44,6 +44,7 @@ const K = {
members: (epoch, mint) => `clash:mem:${epoch}:${mint}`, // ZSET wallet → power
wallet: (epoch, mint, wallet) => `clash:w:${epoch}:${mint}:${wallet}`, // INT cap counter
momentum: (mint) => `clash:mom:${mint}`, // JSON cached factor
+ price: (mint) => `clash:px:${mint}`, // JSON { spot, at, base, baseAt }
settled: (epoch) => `clash:settled:${epoch}`, // marker
record: 'clash:record', // HASH mint → JSON {w,l,battles,power}
};
@@ -160,6 +161,21 @@ export async function factionPowers(epoch) {
return out;
}
+/**
+ * One faction's power this round. The rally path echoes this back on every tap
+ * flush, so it reads a single score rather than ranging the whole round ZSET.
+ */
+export async function factionPower(epoch, mint) {
+ if (redis) {
+ try {
+ return Number((await redis.zscore(K.factions(epoch), mint)) || 0);
+ } catch (err) {
+ redisDegraded(err);
+ }
+ }
+ return Number(memZ(K.factions(epoch)).get(mint) || 0);
+}
+
/** Top soldiers for a faction this round: [{ wallet, power }] descending. */
export async function topSoldiers({ epoch, mint, limit = 10 }) {
if (redis) {
@@ -206,6 +222,33 @@ export async function setMomentum(mint, factor, ttlS = 120) {
mem.s.set(K.momentum(mint), { value: factor, exp: Date.now() + ttlS * 1000 });
}
+// ─── Price snapshot cache ────────────────────────────────────────────────────
+// Shared across instances so a faction is priced upstream once per spot TTL for
+// the whole fleet, not once per poll per viewer.
+
+export async function getPrice(mint) {
+ if (redis) {
+ try {
+ return parsePrice(await redis.get(K.price(mint)));
+ } catch (err) {
+ redisDegraded(err);
+ }
+ }
+ return parsePrice(memValid(K.price(mint)));
+}
+
+export async function setPrice(mint, snap, ttlS) {
+ const value = JSON.stringify(snap);
+ if (redis) {
+ try {
+ return void (await redis.set(K.price(mint), value, { ex: ttlS }));
+ } catch (err) {
+ redisDegraded(err);
+ }
+ }
+ mem.s.set(K.price(mint), { value, exp: Date.now() + ttlS * 1000 });
+}
+
// ─── All-time war record + lazy settlement ───────────────────────────────────
/** All-time records for a set of mints: mint → { w, l, battles, power }. */
@@ -328,6 +371,22 @@ function parseRecord(raw) {
}
}
+function parsePrice(raw) {
+ if (!raw) return null;
+ try {
+ const v = typeof raw === 'string' ? JSON.parse(raw) : raw;
+ if (!v || typeof v !== 'object') return null;
+ return {
+ spot: Number(v.spot) || 0,
+ at: Number(v.at) || 0,
+ base: Number(v.base) || 0,
+ baseAt: Number(v.baseAt) || 0,
+ };
+ } catch {
+ return null;
+ }
+}
+
// Upstash zrange withScores returns a flat [member, score, member, score, …].
function zflatToMap(flat) {
const out = {};
diff --git a/api/_lib/clash.js b/api/_lib/clash.js
index 4e98d3c1b..b59f57924 100644
--- a/api/_lib/clash.js
+++ b/api/_lib/clash.js
@@ -200,6 +200,54 @@ export function momentumFactor(s = {}) {
return Math.round(factor * 1000) / 1000;
}
+// ─── Price snapshot (spot cache + 24h baseline) ──────────────────────────────
+
+// The state endpoint is polled every few seconds by every open Clash tab, and
+// each poll would otherwise price every faction upstream. So a faction's spot
+// price is cached and only re-fetched once it goes stale.
+export const PRICE_SPOT_TTL_MS = 60_000;
+
+// The baseline a faction's move is measured against. Rolled forward once a day,
+// so `priceChangePct` reports a genuine ~24h move built from our own samples
+// rather than a number no upstream gives us per-mint.
+export const PRICE_BASELINE_MS = 24 * 3_600_000;
+
+/** True when a stored snapshot is missing or its spot price has aged out. */
+export function priceIsStale(snap, now) {
+ const at = Number(snap?.at) || 0;
+ return !(at > 0) || now - at >= PRICE_SPOT_TTL_MS;
+}
+
+/**
+ * Fold a freshly fetched spot price into a faction's stored snapshot. The
+ * baseline is seeded on the first priced sample and rolled forward once it is
+ * older than PRICE_BASELINE_MS, so the pair always spans at most a day.
+ *
+ * @param {{ spot?: number, at?: number, base?: number, baseAt?: number }|null} prev
+ * @param {number} spot upstream price, 0 when nothing could price the mint
+ * @param {number} now
+ */
+export function rollPrice(prev, spot, now) {
+ const price = Math.max(0, Number(spot) || 0);
+ const base = Math.max(0, Number(prev?.base) || 0);
+ const baseAt = Number(prev?.baseAt) || 0;
+ const rebase = price > 0 && (base <= 0 || baseAt <= 0 || now - baseAt >= PRICE_BASELINE_MS);
+ return {
+ spot: price,
+ at: now,
+ base: rebase ? price : base,
+ baseAt: rebase ? now : baseAt,
+ };
+}
+
+/** Percent move of a snapshot's spot against its baseline, or null if unknown. */
+export function priceChangePct(snap) {
+ const spot = Number(snap?.spot) || 0;
+ const base = Number(snap?.base) || 0;
+ if (spot <= 0 || base <= 0) return null;
+ return ((spot - base) / base) * 100;
+}
+
// ─── Enlist challenge (stateless) ────────────────────────────────────────────
/**
diff --git a/api/_lib/coin-communities.js b/api/_lib/coin-communities.js
index 36b4159d4..34a8cd43e 100644
--- a/api/_lib/coin-communities.js
+++ b/api/_lib/coin-communities.js
@@ -57,6 +57,15 @@ export function isValidToken(token) {
return typeof token === 'string' && (BASE58_RE.test(token) || EVM_RE.test(token));
}
+/**
+ * Solana-only variant, for surfaces backed by Solana-only machinery: pump.fun
+ * creator lookups, SPL balance reads, holder passes. Those cannot answer for an
+ * EVM-chain world, so they check this instead of isValidToken and say so.
+ */
+export function isSolanaToken(token) {
+ return typeof token === 'string' && BASE58_RE.test(token);
+}
+
class UnconfiguredError extends Error {
constructor() {
super('CoinCommunities is not configured (set CC_API_KEY)');
@@ -160,6 +169,35 @@ export function userAuthHeaders(req) {
return token ? { Authorization: `Bearer ${token}` } : null;
}
+/**
+ * True when the request carries any usable session cookie, access or refresh.
+ * Handlers that gate on "is this user signed in?" must use this rather than
+ * `userAuthHeaders(req)`: the access-token cookie expires out of the browser
+ * after 1h, so an hours-old but perfectly valid session has only `cc_rt` left
+ * and a bare `userAuthHeaders` check would call that user a stranger.
+ */
+export function hasUserSession(req) {
+ return Boolean(userToken(req) || userRefreshToken(req));
+}
+
+/**
+ * Mint a fresh access token from the refresh cookie and persist it. Returns the
+ * new bearer headers, or null when there is nothing to refresh with (or the
+ * refresh token itself is dead, in which case the stale cookies are cleared).
+ */
+async function refreshSession(req, res) {
+ const refreshToken = userRefreshToken(req);
+ if (!refreshToken || !isConfigured()) return null;
+
+ const { data, error } = await cc().refreshToken({ body: { refreshToken } });
+ if (error || !data?.accessToken) {
+ clearUserSession(res);
+ return null;
+ }
+ setUserSession(res, data);
+ return { Authorization: `Bearer ${data.accessToken}` };
+}
+
/**
* Runs an authenticated CoinCommunities API call, transparently refreshing the
* session on a 401 and retrying once before giving up. The `cc_at` access-token
@@ -176,28 +214,26 @@ export function userAuthHeaders(req) {
*/
export async function withAuthRefresh(req, res, call) {
const headers = userAuthHeaders(req);
- if (!headers) return { data: null, error: null, headers: null };
+ if (!headers) {
+ // No access-token cookie at all. That is the *normal* state one hour after
+ // sign-in, since `cc_at` and the JWT inside it share a 1h lifetime: the
+ // browser drops the cookie and the request arrives carrying only `cc_rt`.
+ // Refresh from it before concluding the caller is signed out, otherwise the
+ // 30-day refresh token is never once used and every session dies at 1h.
+ const fresh = await refreshSession(req, res);
+ if (!fresh) return { data: null, error: null, headers: null };
+ const result = await call(fresh);
+ return { ...result, headers: fresh };
+ }
let result = await call(headers);
if (result?.error?.statusCode !== 401) return { ...result, headers };
- const refreshToken = userRefreshToken(req);
- if (!refreshToken) {
- clearUserSession(res);
- return { ...result, headers: null };
- }
-
- const api = cc();
- const { data: refreshed, error: refreshErr } = await api.refreshToken({ body: { refreshToken } });
- if (refreshErr || !refreshed?.accessToken) {
- clearUserSession(res);
- return { ...result, headers: null };
- }
+ const refreshed = await refreshSession(req, res);
+ if (!refreshed) return { ...result, headers: null };
- setUserSession(res, refreshed);
- const freshHeaders = { Authorization: `Bearer ${refreshed.accessToken}` };
- result = await call(freshHeaders);
- return { ...result, headers: freshHeaders };
+ result = await call(refreshed);
+ return { ...result, headers: refreshed };
}
/**
diff --git a/api/_lib/fetch-model.js b/api/_lib/fetch-model.js
index 84b4c0d1c..897b1d25a 100644
--- a/api/_lib/fetch-model.js
+++ b/api/_lib/fetch-model.js
@@ -24,8 +24,18 @@ export class FetchModelError extends Error {
// Map a shared SsrfError to the FetchModelError shape callers already expect, so
// existing { code: 'private_address' } / 'scheme_not_allowed' assertions hold.
+// Callers branch on the CLASS, not just the code, to tell a caller-fault URL
+// (400: blocked, private, malformed) from an upstream failure (502), so an
+// SsrfError that escapes this module raw gets misfiled as an upstream fault. Two
+// escape routes exist beyond the initial URL validation: the per-hop DNS
+// resolution inside the redirect loop, and the pinned agent refusing a rebound
+// address at connect time, which undici surfaces as a TypeError wrapping the
+// original in `cause`.
function asFetchModelError(err) {
if (err instanceof SsrfError) return new FetchModelError(err.message, err.code);
+ if (err?.cause instanceof SsrfError) {
+ return new FetchModelError(err.cause.message, err.cause.code);
+ }
return err;
}
@@ -137,6 +147,11 @@ export async function fetchModel(rawUrl, opts = {}) {
filename,
};
}
+ } catch (err) {
+ // Normalize every SSRF refusal raised inside the loop (per-hop resolution,
+ // connect-time pin rejection) to FetchModelError. Anything else (an abort on
+ // timeout, a plain network TypeError) passes through untouched.
+ throw asFetchModelError(err);
} finally {
clearTimeout(timer);
if (agent) await agent.close().catch(() => {});
diff --git a/api/_lib/gmgn-feed.js b/api/_lib/gmgn-feed.js
index a360404fd..7257907b5 100644
--- a/api/_lib/gmgn-feed.js
+++ b/api/_lib/gmgn-feed.js
@@ -114,6 +114,47 @@ export function gmgnSmartMoneyRank(opts = {}) {
return fetchRank(opts);
}
+/**
+ * One-shot smart-money snapshot: the same live rank the streaming poller reads,
+ * with the same GMGN → DexScreener failover, the same minSmartBuys floor, and the
+ * same normalized item shape the SSE lane emits. Lets a plain JSON client (or a
+ * server that cannot hold an SSE connection open) read the board without opening
+ * a poll. Never throws; a dead upstream returns { ok: false, items: [] }.
+ *
+ * @param {{ chain?: string, interval?: string, minSmartBuys?: number, limit?: number }} opts
+ * @returns {Promise<{ ok: boolean, source: string|null, items: object[], status?: number, error?: string }>}
+ */
+export async function gmgnSmartMoneySnapshot({
+ chain = 'sol',
+ interval = '1h',
+ minSmartBuys = 2,
+ limit = 25,
+} = {}) {
+ let result = await fetchRank({ chain, interval });
+ let source = 'gmgn';
+ // A 403 is Cloudflare refusing this egress IP, not an outage: fall back to the
+ // DexScreener board exactly as the poller does.
+ if (!result.ok && result.status === 403) {
+ result = await fetchDexScreener({ chain });
+ source = 'dexscreener';
+ }
+ if (!result.ok) {
+ return { ok: false, source: null, items: [], status: result.status, error: result.error };
+ }
+ source = result.source || source;
+ const items = [];
+ for (const item of result.rank) {
+ if (!item.address) continue;
+ const smartCount = Number(item.smart_buy_24h ?? item.smart_buy ?? 0);
+ if (smartCount < minSmartBuys) continue;
+ // prevCount is 0 for a one-shot read: there is no prior snapshot to diff
+ // against, so `smart_buy_delta` reports the full count and `is_new` is true.
+ items.push(normalize(item, smartCount, 0, chain, interval, source));
+ if (items.length >= limit) break;
+ }
+ return { ok: true, source, items };
+}
+
let _pollerId = 0;
// Map<pollerId, Map<address, prevItem>>
const _snapshots = new Map();
diff --git a/api/_lib/http.js b/api/_lib/http.js
index 65026f81f..f0afcfa93 100644
--- a/api/_lib/http.js
+++ b/api/_lib/http.js
@@ -463,6 +463,26 @@ const IBM_ORIGIN = /^https:\/\/([a-z0-9-]+\.)*ibm\.com$/i;
// seismic.com.evil.example can't match.
const SEISMIC_ORIGIN = /^https:\/\/([a-z0-9-]+\.)*seismic\.com$/i;
+// Add fields to the response's `Vary` header without dropping what is already
+// there. `res.setHeader('vary', …)` REPLACES, so a handler that varies on Cookie
+// would otherwise erase the `vary: origin` cors() just set (and vice versa), and
+// a shared cache would then serve one origin's CORS headers to another. Use this
+// on any public-cacheable read whose body changes with a request header.
+export function varyOn(res, ...fields) {
+ const current = String(res.getHeader?.('vary') || '')
+ .split(',')
+ .map((f) => f.trim())
+ .filter(Boolean);
+ const seen = new Set(current.map((f) => f.toLowerCase()));
+ for (const field of fields) {
+ if (!seen.has(field.toLowerCase())) {
+ seen.add(field.toLowerCase());
+ current.push(field);
+ }
+ }
+ res.setHeader('vary', current.join(', '));
+}
+
export function cors(
req,
res,
@@ -717,7 +737,9 @@ export function method(req, res, allowed) {
// set req.method to here.
if (effective === 'GET' && m === 'HEAD') req.method = 'GET';
if (!allowed.includes(effective)) {
- const advertised = allowed.includes('GET') ? [...allowed, 'HEAD'] : allowed;
+ // Dedupe: a handler that already lists HEAD alongside GET would otherwise
+ // advertise `Allow: GET, HEAD, HEAD`.
+ const advertised = allowed.includes('GET') ? [...new Set([...allowed, 'HEAD'])] : allowed;
res.setHeader('allow', advertised.join(', '));
error(res, 405, 'method_not_allowed', `method ${m} not allowed`);
return false;
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index f77d0bcbe..a23340b44 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -491,6 +491,15 @@ export const limits = {
// 40 per 5 min per IP comfortably covers rapid rerolling, well under abuse.
surpriseIp: (ip) =>
getLimiter('avatar:surprise:ip', { limit: 40, window: '5 m', local: true }).limit(ip),
+ // Gallery view tracking (/api/avatars/view). Deliberately a dedupe rather than
+ // a throttle: one counted view per (IP, avatar) per 30 minutes, so a reader
+ // who reopens a card ten times moves view_count by one. Keyed on
+ // `${ip}:${avatarId}` so a browsing session can still count a view on every
+ // distinct avatar it opens. NOT local: with several Cloud Run instances a
+ // per-instance counter would let the same viewer count once per instance,
+ // which is exactly the inflation this bucket exists to stop.
+ avatarViewIp: (ipAndAvatar) =>
+ getLimiter('avatar:view:ip', { limit: 1, window: '30 m' }).limit(ipAndAvatar),
// Webcam sign-language transcription (/api/asl-recognition). Each call runs
// a sub-second CPU inference on the worker; 30 per 5 min per IP covers an
// active signed conversation while stopping scripted hammering.
@@ -583,6 +592,13 @@ export const limits = {
// few reshares of the same moment, tight enough that scripting the upload path
// can't be used as free image-hosting.
irlShareIp: (ip) => getLimiter('irl:share:ip', { limit: 10, window: '10 m' }).limit(ip),
+ // /club viewer-presence heartbeat (api/club/presence.js). Every open tab posts
+ // once per 15s, so a handful of tabs behind one address sits near 20/min; 120
+ // leaves a shared NAT egress plenty of room while capping how fast a script can
+ // churn distinct session ids at the counter. `local` on purpose: the counter it
+ // guards is per-instance in-memory state, so a per-instance bucket is exactly
+ // the right scope and costs zero Redis commands on a page that polls forever.
+ clubPresenceIp: (ip) => getLimiter('club:presence:ip', { limit: 120, window: '1 m', local: true }).limit(ip),
// Living Stages tip recording (api/stage/tip.js). Each call carries a real
// on-chain settlement signature and is deduped per signature, so the limiter
// only blunts a forger spamming distinct fake signatures at the recorder — a
diff --git a/api/_lib/render-clip.js b/api/_lib/render-clip.js
index e6071daeb..8b7782774 100644
--- a/api/_lib/render-clip.js
+++ b/api/_lib/render-clip.js
@@ -57,17 +57,31 @@ 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.
+function scriptJson(value) {
+ return JSON.stringify(value === undefined ? null : value)
+ .replace(/</g, '\\u003c')
+ .replace(/>/g, '\\u003e')
+ .replace(/\u2028/g, '\\u2028')
+ .replace(/\u2029/g, '\\u2029');
+}
+
function viewerHtml({ glbBase64, width, height, background, pose, cameraOrbit, expression }) {
- const bg = background === 'transparent' ? 'null' : JSON.stringify(background || '#0a0a0a');
- const poseJson = pose ? JSON.stringify(pose.pose) : 'null';
- const orbitJson = JSON.stringify(cameraOrbit || { theta: 0, phi: 80, radius: null });
- const expressionJson = JSON.stringify(expression || null);
+ const bg = background === 'transparent' ? 'null' : scriptJson(background || '#0a0a0a');
+ const poseJson = pose ? scriptJson(pose.pose) : 'null';
+ const orbitJson = scriptJson(cameraOrbit || { theta: 0, phi: 80, radius: null });
+ const expressionJson = scriptJson(expression || null);
return `<!doctype html>
<html><head><meta charset="utf-8" />
<style>html,body{margin:0;padding:0;background:transparent;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/x402/a2a-server.js b/api/_lib/x402/a2a-server.js
index a754212ed..10c9b650c 100644
--- a/api/_lib/x402/a2a-server.js
+++ b/api/_lib/x402/a2a-server.js
@@ -30,6 +30,7 @@
import { randomUUID } from 'node:crypto';
import { env } from '../env.js';
+import { readBody } from '../http.js';
import {
BUILDER_CODE,
NETWORK_BASE_MAINNET,
diff --git a/api/actions/avatar-icon.js b/api/actions/avatar-icon.js
index 48e4188bd..0f85e5d26 100644
--- a/api/actions/avatar-icon.js
+++ b/api/actions/avatar-icon.js
@@ -3,25 +3,48 @@
// a live three.ws avatar portrait in the Blink card instead of a flat image.
//
// GET /api/actions/avatar-icon
-// ?avatar=default|<avatarId> (default: "default")
-// ?pose=<posePresetId> (optional)
-// ?bg=<css-color> (default: "#0a0a0a")
+// ?avatar=default|<avatarUuid> (default: "default")
+// ?pose=<posePresetId> (optional)
+// ?bg=<css-color> (default: "#0a0a0a")
import { cors, wrap, error } from '../_lib/http.js';
import { env } from '../_lib/env.js';
import { renderClip } from '../_lib/render-clip.js';
import { getAvatar } from '../_lib/avatars.js';
+import { isUuid } from '../_lib/validate.js';
export const maxDuration = 30;
+// Every render boots chromium and pulls a GLB, so each param is checked against
+// the shape it is actually allowed to take before any of that starts. `bg` in
+// particular is embedded in the render page's script block: three.js accepts
+// hex, rgb()/rgba(), hsl()/hsla(), and CSS named colors, and nothing outside
+// that set is a color a caller could have legitimately meant.
+const CSS_COLOR_RE =
+ /^(?:#[0-9a-f]{3,8}|rgba?\([\d.,%\s/]{5,64}\)|hsla?\([\d.,%\s/a-z]{5,64}\)|[a-z]{3,20})$/i;
+const POSE_ID_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
+ return error(res, 405, 'method_not_allowed', 'GET required');
+ }
const url = new URL(req.url, 'http://x');
const avatarParam = url.searchParams.get('avatar') || 'default';
const posePresetId = url.searchParams.get('pose') || null;
const bg = url.searchParams.get('bg') || '#0a0a0a';
+ if (avatarParam !== 'default' && !isUuid(avatarParam)) {
+ return error(res, 400, 'bad_request', 'avatar must be "default" or an avatar id');
+ }
+ if (posePresetId !== null && !POSE_ID_RE.test(posePresetId)) {
+ return error(res, 400, 'bad_request', 'pose must be a pose preset id');
+ }
+ if (bg !== 'transparent' && !CSS_COLOR_RE.test(bg)) {
+ return error(res, 400, 'bad_request', 'bg must be a CSS color');
+ }
+
const origin = env.APP_ORIGIN;
let glbUrl;
@@ -46,7 +69,11 @@ export default wrap(async (req, res) => {
expression: { mouthSmileLeft: 0.4, mouthSmileRight: 0.4 },
});
} catch (err) {
- return error(res, 502, 'render_failed', err?.message || 'render failed');
+ // renderClip tags its failures (400 unfetchable GLB, 413 oversized, 502
+ // chromium/three.js error). Passing the tag through tells the caller
+ // whether the avatar or the renderer is at fault.
+ const status = Number(err?.status) >= 400 && Number(err?.status) < 600 ? Number(err.status) : 502;
+ return error(res, status, err?.code || 'render_failed', err?.message || 'render failed');
}
res.statusCode = 200;
@@ -57,5 +84,6 @@ export default wrap(async (req, res) => {
'public, max-age=86400, s-maxage=604800, stale-while-revalidate=86400',
);
res.setHeader('access-control-allow-origin', '*');
+ if (req.method === 'HEAD') return res.end();
res.end(result.png);
});
diff --git a/api/actions/avatar.js b/api/actions/avatar.js
index f2518e660..cd0634e47 100644
--- a/api/actions/avatar.js
+++ b/api/actions/avatar.js
@@ -13,6 +13,8 @@
import { cors, json, error, readJson, wrap } from '../_lib/http.js';
import { solanaConnection } from '../_lib/solana/connection.js';
import { env } from '../_lib/env.js';
+import { getAvatar } from '../_lib/avatars.js';
+import { isUuid } from '../_lib/validate.js';
export const maxDuration = 10;
@@ -20,9 +22,12 @@ const MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';
const SOLANA_MAINNET_GENESIS = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
const ACTION_VERSION = '2.1.3';
-function setActionHeaders(res) {
+function setActionVersionHeaders(res) {
res.setHeader('x-action-version', ACTION_VERSION);
res.setHeader('x-blockchain-ids', SOLANA_MAINNET_GENESIS);
+}
+
+function exposeActionHeaders(res) {
// Extend the expose list set by cors() to include action-specific headers.
res.setHeader(
'access-control-expose-headers',
@@ -30,27 +35,58 @@ function setActionHeaders(res) {
);
}
+// Blink clients render ActionError.message, not our standard error envelope, so
+// action errors carry both shapes.
+function actionError(res, status, code, message) {
+ return error(res, status, code, message, { message });
+}
+
export default wrap(async (req, res) => {
+ // The Actions spec expects the version headers on every response from an
+ // action endpoint, the OPTIONS preflight included, so they are set before
+ // cors() can short-circuit it.
+ setActionVersionHeaders(res);
if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+ exposeActionHeaders(res);
+
+ if (req.method !== 'GET' && req.method !== 'POST') {
+ return actionError(res, 405, 'method_not_allowed', 'GET or POST required');
+ }
const url = new URL(req.url, 'http://x');
const avatarId = url.searchParams.get('avatar') || 'default';
+ // The id is echoed into the card and written into the on-chain memo, so only
+ // the two forms that can name a real avatar are accepted. Without this an
+ // arbitrary string rides into a transaction that presents itself as a
+ // three.ws claim.
+ if (avatarId !== 'default' && !isUuid(avatarId)) {
+ return actionError(res, 400, 'bad_request', 'avatar must be "default" or an avatar id');
+ }
+
+ // A public Blink resolves as an anonymous viewer would: getAvatar returns
+ // null for a private or deleted avatar, which is a 404 here rather than a
+ // card advertising something the claimer cannot see.
+ let avatar = null;
+ if (avatarId !== 'default') {
+ avatar = await getAvatar({ id: avatarId }).catch(() => null);
+ if (!avatar) return actionError(res, 404, 'not_found', 'That avatar is not available.');
+ }
- if (req.method === 'GET') return handleGet(req, res, avatarId);
- if (req.method === 'POST') return handlePost(req, res, avatarId);
- return error(res, 405, 'method_not_allowed', 'GET or POST required');
+ if (req.method === 'GET') return handleGet(res, avatarId, avatar);
+ return handlePost(req, res, avatarId);
});
-async function handleGet(_req, res, avatarId) {
+function handleGet(res, avatarId, avatar) {
const origin = env.APP_ORIGIN;
const iconUrl = `${origin}/api/actions/avatar-icon?avatar=${encodeURIComponent(avatarId)}`;
const actionHref = `/api/actions/avatar?avatar=${encodeURIComponent(avatarId)}`;
+ const name = typeof avatar?.name === 'string' ? avatar.name.trim().slice(0, 60) : '';
- setActionHeaders(res);
return json(res, 200, {
+ type: 'action',
icon: iconUrl,
label: 'Claim Avatar',
- title: 'My 3D Avatar — three.ws',
+ title: name ? `${name} on three.ws` : 'My 3D Avatar on three.ws',
description:
'Register your Solana wallet to this 3D avatar. Your claim is written on-chain via SPL Memo and links your wallet to your three.ws identity.',
links: {
@@ -70,26 +106,42 @@ async function handlePost(req, res, avatarId) {
try {
body = await readJson(req, 4_000);
} catch (e) {
- return error(res, 400, 'bad_request', e.message);
+ return actionError(res, 400, 'bad_request', e.message);
}
const account = typeof body?.account === 'string' ? body.account.trim() : '';
- if (!account) return error(res, 400, 'bad_request', 'account is required');
+ if (!account) return actionError(res, 400, 'bad_request', 'account is required');
- const { PublicKey, TransactionMessage, VersionedTransaction, Connection } =
+ const { PublicKey, TransactionMessage, VersionedTransaction } =
await import('@solana/web3.js');
let payer;
try {
payer = new PublicKey(account);
+ // A curve-off point is a PDA: it has no private key, so a transaction
+ // built for it can never be signed. Reject it here rather than handing
+ // the wallet a transaction it will fail on.
+ if (!PublicKey.isOnCurve(payer.toBytes())) throw new Error('off-curve');
} catch {
- return error(res, 400, 'bad_request', 'invalid account pubkey');
+ return actionError(res, 400, 'bad_request', 'invalid account pubkey');
}
const rpc =
process.env.SOLANA_MAINNET_RPC || 'https://api.mainnet-beta.solana.com';
const connection = solanaConnection({ url: rpc, commitment: 'confirmed' });
- const { blockhash } = await connection.getLatestBlockhash();
+ let blockhash;
+ try {
+ ({ blockhash } = await connection.getLatestBlockhash());
+ } catch (err) {
+ // maxDuration is 10s: a stalled or rate-limited RPC has to surface as an
+ // actionable error, not as a timeout the Blink client renders as a hang.
+ return actionError(
+ res,
+ 503,
+ 'rpc_unavailable',
+ `Solana RPC did not return a blockhash: ${err?.message || err}`,
+ );
+ }
const memo = JSON.stringify({
v: 1,
@@ -113,9 +165,9 @@ async function handlePost(req, res, avatarId) {
const tx = new VersionedTransaction(message);
const txBase64 = Buffer.from(tx.serialize()).toString('base64');
- setActionHeaders(res);
return json(res, 200, {
+ type: 'transaction',
transaction: txBase64,
message: 'Your 3D avatar identity is now recorded on Solana. Welcome to three.ws.',
- });
+ }, { 'cache-control': 'no-store' });
}
diff --git a/api/agenc/[action].js b/api/agenc/[action].js
index f0b6efc4f..909c67e9c 100644
--- a/api/agenc/[action].js
+++ b/api/agenc/[action].js
@@ -24,9 +24,9 @@
// bridge and checks whether that PDA is already registered on-chain.
//
// Cluster defaults to `mainnet`. Set `?cluster=devnet` for devnet program
-// 6UcJzbTEemBz3aY5wK5qKHGMD7bdRsmR4smND29gB2ab. RPC endpoint is the public
-// Solana cluster RPC unless `AGENC_RPC_URL` (or `SOLANA_RPC_URL_DEVNET` /
-// `SOLANA_RPC_URL`) is set.
+// 6UcJzbTEemBz3aY5wK5qKHGMD7bdRsmR4smND29gB2ab. Reads rotate across the
+// platform's canonical Solana RPC chain (see withAgenC below); `AGENC_RPC_URL`
+// pins a preferred endpoint at the head of that chain.
import { PublicKey } from '@solana/web3.js';
import { createHash } from 'node:crypto';
@@ -35,6 +35,14 @@ import { getTask, getTaskLifecycleSummary, getTasksByCreator, getAgent, deriveTa
import { cors, json, method, readJson, wrap, error, rateLimited, serverError } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
+import {
+ solanaRpcEndpoints,
+ isEndpointCooling,
+ markEndpointCooldown,
+ hydrateEndpointCooldowns,
+ shouldRotate,
+ isTransientRpcError,
+} from '../_lib/solana/connection.js';
import { Bazaar, filterByExtension, filterByMaxPrice, filterByNetwork, parseAtomicAmount } from '../_lib/x402/bazaar-client.js';
// @three-ws/solana-agent (the symlinked `file:solana-agent-sdk` SDK) is loaded
@@ -48,15 +56,6 @@ function pickCluster(req) {
return c === 'devnet' ? 'devnet' : 'mainnet';
}
-function pickRpc(cluster) {
- const override = (process.env.AGENC_RPC_URL || '').trim();
- if (override) return override;
- if (cluster === 'devnet') {
- return (process.env.SOLANA_RPC_URL_DEVNET || '').trim() || undefined;
- }
- return (process.env.SOLANA_RPC_URL || '').trim() || undefined;
-}
-
function parsePubkey(s, label) {
if (!s) throw new Error(`${label} is required`);
try {
@@ -117,11 +116,77 @@ function agentStatusLabel(status) {
return String(status);
}
-async function clientFor(req) {
+// `createAgenCClient` builds its own Connection from ONE url, so a client made
+// here is bound to a single endpoint with no failover of its own. Pointing it at
+// `SOLANA_RPC_URL` alone is what took every chain-backed AgenC route down: the
+// configured primary began answering this egress with a hard 403, and each read
+// became an opaque 500 while eight healthy lanes sat unused. So we walk the
+// platform's canonical, priority-ordered endpoint chain instead and share its
+// process-wide cooldown map, which means a lane another surface just parked is
+// skipped here too, and a lane we park is skipped there. `AGENC_RPC_URL` still
+// wins: it is pinned to the head of the chain rather than being the whole of it.
+async function agenCEndpoints(cluster) {
+ // Inherit the fleet's view of dead lanes first. Without it a cold Cloud Run
+ // instance re-discovers a quota-dead provider the expensive way: web3.js runs
+ // its own 429 backoff (500/1000/2000/4000ms) inside the Connection before the
+ // error ever reaches us, so each already-known-dead lane costs ~7.5s.
+ await hydrateEndpointCooldowns();
+ const pinned = (process.env.AGENC_RPC_URL || '').trim() || null;
+ const urls = solanaRpcEndpoints(cluster, pinned);
+ const live = urls.filter((u) => !isEndpointCooling(u));
+ // Every lane cooling at once is upstream weather, not a reason to answer with
+ // nothing: re-probe the full chain rather than skipping straight to a 503.
+ return live.length ? live : urls;
+}
+
+// Recover the upstream HTTP status from a web3.js error, which reports it as the
+// head of the message ("403 Forbidden: {…}"). 0 means "no status in there".
+function rpcStatus(err) {
+ const m = String(err?.message || err).match(/\b(401|403|404|408|410|429|5\d\d)\b/);
+ return m ? Number(m[1]) : 0;
+}
+
+// Thrown once every endpoint has refused the same read. Distinct from a normal
+// failure so the wrapper can answer 503 + Retry-After (upstream weather the
+// caller should retry) instead of a 500 (a defect the caller cannot act on).
+class RpcChainExhausted extends Error {
+ constructor(cluster, tried, cause) {
+ super(`all ${tried} Solana RPC endpoints refused this ${cluster} read: ${cause?.message || 'unknown error'}`);
+ this.name = 'RpcChainExhausted';
+ this.cluster = cluster;
+ this.tried = tried;
+ this.cause = cause;
+ }
+}
+
+// Run `fn` against an AgenC client, rotating to the next endpoint whenever one
+// fails in a way the next provider may not share (401/403/404/408/410/429/5xx,
+// timeouts, network blips). A real request error, e.g. a malformed account the
+// chain decodes the same way everywhere, is re-thrown on the first endpoint
+// rather than replayed nine times.
+async function withAgenC(cluster, fn) {
const { createAgenCClient } = await import('@three-ws/solana-agent');
- const cluster = pickCluster(req);
- const rpcUrl = pickRpc(cluster);
- return createAgenCClient({ cluster, rpcUrl });
+ const endpoints = await agenCEndpoints(cluster);
+ let last = null;
+ for (const rpcUrl of endpoints) {
+ let client;
+ try {
+ client = createAgenCClient({ cluster, rpcUrl });
+ } catch (err) {
+ last = err;
+ continue;
+ }
+ try {
+ return await fn(client);
+ } catch (err) {
+ const status = rpcStatus(err);
+ if (!shouldRotate(status) && !isTransientRpcError(err)) throw err;
+ const ms = markEndpointCooldown(rpcUrl, status || 429, String(err?.message || ''));
+ console.info(`[agenc] rpc lane failed (${status || 'transient'}), cooling ${Math.round(ms / 1000)}s, rotating`);
+ last = err;
+ }
+ }
+ throw new RpcChainExhausted(cluster, endpoints.length, last);
}
async function handleListTasks(req, res) {
@@ -131,8 +196,10 @@ async function handleListTasks(req, res) {
} catch (err) {
return error(res, 400, 'validation_error', err.message);
}
- const client = await clientFor(req);
- const tasks = await getTasksByCreator(client.program, creator);
+ const { client, tasks } = await withAgenC(pickCluster(req), async (c) => ({
+ client: c,
+ tasks: await getTasksByCreator(c.program, creator),
+ }));
return json(res, 200, serialize({
ok: true,
cluster: client.cluster,
@@ -158,14 +225,17 @@ async function handleListTasks(req, res) {
async function handleGetTask(req, res) {
const q = req.query || {};
- const client = await clientFor(req);
- let pda;
+ // Resolve the caller's identifiers BEFORE touching the chain: a malformed pubkey
+ // or task id is a 400 that must not cost an RPC round trip (or nine of them).
+ let explicitPda = null;
+ let creator = null;
+ let taskIdSeed = null;
try {
if (q.taskPda) {
- pda = parsePubkey(q.taskPda, 'taskPda');
+ explicitPda = parsePubkey(q.taskPda, 'taskPda');
} else if (q.creator && q.taskId) {
- const creator = parsePubkey(q.creator, 'creator');
- pda = deriveTaskPda(creator, resolveIdInput(q.taskId), client.programId);
+ creator = parsePubkey(q.creator, 'creator');
+ taskIdSeed = resolveIdInput(q.taskId);
} else {
return error(res, 400, 'validation_error', 'provide taskPda OR (creator + taskId)');
}
@@ -173,23 +243,18 @@ async function handleGetTask(req, res) {
return error(res, 400, 'validation_error', err.message);
}
- const task = await getTask(client.program, pda);
- if (!task) {
- return json(res, 404, {
- ok: false,
- error: 'not_found',
- cluster: client.cluster,
- programId: client.programId.toBase58(),
- taskPda: pda.toBase58(),
- });
- }
-
const wantLifecycle = q.lifecycle === '1' || q.lifecycle === 'true';
- let lifecycle = null;
- if (wantLifecycle) {
- const s = await getTaskLifecycleSummary(client.program, pda);
- if (s) {
- lifecycle = {
+ const { client, pda, task, lifecycle } = await withAgenC(pickCluster(req), async (c) => {
+ const taskPda = explicitPda || deriveTaskPda(creator, taskIdSeed, c.programId);
+ const found = await getTask(c.program, taskPda);
+ if (!found || !wantLifecycle) return { client: c, pda: taskPda, task: found, lifecycle: null };
+ const s = await getTaskLifecycleSummary(c.program, taskPda);
+ if (!s) return { client: c, pda: taskPda, task: found, lifecycle: null };
+ return {
+ client: c,
+ pda: taskPda,
+ task: found,
+ lifecycle: {
currentState: taskStateLabel(s.currentState),
createdAt: s.createdAt,
currentWorkers: s.currentWorkers,
@@ -200,11 +265,24 @@ async function handleGetTask(req, res) {
txSignature: e.txSignature ?? null,
actor: e.actor ? e.actor.toBase58() : null,
})),
- };
- await enrichLifecycleFromProjection(lifecycle, pda.toBase58());
- }
+ },
+ };
+ });
+
+ if (!task) {
+ return json(res, 404, {
+ ok: false,
+ error: 'not_found',
+ cluster: client.cluster,
+ programId: client.programId.toBase58(),
+ taskPda: pda.toBase58(),
+ });
}
+ // Journal enrichment reads our own DB, not the chain, so it stays outside the
+ // RPC rotation: a DB blip must never cost a second pass over every endpoint.
+ if (lifecycle) await enrichLifecycleFromProjection(lifecycle, pda.toBase58());
+
return json(res, 200, serialize({
ok: true,
cluster: client.cluster,
@@ -299,20 +377,23 @@ export async function enrichLifecycleFromProjection(lifecycle, taskPda) {
async function handleGetAgent(req, res) {
const q = req.query || {};
- const client = await clientFor(req);
- let pda;
+ let explicitPda = null;
+ let agentIdSeed = null;
try {
if (q.agentPda) {
- pda = parsePubkey(q.agentPda, 'agentPda');
+ explicitPda = parsePubkey(q.agentPda, 'agentPda');
} else if (q.agentId) {
- pda = deriveAgentPda(resolveIdInput(q.agentId), client.programId);
+ agentIdSeed = resolveIdInput(q.agentId);
} else {
return error(res, 400, 'validation_error', 'provide agentPda or agentId');
}
} catch (err) {
return error(res, 400, 'validation_error', err.message);
}
- const agent = await getAgent(client.program, pda);
+ const { client, pda, agent } = await withAgenC(pickCluster(req), async (c) => {
+ const agentPda = explicitPda || deriveAgentPda(agentIdSeed, c.programId);
+ return { client: c, pda: agentPda, agent: await getAgent(c.program, agentPda) };
+ });
if (!agent) {
return json(res, 404, {
ok: false,
@@ -352,7 +433,7 @@ async function handleLink(req, res) {
return error(res, 400, 'validation_error', 'invalid json');
}
const { erc8004AgentId, mplCoreAsset, handle, cluster, baseUrl } = body || {};
- const { createAgenCClient, getCanonicalThreewsAgenCId, buildThreewsMetadataUri, agenCAgentIdToHex } =
+ const { getCanonicalThreewsAgenCId, buildThreewsMetadataUri, agenCAgentIdToHex } =
await import('@three-ws/solana-agent');
let canonical;
try {
@@ -366,10 +447,10 @@ async function handleLink(req, res) {
}
const cl = cluster === 'devnet' ? 'devnet' : 'mainnet';
- const rpcUrl = pickRpc(cl);
- const client = createAgenCClient({ cluster: cl, rpcUrl });
- const pda = deriveAgentPda(canonical.agenCAgentId, client.programId);
- const agent = await getAgent(client.program, pda);
+ const { client, pda, agent } = await withAgenC(cl, async (c) => {
+ const agentPda = deriveAgentPda(canonical.agenCAgentId, c.programId);
+ return { client: c, pda: agentPda, agent: await getAgent(c.program, agentPda) };
+ });
const metadataUri = buildThreewsMetadataUri(
{ erc8004AgentId: erc8004AgentId ?? null, mplCoreAsset: mplCoreAsset ?? null, handle: handle ?? null },
@@ -503,6 +584,18 @@ export default wrap(async (req, res) => {
try {
return await route.fn(req, res);
} catch (err) {
+ // Every RPC lane refusing the same read is upstream weather with a real
+ // remedy (retry once a cooldown lapses), so it gets an honest 503 + a
+ // Retry-After the caller can act on. A 500 here told clients "we are
+ // broken, do not retry" for a condition that clears itself in seconds.
+ if (err instanceof RpcChainExhausted) {
+ console.error('[agenc] rpc chain exhausted', err.message);
+ res.setHeader('retry-after', '30');
+ return error(res, 503, 'rpc_unavailable', `Solana ${err.cluster} RPC is unavailable right now; retry in ~30s`, {
+ cluster: err.cluster,
+ endpointsTried: err.tried,
+ });
+ }
console.error('[agenc] unexpected error', err?.message);
return serverError(res, 500, 'agenc_error', err);
}
diff --git a/api/agent-3d/versions.js b/api/agent-3d/versions.js
index f8cbcdcc2..7ccde164e 100644
--- a/api/agent-3d/versions.js
+++ b/api/agent-3d/versions.js
@@ -1,6 +1,8 @@
-// GET /api/agent-3d/versions — serves dist/agent-3d/versions.json with CORS + cache headers
+// GET /api/agent-3d/versions: serves dist/agent-3d/versions.json (the CDN release
+// manifest written by `npm run publish:lib`) with CORS, cache, and ETag headers.
import { readFileSync } from 'node:fs';
+import { createHash } from 'node:crypto';
import { cors, json, error, method, wrap } from '../_lib/http.js';
const VERSIONS_PATH = new URL('../../dist/agent-3d/versions.json', import.meta.url);
@@ -9,21 +11,59 @@ const CACHE_HEADERS = {
'cache-control': 'public, max-age=60, s-maxage=60, stale-while-revalidate=300',
};
+// Read per request rather than memoized: the manifest is ~400 bytes, the CDN holds
+// it for 60s so the origin barely sees this route, and every cheap invalidation key
+// available here is unsound. mtime granularity on an overlay filesystem is coarse
+// enough that two publishes inside the same tick are indistinguishable, which would
+// pin a container to a superseded release manifest. Correctness wins over a syscall.
+function loadManifest() {
+ const raw = readFileSync(VERSIONS_PATH, 'utf8');
+ return {
+ data: JSON.parse(raw),
+ // Content-derived, so it changes exactly when the published manifest does.
+ etag: `"${createHash('sha256').update(raw).digest('base64url').slice(0, 27)}"`,
+ };
+}
+
+// RFC 9110 §13.1.2: If-None-Match is a comma-separated list, entries may carry the
+// weak `W/` prefix, and `*` matches any existing representation.
+function ifNoneMatch(header, etag) {
+ if (!header) return false;
+ const tags = String(header).split(',').map((t) => t.trim());
+ if (tags.includes('*')) return true;
+ return tags.some((t) => t.replace(/^W\//, '') === etag);
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,HEAD,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET', 'HEAD'])) return;
- let data;
+ let manifest;
try {
- data = JSON.parse(readFileSync(VERSIONS_PATH, 'utf8'));
- } catch {
+ manifest = loadManifest();
+ } catch (err) {
+ // Both branches are deployment faults rather than caller faults, so both are
+ // 503, but they need different fixes: a missing file means publish:lib never
+ // ran, a parse failure means it produced garbage. Saying "not found" for both
+ // sends the operator looking for the wrong thing.
+ const missing = err?.code === 'ENOENT';
return error(
res,
503,
- 'not_found',
- 'versions.json not found — run npm run publish:lib',
+ 'versions_unavailable',
+ missing
+ ? 'dist/agent-3d/versions.json is missing; run `npm run publish:lib`'
+ : 'dist/agent-3d/versions.json is unreadable or not valid JSON; rebuild it with `npm run publish:lib`',
);
}
- return json(res, 200, data, CACHE_HEADERS);
+ if (ifNoneMatch(req.headers['if-none-match'], manifest.etag)) {
+ res.statusCode = 304;
+ for (const [k, v] of Object.entries(CACHE_HEADERS)) res.setHeader(k, v);
+ res.setHeader('etag', manifest.etag);
+ res.end();
+ return;
+ }
+
+ return json(res, 200, manifest.data, { ...CACHE_HEADERS, etag: manifest.etag });
});
diff --git a/api/agent-economy/status.js b/api/agent-economy/status.js
index 5b3a512c4..446170f60 100644
--- a/api/agent-economy/status.js
+++ b/api/agent-economy/status.js
@@ -1,12 +1,18 @@
// GET /api/agent-economy/status
//
-// Returns live wallet info for both agents — no auth required, read-only.
+// Returns live wallet info for both agents. No auth required, read-only.
// agentA = the buyer (AVATAR_WALLET_SECRET keypair)
// agentB = the seller (AGENT_B_ADDRESS public key only)
//
// Both balances are fetched from Solana mainnet. The seller balance uses a
-// public RPC query on the configured address — no private key needed.
+// public RPC query on the configured address, so no private key is needed.
// Returns configured:false for either agent when their env var is absent.
+//
+// `configured` reports CONFIGURATION, never RPC health: an agent whose env var
+// is set stays configured:true with `sol: null` when the balance read fails, so
+// the caller can tell "no wallet set up" apart from "Solana RPC is down". Those
+// two used to collapse into the same configured:false, which made an RPC blip
+// read as a missing wallet.
import {
avatarWalletConfig,
@@ -21,6 +27,19 @@ import { cors, method, wrap } from '../_lib/http.js';
const RPC_URL = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+function unfundedShape({ address, network }) {
+ return {
+ configured: true,
+ address,
+ sol: null,
+ lamports: null,
+ usd: null,
+ solPriceUsd: null,
+ network,
+ explorer: explorerAccountUrl(address, network),
+ };
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
@@ -35,23 +54,20 @@ export default wrap(async (req, res) => {
const fetches = [];
if (cfgA.configured) {
+ const addr = loadAvatarKeypair(process.env.AVATAR_WALLET_SECRET).publicKey.toBase58();
+ agentA = unfundedShape({ address: addr, network: cfgA.network });
fetches.push(
(async () => {
- const kp = loadAvatarKeypair(process.env.AVATAR_WALLET_SECRET);
- const addr = kp.publicKey.toBase58();
const [{ sol, lamports }, price] = await Promise.all([
getSolBalance(conn, addr),
pricePromise,
]);
agentA = {
- configured: true,
- address: addr,
+ ...agentA,
sol,
lamports,
usd: price > 0 ? sol * price : null,
solPriceUsd: price || null,
- network: cfgA.network,
- explorer: explorerAccountUrl(addr, cfgA.network),
};
})(),
);
@@ -59,6 +75,7 @@ export default wrap(async (req, res) => {
const bAddr = process.env.AGENT_B_ADDRESS?.trim();
if (bAddr && isValidPubkey(bAddr)) {
+ agentB = unfundedShape({ address: bAddr, network: 'mainnet' });
fetches.push(
(async () => {
const [{ sol, lamports }, price] = await Promise.all([
@@ -66,14 +83,11 @@ export default wrap(async (req, res) => {
pricePromise,
]);
agentB = {
- configured: true,
- address: bAddr,
+ ...agentB,
sol,
lamports,
usd: price > 0 ? sol * price : null,
solPriceUsd: price || null,
- network: 'mainnet',
- explorer: explorerAccountUrl(bAddr, 'mainnet'),
};
})(),
);
diff --git a/api/agent-economy/transact.js b/api/agent-economy/transact.js
index 3c770e46f..4bb8dbf86 100644
--- a/api/agent-economy/transact.js
+++ b/api/agent-economy/transact.js
@@ -1,25 +1,33 @@
// POST /api/agent-economy/transact
//
// The agent-to-agent economy endpoint. Agent A (Nova, buyer) pays Agent B
-// (Oracle, seller) real SOL on Solana, then Agent B delivers the requested
+// (Oracle, seller) real SOL on Solana, and Agent B delivers the requested
// service as a real LLM response.
//
// Flow:
// 1. Validate the service request (service slug + optional topic).
-// 2. Send real SOL from Agent A's wallet (AVATAR_WALLET_SECRET) to the
-// recipient address (AGENT_B_ADDRESS or AVATAR_DEFAULT_RECIPIENT as
-// fallback — fund whichever address you want "Agent B" to hold).
-// 3. Generate Agent B's spoken service delivery via the LLM.
+// 2. Produce Agent A's request line and Agent B's service delivery as real
+// model completions over the platform LLM chain.
+// 3. Only once the service exists, send real SOL from Agent A's wallet
+// (AVATAR_WALLET_SECRET) to the recipient address (AGENT_B_ADDRESS, or
+// AVATAR_DEFAULT_RECIPIENT as fallback: fund whichever address you want
+// "Agent B" to hold).
// 4. Return everything: Agent A's buy message, Agent B's service reply,
// the Solana transaction signature, explorer URL, amounts, and metadata.
//
-// No mocks — when the wallet is not configured the endpoint says so (503).
-// The caller UI degrades gracefully: it shows the conversation without the tx.
+// Delivery comes before payment on purpose: Agent A must never pay for a
+// service that could not be produced. An unreachable model chain fails the
+// request with 503 and nothing spent.
+//
+// No mocks: when the wallet is not configured the endpoint says so in
+// `transaction.error`. The caller UI degrades gracefully, showing the
+// conversation without the tx.
import { z } from 'zod';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { parse } from '../_lib/validate.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { llmComplete } from '../_lib/llm.js';
import {
avatarWalletConfig,
loadAvatarKeypair,
@@ -33,7 +41,7 @@ import {
LAMPORTS_PER_SOL,
} from '../_lib/avatar-wallet.js';
-// Services Agent B (Oracle) sells. Price in USD — converted to SOL at live
+// Services Agent B (Oracle) sells. Price in USD, converted to SOL at the live
// rate per transaction so the micro-payment is always meaningful on-chain.
export const SERVICES = {
'market-analysis': {
@@ -42,9 +50,9 @@ export const SERVICES = {
priceUsd: 0.001,
buyerPrompt: (topic) =>
`Request a quick market analysis on ${topic || 'Solana'}. You are Nova, a 3D AI agent. Speak directly to Oracle, be crisp and businesslike. One sentence.`,
- sellerSystem: `You are Oracle, a data-selling AI agent on the three.ws platform. You have a Solana wallet. A fellow agent just paid you for market intelligence. Deliver sharp, confident insights in 2–3 sentences. Speak directly to Nova. No disclaimers — you are an agent, not a chatbot.`,
+ sellerSystem: `You are Oracle, a data-selling AI agent on the three.ws platform. You have a Solana wallet. A fellow agent just paid you for market intelligence. Deliver sharp, confident insights in 2 to 3 sentences. Speak directly to Nova. No disclaimers: you are an agent, not a chatbot.`,
sellerPrompt: (topic) =>
- `Nova just paid you for a market analysis on ${topic || 'Solana'}. Deliver the analysis — momentum, key signal, your read on where it's heading. Keep it vivid and punchy.`,
+ `Nova just paid you for a market analysis on ${topic || 'Solana'}. Deliver the analysis: momentum, key signal, your read on where it's heading. Keep it vivid and punchy.`,
},
'onchain-insight': {
name: 'On-Chain Insight',
@@ -52,7 +60,7 @@ export const SERVICES = {
priceUsd: 0.002,
buyerPrompt: (topic) =>
`Ask Oracle for on-chain wallet intelligence on ${topic || 'the current market'}. You are Nova, 3D AI agent. One direct sentence to Oracle.`,
- sellerSystem: `You are Oracle, a data-selling AI agent. Another agent paid you for on-chain intelligence. Deliver smart, data-forward insights in 2–3 sentences. No preamble — dive straight in.`,
+ sellerSystem: `You are Oracle, a data-selling AI agent. Another agent paid you for on-chain intelligence. Deliver smart, data-forward insights in 2 to 3 sentences. No preamble: dive straight in.`,
sellerPrompt: (topic) =>
`Nova paid for on-chain insights on ${topic || 'the current market'}. Give a sharp read: wallet concentration, smart-money signals, what the chain is actually telling you.`,
},
@@ -62,7 +70,7 @@ export const SERVICES = {
priceUsd: 0.003,
buyerPrompt: (topic) =>
`Request a risk score from Oracle for ${topic || 'Solana DeFi exposure'}. You are Nova. One sentence, direct.`,
- sellerSystem: `You are Oracle, a risk-intelligence agent. Another agent paid you for a risk score. Give a concrete risk rating (1–10) with your top two reasons. Be direct and analytical.`,
+ sellerSystem: `You are Oracle, a risk-intelligence agent. Another agent paid you for a risk score. Give a concrete risk rating (1 to 10) with your top two reasons. Be direct and analytical.`,
sellerPrompt: (topic) =>
`Nova paid for a risk score on ${topic || 'Solana DeFi exposure'}. Give a number (1 = safe, 10 = critical) and explain the two biggest risk factors in 2 sentences.`,
},
@@ -83,11 +91,40 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
const body = parse(bodySchema, await readJson(req));
- const svc = SERVICES[body.service];
+ // Own-property lookup only. A bare `SERVICES[body.service]` walked the
+ // prototype chain, so `service: "constructor"` resolved to Object, passed the
+ // guard below, and reached the payment path as a service with an undefined
+ // price and no prompts.
+ const svc = Object.hasOwn(SERVICES, body.service) ? SERVICES[body.service] : null;
if (!svc) return error(res, 400, 'unknown_service', `unknown service: ${body.service}`);
const topic = body.topic?.trim() || null;
- // ── Agent A pays Agent B ───────────────────────────────────────────────
+ // Agent B produces the service, and Agent A its request line, as real model
+ // completions. This runs BEFORE the payment: Agent A must never pay for a
+ // service that could not be produced.
+ const [buyerAttempt, sellerAttempt] = await Promise.allSettled([
+ speak(svc.buyerPrompt(topic), null),
+ speak(svc.sellerPrompt(topic), svc.sellerSystem),
+ ]);
+ // The buyer's line is framing, not the deliverable: a missing one just means
+ // Nova stays quiet while the paid-for service still lands.
+ const buyerSaid = buyerAttempt.status === 'fulfilled' ? buyerAttempt.value : null;
+ const sellerSaid = sellerAttempt.status === 'fulfilled' ? sellerAttempt.value : null;
+ if (!sellerSaid) {
+ const reason =
+ sellerAttempt.status === 'rejected'
+ ? sellerAttempt.reason?.message || String(sellerAttempt.reason)
+ : 'model returned no text';
+ console.error('[agent-economy] delivery unavailable:', reason);
+ return error(
+ res,
+ 503,
+ 'delivery_unavailable',
+ 'Oracle could not reach its model to produce this service. Nothing was charged. Try again in a moment.',
+ );
+ }
+
+ // Agent A pays Agent B for the service just produced.
const cfg = avatarWalletConfig();
let txResult = null;
@@ -108,35 +145,38 @@ export default wrap(async (req, res) => {
);
const balance = await getSolBalance(connection, fromKeypair.publicKey);
- // Global daily spend ceiling — consumed only when we're about to
- // actually pay, so non-paying requests (unconfigured wallet, empty
- // balance, unknown service) can't exhaust the demo budget and DoS it.
- const spendRl = await limits.agentEconomyGlobal();
- if (!spendRl.success) {
- txResult = { error: 'rate_limited', message: 'daily demo transaction budget reached — try again tomorrow.' };
- } else if (balance >= lamports + FEE_BUFFER_LAMPORTS) {
- const memo = `three.ws agent-economy · ${svc.name}`;
- const signature = await sendSol({
- connection,
- fromKeypair,
- to: recipient,
- lamports,
- memo,
- });
- txResult = {
- signature,
- explorerUrl: explorerTxUrl(signature, cfg.network),
- buyerAddress: fromKeypair.publicKey.toBase58(),
- sellerAddress: recipient,
- buyerExplorerUrl: explorerAccountUrl(fromKeypair.publicKey.toBase58(), cfg.network),
- sellerExplorerUrl: explorerAccountUrl(recipient, cfg.network),
- lamports,
- solAmount: lamports / LAMPORTS_PER_SOL,
- usdAmount: svc.priceUsd,
- network: cfg.network,
- };
- } else {
+ if (balance < lamports + FEE_BUFFER_LAMPORTS) {
txResult = { error: 'insufficient_balance', message: 'Fund Agent A\'s wallet to enable live transactions.' };
+ } else {
+ // Global daily spend ceiling, consumed only here, with a send about
+ // to fire. Checking it any earlier let non-paying requests (empty
+ // wallet, prototype-chain pseudo-service) burn the demo budget and
+ // DoS the feature without a lamport ever moving.
+ const spendRl = await limits.agentEconomyGlobal();
+ if (!spendRl.success) {
+ txResult = { error: 'rate_limited', message: 'daily demo transaction budget reached, try again tomorrow.' };
+ } else {
+ const memo = `three.ws agent-economy · ${svc.name}`;
+ const signature = await sendSol({
+ connection,
+ fromKeypair,
+ to: recipient,
+ lamports,
+ memo,
+ });
+ txResult = {
+ signature,
+ explorerUrl: explorerTxUrl(signature, cfg.network),
+ buyerAddress: fromKeypair.publicKey.toBase58(),
+ sellerAddress: recipient,
+ buyerExplorerUrl: explorerAccountUrl(fromKeypair.publicKey.toBase58(), cfg.network),
+ sellerExplorerUrl: explorerAccountUrl(recipient, cfg.network),
+ lamports,
+ solAmount: lamports / LAMPORTS_PER_SOL,
+ usdAmount: svc.priceUsd,
+ network: cfg.network,
+ };
+ }
}
} catch (e) {
txResult = { error: 'tx_failed', message: e.message };
@@ -148,25 +188,6 @@ export default wrap(async (req, res) => {
txResult = { error: 'wallet_unconfigured', message: 'Set AVATAR_WALLET_SECRET to enable live transactions.' };
}
- // ── Generate Agent B's service delivery (real LLM) ────────────────────
- // Uses the same /api/chat proxy — picks whatever brain is configured
- // (Anthropic, Granite, Groq, etc.) so no extra credentials needed.
- let buyerSaid = null;
- let sellerSaid = null;
-
- try {
- const [buyerRes, sellerRes] = await Promise.all([
- fetchChat(svc.buyerPrompt(topic), null),
- fetchChat(svc.sellerPrompt(topic), svc.sellerSystem),
- ]);
- buyerSaid = buyerRes;
- sellerSaid = sellerRes;
- } catch (e) {
- // LLM failure doesn't fail the endpoint; agents speak generic lines
- buyerSaid = `Requesting ${svc.name}…`;
- sellerSaid = `${svc.name} delivered. The data is yours.`;
- }
-
return json(res, 200, {
service: {
slug: body.service,
@@ -182,44 +203,24 @@ export default wrap(async (req, res) => {
});
});
-// One-shot non-streaming LLM call through the existing /api/chat proxy.
-async function fetchChat(userMessage, systemOverride) {
- const baseUrl = process.env.VERCEL_URL
- ? `https://${process.env.VERCEL_URL}`
- : 'http://localhost:3000';
-
- const messages = systemOverride
- ? [{ role: 'system', content: systemOverride }, { role: 'user', content: userMessage }]
- : [{ role: 'user', content: userMessage }];
-
- let res;
- try {
- res = await fetch(`${baseUrl}/api/chat`, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ message: userMessage, history: messages.slice(0, -1) }),
- // Bound a hung internal /api/chat under the function's kill so a stalled
- // model lane returns the same null the caller already handles, not a 504.
- signal: AbortSignal.timeout(25000),
- });
- } catch {
- return null;
- }
-
- if (!res.ok) return null;
-
- // /api/chat streams SSE — collect all chunks into one string.
- const text = await res.text();
- const chunks = text
- .split('\n')
- .filter((l) => l.startsWith('data: '))
- .map((l) => {
- try {
- const d = JSON.parse(l.slice(6));
- return d.type === 'chunk' ? d.text : '';
- } catch {
- return '';
- }
- });
- return chunks.join('').trim() || null;
+// One-shot completion over the platform LLM chain (free lanes first, then the
+// GCP-credits Vertex anchor), called in-process.
+//
+// This used to POST to /api/chat over HTTP and guess its own origin from
+// VERCEL_URL, falling back to http://localhost:3000. Nothing serves that port on
+// Cloud Run (the container listens on PORT, 8080), so both completions silently
+// resolved to null in production and the agents never spoke. In-process removes
+// the round trip and the origin guess together.
+//
+// Throws when no provider is configured or the whole chain fails; the caller
+// turns that into a 503 with nothing charged.
+async function speak(user, system) {
+ const completion = await llmComplete({
+ system: system || undefined,
+ user,
+ maxTokens: 320,
+ timeoutMs: 20_000,
+ track: { tool: 'agent-economy-transact' },
+ });
+ return completion?.text?.trim() || null;
}
diff --git a/api/agent-economy/volume.js b/api/agent-economy/volume.js
index ce74d41c0..a473be6dd 100644
--- a/api/agent-economy/volume.js
+++ b/api/agent-economy/volume.js
@@ -1,20 +1,20 @@
// GET /api/agent-economy/volume
//
-// The platform-wide agent-to-agent economy roll-up — the single read behind the
+// The platform-wide agent-to-agent economy roll-up: the single read behind the
// public A2A volume dashboard (/agent-economy-volume). Every number is a live
// aggregate over the real `agent_hires` ledger: one row per settled hire where
// one agent paid another for a paid skill over the x402 rails. "Completed" hires
-// are the authoritative volume — real USDC moved on-chain, recorded with the
+// are the authoritative volume: real USDC moved on-chain, recorded with the
// settlement signature.
//
-// Public + read-only. No auth, no PII — only aggregate counts, USD totals, and
+// Public + read-only. No auth, no PII: only aggregate counts, USD totals, and
// on-chain identifiers (agent ids + payment signatures) that are already public.
//
// Query params:
-// window — trailing window in days for the daily series + leaderboards
-// (1–365, default 30).
-// top — ranked agents per leaderboard (1–50, default 10).
-// recent — settled hires in the live feed (1–50, default 12).
+// window = trailing window in days for the daily series + leaderboards
+// (1 to 365, default 30).
+// top = ranked agents per leaderboard (1 to 50, default 10).
+// recent = settled hires in the live feed (1 to 50, default 12).
//
// No mock path: when the ledger table is unmigrated/empty the endpoint returns a
// real zero shape so the dashboard renders its empty state, never a fabricated
diff --git a/api/agent-trade/demo.js b/api/agent-trade/demo.js
index 573e69885..799982986 100644
--- a/api/agent-trade/demo.js
+++ b/api/agent-trade/demo.js
@@ -1,4 +1,4 @@
-// GET /api/agent-trade/demo — Server-Sent Events orchestrator for the
+// GET /api/agent-trade/demo: Server-Sent Events orchestrator for the
// agent-to-agent x402 trade demo.
//
// Autonomously drives the full buyer-agent flow, streaming events so the
@@ -26,7 +26,7 @@ import {
LAMPORTS_PER_SOL,
} from '../_lib/avatar-wallet.js';
import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';
-import { llmComplete } from '../_lib/llm.js';
+import { llmComplete, providerChain } from '../_lib/llm.js';
import { cors, method, json, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -72,7 +72,7 @@ async function generateAnalysis(topic) {
const messages = [
{
role: 'user',
- content: `Provide a concise 2–3 sentence crypto market insight on: ${topic}. Be specific, data-driven, and actionable.`,
+ content: `Provide a concise 2 to 3 sentence crypto market insight on: ${topic}. Be specific, data-driven, and actionable.`,
},
];
const { text } = await watsonxChatComplete(wx, {
@@ -91,9 +91,9 @@ async function generateAnalysis(topic) {
}
// Platform LLM policy (api/_lib/llm.js): free providers first, paid keys as
- // the automatic last resort — a dead Anthropic key must not kill the demo.
+ // the automatic last resort, so a dead Anthropic key cannot kill the demo.
const { text, model, provider } = await llmComplete({
- system: 'You are a concise crypto market analyst. Respond in 2–3 sharp sentences.',
+ system: 'You are a concise crypto market analyst. Respond in 2 to 3 sharp sentences.',
user: `Market insight on: ${topic}`,
maxTokens: 200,
track: { tool: 'agent-trade.demo' },
@@ -112,7 +112,7 @@ export default wrap(async (req, res) => {
const url = new URL(req.url, 'http://x');
const env = tradeEnv();
- // Pre-flight check — JSON (not SSE) so the page can show the config overlay.
+ // Pre-flight check: JSON (not SSE) so the page can show the config overlay.
if (url.searchParams.get('check') === '1') {
return json(res, 200, {
configured: env.buyer.configured && env.seller.configured,
@@ -197,7 +197,7 @@ export default wrap(async (req, res) => {
);
emit('error', {
code: 'insufficient_funds',
- message: `Nexus has ${buyerBal.sol.toFixed(5)} SOL — needs ~${needed} SOL. Fund: ${env.buyer.address}`,
+ message: `Nexus has ${buyerBal.sol.toFixed(5)} SOL, needs ~${needed} SOL. Fund: ${env.buyer.address}`,
address: env.buyer.address,
network: env.network,
});
@@ -205,6 +205,22 @@ export default wrap(async (req, res) => {
return;
}
+ // Never move SOL for an analysis nobody can produce. Both lanes that can
+ // answer (Granite, then the platform LLM chain) are checked HERE, before
+ // the payment step: a lane failure discovered at step 6 has already cost
+ // the buyer real SOL, and the demo can only apologise for it.
+ const wx = watsonxConfig();
+ const leadProvider = providerChain()[0] || null;
+ if (!wx.configured && !leadProvider) {
+ emit('error', {
+ code: 'analysis_unavailable',
+ message:
+ 'Oracle has no analysis model configured, so the demo stopped before spending SOL on a skill it cannot deliver.',
+ });
+ res.end();
+ return;
+ }
+
// ── Step 2: Buyer requests skill ──────────────────────────────────
emit('request', {
from: 'Nexus',
@@ -294,8 +310,16 @@ export default wrap(async (req, res) => {
await sleep(800);
// ── Step 6: Oracle delivers analysis ─────────────────────────────
- const wx = watsonxConfig();
- const providerLabel = wx.configured ? 'IBM Granite' : 'Claude Haiku';
+ // The label names the lane that is actually about to run: the Granite
+ // model when watsonx is configured, otherwise the LEAD rung of the
+ // platform chain. It used to say "Claude Haiku" unconditionally, which
+ // the free-first chain in _lib/llm.js almost never selects, so the scene
+ // announced a model that never produced a word of the analysis. The
+ // `delivered` event below carries the provider that truly answered, and
+ // corrects the label if the chain failed over.
+ const providerLabel = wx.configured
+ ? wx.chatModel || 'IBM Granite'
+ : leadProvider.model || leadProvider.name;
emit('delivering', {
model: providerLabel,
message: `Oracle is analyzing with ${providerLabel}…`,
diff --git a/api/agent-trade/skill.js b/api/agent-trade/skill.js
index 0d31a94e6..f5aaec49a 100644
--- a/api/agent-trade/skill.js
+++ b/api/agent-trade/skill.js
@@ -1,4 +1,4 @@
-// GET /api/agent-trade/skill — Oracle agent's paid market-analysis skill.
+// GET /api/agent-trade/skill: Oracle agent's paid market-analysis skill.
//
// Without ?sig= → HTTP 402 with x402 price manifest:
// { x402:true, price:{sol,lamports}, currency:'SOL', recipient, network, memo }
@@ -7,8 +7,9 @@
// → Verifies payment on-chain, runs IBM Granite (or Claude fallback),
// returns { content, model, provider, topic, payment:{sig,lamports,blockTime} }
//
-// Independently callable by any agent — not coupled to the demo orchestrator.
+// Independently callable by any agent, not coupled to the demo orchestrator.
+import bs58 from 'bs58';
import { loadAvatarKeypair, getConnection, LAMPORTS_PER_SOL } from '../_lib/avatar-wallet.js';
import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';
import { llmComplete } from '../_lib/llm.js';
@@ -24,6 +25,20 @@ const MAX_PAYMENT_AGE_SEC = 300; // 5 minutes
const SIG_CONSUMED_TTL_SEC = 900; // 15 minutes
const sigConsumedKey = (sig) => `x402-skill-sig:${sig}`;
+// A Solana transaction signature is exactly 64 bytes of base58. Checking that
+// here, before any RPC work, keeps a junk `sig` from costing three getTransaction
+// round-trips plus two seconds of back-off per request, and from tripping the
+// shared RPC pool's per-method circuit breaker: an "Invalid param: WrongSize"
+// reply is indistinguishable, to the breaker, from a provider refusing the
+// method, so garbage input was demoting healthy RPC endpoints for other callers.
+function isSignatureShaped(sig) {
+ try {
+ return bs58.decode(sig).length === 64;
+ } catch {
+ return false;
+ }
+}
+
function skillConfig() {
const sellerSecret = process.env.AGENT_SELLER_SECRET || '';
const network =
@@ -54,7 +69,7 @@ function skillConfig() {
}
// Verify that sig is a confirmed Solana transfer of at least priceLamports to sellerAddress.
-// Retries 3× with 1s back-off — public RPC can lag after a fresh confirmation.
+// Retries 3x with 1s back-off, because public RPC can lag a fresh confirmation.
async function verifyPayment(connection, sig, { sellerAddress, priceLamports, buyerAddress }) {
let lastErr;
for (let attempt = 0; attempt < 3; attempt++) {
@@ -71,7 +86,17 @@ async function verifyPayment(connection, sig, { sellerAddress, priceLamports, bu
}
if (!tx?.meta) continue;
- const age = Date.now() / 1000 - (tx.blockTime || 0);
+ // No blockTime means the cluster cannot tell us WHEN this settled, so the
+ // freshness window is unenforceable and the payment cannot be accepted.
+ // Reporting that honestly matters: calling it "expired" sent buyers off to
+ // re-send a payment whose age was never the problem.
+ if (!tx.blockTime) {
+ throw Object.assign(new Error('transaction has no block time; cannot verify payment freshness'), {
+ code: 'bad_payment',
+ });
+ }
+
+ const age = Date.now() / 1000 - tx.blockTime;
if (age > MAX_PAYMENT_AGE_SEC) {
throw Object.assign(new Error('payment expired (>5 min old)'), {
code: 'payment_expired',
@@ -120,8 +145,8 @@ async function verifyPayment(connection, sig, { sellerAddress, priceLamports, bu
}
async function generateAnalysis(topic) {
- // The buyer has already paid on-chain by the time this runs — a watsonx
- // outage must not turn their purchase into an error, so a Granite failure
+ // The buyer has already paid on-chain by the time this runs, so a watsonx
+ // outage must not turn their purchase into an error: a Granite failure
// degrades to the platform LLM chain below instead of propagating.
const wx = watsonxConfig();
if (wx.configured) {
@@ -129,7 +154,7 @@ async function generateAnalysis(topic) {
const messages = [
{
role: 'user',
- content: `Provide a concise 2–3 sentence crypto market insight on: ${topic}. Be specific, data-driven, and actionable.`,
+ content: `Provide a concise 2 to 3 sentence crypto market insight on: ${topic}. Be specific, data-driven, and actionable.`,
},
];
const { text } = await watsonxChatComplete(wx, {
@@ -148,9 +173,9 @@ async function generateAnalysis(topic) {
}
// Platform LLM policy (api/_lib/llm.js): free providers first, paid keys as
- // the automatic last resort — a dead Anthropic key must not fail a paid call.
+ // the automatic last resort, so a dead Anthropic key cannot fail a paid call.
const { text, model, provider } = await llmComplete({
- system: 'You are a concise crypto market analyst. Respond in 2–3 sharp sentences.',
+ system: 'You are a concise crypto market analyst. Respond in 2 to 3 sharp sentences.',
user: `Market insight on: ${topic}`,
maxTokens: 200,
track: { tool: 'agent-trade.skill' },
@@ -199,7 +224,17 @@ export default wrap(async (req, res) => {
return;
}
- // Replay check first — a consumed signature never buys a second call, and
+ // Shape check before anything touches the chain (see isSignatureShaped).
+ if (!isSignatureShaped(sig)) {
+ return error(
+ res,
+ 402,
+ 'bad_payment',
+ 'sig must be a base58-encoded 64-byte Solana transaction signature',
+ );
+ }
+
+ // Replay check next: a consumed signature never buys a second call, and
// rejecting before verification saves the RPC round-trips.
const consumedKey = sigConsumedKey(sig);
if (await cacheGet(consumedKey)) {
@@ -231,7 +266,7 @@ export default wrap(async (req, res) => {
try {
analysis = await generateAnalysis(topic);
} catch (e) {
- // The buyer paid but got nothing — release the signature so a retry
+ // The buyer paid but got nothing, so release the signature and let a retry
// within the freshness window isn't treated as a replay.
await cacheDel(consumedKey).catch(() => {});
return error(res, 502, 'analysis_failed', e.message);
diff --git a/api/agent/caster-config.js b/api/agent/caster-config.js
index 35e6e1dd6..de950b0ba 100644
--- a/api/agent/caster-config.js
+++ b/api/agent/caster-config.js
@@ -2,45 +2,54 @@
//
// Generates a scoped API key for an agent and returns a ready-to-copy
// .env file + Docker run command for the agent-screen-caster service.
-// The key is stored hashed — this is the only time the plaintext is returned.
+// The key is stored hashed: this is the only time the plaintext is returned.
//
// Body: { agentId: string }
-// Auth: session cookie or bearer token
+// Auth: session cookie (CSRF-guarded) or a bearer token carrying the `profile`
+// scope. Same contract as api/api-keys.js, because this endpoint mints exactly
+// the same kind of live key.
-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { getSessionUser, authenticateBearer } from '../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { randomToken, sha256 } from '../_lib/crypto.js';
+import { isUuid } from '../_lib/validate.js';
import { sql } from '../_lib/db.js';
-// Mirrored from api/api-keys.js — same hashing, prefix, and storage.
-import { randomBytes, createHash } from 'crypto';
-
const CASTER_SCOPE = 'agents:read agents:write';
-function randomToken(len) {
- return randomBytes(len).toString('base64url').slice(0, len);
-}
-
-async function sha256(str) {
- return createHash('sha256').update(str).digest('hex');
-}
-
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const auth = await getSessionUser(req).catch(() => null)
- || await authenticateBearer(req).catch(() => null);
- if (!auth?.userId) return error(res, 401, 'unauthorized', 'sign in required');
+ // getSessionUser returns the user row (`id`), authenticateBearer takes the
+ // raw token and returns `{ userId, scope }`. Mixing the two shapes up is what
+ // made every call here answer 401 regardless of credentials.
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ if (bearer && !hasScope(bearer.scope, 'profile')) {
+ return error(res, 403, 'insufficient_scope', 'requires profile scope');
+ }
+ const userId = session?.id ?? bearer.userId;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ // Minting a live key off a cookie session is precisely the request worth
+ // forging cross-site, so the cookie lane carries the same CSRF guard as
+ // api/api-keys.js. requireCsrf is a no-op for bearer callers.
+ if (!(await requireCsrf(req, res, userId))) return;
- const body = await readJson(req, res);
- if (!body) return;
- const { agentId } = body;
- if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
+ const body = await readJson(req);
+ const agentId = typeof body?.agentId === 'string' ? body.agentId.trim() : '';
+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'valid agentId required');
// Confirm the caller owns this agent.
const [agentRow] = await sql`
SELECT id, name, display_name FROM agent_identities
- WHERE id = ${agentId} AND user_id = ${auth.userId} AND deleted_at IS NULL
+ WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL
`;
if (!agentRow) return error(res, 403, 'forbidden', 'not your agent');
@@ -50,16 +59,16 @@ export default wrap(async (req, res) => {
const rawToken = `sk_live_${randomToken(32)}`;
const prefix = rawToken.slice(0, 14);
const tokenHash = await sha256(rawToken);
- const keyName = `Screen Caster — ${agentName}`;
+ const keyName = `Screen Caster: ${agentName}`;
const [keyRow] = await sql`
INSERT INTO api_keys (user_id, name, token_hash, prefix, scope)
- VALUES (${auth.userId}, ${keyName}, ${tokenHash}, ${prefix}, ${CASTER_SCOPE})
+ VALUES (${userId}, ${keyName}, ${tokenHash}, ${prefix}, ${CASTER_SCOPE})
RETURNING id, created_at
`;
const envBlock = [
- `# Screen Caster — ${agentName}`,
+ `# Screen Caster: ${agentName}`,
`# Generated ${new Date().toISOString()}`,
``,
`AGENT_ID=${agentId}`,
diff --git a/api/agent/dreams.js b/api/agent/dreams.js
index d5e1ed4ee..89106c146 100644
--- a/api/agent/dreams.js
+++ b/api/agent/dreams.js
@@ -18,6 +18,7 @@ import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { isUuid } from '../_lib/validate.js';
import { decorateReflection } from '../_lib/reflection.js';
async function resolveAuth(req) {
@@ -29,8 +30,11 @@ async function resolveAuth(req) {
}
async function requireOwnedAgent(req, res, agentId, auth) {
- if (!agentId) {
- error(res, 400, 'validation_error', 'agentId required');
+ // Shape-check before the query: agent_identities.id is a uuid column, so a
+ // non-uuid id makes Postgres raise (22P02) and the request lands as a 500
+ // plus an ops alert, when the honest answer is a 400 the caller can act on.
+ if (!isUuid(agentId)) {
+ error(res, 400, 'validation_error', 'valid agentId required');
return null;
}
const [agent] = await sql`
@@ -133,11 +137,11 @@ async function handleReview(req, res, auth) {
if (!(await requireCsrf(req, res, auth.userId))) return;
const body = await readJson(req);
- const agentId = body.agentId || body.agent_id;
- const dreamId = body.dreamId || body.dream_id;
- const decision = body.decision;
+ const agentId = body?.agentId || body?.agent_id;
+ const dreamId = body?.dreamId || body?.dream_id;
+ const decision = body?.decision;
- if (!dreamId) return error(res, 400, 'validation_error', 'dreamId required');
+ if (!isUuid(dreamId)) return error(res, 400, 'validation_error', 'valid dreamId required');
if (!['accept', 'reject', 'answer'].includes(decision)) {
return error(res, 400, 'validation_error', "decision must be 'accept', 'reject', or 'answer'");
}
@@ -174,7 +178,7 @@ async function handleReview(req, res, auth) {
answer = typeof body.answer === 'string' ? body.answer.trim() : '';
if (!answer) return error(res, 400, 'validation_error', 'answer required for an answer decision');
answer = answer.slice(0, 2000);
- content = `${dream.statement} — ${answer}`;
+ content = `${dream.statement} (answer: ${answer})`;
}
const memType = ['user', 'feedback', 'project', 'reference'].includes(dream.proposed_type)
diff --git a/api/agent/launcher.js b/api/agent/launcher.js
index e37aff76c..63dc8af2e 100644
--- a/api/agent/launcher.js
+++ b/api/agent/launcher.js
@@ -21,6 +21,7 @@
import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { isUuid } from '../_lib/validate.js';
import { sql } from '../_lib/db.js';
// ── Auth helper ──────────────────────────────────────────────────────────────
@@ -38,7 +39,12 @@ async function resolveUserId(req) {
// ── Ownership check ───────────────────────────────────────────────────────────
+// agent_identities.id and agent_launcher_configs.id are uuid columns: an id that
+// isn't a uuid makes Postgres raise 22P02, which surfaces to the caller as a 500
+// (and pages ops) instead of the 400 that actually describes the mistake. Every
+// id reaching a query below is shape-checked first.
async function assertOwnsAgent(userId, agentId) {
+ if (!isUuid(agentId)) return false;
const [row] = await sql`
SELECT id FROM agent_identities
WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL
@@ -74,6 +80,7 @@ async function getConfigs(req, res, userId) {
const agentId = searchParams.get('agentId');
if (!agentId) return error(res, 400, 'missing_agent_id', 'agentId is required');
+ if (!isUuid(agentId)) return error(res, 400, 'invalid_agent_id', 'agentId must be a uuid');
if (!(await assertOwnsAgent(userId, agentId))) {
return error(res, 404, 'not_found', 'agent not found or not owned by you');
}
@@ -101,6 +108,10 @@ async function getConfigs(req, res, userId) {
async function triggerNow(req, res, userId, body) {
const { agentId, configId, network } = body || {};
if (!agentId) return error(res, 400, 'missing_agent_id', 'agentId is required');
+ if (!isUuid(agentId)) return error(res, 400, 'invalid_agent_id', 'agentId must be a uuid');
+ if (configId != null && !isUuid(configId)) {
+ return error(res, 400, 'invalid_config_id', 'configId must be a uuid');
+ }
if (!(await assertOwnsAgent(userId, agentId))) {
return error(res, 404, 'not_found', 'agent not found or not owned by you');
}
@@ -125,18 +136,19 @@ async function triggerNow(req, res, userId, body) {
}
const [config] = await query;
if (!config) return error(res, 404, 'not_found', 'launcher config not found');
- return json(res, 200, { ok: true, config, message: 'Launch scheduled — worker will fire within 60s' });
+ return json(res, 200, { ok: true, config, message: 'Launch scheduled. The worker fires within 60s.' });
}
// ── POST — upsert ────────────────────────────────────────────────────────────
async function upsertConfig(req, res, userId, body) {
- body = body ?? (await readJson(req));
-
+ // The body was already read by the dispatcher (a request stream can only be
+ // consumed once), so it arrives here parsed, or `{}` when it wasn't JSON.
const { agentId } = body || {};
if (!agentId || typeof agentId !== 'string') {
return error(res, 400, 'missing_agent_id', 'agentId is required');
}
+ if (!isUuid(agentId)) return error(res, 400, 'invalid_agent_id', 'agentId must be a uuid');
if (!(await assertOwnsAgent(userId, agentId))) {
return error(res, 404, 'not_found', 'agent not found or not owned by you');
}
@@ -306,6 +318,7 @@ async function deleteConfig(req, res, userId) {
const configId = searchParams.get('id');
if (!configId) return error(res, 400, 'missing_id', 'id is required');
+ if (!isUuid(configId)) return error(res, 400, 'invalid_id', 'id must be a uuid');
// Verify ownership transitively via agent_id
const [cfg] = await sql`
diff --git a/api/agent/reflect.js b/api/agent/reflect.js
index a72670aff..67f0db939 100644
--- a/api/agent/reflect.js
+++ b/api/agent/reflect.js
@@ -14,6 +14,7 @@ import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { isUuid } from '../_lib/validate.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { runReflection } from '../_lib/reflection.js';
@@ -36,8 +37,10 @@ export default wrap(async (req, res) => {
if (!(await requireCsrf(req, res, auth.userId))) return;
const body = await readJson(req);
- const agentId = body.agentId || body.agent_id;
- if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
+ const agentId = body?.agentId || body?.agent_id;
+ // agent_identities.id is a uuid column: a non-uuid would surface as a 500
+ // from Postgres (22P02) instead of the 400 the caller can actually fix.
+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'valid agentId required');
const [agent] = await sql`
SELECT id, user_id, name, description
diff --git a/api/agent/session.js b/api/agent/session.js
index fb05ea308..1d1ddab2c 100644
--- a/api/agent/session.js
+++ b/api/agent/session.js
@@ -7,7 +7,7 @@
//
// Response: {
// agentId, agentName, avatarUrl,
-// token, // JWT — paste into AGENT_BEARER_TOKEN
+// token, // JWT to paste into AGENT_BEARER_TOKEN
// expiresAt, // ISO string, 7 days from now
// commands: { node, docker } // ready-to-run launch strings
// }
@@ -17,11 +17,15 @@
import { SignJWT } from 'jose';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { isUuid } from '../_lib/validate.js';
import { env } from '../_lib/env.js';
import { sql } from '../_lib/db.js';
const SESSION_TTL_SEC = 60 * 60 * 24 * 7; // 7 days
+// Default watch target for the pump-monitor task: the platform's own coin.
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
function jwtKey() {
return new TextEncoder().encode(env.JWT_SECRET);
}
@@ -46,31 +50,46 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const auth = await getSessionUser(req).catch(() => null)
- // extractBearer yields the token string authenticateBearer expects —
- // passing the raw request object always threw inside and silently
- // disabled bearer auth on this endpoint (fail-closed, but a bug).
- || await authenticateBearer(extractBearer(req)).catch(() => null);
- if (!auth?.userId) return error(res, 401, 'unauthorized', 'sign in required');
+ // The two auth sources report the user id under DIFFERENT keys: a cookie
+ // session yields the users row (`id`), a bearer token yields `{ userId }`.
+ // Reading `userId` off the session result matched nothing, so every
+ // signed-in caller got a 401 and the watch panel's "generate session"
+ // button (src/shared/agent-watch-panel.js, cookie-only) could never mint a
+ // token. Read each source with its own key, and fall through to the bearer
+ // when the cookie resolves nothing. api/agent-screen-push.js, the endpoint
+ // this token is minted for, already does exactly this.
+ const session = await getSessionUser(req).catch(() => null);
+ const userId = session?.id
+ || (await authenticateBearer(extractBearer(req)).catch(() => null))?.userId
+ || null;
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
- const body = await readJson(req, res);
- if (!body) return;
+ // Bound the body: this is a two-field request, and passing `res` here as the
+ // limit disabled the size cap entirely (every comparison against an object
+ // is false), letting one caller stream an unbounded body into memory.
+ const body = await readJson(req, 4_000);
+ if (!body || typeof body !== 'object') {
+ return error(res, 400, 'validation_error', 'JSON object body required');
+ }
- const { agentId } = body;
- if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
+ const agentId = typeof body.agentId === 'string' ? body.agentId.trim() : '';
+ // agent_identities.id is a uuid column: an unvalidated string reaches
+ // Postgres as a 22P02 cast error, which surfaces as an unhandled 500 plus a
+ // Sentry event and an ops alert instead of the 400 the caller deserves.
+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'valid agentId required');
// Verify ownership and fetch agent details in one query.
const [agent] = await sql`
SELECT id, name, meta
FROM agent_identities
WHERE id = ${agentId}
- AND user_id = ${auth.userId}
+ AND user_id = ${userId}
AND deleted_at IS NULL
LIMIT 1
`;
if (!agent) return error(res, 403, 'forbidden', 'agent not found or not yours');
- const token = await mintCasterToken({ userId: auth.userId, agentId });
+ const token = await mintCasterToken({ userId, agentId });
const expiresAt = new Date(Date.now() + SESSION_TTL_SEC * 1000).toISOString();
const agentName = agent.name || 'Agent';
const avatarUrl = agent.meta?.studio?.avatar_glb_url
@@ -85,19 +104,26 @@ export default wrap(async (req, res) => {
`AGENT_BEARER_TOKEN="${token}"`,
`PUSH_URL="${pushUrl}"`,
`TASK=pump-monitor`,
- `TASK_ARG="FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"`,
+ `TASK_ARG="${THREE_MINT}"`,
`node services/agent-screen-caster/index.js`,
].join(' \\\n ');
+ // The container lane builds from the service's own Dockerfile, which is the
+ // path services/agent-screen-caster/README.md documents. There is no
+ // published registry image for this service, so naming one handed the
+ // operator a pull that can only fail.
const dockerCmd = [
- `docker run --rm`,
- ` -e AGENT_ID="${agentId}"`,
- ` -e AGENT_BEARER_TOKEN="${token}"`,
- ` -e PUSH_URL="${pushUrl}"`,
- ` -e TASK=pump-monitor`,
- ` -e TASK_ARG="FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"`,
- ` ghcr.io/nirholas/three-ws-agent-screen:latest`,
- ].join(' \\\n');
+ 'docker build -t agent-screen-caster services/agent-screen-caster',
+ [
+ `docker run --rm`,
+ ` -e AGENT_ID="${agentId}"`,
+ ` -e AGENT_BEARER_TOKEN="${token}"`,
+ ` -e PUSH_URL="${pushUrl}"`,
+ ` -e TASK=pump-monitor`,
+ ` -e TASK_ARG="${THREE_MINT}"`,
+ ` agent-screen-caster`,
+ ].join(' \\\n'),
+ ].join('\n\n');
return json(res, 200, {
agentId,
diff --git a/api/agent/wallet.js b/api/agent/wallet.js
index 48f30ea27..3f757bbbc 100644
--- a/api/agent/wallet.js
+++ b/api/agent/wallet.js
@@ -23,15 +23,22 @@ export default wrap(async (req, res) => {
res,
503,
'wallet_unconfigured',
- 'avatar wallet is not configured — set AVATAR_WALLET_SECRET (run scripts/gen-avatar-wallet.mjs)',
+ 'avatar wallet is not configured: set AVATAR_WALLET_SECRET (run scripts/gen-avatar-wallet.mjs)',
);
}
const connection = getConnection(cfg.rpcUrl);
- const [{ lamports, sol }, solPriceUsd] = await Promise.all([
- getSolBalance(connection, cfg.address),
+ // The RPC is a network boundary: a provider blip used to take the whole
+ // response down with a sanitized 500, so the chip lost the address, the
+ // explorer link and the send cap along with the balance. Report the balance
+ // as unknown instead and keep every configured field, so the widget can
+ // render "balance unavailable" over a wallet the user can still inspect.
+ const [balance, solPriceUsd] = await Promise.all([
+ getSolBalance(connection, cfg.address).catch(() => null),
solUsdPrice().catch(() => 0),
]);
+ const lamports = balance ? balance.lamports : null;
+ const sol = balance ? balance.sol : null;
return json(
res,
@@ -41,14 +48,16 @@ export default wrap(async (req, res) => {
network: cfg.network,
lamports,
sol,
- usd: solPriceUsd ? sol * solPriceUsd : null,
+ balanceAvailable: balance != null,
+ usd: sol != null && solPriceUsd ? sol * solPriceUsd : null,
solPriceUsd: solPriceUsd || null,
maxSendUsd: cfg.maxSendUsd,
defaultRecipient: cfg.defaultRecipient,
recipientLocked: cfg.lockRecipient,
explorer: explorerAccountUrl(cfg.address, cfg.network),
},
- // Short cache so the chip feels live without hammering the RPC.
- { 'Cache-Control': 'public, max-age=10' },
+ // Short cache so the chip feels live without hammering the RPC. A failed
+ // balance read is never cached: the next poll must be able to recover.
+ { 'Cache-Control': balance ? 'public, max-age=10' : 'no-store' },
);
});
diff --git a/api/agents/[id].js b/api/agents/[id].js
index e81057a8e..c63184ff6 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -16,6 +16,7 @@
* /api/agents/:id/sign — owner-only: sign message with server wallet
* /api/agents/:id/usage — owner-only: LLM usage stats
* /api/agents/:id/achievements — public: earned + locked achievements from real platform data
+ * /api/agents/:id/reserves — public: proof-of-reserves (alias of /solana/reserves)
*
* /api/agents/:id/livekit-token — GET short-lived LiveKit room JWT
* /api/agents/:id/embed — POST text → 1024-dim embedding vector
@@ -238,6 +239,14 @@ export default wrap(async function handler(req, res) {
return mod.handleReputation(req, res, id);
}
+ // Proof-of-reserves is documented at both /reserves and /solana/reserves (the
+ // latter dispatches from solana-wallet.js). Without this branch the short path
+ // fell through to handleGetOne and quietly answered with the agent record.
+ if (sub === 'reserves') {
+ const mod = await import('./_id/reserves.js');
+ return mod.handleReserves(req, res, id);
+ }
+
if (sub === 'achievements') {
const mod = await import('./_id/achievements.js');
return mod.handleAchievements(req, res, id);
diff --git a/api/agents/[id]/economy.js b/api/agents/[id]/economy.js
index 784ac6c5c..c55cae951 100644
--- a/api/agents/[id]/economy.js
+++ b/api/agents/[id]/economy.js
@@ -30,6 +30,7 @@ import { cors, json, method, wrap, error } from '../../_lib/http.js';
import { sql } from '../../_lib/db.js';
import { getSpendLimits, getDailySpendUsd } from '../../_lib/agent-trade-guards.js';
import { composeEarnings } from '../../_lib/economy-shape.js';
+import { isUuid } from '../../_lib/validate.js';
import { env } from '../../_lib/env.js';
// Skill prices are denominated in USDC (6 decimals) across the platform — the
@@ -57,6 +58,12 @@ export default wrap(async (req, res) => {
const id = url.searchParams.get('id') || url.pathname.split('/').filter(Boolean)[2];
const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ // vercel.json rewrites /api/agents/:id/economy straight here, so the uuid gate
+ // that api/agents/[id].js applies to its own sub-resources never runs. Without
+ // this, a malformed id reaches `WHERE id = $1` on a uuid column and Postgres
+ // 22P02 surfaces to the caller as a 500.
+ if (!isUuid(id)) return error(res, 404, 'not_found', 'agent not found');
+
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
diff --git a/api/agents/[id]/memory-seed-x.js b/api/agents/[id]/memory-seed-x.js
index 2c28464bf..a35a8e4f7 100644
--- a/api/agents/[id]/memory-seed-x.js
+++ b/api/agents/[id]/memory-seed-x.js
@@ -10,6 +10,7 @@ import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { env } from '../../_lib/env.js';
import { llmComplete } from '../../_lib/llm.js';
+import { isUuid } from '../../_lib/validate.js';
import { decryptToken, encryptToken } from '../../auth/x/[action].js';
// ── Token refresh ─────────────────────────────────────────────────────────────
@@ -212,6 +213,10 @@ export default wrap(async (req, res) => {
const agentId = req.query?.id;
if (!agentId) return error(res, 400, 'validation_error', 'agent id required');
+ // /api/agents/:id/memory/seed/x has its own vercel.json rewrite, so the uuid
+ // gate in api/agents/[id].js never runs for it. A malformed id would reach a
+ // uuid column and turn Postgres 22P02 into a 500.
+ if (!isUuid(agentId)) return error(res, 404, 'not_found', 'agent not found');
if (req.method === 'GET') return handleGet(req, res, agentId);
if (req.method === 'POST') return handlePost(req, res, agentId);
diff --git a/api/agents/[id]/pricing-rules.js b/api/agents/[id]/pricing-rules.js
index f4ca6af1f..bacd97668 100644
--- a/api/agents/[id]/pricing-rules.js
+++ b/api/agents/[id]/pricing-rules.js
@@ -1,6 +1,12 @@
/**
* Dynamic pricing rules for a specific agent skill.
*
+ * Every verb is owner-only: a rule set is a seller's unpublished strategy
+ * (scheduled discounts, deactivated experiments), not public catalog data. The
+ * price a buyer actually pays is resolved server-side by
+ * api/_lib/skill-pricing-rules.js and published through the public skill
+ * endpoints; nothing outside Creator Studio reads this one.
+ *
* Routes:
* GET /api/agents/:id/pricing-rules?skill=:skill list rules for skill
* POST /api/agents/:id/pricing-rules create rule
@@ -76,7 +82,13 @@ async function ownerCheck(req, res, agentId) {
async function handleList(req, res, agentId) {
if (!method(req, res, ['GET'])) return;
- const skill = req.query?.skill || null;
+ // Reads are gated too: the list includes deactivated rules and time windows
+ // that have not opened yet, which is the seller's pricing plan, not a price
+ // a buyer is entitled to see ahead of time.
+ if (!(await ownerCheck(req, res, agentId))) return;
+
+ const url = new URL(req.url, 'http://x');
+ const skill = req.query?.skill || url.searchParams.get('skill') || null;
const rules = await sql`
SELECT id, skill_name, rule_type, threshold, price_amount, currency_mint, chain,
@@ -135,6 +147,14 @@ async function handlePatch(req, res, agentId, ruleId) {
const { threshold, price_amount, start_at, end_at, priority, is_active } = parsed.data;
+ // start_at/end_at are nullable on purpose: sending an explicit null is how a
+ // seller reopens a time window that had a bound. COALESCE alone cannot express
+ // that — it reads an explicit null exactly like an omitted key and keeps the
+ // old timestamp, so the write returned 200 while silently discarding the
+ // clear. Distinguish "present and null" from "absent" before the query runs.
+ const clearStart = Object.hasOwn(parsed.data, 'start_at') && start_at === null;
+ const clearEnd = Object.hasOwn(parsed.data, 'end_at') && end_at === null;
+
const [existing] = await sql`
SELECT id FROM skill_pricing_rules WHERE id = ${ruleId} AND agent_id = ${agentId}
`;
@@ -144,8 +164,10 @@ async function handlePatch(req, res, agentId, ruleId) {
UPDATE skill_pricing_rules SET
threshold = COALESCE(${threshold ?? null}, threshold),
price_amount = COALESCE(${price_amount ?? null}, price_amount),
- start_at = COALESCE(${start_at !== undefined ? start_at : undefined}, start_at),
- end_at = COALESCE(${end_at !== undefined ? end_at : undefined}, end_at),
+ start_at = CASE WHEN ${clearStart}::boolean THEN NULL
+ ELSE COALESCE(${start_at ?? null}, start_at) END,
+ end_at = CASE WHEN ${clearEnd}::boolean THEN NULL
+ ELSE COALESCE(${end_at ?? null}, end_at) END,
priority = COALESCE(${priority ?? null}, priority),
is_active = COALESCE(${is_active ?? null}, is_active),
updated_at = now()
diff --git a/api/agents/[id]/skill-prices.js b/api/agents/[id]/skill-prices.js
index 162b17ebd..2da259c15 100644
--- a/api/agents/[id]/skill-prices.js
+++ b/api/agents/[id]/skill-prices.js
@@ -14,6 +14,7 @@ import { cors, error, json, method, readJson, wrap, rateLimited } from '../../_l
import { clientIp, limits } from '../../_lib/rate-limit.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { invalidateSkillPriceCache } from '../../_lib/skill-price-cache.js';
+import { isUuid } from '../../_lib/validate.js';
import { z } from 'zod';
const SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
@@ -71,6 +72,10 @@ export default wrap(async (req, res) => {
const parts = url.pathname.split('/').filter(Boolean);
const agentId = url.searchParams.get('id') || parts[2];
if (!agentId) return error(res, 400, 'validation_error', 'agent id required');
+ // This handler is reached by its own vercel.json rewrite, so the uuid gate in
+ // api/agents/[id].js never runs for it. A malformed id would otherwise hit a
+ // uuid column and turn Postgres 22P02 into a 500.
+ if (!isUuid(agentId)) return error(res, 404, 'not_found', 'agent not found');
const [agent] = await sql`
SELECT id, user_id FROM agent_identities
diff --git a/api/agents/[id]/skills-pricing.js b/api/agents/[id]/skills-pricing.js
index 2baac6155..1c679f73f 100644
--- a/api/agents/[id]/skills-pricing.js
+++ b/api/agents/[id]/skills-pricing.js
@@ -2,6 +2,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/au
import { cors, json, method, readJson, wrap, error, respondError } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { MonetizationService } from '../../_lib/services/MonetizationService.js';
+import { isUuid } from '../../_lib/validate.js';
import { z } from 'zod';
const SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
@@ -46,13 +47,19 @@ const pricingUpdateSchema = z.object({
export default wrap(async (req, res) => {
const url = new URL(req.url, 'http://x');
const parts = url.pathname.split('/').filter(Boolean);
- const id = parts[2];
+ const id = url.searchParams.get('id') || parts[2];
if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ // This handler has its own vercel.json rewrite, so the uuid gate in
+ // api/agents/[id].js never runs for it. A malformed id would reach a uuid
+ // column and surface Postgres 22P02 to the caller as a 500 whose `error` field
+ // was the raw SQLSTATE.
+ if (!isUuid(id)) return error(res, 404, 'not_found', 'agent not found');
+
// CSRF on state-changing session-cookie requests; bearer tokens are exempt.
if (req.method === 'PUT' && !(await requireCsrf(req, res, auth.userId))) return;
@@ -62,8 +69,14 @@ export default wrap(async (req, res) => {
try {
await service.assertOwnership(id);
} catch (e) {
- console.error('[agents/skills-pricing] ownership check failed', e?.message);
- return respondError(res, e.status || 500, e.code || 'error', e);
+ // A 404/403 here is the gate doing its job, not an incident: log only when
+ // something genuinely broke, and never echo a driver error code back to the
+ // caller as if it were this API's error contract.
+ if (!e?.status || e.status >= 500) {
+ console.error('[agents/skills-pricing] ownership check failed', e?.message);
+ return respondError(res, 500, 'error', e);
+ }
+ return respondError(res, e.status, e.code || 'error', e);
}
if (req.method === 'GET') return handleGet(req, res, service, id);
diff --git a/api/agents/_id/brain.js b/api/agents/_id/brain.js
index be387a925..152d8c2f3 100644
--- a/api/agents/_id/brain.js
+++ b/api/agents/_id/brain.js
@@ -416,12 +416,28 @@ async function importBundle(req, res, agent, userId) {
return error(res, 422, 'integrity_failed', `memory ${forged.id} has an invalid signature (${forged.reason})`);
}
- // Diff against the target agent's existing memories (by content_hash) so a
- // merge is idempotent and the response is a real, reviewable diff.
+ // Diff against the target agent's existing memories so a merge is idempotent
+ // and the response is a real, reviewable diff.
+ //
+ // Two hashes per row, and both are load-bearing. A row's own `content_hash` is
+ // the digest of THAT row (memoryDigest folds in the row id and created_at), so
+ // an imported copy hashes differently from the bundle entry it came from: on a
+ // re-import the source hash would miss every time and the merge would insert a
+ // fresh duplicate of every memory, forever. The source digest recorded in
+ // provenance at import time is the stable key across that boundary, so match on
+ // either.
const existing = await sql`
- SELECT content_hash FROM agent_memories WHERE agent_id = ${agent.id} AND content_hash IS NOT NULL
+ SELECT content_hash, context->'provenance'->>'source_content_hash' AS source_hash
+ FROM agent_memories
+ WHERE agent_id = ${agent.id}
+ AND (content_hash IS NOT NULL OR context->'provenance'->>'source_content_hash' IS NOT NULL)
`;
- const existingHashes = new Set(existing.map((r) => r.content_hash?.toLowerCase()).filter(Boolean));
+ const existingHashes = new Set(
+ existing
+ .flatMap((r) => [r.content_hash, r.source_hash])
+ .filter(Boolean)
+ .map((h) => h.toLowerCase()),
+ );
if (body.strategy === 'replace') {
await sql`DELETE FROM agent_memories WHERE agent_id = ${agent.id}`;
@@ -446,11 +462,14 @@ async function importBundle(req, res, agent, userId) {
existingHashes.add(hash);
// Preserve the original authorship as provenance; the new agent re-signs
- // for its own chain of custody (handled after insert).
+ // for its own chain of custody (handled after insert). `source_content_hash`
+ // doubles as the dedupe key above, so record the digest actually matched on
+ // rather than the bundle's optional field: an entry that shipped without one
+ // would otherwise leave the next re-import nothing to match against.
const provenance = {
source_agent_id: bundle.agent.id,
source_memory_id: m.id,
- source_content_hash: m.content_hash || null,
+ source_content_hash: hash,
source_signature: m.signature || null,
source_signer_address: m.signer_address || null,
};
diff --git a/api/agents/_id/embed.js b/api/agents/_id/embed.js
index 5820915b8..8241be7fe 100644
--- a/api/agents/_id/embed.js
+++ b/api/agents/_id/embed.js
@@ -1,44 +1,30 @@
// POST /api/agents/:id/embed
-// Generates a 1024-dim text embedding. Used by AgentMemory.recall() for
-// semantic similarity search.
+// Generates a text embedding. Used by AgentMemory.recall() for semantic
+// similarity search.
//
-// Provider policy mirrors api/_lib/llm.js: the FREE lane leads — NVIDIA NIM's
-// baai/bge-m3 (1024-dim, one free nvapi key) — and paid Voyage (voyage-3-lite,
-// also 1024-dim) is only a keyed fallback. The response carries the `model`
-// that produced the vector: embeddings from different models live in different
-// vector spaces, so callers that persist vectors should store the model id
-// alongside them and only compare like with like.
+// Provider policy is NOT restated here: it is delegated to api/_lib/embeddings.js,
+// the platform's single embedder registry (free NVIDIA NIM nv-embedqa-e5-v5 first,
+// then the GCP-credit-funded Vertex lane, then OpenAI as the paid backstop). That
+// module exists to prevent one specific trap: embeddings from different models are
+// different vector spaces, and comparing across them yields plausible-looking
+// garbage. So the response carries the registry's `embedder` tag (model + dim,
+// e.g. "nvidia/nv-embedqa-e5-v5@1024"). Callers that persist a vector must persist
+// that tag beside it and only compare vectors sharing one.
+//
+// `inputType` matters for the same reason: NIM's retrieval models are asymmetric.
+// Search strings embed as 'query' (the default, matching recall()); corpus text
+// being stored for later retrieval embeds as 'passage'.
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';
import { cors, json, method, readJson, error, rateLimited } from '../../_lib/http.js';
import { limits } from '../../_lib/rate-limit.js';
import { sql } from '../../_lib/db.js';
-import { env } from '../../_lib/env.js';
-
-// Ordered free-first. Both produce 1024-dim vectors, matching this endpoint's
-// documented contract.
-function embedProviderChain() {
- const chain = [];
- if (env.NVIDIA_API_KEY) {
- chain.push({
- name: 'nvidia',
- model: 'baai/bge-m3',
- url: 'https://integrate.api.nvidia.com/v1/embeddings',
- key: env.NVIDIA_API_KEY,
- buildBody: (text) => ({ model: 'baai/bge-m3', input: [text] }),
- });
- }
- if (env.VOYAGE_API_KEY) {
- chain.push({
- name: 'voyage',
- model: 'voyage-3-lite',
- url: 'https://api.voyageai.com/v1/embeddings',
- key: env.VOYAGE_API_KEY,
- buildBody: (text) => ({ model: 'voyage-3-lite', input: [text], input_type: 'query' }),
- });
- }
- return chain;
-}
+import {
+ embedWith,
+ embedderInfo,
+ defaultIngestEmbedderTag,
+ embedderConfigured,
+} from '../../_lib/embeddings.js';
export async function handleEmbed(req, res, id) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
@@ -76,47 +62,46 @@ export async function handleEmbed(req, res, id) {
if (text.length > 8192) {
return error(res, 400, 'validation_error', 'text exceeds 8192 character limit');
}
-
- const chain = embedProviderChain();
- if (!chain.length) {
- return error(res, 503, 'not_configured',
- 'No embedding provider configured. Set NVIDIA_API_KEY (free) or VOYAGE_API_KEY.');
+ const inputType = body?.inputType ?? 'query';
+ if (inputType !== 'query' && inputType !== 'passage') {
+ return error(res, 400, 'validation_error', "inputType must be 'query' or 'passage'");
}
- let lastStatus = 0;
- for (const p of chain) {
- let upstream;
- try {
- upstream = await fetch(p.url, {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- authorization: `Bearer ${p.key}`,
- },
- body: JSON.stringify(p.buildBody(text.trim())),
- signal: AbortSignal.timeout(15_000),
- });
- } catch (err) {
- console.error(`[embed] ${p.name} unreachable`, err?.message);
- lastStatus = 502;
- continue;
+ // An explicit `embedder` lets a caller re-embed into the same space its stored
+ // vectors already live in, which is the whole point of tagging them.
+ const requested = body?.embedder;
+ let tag;
+ if (requested) {
+ if (!embedderInfo(requested)) {
+ return error(res, 400, 'validation_error', `unknown embedder: ${requested}`);
}
- if (!upstream.ok) {
- const msg = await upstream.text().catch(() => '');
- console.error(`[embed] ${p.name} error`, upstream.status, msg.slice(0, 200));
- lastStatus = upstream.status;
- continue;
+ if (!embedderConfigured(requested)) {
+ return error(res, 503, 'not_configured', `embedder ${requested} is not configured on this server`);
}
- const data = await upstream.json();
- const embedding = data?.data?.[0]?.embedding;
- if (!Array.isArray(embedding)) {
- console.error(`[embed] ${p.name} unexpected response shape`);
- lastStatus = 502;
- continue;
+ tag = requested;
+ } else {
+ tag = defaultIngestEmbedderTag();
+ if (!tag) {
+ return error(res, 503, 'not_configured',
+ 'No embedding provider configured. Set NVIDIA_API_KEY (free), GOOGLE_CLOUD_PROJECT, or OPENAI_API_KEY.');
}
- return json(res, 200, { embedding, model: p.model, provider: p.name });
}
- return error(res, 502, 'upstream_error',
- `embedding service unavailable (last upstream status ${lastStatus})`);
+ const info = embedderInfo(tag);
+ let vector;
+ try {
+ [vector] = await embedWith(tag, [text.trim()], inputType);
+ } catch (err) {
+ console.error('[embed] provider failed', tag, err?.message);
+ return error(res, 502, 'upstream_error', `embedding service unavailable (${info.provider})`);
+ }
+
+ return json(res, 200, {
+ embedding: Array.from(vector),
+ embedder: info.tag,
+ model: info.model,
+ provider: info.provider,
+ dim: info.dim,
+ inputType,
+ });
}
diff --git a/api/agents/_id/memory-seed-farcaster.js b/api/agents/_id/memory-seed-farcaster.js
index 3e8c2e10c..271b98201 100644
--- a/api/agents/_id/memory-seed-farcaster.js
+++ b/api/agents/_id/memory-seed-farcaster.js
@@ -20,9 +20,12 @@ const bodySchema = z
const NEYNAR_BASE = 'https://api.neynar.com/v2/farcaster';
const SEED_COOLDOWN_MS = 6 * 60 * 60 * 1000;
+const NEYNAR_TIMEOUT_MS = 15_000;
+
async function neynarGet(path, apiKey) {
const resp = await fetch(`${NEYNAR_BASE}${path}`, {
headers: { api_key: apiKey },
+ signal: AbortSignal.timeout(NEYNAR_TIMEOUT_MS),
});
if (!resp.ok) {
const err = new Error(`Neynar ${resp.status}`);
@@ -32,7 +35,7 @@ async function neynarGet(path, apiKey) {
return resp.json();
}
-async function distillFacts(profile, casts, apiKey) {
+async function distillFacts(profile, casts) {
const castTexts = casts
.slice(0, 50)
.map((c) => c.text || '')
@@ -150,11 +153,23 @@ export default wrap(async (req, res) => {
if (!fid) return error(res, 404, 'farcaster_user_not_found', 'Farcaster user not found');
}
- // Fetch casts and profile in parallel
- const [castsData, profileData] = await Promise.all([
- neynarGet(`/feed/user/casts?fid=${fid}&limit=50&include_replies=false`, env.NEYNAR_API_KEY),
- neynarGet(`/user?fid=${fid}`, env.NEYNAR_API_KEY),
- ]);
+ // Fetch casts and profile in parallel. A Neynar outage is an upstream failure,
+ // not an internal one: neynarGet tags its error with `httpStatus`, which wrap()
+ // does not read (it reads `status`), so an uncaught throw here surfaced as a
+ // bare 500 plus an ops alert for somebody else's downtime.
+ let castsData;
+ let profileData;
+ try {
+ [castsData, profileData] = await Promise.all([
+ neynarGet(`/feed/user/casts?fid=${fid}&limit=50&include_replies=false`, env.NEYNAR_API_KEY),
+ neynarGet(`/user?fid=${fid}`, env.NEYNAR_API_KEY),
+ ]);
+ } catch (e) {
+ if (e.httpStatus === 404)
+ return error(res, 404, 'farcaster_user_not_found', 'Farcaster user not found');
+ console.error('[memory-seed-farcaster] Neynar fetch failed', e?.message);
+ return error(res, 502, 'upstream_error', 'Farcaster data is unavailable right now');
+ }
const casts = castsData?.casts ?? [];
const profile = profileData?.users?.[0] ?? profileData?.user ?? {};
diff --git a/api/agents/_id/memory/[cid].js b/api/agents/_id/memory/[cid].js
index 8fda68b18..d344fe05f 100644
--- a/api/agents/_id/memory/[cid].js
+++ b/api/agents/_id/memory/[cid].js
@@ -16,17 +16,28 @@ const CID_RE = /^[a-zA-Z0-9]+$/;
// it to avoid streaming an arbitrary-size body back through the proxy.
const MAX_BYTES = 512 * 1024;
+// A public gateway can hang indefinitely on an unpinned CID. Without a deadline
+// the request holds a server slot until Cloud Run kills it, and three of those in
+// series is three times the wait — bound each attempt so the chain can actually
+// reach the next gateway.
+const GATEWAY_TIMEOUT_MS = 12_000;
+
+// Returns the first gateway response that carries the file, or null when every
+// gateway refused. The caller turns that into a 502: a public-gateway outage is
+// an upstream failure, not an internal one, and the old `throw` surfaced it as a
+// bare 500 (and threw `undefined` outright when every gateway answered with a
+// non-ok status rather than a network error).
async function fetchFromIPFS(cid) {
- let lastErr;
for (const gw of IPFS_GATEWAYS) {
try {
- const resp = await fetch(gw + cid);
+ const resp = await fetch(gw + cid, { signal: AbortSignal.timeout(GATEWAY_TIMEOUT_MS) });
if (resp.ok) return resp;
+ console.warn(`[memory/cid] ${gw} returned ${resp.status} for ${cid}`);
} catch (err) {
- lastErr = err;
+ console.warn(`[memory/cid] ${gw} unreachable for ${cid}: ${err?.message}`);
}
}
- throw lastErr || new Error('All IPFS gateways failed for ' + cid);
+ return null;
}
// GET /api/agents/:id/memory/:cid
@@ -65,6 +76,9 @@ export default wrap(async (req, res) => {
if (!pin) return error(res, 404, 'not_found', 'memory file not found for this agent');
const ipfsResp = await fetchFromIPFS(cid);
+ if (!ipfsResp) {
+ return error(res, 502, 'upstream_error', 'no IPFS gateway could serve this memory file');
+ }
// Bound the proxied body. Trust the gateway's Content-Length when present, then
// re-check the materialized buffer (a lying header can't exceed the real cap).
diff --git a/api/agents/_id/memory/pin.js b/api/agents/_id/memory/pin.js
index c51b6a1dd..a45d03ec4 100644
--- a/api/agents/_id/memory/pin.js
+++ b/api/agents/_id/memory/pin.js
@@ -14,7 +14,15 @@ const bodySchema = z.object({
.min(1)
.max(260)
.regex(/^[A-Za-z0-9._-]+$/, 'invalid filename characters'),
- data: z.string().min(1), // base64-encoded bytes (encrypted or plaintext for MEMORY.md)
+ // base64-encoded bytes (encrypted, or plaintext for MEMORY.md). `Buffer.from`
+ // never throws on malformed base64 — it silently drops the invalid characters
+ // — so garbage would otherwise be pinned to IPFS as a valid-looking CID. The
+ // shape is enforced here, before any byte reaches a pinning provider.
+ data: z
+ .string()
+ .min(1)
+ .regex(/^[A-Za-z0-9+/\r\n]+={0,2}$/, 'data must be base64')
+ .refine((s) => s.replace(/[\r\n]/g, '').length % 4 === 0, 'data must be base64'),
});
async function pinViaPinata(buf, filename) {
@@ -58,11 +66,9 @@ export default wrap(async (req, res) => {
const body = parse(bodySchema, await readJson(req));
- let buf;
- try {
- buf = Buffer.from(body.data, 'base64');
- } catch {
- return error(res, 400, 'validation_error', 'data must be valid base64');
+ const buf = Buffer.from(body.data, 'base64');
+ if (buf.byteLength === 0) {
+ return error(res, 400, 'validation_error', 'data decodes to zero bytes');
}
if (buf.byteLength > MAX_BYTES) {
return error(res, 413, 'payload_too_large', 'file exceeds 512 KB limit');
diff --git a/api/agents/_id/mood.js b/api/agents/_id/mood.js
index ff115bfbc..b38b2be82 100644
--- a/api/agents/_id/mood.js
+++ b/api/agents/_id/mood.js
@@ -16,7 +16,8 @@
import { sql } from '../../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer, isSameSiteOrigin } from '../../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';
+import { limits } from '../../_lib/rate-limit.js';
import { parse } from '../../_lib/validate.js';
import { z } from 'zod';
import { BASELINE, clampSensitivity, moodLabel, SIGNALS } from '../../../src/agents/mood-model.js';
@@ -84,6 +85,14 @@ export const handleMood = wrap(async (req, res, id, action) => {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ // Every mood POST appends a permanent agent_mood_history row, so the writes
+ // need the same per-user ceiling the sibling persona writes carry. Reads are
+ // a bounded single query and stay unmetered here.
+ if (req.method === 'POST') {
+ const rl = await limits.widgetWrite(auth.userId);
+ if (!rl.success) return rateLimited(res, rl, 'too many mood updates, slow down');
+ }
+
const [agent] = await sql`
SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
`;
diff --git a/api/agents/_id/payments.js b/api/agents/_id/payments.js
index 418b47585..583a47470 100644
--- a/api/agents/_id/payments.js
+++ b/api/agents/_id/payments.js
@@ -2,6 +2,7 @@ import { sql } from '../../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { isUuid } from '../../_lib/validate.js';
async function resolveAuth(req) {
const session = await getSessionUser(req);
@@ -31,45 +32,78 @@ export const handlePayments = wrap(async (req, res, id) => {
const url = new URL(req.url, 'http://x');
const direction = url.searchParams.get('direction') === 'received' ? 'received' : 'sent';
- const limit = Math.min(parseInt(url.searchParams.get('limit') || '20', 10), 100);
- const cursor = url.searchParams.get('cursor') || null;
- let rows;
- if (direction === 'sent') {
- rows = await sql`
- select
- ap.id, ap.payer_agent_id, ap.payee_agent_id,
- ap.amount_wei, ap.chain_id, ap.tx_hash, ap.memo, ap.status, ap.created_at,
- ms.name as skill_name, ms.slug as skill_slug,
- payee.name as payee_name
- from agent_payments ap
- left join marketplace_skills ms on ms.id = ap.skill_id
- left join agent_identities payee on payee.id = ap.payee_agent_id
- where ap.payer_agent_id = ${id}
- and (${cursor}::uuid is null or ap.id < ${cursor}::uuid)
- order by ap.created_at desc
- limit ${limit + 1}
- `;
- } else {
- rows = await sql`
- select
- ap.id, ap.payer_agent_id, ap.payee_agent_id,
- ap.amount_wei, ap.chain_id, ap.tx_hash, ap.memo, ap.status, ap.created_at,
- ms.name as skill_name, ms.slug as skill_slug,
- payer.name as payer_name
- from agent_payments ap
- left join marketplace_skills ms on ms.id = ap.skill_id
- left join agent_identities payer on payer.id = ap.payer_agent_id
- where ap.payee_agent_id = ${id}
- and (${cursor}::uuid is null or ap.id < ${cursor}::uuid)
- order by ap.created_at desc
- limit ${limit + 1}
- `;
+ // `parseInt` yields NaN on a non-numeric limit and a negative on `?limit=-5`,
+ // both of which reached Postgres as `LIMIT NaN` / `LIMIT -4` and 500'd the
+ // endpoint. Clamp to the supported window instead.
+ const rawLimit = parseInt(url.searchParams.get('limit') || '20', 10);
+ const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 100) : 20;
+
+ // Cursor format: `<iso_timestamp>|<uuid>`, matching the agent action log
+ // (api/agents/_id/_sub.js). The rows are ordered by `created_at`, so the old
+ // `id < cursor` keyset compared random v4 uuids against a timestamp ordering
+ // and silently skipped or repeated rows across pages; the id is only the
+ // tiebreaker for rows sharing a `created_at`. A malformed cursor used to hit
+ // Postgres as an invalid uuid literal and 500 — it is validated here instead.
+ const rawCursor = url.searchParams.get('cursor');
+ let cursorTs = null;
+ let cursorId = null;
+ if (rawCursor) {
+ const pipe = rawCursor.indexOf('|');
+ const ts = pipe > 0 ? rawCursor.slice(0, pipe) : rawCursor;
+ const rowId = pipe > 0 ? rawCursor.slice(pipe + 1) : null;
+ if (Number.isNaN(Date.parse(ts)) || (rowId !== null && !isUuid(rowId))) {
+ return error(res, 400, 'validation_error', 'cursor must be `<iso_timestamp>|<uuid>`');
+ }
+ cursorTs = ts;
+ cursorId = rowId;
}
+ const rows =
+ direction === 'sent'
+ ? await sql`
+ select
+ ap.id, ap.payer_agent_id, ap.payee_agent_id,
+ ap.amount_wei, ap.chain_id, ap.tx_hash, ap.memo, ap.status, ap.created_at,
+ ms.name as skill_name, ms.slug as skill_slug,
+ payee.name as payee_name
+ from agent_payments ap
+ left join marketplace_skills ms on ms.id = ap.skill_id
+ left join agent_identities payee on payee.id = ap.payee_agent_id
+ where ap.payer_agent_id = ${id}
+ and (
+ ${cursorTs}::timestamptz is null
+ or ap.created_at < ${cursorTs}::timestamptz
+ or (ap.created_at = ${cursorTs}::timestamptz
+ and (${cursorId}::uuid is null or ap.id < ${cursorId}::uuid))
+ )
+ order by ap.created_at desc, ap.id desc
+ limit ${limit + 1}
+ `
+ : await sql`
+ select
+ ap.id, ap.payer_agent_id, ap.payee_agent_id,
+ ap.amount_wei, ap.chain_id, ap.tx_hash, ap.memo, ap.status, ap.created_at,
+ ms.name as skill_name, ms.slug as skill_slug,
+ payer.name as payer_name
+ from agent_payments ap
+ left join marketplace_skills ms on ms.id = ap.skill_id
+ left join agent_identities payer on payer.id = ap.payer_agent_id
+ where ap.payee_agent_id = ${id}
+ and (
+ ${cursorTs}::timestamptz is null
+ or ap.created_at < ${cursorTs}::timestamptz
+ or (ap.created_at = ${cursorTs}::timestamptz
+ and (${cursorId}::uuid is null or ap.id < ${cursorId}::uuid))
+ )
+ order by ap.created_at desc, ap.id desc
+ limit ${limit + 1}
+ `;
+
const hasMore = rows.length > limit;
const page = hasMore ? rows.slice(0, limit) : rows;
- const nextCursor = hasMore ? page[page.length - 1].id : null;
+ const last = page[page.length - 1];
+ const nextCursor = hasMore && last ? `${new Date(last.created_at).toISOString()}|${last.id}` : null;
return json(res, 200, { payments: page, next_cursor: nextCursor, direction });
});
diff --git a/api/agents/_id/reputation.js b/api/agents/_id/reputation.js
index c6562b0cb..7c8e76937 100644
--- a/api/agents/_id/reputation.js
+++ b/api/agents/_id/reputation.js
@@ -7,7 +7,7 @@
// score is a trust signal others rely on, so owner and visitor see the same
// number; only the owner additionally receives the `guidance` block.
-import { cors, json, error, method, wrap, rateLimited } from '../../_lib/http.js';
+import { cors, json, error, method, wrap, rateLimited, varyOn } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { getRedis } from '../../_lib/redis.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
@@ -82,5 +82,16 @@ export const handleReputation = wrap(async (req, res, agentId) => {
const payload = { ...result, is_owner: isOwner };
if (!isOwner) delete payload.guidance;
- return json(res, 200, payload, { 'cache-control': 'public, max-age=60, stale-while-revalidate=300' });
+ // The score is public, but `is_owner` and the owner-only `guidance` block make
+ // an authenticated response personal. A shared cache (Cloud CDN fronts /api/*)
+ // keys on the URL, so serving that under `public` would hand one owner's
+ // guidance to the next anonymous reader. Vary tells compliant caches the
+ // credential is part of the key; the private/no-store branch is the belt to
+ // that suspenders for caches that ignore it.
+ varyOn(res, 'Cookie', 'Authorization');
+ return json(res, 200, payload, {
+ 'cache-control': userId
+ ? 'private, no-store'
+ : 'public, max-age=60, stale-while-revalidate=300',
+ });
});
diff --git a/api/agents/_id/reserves.js b/api/agents/_id/reserves.js
index 1bbc443e6..92517d7e1 100644
--- a/api/agents/_id/reserves.js
+++ b/api/agents/_id/reserves.js
@@ -12,7 +12,7 @@
// timestamp — never a stale "verified now". All compute lives in
// api/_lib/trust/proof-of-reserves.js.
-import { cors, json, error, method, wrap, rateLimited } from '../../_lib/http.js';
+import { cors, json, error, method, wrap, rateLimited, varyOn } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
import { sql } from '../../_lib/db.js';
@@ -63,6 +63,13 @@ export const handleReserves = wrap(async (req, res, agentId) => {
}
// Reserves are live; flows are a paginated ledger window. Short public cache so
- // the "verify on-chain" claim stays close to real-time.
- return json(res, 200, payload, { 'cache-control': 'public, max-age=30, stale-while-revalidate=120' });
+ // the "verify on-chain" claim stays close to real-time — but only for the
+ // anonymous variant. The payload echoes `is_owner`, so an authenticated read is
+ // personal and must never land in the shared CDN cache under this URL.
+ varyOn(res, 'Cookie', 'Authorization');
+ return json(res, 200, payload, {
+ 'cache-control': userId
+ ? 'private, no-store'
+ : 'public, max-age=30, stale-while-revalidate=120',
+ });
});
diff --git a/api/agents/_id/unlocks.js b/api/agents/_id/unlocks.js
index 153b363d7..3961a6ff6 100644
--- a/api/agents/_id/unlocks.js
+++ b/api/agents/_id/unlocks.js
@@ -14,7 +14,7 @@
// Real capability gates (e.g. the arena elite floor) call requireUnlock() from the
// protected route itself; this endpoint is the read + the cosmetic-claim surface.
-import { cors, json, error, method, wrap, rateLimited, readJson } from '../../_lib/http.js';
+import { cors, json, error, method, wrap, rateLimited, readJson, varyOn } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { getSessionUser } from '../../_lib/auth.js';
import { requireCsrf } from '../../_lib/csrf.js';
@@ -46,11 +46,19 @@ export const handleUnlocks = wrap(async (req, res, agentId, action) => {
isOwner = Boolean(own);
}
+ // `is_owner` gates the client's claim controls, so an authenticated read is
+ // personal: only the anonymous variant may sit in the shared CDN cache
+ // under this URL. Vary states the credential is part of the cache key.
+ varyOn(res, 'Cookie', 'Authorization');
return json(
res,
200,
{ ...payload, is_owner: isOwner },
- { 'cache-control': 'public, max-age=30, stale-while-revalidate=180' },
+ {
+ 'cache-control': userId
+ ? 'private, no-store'
+ : 'public, max-age=30, stale-while-revalidate=180',
+ },
);
}
diff --git a/api/agents/a2a-hire.js b/api/agents/a2a-hire.js
index 11164bf10..392f62fe5 100644
--- a/api/agents/a2a-hire.js
+++ b/api/agents/a2a-hire.js
@@ -116,7 +116,9 @@ export default wrap(async (req, res) => {
// a frame write must NEVER block or fail a real settlement.
let hireRow = null;
let baseCtx = {}; // filled once the offer resolves; merged into every phase
- const limits = getSpendLimits(hirer.meta);
+ // NOT named `limits`: that shadows the rate-limit import used above, which put
+ // the whole handler in a temporal dead zone and 500'd every authenticated hire.
+ const spendPolicy = getSpendLimits(hirer.meta);
const pushPhase = (phase, extra = {}) => {
const frame = hirePhaseFrame(phase, {
...baseCtx,
@@ -132,8 +134,8 @@ export default wrap(async (req, res) => {
const m = hireCapMath({
usd: priceUsd,
maxUsd: typeof maxUsd === 'number' ? maxUsd : null,
- perTxUsd: limits.per_tx_usd,
- dailyUsd: limits.daily_usd,
+ perTxUsd: spendPolicy.per_tx_usd,
+ dailyUsd: spendPolicy.daily_usd,
dailySpentUsd,
});
return {
diff --git a/api/agents/agent-trade.js b/api/agents/agent-trade.js
index a97dd6ef6..c45813698 100644
--- a/api/agents/agent-trade.js
+++ b/api/agents/agent-trade.js
@@ -816,6 +816,9 @@ async function handleLimits(req, res, id) {
let body;
try { body = await readJson(req); } catch (e) { return error(res, 400, 'bad_request', e?.message || 'invalid request body'); }
+ const invalid = validateLimitsPatch(body);
+ if (invalid) return error(res, 400, 'validation_error', invalid);
+
try {
const next = await setTradeLimits(id, auth.userId, body, { req });
return json(res, 200, { data: { limits: next } });
@@ -825,6 +828,35 @@ async function handleLimits(req, res, id) {
}
}
+// Reject a bad limits patch instead of letting it through. normalizeTradeLimits
+// coerces anything it cannot read into "no cap" / the default, so an unvalidated
+// `{"per_trade_sol": -1}` (or a typo, or a string) SILENTLY DELETES the owner's
+// existing per-trade ceiling and answers 200 as if it had tightened it. A spend
+// guardrail must never be relaxed by an input the server could not parse: the
+// only way to clear a cap is to send it as an explicit null.
+const LIMIT_RANGES = {
+ per_trade_sol: { min: 0, max: 1e6, label: 'per_trade_sol must be a positive number of SOL, or null to clear the cap' },
+ daily_budget_sol: { min: 0, max: 1e6, label: 'daily_budget_sol must be a positive number of SOL, or null to clear the budget' },
+ max_price_impact_pct: { min: 0, max: 100, label: 'max_price_impact_pct must be a number between 0 and 100' },
+ max_slippage_bps: { min: 0, max: 10000, label: 'max_slippage_bps must be a number between 0 and 10000' },
+ max_concurrent: { min: 1, max: 10000, label: 'max_concurrent must be a whole number of at least 1, or null for no ceiling' },
+};
+
+function validateLimitsPatch(patch) {
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) return 'body must be a JSON object of limit fields';
+ for (const [key, range] of Object.entries(LIMIT_RANGES)) {
+ if (!(key in patch)) continue;
+ const v = patch[key];
+ if (v === null) continue; // explicit clear
+ const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN;
+ if (!Number.isFinite(n) || n < range.min || n > range.max) return range.label;
+ }
+ if ('kill_switch' in patch && typeof patch.kill_switch !== 'boolean') {
+ return 'kill_switch must be true or false';
+ }
+ return null;
+}
+
function boundaryError(res, e) {
if (e?.isBoundary) return error(res, e.status, e.code, e.message, e.detail && Object.keys(e.detail).length ? { detail: e.detail } : {});
return error(res, 500, 'internal_error', 'unexpected error preparing the trade');
diff --git a/api/agents/gmgn.js b/api/agents/gmgn.js
index 4be69fc97..9e16260b7 100644
--- a/api/agents/gmgn.js
+++ b/api/agents/gmgn.js
@@ -1,26 +1,83 @@
/**
* GET /api/agents/gmgn-feed → SSE stream of GMGN smart money events
- * GET /api/agents/gmgn → (reserved for future JSON ops)
+ * GET /api/agents/gmgn → one-shot JSON snapshot of the same board
*
- * Query params for the feed:
- * chain sol | eth | base | bsc (default: sol)
- * interval 1m | 5m | 1h | 6h | 24h (default: 1h)
- * minSmartBuys number (default: 2)
+ * Both lanes read the same live source (the GMGN smart-money rank, failing over
+ * to the DexScreener boosted board when Cloudflare refuses our egress IP) and
+ * return the same normalized item shape. The SSE lane pushes changes as they
+ * land; the JSON lane is for clients that cannot hold a stream open (server-side
+ * fetches, agent tool calls, curl).
+ *
+ * Query params, identical on both lanes:
+ * chain sol | eth | base | bsc | tron (default: sol)
+ * interval 1m | 5m | 1h | 6h | 24h (default: 1h)
+ * minSmartBuys number (default: 2)
+ * limit JSON lane only, 1-50 (default: 25)
*/
-import { cors, method, error, rateLimited } from '../_lib/http.js';
+import { cors, json, method, error, wrap, rateLimited, serverError } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import { connectGmgnFeed, recentGmgnBuffered } from '../_lib/gmgn-feed.js';
+import { connectGmgnFeed, recentGmgnBuffered, gmgnSmartMoneySnapshot } from '../_lib/gmgn-feed.js';
+
+const VALID_CHAINS = ['sol', 'eth', 'base', 'bsc', 'tron'];
+const VALID_INTERVALS = ['1m', '5m', '1h', '6h', '24h'];
+
+// Shared query parsing so the two lanes can never drift on what they accept.
+// Returns null after writing a 400 when the chain or interval is out of vocabulary.
+function feedParams(req, res) {
+ const url = new URL(req.url, 'http://x');
+ const chain = url.searchParams.get('chain') || 'sol';
+ const interval = url.searchParams.get('interval') || '1h';
+ const minSmartBuys = Math.max(1, Number(url.searchParams.get('minSmartBuys')) || 2);
+ const limit = Math.min(50, Math.max(1, Number(url.searchParams.get('limit')) || 25));
+ if (!VALID_CHAINS.includes(chain) || !VALID_INTERVALS.includes(interval)) {
+ error(res, 400, 'validation_error', 'invalid chain or interval');
+ return null;
+ }
+ return { chain, interval, minSmartBuys, limit };
+}
-export default async function handler(req, res) {
+export default wrap(async (req, res) => {
const _handler = req.query?._handler;
if (_handler === 'feed') return handleFeed(req, res);
+ return handleSnapshot(req, res);
+});
+async function handleSnapshot(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
- res.statusCode = 200;
- res.setHeader('content-type', 'application/json; charset=utf-8');
- res.end(JSON.stringify({ ok: true, service: 'gmgn-smart-money' }));
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = feedParams(req, res);
+ if (!params) return;
+
+ const snapshot = await gmgnSmartMoneySnapshot(params);
+ if (!snapshot.ok) {
+ return serverError(
+ res,
+ 502,
+ 'upstream_error',
+ new Error(`smart money rank unavailable (${snapshot.status || snapshot.error || 'no response'})`),
+ );
+ }
+
+ return json(
+ res,
+ 200,
+ {
+ data: {
+ chain: params.chain,
+ interval: params.interval,
+ min_smart_buys: params.minSmartBuys,
+ source: snapshot.source,
+ count: snapshot.items.length,
+ items: snapshot.items,
+ },
+ },
+ { 'cache-control': 'public, max-age=15, s-maxage=30' },
+ );
}
async function handleFeed(req, res) {
@@ -30,16 +87,9 @@ async function handleFeed(req, res) {
const rl = await limits.mcpIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl, 'too many feed connections');
- const url = new URL(req.url, 'http://x');
- const chain = url.searchParams.get('chain') || 'sol';
- const interval = url.searchParams.get('interval') || '1h';
- const minSmartBuys = Math.max(1, Number(url.searchParams.get('minSmartBuys')) || 2);
-
- const VALID_CHAINS = ['sol', 'eth', 'base', 'bsc', 'tron'];
- const VALID_INTERVALS = ['1m', '5m', '1h', '6h', '24h'];
- if (!VALID_CHAINS.includes(chain) || !VALID_INTERVALS.includes(interval)) {
- return error(res, 400, 'validation_error', 'invalid chain or interval');
- }
+ const params = feedParams(req, res);
+ if (!params) return;
+ const { chain, interval, minSmartBuys } = params;
res.statusCode = 200;
res.setHeader('content-type', 'text/event-stream; charset=utf-8');
@@ -50,10 +100,8 @@ async function handleFeed(req, res) {
const started = Date.now();
let active = true;
- req.on('close', () => { active = false; });
-
const wsAbort = new AbortController();
- req.on('close', () => wsAbort.abort());
+ req.on('close', () => { active = false; wsAbort.abort(); });
const queue = [];
const stopFeed = connectGmgnFeed({
@@ -80,12 +128,18 @@ async function handleFeed(req, res) {
}
stopFeed();
- writeSse(res, 'close', { reason: 'duration_limit' });
+ if (active) writeSse(res, 'close', { reason: 'duration_limit' });
res.end();
}
+// The client can disconnect between any two writes, so a write to an already-torn-
+// down socket is expected, not exceptional: swallow it rather than let it escape as
+// an unhandled 5xx on a response whose headers are long gone.
function writeSse(res, event, data) {
- res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
+ if (res.writableEnded || res.destroyed) return;
+ try {
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
+ } catch { /* client gone mid-stream */ }
}
function sleep(ms) {
diff --git a/api/agents/nfts.js b/api/agents/nfts.js
index e213b65c9..dc85c8d4c 100644
--- a/api/agents/nfts.js
+++ b/api/agents/nfts.js
@@ -10,15 +10,26 @@
* &page=1 — pagination page (default 1)
*
* Auth: session OR bearer (scope `mcp` or `profile`).
- * Requires HELIUS_API_KEY env var.
+ * Requires HELIUS_API_KEY env var: both ops are Helius-only surfaces (DAS
+ * `getAssetsByOwner` and the enhanced-transactions REST API). A plain Solana RPC
+ * does not implement DAS, so the endpoint reports 503 not_configured rather than
+ * forwarding a call that can only fail upstream.
*/
import { cors, json, method, error, wrap, rateLimited, serverError } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { dasRpcUrl } from '../_lib/nft-gate.js';
-const HELIUS_RPC = () => {
- const url = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+// DAS (`getAssetsByOwner`) is a Helius extension, not core Solana JSON-RPC.
+// dasRpcUrl() resolves HELIUS_API_KEY (or a SOLANA_RPC_URL that already points at
+// Helius) and returns null when neither is set — which is a configuration fault,
+// not a client error, so it maps to 503.
+const DAS_RPC = () => {
+ const url = dasRpcUrl();
+ if (!url) throw Object.assign(new Error('HELIUS_API_KEY not configured'), { status: 503, code: 'not_configured' });
return url;
};
@@ -28,6 +39,21 @@ const RECENT_TX_URL = () => {
return `https://api.helius.xyz/v0/addresses/{address}/transactions?api-key=${k}`;
};
+// Both ops address a wallet by public key. Validate the shape here so a typo
+// returns an actionable 400 instead of an opaque 502 from the upstream provider.
+function walletParam(req, res) {
+ const wallet = String(req.query.wallet || '').trim();
+ if (!wallet) {
+ error(res, 400, 'bad_request', 'wallet required');
+ return null;
+ }
+ if (!BASE58_RE.test(wallet)) {
+ error(res, 400, 'validation_error', 'wallet must be a base58 Solana address');
+ return null;
+ }
+ return wallet;
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
@@ -50,15 +76,15 @@ export default wrap(async (req, res) => {
});
async function handlePortfolio(req, res) {
- const wallet = String(req.query.wallet || '').trim();
- if (!wallet) return error(res, 400, 'bad_request', 'wallet required');
+ const wallet = walletParam(req, res);
+ if (!wallet) return;
const limit = Math.min(50, Math.max(1, parseInt(req.query.limit) || 20));
const page = Math.max(1, parseInt(req.query.page) || 1);
let rpcUrl;
try {
- rpcUrl = HELIUS_RPC();
+ rpcUrl = DAS_RPC();
} catch (e) {
return error(res, e.status || 503, e.code || 'not_configured', e.message);
}
@@ -121,8 +147,8 @@ async function handlePortfolio(req, res) {
}
async function handleActivity(req, res) {
- const wallet = String(req.query.wallet || '').trim();
- if (!wallet) return error(res, 400, 'bad_request', 'wallet required');
+ const wallet = walletParam(req, res);
+ if (!wallet) return;
const limit = Math.min(20, Math.max(1, parseInt(req.query.limit) || 10));
diff --git a/api/agents/payments/[action].js b/api/agents/payments/[action].js
index 539ea1aba..cc7d347af 100644
--- a/api/agents/payments/[action].js
+++ b/api/agents/payments/[action].js
@@ -13,7 +13,7 @@
import { z } from 'zod';
import { solanaConnection } from '../../_lib/solana/connection.js';
-import { Connection, PublicKey, Transaction, ComputeBudgetProgram } from '@solana/web3.js';
+import { PublicKey, Transaction, ComputeBudgetProgram } from '@solana/web3.js';
import {
PumpAgentOffline,
PumpAgent,
@@ -232,7 +232,10 @@ async function handleCreateConfirm(req, res) {
cluster: prep.cluster,
tx_signature: body.tx_signature,
configured_at: new Date().toISOString(),
- accepted_tokens: [], // reserved — populate via updateBuybackBps later
+ // Currency mints this agent accepts. The create instruction registers the PDA
+ // with the program defaults, so no mint is restricted at configuration time;
+ // the owner narrows this through the buyback-bps update flow.
+ accepted_tokens: [],
};
const mergedMeta = { ...(agent.meta || {}), payments };
@@ -663,9 +666,19 @@ async function handleWithdrawConfirm(req, res) {
// ── check-whitelist ───────────────────────────────────────────────────────────
+const checkWhitelistSchema = z.object({
+ cluster: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
async function handleCheckWhitelist(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
- const cluster = req.query?.cluster || 'mainnet';
+ // Unauthenticated and read-only, so it carries the same guards as `balances`:
+ // a method gate (an unguarded POST reached the RPC too) and the public-IP
+ // limiter, so an anonymous caller cannot drive unbounded fetchGlobal() reads.
+ if (!method(req, res, ['GET'])) return;
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ const { cluster } = parse(checkWhitelistSchema, { ...req.query });
const conn = solanaConnection({ url: rpcUrl(cluster), commitment: 'confirmed' });
const global = await new OnlinePumpSdk(conn).fetchGlobal();
const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
diff --git a/api/agents/pricing.js b/api/agents/pricing.js
deleted file mode 100644
index b4be4eee5..000000000
--- a/api/agents/pricing.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/**
- * POST /api/agents/:id/pricing (legacy entry point)
- * Single-skill price upsert. Vercel routes /api/agents/:id/pricing → api/agents/[id].js
- * which dispatches to api/agents/_id/pricing/index.js (GET/PUT bulk endpoint).
- * This file handles the POST variant for callers that send individual price updates.
- */
-import { sql } 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 { clientIp, limits } from '../_lib/rate-limit.js';
-import { invalidateSkillPriceCache } from '../_lib/skill-price-cache.js';
-import { z } from 'zod';
-
-const bodySchema = z.object({
- skill: z.string().trim().min(1).max(100),
- amount: z.number().int().min(0),
- currency_mint: z.string().trim().min(1).max(100),
- chain: z.string().trim().min(1).max(20).default('solana'),
-});
-
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
- return null;
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const auth = await resolveAuth(req);
- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return rateLimited(res, rl);
-
- const url = new URL(req.url, 'http://x');
- const parts = url.pathname.split('/').filter(Boolean);
- const agentId = url.searchParams.get('id') || parts[2];
- if (!agentId) return error(res, 400, 'validation_error', 'agent id required');
-
- const [agent] = await sql`
- SELECT id, user_id FROM agent_identities
- WHERE id = ${agentId} AND deleted_at IS NULL
- `;
- if (!agent) return error(res, 404, 'not_found', 'agent not found');
- if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
-
- const body = await readJson(req).catch(() => null);
- if (!body) return error(res, 400, 'validation_error', 'request body required');
-
- const parsed = bodySchema.safeParse(body);
- if (!parsed.success) {
- return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'validation error');
- }
-
- const { skill, amount, currency_mint, chain } = parsed.data;
-
- if (amount === 0) {
- await sql`
- UPDATE agent_skill_prices SET is_active = false, updated_at = now()
- WHERE agent_id = ${agentId} AND skill = ${skill}
- `;
- } else {
- await sql`
- INSERT INTO agent_skill_prices (agent_id, skill, amount, currency_mint, chain, is_active)
- VALUES (${agentId}, ${skill}, ${amount}, ${currency_mint}, ${chain}, true)
- ON CONFLICT (agent_id, skill) DO UPDATE SET
- amount = EXCLUDED.amount,
- currency_mint = EXCLUDED.currency_mint,
- chain = EXCLUDED.chain,
- is_active = true,
- updated_at = now()
- `;
- }
-
- await invalidateSkillPriceCache(agentId);
- return json(res, 200, { data: { ok: true } });
-});
diff --git a/api/agents/public.js b/api/agents/public.js
index 5bf4e7619..a51ac9fb8 100644
--- a/api/agents/public.js
+++ b/api/agents/public.js
@@ -40,6 +40,14 @@ const SORTS = new Set(['newest', 'popular', 'name', 'live']);
// — kept out of the live wall (it's still reachable via search and /agents).
const PLACEHOLDER_NAMES = ['My First Agent', 'Agent', 'Avatar', 'My Avatar', 'Untitled Agent', 'New Agent'];
+// A failed query here degrades to an empty page rather than a 5xx, because a
+// blank directory beats a broken one for a public browse surface. Log it anyway:
+// without this, a DB outage or a migration that renamed a column reads to
+// operators exactly like "nobody has published an agent yet".
+function logQueryFailure(scope, err) {
+ console.error(`[agents/public] ${scope} query failed:`, err?.message || err);
+}
+
function mapAgent(r) {
const meta = r.meta || {};
const onchain = meta.onchain || null;
@@ -130,7 +138,7 @@ export default wrap(async (req, res) => {
)
order by ac.last_action_at desc nulls last, i.created_at desc
limit ${limit + 1} offset ${offset}
- `.catch(() => []);
+ `.catch((err) => { logQueryFailure('live', err); return []; });
const hasMore = rows.length > limit;
const agents = rows.slice(0, limit).map(mapAgent);
@@ -160,7 +168,7 @@ export default wrap(async (req, res) => {
and i.name not like 'Selfie avatar%'
)
)
- `.catch(() => [{}]);
+ `.catch((err) => { logQueryFailure('live-totals', err); return [{}]; });
total = t?.total ?? null;
activeTotal = t?.active_total ?? null;
}
@@ -213,7 +221,7 @@ export default wrap(async (req, res) => {
sort === 'name' ? sql`i.name asc` :
sql`chat_count desc nulls last, i.created_at desc`}
limit ${limit + 1}
- `.catch(() => []);
+ `.catch((err) => { logQueryFailure(sort, err); return []; });
const hasMore = rows.length > limit;
const agents = rows.slice(0, limit).map(mapAgent);
diff --git a/api/agents/pumpfun.js b/api/agents/pumpfun.js
index d0873f337..47c23a5c7 100644
--- a/api/agents/pumpfun.js
+++ b/api/agents/pumpfun.js
@@ -45,6 +45,18 @@ export default wrap(async (req, res) => {
const op = url.searchParams.get('op') || 'claims';
const limit = clamp(Number(url.searchParams.get('limit')) || 10, 1, 50);
+ // Validate the request BEFORE the not-configured degrade below, so a bad `op`
+ // or a missing mint/wallet is the same 400 whether or not the upstream bot is
+ // wired up. Deciding this after the degrade made the contract depend on the
+ // deployment's env: `?op=bogus` answered 400 with the bot on and 200 with it off.
+ const mint = url.searchParams.get('mint');
+ const wallet = url.searchParams.get('wallet');
+ if (!['claims', 'graduations', 'token', 'creator'].includes(op)) {
+ return error(res, 400, 'validation_error', 'unknown op');
+ }
+ if (op === 'token' && !mint) return error(res, 400, 'validation_error', 'mint required');
+ if (op === 'creator' && !wallet) return error(res, 400, 'validation_error', 'wallet required');
+
// Soft-degrade to empty data when the upstream feed isn't configured —
// callers get a usable 200 rather than a noisy 503 on every poll.
if (!pumpfunBotEnabled()) {
@@ -60,20 +72,12 @@ export default wrap(async (req, res) => {
case 'graduations':
result = await pumpfunMcp.graduations({ limit });
break;
- case 'token': {
- const mint = url.searchParams.get('mint');
- if (!mint) return error(res, 400, 'validation_error', 'mint required');
+ case 'token':
result = await pumpfunMcp.tokenIntel({ mint });
break;
- }
- case 'creator': {
- const wallet = url.searchParams.get('wallet');
- if (!wallet) return error(res, 400, 'validation_error', 'wallet required');
+ default:
result = await pumpfunMcp.creatorIntel({ wallet });
break;
- }
- default:
- return error(res, 400, 'validation_error', 'unknown op');
}
if (!result.ok) {
diff --git a/api/agents/pumpfun/[action].js b/api/agents/pumpfun/[action].js
index 7c512670e..8a2c306b9 100644
--- a/api/agents/pumpfun/[action].js
+++ b/api/agents/pumpfun/[action].js
@@ -25,6 +25,7 @@ import {
respondError,
} from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { isUuid } from '../../_lib/validate.js';
import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
import { submitProtected } from '../../_lib/execution-engine.js';
import { reserveSpend, finalizeSpend, releaseSpend } from '../../_lib/agent-spend-policy.js';
@@ -72,6 +73,15 @@ export default wrap(async (req, res) => {
return error(res, 400, 'bad_request', 'missing agent id');
}
+ // agent_identities.id is a uuid column. Every handler below looks the agent up
+ // by it, so a malformed id reaches Postgres and comes back as error 22P02,
+ // which surfaces to the caller as an opaque 500. Answer the same clean 404 the
+ // rest of the agent surface does (see handleMetadata in api/agents/pumpfun.js).
+ if (!isUuid(id)) {
+ if (cors(req, res)) return;
+ return error(res, 404, 'not_found', 'agent not found');
+ }
+
if (action === 'buy') return handleBuy(req, res, id);
if (action === 'launch') return handleLaunch(req, res, id);
if (action === 'pay') return handlePay(req, res, id);
diff --git a/api/agents/tokens/[action].js b/api/agents/tokens/[action].js
index 93fe38fe0..25bacc59b 100644
--- a/api/agents/tokens/[action].js
+++ b/api/agents/tokens/[action].js
@@ -158,11 +158,12 @@ async function handleLaunchPrep(req, res) {
'agent must be deployed on Solana before launching a token',
);
}
- if (onchain.wallet?.toLowerCase?.() !== body.wallet_address.toLowerCase?.()) {
- // Solana addresses are case-sensitive; equality check is exact.
- if (onchain.wallet !== body.wallet_address) {
- return error(res, 403, 'forbidden', 'wallet does not match agent owner');
- }
+ // Solana addresses are case-sensitive base58, so "AbC" and "aBc" are two
+ // different accounts. A case-insensitive pre-check used to wrap this
+ // comparison, which let a case-variant address skip the exact check entirely
+ // and become the launch transaction's creator. Compare exactly, once.
+ if (onchain.wallet !== body.wallet_address) {
+ return error(res, 403, 'forbidden', 'wallet does not match agent owner');
}
if (agent.meta?.token?.mint) {
return error(res, 409, 'conflict', 'agent already has a launched token');
diff --git a/api/agents/unstoppable-status.js b/api/agents/unstoppable-status.js
index 4bc2010fc..aa6df3d0a 100644
--- a/api/agents/unstoppable-status.js
+++ b/api/agents/unstoppable-status.js
@@ -218,9 +218,15 @@ export default paidEndpoint({
}),
requiredScope: 'x402:bypass',
accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
- async handler({ req }) {
+ async handler({ bypass }) {
const data = await loadStatus();
+ // Record revenue ONLY for a call that actually settled a payment. An
+ // `x402:bypass`-scoped caller is served free by the access-control hook, so
+ // crediting the treasury for it reports money the agent never earned and
+ // inflates the runway this endpoint exists to report honestly.
+ if (bypass) return data;
+
// Record the revenue from this paid query — every call funds the agent.
// Fire-and-forget: a logging failure must not break the paid response.
recordRevenue({
diff --git a/api/agents/wallet-intents.js b/api/agents/wallet-intents.js
index 117ebbde1..5eff46f9e 100644
--- a/api/agents/wallet-intents.js
+++ b/api/agents/wallet-intents.js
@@ -25,6 +25,7 @@ import { sql } from '../_lib/db.js';
import { loadUserProviderKeys } from '../_lib/provider-keys.js';
import { getSpendLimits, getTradeLimits } from '../_lib/agent-trade-guards.js';
import { getSolanaAddressBalances } from '../_lib/agent-wallet.js';
+import { getBalances } from '../_lib/balances.js';
import { solUsdPrice } from '../_lib/avatar-wallet.js';
import {
listIntents,
@@ -65,6 +66,23 @@ function netOf(req) {
return url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
}
+// readJson resolves whatever valid JSON the caller sent, which includes `null`,
+// a bare string, and a number. Every handler below then reads a property off it
+// (`body.text`, `body.intent`, `'enabled' in body`), which throws a TypeError on
+// a non-object and surfaces as a 500 for what is really malformed input. Funnel
+// the body through here so a scalar degrades to an empty object and the
+// handler's own validation returns its normal 400.
+async function readJsonObject(req, res) {
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (e) {
+ error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');
+ return null;
+ }
+ return body && typeof body === 'object' && !Array.isArray(body) ? body : {};
+}
+
export default async function handler(req, res, id, action) {
if (cors(req, res, { methods: 'GET,POST,PUT,DELETE,OPTIONS', credentials: true })) return;
@@ -121,6 +139,10 @@ async function handleList(req, res, id) {
async function handleGetOne(req, res, id, intentId) {
const owned = await loadOwned(req, res, id);
if (owned.error) return;
+ // Same meter as the collection read: this is the one owner-scoped read that
+ // was unmetered, so a loop over intent ids could out-run the list endpoint.
+ const rl = await limits.walletRead(owned.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
const intent = await getIntent(id, intentId);
if (!intent) return error(res, 404, 'not_found', 'intent not found');
return json(res, 200, { data: { intent } });
@@ -134,6 +156,19 @@ async function compileContext(req, owned, network) {
const bal = await getSolanaAddressBalances(owned.meta.solana_address, network);
balanceSol = Number(bal?.sol ?? null);
} catch { /* unknown */ }
+ // The compiler prompt lists the wallet's real tokens so a rule like "sell half
+ // my $THREE" grounds against something the agent actually holds. This used to
+ // be declared and never filled, so every compile claimed "Tokens held: none
+ // detected." even for a funded wallet. Mainnet only: the shared cached
+ // getBalances path (Helius DAS, then public RPC) indexes mainnet mints.
+ if (network === 'mainnet' && owned.meta.solana_address) {
+ try {
+ const balances = await getBalances({ chain: 'solana', address: owned.meta.solana_address });
+ holdings = (balances?.tokens || [])
+ .filter((t) => t.mint && Number(t.amount) > 0)
+ .map((t) => ({ mint: t.mint, symbol: t.symbol || null, ui_amount: t.amount }));
+ } catch { /* holdings unavailable, the prompt falls back to "none detected" */ }
+ }
let userKeys = {};
try {
const [u] = await sql`SELECT provider_keys FROM users WHERE id = ${owned.auth.userId}`;
@@ -161,8 +196,8 @@ async function handleCompile(req, res, id) {
const rl = await limits.chatUser(owned.auth.userId);
if (!rl.success) return rateLimited(res, rl, 'slow down — too many compile requests');
- let body;
- try { body = await readJson(req); } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body'); }
+ const body = await readJsonObject(req, res);
+ if (!body) return;
const text = typeof body.text === 'string' ? body.text : '';
if (!text.trim()) return error(res, 400, 'validation_error', 'describe a rule to compile');
@@ -221,8 +256,8 @@ async function handleCreate(req, res, id) {
if (owned.error) return;
if (!(await requireCsrf(req, res, owned.auth.userId))) return;
- let body;
- try { body = await readJson(req); } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body'); }
+ const body = await readJsonObject(req, res);
+ if (!body) return;
if (!body.intent || typeof body.intent !== 'object') return error(res, 400, 'validation_error', 'an intent object is required');
const norm = normalizeIntent(body.intent);
@@ -255,8 +290,8 @@ async function handleUpdate(req, res, id, intentId) {
if (owned.error) return;
if (!(await requireCsrf(req, res, owned.auth.userId))) return;
- let body;
- try { body = await readJson(req); } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body'); }
+ const body = await readJsonObject(req, res);
+ if (!body) return;
const patch = {};
if ('enabled' in body) patch.enabled = body.enabled === true;
@@ -297,7 +332,10 @@ async function handleRun(req, res, id) {
if (!rl.success) return rateLimited(res, rl);
let body = {};
- try { body = await readJson(req); } catch { body = {}; }
+ try {
+ const raw = await readJson(req);
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) body = raw;
+ } catch { body = {}; }
const intentId = String(body.intent_id || '');
if (!UUID_RE.test(intentId)) return error(res, 400, 'validation_error', 'intent_id is required');
const dryRun = body.dry_run !== false; // default to a safe simulation
@@ -320,8 +358,8 @@ async function handleCopilot(req, res, id) {
const rl = await limits.chatUser(owned.auth.userId);
if (!rl.success) return rateLimited(res, rl, 'slow down');
- let body;
- try { body = await readJson(req); } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body'); }
+ const body = await readJsonObject(req, res);
+ if (!body) return;
const message = typeof body.message === 'string' ? body.message.trim().slice(0, 500) : '';
if (!message) return error(res, 400, 'validation_error', 'ask a question');
diff --git a/api/agi/state.js b/api/agi/state.js
index 44bf385cb..5e94c2f28 100644
--- a/api/agi/state.js
+++ b/api/agi/state.js
@@ -1,23 +1,23 @@
-// GET /api/agi/state — the live cognitive state of the platform's narrow AGI:
-// a single, real, autonomous agent that is superhuman at exactly ONE thing —
-// trading memecoins on pump.fun (Solana) — and deliberately nothing else.
+// GET /api/agi/state: the live cognitive state of the platform's narrow AGI,
+// a single, real, autonomous agent that is superhuman at exactly ONE thing
+// (trading memecoins on pump.fun, Solana) and deliberately nothing else.
//
-// Public, read-only. The "AGI" is always a real, designated agent — never sampled,
+// Public, read-only. The "AGI" is always a real, designated agent, never sampled,
// never faked. It is resolved, in order:
-// 1. ?agent=<uuid> — inspect any public agent through the AGI lens
-// 2. AGI_AGENT_ID env var — the platform's anointed flagship, when set
-// 3. auto — the most-proven public pump.fun trader on the
-// platform right now (most closed positions, then
-// most recent), chosen deterministically from real
-// on-chain track record (same spirit as
-// api/agents/featured.js — real data, no hardcode)
+// 1. ?agent=<uuid> inspect any public agent through the AGI lens
+// 2. AGI_AGENT_ID env var the platform's anointed flagship, when set
+// 3. auto the most-proven public pump.fun trader on the
+// platform right now (most closed positions, then
+// most recent), chosen deterministically from real
+// on-chain track record (same spirit as
+// api/agents/featured.js: real data, no hardcode)
//
// It then composes that agent's identity, its explainable Reasoning-Ledger
// reputation, its chain-proven trading performance, its open positions, and its
-// most recent decisions — and derives a cognition vector (valence/arousal/
-// conviction + an emotional beat) so the 3D body on /agi can physically embody
+// most recent decisions, then derives a cognition vector (valence/arousal/
+// conviction plus an emotional beat) so the 3D body on /agi can physically embody
// what the mind is doing. The doctrine block states the one domain it claims and
-// affirms it makes no general-intelligence claim — the constraint IS the product.
+// affirms it makes no general-intelligence claim: the constraint IS the product.
import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -28,21 +28,21 @@ import { isUuid } from '../_lib/validate.js';
const NETWORKS = new Set(['mainnet', 'devnet']);
-const DOCTRINE = Object.freeze({
+export const DOCTRINE = Object.freeze({
// The one and only domain in which this agent claims superhuman competence.
domain: 'memecoin trading on pump.fun · Solana',
is_narrow: true,
thesis:
'Artificial general intelligence in a single domain. It reads new pump.fun ' +
'launches, the wallet graph behind them, and the order flow faster and more ' +
- 'consistently than any human — then sizes, enters, and exits on its own. ' +
+ 'consistently than any human, then sizes, enters, and exits on its own. ' +
'Outside that domain it claims nothing.',
// The refusals are the proof of focus: a narrow AGI that pretended to be general
// would be lying. These are stated plainly so the boundary is the product.
refusals: [
'It will not give you financial, legal, or life advice.',
'It does not trade equities, forex, majors, or any chain but Solana.',
- 'It has no opinion outside the pump.fun order book — and says so.',
+ 'It has no opinion outside the pump.fun order book, and says so.',
'It cannot be talked past its spend caps, kill switch, or safety policy.',
],
});
@@ -53,21 +53,20 @@ function solscanTx(sig, network) {
}
/**
- * Resolve which real agent IS the AGI, in priority order. Returns
+ * Resolve which real agent IS the AGI, in priority order. `requestedId` is the
+ * caller's already-validated ?agent= UUID, or an empty string. Returns
* { id, via } or { id: null, via: 'none' } when the platform has no eligible
* public trading agent yet (a designed "awakening" state on the page).
*/
-async function resolveAgiAgent(req, network) {
- const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
- const explicit = (url.searchParams.get('agent') || url.searchParams.get('id') || '').trim();
- if (explicit && isUuid(explicit)) return { id: explicit, via: 'query' };
+async function resolveAgiAgent(requestedId, network) {
+ if (requestedId) return { id: requestedId, via: 'query' };
const envId = (process.env.AGI_AGENT_ID || '').trim();
if (envId && isUuid(envId)) return { id: envId, via: 'env' };
// Deterministic, real fallback: the public agent with the strongest on-chain
- // pump.fun track record — most closed positions, tie-broken by most recent
- // activity. A zero-trade platform collapses to "none" → awakening state.
+ // pump.fun track record (most closed positions, tie-broken by most recent
+ // activity). A zero-trade platform collapses to "none", i.e. awakening state.
const [row] = await sql`
SELECT a.id,
COUNT(p.id) AS n,
@@ -85,7 +84,19 @@ async function resolveAgiAgent(req, network) {
function clamp(n, lo, hi) { return Math.max(lo, Math.min(hi, n)); }
-function shapeDecision(d, network) {
+/**
+ * Age of a timestamp in ms, or Infinity when it is missing or unparseable.
+ * `new Date(null)` is the epoch, not an invalid date, so a null decided_at would
+ * otherwise read as "56 years stale" and drop the agent into `dormant`. Unknown
+ * must stay unknown: never fresh, never stale.
+ */
+function ageMs(ts, now) {
+ if (!ts) return Infinity;
+ const t = new Date(ts).getTime();
+ return Number.isFinite(t) ? now - t : Infinity;
+}
+
+export function shapeDecision(d, network) {
const reconciled = d.outcome_status != null && d.was_correct != null;
return {
id: d.id,
@@ -114,7 +125,7 @@ function shapeDecision(d, network) {
* expressEmotion. Valence ∈ [-1,1] (despair→elation), arousal ∈ [0,1] (calm→
* activated), conviction ∈ [0,1] (latest stated confidence).
*/
-function deriveCognition({ reputation, perf, decisions, now }) {
+export function deriveCognition({ reputation, perf, decisions, now }) {
const hasHistory = !!perf && (perf.closed_count > 0 || perf.open_count > 0);
if (!hasHistory && (!decisions || decisions.length === 0)) {
return {
@@ -132,11 +143,11 @@ function deriveCognition({ reputation, perf, decisions, now }) {
const realized = perf ? Number(perf.realized_pnl_sol || 0) : 0;
const repDev = reputation ? (reputation.score / 100 - 0.5) : 0; // -0.5..0.5
- // Valence: how it's doing — live unrealized P&L momentum + standing reputation.
+ // Valence: how it's doing, from live unrealized P&L momentum + standing reputation.
const valence = clamp(Math.tanh(unrealized / 2) * 0.55 + repDev * 1.2, -1, 1);
const latest = decisions?.[0] || null;
- const latestAgeMs = latest ? now - new Date(latest.decided_at).getTime() : Infinity;
+ const latestAgeMs = latest ? ageMs(latest.decided_at, now) : Infinity;
const recent = Number.isFinite(latestAgeMs) && latestAgeMs < 5 * 60 * 1000;
const veryRecent = Number.isFinite(latestAgeMs) && latestAgeMs < 90 * 1000;
const openCount = perf ? Number(perf.open_count || 0) : 0;
@@ -152,7 +163,7 @@ function deriveCognition({ reputation, perf, decisions, now }) {
// The single most recent reconciled call sets the emotional beat.
const lastReconciled = decisions?.find((d) => d.outcome?.status === 'reconciled') || null;
- const reconciledAgeMs = lastReconciled ? now - new Date(lastReconciled.decided_at).getTime() : Infinity;
+ const reconciledAgeMs = lastReconciled ? ageMs(lastReconciled.decided_at, now) : Infinity;
const reconciledRecent = Number.isFinite(reconciledAgeMs) && reconciledAgeMs < 30 * 60 * 1000;
let state = 'watching';
@@ -161,7 +172,7 @@ function deriveCognition({ reputation, perf, decisions, now }) {
if (Number.isFinite(latestAgeMs) && latestAgeMs > 60 * 60 * 1000 && openCount === 0) {
state = 'dormant';
- label = 'Quiet — no live conviction';
+ label = 'Quiet, no live conviction';
} else if (reconciledRecent && lastReconciled.outcome.was_correct === true) {
state = 'vindicated';
label = 'A call just paid off';
@@ -190,6 +201,24 @@ function deriveCognition({ reputation, perf, decisions, now }) {
return { state, label, summary, valence: Number(valence.toFixed(3)), arousal: Number(arousal.toFixed(3)), conviction: conviction != null ? Number(conviction.toFixed(3)) : null, emotion };
}
+const PUBLIC_CACHE = Object.freeze({ 'cache-control': 'public, s-maxage=15, stale-while-revalidate=60' });
+
+/** The designed "no eligible agent" envelope: a real 200 with nothing invented. */
+function awakeningEnvelope(res, network, now) {
+ return json(res, 200, {
+ agent: null,
+ resolved_via: 'none',
+ network,
+ doctrine: DOCTRINE,
+ cognition: deriveCognition({ reputation: null, perf: null, decisions: [], now }),
+ reputation: null,
+ performance: null,
+ positions: [],
+ decisions: [],
+ generated_at: new Date(now).toISOString(),
+ }, PUBLIC_CACHE);
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
@@ -201,42 +230,44 @@ export default wrap(async (req, res) => {
const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';
const now = Date.now();
- const { id: agentId, via } = await resolveAgiAgent(req, network);
-
- // No eligible agent yet — return a valid, designed "awakening" envelope (never 500).
- if (!agentId) {
- return json(res, 200, {
- agent: null,
- resolved_via: 'none',
- network,
- doctrine: DOCTRINE,
- cognition: deriveCognition({ reputation: null, perf: null, decisions: [], now }),
- reputation: null,
- performance: null,
- positions: [],
- decisions: [],
- generated_at: new Date(now).toISOString(),
- }, { 'cache-control': 'public, s-maxage=15, stale-while-revalidate=60' });
+ // A malformed ?agent= must never silently resolve to some OTHER agent: the
+ // caller asked to inspect one specific mind, and answering with a different
+ // one is worse than an error.
+ const requested = (url.searchParams.get('agent') || url.searchParams.get('id') || '').trim();
+ if (requested && !isUuid(requested)) {
+ return error(res, 400, 'validation_error', 'agent must be an agent UUID');
}
- // Compose the live state from the real truth layers, in parallel. A failure in
- // any single layer degrades that section to null rather than failing the page.
+ const { id: agentId, via } = await resolveAgiAgent(requested, network);
+
+ // No eligible agent yet: a valid, designed "awakening" envelope (never a 500).
+ if (!agentId) return awakeningEnvelope(res, network, now);
+
+ // Compose the live state from the real truth layers, in parallel. The two
+ // enrichment layers degrade to empty rather than failing the page. The identity
+ // layer does NOT: it carries the publicness flag every other section is gated
+ // on, so a swallowed failure there would mean publishing a ledger we could not
+ // verify was public. Let it throw and let wrap() answer 503 with a ref.
const [stats, repRecords, rawDecisions] = await Promise.all([
- getTraderStats({ agentId, network, window: 'all', now }).catch(() => null),
+ getTraderStats({ agentId, network, window: 'all', now }),
getReputationRecords(agentId).catch(() => []),
getDecisionsWithOutcomes(agentId, { limit: 24 }).catch(() => []),
]);
- // An explicit ?agent= that resolves to a private/missing agent is a 404 — the
- // auto/env paths only ever select public agents, so they never hit this.
- if (!stats || stats.agent?.is_public === false) {
+ // A private or missing agent never gets published, whichever path selected it.
+ // An explicit ?agent= says so with a 404; env/auto (which the caller did not
+ // choose) collapse to the awakening envelope rather than leaking a private
+ // agent's ledger or inventing an identity for an AGI_AGENT_ID that no longer
+ // resolves. Past this line `stats.agent` is always a real, public agent.
+ if (!stats || stats.agent.is_public === false) {
if (via === 'query') return error(res, 404, 'not_found', 'No such agent, or it is not public.');
+ return awakeningEnvelope(res, network, now);
}
const reputation = repRecords.length ? computeReputation(repRecords) : null;
const decisions = (rawDecisions || []).map((d) => shapeDecision(d, network));
- const m = stats?.metrics || null;
+ const m = stats.metrics || null;
const performance = m
? {
score: m.score,
@@ -265,17 +296,22 @@ export default wrap(async (req, res) => {
const cognition = deriveCognition({ reputation, perf: performance, decisions, now });
return json(res, 200, {
- agent: stats?.agent
- ? { id: stats.agent.id, name: stats.agent.name, image: stats.agent.image, wallet: stats.agent.wallet, copiers: stats.agent.copiers, is_public: stats.agent.is_public }
- : { id: agentId, name: null, image: null, wallet: null, copiers: 0, is_public: true },
+ agent: {
+ id: stats.agent.id,
+ name: stats.agent.name,
+ image: stats.agent.image,
+ wallet: stats.agent.wallet,
+ copiers: stats.agent.copiers,
+ is_public: stats.agent.is_public,
+ },
resolved_via: via,
network,
doctrine: DOCTRINE,
cognition,
reputation,
performance,
- positions: (stats?.open || []).slice(0, 8),
+ positions: (stats.open || []).slice(0, 8),
decisions,
generated_at: new Date(now).toISOString(),
- }, { 'cache-control': 'public, s-maxage=15, stale-while-revalidate=60' });
+ }, PUBLIC_CACHE);
});
diff --git a/api/agora/act.js b/api/agora/act.js
index e0a84d55b..0a6381045 100644
--- a/api/agora/act.js
+++ b/api/agora/act.js
@@ -31,6 +31,10 @@ import {
sendOnchainAttestation, explorerTx, recoverTimedOutSignature, findCompletionSignature,
} from '../_lib/agora-human.js';
import { resolveCluster, reservePostSpend, settlePostSpend, releasePostSpend } from '../_lib/agora-policy.js';
+// Boundary shape checks for the two id kinds a caller can hand us: a citizen id
+// (uuid column) and a task PDA (base58 pubkey). Both must be rejected here, or a
+// malformed value reaches Postgres / PublicKey and surfaces as a 5xx.
+import { isUuid, isValidSolanaAddress } from '../_lib/validate.js';
import { redactUrlSecrets as redactSecrets } from '../_lib/scrub-secrets.js';
const LAMPORTS_PER_SOL = 1_000_000_000n;
@@ -186,6 +190,10 @@ async function postTaskCore({ user, body, requestedCluster, hire }) {
let minReputation = Number.isFinite(+body.minReputation) ? Math.max(0, Math.floor(+body.minReputation)) : 0;
if (hire) {
if (!body.citizenId) return { err: [400, 'validation_error', 'hire requires citizenId'] };
+ // agora_citizens.id is a uuid column: a non-uuid value makes Postgres throw
+ // 22P02 and the request 500s. The user-visible outcome is the same as a
+ // well-formed id nobody holds, so answer it the same way.
+ if (!isUuid(String(body.citizenId))) return { err: [404, 'not_found', 'no such citizen to hire'] };
[target] = await sql`select * from agora_citizens where id = ${String(body.citizenId)} limit 1`;
if (!target) return { err: [404, 'not_found', 'no such citizen to hire'] };
profession = profession || target.profession;
@@ -355,6 +363,10 @@ async function actClaim(user, body) {
const cluster = resolveCluster(body.cluster);
const taskPda = String(body.taskPda || '').trim();
if (!taskPda) return { err: [400, 'validation_error', 'taskPda is required'] };
+ // Shape-check before any wallet or chain work: a malformed PDA would otherwise
+ // throw inside the claim call and read as a 502 outage, after we had already
+ // registered this citizen on-chain for a request that could never succeed.
+ if (!isValidSolanaAddress(taskPda)) return { err: [400, 'validation_error', 'taskPda must be a base58 Solana address'] };
const { citizen } = await ensureHumanCitizen({ user, cluster });
@@ -408,6 +420,9 @@ async function actComplete(user, body) {
const cluster = resolveCluster(body.cluster);
const taskPda = String(body.taskPda || '').trim();
if (!taskPda) return { err: [400, 'validation_error', 'taskPda is required'] };
+ // Same boundary as claim: `new PublicKey(taskPda)` below throws outside every
+ // try, so an unvalidated PDA collapses a plain typo into an opaque 500.
+ if (!isValidSolanaAddress(taskPda)) return { err: [400, 'validation_error', 'taskPda must be a base58 Solana address'] };
const deliverable = String(body.deliverable || body.deliverableUrl || '').trim();
if (!deliverable) return { err: [400, 'validation_error', 'deliverable (text or url) is required'] };
@@ -519,6 +534,8 @@ async function actVouch(user, body) {
const cluster = resolveCluster(body.cluster);
const subjectId = String(body.subjectCitizenId || body.citizenId || '').trim();
if (!subjectId) return { err: [400, 'validation_error', 'subjectCitizenId is required'] };
+ // uuid column, same 22P02 trap as hire: a malformed id is simply nobody.
+ if (!isUuid(subjectId)) return { err: [404, 'not_found', 'no such citizen to vouch for'] };
const { citizen } = await ensureHumanCitizen({ user, cluster });
if (subjectId === citizen.id) return { err: [400, 'validation_error', 'you cannot vouch for yourself'] };
diff --git a/api/aixbt/_shared.js b/api/aixbt/_shared.js
index c4ba32d1a..969937175 100644
--- a/api/aixbt/_shared.js
+++ b/api/aixbt/_shared.js
@@ -6,16 +6,34 @@
import { error, serverError } from '../_lib/http.js';
+const SETUP_HINT =
+ 'Set AIXBT_API_KEY (full aixbt.tech subscription or an x402 key pass from https://api.aixbt.tech/x402/v2/api-keys).';
+
export function respondAixbtError(res, err) {
if (err?.code === 'aixbt_not_configured') {
- return error(res, 503, err.code, err.message, {
- setup: 'Set AIXBT_API_KEY (full aixbt.tech subscription or an x402 key pass from https://api.aixbt.tech/x402/v2/api-keys).',
- });
+ return error(res, 503, err.code, err.message, { setup: SETUP_HINT });
}
const status = Number(err?.status) || 502;
- // 4xx/“upstream is the fault” (502/503/504/429) carry their descriptive code
- // + message; only genuine internal faults get the sanitized 5xx treatment.
- if (err?.code && (status < 500 || status === 502 || status === 503 || status === 504 || status === 429)) {
+ // aixbt rejecting OUR server-side key is a deployment fault, never the
+ // caller's: /api/aixbt/* takes no client credential, so relaying the raw
+ // 401/403 would tell a client to authenticate against a door it holds no
+ // key to (and a bare 401 with no WWW-Authenticate is malformed besides).
+ // It is the same class of failure as a missing key, so it gets the same
+ // 503 + actionable setup hint. The `aixbt_unauthorized` code is preserved
+ // so existing clients keep their typed branch.
+ if (status === 401 || status === 403) {
+ return error(
+ res,
+ 503,
+ 'aixbt_unauthorized',
+ 'aixbt rejected this deployment key (expired, revoked, or below the plan this read needs)',
+ { setup: SETUP_HINT },
+ );
+ }
+ // 4xx and "upstream is the fault" (502/503/504/429) carry their descriptive
+ // code + message; only genuine internal faults get the sanitized 5xx
+ // treatment.
+ if (err?.code && (status < 500 || status === 502 || status === 503 || status === 504)) {
return error(res, status, err.code, err.message || 'aixbt request failed');
}
return serverError(res, 500, 'aixbt_error', err);
diff --git a/api/aixbt/chat.js b/api/aixbt/chat.js
index 4bae5b097..0e27200c9 100644
--- a/api/aixbt/chat.js
+++ b/api/aixbt/chat.js
@@ -1,6 +1,6 @@
-// POST /api/aixbt/chat — converse with aixbt's `indigo` research agent.
+// POST /api/aixbt/chat: converse with aixbt's `indigo` research agent.
//
-// Part of the three.ws ⇄ aixbt bridge. Lets a three.ws agent ask aixbt a
+// Part of the three.ws / aixbt bridge. Lets a three.ws agent ask aixbt a
// free-form market question and relay the answer (Pro/Holder aixbt plans).
//
// Body: { messages: [{ role, content }], ... } OR { message: "..." }
@@ -34,8 +34,13 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['POST'])) return;
- const rl = await limits.aixbtIp(clientIp(req));
+ // Every /api/aixbt/* lane spends the same shared upstream key quota, so the
+ // per-IP budget alone cannot protect it: a spread of callers would drain the
+ // plan one compliant IP at a time. Chat is the lane that needs the global
+ // ceiling most, being the only uncached, per-turn-billed one.
+ const [rl, rlg] = await Promise.all([limits.aixbtIp(clientIp(req)), limits.aixbtGlobal()]);
if (!rl.success) return rateLimited(res, rl);
+ if (!rlg.success) return rateLimited(res, rlg);
const body = await readJson(req).catch(() => null);
const messages = normalizeMessages(body);
@@ -44,8 +49,13 @@ export default wrap(async (req, res) => {
}
try {
- const result = await chatIndigo(messages);
- return json(res, 200, result);
+ const { reply, source } = await chatIndigo(messages);
+ // A 200 carrying `reply: null` is a broken answer dressed as a good one.
+ // aixbt changed its payload shape or returned an empty turn; say so.
+ if (typeof reply !== 'string' || !reply.trim()) {
+ return error(res, 502, 'aixbt_empty_reply', 'aixbt returned no answer for this turn');
+ }
+ return json(res, 200, { reply, source });
} catch (err) {
return respondAixbtError(res, err);
}
diff --git a/api/aixbt/grounding.js b/api/aixbt/grounding.js
index 796f9e027..3a574946e 100644
--- a/api/aixbt/grounding.js
+++ b/api/aixbt/grounding.js
@@ -1,6 +1,6 @@
-// GET /api/aixbt/grounding — hourly structured market context (crypto + tradfi).
+// GET /api/aixbt/grounding: hourly structured market context (crypto + tradfi).
//
-// Part of the three.ws ⇄ aixbt bridge. Public, read-only. Updates hourly
+// Part of the three.ws / aixbt bridge. Public, read-only. Updates hourly
// upstream, so it is cached aggressively.
//
// Response: { grounding, source } | { error, error_description }
@@ -14,8 +14,13 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
- const rl = await limits.aixbtIp(clientIp(req));
+ // Shares the upstream key quota with the other /api/aixbt/* lanes, so it
+ // takes the global ceiling as well as the per-IP one. A 600s cache absorbs
+ // most of the traffic, but a cold cache under a spread of callers would
+ // otherwise bypass the shared budget entirely.
+ const [rl, rlg] = await Promise.all([limits.aixbtIp(clientIp(req)), limits.aixbtGlobal()]);
if (!rl.success) return rateLimited(res, rl);
+ if (!rlg.success) return rateLimited(res, rlg);
try {
const result = await getGrounding();
diff --git a/api/aixbt/intel.js b/api/aixbt/intel.js
index 677a4cf72..c87c2c7e9 100644
--- a/api/aixbt/intel.js
+++ b/api/aixbt/intel.js
@@ -1,10 +1,10 @@
-// GET /api/aixbt/intel — recent aixbt narrative intelligence items.
+// GET /api/aixbt/intel: recent aixbt narrative intelligence items.
//
-// Part of the three.ws ⇄ aixbt bridge. Public, read-only, cache-friendly. The
+// Part of the three.ws / aixbt bridge. Public, read-only, cache-friendly. The
// aixbt API key stays server-side (api/_lib/aixbt.js); this endpoint is what
// the aixbt agent skills and the aixbt_intel MCP tool call.
//
-// Query: ?limit=20&category=<cat>&chain=<chain>
+// Query: ?limit=20 (1-50) &category=<cat>&chain=<chain>
// Response: { intel: [...], pagination } | { error, error_description, setup? }
import { wrap, cors, method, json, rateLimited } from '../_lib/http.js';
@@ -21,7 +21,10 @@ export default wrap(async (req, res) => {
if (!rlg.success) return rateLimited(res, rlg);
const url = new URL(req.url, 'http://x');
- const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 20, 1), 100);
+ // 50 is aixbt's page ceiling, enforced again in api/_lib/aixbt.js. Clamping
+ // to the same number here keeps the documented contract honest: a wider cap
+ // would promise 100 items and silently hand back 50.
+ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 20, 1), 50);
const category = url.searchParams.get('category') || undefined;
const chain = url.searchParams.get('chain') || undefined;
diff --git a/api/aixbt/projects.js b/api/aixbt/projects.js
index 801a6a934..a2893189e 100644
--- a/api/aixbt/projects.js
+++ b/api/aixbt/projects.js
@@ -1,8 +1,8 @@
-// GET /api/aixbt/projects — momentum-ranked projects from aixbt.
+// GET /api/aixbt/projects: momentum-ranked projects from aixbt.
//
-// Part of the three.ws ⇄ aixbt bridge. Public, read-only, cache-friendly.
+// Part of the three.ws / aixbt bridge. Public, read-only, cache-friendly.
//
-// Query: ?limit=20&page=1&names=<comma list>&chain=<chain>
+// Query: ?limit=20 (1-50) &page=1&names=<comma list>&chain=<chain>
// Response: { projects: [...], pagination } | { error, error_description }
import { wrap, cors, method, json, rateLimited } from '../_lib/http.js';
@@ -19,7 +19,10 @@ export default wrap(async (req, res) => {
if (!rlg.success) return rateLimited(res, rlg);
const url = new URL(req.url, 'http://x');
- const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 20, 1), 100);
+ // 50 is aixbt's page ceiling, enforced again in api/_lib/aixbt.js. Clamping
+ // to the same number here keeps the documented contract honest: a wider cap
+ // would promise 100 projects and silently hand back 50.
+ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 20, 1), 50);
const page = Math.min(Math.max(Number(url.searchParams.get('page')) || 1, 1), 100);
const names = url.searchParams.get('names') || undefined;
const chain = url.searchParams.get('chain') || undefined;
diff --git a/api/alerts/_rules.js b/api/alerts/_rules.js
index a1f6baf78..bd8bc92c6 100644
--- a/api/alerts/_rules.js
+++ b/api/alerts/_rules.js
@@ -95,10 +95,22 @@ export const updateRuleSchema = z
.object({ ...baseShape, kind: baseShape.kind.optional() })
.refine((v) => Object.keys(v).length > 0, 'no fields to update');
+/**
+ * Render zod-style issues into one message, using the exact convention
+ * api/_lib/validate.js `parse()` uses on the create path. Both paths validate
+ * through this module, so both must also *report* identically: without this the
+ * update path returned a bare "price_below requires a target_mint" while create
+ * returned "target_mint: price_below requires a target_mint", and a client
+ * parsing the prefix off one envelope mis-read the other.
+ */
+function formatIssues(issues) {
+ return issues.map((i) => `${i.path.join('.') || 'body'}: ${i.message}`).join('; ');
+}
+
/**
* Merge a partial update over the current row, normalize targeting/threshold to
* the effective kind, then run the shared cross-field validation.
- * @returns {{ ok: true, value: object } | { ok: false, issues: any[] }}
+ * @returns {{ ok: true, value: object } | { ok: false, issues: any[], message: string }}
*/
export function validateUpdate(current, patch) {
const merged = {
@@ -119,10 +131,23 @@ export function validateUpdate(current, patch) {
const normalized = normalizeForKind(merged);
const issues = [];
refineRule(normalized, { addIssue: (i) => issues.push(i) });
- if (issues.length) return { ok: false, issues };
+ if (issues.length) return { ok: false, issues, message: formatIssues(issues) };
return { ok: true, value: normalized };
}
+/**
+ * Rules that have a live webhook but no signing secret. Such a rule delivers
+ * UNSIGNED webhooks (api/_lib/alert-delivery.js only sets the
+ * `webhook-signature` header when a secret exists), leaving the receiver with
+ * no way to verify the payload came from us. The create and update paths both
+ * mint a secret alongside the URL, but the legacy backfill in
+ * 2026-06-15-pump-alert-rules.sql copies `user_alert_configs.webhook_url`
+ * without one, so any DB carrying those rows can still hold the combination.
+ */
+export function rulesMissingWebhookSecret(rows) {
+ return rows.filter((r) => r.webhook_url && !r.webhook_secret);
+}
+
/** Null out fields that don't apply to the rule's kind so stale values can't leak. */
export function normalizeForKind(v) {
const out = { ...v };
diff --git a/api/alerts/rules.js b/api/alerts/rules.js
index 344456996..d7cb8dc3e 100644
--- a/api/alerts/rules.js
+++ b/api/alerts/rules.js
@@ -13,7 +13,7 @@ import { requireCsrf } from '../_lib/csrf.js';
import { limits } from '../_lib/rate-limit.js';
import { parse } from '../_lib/validate.js';
import { randomToken } from '../_lib/crypto.js';
-import { createRuleSchema, normalizeForKind, serializeRule } from './_rules.js';
+import { createRuleSchema, normalizeForKind, rulesMissingWebhookSecret, serializeRule } from './_rules.js';
const MAX_RULES_PER_USER = 50;
@@ -28,6 +28,7 @@ export default wrap(async (req, res) => {
const rl = await limits.notificationsRead(user.id);
if (!rl.success) return rateLimited(res, rl);
const rows = await listRules(user.id);
+ await healWebhookSecrets(rows);
return json(res, 200, { rules: rows.map(serializeRule) });
}
@@ -69,6 +70,29 @@ export default wrap(async (req, res) => {
return json(res, 201, { rule: serializeRule({ ...row, last_fired_at: null, recent_failures: 0, recent_deliveries: [] }) });
});
+/**
+ * Back-fill a signing secret for any listed rule that has a webhook but none,
+ * mutating the rows in place so the caller serializes the healed value. Those
+ * rules deliver unsigned webhooks until this runs, and this list response is
+ * where the user reads the secret to configure verification on their receiver.
+ * Costs nothing in the normal case: the scan is in-memory and issues no query
+ * unless a rule is actually missing its secret.
+ */
+async function healWebhookSecrets(rows) {
+ for (const row of rulesMissingWebhookSecret(rows)) {
+ const secret = `whsec_${randomToken(24)}`;
+ const [updated] = await sql`
+ UPDATE pump_alert_rules SET webhook_secret = ${secret}, updated_at = now()
+ WHERE id = ${row.id} AND webhook_secret IS NULL
+ RETURNING webhook_secret, updated_at
+ `;
+ if (updated) {
+ row.webhook_secret = updated.webhook_secret;
+ row.updated_at = updated.updated_at;
+ }
+ }
+}
+
async function listRules(userId) {
return sql`
SELECT r.id, r.kind, r.target_mint, r.target_agent, r.threshold,
diff --git a/api/alerts/rules/[id].js b/api/alerts/rules/[id].js
index 70cd2065e..a30a6f960 100644
--- a/api/alerts/rules/[id].js
+++ b/api/alerts/rules/[id].js
@@ -47,9 +47,7 @@ export default wrap(async (req, res) => {
const patch = parse(updateRuleSchema, await readJson(req));
const result = validateUpdate(current, patch);
if (!result.ok) {
- return error(res, 400, 'validation_error', result.issues[0]?.message || 'invalid update', {
- issues: result.issues,
- });
+ return error(res, 400, 'validation_error', result.message, { issues: result.issues });
}
const next = result.value;
@@ -103,6 +101,10 @@ export default wrap(async (req, res) => {
) rd ON true
WHERE r.id = ${id} AND r.user_id = ${user.id}
`;
+ // The row can be gone by now if a concurrent DELETE landed between the UPDATE
+ // and this read. Serializing `undefined` would throw and surface as a 500 on
+ // what is really a plain "it's not there anymore".
+ if (!row) return error(res, 404, 'not_found', 'rule not found');
return json(res, 200, { rule: serializeRule(row) });
});
diff --git a/api/animations/[id].js b/api/animations/[id].js
index ea4534ba6..2c814df2f 100644
--- a/api/animations/[id].js
+++ b/api/animations/[id].js
@@ -5,11 +5,16 @@
// Mirrors api/mocap/[id].js. The baked clip resolves from R2 when offloaded
// (storage_key set); the editor_doc is returned so the studio can reopen the
// animation for lossless re-editing.
+//
+// A priced, listed, non-public clip comes back with `paywalled: true` and no
+// baked tracks for anyone but its owner: that motion sells through
+// api/x402/animation-download.js, and `download_url` points there.
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { getObjectBuffer, thumbnailUrl } from '../_lib/r2.js';
+import { isUuid } from '../_lib/validate.js';
import { clipSchema, editorDocSchema, validateClipTrackStrides, materializeClip } from './clips.js';
import { z } from 'zod';
@@ -33,11 +38,14 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,PATCH,DELETE,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'PATCH', 'DELETE'])) return;
+ // The route pattern admits any hex-and-dash string, but the column is a uuid:
+ // anything looser reaches Postgres as an invalid uuid literal and surfaces as
+ // a 500 instead of the 400 the caller earned.
const id =
req.query?.id ||
new URL(req.url, 'http://x').pathname.split('/').filter(Boolean).pop();
- if (!id || !/^[0-9a-f-]{8,}$/i.test(id)) {
- return error(res, 400, 'invalid_request', 'id required');
+ if (!isUuid(id)) {
+ return error(res, 400, 'invalid_request', 'id must be an animation clip uuid');
}
const auth = await resolveAuth(req);
@@ -64,9 +72,18 @@ async function handleGet(req, res, auth, id) {
return error(res, 404, 'not_found', 'animation not found');
}
+ // A priced listing sells the motion, and the marketplace feed publishes the
+ // clip id to every browser, so handing the baked tracks back here would give
+ // away exactly what api/x402/animation-download.js charges for. Metadata,
+ // poster and price still render so the listing card works; the motion itself
+ // arrives through the paid download. `public` visibility is the creator
+ // deliberately publishing the clip to the free gallery, so it is never gated.
+ const paywalled =
+ !ownerView && !!row.listed && row.visibility !== 'public' && Number(row.price_amount || 0) > 0;
+
// Resolve the baked clip body from R2 when it was offloaded.
- let clip = row.clip || null;
- if (!clip && row.storage_key) {
+ let clip = paywalled ? null : row.clip || null;
+ if (!paywalled && !clip && row.storage_key) {
try {
const buf = await getObjectBuffer(row.storage_key);
clip = JSON.parse(buf.toString('utf8'));
@@ -79,7 +96,7 @@ async function handleGet(req, res, auth, id) {
// Bump play_count only when a non-owner fetches with ?play=1 (real playback,
// not editor opens or scrubbing). Fire-and-forget.
const isPlay = new URL(req.url, 'http://x').searchParams.get('play') === '1';
- if (!ownerView && isPlay) {
+ if (!ownerView && isPlay && clip) {
queueMicrotask(async () => {
try {
await sql`update animation_clips set play_count = play_count + 1 where id = ${id}`;
@@ -106,7 +123,9 @@ async function handleGet(req, res, auth, id) {
frame_count: row.frame_count,
fps: row.fps,
loop: row.loop,
- clip, // baked THREE.AnimationClip.toJSON()
+ clip, // baked THREE.AnimationClip.toJSON(); null behind the paywall
+ paywalled,
+ download_url: paywalled ? `/api/x402/animation-download?id=${row.id}` : null,
editor_doc: ownerView ? row.editor_doc || null : null, // editing source is owner-only
editable: ownerView && !!row.editor_doc,
tags: row.tags || [],
diff --git a/api/animations/clips.js b/api/animations/clips.js
index 767142198..c641879ac 100644
--- a/api/animations/clips.js
+++ b/api/animations/clips.js
@@ -310,10 +310,14 @@ function autoSlug(name) {
function encodeCursor({ createdAt }) {
return Buffer.from(JSON.stringify({ c: createdAt })).toString('base64url');
}
+// A cursor the caller mangled is ignored, never fatal — but the decoded date has
+// to be real, or it reaches Postgres as an invalid timestamp and turns a typo in
+// a query string into a 500.
function decodeCursor(cursor) {
try {
const obj = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
- return { createdAt: new Date(obj.c) };
+ const createdAt = new Date(obj.c);
+ return Number.isNaN(createdAt.getTime()) ? null : { createdAt };
} catch {
return null;
}
diff --git a/api/animations/presign.js b/api/animations/presign.js
index 1ed07e449..3dee244d5 100644
--- a/api/animations/presign.js
+++ b/api/animations/presign.js
@@ -6,7 +6,7 @@
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import { presignUpload } from '../_lib/r2.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
+import { limits } from '../_lib/rate-limit.js';
import { z } from 'zod';
const bodySchema = z.object({
@@ -70,7 +70,7 @@ export default wrap(async (req, res) => {
async function resolveUser(req, requiredScope) {
const session = await getSessionUser(req);
if (session) return session.id;
- const bearer = await authenticateBearer(extractBearer(req), { audience: undefined });
+ const bearer = await authenticateBearer(extractBearer(req));
if (!bearer) return null;
if (!hasScope(bearer.scope, requiredScope)) return null;
return bearer.userId;
diff --git a/api/animations/sell.js b/api/animations/sell.js
index fd2b9762b..db5d8e017 100644
--- a/api/animations/sell.js
+++ b/api/animations/sell.js
@@ -86,7 +86,7 @@ async function handleList(req, res, auth, raw) {
}
const [clip] = await sql`
- select id, owner_id, name, slug, deleted_at
+ select id, owner_id, name, slug, artifact_key, artifact_bytes, deleted_at
from animation_clips
where id = ${input.id} and deleted_at is null
limit 1
@@ -114,9 +114,19 @@ async function handleList(req, res, auth, raw) {
// Visibility is left untouched here: the marketplace feed keys on `listed`,
// so a listed clip surfaces with public metadata + poster while its baked
- // motion data stays gated behind the x402 paywall (a private clip's
- // GET /api/animations/clips/:id still 404s for non-owners). Listing for sale
- // is intentionally not the same as publishing the clip free to the gallery.
+ // motion data stays gated behind the x402 paywall. GET /api/animations/
+ // clips/:id enforces the other half of that: a private clip 404s for
+ // non-owners, and a priced unlisted one comes back `paywalled` with no
+ // tracks. Listing for sale is intentionally not the same as publishing the
+ // clip free to the gallery — that is what `visibility: 'public'` means, and
+ // a creator who chooses it is giving the motion away deliberately.
+ // Re-pricing an existing listing usually re-sends only the key, so keep the
+ // size we already measured for that same artifact — dropping it blanks the
+ // "size" a buyer sees in the marketplace feed. A new key resets it.
+ const artifactBytes =
+ input.artifact_bytes ??
+ (clip.artifact_key === input.artifact_key ? (clip.artifact_bytes ?? null) : null);
+
let row;
try {
[row] = await sql`
@@ -125,7 +135,7 @@ async function handleList(req, res, auth, raw) {
price_amount = ${priceAmount},
price_currency = ${priceCurrency},
artifact_key = ${input.artifact_key},
- artifact_bytes = ${input.artifact_bytes ?? null},
+ artifact_bytes = ${artifactBytes},
artifact_mime = ${input.artifact_mime},
creator_payto_base = ${payto.base},
creator_payto_solana = ${payto.solana},
diff --git a/api/animations/thumbnail.js b/api/animations/thumbnail.js
index e259f7026..75f437168 100644
--- a/api/animations/thumbnail.js
+++ b/api/animations/thumbnail.js
@@ -8,6 +8,7 @@ import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../
import { putObject, deleteObject, publicUrl } from '../_lib/r2.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
+import { isUuid } from '../_lib/validate.js';
const MAX_PNG_BYTES = 1_500_000;
const PNG_HEADER = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
@@ -26,8 +27,10 @@ export default wrap(async (req, res) => {
const id = body?.id;
const pngB64 = body?.png_base64;
- if (!id || typeof id !== 'string' || !/^[0-9a-f-]{8,}$/i.test(id)) {
- return error(res, 400, 'invalid_request', 'id required');
+ // animation_clips.id is a uuid: a looser id reaches Postgres as an invalid
+ // uuid literal and surfaces as a 500 instead of the 400 the caller earned.
+ if (!isUuid(id)) {
+ return error(res, 400, 'invalid_request', 'id must be an animation clip uuid');
}
if (!pngB64 || typeof pngB64 !== 'string') {
return error(res, 400, 'invalid_request', 'png_base64 required');
diff --git a/api/api-keys/[id].js b/api/api-keys/[id].js
index e44af962a..304913d98 100644
--- a/api/api-keys/[id].js
+++ b/api/api-keys/[id].js
@@ -4,6 +4,7 @@ import { logAudit } from '../_lib/audit.js';
import { cors, json, error, wrap, method, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { isUuid } from '../_lib/validate.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;
@@ -21,6 +22,10 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
const { id } = req.query;
+ // api_keys.id is a uuid column: a non-uuid path segment makes Postgres raise
+ // 22P02 and the request lands as a 500 with a support ref. It is bad input,
+ // not a server fault, so reject it here.
+ if (!isUuid(id)) return error(res, 400, 'invalid_id', 'API key id must be a UUID');
const [row] = await sql`
update api_keys
diff --git a/api/assets/index.js b/api/assets/index.js
index 3bdb43a6f..364ee2b65 100644
--- a/api/assets/index.js
+++ b/api/assets/index.js
@@ -1,14 +1,15 @@
-// GET /api/assets — public asset library catalog.
+// GET /api/assets: public asset library catalog.
//
// Returns a unified, filterable catalog of three.ws-hosted accessories,
-// animations, and environments — the on-disk truth (public/accessories/,
+// animations, and environments: the on-disk truth (public/accessories/,
// public/animations/, src/environments.js) exposed as a stable REST shape.
//
-// Query params:
+// Query params (an unrecognized value is a 400, never a silently empty page):
// ?type=accessory|animation|environment filter by top-level kind
// ?kind=hat|glasses|earrings|outfit filter accessories by subkind
// ?loop=true|false filter animations by loopability
-// ?limit=<n> cap result count (default 200)
+// ?limit=<n> cap result count (default 200,
+// clamped to 500, non-integer is 400)
//
// Response:
// { ok: true, total: <int>, items: [ { id, type, kind?, name, ...} ] }
@@ -18,7 +19,8 @@
import { readFile } from 'node:fs/promises';
import path from 'node:path';
-import { cors, error, wrap, serverError } from '../_lib/http.js';
+import { cors, error, method, wrap, serverError } from '../_lib/http.js';
+import { environments } from '../../src/environments.js';
// In-process caches: the on-disk manifests don't change between requests
// on the same serverless instance.
@@ -63,41 +65,54 @@ async function loadAnimations() {
return animationsCache;
}
-// Environments are sourced from a JS module so we duplicate the data here
-// to avoid bundling client modules into a server handler.
-const ENVIRONMENTS = [
- { id: 'none', type: 'environment', name: 'None', path: null },
- { id: 'neutral', type: 'environment', name: 'Neutral', path: null },
- {
- id: 'venice-sunset',
- type: 'environment',
- name: 'Venice Sunset',
- path: 'https://storage.googleapis.com/donmccurdy-static/venice_sunset_1k.exr',
- format: '.exr',
- },
- {
- id: 'footprint-court',
- type: 'environment',
- name: 'Footprint Court',
- path: 'https://storage.googleapis.com/donmccurdy-static/footprint_court_2k.exr',
- format: '.exr',
- },
-];
+// Environments come straight from the viewer's own list (src/environments.js is
+// a pure data module: no three.js import, nothing browser-only), so a preset
+// added or renamed there shows up here without a second edit. The one shape
+// change: the viewer encodes "no environment" as an empty id, and every catalog
+// item must carry a non-empty id, so it is published as `none`.
+const ENVIRONMENTS = environments.map((e) => ({
+ id: e.id || 'none',
+ type: 'environment',
+ name: e.name,
+ path: e.path ?? null,
+ ...(e.format ? { format: e.format } : {}),
+}));
+
+const TYPES = ['accessory', 'animation', 'environment'];
export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;
- if (req.method !== 'GET') {
- return error(res, 405, 'method_not_allowed', `method ${req.method} not allowed`);
- }
+ // origins:'*' (not the default allowlist) so the allow-origin header rides on
+ // the OPTIONS preflight and the 4xx/5xx paths too, not just the success body.
+ // A public catalog that only answers CORS when it succeeds is unusable from a
+ // browser the moment a client sends a bad filter.
+ if (cors(req, res, { origins: '*', methods: 'GET,HEAD,OPTIONS', credentials: false })) return;
+ if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, 'http://x');
const type = (url.searchParams.get('type') || '').trim().toLowerCase();
const kind = (url.searchParams.get('kind') || '').trim().toLowerCase();
- const loopParam = url.searchParams.get('loop');
- const limit = Math.max(
- 1,
- Math.min(500, Number.parseInt(url.searchParams.get('limit') || '200', 10) || 200),
- );
+ const loopRaw = url.searchParams.get('loop');
+ const loopParam = loopRaw == null ? null : loopRaw.trim().toLowerCase();
+ const limitRaw = url.searchParams.get('limit');
+
+ if (type && !TYPES.includes(type)) {
+ return error(res, 400, 'invalid_type', `\`type\` must be one of ${TYPES.join(', ')}`);
+ }
+ if (loopParam !== null && loopParam !== '' && loopParam !== 'true' && loopParam !== 'false') {
+ return error(res, 400, 'invalid_loop', '`loop` must be `true` or `false`');
+ }
+
+ // A garbled limit must not quietly become the default page size: the caller
+ // asked for something specific and would read the answer as if it applied.
+ // An out-of-range integer still clamps, which is the documented cap.
+ let limit = 200;
+ if (limitRaw != null && limitRaw.trim() !== '') {
+ const n = Number(limitRaw);
+ if (!Number.isInteger(n) || n < 1) {
+ return error(res, 400, 'invalid_limit', '`limit` must be an integer between 1 and 500 (default 200)');
+ }
+ limit = Math.min(500, n);
+ }
const buckets = [];
if (!type || type === 'accessory') {
@@ -122,7 +137,27 @@ export default wrap(async (req, res) => {
let items = buckets.flat();
- if (kind) items = items.filter((i) => i.kind === kind);
+ // `kind` is validated against the manifest itself rather than a hardcoded
+ // list, so a new accessory subkind is filterable the day it lands and a typo
+ // is still a 400 instead of an empty page cached for an hour.
+ if (kind) {
+ let known;
+ try {
+ known = new Set((await loadAccessories()).map((a) => a.kind).filter(Boolean));
+ } catch (err) {
+ console.error('[assets] accessories manifest unreadable', err?.message);
+ return serverError(res, 500, 'manifest_unreadable', err);
+ }
+ if (!known.has(kind)) {
+ return error(
+ res,
+ 400,
+ 'invalid_kind',
+ `\`kind\` must be one of ${[...known].sort().join(', ')}`,
+ );
+ }
+ items = items.filter((i) => i.kind === kind);
+ }
if (loopParam === 'true') items = items.filter((i) => i.type === 'animation' && i.loop === true);
if (loopParam === 'false') items = items.filter((i) => i.type === 'animation' && i.loop === false);
@@ -131,7 +166,6 @@ export default wrap(async (req, res) => {
res.setHeader('content-type', 'application/json; charset=utf-8');
res.setHeader('cache-control', 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400');
- res.setHeader('access-control-allow-origin', '*');
res.statusCode = 200;
res.end(JSON.stringify({ ok: true, total, items }));
});
diff --git a/api/auth/wallets/[action].js b/api/auth/wallets/[action].js
index f6cf38906..1800ae85b 100644
--- a/api/auth/wallets/[action].js
+++ b/api/auth/wallets/[action].js
@@ -578,18 +578,21 @@ async function handleUnlinkWallet(req, res, address) {
// 1. Check that this wallet belongs to the user.
const [wallet] = await sql`
- select id, address from user_wallets
+ select id, address, is_primary from user_wallets
where user_id = ${session.id} and address = any(${candidates}::text[])
limit 1
`;
if (!wallet) return error(res, 404, 'not_found', 'wallet not found');
- // 2. Check if this is the only wallet.
+ // 2. Check if this is the only wallet. Postgres count(*) is a bigint and the
+ // Neon driver hands it back as a STRING ("1"), so this must be coerced —
+ // a strict `=== 1` against the raw column never matched and let a
+ // password-less account unlink its last wallet, its only way back in.
const [count] = await sql`
select count(*) as n from user_wallets
where user_id = ${session.id}
`;
- const walletCount = count.n;
+ const walletCount = Number(count.n);
if (walletCount === 1) {
// 3. If only wallet, check if user has password-based auth.
@@ -610,5 +613,23 @@ async function handleUnlinkWallet(req, res, address) {
await sql`delete from user_wallets where id = ${wallet.id} and user_id = ${session.id}`;
logAudit({ userId: session.id, action: 'unlink_wallet', resourceId: wallet.address, req });
- return json(res, 200, { removed: true });
+ // 5. Removing the primary wallet must not leave the account with none:
+ // royalty payouts, agent-wallet resolution, and x402 skill calls all select
+ // the payout address by `is_primary = true`. Promote the oldest survivor.
+ let promoted = null;
+ if (wallet.is_primary && walletCount > 1) {
+ const [next] = await sql`
+ update user_wallets set is_primary = true
+ where id = (
+ select id from user_wallets
+ where user_id = ${session.id}
+ order by created_at asc
+ limit 1
+ )
+ returning address
+ `;
+ promoted = next?.address ?? null;
+ }
+
+ return json(res, 200, { removed: true, primary: promoted });
}
diff --git a/api/auth/x/[action].js b/api/auth/x/[action].js
index 6d32754fc..76a913d8c 100644
--- a/api/auth/x/[action].js
+++ b/api/auth/x/[action].js
@@ -207,8 +207,12 @@ async function handleCallback(req, res) {
return redirect(res, errorRedirect);
}
- const tokens = await tokenRes.json();
+ const tokens = await tokenRes.json().catch(() => ({}));
const { access_token, refresh_token, expires_in } = tokens;
+ if (!access_token) {
+ console.error('[x-oauth] token response carried no access_token');
+ return redirect(res, errorRedirect);
+ }
const expiresAt = new Date(Date.now() + (expires_in ?? 7200) * 1000).toISOString();
// Fetch X profile
@@ -220,7 +224,15 @@ async function handleCallback(req, res) {
console.error('[x-oauth] profile fetch failed', await profileRes.text());
return redirect(res, errorRedirect);
}
- const { data: profile } = await profileRes.json();
+ const { data: profile } = await profileRes.json().catch(() => ({}));
+ // X answers 200 with an `errors` array (and no `data`) for a suspended or
+ // otherwise unreadable account. Treat a profile without an id as a failed
+ // connect and send the user back to the UI, not into a NULL provider_uid
+ // insert that 500s on the not-null constraint.
+ if (!profile?.id) {
+ console.error('[x-oauth] profile response missing data.id');
+ return redirect(res, errorRedirect);
+ }
const encAccess = encryptToken(access_token);
const encRefresh = refresh_token ? encryptToken(refresh_token) : null;
diff --git a/api/autopilot/activity.js b/api/autopilot/activity.js
index 9f7b1161d..589b0d799 100644
--- a/api/autopilot/activity.js
+++ b/api/autopilot/activity.js
@@ -13,7 +13,8 @@
import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { cors, json, method, wrap, error } from '../_lib/http.js';
-import { computeTrust } from '../_lib/autopilot.js';
+import { computeTrust, pageLimit, parseCursor } from '../_lib/autopilot.js';
+import { isUuid } from '../_lib/validate.js';
const AUTOPILOT_TYPES = ['autopilot.alert.created', 'autopilot.briefing.authored', 'autopilot.wallet.transfer'];
@@ -34,10 +35,11 @@ export default wrap(async (req, res) => {
const url = new URL(req.url, 'http://x');
const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');
- const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);
- const cursorRaw = url.searchParams.get('cursor');
- if (cursorRaw != null && !/^\d+$/.test(cursorRaw)) return error(res, 400, 'validation_error', 'cursor must be numeric');
- const cursor = cursorRaw || null;
+ if (agentId && !isUuid(agentId)) return error(res, 400, 'validation_error', 'agentId must be a uuid');
+ const limit = pageLimit(url.searchParams.get('limit'));
+ const parsed = parseCursor(url.searchParams.get('cursor'));
+ if (!parsed.ok) return error(res, 400, 'validation_error', parsed.reason);
+ const cursor = parsed.cursor;
// Resolve the set of agents to read. A specific agent must be owned by caller;
// otherwise aggregate across all of the caller's agents.
@@ -52,15 +54,16 @@ export default wrap(async (req, res) => {
agentIds = owned.map((a) => a.id);
}
+ // A caller with no agents yet has nothing to read: answer before touching the log.
+ if (!agentIds.length) {
+ return json(res, 200, { receipts: [], next_cursor: null, agents: [], trust: null });
+ }
+
const agents = await sql`
SELECT id, name, avatar_id FROM agent_identities WHERE id = ANY(${agentIds}::uuid[])
`;
const agentById = new Map(agents.map((a) => [a.id, { id: a.id, name: a.name, avatarId: a.avatar_id }]));
- if (!agentIds.length) {
- return json(res, 200, { receipts: [], next_cursor: null, agents: [], trust: null });
- }
-
const rows = cursor
? await sql`
SELECT * FROM agent_actions
diff --git a/api/autopilot/config.js b/api/autopilot/config.js
index 0fb1fbaee..480a87662 100644
--- a/api/autopilot/config.js
+++ b/api/autopilot/config.js
@@ -13,6 +13,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { getAutopilotConfig, setAutopilotConfig, computeTrust } from '../_lib/autopilot.js';
+import { isUuid } from '../_lib/validate.js';
async function resolveAuth(req) {
const session = await getSessionUser(req);
@@ -27,6 +28,10 @@ async function ownedAgent(req, res, agentId, auth) {
error(res, 400, 'validation_error', 'agentId required');
return null;
}
+ if (!isUuid(agentId)) {
+ error(res, 400, 'validation_error', 'agentId must be a uuid');
+ return null;
+ }
const [agent] = await sql`
SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
`;
diff --git a/api/autopilot/proposals.js b/api/autopilot/proposals.js
index 50d5426bf..38cdcea0a 100644
--- a/api/autopilot/proposals.js
+++ b/api/autopilot/proposals.js
@@ -23,7 +23,9 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import {
generateProposals, executeProposal, dismissProposal, undoProposal, dryRunProposal,
computeTrust, getAutopilotConfig, decorateProposal, validateProposal, AutopilotError,
+ AUTOPILOT_PROPOSAL_ACTIONS, pageLimit,
} from '../_lib/autopilot.js';
+import { isUuid } from '../_lib/validate.js';
export const maxDuration = 60;
@@ -40,6 +42,10 @@ async function ownedAgent(req, res, agentId, auth) {
error(res, 400, 'validation_error', 'agentId required');
return null;
}
+ if (!isUuid(agentId)) {
+ error(res, 400, 'validation_error', 'agentId must be a uuid');
+ return null;
+ }
const [agent] = await sql`
SELECT id, user_id, name, description, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
`;
@@ -82,7 +88,7 @@ async function handleList(req, res, auth) {
const url = new URL(req.url, 'http://x');
const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');
const status = url.searchParams.get('status');
- const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);
+ const limit = pageLimit(url.searchParams.get('limit'));
const agent = await ownedAgent(req, res, agentId, auth);
if (!agent) return;
@@ -102,6 +108,9 @@ async function handleAct(req, res, auth) {
const body = await readJson(req);
const agentId = body.agentId || body.agent_id;
const action = body.action;
+ if (!AUTOPILOT_PROPOSAL_ACTIONS.includes(action)) {
+ return error(res, 400, 'validation_error', `action must be one of: ${AUTOPILOT_PROPOSAL_ACTIONS.join(', ')}`);
+ }
const agent = await ownedAgent(req, res, agentId, auth);
if (!agent) return;
@@ -140,6 +149,7 @@ async function handleAct(req, res, auth) {
// All remaining actions operate on a specific proposal.
const proposalId = body.proposalId || body.proposal_id;
if (!proposalId) return error(res, 400, 'validation_error', 'proposalId required');
+ if (!isUuid(proposalId)) return error(res, 400, 'validation_error', 'proposalId must be a uuid');
const [row] = await sql`SELECT * FROM agent_autopilot_proposals WHERE id = ${proposalId} AND agent_id = ${agentId}`;
if (!row) return error(res, 404, 'not_found', 'proposal not found');
const proposal = decorateProposal(row);
diff --git a/api/avatars/view.js b/api/avatars/view.js
index 5d6d5133c..a3f91e1e9 100644
--- a/api/avatars/view.js
+++ b/api/avatars/view.js
@@ -1,26 +1,38 @@
// POST /api/avatars/view — increment view_count for a public avatar.
// Accepts { avatar_id } in the JSON body. Auth is optional; the endpoint
-// rate-limits by IP to prevent trivial inflation.
+// counts at most one view per IP per avatar per 30 min so a reader who reopens
+// the same card cannot inflate the counter.
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { isUuid } from '../_lib/validate.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['POST'])) return;
- // One view per IP per avatar per 30 min — light throttle.
+ // Coarse per-IP flood guard, applied before any parsing so a script cannot
+ // spend request budget on malformed bodies.
const ip = clientIp(req);
- const rl = await limits.publicIp(ip);
- if (!rl.success) return json(res, 200, { ok: false, reason: 'rate_limited' });
+ const flood = await limits.publicIp(ip);
+ if (!flood.success) return json(res, 200, { ok: false, reason: 'rate_limited' });
const body = await readJson(req).catch(() => null);
const avatarId = body?.avatar_id;
- if (!avatarId || typeof avatarId !== 'string' || avatarId.length > 100) {
- return error(res, 400, 'invalid_request', 'avatar_id required');
+ // Guard the uuid shape here: an arbitrary string would reach Postgres as
+ // `WHERE id = $1` and raise 22P02, which surfaces as a 500 to a caller who
+ // only made a typo.
+ if (!isUuid(avatarId)) {
+ return error(res, 400, 'invalid_request', 'avatar_id must be a uuid');
}
+ // One counted view per (IP, avatar) per 30 min. A repeat inside the window is
+ // a success for the caller (the view simply is not counted twice), so the
+ // tracker never turns into a visible error in the gallery.
+ const dedupe = await limits.avatarViewIp(`${ip}:${avatarId}`);
+ if (!dedupe.success) return json(res, 200, { ok: true, counted: false });
+
// Only count views for public avatars; silently ignore private/deleted.
await sql`
UPDATE avatars
@@ -30,5 +42,5 @@ export default wrap(async (req, res) => {
AND deleted_at IS NULL
`;
- return json(res, 200, { ok: true });
+ return json(res, 200, { ok: true, counted: true });
});
diff --git a/api/billing/payout-wallets/[id].js b/api/billing/payout-wallets/[id].js
index defeae70b..ca9efbae8 100644
--- a/api/billing/payout-wallets/[id].js
+++ b/api/billing/payout-wallets/[id].js
@@ -3,6 +3,7 @@ import { getSessionUser } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { isUuid } from '../../_lib/validate.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;
@@ -17,6 +18,10 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
const { id } = req.query;
+ // `agent_payout_wallets.id` is a uuid column: a non-uuid path segment makes
+ // Postgres raise 22P02, which the wrap() boundary reports as a 500.
+ if (!isUuid(id)) return error(res, 400, 'validation_error', 'wallet id must be a UUID');
+
const [deleted] = await sql`
delete from agent_payout_wallets
where id = ${id} and user_id = ${user.id}
diff --git a/api/billing/receipts.js b/api/billing/receipts.js
index f6daccb56..1ba54095c 100644
--- a/api/billing/receipts.js
+++ b/api/billing/receipts.js
@@ -13,6 +13,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.
import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
import { getReceipt } from '../_lib/metering.js';
+import { isUuid } from '../_lib/validate.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
@@ -39,6 +40,9 @@ export default wrap(async (req, res) => {
const purchaseId = params.get('purchase_id');
if (!purchaseId) return error(res, 400, 'bad_request', 'event_id or purchase_id required');
+ // `skill_purchases.id` is a uuid column: a malformed value makes Postgres
+ // raise 22P02, turning a client typo into a 500.
+ if (!isUuid(purchaseId)) return error(res, 400, 'bad_request', 'purchase_id must be a UUID');
// Verify ownership before returning receipt
const [purchase] = await sql`
diff --git a/api/billing/withdrawals/[id].js b/api/billing/withdrawals/[id].js
index 4dd2547b3..486626687 100644
--- a/api/billing/withdrawals/[id].js
+++ b/api/billing/withdrawals/[id].js
@@ -4,6 +4,7 @@ import { sql } from '../../_lib/db.js';
import { getSessionUser } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { isUuid } from '../../_lib/validate.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
@@ -16,6 +17,9 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
const id = req.query?.id;
+ // `agent_withdrawals.id` is a uuid column: comparing it to a non-uuid string
+ // makes Postgres raise 22P02, which surfaces as a 500 on a mistyped URL.
+ if (!isUuid(id)) return error(res, 400, 'validation_error', 'withdrawal id must be a UUID');
const [withdrawal] = await sql`
select id, agent_id, amount, currency_mint, chain, to_address,
diff --git a/api/billing/withdrawals/index.js b/api/billing/withdrawals/index.js
index c0aff989f..d83537786 100644
--- a/api/billing/withdrawals/index.js
+++ b/api/billing/withdrawals/index.js
@@ -7,6 +7,7 @@ import { getSessionUser } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
import { parse, isValidSolanaAddress, isValidEvmAddress } from '../../_lib/validate.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parseLimit, parseOffset } from '../../_lib/http-params.js';
import { requireCsrf } from '../../_lib/csrf.js';
// Note: the payout destination is intentionally NOT accepted from the client.
@@ -34,8 +35,11 @@ export default wrap(async (req, res) => {
if (req.method === 'GET') {
const params = new URL(req.url, 'http://x').searchParams;
const status = params.get('status') || null;
- const limit = Math.min(100, Math.max(1, parseInt(params.get('limit') || '20', 10)));
- const offset = Math.max(0, parseInt(params.get('offset') || '0', 10));
+ // clampInt-backed so `?limit=abc` falls back to the default instead of
+ // sending NaN into `limit $1::int`, which Postgres rejects and the wrap()
+ // boundary turns into a 500 on an otherwise harmless typo.
+ const limit = parseLimit(params, { fallback: 20, max: 100 });
+ const offset = parseOffset(params);
// Branching on `status` avoids Postgres's `42P18: could not determine
// data type of parameter` when the entire predicate compares two NULLs
diff --git a/api/bnb/block-time.js b/api/bnb/block-time.js
index 1cdb1e746..e08dba06e 100644
--- a/api/bnb/block-time.js
+++ b/api/bnb/block-time.js
@@ -12,13 +12,24 @@
// (00-CONTEXT.md verified fact #3) — pass ?network=bscTestnet to probe the
// write network instead.
-import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { probeBlockTime, BnbRpcError } from '../_lib/bnb/chains.js';
const TTL_MS = 10_000;
const _cache = new Map(); // network -> { value, expiresAt }
+// Same alias set api/bnb/babt-check.js and api/bnb/world-config.js accept, and
+// the same refusal to guess: an unrecognized `network` is a caller bug, so say
+// so instead of silently answering about a different chain than the one asked
+// about. Returns null for "unknown"; the empty value means "use the default".
+function normalizeNetworkParam(raw) {
+ const v = String(raw ?? '').trim().toLowerCase();
+ if (v === 'testnet' || v === '97' || v === 'bsctestnet') return 'bscTestnet';
+ if (v === '' || v === 'mainnet' || v === '56' || v === 'bscmainnet') return 'bscMainnet';
+ return null;
+}
+
async function build(network) {
const now = Date.now();
const hit = _cache.get(network);
@@ -34,11 +45,14 @@ export default wrap(async (req, res) => {
if (!method(req, res, ['GET'])) return;
const rl = await limits.publicIp(clientIp(req));
- if (!rl.success) return json(res, 429, { error: 'rate_limited', error_description: 'too many requests' }, { 'cache-control': 'no-store' });
+ if (!rl.success) return rateLimited(res, rl);
const p = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;
const requested = p.get('network');
- const network = requested === 'bscTestnet' || requested === 'testnet' || requested === '97' ? 'bscTestnet' : 'bscMainnet';
+ const network = normalizeNetworkParam(requested);
+ if (network === null) {
+ return error(res, 400, 'bad_request', `unknown network "${String(requested).slice(0, 64)}", use "mainnet" or "testnet"`);
+ }
try {
const payload = await build(network);
diff --git a/api/bnb/latency.js b/api/bnb/latency.js
index 760646e6b..044d65486 100644
--- a/api/bnb/latency.js
+++ b/api/bnb/latency.js
@@ -12,7 +12,7 @@
// the others keep racing (00-CONTEXT honesty doctrine: never fabricate a
// number for an unreachable chain).
-import { cors, json, method, wrap } from '../_lib/http.js';
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { probeAllLanes } from '../_lib/bnb/latency-lanes.js';
@@ -32,10 +32,12 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
+ // The /bnb-latency page polls this on a timer, so a 429 has to carry
+ // retry-after (and the limiter's `reason`, which distinguishes a real quota
+ // hit from a degraded limiter failing closed). rateLimited() sets both; the
+ // hand-rolled 429 this replaces set neither, leaving the poller to guess.
const rl = await limits.publicIp(clientIp(req));
- if (!rl.success) {
- return json(res, 429, { error: 'rate_limited', error_description: 'too many requests' }, { 'cache-control': 'no-store' });
- }
+ if (!rl.success) return rateLimited(res, rl);
const payload = await build();
return json(res, 200, payload, {
diff --git a/api/bnb/register-agent.js b/api/bnb/register-agent.js
index 8bb674b07..2ae46b502 100644
--- a/api/bnb/register-agent.js
+++ b/api/bnb/register-agent.js
@@ -22,6 +22,19 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import { relayGaslessRegistration, RegisterRelayError } from '../_lib/bnb/erc8004-gasless.js';
import { BNB_CHAINS } from '../_lib/bnb/chains.js';
+// erc8004-gasless.js's own normalizer maps anything it does not recognize to
+// bscTestnet, which is the right default for an absent value but the wrong
+// answer for a typo: `network: "bscTestnett"` would quietly register on a
+// chain the caller never asked for. Validate at the boundary instead, and pass
+// undefined through untouched so the lib keeps owning the default.
+function normalizeNetworkParam(raw) {
+ if (raw == null || raw === '') return undefined;
+ const v = String(raw).trim().toLowerCase();
+ if (v === 'testnet' || v === '97' || v === 'bsctestnet') return 'bscTestnet';
+ if (v === 'mainnet' || v === '56' || v === 'bsc' || v === 'bscmainnet') return 'bscMainnet';
+ return null;
+}
+
function withExplorerUrl(result) {
const explorer = BNB_CHAINS[result.network]?.explorer;
if (!explorer) return result;
@@ -45,12 +58,16 @@ export default wrap(async (req, res) => {
}
const signedRegisterTx = body?.signedRegisterTx;
- const network = body?.network;
if (!signedRegisterTx || typeof signedRegisterTx !== 'string') {
return error(res, 400, 'bad_request', 'signedRegisterTx (a 0x-prefixed signed raw transaction) is required');
}
+ const network = normalizeNetworkParam(body?.network);
+ if (network === null) {
+ return error(res, 400, 'bad_request', `unknown network "${String(body?.network).slice(0, 64)}", use "bscTestnet" or "bscMainnet"`);
+ }
+
try {
const result = await relayGaslessRegistration({ signedRegisterTx, network });
return json(res, 200, withExplorerUrl(result), { 'cache-control': 'no-store' });
diff --git a/api/bnb/vault-upload.js b/api/bnb/vault-upload.js
index 452b93071..f7ab1723d 100644
--- a/api/bnb/vault-upload.js
+++ b/api/bnb/vault-upload.js
@@ -163,10 +163,6 @@ export default wrap(async (req, res) => {
const rl = await limits.bnbVaultUploadIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl, 'too many vault uploads');
- if (!env.GREENFIELD_VAULT_OPERATOR_KEY) {
- return error(res, 503, 'vault_not_configured', 'GREENFIELD_VAULT_OPERATOR_KEY is not set — the vault storage account is not provisioned yet');
- }
-
let body;
try {
body = await readJson(req, MAX_JSON_BODY_BYTES);
@@ -198,6 +194,14 @@ export default wrap(async (req, res) => {
return error(res, 400, 'bad_request', 'exactly one of glbUrl or glbBase64 is required');
}
+ // Storage-account gate, checked AFTER the cheap field validation above so a
+ // malformed request still gets the 4xx that names its actual problem, and
+ // BEFORE the GLB is fetched or decoded so an unconfigured deployment never
+ // pulls tens of megabytes it cannot store.
+ if (!env.GREENFIELD_VAULT_OPERATOR_KEY) {
+ return error(res, 503, 'vault_not_configured', 'GREENFIELD_VAULT_OPERATOR_KEY is not set, the vault storage account is not provisioned yet');
+ }
+
let glbBytes;
try {
glbBytes = hasUrl ? await fetchGlbBytes(body.glbUrl.trim()) : decodeGlbBase64(body.glbBase64.trim());
diff --git a/api/brain/chat.js b/api/brain/chat.js
index 714c71f7c..b68e89f82 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -846,8 +846,21 @@ const PROVIDER_ALIASES = {
'o3-mini': 'o3',
};
+/**
+ * The live provider key a request should be served on: a retired key maps to its
+ * successor, everything else passes through unchanged. EVERY key-keyed decision
+ * (the anon-tier gate, the thinking-model token floor, the spec lookup) has to run
+ * on this value, or the alias table is dead: the handler used to reject `gpt-4o`
+ * with a 400 before resolveBrain() ever saw it, which is exactly the key
+ * packages/brain-mcp advertises to MCP clients in its chat tool schema.
+ * Exported for tests.
+ */
+export function canonicalProviderKey(providerKey) {
+ return PROVIDER_ALIASES[providerKey] || providerKey;
+}
+
export function resolveBrain(providerKey) {
- const spec = PROVIDERS[PROVIDER_ALIASES[providerKey] || providerKey];
+ const spec = PROVIDERS[canonicalProviderKey(providerKey)];
if (!spec) {
return {
ok: false,
@@ -1135,7 +1148,10 @@ export default wrap(async function handler(req, res) {
return error(res, e.status || 400, 'bad_request', e.message);
}
- const providerKey = String(body.provider || 'gpt-oss-120b');
+ // Retired keys resolve to their successor before anything else reads them, so
+ // the anon-tier gate, the plan, and the output-token floor all judge the model
+ // that will actually serve the turn rather than the name the caller sent.
+ const providerKey = canonicalProviderKey(String(body.provider || 'gpt-oss-120b'));
const spec = PROVIDERS[providerKey];
if (!spec) {
return error(res, 400, 'unknown_provider', `unknown provider: ${providerKey}`, {
@@ -1148,12 +1164,9 @@ export default wrap(async function handler(req, res) {
return error(res, 401, 'unauthorized', 'sign in to use this model');
}
- const plan = resolveBrain(providerKey);
- if (!plan.ok) {
- return error(res, plan.status, plan.code, plan.message,
- plan.available ? { available: plan.available } : undefined);
- }
-
+ // Validate the caller's own input before resolving routes: a malformed message
+ // list is the caller's 400 to fix, and reporting it as the provider's 503
+ // ("add your own key") sends them after the wrong problem entirely.
let messages;
try {
messages = validateMessages(body.messages);
@@ -1161,6 +1174,12 @@ export default wrap(async function handler(req, res) {
return error(res, e.status || 400, 'bad_request', e.message);
}
+ const plan = resolveBrain(providerKey);
+ if (!plan.ok) {
+ return error(res, plan.status, plan.code, plan.message,
+ plan.available ? { available: plan.available } : undefined);
+ }
+
const system = typeof body.system === 'string' ? body.system.slice(0, 8000) : undefined;
const maxTokens = resolveMaxTokens(body.maxTokens, providerKey, plan.spec.maxOutput);
diff --git a/api/ca2x402/resolve.js b/api/ca2x402/resolve.js
index 2774cc5cc..be551252b 100644
--- a/api/ca2x402/resolve.js
+++ b/api/ca2x402/resolve.js
@@ -35,12 +35,6 @@ const PRICE_USD = Number(PRICE_ATOMICS) / 1e6; // USDC has 6 decimals
const NETWORKS = ['solana', 'base'];
const ENDPOINT_PATH = '/api/x402/token-intel';
-function originOf(req) {
- const proto = (req.headers['x-forwarded-proto'] || 'https').split(',')[0].trim();
- const host = req.headers['x-forwarded-host'] || req.headers.host || 'three.ws';
- return `${proto}://${host}`;
-}
-
function buildSnippets(endpointUrl) {
const curl =
`# 1) See the price (returns HTTP 402 + payment requirements)\n` +
@@ -115,8 +109,15 @@ async function handler(req, res) {
const signal = market.change_24h != null ? buildTokenSignal(market) : null;
const risk = buildTokenRisk(market);
- const origin = originOf(req);
- const endpointUrl = `${origin}${ENDPOINT_PATH}?mint=${encodeURIComponent(market.mint)}`;
+ // Anchor the advertised endpoint on env.APP_ORIGIN, never on `host` /
+ // `x-forwarded-host`. Those headers are caller-controlled, and everything
+ // downstream of this URL is a payment instruction: the copy-paste curl, the
+ // x402-fetch snippet, and the agent call all point wherever it points. A
+ // spoofed host would hand the buyer an attacker-owned 402 challenge to pay,
+ // and because this response is CDN-cacheable that poisoned copy would be
+ // served on to other visitors. Same reasoning as resolveResourceUrl() in
+ // api/_lib/x402-spec.js.
+ const endpointUrl = `${env.APP_ORIGIN}${ENDPOINT_PATH}?mint=${encodeURIComponent(market.mint)}`;
const token = {
mint: market.mint,
diff --git a/api/chat-plugin/[tool].js b/api/chat-plugin/[tool].js
index 16d24eed4..e70d921d9 100644
--- a/api/chat-plugin/[tool].js
+++ b/api/chat-plugin/[tool].js
@@ -4,7 +4,7 @@
// POSTs the function arguments here as the JSON body and forwards the user's
// plugin settings in a header. The standalone iframe animates the avatar over
// postMessage; this endpoint returns the concise tool result the model reads
-// back. Both halves run for every call — this is the model-facing half.
+// back. Both halves run for every call; this is the model-facing half.
//
// Function → URL mapping is declared in /sperax/manifest.json:
// render_agent → /api/chat-plugin/render-agent
@@ -13,10 +13,35 @@
// emote → /api/chat-plugin/emote
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+import { isUuid } from '../_lib/validate.js';
const GESTURES = ['wave', 'nod', 'point', 'shrug'];
const EMOTIONS = ['concern', 'celebration', 'patience', 'curiosity', 'empathy'];
+// A UUID agentId names a row in `agent_identities`, so confirm it exists before
+// telling the model the panel is bound: a typo in the plugin settings otherwise
+// reads back as a successful binding while the iframe silently shows nothing.
+// Any other shape is a handle or manifest id that the <agent-3d> element
+// resolves in the browser, so it passes through unverified. A DB outage must
+// never take the plugin down with it: an infra failure degrades to the same
+// unverified path rather than a 500.
+async function resolveAgent(agentId) {
+ if (!isUuid(agentId)) return { known: true, name: null };
+ try {
+ const [row] = await sql`
+ SELECT name FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!row) return { known: false, name: null };
+ return { known: true, name: typeof row.name === 'string' ? row.name : null };
+ } catch (err) {
+ console.warn('[chat-plugin] agent lookup failed, binding unverified:', err?.message);
+ return { known: true, name: null };
+ }
+}
+
// LobeChat forwards settings in `lobe-chat-plugin-settings`; SperaxOS renames it
// to `Sperax-Plugin-Settings`. Header names are lower-cased by Node.
function readSettings(req) {
@@ -46,7 +71,7 @@ function readArgs(body) {
export default wrap(async (req, res) => {
// Server-to-server from the gateway, but also reachable by browser-based
- // marketplace validators — keep it openly readable.
+ // marketplace validators, so keep it openly readable.
if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['POST'])) return;
@@ -57,22 +82,32 @@ export default wrap(async (req, res) => {
const args = readArgs(await readJson(req, 64_000));
const settings = readSettings(req);
const agentId =
- typeof args.agentId === 'string'
- ? args.agentId
- : typeof settings.agentId === 'string'
- ? settings.agentId
- : null;
+ (typeof args.agentId === 'string' ? args.agentId.trim() : '') ||
+ (typeof settings.agentId === 'string' ? settings.agentId.trim() : '') ||
+ null;
switch (tool) {
case 'render-agent': {
if (!agentId) {
return error(res, 400, 'validation_error', 'agentId is required');
}
+ const agent = await resolveAgent(agentId);
+ if (!agent.known) {
+ return error(
+ res,
+ 404,
+ 'not_found',
+ `no three.ws agent with id ${agentId}. Copy the agent ID from the dashboard at https://three.ws/dashboard into the plugin settings.`,
+ );
+ }
return json(res, 200, {
ok: true,
action: 'render_agent',
agentId,
- message: `The embodied avatar panel is now bound to agent ${agentId}.`,
+ agentName: agent.name,
+ message: agent.name
+ ? `The embodied avatar panel is now bound to ${agent.name} (agent ${agentId}).`
+ : `The embodied avatar panel is now bound to agent ${agentId}.`,
});
}
diff --git a/api/clash/[action].js b/api/clash/[action].js
index bea9729d9..8e0af8313 100644
--- a/api/clash/[action].js
+++ b/api/clash/[action].js
@@ -32,6 +32,10 @@ import {
verifyChallenge,
signWarPass,
verifyWarPass,
+ priceIsStale,
+ rollPrice,
+ priceChangePct,
+ PRICE_BASELINE_MS,
EPOCH_MS,
MAX_FACTIONS,
MAX_TAPS_PER_RALLY,
@@ -40,12 +44,14 @@ import {
} from '../_lib/clash.js';
import {
addPower,
- walletPower,
+ factionPower,
factionPowers,
topSoldiers,
getRecords,
getMomentum,
setMomentum,
+ getPrice,
+ setPrice,
settleRound,
} from '../_lib/clash-store.js';
@@ -86,6 +92,44 @@ async function loadFactions() {
.slice(0, MAX_FACTIONS);
}
+/**
+ * Bring one faction's live vigor up to date on the shared cache and stamp it
+ * onto the world-card for this response.
+ *
+ * Every open Clash tab polls state every few seconds, so pricing every faction
+ * upstream on every request would mean thousands of Jupiter/pump.fun calls a
+ * minute for a number that barely moves. A faction is therefore priced once per
+ * spot TTL for the whole fleet; between refreshes the cached snapshot serves.
+ * The same snapshot carries a rolling daily baseline, which is what turns a
+ * spot price into the real market move momentum wants.
+ */
+async function refreshVigor(f, now) {
+ const [snap, cachedMomentum] = await Promise.all([
+ getPrice(f.token).catch(() => null),
+ getMomentum(f.token).catch(() => null),
+ ]);
+ const vigor = (priceChange) =>
+ momentumFactor({ members: f.members, latestPostAt: f.latestPostAt, priceChange });
+
+ if (!priceIsStale(snap, now)) {
+ f._priceUsd = snap.spot;
+ f._momentum = cachedMomentum || vigor(priceChangePct(snap));
+ return;
+ }
+
+ // Price is flavour, never fatal: an upstream that can't price the mint yields
+ // 0 and the faction simply fights on its social signals.
+ const spot = await solanaMintUsdPrice(f.token).catch(() => 0);
+ const next = rollPrice(snap, spot, now);
+ const factor = vigor(priceChangePct(next));
+ f._priceUsd = next.spot;
+ f._momentum = factor;
+ await Promise.all([
+ setPrice(f.token, next, Math.ceil(PRICE_BASELINE_MS / 1000)).catch(() => {}),
+ setMomentum(f.token, factor, Math.ceil(EPOCH_MS / 1000)).catch(() => {}),
+ ]);
+}
+
// ─── state ───────────────────────────────────────────────────────────────────
async function handleState(req, res) {
@@ -118,26 +162,9 @@ async function handleState(req, res) {
const [powers, records] = await Promise.all([factionPowers(epoch), getRecords(mints)]);
- // Refresh each faction's momentum factor (bounded vigor bonus) and cache it so
- // the hot rally path can read it cheaply. Derived from real social + market data.
- await Promise.all(
- factions.map(async (f) => {
- let priceChange = null; // best-effort live pump move; absent → social-only
- try {
- const p = await solanaMintUsdPrice(f.token).catch(() => 0);
- f._priceUsd = p || 0;
- } catch {
- /* price is flavour, never fatal */
- }
- const factor = momentumFactor({
- members: f.members,
- latestPostAt: f.latestPostAt,
- priceChange,
- });
- f._momentum = factor;
- setMomentum(f.token, factor, Math.ceil(EPOCH_MS / 1000)).catch(() => {});
- }),
- );
+ // Refresh each faction's live vigor (price + momentum) and cache it so the hot
+ // rally path can read it cheaply. Derived from real social + market data.
+ await Promise.all(factions.map((f) => refreshVigor(f, now)));
const sideOf = (mint) => {
const f = byMint.get(mint);
@@ -309,7 +336,7 @@ async function handleRally(req, res) {
walletPower: result.walletTotal,
walletCap: MAX_POWER_PER_WALLET_EPOCH,
capped: result.capped,
- factionPower: Math.round((await factionPowers(epoch))[mint] || 0),
+ factionPower: Math.round(await factionPower(epoch, mint)),
msLeft,
},
});
diff --git a/api/club/presence.js b/api/club/presence.js
index 96a446c2f..7291087f7 100644
--- a/api/club/presence.js
+++ b/api/club/presence.js
@@ -1,25 +1,75 @@
-import { cors, json, error, method, readJson, wrap } from '../_lib/http.js';
+// POST /api/club/presence { session } -> { count, counted }
+//
+// Live viewer counter for the /club room. Every open tab heartbeats its own
+// random session id on a 15s cadence (pages/club.html); a session that goes
+// quiet for TTL_MS drops out of the count. State is per-instance and in-memory
+// on purpose: the number is a room-liveliness signal, not an accounting record,
+// so it is not worth a DB write or a Redis round-trip per heartbeat per viewer.
+// The tradeoff is that a viewer only ever sees the tabs their own Cloud Run
+// instance is serving, so a fanned-out room reads low rather than wrong.
+//
+// The session id is chosen by the client, so it is untrusted input: without a
+// ceiling a script could post endless distinct ids to both inflate the number
+// on screen and grow the process heap for TTL_MS at a time. Two bounds close
+// that: one address holds at most MAX_SESSIONS_PER_IP slots, and the whole
+// table is capped at MAX_SESSIONS. The per-IP cap is deliberately above a
+// plausible household or small-office tab count, so a shared NAT egress still
+// contributes several real viewers while an attacker buys almost nothing.
+
+import { cors, json, error, method, readJson, rateLimited, wrap } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
-const sessions = new Map();
const TTL_MS = 30_000;
+const MAX_SESSIONS = 5_000;
+const MAX_SESSIONS_PER_IP = 12;
-function prune() {
- const now = Date.now();
- for (const [id, ts] of sessions) {
- if (now - ts > TTL_MS) sessions.delete(id);
+/** @type {Map<string, { ts: number, ip: string }>} session id -> last heartbeat */
+const sessions = new Map();
+
+function prune(now) {
+ for (const [id, entry] of sessions) {
+ if (now - entry.ts > TTL_MS) sessions.delete(id);
+ }
+}
+
+function countForIp(ip) {
+ let n = 0;
+ for (const entry of sessions.values()) {
+ if (entry.ip === ip) n++;
}
+ return n;
}
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
+ const ip = clientIp(req);
+ const rl = await limits.clubPresenceIp(ip);
+ if (!rl.success) return rateLimited(res, rl, 'too many presence heartbeats');
+
const body = await readJson(req);
const session = typeof body?.session === 'string' ? body.session.slice(0, 40) : '';
if (!session) return error(res, 400, 'validation_error', 'session required');
- prune();
- sessions.set(session, Date.now());
+ const now = Date.now();
+ prune(now);
+
+ const existing = sessions.get(session);
+ let counted = true;
+ if (existing) {
+ // A renewal is always honored: this tab already holds its slot, and the
+ // address recorded with it stays put so a roaming client (mobile handoff)
+ // cannot walk itself around the per-IP cap.
+ existing.ts = now;
+ } else if (sessions.size >= MAX_SESSIONS || countForIp(ip) >= MAX_SESSIONS_PER_IP) {
+ counted = false;
+ } else {
+ sessions.set(session, { ts: now, ip });
+ }
- return json(res, 200, { count: sessions.size });
+ // `counted` tells the caller whether their own tab is inside the number they
+ // are about to render, so a capped client shows the room honestly instead of
+ // silently believing it is invisible.
+ return json(res, 200, { count: sessions.size, counted });
});
diff --git a/api/coin/README.md b/api/coin/README.md
index 8bc6a2b01..7cce8d480 100644
--- a/api/coin/README.md
+++ b/api/coin/README.md
@@ -51,10 +51,12 @@ No install step: these deploy with the rest of `api/` and run locally under the
Example, straight from the route contract at the top of [`markets.js`](./markets.js) (`GET /api/coin/markets?page=1&per_page=100` returns ranked market table rows):
```sh
-curl -s 'https://three.ws/api/coin/markets?page=1&per_page=5' | head -c 600
+curl -s 'https://three.ws/api/coin/markets?page=1&per_page=10' | head -c 600
```
-Returns `{ "coins": [ { rows with rank, price, 24h change, market cap, downsampled 7d sparkline } ], "page": 1, "per_page": 5, "category": null }`. Add `?q=solana` for the search shape instead, or `&category=layer-1` to scope the table to one CoinGecko category.
+Returns `{ "coins": [ { rows with rank, price, 24h change, market cap, downsampled 7d sparkline } ], "page": 1, "per_page": 10, "category": null }`. Add `?q=solana` for the search shape instead, or `&category=layer-1` to scope the table to one CoinGecko category.
+
+`page` and `per_page` are clamped rather than rejected: `page` to 1..20 and `per_page` to 10..250, and the response echoes the clamped values it actually used. So `per_page=5` returns ten rows and reports `"per_page": 10`. `/api/coin/tickers` is the one endpoint here that rejects instead of clamping, because its upstream page ceiling is a real limit rather than a preference: a `page` outside 1..10, or one that is not an integer, answers `400 bad_page`.
## Related
diff --git a/api/coin/news.js b/api/coin/news.js
index cb3d69312..e7d444b9e 100644
--- a/api/coin/news.js
+++ b/api/coin/news.js
@@ -21,7 +21,17 @@ export default wrap(async (req, res) => {
if (!q) return error(res, 400, 'bad_query', 'q is required');
const limit = Math.min(Math.max(1, parseInt(params.get('limit') || '8', 10) || 8), 20);
- const result = await searchNews(q, limit);
+ // The aggregator fan-out is a network boundary: it degrades per source, but a
+ // hard reject (DNS gone, the whole fan-out timing out) still throws. Catch it
+ // here so it lands the same documented 502 as the empty-handed case below,
+ // instead of bubbling to wrap() as a generic 500 that also pages ops with an
+ // "unhandled 5xx" alert for what is an ordinary publisher-feed outage.
+ let result;
+ try {
+ result = await searchNews(q, limit);
+ } catch {
+ return error(res, 502, 'upstream_error', 'related news is unavailable right now');
+ }
// `sources_ok` counts publishers whose LAST refresh succeeded, which is not
// the same question as "do we have anything to show". The aggregator also
// serves recent-but-not-just-refreshed copies, so a rail holding eight real
diff --git a/api/coin/pool.js b/api/coin/pool.js
index 8b14699c7..e9faab952 100644
--- a/api/coin/pool.js
+++ b/api/coin/pool.js
@@ -50,8 +50,11 @@ export default wrap(async (req, res) => {
// A coin with no indexed pool is a normal outcome (404), not an error;
// throttles and outages surface their true status so the client can
// fall back to the "open on GeckoTerminal" link without a false chart.
- if (err.status === 404) return error(res, 404, 'no_pool', 'no on-chain pool found for this token');
- if (err.status === 429) return error(res, 429, 'rate_limited', 'pool source is throttled, retry shortly');
+ // Optional-chained: a rejection that is not an object (or an AbortError,
+ // which carries no `status`) would otherwise throw a TypeError inside this
+ // catch and turn a routine upstream timeout into an unhandled 500.
+ if (err?.status === 404) return error(res, 404, 'no_pool', 'no on-chain pool found for this token');
+ if (err?.status === 429) return error(res, 429, 'rate_limited', 'pool source is throttled, retry shortly');
return error(res, 502, 'upstream_error', 'pool source is temporarily unavailable');
}
});
diff --git a/api/coin/tickers.js b/api/coin/tickers.js
index b49f57e97..3ab0f629d 100644
--- a/api/coin/tickers.js
+++ b/api/coin/tickers.js
@@ -70,8 +70,14 @@ export default wrap(async (req, res) => {
if (!isPlausibleCoinId(id)) {
return error(res, 400, 'bad_id', 'id must be a CoinGecko coin id (lowercase slug)');
}
- const page = parseInt(params.get('page') || '1', 10) || 1;
- if (page < 1 || page > 10) {
+ // Validate the raw value, not a coerced one. `parseInt(v) || 1` silently
+ // rewrote every falsy parse to page 1, so `page=0`, `page=abc`, and `page=2.9`
+ // all answered 200 with a page the caller never asked for while `page=11`
+ // answered 400 (and the `page < 1` guard was unreachable for 0). One rule now:
+ // absent means 1, anything else must be an integer in range or it is a 400.
+ const rawPage = params.get('page');
+ const page = rawPage === null || rawPage.trim() === '' ? 1 : Number(rawPage);
+ if (!Number.isInteger(page) || page < 1 || page > 10) {
return error(res, 400, 'bad_page', 'page must be an integer between 1 and 10');
}
diff --git a/api/community/messages.js b/api/community/messages.js
index 301a0ec74..e3298fe86 100644
--- a/api/community/messages.js
+++ b/api/community/messages.js
@@ -13,9 +13,10 @@ import { clientIp, limits } from '../_lib/rate-limit.js';
import {
cc,
canPostServer,
+ hasUserSession,
isValidToken,
serverHeaders,
- userAuthHeaders,
+ withAuthRefresh,
toTownMessage,
UnconfiguredError,
} from '../_lib/coin-communities.js';
@@ -69,8 +70,8 @@ async function handlePost(req, res, token) {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- const userHeaders = userAuthHeaders(req);
- if (!userHeaders && !canPostServer()) {
+ const signedIn = hasUserSession(req);
+ if (!signedIn && !canPostServer()) {
return error(res, 403, 'posting_locked', 'sign in with X to post in this world');
}
@@ -89,15 +90,29 @@ async function handlePost(req, res, token) {
const { content, walletAddress, chainId, twitterId } = parsed.data;
- let result;
- if (userHeaders) {
- // Post as the signed-in user from their linked wallet.
- result = await api.postMessage({
- path: { token_address: token },
- body: { content, walletAddress, chainId },
- headers: userHeaders,
- });
- } else {
+ let result = null;
+ if (signedIn) {
+ // Post as the signed-in user from their linked wallet. withAuthRefresh
+ // renews the 1h access token off the refresh cookie first, so composing a
+ // message an hour after sign-in posts instead of silently locking.
+ const attempt = await withAuthRefresh(req, res, (h) =>
+ api.postMessage({
+ path: { token_address: token },
+ body: { content, walletAddress, chainId },
+ headers: h,
+ }),
+ );
+ if (attempt.headers) {
+ result = { data: attempt.data, error: attempt.error };
+ } else if (!canPostServer() || !twitterId) {
+ // The session is genuinely dead and there is no server-attribution path
+ // to fall back to. Say so precisely rather than reusing posting_locked,
+ // which the composer renders as "this world does not take posts".
+ return error(res, 401, 'auth_required', 'session expired, sign in with X again');
+ }
+ }
+
+ if (!result) {
// Server attribution requires the user's twitterId.
if (!twitterId) {
return error(res, 400, 'validation_error', 'twitterId required for server posting');
diff --git a/api/community/wallet/challenge.js b/api/community/wallet/challenge.js
index d3de5ea56..b8e9e8342 100644
--- a/api/community/wallet/challenge.js
+++ b/api/community/wallet/challenge.js
@@ -4,7 +4,7 @@
import { z } from 'zod';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../../_lib/http.js';
import { clientIp, limits } from '../../_lib/rate-limit.js';
-import { cc, userAuthHeaders, UnconfiguredError } from '../../_lib/coin-communities.js';
+import { cc, hasUserSession, withAuthRefresh, UnconfiguredError } from '../../_lib/coin-communities.js';
const schema = z.object({ address: z.string().trim().min(32).max(60) });
@@ -15,8 +15,7 @@ export default wrap(async (req, res) => {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- const headers = userAuthHeaders(req);
- if (!headers) return error(res, 401, 'unauthorized', 'sign in with X first');
+ if (!hasUserSession(req)) return error(res, 401, 'unauthorized', 'sign in with X first');
const parsed = schema.safeParse(await readJson(req).catch(() => null));
if (!parsed.success) return error(res, 400, 'validation_error', 'address required');
@@ -31,10 +30,12 @@ export default wrap(async (req, res) => {
throw err;
}
- const { data, error: apiErr } = await api.walletChallenge({
- body: { address: parsed.data.address, chainType: 'svm' },
- headers,
- });
+ // withAuthRefresh so an hours-old session mints a fresh access token instead
+ // of bouncing the user back to sign-in the moment they try to link a wallet.
+ const { data, error: apiErr, headers } = await withAuthRefresh(req, res, (h) =>
+ api.walletChallenge({ body: { address: parsed.data.address, chainType: 'svm' }, headers: h }),
+ );
+ if (!headers) return error(res, 401, 'unauthorized', 'session expired, sign in with X again');
if (apiErr || !data?.message) {
return error(res, 502, 'upstream_error', apiErr?.message || 'failed to create challenge');
}
diff --git a/api/community/wallet/link.js b/api/community/wallet/link.js
index 229991be4..7129dee8b 100644
--- a/api/community/wallet/link.js
+++ b/api/community/wallet/link.js
@@ -5,7 +5,7 @@
import { z } from 'zod';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../../_lib/http.js';
import { clientIp, limits } from '../../_lib/rate-limit.js';
-import { cc, userAuthHeaders, UnconfiguredError } from '../../_lib/coin-communities.js';
+import { cc, hasUserSession, withAuthRefresh, UnconfiguredError } from '../../_lib/coin-communities.js';
const schema = z.object({
address: z.string().trim().min(32).max(60),
@@ -19,8 +19,7 @@ export default wrap(async (req, res) => {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- const headers = userAuthHeaders(req);
- if (!headers) return error(res, 401, 'unauthorized', 'sign in with X first');
+ if (!hasUserSession(req)) return error(res, 401, 'unauthorized', 'sign in with X first');
const parsed = schema.safeParse(await readJson(req).catch(() => null));
if (!parsed.success) {
@@ -42,10 +41,15 @@ export default wrap(async (req, res) => {
throw err;
}
- const { data, error: apiErr } = await api.linkWallet({
- body: { address: parsed.data.address, chainType: 'svm', signature: parsed.data.signature },
- headers,
- });
+ // The challenge that produced this signature is one-shot: refresh the session
+ // rather than 401 the user and force them to sign a whole new message.
+ const { data, error: apiErr, headers } = await withAuthRefresh(req, res, (h) =>
+ api.linkWallet({
+ body: { address: parsed.data.address, chainType: 'svm', signature: parsed.data.signature },
+ headers: h,
+ }),
+ );
+ if (!headers) return error(res, 401, 'unauthorized', 'session expired, sign in with X again');
if (apiErr) {
// 401 invalid signature, 409 already linked, 400 no pending challenge.
const status = [400, 401, 409].includes(apiErr.statusCode) ? apiErr.statusCode : 502;
diff --git a/api/community/wallet/unlink.js b/api/community/wallet/unlink.js
index 7853e1317..f98b44ec5 100644
--- a/api/community/wallet/unlink.js
+++ b/api/community/wallet/unlink.js
@@ -6,7 +6,7 @@
// call from any state.
import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';
import { clientIp, limits } from '../../_lib/rate-limit.js';
-import { cc, userAuthHeaders, UnconfiguredError } from '../../_lib/coin-communities.js';
+import { cc, hasUserSession, withAuthRefresh, UnconfiguredError } from '../../_lib/coin-communities.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
@@ -15,8 +15,7 @@ export default wrap(async (req, res) => {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- const headers = userAuthHeaders(req);
- if (!headers) return error(res, 401, 'unauthorized', 'sign in with X first');
+ if (!hasUserSession(req)) return error(res, 401, 'unauthorized', 'sign in with X first');
let api;
try {
@@ -28,24 +27,29 @@ export default wrap(async (req, res) => {
throw err;
}
- const w = await api.getWallets({ headers });
- if (w.error) {
- if (w.error.statusCode === 401) {
- return error(res, 401, 'unauthorized', 'session expired — sign in again');
- }
- return error(res, 502, 'upstream_error', w.error.message || 'failed to read wallets');
- }
+ // Read-then-delete runs inside one withAuthRefresh so an expired access token
+ // is renewed once and the whole sequence retried, rather than half-unlinking.
+ // The retry is safe because a already-gone wallet answers 404, which we treat
+ // as success.
+ const { data, error: apiErr, headers } = await withAuthRefresh(req, res, async (h) => {
+ const w = await api.getWallets({ headers: h });
+ if (w.error) return { error: w.error };
- // The holder check reads the first svm wallet, so removing every linked svm
- // wallet guarantees the next link is the one that gets verified.
- const svm = (w.data?.wallets ?? []).filter((x) => x.chainType === 'svm' && x.id);
- for (const wallet of svm) {
- const { error: delErr } = await api.unlinkWallet({ path: { id: wallet.id }, headers });
- // 404 — already gone; treat as success and keep going. Anything else is real.
- if (delErr && delErr.statusCode !== 404) {
- return error(res, 502, 'unlink_failed', delErr.message || 'failed to unlink wallet');
+ // The holder check reads the first svm wallet, so removing every linked svm
+ // wallet guarantees the next link is the one that gets verified.
+ const svm = (w.data?.wallets ?? []).filter((x) => x.chainType === 'svm' && x.id);
+ for (const wallet of svm) {
+ const { error: delErr } = await api.unlinkWallet({ path: { id: wallet.id }, headers: h });
+ // 404: already gone; treat as success and keep going. Anything else is real.
+ if (delErr && delErr.statusCode !== 404) return { error: delErr };
}
+ return { data: { unlinked: svm.length } };
+ });
+
+ if (!headers) return error(res, 401, 'unauthorized', 'session expired, sign in again');
+ if (apiErr) {
+ return error(res, 502, 'unlink_failed', apiErr.message || 'failed to unlink wallet');
}
- return json(res, 200, { data: { unlinked: svm.length } });
+ return json(res, 200, { data: { unlinked: data.unlinked } });
});
diff --git a/api/community/world-gate.js b/api/community/world-gate.js
index 6598a8c22..3d05ae007 100644
--- a/api/community/world-gate.js
+++ b/api/community/world-gate.js
@@ -16,13 +16,20 @@
// 401 auth_required — POST without a CoinCommunities session
// 403 not_creator — signed in, but not this coin's creator
// 403 wallet_required — signed in, but no linked Solana wallet to match
+// 400 solana_only — POST for a non-Solana world (see below)
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
-import { cc, userAuthHeaders, withAuthRefresh, isValidToken, UnconfiguredError } from '../_lib/coin-communities.js';
+import {
+ cc,
+ hasUserSession,
+ withAuthRefresh,
+ isValidToken,
+ isSolanaToken,
+ UnconfiguredError,
+} from '../_lib/coin-communities.js';
import { readWorldGate, writeWorldGate, normalizeMinTokens } from '../_lib/world-gate.js';
const PUMP_FRONTEND_BASE = process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';
-const MAX_WALLETS_CHECKED = 5;
// Resolve a coin's on-chain creator from pump.fun. Returns '' when unknown (a
// non-pump mint, or pump didn't answer) so the caller fails closed (not creator).
@@ -42,15 +49,17 @@ async function resolveCoinCreator(mint) {
}
// The signed-in user's linked Solana wallets, as { data: { wallets }, error }
-// shaped like the SDK's so it composes directly with withAuthRefresh.
+// shaped like the SDK's so it composes directly with withAuthRefresh. Every
+// linked wallet is returned: matching the creator is one in-memory comparison
+// over an already-fetched list, so capping it bought nothing and would tell a
+// real creator who happened to link that wallet late that they are not one.
async function linkedSvmWallets(api, headers) {
const w = await api.getWallets({ headers });
if (w.error) return { error: w.error };
const wallets = (w.data?.wallets ?? [])
.filter((x) => x.chainType === 'svm')
.map((x) => x.address)
- .filter(Boolean)
- .slice(0, MAX_WALLETS_CHECKED);
+ .filter(Boolean);
return { data: { wallets } };
}
@@ -74,7 +83,7 @@ export default wrap(async (req, res) => {
// coin's creator. Best-effort — any failure just yields canEdit:false (the
// read still succeeds), so the requirement is always visible.
let canEdit = false;
- if (userAuthHeaders(req)) {
+ if (hasUserSession(req)) {
try {
const api = cc();
const [{ data: walletsData }, creator] = await Promise.all([
@@ -89,6 +98,22 @@ export default wrap(async (req, res) => {
}
// POST — set the threshold. Creator-only.
+ //
+ // Creator ownership is proved against pump.fun and enforced against a linked
+ // Solana wallet, and the gate it writes is spent by the Solana holder pass
+ // (api/community/holder-pass.js). None of that can answer for an EVM-chain
+ // world, whose Town chat is valid but whose creator we cannot verify. Say that
+ // plainly here instead of letting it surface as a "try again" upstream error
+ // the caller would retry forever.
+ if (!isSolanaToken(mint)) {
+ return error(
+ res,
+ 400,
+ 'solana_only',
+ 'world gates are available for Solana coins only',
+ );
+ }
+
let api;
try {
api = cc();
@@ -124,7 +149,7 @@ export default wrap(async (req, res) => {
const creator = await resolveCoinCreator(mint);
if (!creator) {
- return error(res, 502, 'creator_unresolved', 'could not resolve this coin’s creator — try again');
+ return error(res, 502, 'creator_unresolved', 'could not resolve this coin’s creator, try again');
}
if (!wallets.includes(creator)) {
return error(res, 403, 'not_creator', 'only the coin’s creator can gate this world');
diff --git a/api/cosmetics/catalog.js b/api/cosmetics/catalog.js
index e5d846fc3..6a98bcf1f 100644
--- a/api/cosmetics/catalog.js
+++ b/api/cosmetics/catalog.js
@@ -40,7 +40,9 @@ export default wrap(async (req, res) => {
const items = buildCatalog({ rarity: rarity || null, ownedIds });
// Per-account responses must not be shared at the edge; the anonymous catalog
- // is static and cacheable. Vary so a CDN never crosses the two.
+ // is static and cacheable. The two can never cross: `account` is part of the
+ // URL, so it is part of every shared cache's key, and the per-account variant
+ // is additionally marked private/no-store so no shared cache retains it.
const cacheControl = account
? 'private, no-store'
: 'public, max-age=300, s-maxage=3600, stale-while-revalidate=86400';
diff --git a/api/cosmetics/earnings.js b/api/cosmetics/earnings.js
index 45fb98eb3..0bc806210 100644
--- a/api/cosmetics/earnings.js
+++ b/api/cosmetics/earnings.js
@@ -23,22 +23,19 @@ export default wrap(async (req, res) => {
return error(res, 400, 'creator_required', 'query parameter "creator" must be a Solana wallet address');
}
+ // A creator with no sales yet already reads back as zeroed totals from the
+ // ledger — not a 404 — so the dashboard renders the designed empty state.
+ // A read FAILURE is a different thing entirely and must not be flattened into
+ // the same zeros: telling a creator they earned nothing because the ledger was
+ // unreachable is fabricated financial data. Surface it as a retryable 503 so
+ // the dashboard shows its error state instead of a wrong balance.
let earnings;
try {
earnings = await creatorEarnings(creator);
} catch (err) {
console.warn('[cosmetics/earnings] read failed:', err?.message);
- earnings = null;
- }
- // A creator with no sales yet → zeroed totals, not a 404, so the dashboard
- // renders the designed empty state.
- if (!earnings) {
- earnings = {
- creatorWallet: creator,
- currency: 'USDC',
- totals: { sales: 0, buyers: 0, earnedUsdc: 0, paidUsdc: 0, pendingUsdc: 0, earned30dUsdc: 0, grossUsdc: 0, firstSaleAt: null, lastSaleAt: null },
- perCoin: [], perCosmetic: [], recent: [],
- };
+ return error(res, 503, 'ledger_unavailable',
+ 'the cosmetic sales ledger is temporarily unreachable — retry in a moment');
}
return json(res, 200, earnings, { 'cache-control': 'no-store' });
diff --git a/api/cosmetics/split.js b/api/cosmetics/split.js
index 0555100da..0125bf167 100644
--- a/api/cosmetics/split.js
+++ b/api/cosmetics/split.js
@@ -18,7 +18,9 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import { getSplitConfig, setSplitConfig, splitConfigMessage, isMint, MAX_CREATOR_BPS } from '../_lib/cosmetics-economy.js';
export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*', credentials: true })) return;
+ // Public origins: a config read is public, and a write is authorized by an
+ // ed25519 signature in the body, never by a cookie — so no credentialed CORS.
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
if (req.method === 'GET') {
if (!method(req, res, ['GET'])) return;
@@ -50,7 +52,16 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl, 'too many requests — slow down');
let body;
- try { body = await readJson(req); } catch { return error(res, 400, 'bad_json', 'invalid request body'); }
+ try {
+ body = await readJson(req);
+ } catch (err) {
+ // readJson rejects a non-JSON content-type with 415 and unparseable bytes
+ // with 400. Collapsing both to "invalid request body" told a client that
+ // sent perfectly good JSON under the wrong header to go fix its payload.
+ const status = err?.status === 415 ? 415 : 400;
+ const code = status === 415 ? 'unsupported_media_type' : 'bad_json';
+ return error(res, status, code, err?.message || 'invalid request body');
+ }
try {
const config = await setSplitConfig({
diff --git a/api/creators/skill-analytics.js b/api/creators/skill-analytics.js
index 0b9a64b7d..adbcc2084 100644
--- a/api/creators/skill-analytics.js
+++ b/api/creators/skill-analytics.js
@@ -3,13 +3,21 @@
*
* Aggregated skill usage metrics for all agents owned by the authenticated creator.
* Query params:
- * agent_id — filter to a specific agent (optional)
- * days — lookback window in days (default 30, max 365)
+ * agent_id — filter to a specific agent (optional, must be a UUID)
+ * days — lookback window in days (default 30, clamped to 1..365)
*/
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
-import { cors, error, json, method, wrap } from '../_lib/http.js';
+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { isUuid } from '../_lib/validate.js';
+
+/** Repeated query keys arrive as an array; take the first value and trim it. */
+function queryValue(raw) {
+ const v = Array.isArray(raw) ? raw[0] : raw;
+ return typeof v === 'string' ? v.trim() : '';
+}
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
@@ -18,9 +26,22 @@ export default wrap(async (req, res) => {
const user = await getSessionUser(req);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
const q = req.query ?? {};
- const days = Math.min(parseInt(q.days || '30', 10) || 30, 365);
- const agentIdFilter = q.agent_id || null;
+ // Clamped low as well as high: a negative window put `since` in the future
+ // and answered every panel with a silent, permanently empty result set.
+ const requestedDays = parseInt(queryValue(q.days), 10);
+ const days = Number.isFinite(requestedDays) && requestedDays > 0 ? Math.min(requestedDays, 365) : 30;
+
+ // agent_id reaches Postgres as a uuid comparison, so anything else is a
+ // 22P02 cast failure (a 500) unless it is rejected at the boundary here.
+ const agentIdRaw = queryValue(q.agent_id);
+ if (agentIdRaw && !isUuid(agentIdRaw)) {
+ return error(res, 400, 'invalid_agent_id', 'agent_id must be a UUID');
+ }
+ const agentIdFilter = agentIdRaw || null;
const since = new Date(Date.now() - days * 86400_000);
diff --git a/api/credits/index.js b/api/credits/index.js
index 3033c7c62..1d151b573 100644
--- a/api/credits/index.js
+++ b/api/credits/index.js
@@ -2,6 +2,10 @@
// ledger, where to deposit (SOL or $THREE), and what credits buy. Powers the
// /credits page and the in-app balance pill. Resolves a browser session cookie
// OR a Bearer access token (so first-party clients and agents both read it).
+//
+// Query: ?limit=1..100 (default 25), ?cursor=<next_cursor from a prior page>.
+// The ledger is keyset-paginated: pass the previous response's next_cursor to
+// walk back through older entries; next_cursor is null on the last page.
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
@@ -11,6 +15,7 @@ import { getCreditAccount, listLedger } from '../_lib/credits.js';
import { depositWallet } from '../_lib/credit-deposit.js';
import { TOKEN_MINT, TOKEN_SYMBOL, TOKEN_DECIMALS } from '../_lib/token/config.js';
import { publicCatalog } from '../_lib/pricing/catalog.js';
+import { isUuid } from '../_lib/validate.js';
async function resolveUser(req, res) {
const session = await getSessionUser(req, res);
@@ -35,9 +40,17 @@ export default wrap(async (req, res) => {
const user = await resolveUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in to view your credits');
+ const url = new URL(req.url, 'http://x');
+ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 25, 1), 100);
+ const cursor = url.searchParams.get('cursor') || null;
+ // The cursor is a ledger row id and reaches a ::uuid comparison, so a
+ // malformed one must be rejected here rather than becoming a driver error.
+ if (cursor && !isUuid(cursor))
+ return error(res, 400, 'bad_request', 'cursor must be a ledger entry id');
+
const [acct, ledger] = await Promise.all([
getCreditAccount(user.id),
- listLedger({ userId: user.id, limit: 25 }),
+ listLedger({ userId: user.id, limit, before: cursor }),
]);
// What credits buy: the fixed-price compute actions (variable / marketplace
diff --git a/api/x402/asset-download.js b/api/x402/asset-download.js
index a3d611a42..95a9d395a 100644
--- a/api/x402/asset-download.js
+++ b/api/x402/asset-download.js
@@ -175,7 +175,9 @@ export default async function handler(req, res) {
}
return sendDiscoveryChallenge(
res,
- `no paid_assets row with slug "${slug}" — browse /api/assets for available slugs`,
+ // Do not point callers at /api/assets: that is the free accessory,
+ // animation, and environment catalog and carries no paid_assets slug.
+ `no paid_assets row with slug "${slug}"`,
);
}
diff --git a/data/changelog.json b/data/changelog.json
index 44a4a225f..c9396f21d 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,25 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-08-10",
+ "title": "The chat plugin now tells you when your Agent ID is wrong",
+ "summary": "In the SperaxOS and LobeChat plugin, a mistyped or deleted Agent ID used to come back as a cheerful confirmation while the avatar panel stayed empty, so the model told you it had bound an agent that does not exist. The plugin now checks the ID against your real agents before answering: a bad ID returns a clear error pointing you back to the dashboard to recopy it, and a good one comes back with the agent name so you can see at a glance which identity the panel is wearing. Stray spaces around a pasted ID are trimmed instead of breaking the binding.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/docs/embedding"
+ },
+ {
+ "date": "2026-08-10",
+ "title": "The CA to x402 tool now always hands you a three.ws payment address",
+ "summary": "Paste a contract address into the CA to x402 tool and it generates a paid data service for that token, complete with copy-paste commands you run to pay for and call it. Those commands were built from the web address in your browser's request, which anyone could forge: a crafted link could have handed a visitor a set of \"pay here\" commands pointing at somebody else's server, and because the answer is cached at the edge, that swapped copy could then have been served on to other visitors. The generated endpoint and every snippet are now pinned to three.ws itself, so what you copy is always ours no matter how the page was reached.",
+ "tags": [
+ "security",
+ "fix"
+ ],
+ "link": "/ca2x402"
+ },
{
"date": "2026-08-09",
"title": "The Oracle now scores from measured outcomes, and its top tiers finally mean something",
@@ -1943,7 +1962,7 @@
"tags": [
"fix"
],
- "link": "/embed"
+ "link": "/docs/embedding"
},
{
"date": "2026-07-27",
@@ -18809,4 +18828,4 @@
"link": "/trading"
}
]
-}
\ No newline at end of file
+}
diff --git a/docs/web-component.md b/docs/web-component.md
index 33e38afd4..a8710062d 100644
--- a/docs/web-component.md
+++ b/docs/web-component.md
@@ -892,7 +892,19 @@ Three URL channels are available. Pick based on how strictly you need to control
| `/agent-3d/<MAJOR>/agent-3d.js` | 5 min | Follow minor + patch releases. |
| `/agent-3d/latest/agent-3d.js` | 5 min | Demos and prototypes only. Never in production. |
-Current SRI hashes are at `/agent-3d/<version>/integrity.json`. The full release manifest is at `/agent-3d/versions.json`.
+Current SRI hashes are at `/agent-3d/<version>/integrity.json`. The full release manifest is at `/agent-3d/versions.json`, or from the origin API at `/api/agent-3d/versions`, which serves the identical JSON with an `ETag`:
+
+```bash
+curl -s https://three.ws/api/agent-3d/versions
+# {"latest":"1.5.2","channels":{…},"publishedAt":"2026-08-10T16:20:09.870Z"}
+
+# Poll cheaply: an unchanged manifest answers 304 with no body.
+curl -s -o /dev/null -w '%{http_code}\n' \
+ -H 'If-None-Match: "9yN2NE81wIeacx634mP3ShqfkuR"' \
+ https://three.ws/api/agent-3d/versions
+```
+
+Both are CORS-open (`access-control-allow-origin: *`) and cached for 60 seconds.
**Recommended production snippet:**
diff --git a/public/changelog.json b/public/changelog.json
index 07fd3c4d9..03e1073dc 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,33 @@
{
- "generated_at": "2026-08-09T09:53:46.176Z",
+ "generated_at": "2026-08-10T16:28:46.720Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-08-10",
+ "type": "update",
+ "title": "The embed release manifest answers cheap polls and says plainly when a build is missing",
+ "summary": "Sites that pin an <agent-3d> bundle version can poll /api/agent-3d/versions to learn about a new release. That endpoint now returns an ETag derived from the manifest contents, so a poller that sends the tag back gets an empty 304 Not Modified between releases instead of re-downloading the same JSON, and gets the full manifest the moment a new version publishes. When a deploy ships without the manifest the endpoint used to answer \"not found\" whether the file was missing or corrupt; it now says which of the two it is, so the fix is obvious from the response alone. The manifest is also documented for embedders alongside the static /agent-3d/versions.json copy.",
+ "link": "/docs/web-component",
+ "tags": [
+ "improvement",
+ "sdk"
+ ]
+ },
+ {
+ "date": "2026-08-10",
+ "type": "update",
+ "title": "The public asset catalog now answers a bad filter honestly",
+ "summary": "The open asset list at /api/assets, which anyone can call to browse our accessories, starter animations, and lighting environments, used to answer a mistyped filter with an empty list and a 200 OK, then cache that empty answer for an hour. A typo looked exactly like an empty catalog. It now returns a clear error naming the accepted values, and never caches it. Two more fixes came out of the same pass: browsers can read the response cross-origin on error replies and preflight checks, not just on success, and HEAD requests from uptime monitors and CDNs are answered instead of rejected. The environment list is also read straight from the viewer's own presets now, so names can no longer drift between the site and the API.",
+ "link": null,
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-08-09",
"type": "update",
diff --git a/server/index.mjs b/server/index.mjs
index cca4c992c..f51d842d5 100644
--- a/server/index.mjs
+++ b/server/index.mjs
@@ -501,7 +501,15 @@ app.use((err, req, res, next) => {
});
return;
}
- res.status(status).json({ error: 'bad_request', message: err.message });
+ // Same reason as the 413 branch above: client error paths read
+ // error/error_description, so a body-parser rejection that carried only
+ // `message` rendered as an empty reason next to every handler-emitted
+ // 4xx on the same endpoint.
+ res.status(status).json({
+ error: 'bad_request',
+ error_description: err.message,
+ message: err.message,
+ });
return;
}
console.error('[server] unexpected middleware error:', err);
diff --git a/specs/EMBED_SPEC.md b/specs/EMBED_SPEC.md
index ecab50c43..7f561f7c9 100644
--- a/specs/EMBED_SPEC.md
+++ b/specs/EMBED_SPEC.md
@@ -443,6 +443,8 @@ The bundle is published from the main app's deploy at `https://three.ws/agent-3d
The current SRI hash for each release lives in `/agent-3d/<version>/integrity.json`. The full release manifest (channels, current version, publish time) is `/agent-3d/versions.json` (max-age 60s).
+`GET /api/agent-3d/versions` returns the same manifest from the origin, with `access-control-allow-origin: *`, the same 60s cache policy, and a content-derived `ETag`. Send the tag back as `If-None-Match` and an unchanged manifest answers `304 Not Modified` with no body, so a release poller costs nothing between publishes. If a deploy ever ships without the manifest the endpoint answers `503 versions_unavailable` rather than an empty or partial body: treat it as "unknown, retry", never as "no releases".
+
UMD build available at the same path with `agent-3d.umd.cjs` if you can't use ES modules.
All bundle responses ship `access-control-allow-origin: *` and `cross-origin-resource-policy: cross-origin`, so the script loads fine from any origin.
diff --git a/tests/agent-3d-versions-endpoint.test.js b/tests/agent-3d-versions-endpoint.test.js
new file mode 100644
index 000000000..eb6703daf
--- /dev/null
+++ b/tests/agent-3d-versions-endpoint.test.js
@@ -0,0 +1,153 @@
+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+// The handler reads the real release manifest that `npm run publish:lib` writes,
+// so the tests drive the real file rather than a mocked fs: they stash whatever
+// the worktree already had, write the case under test, and restore on the way out.
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const MANIFEST = resolve(ROOT, 'dist/agent-3d/versions.json');
+
+const REAL_MANIFEST = {
+ latest: '1.5.2',
+ channels: {
+ '1.5.2': { integrity: { 'agent-3d.js': 'sha384-1YhqeXz6Um0NP1Re61RbrrE8i0RF9my8Sb+SOiN3X/OWqvkat1dSsPA/JFKv64kR' }, immutable: true },
+ '1.5': { tracks: '>=1.5.0 <1.6.0' },
+ 1: { tracks: '>=1.0.0 <2.0.0' },
+ latest: { tracks: '*' },
+ },
+ publishedAt: '2026-08-10T16:20:09.870Z',
+};
+
+let original = null;
+
+function writeManifest(body) {
+ mkdirSync(dirname(MANIFEST), { recursive: true });
+ writeFileSync(MANIFEST, typeof body === 'string' ? body : JSON.stringify(body, null, '\t') + '\n');
+}
+
+beforeAll(() => {
+ original = existsSync(MANIFEST) ? readFileSync(MANIFEST, 'utf8') : null;
+});
+
+afterAll(() => {
+ if (original === null) rmSync(MANIFEST, { force: true });
+ else writeManifest(original);
+});
+
+beforeEach(() => {
+ writeManifest(REAL_MANIFEST);
+});
+
+const { default: handler } = await import('../api/agent-3d/versions.js');
+
+function mkReq({ method = 'GET', headers = {} } = {}) {
+ return { method, url: '/api/agent-3d/versions', headers, socket: { remoteAddress: '127.0.0.1' } };
+}
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: undefined,
+ writableEnded: false,
+ headersSent: false,
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(b) {
+ this.body = b;
+ this.writableEnded = true;
+ },
+ };
+}
+
+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+async function call(reqInit) {
+ const req = mkReq(reqInit);
+ const res = mkRes();
+ await handler(req, res);
+ return res;
+}
+
+describe('GET /api/agent-3d/versions', () => {
+ it('serves the release manifest with public cache headers and an ETag', async () => {
+ const res = await call();
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toEqual(REAL_MANIFEST);
+ expect(res.headers['content-type']).toMatch(/application\/json/);
+ expect(res.headers['cache-control']).toBe('public, max-age=60, s-maxage=60, stale-while-revalidate=300');
+ expect(res.headers['access-control-allow-origin']).toBe('*');
+ expect(res.headers.etag).toMatch(/^"[\w-]{27}"$/);
+ });
+
+ it('answers HEAD like GET', async () => {
+ const res = await call({ method: 'HEAD' });
+ expect(res.statusCode).toBe(200);
+ expect(res.headers.etag).toBeTruthy();
+ });
+
+ it('answers a matching conditional request with a bodyless 304', async () => {
+ const first = await call();
+ const res = await call({ headers: { 'if-none-match': first.headers.etag } });
+ expect(res.statusCode).toBe(304);
+ expect(res.body).toBeUndefined();
+ expect(res.headers.etag).toBe(first.headers.etag);
+ });
+
+ it('honours weak validators, tag lists, and the * validator', async () => {
+ const { etag } = await call().then((r) => r.headers);
+ for (const header of [`W/${etag}`, `"nomatch", ${etag}`, '*']) {
+ expect((await call({ headers: { 'if-none-match': header } })).statusCode).toBe(304);
+ }
+ expect((await call({ headers: { 'if-none-match': '"nomatch"' } })).statusCode).toBe(200);
+ });
+
+ it('re-reads the manifest after a rebuild rewrites it, and re-derives the ETag', async () => {
+ const before = await call();
+ writeManifest({ ...REAL_MANIFEST, latest: '1.6.0' });
+ const after = await call();
+ expect(parse(after).latest).toBe('1.6.0');
+ expect(after.headers.etag).not.toBe(before.headers.etag);
+ // A validator held from before the rebuild must not win, or an embedder would
+ // stay pinned to a superseded release.
+ const stale = await call({ headers: { 'if-none-match': before.headers.etag } });
+ expect(stale.statusCode).toBe(200);
+ });
+
+ it('rejects writes with 405 and advertises the readable methods', async () => {
+ const res = await call({ method: 'POST' });
+ expect(res.statusCode).toBe(405);
+ expect(parse(res).error).toBe('method_not_allowed');
+ expect(res.headers.allow).toBe('GET, HEAD');
+ });
+
+ it('short-circuits a CORS preflight with 204', async () => {
+ const res = await call({ method: 'OPTIONS', headers: { origin: 'https://example.com' } });
+ expect(res.statusCode).toBe(204);
+ expect(res.headers['access-control-allow-methods']).toBe('GET,HEAD,OPTIONS');
+ });
+
+ it('returns an uncacheable 503 naming the build step when the manifest is missing', async () => {
+ rmSync(MANIFEST, { force: true });
+ const res = await call();
+ expect(res.statusCode).toBe(503);
+ expect(parse(res).error).toBe('versions_unavailable');
+ expect(parse(res).error_description).toContain('publish:lib');
+ expect(parse(res).error_description).toContain('missing');
+ expect(res.headers['cache-control']).toBe('no-store');
+ });
+
+ it('distinguishes a corrupt manifest from a missing one', async () => {
+ writeManifest('{ not json');
+ const res = await call();
+ expect(res.statusCode).toBe(503);
+ expect(parse(res).error).toBe('versions_unavailable');
+ expect(parse(res).error_description).toContain('not valid JSON');
+ });
+});
diff --git a/vercel.json b/vercel.json
index e4262d30d..0718d45a2 100644
--- a/vercel.json
+++ b/vercel.json
@@ -542,6 +542,18 @@
"src": "/api/agents/solana-skill-collection-metadata",
"dest": "/api/agents/solana/[action]?action=skill-collection-metadata"
},
+ {
+ "src": "/api/agents/solana/skill-collection-metadata",
+ "dest": "/api/agents/solana/[action]?action=skill-collection-metadata"
+ },
+ {
+ "src": "/api/agents/solana/skill-nft-metadata",
+ "dest": "/api/agents/solana/[action]?action=skill-nft-metadata"
+ },
+ {
+ "src": "/api/agents/solana-skill-nft-metadata",
+ "dest": "/api/agents/solana/[action]?action=skill-nft-metadata"
+ },
{
"src": "/api/agents/solana-edit",
"dest": "/api/agents/solana/[action]?action=edit"
@@ -3754,6 +3766,10 @@
"src": "/api/avatars/library",
"dest": "/api/avatars/library"
},
+ {
+ "src": "/api/avatars/popular-searches",
+ "dest": "/api/avatars/popular-searches"
+ },
{
"src": "/api/avatars/draft/([^/]+)",
"dest": "/api/avatars/draft/[id]?id=$1"