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): harden the scene-gate, stage, swarm, skills and share handlers across the fleet

nirholasf089cafec216
diff --git a/.env.example b/.env.example
index 9d0335759..d5281dfde 100644
--- a/.env.example
+++ b/.env.example
@@ -1442,12 +1442,16 @@ LIVEKIT_SERVER_URL=
# Get a key at https://aistudio.google.com.
GEMINI_API_KEY=
-# Neynar (Farcaster) — powers /api/seed/farcaster social-memory seeding.
-# Get a key at https://neynar.com.
+# Neynar (Farcaster) - the indexed lane for Farcaster social-memory seeding.
+# Optional: without it /api/seed/farcaster reads a public Farcaster hub
+# (FARCASTER_HUB_URL) keyless, minus the follower and reaction counts only an
+# indexer has. Get a key at https://neynar.com.
NEYNAR_API_KEY=
-# X (Twitter) — read-only public-data bearer token used by /api/seed/x.
-# Get one from https://developer.twitter.com (Read access).
+# X (Twitter) - read-only public-data bearer token used by /api/seed/x.
+# Get one from https://developer.twitter.com (Read access). Optional when the
+# OAuth 1.0a app pair below is set: /api/seed/x exchanges X_API_KEY and
+# X_API_SECRET for the same app-only bearer at runtime.
TWITTER_BEARER_TOKEN=
# X (Twitter) posting — OAuth 1.0a user context for @trythreews, used by
diff --git a/api/_lib/og-avatar.js b/api/_lib/og-avatar.js
new file mode 100644
index 000000000..e1c2b1c6e
--- /dev/null
+++ b/api/_lib/og-avatar.js
@@ -0,0 +1,88 @@
+/**
+ * Size-capped remote image fetch for dynamic OG cards.
+ *
+ * Every OG handler that inlines a portrait does the same three things: fetch the
+ * URL, base64 it, and drop it into an `<image href="data:...">`. The URL comes
+ * from user-controlled profile data (`agent_identities.profile_image_url`,
+ * an avatar thumbnail), so a naive `await resp.arrayBuffer()` lets any account
+ * point a crawler-facing endpoint at an arbitrarily large body and pull all of it
+ * into the render process. A 1200x630 portrait needs a few hundred KB at most.
+ *
+ * This helper is the one place that boundary is enforced:
+ * - only http(s) URLs are fetched at all,
+ * - the response must declare an image content type,
+ * - a declared content-length over the cap is rejected before reading a byte,
+ * - the body is streamed and abandoned the moment it crosses the cap, so a
+ * server that omits or lies about content-length cannot get past it either.
+ *
+ * It never throws. A dead host, a timeout, an HTML error page, or an oversized
+ * body all return null, which every caller already renders as a monogram.
+ */
+
+/** A portrait that does not fit in 1.5 MB is not a portrait we want to inline. */
+export const MAX_OG_IMAGE_BYTES = 1_500_000;
+
+const DEFAULT_TIMEOUT_MS = 3000;
+
+/**
+ * @param {string|null|undefined} url remote image URL (user-supplied)
+ * @param {{ timeoutMs?: number, maxBytes?: number }} [opts]
+ * @returns {Promise<{ ct: string, b64: string }|null>} inline-ready image, or null
+ */
+export async function fetchOgImage(url, opts = {}) {
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const maxBytes = opts.maxBytes ?? MAX_OG_IMAGE_BYTES;
+
+ if (typeof url !== 'string' || !/^https?:\/\//i.test(url)) return null;
+
+ try {
+ const resp = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
+ if (!resp.ok) return null;
+
+ const ct = resp.headers.get('content-type') || '';
+ if (!/^image\//i.test(ct)) return null;
+
+ const declared = Number(resp.headers.get('content-length') || 0);
+ if (declared > maxBytes) return null;
+
+ const bytes = await readCapped(resp, maxBytes);
+ if (!bytes) return null;
+
+ return { ct: ct.split(';')[0].trim(), b64: Buffer.from(bytes).toString('base64') };
+ } catch {
+ // A slow host, a DNS failure, or an aborted read is never worth a broken
+ // unfurl. The caller draws its monogram instead.
+ return null;
+ }
+}
+
+/**
+ * Read at most `maxBytes` from a fetch response, returning null the moment the
+ * body proves larger. Falls back to a buffered read only when the runtime gave us
+ * no stream to walk, in which case content-length above is the only guard left.
+ */
+async function readCapped(resp, maxBytes) {
+ if (!resp.body || typeof resp.body.getReader !== 'function') {
+ const buf = Buffer.from(await resp.arrayBuffer());
+ return buf.byteLength > maxBytes ? null : buf;
+ }
+
+ const reader = resp.body.getReader();
+ const chunks = [];
+ let total = 0;
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > maxBytes) {
+ await reader.cancel();
+ return null;
+ }
+ chunks.push(value);
+ }
+ } finally {
+ reader.releaseLock?.();
+ }
+ return Buffer.concat(chunks.map((c) => Buffer.from(c)), total);
+}
diff --git a/api/_lib/referrals.js b/api/_lib/referrals.js
index 3ca3e0e36..38187980b 100644
--- a/api/_lib/referrals.js
+++ b/api/_lib/referrals.js
@@ -162,7 +162,7 @@ export async function getReferralCodeAvailability(userId, desired) {
export async function setReferralCode(userId, desired) {
const code = normalizeReferralCode(desired);
if (!code) {
- throw new ReferralCodeError('invalid', 400, `Use ${REFERRAL_CODE_MIN_LEN}–${REFERRAL_CODE_MAX_LEN} letters or numbers (no spaces or symbols).`);
+ throw new ReferralCodeError('invalid', 400, `Use ${REFERRAL_CODE_MIN_LEN} to ${REFERRAL_CODE_MAX_LEN} letters or numbers (no spaces or symbols).`);
}
if (isReservedReferralCode(code)) {
throw new ReferralCodeError('reserved', 409, 'That code is reserved. Pick another.');
diff --git a/api/_lib/rss-feed.js b/api/_lib/rss-feed.js
index 9d7d12c39..8e561642b 100644
--- a/api/_lib/rss-feed.js
+++ b/api/_lib/rss-feed.js
@@ -1,7 +1,7 @@
// Build an RSS 2.0 feed for HackerNoon's "Auto Import" ingester (also valid
// for any standard reader). Two sources:
-// - curated: data/rss/items.json (default — hand-edited, full editorial control)
-// - archive: data/archives/*.json (scraped X posts — fallback / mirror mode)
+// - curated: data/rss/items.json (default, hand-edited, full editorial control)
+// - archive: data/archives/*.json (scraped X posts, fallback / mirror mode)
import { readdir, readFile } from 'node:fs/promises';
import path from 'node:path';
diff --git a/api/_lib/solana-attestations.js b/api/_lib/solana-attestations.js
index 464b94576..12e9c08bf 100644
--- a/api/_lib/solana-attestations.js
+++ b/api/_lib/solana-attestations.js
@@ -101,8 +101,37 @@ export function attesterFromTx(tx) {
|| null;
}
+// Does this RPC error mean our stored cursor is no longer in the node's ledger?
+//
+// getSignaturesForAddress({ until }) resolves `until` against the node's own
+// history and fails the WHOLE call with "Transaction <sig> not found" once that
+// signature has been pruned. Because we only ever store the newest signature we
+// saw, a pruned cursor is terminal: every later tick presents the same dead
+// signature, gets the same error, and never advances. The asset stops indexing
+// permanently, and the cron still reports 200 because the handler catches per
+// agent, so nothing pages. Detect it and re-scan from the head instead.
+export function isPrunedCursorError(err) {
+ const msg = err?.message || String(err || '');
+ return /Transaction .* not found/i.test(msg) || /failed to get signatures for address/i.test(msg);
+}
+
+// Signatures newer than the cursor, self-healing past a pruned cursor.
+//
+// The retry drops `until` and takes the most recent `limit` signatures instead.
+// That is safe to replay: every row lands through `on conflict (signature) do
+// nothing`, so re-reading a window we already indexed inserts nothing twice.
+export async function signaturesSinceCursor(conn, agentKey, limit, until) {
+ try {
+ return { sigs: await conn.getSignaturesForAddress(agentKey, { limit, until }), cursorReset: false };
+ } catch (err) {
+ if (!until || !isPrunedCursorError(err)) throw err;
+ const sigs = await conn.getSignaturesForAddress(agentKey, { limit });
+ return { sigs, cursorReset: true };
+ }
+}
+
// Crawl recent signatures for one agent and upsert into solana_attestations.
-// Returns { scanned, inserted, skipped }.
+// Returns { scanned, inserted, skipped, cursorReset }.
export async function crawlAgentAttestations({ agentAsset, network, ownerWallet, limit = 200 }) {
const conn = solanaConnection({ url: RPC[network] || RPC.devnet, commitment: 'confirmed' });
const agentKey = new PublicKey(agentAsset);
@@ -114,14 +143,18 @@ export async function crawlAgentAttestations({ agentAsset, network, ownerWallet,
`;
const until = cursor?.last_signature || undefined;
- const sigs = await conn.getSignaturesForAddress(agentKey, { limit, until });
+ const { sigs, cursorReset } = await signaturesSinceCursor(conn, agentKey, limit, until);
if (sigs.length === 0) {
+ // A reset cursor must NOT be written back: re-storing the pruned signature
+ // would re-arm the exact stall this recovery exists to clear.
+ const keep = cursorReset ? null : until || null;
await sql`
insert into solana_attestations_cursor (agent_asset, network, last_signature, last_indexed_at)
- values (${agentAsset}, ${network}, ${until || null}, now())
- on conflict (agent_asset) do update set last_indexed_at = now()
+ values (${agentAsset}, ${network}, ${keep}, now())
+ on conflict (agent_asset) do update
+ set last_signature = excluded.last_signature, last_indexed_at = now()
`;
- return { scanned: 0, inserted: 0, skipped: 0 };
+ return { scanned: 0, inserted: 0, skipped: 0, cursorReset };
}
const txs = await conn.getTransactions(
@@ -182,7 +215,7 @@ export async function crawlAgentAttestations({ agentAsset, network, ownerWallet,
set last_signature = excluded.last_signature, last_indexed_at = now()
`;
- return { scanned: sigs.length, inserted, skipped };
+ return { scanned: sigs.length, inserted, skipped, cursorReset };
}
// Verify rules — applied at index time, can be re-run.
diff --git a/api/_lib/token/price.js b/api/_lib/token/price.js
index f1d187f89..160202f75 100644
--- a/api/_lib/token/price.js
+++ b/api/_lib/token/price.js
@@ -103,10 +103,18 @@ export async function getTokenPriceUsd({ fresh = false } = {}) {
/**
* Quote a USD amount as a token amount at the current live price.
+ *
+ * Pass `price` when the caller already resolved one this request (the
+ * /api/token/price display path does): the quote is then computed against the
+ * exact price the caller reports back, instead of a second lookup that can
+ * land on the other side of the 30s cache boundary and hand the client a
+ * `token_amount` that does not match the `price_usd` printed beside it.
+ *
* @param {number} usd positive USD amount to convert
+ * @param {{ price?: { priceUsd: number, source: string, at: string } }} [opts]
* @returns {Promise<{ usd: number, priceUsd: number, source: string, priceAt: string, tokenAmount: number, atomics: bigint }>}
*/
-export async function quoteTokenForUsd(usd) {
+export async function quoteTokenForUsd(usd, { price } = {}) {
const usdNum = Number(usd);
if (!Number.isFinite(usdNum) || usdNum <= 0) {
throw Object.assign(new Error('usd must be a positive number'), {
@@ -114,12 +122,24 @@ export async function quoteTokenForUsd(usd) {
code: 'bad_request',
});
}
- const { priceUsd, source, at } = await getTokenPriceUsd();
+ const { priceUsd, source, at } = price ?? (await getTokenPriceUsd());
const tokenAmount = usdNum / priceUsd;
// Convert to atomics with BigInt to avoid float drift on large token counts:
// floor(tokenAmount * 10^decimals). We scale through micro-precision on the
// USD/price ratio so a sub-cent price still rounds correctly.
const scaled = Math.round(tokenAmount * Number(ATOMICS_PER_TOKEN));
+ // A sub-cent price divides a large USD figure into a token count whose
+ // atomics overflow the float64 range (usd 1e300 at $0.0017 scales past
+ // Number.MAX_VALUE), and `BigInt(Infinity)` is a RangeError, not a typed
+ // failure. Left unguarded that turned a client-supplied `?usd=` into an
+ // unhandled 500 with a Sentry capture and an ops alert per hit. Reject it
+ // here as the amount error it actually is, alongside the too-small guard.
+ if (!Number.isFinite(scaled)) {
+ throw Object.assign(new Error('quoted amount exceeds the representable range'), {
+ status: 422,
+ code: 'amount_too_large',
+ });
+ }
const atomics = BigInt(scaled);
if (atomics <= 0n) {
throw Object.assign(new Error('quoted amount rounds to zero at current price'), {
diff --git a/api/_lib/x-post.js b/api/_lib/x-post.js
index a82f2c206..0201f585e 100644
--- a/api/_lib/x-post.js
+++ b/api/_lib/x-post.js
@@ -40,7 +40,7 @@ export async function getUserTier(userId) {
async function refreshIfNeeded(conn) {
const expiresAt = conn.expires_at ? new Date(conn.expires_at).getTime() : 0;
if (expiresAt - Date.now() > 60_000) return decryptToken(conn.access_token);
- if (!conn.refresh_token) throw new XPostError('reauth_required', 'refresh_token missing — reconnect X account', 401);
+ if (!conn.refresh_token) throw new XPostError('reauth_required', 'refresh_token missing, reconnect X account', 401);
const refreshToken = decryptToken(conn.refresh_token);
const creds = Buffer.from(`${env.X_OAUTH_CLIENT_ID}:${env.X_OAUTH_CLIENT_SECRET}`).toString('base64');
diff --git a/api/_mcpagent/discovery.js b/api/_mcpagent/discovery.js
new file mode 100644
index 000000000..29be135d7
--- /dev/null
+++ b/api/_mcpagent/discovery.js
@@ -0,0 +1,134 @@
+// Bazaar discovery + service metadata for the hosted Agent-wallet MCP endpoint.
+//
+// The 402 challenge an unauthenticated/unpaid caller receives carries this
+// metadata so x402 facilitators (CDP Bazaar, agentic.market, x402scan) index
+// /api/mcp-agent with its own service name, tags, icon, and a v2 `bazaar`
+// extension describing the JSON-RPC tools/call shape. Without it the endpoint
+// inherited the main /api/mcp envelope: it advertised itself as the avatar and
+// model-validation server AND, worse, quoted `resource: .../api/mcp` inside
+// every accepts[] entry, so a paying agent signed a payment scoped to a
+// resource it never called. Mirrors api/_mcpbazaar/discovery.js and
+// api/_mcp3d/discovery.js.
+
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+
+export const RESOURCE_DESCRIPTION =
+ 'three.ws Agent MCP: Streamable HTTP (MCP 2025-06-18) that gives an assistant a real on-chain ' +
+ 'wallet on the x402 network: wallet_status (address, USDC and SOL balance, spend caps), ' +
+ 'find_services (search the live facilitator network for paid services), pay_and_call (call a ' +
+ 'paid x402 endpoint and settle the USDC payment from the signed-in user own three.ws agent ' +
+ 'wallet, bounded by their caps), provision_wallet, and monetize_endpoint (list your own paid ' +
+ 'service). Connect with a three.ws account (OAuth) or pay per call in USDC on Base or Solana ' +
+ 'mainnet, no API key. Operated by three.ws.';
+
+// Endpoint-level v2 bazaar discovery entry, shaped exactly like the validator
+// expects (see api/_lib/x402-spec.js, bazaarExtension). The advertised example
+// is find_services: a read-only search, so a facilitator probing the documented
+// call can never move a caller's funds.
+function agentBazaarExtension() {
+ const exampleBody = {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: {
+ name: 'find_services',
+ arguments: { query: 'weather', type: 'http', limit: 5 },
+ },
+ };
+ const exampleResponse = {
+ jsonrpc: '2.0',
+ id: 1,
+ result: {
+ content: [
+ {
+ type: 'text',
+ text: '1. Weather Now - $0.001\n https://api.example.com/weather',
+ },
+ ],
+ structuredContent: {
+ query: 'weather',
+ count: 1,
+ services: [
+ {
+ resource: 'https://api.example.com/weather',
+ name: 'Weather Now',
+ price: '$0.001',
+ networks: ['eip155:8453'],
+ },
+ ],
+ },
+ },
+ };
+ const requestBodySchema = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['jsonrpc', 'method'],
+ properties: {
+ jsonrpc: { type: 'string', const: '2.0' },
+ id: { type: ['string', 'number'] },
+ method: {
+ type: 'string',
+ enum: ['initialize', 'tools/list', 'tools/call', 'ping'],
+ description: 'MCP JSON-RPC method.',
+ },
+ params: {
+ type: 'object',
+ description:
+ 'For tools/call: { name, arguments }. Tool names: getting_started (free), wallet_status, find_services, pay_and_call, provision_wallet, monetize_endpoint, see tools/list.',
+ },
+ },
+ };
+ const responseBodySchema = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ jsonrpc: { type: 'string', const: '2.0' },
+ id: { type: ['string', 'number'] },
+ result: {
+ type: 'object',
+ properties: {
+ content: {
+ type: 'array',
+ items: {
+ type: 'object',
+ required: ['type', 'text'],
+ properties: {
+ type: { type: 'string', enum: ['text'] },
+ text: { type: 'string' },
+ },
+ },
+ },
+ },
+ },
+ error: {
+ type: 'object',
+ properties: { code: { type: 'number' }, message: { type: 'string' } },
+ },
+ },
+ };
+ return {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'POST', body: exampleBody, bodyType: 'json' },
+ output: { type: 'json', example: exampleResponse },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodyType: 'json',
+ bodySchema: requestBodySchema,
+ outputSchema: responseBodySchema,
+ }),
+ };
+}
+
+// The challenge override block threaded into authenticateRequest/handleSse so
+// the 402 envelope advertises Agent-wallet service metadata + discovery.
+export const AGENT_CHALLENGE = {
+ description: RESOURCE_DESCRIPTION,
+ bazaar: agentBazaarExtension(),
+ ...withService({
+ serviceName: 'three.ws Agent MCP',
+ tags: ['x402', 'mcp', 'wallet', 'payments', 'agent'],
+ }),
+};
diff --git a/api/clip-director.js b/api/clip-director.js
index 1a0785e4d..a90c319d4 100644
--- a/api/clip-director.js
+++ b/api/clip-director.js
@@ -102,12 +102,32 @@ async function handleGet(req, res, userId) {
});
}
+// Every string on this path is caller-supplied and ends up inside an LLM prompt
+// (directClip drives llmComplete), so each one is length-clamped at the
+// boundary. Unclamped, a single anonymous POST could push a megabyte of text
+// through the whole provider chain. The GET path needs none of this: its agent
+// name and trade both come from our own tables.
+const BODY_MAX_BYTES = 8_000;
+
+function clampText(v, max) {
+ if (typeof v !== 'string') return null;
+ const s = v.trim();
+ return s ? s.slice(0, max) : null;
+}
+
async function handlePost(req, res, userId) {
let body;
- try { body = await readJson(req); } catch { return error(res, 400, 'invalid_json', 'Body must be JSON.'); }
+ try {
+ body = await readJson(req, BODY_MAX_BYTES);
+ } catch (err) {
+ if (err?.status === 413) {
+ return error(res, 413, 'body_too_large', `Body must be under ${BODY_MAX_BYTES} bytes.`);
+ }
+ return error(res, 400, 'invalid_json', 'Body must be JSON.');
+ }
const trade = body?.trade;
- if (!trade || typeof trade !== 'object') {
+ if (!trade || typeof trade !== 'object' || Array.isArray(trade)) {
return error(res, 400, 'invalid_trade', 'trade object is required (symbol, multiple or realized_pnl_sol, etc.).');
}
// Accept a raw position row too, normalize either shape.
@@ -116,11 +136,12 @@ async function handlePost(req, res, userId) {
: normalizeTrade(trade);
const surface = SURFACES.has(body?.surface) ? body.surface : 'feed';
+ const copiedByCount = Math.max(0, Math.min(1e9, Math.trunc(Number(body?.copied_by_count)) || 0));
const clip = await directClip({
- agentName: body?.agent_name || 'the agent',
- avatarStyle: body?.avatar_style || null,
+ agentName: clampText(body?.agent_name, 80) || 'the agent',
+ avatarStyle: clampText(body?.avatar_style, 40),
trade: shaped,
- copiedByCount: Number(body?.copied_by_count) || 0,
+ copiedByCount,
surface,
userId,
});
@@ -129,23 +150,27 @@ async function handlePost(req, res, userId) {
}
function normalizeTrade(t) {
- const num = (v) => (v == null || v === '' ? null : Number(v));
+ const num = (v) => {
+ if (v == null || v === '') return null;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+ };
const pnl = num(t.realized_pnl_sol ?? t.realized_pnl_quote);
const pct = num(t.pnl_pct);
return {
- mint: t.mint || null,
- symbol: t.symbol || null,
- name: t.name || null,
+ mint: clampText(t.mint, 64),
+ symbol: clampText(t.symbol, 32),
+ name: clampText(t.name, 80),
multiple: num(t.multiple),
pnl_pct: pct,
entry_sol: num(t.entry_sol),
exit_sol: num(t.exit_sol),
realized_pnl_sol: pnl,
hold_min: num(t.hold_min),
- exit_reason: t.exit_reason || null,
+ exit_reason: clampText(t.exit_reason, 40),
quote_symbol: 'SOL',
is_win: pnl != null ? pnl >= 0 : (pct != null ? pct >= 0 : null),
- sell_sig: t.sell_sig || null,
+ sell_sig: clampText(t.sell_sig, 100),
};
}
diff --git a/api/commit-og.js b/api/commit-og.js
index c26c5ed31..20d103119 100644
--- a/api/commit-og.js
+++ b/api/commit-og.js
@@ -1,4 +1,4 @@
-// api/commit-og.js — social-share landing for a single commit in the
+// api/commit-og.js: social-share landing for a single commit in the
// auto-posted commit feed (api/_lib/commit-feed-push.js). Its only job is to
// carry per-commit Open Graph tags so Telegram, X, and iMessage render a
// branded three.ws poster card for each commit post instead of GitHub's
@@ -56,7 +56,7 @@ export default function handler(req, res) {
const title = esc(headline);
const descParts = [body, [date, author].filter(Boolean).join(' · ')].filter(Boolean);
- const description = esc(descParts.join(' — '));
+ const description = esc(descParts.join(' · '));
res.statusCode = 200;
res.setHeader('content-type', 'text/html; charset=utf-8');
diff --git a/api/config.js b/api/config.js
index d7c464972..2cc2d79c8 100644
--- a/api/config.js
+++ b/api/config.js
@@ -27,7 +27,7 @@ export default wrap(async (req, res) => {
// before being bridged into /mocap-studio.
const liveBodyMocapEnabled = /^(1|true|on)$/i.test((process.env.LIVE_BODY_MOCAP || '').trim());
- // Enterprise SAML SSO — true when an IdP is wired (explicit cert + SSO URL,
+ // Enterprise SAML SSO, true when an IdP is wired (explicit cert + SSO URL,
// or a metadata URL to fetch them from). Drives the SSO button on /login.
// Cheap env-only check so this hot endpoint doesn't pull in the SAML lib.
const samlEnabled = Boolean(
@@ -47,7 +47,7 @@ export default wrap(async (req, res) => {
samlLabel: process.env.SAML_BUTTON_LABEL || 'Single sign-on (SSO)',
features: {
// avatarReconstruct is always true: BYOK providers (Meshy, Tripo) are
- // always available — the selfie page handles key entry inline when the
+ // always available, and the selfie page handles key entry inline when the
// platform backend isn't configured. The reconstruct endpoint returns
// { code: 'regen_needs_byok' } rather than 501 in that case.
avatarReconstruct: true,
diff --git a/api/cosmos.js b/api/cosmos.js
index c288d6eee..65f09f133 100644
--- a/api/cosmos.js
+++ b/api/cosmos.js
@@ -1,19 +1,19 @@
/**
- * /api/cosmos — text → animated WORLD video on the free NVIDIA Cosmos lane.
+ * /api/cosmos: text to an animated WORLD video on the free NVIDIA Cosmos lane.
*
* POST /api/cosmos { prompt: string, seed?: number }
- * → 202 { job_id, status, eta_seconds } (async — poll for the clip)
+ * → 202 { job_id, status, eta_seconds } (async, poll for the clip)
* → 200 { status:'done', video_url } (rare synchronous completion)
*
* GET /api/cosmos?job=<id>
* → { job_id, status, video_url?, error? }
*
* Cosmos is NVIDIA's World Foundation Model family. The Text2World predict model
- * renders a short photoreal video of a world from a prompt — we play it as a
+ * renders a short photoreal video of a world from a prompt, and we play it as a
* living backdrop behind a 3D avatar (see /cosmos). The job runs on NVIDIA's NVCF
* async gateway: submit returns a request id, we hand it back as job_id, and the
* GET poll asks NVCF for status and (on completion) persists the MP4 to R2,
- * returning a durable URL. There is no server-side job store — the NVCF request
+ * returning a durable URL. There is no server-side job store: the NVCF request
* id IS the durable handle, exactly like the TRELLIS text→3D lane.
*
* Reuses the platform NVIDIA_API_KEY (free NIM tier). When it is absent the lane
@@ -26,7 +26,7 @@ import { createNvidiaCosmosProvider, nvidiaCosmosConfigured } from './_providers
const JOB_ID_RE = /^[A-Za-z0-9_-]{20,64}$/;
// Cosmos predict renders ~5 s of 1280×704 @ 24fps video; on the shared free tier
-// that typically lands in 60–120 s. Surfaced to the client so the loading state
+// that typically lands in 60-120 s. Surfaced to the client so the loading state
// can set honest expectations instead of an open-ended spinner.
const ETA_SECONDS = 90;
@@ -50,7 +50,7 @@ async function startJob(req, res) {
if (prompt.length < 3 || prompt.length > 300) {
return json(res, 400, {
error: 'invalid_prompt',
- message: 'Describe the world in 3–300 characters (e.g. "a neon Tokyo street in the rain at night").',
+ message: 'Describe the world in 3-300 characters (e.g. "a neon Tokyo street in the rain at night").',
});
}
const seed = Number.isFinite(Number(body?.seed)) ? Math.trunc(Number(body.seed)) : undefined;
@@ -64,7 +64,7 @@ async function startJob(req, res) {
try {
const result = await provider.textToWorld({ prompt, seed });
- // Synchronous completion (uncommon for video) — hand back the clip directly.
+ // Synchronous completion (uncommon for video), hand back the clip directly.
if (result.resultVideoUrl) {
return json(res, 200, { status: 'done', video_url: result.resultVideoUrl });
}
diff --git a/api/creations-leaderboard.js b/api/creations-leaderboard.js
index ddc691b11..0524263cd 100644
--- a/api/creations-leaderboard.js
+++ b/api/creations-leaderboard.js
@@ -1,5 +1,5 @@
/**
- * Creator marketplace leaderboards (roadmap prompt 09) — the "make discovery
+ * Creator marketplace leaderboards (roadmap prompt 09): the "make discovery
* feel alive" surface for the /creations gallery.
*
* GET /api/creations-leaderboard
@@ -7,16 +7,16 @@
*
* Two REAL, queried rankings, no synthetic scores:
* - topRemixedAssets: the most-remixed published forge_creations, platform-
- * wide — a live count of child derivatives (api/_lib/forge-store.js
+ * wide, a live count of child derivatives (api/_lib/forge-store.js
* listMostRemixed). Same data the /creations gallery's "Trending" sort
* reads from api/remix-feed.js?action=trending; this endpoint additionally
* bundles the creator leaderboard in one round trip for the gallery page.
* - topCreators: agents ranked by how much OTHER creators built on their
- * minted 3D work — a real count of tokenized_3d_assets rows naming one of
+ * minted 3D work, a real count of tokenized_3d_assets rows naming one of
* theirs as parent_mint, plus the real on-chain USDC royalty earned
* (api/_lib/tokenized-launches.js queryTopCreators). This is the only
* creator surface with a public, on-chain identity (agent_identities +
- * its ERC-8004 registration) to link a leaderboard entry to — the
+ * its ERC-8004 registration) to link a leaderboard entry to: the
* forge_creations client_key is intentionally anonymous.
*
* Free, public, cached briefly at the edge. $THREE-policy clean: no coin
diff --git a/api/creations.js b/api/creations.js
index c0ae61bf4..1b48b1931 100644
--- a/api/creations.js
+++ b/api/creations.js
@@ -1,15 +1,15 @@
-// Creations — the creator-gallery + remix-economy backend.
+// Creations: the creator-gallery + remix-economy backend.
//
// This is the discovery/remix surface layered ON TOP OF the existing Loom
// gallery (api/loom.js): Loom remains the single source of truth for "a creation
// is a forged GLB + prompt + attribution", and this endpoint enriches that feed
// with the things a *creator-facing* product needs and Loom deliberately omits:
//
-// · gallery metadata — title, tags, license, type/style, creator binding
-// · remix lineage — parent→child edges, ancestry + descendants
-// · creator aggregates — per-creator creation count, remixes earned, follows
-// · discovery ranking — trending (most-remixed) assets, top creators
-// · signed-ready provenance — an append-only per-creation trail (origin + remix)
+// · gallery metadata: title, tags, license, type/style, creator binding
+// · remix lineage: parent to child edges, ancestry + descendants
+// · creator aggregates: per-creator creation count, remixes earned, follows
+// · discovery ranking: trending (most-remixed) assets, top creators
+// · signed-ready provenance: an append-only per-creation trail (origin + remix)
//
// It never forks Loom: it imports Loom's storage + validators directly so a
// publish writes one canonical record to the same feed every other surface
@@ -17,15 +17,14 @@
// HTTP/MCP contract is unchanged.
//
// ── Storage (Upstash Redis when configured, in-process maps otherwise) ─────────
-// cre:meta:<id> — gallery overlay JSON for a creation
-// cre:children:<parentId> — list of child creation ids (remix lineage)
-// cre:prov:<id> — append-only provenance entries for a creation
-// cre:creator:<key> — creator aggregate record
-// cre:followers:<key> — set (list) of follower ids
-// cre:index — capped list of all overlaid creation ids (newest-first)
-// cre:remixfeed — capped list of recent remix events (for trending window)
+// cre:meta:<id> : gallery overlay JSON for a creation
+// cre:children:<parentId> : list of child creation ids (remix lineage)
+// cre:prov:<id> : append-only provenance entries for a creation
+// cre:creator:<key> : creator aggregate record
+// cre:followers:<key> : set (list) of follower ids
+// cre:remixfeed : capped list of recent remix events (for trending window)
// In dev / tests without Redis the same operations run against module-level maps
-// so the endpoint is fully functional offline — mirroring api/loom.js exactly.
+// so the endpoint is fully functional offline, mirroring api/loom.js exactly.
import { randomUUID } from 'node:crypto';
import { cors, json, error, readJson, wrap, method, setRateLimitHeaders } from './_lib/http.js';
@@ -47,10 +46,8 @@ const CHILDREN_KEY = (id) => `cre:children:${id}`;
const PROV_KEY = (id) => `cre:prov:${id}`;
const CREATOR_KEY = (key) => `cre:creator:${key}`;
const FOLLOWERS_KEY = (key) => `cre:followers:${key}`;
-const INDEX_KEY = 'cre:index';
const REMIX_FEED_KEY = 'cre:remixfeed';
-const INDEX_CAP = 4000;
const REMIX_FEED_CAP = 2000;
const DEFAULT_LIMIT = 36;
const MAX_LIMIT = 120;
@@ -66,7 +63,7 @@ const LICENSES = {
'remix-cc': { label: 'Remix freely', remixable: true, commercial: true, note: 'Anyone may remix and use commercially.' },
'remix-nc': { label: 'Remix · non-commercial', remixable: true, commercial: false, note: 'Remix freely; no commercial use.' },
'remix-royalty': { label: 'Remix · royalty', remixable: true, commercial: true, note: 'Remix allowed; royalties route to the original creator on mint.' },
- 'all-rights': { label: 'All rights reserved', remixable: false, commercial: false, note: 'Display only — no remixing.' },
+ 'all-rights': { label: 'All rights reserved', remixable: false, commercial: false, note: 'Display only, no remixing.' },
};
const DEFAULT_LICENSE = 'remix-cc';
@@ -82,7 +79,6 @@ const mem = {
prov: new Map(), // id -> entry[]
creators: new Map(),
followers: new Map(), // key -> Set
- index: [], // newest-first ids
remixFeed: [], // newest-first remix events
};
@@ -109,14 +105,9 @@ async function putMeta(meta) {
const r = getRedis();
if (!r) {
mem.meta.set(meta.id, meta);
- mem.index.unshift(meta.id);
- if (mem.index.length > INDEX_CAP) mem.index.length = INDEX_CAP;
return meta;
}
- const payload = JSON.stringify(meta);
- await r.set(META_KEY(meta.id), payload);
- await r.lpush(INDEX_KEY, meta.id);
- await r.ltrim(INDEX_KEY, 0, INDEX_CAP - 1);
+ await r.set(META_KEY(meta.id), JSON.stringify(meta));
return meta;
}
@@ -127,6 +118,45 @@ async function getChildren(id) {
return (raw || []).filter(Boolean);
}
+// Batched overlay reads. Every aggregation surface here (feed, creator,
+// creators, trending) enriches a SCAN_CAP-deep slice of the Loom feed, and
+// per-item getMeta + getChildren would be two Upstash REST round-trips PER
+// creation: 1200 HTTP calls to render one gallery page, the exact shape of the
+// quota blowout api/_lib/redis.js was written to stop. mget collapses the meta
+// reads into one call and a pipeline collapses the lrange reads into another,
+// so the whole slice costs two round-trips regardless of its depth.
+async function getMetaMany(ids) {
+ const out = new Map();
+ const wanted = [...new Set(ids.filter(Boolean))];
+ if (!wanted.length) return out;
+
+ const r = getRedis();
+ if (!r) {
+ for (const id of wanted) out.set(id, mem.meta.get(id) || null);
+ return out;
+ }
+ const raw = await r.mget(...wanted.map(META_KEY));
+ wanted.forEach((id, i) => out.set(id, raw?.[i] ? safeParse(raw[i]) : null));
+ return out;
+}
+
+async function getChildrenMany(ids) {
+ const out = new Map();
+ const wanted = [...new Set(ids.filter(Boolean))];
+ if (!wanted.length) return out;
+
+ const r = getRedis();
+ if (!r) {
+ for (const id of wanted) out.set(id, mem.children.get(id) || []);
+ return out;
+ }
+ const pipe = r.pipeline();
+ for (const id of wanted) pipe.lrange(CHILDREN_KEY(id), 0, 199);
+ const results = await pipe.exec();
+ wanted.forEach((id, i) => out.set(id, (results?.[i] || []).filter(Boolean)));
+ return out;
+}
+
async function addChild(parentId, childId) {
const r = getRedis();
if (!r) {
@@ -271,12 +301,15 @@ function isAgentKey(key) {
// Merge a raw Loom creation with its gallery overlay + lineage counts into the
// shape the creator gallery renders. Defensive: a creation with no overlay (every
-// pre-existing Loom item) still renders fully — title falls back to the prompt,
+// pre-existing Loom item) still renders fully, so title falls back to the prompt,
// license to the open default, type/style inferred from tags/prompt.
-async function enrich(creation, { withChildren = false } = {}) {
+// `overlay` lets a caller hand in already-batched meta/children lookups (see
+// enrichAll); without it each call fetches its own, which is right for the
+// single-item paths.
+async function enrich(creation, { withChildren = false, overlay = null } = {}) {
if (!creation) return null;
- const meta = await getMeta(creation.id);
- const childIds = await getChildren(creation.id);
+ const meta = overlay ? overlay.meta.get(creation.id) || null : await getMeta(creation.id);
+ const childIds = overlay ? overlay.children.get(creation.id) || [] : await getChildren(creation.id);
const creatorKey = creatorKeyFor(creation, meta);
const inferred = inferFacets(creation, meta);
const out = {
@@ -306,6 +339,16 @@ async function enrich(creation, { withChildren = false } = {}) {
return out;
}
+// Enrich a whole slice with two overlay round-trips instead of two per item.
+async function enrichAll(creations, opts = {}) {
+ const rows = (creations || []).filter(Boolean);
+ if (!rows.length) return [];
+ const ids = rows.map((c) => c.id);
+ const [meta, children] = await Promise.all([getMetaMany(ids), getChildrenMany(ids)]);
+ const overlay = { meta, children };
+ return (await Promise.all(rows.map((c) => enrich(c, { ...opts, overlay })))).filter(Boolean);
+}
+
function titleFromPrompt(prompt) {
const p = String(prompt || '').trim();
if (!p) return 'Untitled creation';
@@ -362,7 +405,7 @@ async function handleFeed(req, res, url) {
// Pull a deep slice of the canonical Loom feed, enrich, filter, then rank.
// SCAN_CAP bounds the work; the feed is itself capped at 2000 upstream.
const raw = await loomReadFeed(SCAN_CAP, NaN);
- const enriched = (await Promise.all(raw.map((c) => enrich(c)))).filter(Boolean);
+ const enriched = await enrichAll(raw);
let items = enriched.filter((c) => matchesFilters(c, filters));
if (sort === 'new') items.sort((a, b) => b.createdAt - a.createdAt);
@@ -413,7 +456,8 @@ async function handleItem(req, res, url) {
ancestors.push(await enrich(pc));
cursorMeta = await getMeta(cursorMeta.parentId);
}
- const children = (await Promise.all((item.childIds || []).slice(0, 24).map((cid) => loomReadOne(cid).then((c) => (c ? enrich(c) : null))))).filter(Boolean);
+ const childRows = await Promise.all((item.childIds || []).slice(0, 24).map((cid) => loomReadOne(cid)));
+ const children = await enrichAll(childRows);
// Creator card: aggregate + follower count + (for agents) on-chain reputation.
const creator = await buildCreatorCard(item.creatorKey, creation);
@@ -450,9 +494,9 @@ async function handleCreator(req, res, url) {
const followerId = sanitizeOptionalString(url.searchParams.get('follower'), 80);
// Gather this creator's creations from the canonical feed (match by agent
- // binding or author slug) — bounded scan, newest-first.
+ // binding or author slug), a bounded scan, newest-first.
const raw = await loomReadFeed(SCAN_CAP, NaN);
- const all = (await Promise.all(raw.map((c) => enrich(c)))).filter(Boolean);
+ const all = await enrichAll(raw);
const creations = all
.filter((c) => c.creatorKey === key || slugifyAuthor(c.author) === key)
.sort((a, b) => b.createdAt - a.createdAt);
@@ -483,7 +527,7 @@ async function handleCreators(req, res, url) {
const sort = ['remixed', 'prolific', 'followed'].includes(url.searchParams.get('sort')) ? url.searchParams.get('sort') : 'remixed';
const raw = await loomReadFeed(SCAN_CAP, NaN);
- const all = (await Promise.all(raw.map((c) => enrich(c)))).filter(Boolean);
+ const all = await enrichAll(raw);
// Aggregate by creator key across the scanned feed.
const byKey = new Map();
@@ -529,7 +573,7 @@ async function handleCreators(req, res, url) {
async function handleTrending(req, res, url) {
const limit = Math.min(24, Math.max(1, parseInt(url.searchParams.get('limit') || '8', 10) || 8));
const raw = await loomReadFeed(SCAN_CAP, NaN);
- const all = (await Promise.all(raw.map((c) => enrich(c)))).filter(Boolean);
+ const all = await enrichAll(raw);
const now = Date.now();
const score = (c) => c.remixCount * 10 + Math.max(0, 5 - (now - c.createdAt) / 86_400_000);
const trending = all
@@ -567,7 +611,7 @@ function sanitizeRoyalty(raw) {
// shows in the shared feed every surface reads), then attaches the gallery
// overlay (title/tags/license/type/style/creator/lineage) and a provenance entry.
// When parentId is present this is the persisted tail of a remix.
-async function handlePublish(req, res, body, ip) {
+async function handlePublish(req, res, body) {
const prompt = sanitizePrompt(body?.prompt ?? '');
if (!prompt) return error(res, 400, 'bad_request', 'prompt is required');
if (prompt.length > 1000) return error(res, 400, 'bad_request', 'prompt too long (max 1000)');
@@ -785,7 +829,7 @@ export default wrap(async (req, res) => {
setRateLimitHeaders(res, rl);
switch (op) {
case 'publish':
- return handlePublish(req, res, body, ip);
+ return handlePublish(req, res, body);
case 'remix':
return handleRemixLink(req, res, body);
case 'follow':
diff --git a/api/cron/forge-smoke.js b/api/cron/forge-smoke.js
index 3b72a7753..3ed995c3e 100644
--- a/api/cron/forge-smoke.js
+++ b/api/cron/forge-smoke.js
@@ -38,9 +38,21 @@ import { fetchRedisDailyCommands, evaluateRedisBurn, redisBurnAlert } from '../_
import { requireCron } from '../_lib/cron-auth.js';
const SMOKE_PROMPT = 'a small wooden toy boat with a striped sail';
-const SUBMIT_TIMEOUT_MS = 90_000;
+// One budget covers the submit and the poll together, because the draft lane
+// answers the submit synchronously and a real generation takes minutes: on
+// 2026-08-16 this exact prompt returned a valid 1.6 MB GLB from the nvidia lane
+// in 150 s, while /api/forge?health reported a 24 h average of 84.7 s across
+// lanes. The previous 90 s submit timeout sat UNDER that average, so it aborted
+// healthy generations and paged ops daily with "submit returned HTTP 0: The
+// operation was aborted due to timeout" while the pipeline was demonstrably up
+// (26 of 29 nvidia jobs succeeded in the same window). A single shared budget is
+// what keeps that honest: two separate timeouts stack, and 90 s plus 180 s
+// already exceeded the 320 s attemptDeadline Cloud Scheduler gives this job, so
+// a slow-but-working lane could blow the deadline instead of reporting. 240 s
+// leaves the alerting and the response inside that deadline.
+const GENERATION_BUDGET_MS = 240_000;
const POLL_INTERVAL_MS = 5_000;
-const POLL_DEADLINE_MS = 180_000;
+const POLL_TIMEOUT_MS = 15_000;
const LAST_STATUS_KEY = 'forge-smoke:last';
const LAST_STATUS_TTL_S = 7 * 24 * 60 * 60;
@@ -101,6 +113,7 @@ async function verifyGlb(glbUrl) {
// 0.55 s total, which no real generation can do. The flag skips only the cache
// READ; a fresh run is still written back, so the cache stays warm for users.
export async function runGeneration(origin) {
+ const deadline = Date.now() + GENERATION_BUDGET_MS;
const submit = await fetchJson(
`${origin}/api/forge`,
{
@@ -108,7 +121,7 @@ export async function runGeneration(origin) {
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ prompt: SMOKE_PROMPT, tier: 'draft', force_regenerate: true }),
},
- SUBMIT_TIMEOUT_MS,
+ GENERATION_BUDGET_MS,
);
if (submit.status !== 200) {
return {
@@ -124,10 +137,12 @@ export async function runGeneration(origin) {
}
let { status, glb_url: glbUrl, job_id: jobId } = submit.body || {};
- const deadline = Date.now() + POLL_DEADLINE_MS;
while (status !== 'done' && jobId && Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
- const poll = await fetchJson(`${origin}/api/forge?job=${encodeURIComponent(jobId)}`);
+ // Never let one poll outlive the shared budget: the loop condition alone
+ // would still allow a final 15 s request to start just under the deadline.
+ const pollTimeout = Math.min(POLL_TIMEOUT_MS, Math.max(1_000, deadline - Date.now()));
+ const poll = await fetchJson(`${origin}/api/forge?job=${encodeURIComponent(jobId)}`, {}, pollTimeout);
if (poll.status !== 200) return { ok: false, reason: `poll returned HTTP ${poll.status}` };
status = poll.body?.status;
glbUrl = poll.body?.glb_url || glbUrl;
@@ -136,7 +151,7 @@ export async function runGeneration(origin) {
}
}
if (status !== 'done' || !glbUrl) {
- return { ok: false, reason: `job did not finish within ${POLL_DEADLINE_MS / 1000}s (status: ${status})` };
+ return { ok: false, reason: `job did not finish within ${GENERATION_BUDGET_MS / 1000}s (status: ${status})` };
}
const glb = await verifyGlb(glbUrl);
diff --git a/api/csrf-token.js b/api/csrf-token.js
index 1069996bd..dd17fb322 100644
--- a/api/csrf-token.js
+++ b/api/csrf-token.js
@@ -1,4 +1,4 @@
-// GET /api/csrf-token — issue a single-use CSRF token bound to the session user.
+// GET /api/csrf-token: issue a single-use CSRF token bound to the session user.
import { authenticateBearer, extractBearer, getSessionUser } from './_lib/auth.js';
import { cors, error, json, method, wrap } from './_lib/http.js';
import { issueCsrf } from './_lib/csrf.js';
diff --git a/api/dca-strategies.js b/api/dca-strategies.js
index 341777eaf..05c1a4987 100644
--- a/api/dca-strategies.js
+++ b/api/dca-strategies.js
@@ -22,7 +22,7 @@ import {
planStatusChange,
} from './_lib/recurring.js';
-// Whitelisted token-out symbols — runtime operator config, never hardcoded
+// Whitelisted token-out symbols, runtime operator config, never hardcoded
// tickers. DCA_ALLOWED_TOKEN_OUT is a comma-separated symbol list; when unset
// or empty, strategy creation is rejected until the operator configures it.
function allowedTokenOutSymbols() {
@@ -34,7 +34,7 @@ function allowedTokenOutSymbols() {
);
}
-// Default chain for new strategies — operator config (DCA_CHAIN_ID), never a
+// Default chain for new strategies, operator config (DCA_CHAIN_ID), never a
// hardcoded network. Required when the request body omits chain_id.
function defaultChainId() {
const parsed = parseInt(process.env.DCA_CHAIN_ID || '', 10);
@@ -335,7 +335,7 @@ export default wrap(async (req, res) => {
res,
400,
'not_configured',
- 'DCA token-out whitelist is not configured — set DCA_ALLOWED_TOKEN_OUT (comma-separated symbols)',
+ 'DCA token-out whitelist is not configured. Set DCA_ALLOWED_TOKEN_OUT (comma-separated symbols).',
);
}
if (!allowedTokenOut.has(body.token_out_symbol)) {
@@ -353,7 +353,7 @@ export default wrap(async (req, res) => {
res,
400,
'not_configured',
- 'chain_id is required — pass it in the body or set DCA_CHAIN_ID',
+ 'chain_id is required. Pass it in the body or set DCA_CHAIN_ID.',
);
}
diff --git a/api/demo-economy.js b/api/demo-economy.js
index 594d0b55b..2db92144c 100644
--- a/api/demo-economy.js
+++ b/api/demo-economy.js
@@ -15,7 +15,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.j
import { limits, clientIp } from './_lib/rate-limit.js';
import { Bazaar } from './_lib/x402/bazaar-client.js';
-// ── Wallet imports (lazy — only when live mode is active) ────────────────────
+// ── Wallet imports (lazy, only when live mode is active) ─────────────────────
async function walletDeps() {
const mod = await import('./_lib/avatar-wallet.js');
return mod;
@@ -58,14 +58,14 @@ async function fetchMarketBriefing() {
};
} catch {
// No invented market data: a GeckoTerminal failure degrades to an explicit
- // "unavailable" signal handled by the caller — never fabricated numbers.
+ // "unavailable" signal handled by the caller, never fabricated numbers.
return null;
}
}
// The service NOVA actually buys from ORACLE: three.ws's own live Solana market
// briefing, delivered by fetchMarketBriefing() below. This is the real product
-// the demo transacts — not a fabricated listing — so it is always present.
+// the demo transacts (not a fabricated listing), so it is always present.
const THREEWS_BRIEFING_SERVICE = {
name: 'Solana market briefing (live)',
resource: 'https://three.ws/api/demo-economy',
@@ -76,7 +76,7 @@ const THREEWS_BRIEFING_SERVICE = {
// ── Bazaar service discovery ─────────────────────────────────────────────────
// Returns the real three.ws briefing service (always) plus any live listings
// pulled from the Coinbase x402 bazaar. If the bazaar is unreachable we say so
-// honestly via bazaarAvailable:false — we never invent competitor listings.
+// honestly via bazaarAvailable:false; we never invent competitor listings.
async function discoverServices() {
try {
const bazaar = new Bazaar();
@@ -85,14 +85,14 @@ async function discoverServices() {
.map((r) => ({
name: r.description?.slice(0, 60) || r.resource?.split('/').pop() || 'Service',
resource: r.resource,
- price: r.formattedPrice || r.price || '—',
+ price: r.formattedPrice || r.price || 'price not listed',
network: r.network || 'base',
}))
.filter((s) => s.resource && s.resource !== THREEWS_BRIEFING_SERVICE.resource)
.slice(0, 3);
return { services: [THREEWS_BRIEFING_SERVICE, ...listings], bazaarAvailable: true };
} catch {
- // Live bazaar unreachable — degrade to an explicit "unavailable" signal.
+ // Live bazaar unreachable: degrade to an explicit "unavailable" signal.
// The demo still transacts the real three.ws briefing service.
return { services: [THREEWS_BRIEFING_SERVICE], bazaarAvailable: false };
}
@@ -142,7 +142,7 @@ export default wrap(async (req, res) => {
res.flushHeaders?.();
const pace = 900; // ms between narration beats
- const DEMO_LAMPORTS = 1000; // 0.000001 SOL — ~$0.0002, trivially cheap
+ const DEMO_LAMPORTS = 1000; // 0.000001 SOL, ~$0.0002, trivially cheap
try {
// ── Step 1: Agents ready ─────────────────────────────────────────────
@@ -161,7 +161,7 @@ export default wrap(async (req, res) => {
label: 'Browsing x402 bazaar',
detail: bazaarAvailable
? 'NOVA is discovering available services on the Coinbase x402 network'
- : 'Live bazaar unavailable — NOVA falls back to the three.ws briefing service',
+ : 'Live bazaar unavailable, so NOVA falls back to the three.ws briefing service',
icon: '🔍',
});
await sleep(pace * 0.7);
@@ -188,7 +188,7 @@ export default wrap(async (req, res) => {
});
await sleep(pace * 0.5);
- // Attempt real transfer — authenticated callers only. Anonymous callers
+ // Attempt real transfer, authenticated callers only. Anonymous callers
// always take the explicit-simulation path (no SOL ever leaves the wallet).
let payment = null;
let sim = !authed;
@@ -300,7 +300,7 @@ export default wrap(async (req, res) => {
id: 'payment_confirmed',
label: sim ? 'Simulation complete' : 'On-chain confirmed',
detail: sim
- ? 'Simulated payment — no funds moved'
+ ? 'Simulated payment, no funds moved'
: `${payment.amount_sol} SOL transferred · view on Solscan`,
icon: '⛓️',
});
@@ -326,13 +326,13 @@ export default wrap(async (req, res) => {
icon: '📺',
});
} else {
- // Degraded: market data source did not respond — say so explicitly
+ // Degraded: market data source did not respond, so say so explicitly
// instead of inventing numbers.
sseWrite(res, 'content', { type: 'market_unavailable' });
sseWrite(res, 'step', {
id: 'done',
label: 'Market data unavailable',
- detail: 'Live market data is unavailable right now — try again shortly',
+ detail: 'Live market data is unavailable right now. Try again shortly.',
icon: '📡',
});
}
diff --git a/api/forge-poster.js b/api/forge-poster.js
index 14def13f6..97b551457 100644
--- a/api/forge-poster.js
+++ b/api/forge-poster.js
@@ -61,7 +61,7 @@ export default wrap(async (req, res) => {
if (buf.length === 0 || buf.length > MAX_POSTER_BYTES) {
return json(res, 400, {
error: 'invalid_image',
- message: `Poster must be 1 byte – ${MAX_POSTER_BYTES} bytes.`,
+ message: `Poster must be between 1 and ${MAX_POSTER_BYTES} bytes.`,
});
}
diff --git a/api/forge-quality-check.js b/api/forge-quality-check.js
index 98cf041c7..b18e3abd8 100644
--- a/api/forge-quality-check.js
+++ b/api/forge-quality-check.js
@@ -45,7 +45,9 @@ export default wrap(async function handler(req, res) {
// Capability probe - lets a UI decide whether to surface a "check quality"
// affordance, and reports which lane will serve.
- if (req.method === 'GET' || req.method === 'HEAD') {
+ // method() above already normalized an incoming HEAD to GET, so this one
+ // check covers both verbs.
+ if (req.method === 'GET') {
return json(
res,
200,
diff --git a/api/forge-rembg.js b/api/forge-rembg.js
index 4fdb054a9..e2a33d3d4 100644
--- a/api/forge-rembg.js
+++ b/api/forge-rembg.js
@@ -93,7 +93,21 @@ async function pollJob(req, res, jobId) {
return unconfigured(res);
}
- const result = await provider.status(jobId);
+ // Poll is an outbound call to the worker, so it gets the same boundary guard
+ // as submit. Without it an upstream fault escapes to wrap() as a 500, and
+ // because clients poll every couple of seconds one worker outage pages ops
+ // once per poll per client instead of once. A 502 with no `status` field
+ // leaves the client's poll loop retrying, which is what a transient fault
+ // deserves.
+ let result;
+ try {
+ result = await provider.status(jobId);
+ } catch (err) {
+ return json(res, 502, {
+ error: 'rembg_status_failed',
+ message: err?.message || 'Could not read the background-removal job.',
+ });
+ }
return json(res, 200, {
job_id: jobId,
status: result.status,
diff --git a/api/forge-remesh.js b/api/forge-remesh.js
index a32c24292..9768a8e28 100644
--- a/api/forge-remesh.js
+++ b/api/forge-remesh.js
@@ -117,7 +117,21 @@ async function pollJob(req, res, jobId) {
return unconfigured(res);
}
- const result = await provider.status(jobId);
+ // Poll is an outbound call to the worker, so it gets the same boundary guard
+ // as submit. Without it an upstream fault escapes to wrap() as a 500, and
+ // because clients poll every couple of seconds one worker outage pages ops
+ // once per poll per client instead of once. A 502 with no `status` field
+ // leaves the client's poll loop retrying, which is what a transient fault
+ // deserves.
+ let result;
+ try {
+ result = await provider.status(jobId);
+ } catch (err) {
+ return json(res, 502, {
+ error: 'remesh_status_failed',
+ message: err?.message || 'Could not read the mesh-processing job.',
+ });
+ }
return json(res, 200, {
job_id: jobId,
status: result.status,
diff --git a/api/forge-segment.js b/api/forge-segment.js
index 8e9b0339c..a5ea8cf3b 100644
--- a/api/forge-segment.js
+++ b/api/forge-segment.js
@@ -115,7 +115,21 @@ async function pollJob(req, res, jobId) {
return unconfigured(res);
}
- const result = await provider.status(jobId);
+ // Poll is an outbound call to the worker, so it gets the same boundary guard
+ // as submit. Without it an upstream fault escapes to wrap() as a 500, and
+ // because clients poll every couple of seconds one worker outage pages ops
+ // once per poll per client instead of once. A 502 with no `status` field
+ // leaves the client's poll loop retrying, which is what a transient fault
+ // deserves.
+ let result;
+ try {
+ result = await provider.status(jobId);
+ } catch (err) {
+ return json(res, 502, {
+ error: 'segment_status_failed',
+ message: err?.message || 'Could not read the segmentation job.',
+ });
+ }
return json(res, 200, {
job_id: jobId,
status: result.status,
diff --git a/api/forge-stylize.js b/api/forge-stylize.js
index 8630fed1b..55e6cb762 100644
--- a/api/forge-stylize.js
+++ b/api/forge-stylize.js
@@ -66,7 +66,13 @@ async function startJob(req, res) {
});
}
- const style = STYLE_BOUNDS[body?.style] ? body.style : 'voxel';
+ // Object.hasOwn, not a bare truthy lookup: `STYLE_BOUNDS[k]` is truthy for
+ // every Object.prototype key, so `style: "constructor"` (or "toString",
+ // "valueOf", "__proto__") walked straight past the allowlist and reached the
+ // worker with an unknown filter and a NaN/undefined resolution.
+ const style = typeof body?.style === 'string' && Object.hasOwn(STYLE_BOUNDS, body.style)
+ ? body.style
+ : 'voxel';
const bounds = STYLE_BOUNDS[style];
const outputFormat = VALID_FORMATS.has(body?.output_format) ? body.output_format : 'glb';
const requested = Number(body?.resolution);
@@ -118,7 +124,21 @@ async function pollJob(req, res, jobId) {
return unconfigured(res);
}
- const result = await provider.status(jobId);
+ // Poll is an outbound call to the worker, so it gets the same boundary guard
+ // as submit. Without it an upstream fault escapes to wrap() as a 500, and
+ // because clients poll every couple of seconds one worker outage pages ops
+ // once per poll per client instead of once. A 502 with no `status` field
+ // leaves the client's poll loop retrying, which is what a transient fault
+ // deserves.
+ let result;
+ try {
+ result = await provider.status(jobId);
+ } catch (err) {
+ return json(res, 502, {
+ error: 'stylize_status_failed',
+ message: err?.message || 'Could not read the stylization job.',
+ });
+ }
return json(res, 200, {
job_id: jobId,
status: result.status,
diff --git a/api/forge-upload.js b/api/forge-upload.js
index d54b78fdb..c39ad38cf 100644
--- a/api/forge-upload.js
+++ b/api/forge-upload.js
@@ -70,7 +70,11 @@ export default wrap(async (req, res) => {
const contentType =
typeof body?.content_type === 'string' ? body.content_type.trim().toLowerCase() : '';
- const ext = CONTENT_TYPE_EXT[contentType];
+ // Object.hasOwn, not a bare truthy lookup: freezing the map does not detach
+ // its prototype, so `content_type: "constructor"` resolved to the Object
+ // function (and "__proto__" to Object.prototype), passed this check, and
+ // presigned an upload whose storage key ended in the stringified builtin.
+ const ext = Object.hasOwn(CONTENT_TYPE_EXT, contentType) ? CONTENT_TYPE_EXT[contentType] : null;
if (!ext) {
return json(res, 400, {
error: 'invalid_content_type',
diff --git a/api/input-multiview.js b/api/input-multiview.js
index 02cd56383..b388e84b8 100644
--- a/api/input-multiview.js
+++ b/api/input-multiview.js
@@ -1,7 +1,7 @@
/**
* POST /api/input-multiview — multi-image validation + 3D reconstruction.
*
- * Accepts 2–4 photos of an object from different angles, validates each with
+ * Accepts 2 to 6 photos of an object from different angles, validates each with
* vision (clear subject? in focus? same object?), then submits them to
* /api/forge as a multi-view reconstruction job. The validation step catches
* mismatched images, blank uploads, and text screenshots before burning a
@@ -16,7 +16,7 @@
* POST /api/input-multiview
* Content-Type: application/json
* {
- * image_urls: string[], // 2–4 public https URLs (required)
+ * image_urls: string[], // 2 to 6 public https URLs (required)
* storage_keys?: string[], // R2 keys from /api/forge-upload (for transient delete)
* prompt?: string, // optional guidance text (max 1000 chars)
* tier?: string, // "draft" | "standard" | "high"
@@ -161,7 +161,9 @@ export default wrap(async (req, res) => {
skip_validation: true,
};
- const forgeOrigin = env.APP_ORIGIN || 'http://localhost:3000';
+ // env.APP_ORIGIN always resolves (api/_lib/env.js falls back to the canonical
+ // origin), so this self-call lands on the deployment's own /api/forge.
+ const forgeOrigin = env.APP_ORIGIN;
let forgeResp;
try {
forgeResp = await fetch(`${forgeOrigin}/api/forge`, {
@@ -173,7 +175,7 @@ export default wrap(async (req, res) => {
},
body: JSON.stringify(forgeBody),
});
- } catch (e) {
+ } catch {
return error(res, 502, 'generation_unreachable',
'Could not reach the generation service. Please try again.');
}
diff --git a/api/input-photo.js b/api/input-photo.js
index 62c6a35bb..1c696a0ca 100644
--- a/api/input-photo.js
+++ b/api/input-photo.js
@@ -136,7 +136,9 @@ export default wrap(async (req, res) => {
};
// Self-call /api/forge — keeps generation logic in one place.
- const forgeOrigin = env.APP_ORIGIN || 'http://localhost:3000';
+ // env.APP_ORIGIN always resolves (api/_lib/env.js falls back to the canonical
+ // origin), so this self-call lands on the deployment's own /api/forge.
+ const forgeOrigin = env.APP_ORIGIN;
let forgeResp;
try {
forgeResp = await fetch(`${forgeOrigin}/api/forge`, {
@@ -149,7 +151,7 @@ export default wrap(async (req, res) => {
},
body: JSON.stringify(forgeBody),
});
- } catch (e) {
+ } catch {
return error(res, 502, 'generation_unreachable',
'Could not reach the generation service. Please try again.');
}
diff --git a/api/instant-agent.js b/api/instant-agent.js
index c33273a02..f79339693 100644
--- a/api/instant-agent.js
+++ b/api/instant-agent.js
@@ -155,6 +155,9 @@ export function safeHandle(raw, name = '') {
const clean = (s) =>
String(s || '')
.normalize('NFKD')
+ // Drop the combining marks NFKD just split off, so an accented name
+ // slugifies to the letters underneath it ("Munz", not "mu-nz").
+ .replace(/\p{M}+/gu, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
diff --git a/api/locale.js b/api/locale.js
index 936b4158e..31518445d 100644
--- a/api/locale.js
+++ b/api/locale.js
@@ -132,7 +132,11 @@ export default wrap(async (req, res) => {
const url = new URL(req.url, 'http://localhost');
const code = (url.searchParams.get('code') || '').trim();
if (!allowedCodes().has(code)) {
- return error(res, 400, 'unknown_locale', `"${code}" is not a published locale. See /locales/manifest.json.`);
+ // Echo back only enough of the rejected value to identify it. A locale
+ // code is at most a handful of characters, so anything longer is a
+ // probe, and reflecting it whole just turns a 400 into an amplifier.
+ const shown = code.length > 24 ? `${code.slice(0, 24)}...` : code;
+ return error(res, 400, 'unknown_locale', `"${shown}" is not a published locale. See /locales/manifest.json.`);
}
// Normalize before anything else touches it, so every caller asking for the
diff --git a/api/loom.js b/api/loom.js
index 9910a6390..83dfad4be 100644
--- a/api/loom.js
+++ b/api/loom.js
@@ -91,8 +91,16 @@ export async function writeCreation(rec) {
// Read the feed newest-first. `before` (ms epoch) pages backwards: only items
// strictly older than it are returned. Returns up to `limit` records.
+//
+// The ceiling here is LIST_CAP (what storage actually holds), NOT the smaller
+// public MAX_LIMIT: the HTTP handler below already clamps a caller-supplied
+// `limit` to MAX_LIMIT before it gets here, so enforcing it a second time only
+// hit INTERNAL callers. api/creations.js asks for a SCAN_CAP-deep slice to
+// aggregate creator/trending rankings over, and silently got 120 rows instead,
+// which under-reported every creator's creation count and made gallery
+// pagination dead-end well before the feed did.
export async function readFeed(limit, before) {
- const cap = Math.max(1, Math.min(MAX_LIMIT, limit | 0 || DEFAULT_LIMIT));
+ const cap = Math.max(1, Math.min(LIST_CAP, limit | 0 || DEFAULT_LIMIT));
const hasBefore = Number.isFinite(before);
const r = getRedis();
diff --git a/api/mcp-agent.js b/api/mcp-agent.js
index 8f74ee0db..5333a67d6 100644
--- a/api/mcp-agent.js
+++ b/api/mcp-agent.js
@@ -9,6 +9,7 @@ import { settlePayment, encodePaymentResponseHeader } from './_lib/x402-spec.js'
import { peekCalledTool } from './_lib/mcp-dispatch.js';
import { isDiscoveryOnlyBatch } from './_lib/mcp-batch-price.js';
import { PROTOCOL_VERSION, dispatch, isPublicTool } from './_mcpagent/dispatch.js';
+import { AGENT_CHALLENGE } from './_mcpagent/discovery.js';
import {
send401,
sendJsonRpcError,
@@ -19,10 +20,18 @@ import {
} from './_mcp/auth.js';
import { sendX402Error, reservePaymentProof } from './_mcp/payments.js';
+// Every 402/401 challenge this server issues is scoped to its OWN resource.
+// Passing neither resourcePath nor challenge left the Agent wallet advertising
+// https://three.ws/api/mcp and the main server's description to facilitators,
+// and quoted that same wrong resource inside every accepts[] entry, so a paying
+// agent signed a payment scoped to an endpoint it never called.
+const RESOURCE_PATH = '/api/mcp-agent';
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,HEAD,POST,DELETE,OPTIONS', origins: '*' })) return;
- if (req.method === 'GET' || req.method === 'HEAD') return handleSse(req, res);
+ if (req.method === 'GET' || req.method === 'HEAD')
+ return handleSse(req, res, { resourcePath: RESOURCE_PATH, challenge: AGENT_CHALLENGE });
if (req.method === 'DELETE') return handleTerminate(req, res);
if (req.method !== 'POST') return send401(res, 'method not supported');
@@ -35,6 +44,8 @@ export default wrap(async (req, res) => {
const { toolName } = peekCalledTool(body);
const result = await authenticateRequest(req, res, {
+ resourcePath: RESOURCE_PATH,
+ challenge: AGENT_CHALLENGE,
allowFree:
Boolean(toolName && isPublicTool(toolName)) ||
(isDiscoveryOnlyBatch(body) && !isMcpProtocolClient(req)),
@@ -64,7 +75,7 @@ export default wrap(async (req, res) => {
let releaseProof = async () => {};
if (x402Ctx) {
const guard = await reservePaymentProof(
- '/api/mcp-agent',
+ RESOURCE_PATH,
// authenticateRequest accepts BOTH payment headers (v1 X-PAYMENT and
// the v2 payment-signature dialect); the guard must key on whichever
// one carried the proof or a v2 replay slips past it unclaimed.
diff --git a/api/og-leaderboard.js b/api/og-leaderboard.js
index 6cb66502e..05ec44a32 100644
--- a/api/og-leaderboard.js
+++ b/api/og-leaderboard.js
@@ -18,6 +18,7 @@
// hour per variant rather than per crawl.
import { ImageResponse } from '@vercel/og';
+import { method } from './_lib/http.js';
import { TOKEN_MINT as THREE_MINT } from './_lib/token/config.js';
import { fetchTokenMarketData } from './_lib/market/token-market.js';
import { threeHolderBalances } from './_lib/coin/three-holders.js';
@@ -221,12 +222,10 @@ export default async function handler(req, res) {
res.end();
return;
}
- if (req.method !== 'GET') {
- res.statusCode = 405;
- res.setHeader('allow', 'GET, OPTIONS');
- res.end('method not allowed');
- return;
- }
+ // A bare `res.end('method not allowed')` sent an untyped text body that
+ // consumers sniffed as HTML; every other handler here answers a rejected
+ // method with the shared JSON error shape.
+ if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
const wallet = (url.searchParams.get('wallet') || '').trim();
diff --git a/api/ops/health.js b/api/ops/health.js
index 3a1594a5f..a457fad9a 100644
--- a/api/ops/health.js
+++ b/api/ops/health.js
@@ -156,6 +156,15 @@ export const CRONS = [
{ id: 'coin-intel-observe', label: 'Coin intel observe' },
{ id: 'unstoppable-tick', label: 'Unstoppable agent tick' },
{ id: 'sketchfab-showcase', label: 'Sketchfab showcase' },
+ // Storage and job-recovery crons. Both write heartbeats already, but neither
+ // was surfaced here, so a stall was invisible until it showed up as a symptom
+ // somewhere else: db-retention is the only thing holding the Neon branch under
+ // its size cap (when it stops, every write-heavy cron latches into the
+ // storage-pressure skip), and reconstruct-sweep is what finalizes or reaps a
+ // reconstruct job whose worker callback never arrived (when it stops, avatars
+ // sit in 'rigging' forever).
+ { id: 'db-retention', label: 'DB retention' },
+ { id: 'reconstruct-sweep', label: 'Reconstruct sweep' },
].map((c) => {
const schedule = CRON_SCHEDULES.get(c.driven_by || c.id) || null;
return { ...c, schedule, stale_after_ms: deriveStaleAfterMs(schedule) };
diff --git a/api/oracle-share.js b/api/oracle-share.js
index 1b8fe8baf..e865ba58f 100644
--- a/api/oracle-share.js
+++ b/api/oracle-share.js
@@ -18,7 +18,7 @@
*/
import { sql } from './_lib/db.js';
-import { cors, wrap } from './_lib/http.js';
+import { cors, method, wrap } from './_lib/http.js';
import { env } from './_lib/env.js';
import { terminalLinks } from '../src/shared/trading-terminals.js';
import { hitRateFor } from './_lib/oracle/conviction.js';
@@ -29,6 +29,9 @@ const PUMP_CURVE_INITIAL_REAL_TOKENS = 793_100_000 * 1e6; // matches api/_lib/or
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ // A server-rendered page is a GET surface; a POST used to render the whole
+ // page (DB read + a live pump.fun fetch) exactly like a GET.
+ if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, 'http://x');
const mint = (url.searchParams.get('mint') || '').trim();
diff --git a/api/page-og.js b/api/page-og.js
index e4418b22b..86ded0c22 100644
--- a/api/page-og.js
+++ b/api/page-og.js
@@ -15,6 +15,7 @@
// show the preview.
import { ImageResponse } from '@vercel/og';
import { readFileSync } from 'node:fs';
+import { method } from './_lib/http.js';
const WIDTH = 1200;
const HEIGHT = 630;
@@ -427,6 +428,9 @@ export default async function handler(req, res) {
res.end();
return;
}
+ // A share card is a GET surface. Without this gate any verb (POST, DELETE)
+ // drove a full satori render on a route that never accepts writes.
+ if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, 'http://x');
const section = sectionFor(url.searchParams.get('s'));
diff --git a/api/play-oembed.js b/api/play-oembed.js
index 66f4aece3..a78375674 100644
--- a/api/play-oembed.js
+++ b/api/play-oembed.js
@@ -1,90 +1,137 @@
-// api/play-oembed — oEmbed provider for /play Coin Communities worlds.
-// Returns rich oEmbed JSON so a coin-world link (three.ws/play?coin=<mint>)
-// unfurls as an interactive 3D world on platforms that resolve oEmbed
-// (WordPress, Ghost, Discord, dev.to, Notion) and, once three.ws is
-// registered as a provider, on iframely/embed.ly-backed editors such as the
-// AWS Builder Center.
+// api/play-oembed: oEmbed provider for /play Coin Communities worlds.
+// Returns rich oEmbed JSON (or XML) so a coin-world link
+// (three.ws/play?coin=<mint>) unfurls as an interactive 3D world on platforms
+// that resolve oEmbed (WordPress, Ghost, Discord, dev.to, Notion) and, once
+// three.ws is registered as a provider, on iframely/embed.ly-backed editors
+// such as the AWS Builder Center.
//
-// Spec: https://oembed.com/ — ?url=<coin world url>&format=json&maxwidth=&maxheight=
+// Spec: https://oembed.com/ (?url=<coin world url>&format=json|xml&maxwidth=&maxheight=)
+//
+// Discovery: pages/play.html carries the <link rel="alternate"
+// type="application/json+oembed"> pair that points consumers here.
-function send(res, status, body) {
- res.statusCode = status;
- res.setHeader('content-type', 'application/json; charset=utf-8');
- res.setHeader('cache-control', 'public, max-age=300');
- res.setHeader('access-control-allow-origin', '*');
- res.setHeader('access-control-allow-methods', 'GET, OPTIONS');
- res.end(JSON.stringify(body));
-}
+import { cors, error, method, wrap } from './_lib/http.js';
+import { env } from './_lib/env.js';
+
+// The embed target is ALWAYS the canonical app origin, never the request's Host
+// header. A crawler-supplied Host (or X-Forwarded-Host) used to be echoed
+// straight into the returned iframe src and provider_url, so a single crafted
+// request handed any consumer an oEmbed payload that framed an attacker's site
+// under the three.ws provider name. Mirrors api/widgets/oembed.js.
+const ORIGIN = env.APP_ORIGIN;
+
+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const THUMB_W = 1200;
+const THUMB_H = 630;
function esc(s = '') {
return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
}
-function origin(req) {
- const host = req.headers['x-forwarded-host'] || req.headers.host;
- return `https://${host}`;
-}
-
function clampInt(v, min, max, dflt) {
const n = parseInt(v, 10);
return Number.isFinite(n) ? Math.max(min, Math.min(max, n)) : dflt;
}
-// Pull a pump.fun mint out of the pasted url (?coin= / ?mint= or a /play/<mint> path).
-function extractMint(urlParam) {
- if (!urlParam) return '';
+// An oEmbed provider answers only for URLs in its OWN scheme; anything else is a
+// 404 per the spec. Accept our canonical origin and a localhost dev server, and
+// only the /play surface within it.
+function resolveWorld(target) {
+ let parsed;
try {
- const u = new URL(urlParam);
- const q = u.searchParams.get('coin') || u.searchParams.get('mint');
- if (q) return q;
- const m = u.pathname.match(/\/play\/([1-9A-HJ-NP-Za-km-z]{32,44})/);
- if (m) return m[1];
+ parsed = new URL(target);
} catch {
- const m = String(urlParam).match(/[?&](?:coin|mint)=([1-9A-HJ-NP-Za-km-z]{32,44})/);
- if (m) return m[1];
+ return null;
}
- return '';
-}
+ const originStr = `${parsed.protocol}//${parsed.host}`;
+ const okOrigin = originStr === ORIGIN || /^https?:\/\/localhost(:\d+)?$/.test(originStr);
+ if (!okOrigin) return null;
-export default async function handler(req, res) {
- if (req.method === 'OPTIONS') return send(res, 204, {});
- const u = new URL(req.url, 'http://localhost');
- const urlParam = u.searchParams.get('url') || '';
- const format = (u.searchParams.get('format') || 'json').toLowerCase();
- const maxwidth = clampInt(u.searchParams.get('maxwidth'), 240, 1920, 720);
- const maxheight = clampInt(u.searchParams.get('maxheight'), 160, 1080, 460);
- if (format !== 'json') return send(res, 501, { error: 'only json supported' });
- if (!urlParam) return send(res, 400, { error: 'url parameter required' });
+ const path = parsed.pathname.replace(/\/+$/, '') || '/';
+ // /play/<mint> (path form) and /play?coin=|mint=<mint> (canonical share link).
+ const pathMint = path.match(/^\/play\/([1-9A-HJ-NP-Za-km-z]{32,44})$/);
+ if (pathMint) return { mint: pathMint[1] };
+ if (path !== '/play') return null;
- const proto = origin(req);
- const mint = extractMint(urlParam);
+ const q = parsed.searchParams.get('coin') || parsed.searchParams.get('mint') || '';
+ return { mint: MINT_RE.test(q) ? q : '' };
+}
+function buildPayload(mint, maxwidth, maxheight) {
const embedUrl = mint
- ? `${proto}/play?coin=${encodeURIComponent(mint)}&embed=1`
- : `${proto}/play?embed=1`;
+ ? `${ORIGIN}/play?coin=${encodeURIComponent(mint)}&embed=1`
+ : `${ORIGIN}/play?embed=1`;
const thumbnail = mint
- ? `${proto}/api/play-og?coin=${encodeURIComponent(mint)}`
- : `${proto}/api/play-og`;
- const title = mint ? `three.ws · coin world ${mint.slice(0, 4)}…${mint.slice(-4)}` : 'three.ws · Coin Communities';
+ ? `${ORIGIN}/api/play-og?coin=${encodeURIComponent(mint)}`
+ : `${ORIGIN}/api/play-og`;
+ const title = mint
+ ? `three.ws · coin world ${mint.slice(0, 4)}…${mint.slice(-4)}`
+ : 'three.ws · Coin Communities';
- const iframeHtml =
+ const html =
`<iframe src="${esc(embedUrl)}" width="${maxwidth}" height="${maxheight}" ` +
`frameborder="0" loading="lazy" ` +
`allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; microphone; xr-spatial-tracking; fullscreen" ` +
`allowfullscreen style="border:none;border-radius:16px;overflow:hidden;max-width:100%;"></iframe>`;
- return send(res, 200, {
+ return {
version: '1.0',
type: 'rich',
provider_name: 'three.ws',
- provider_url: proto,
+ provider_url: ORIGIN,
title,
- html: iframeHtml,
+ html,
width: maxwidth,
height: maxheight,
thumbnail_url: thumbnail,
- thumbnail_width: 1200,
- thumbnail_height: 630,
+ thumbnail_width: THUMB_W,
+ thumbnail_height: THUMB_H,
cache_age: 300,
- });
+ };
+}
+
+function escapeXml(s) {
+ return String(s)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&apos;');
}
+
+function toXml(payload) {
+ const lines = Object.entries(payload).map(([k, v]) => ` <${k}>${escapeXml(String(v))}</${k}>`);
+ return `<?xml version="1.0" encoding="utf-8" standalone="yes"?>\n<oembed>\n${lines.join('\n')}\n</oembed>`;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const u = new URL(req.url, 'http://x');
+ const target = u.searchParams.get('url') || '';
+ const format = (u.searchParams.get('format') || 'json').toLowerCase();
+ const maxwidth = clampInt(u.searchParams.get('maxwidth'), 240, 1920, 720);
+ const maxheight = clampInt(u.searchParams.get('maxheight'), 160, 1080, 460);
+
+ if (!target) return error(res, 400, 'invalid_request', 'url parameter required');
+ // oembed.com: a provider that cannot answer in the requested format returns
+ // 501 rather than quietly serving a different one.
+ if (format !== 'json' && format !== 'xml')
+ return error(res, 501, 'unsupported_format', 'format must be json or xml');
+
+ const world = resolveWorld(target);
+ if (!world) return error(res, 404, 'not_found', 'url is not a three.ws coin world url');
+
+ const payload = buildPayload(world.mint, maxwidth, maxheight);
+
+ res.statusCode = 200;
+ res.setHeader('cache-control', 'public, max-age=300');
+ if (format === 'xml') {
+ res.setHeader('content-type', 'text/xml; charset=utf-8');
+ res.end(toXml(payload));
+ return;
+ }
+ res.setHeader('content-type', 'application/json+oembed; charset=utf-8');
+ res.end(JSON.stringify(payload));
+});
diff --git a/api/play-og.js b/api/play-og.js
index b2772b9f0..da40e49c4 100644
--- a/api/play-og.js
+++ b/api/play-og.js
@@ -12,6 +12,7 @@
// we run as a plain Vercel function and bridge the Web Response → Node
// ServerResponse, the same pattern proven in api/demo/coin/og.js.
import { ImageResponse } from '@vercel/og';
+import { method } from './_lib/http.js';
const WIDTH = 1200;
const HEIGHT = 630;
@@ -193,6 +194,10 @@ export default async function handler(req, res) {
res.end();
return;
}
+ // A share card is a GET surface. Without this gate any verb (POST, DELETE)
+ // drove a full satori render, so an unthrottled write-shaped request could
+ // burn image-render CPU on a route that never accepts writes.
+ if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, 'http://x');
const origin = originOf(req);
diff --git a/api/provenance.js b/api/provenance.js
index 6b80a70b8..d25a75aa0 100644
--- a/api/provenance.js
+++ b/api/provenance.js
@@ -14,13 +14,16 @@
* authenticity for free. Anchoring (the paid write) lives in the MCP tool only.
*/
-import { cors, wrap } from './_lib/http.js';
+import { cors, method, wrap } from './_lib/http.js';
import { toolDefs } from './_mcp3d/tools/provenance.js';
const verifyTool = toolDefs.find((d) => d.name === 'verify_provenance');
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ // Verification is a read. The CORS preflight already advertises GET only;
+ // enforce it so a POST cannot drive a hash fetch off a body-less request.
+ if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, 'http://x');
const src = url.searchParams.get('src') || url.searchParams.get('glb_url') || '';
diff --git a/api/rss/announcements.js b/api/rss/announcements.js
index 474abd22b..cb2e14e8b 100644
--- a/api/rss/announcements.js
+++ b/api/rss/announcements.js
@@ -1,4 +1,4 @@
-// GET /rss/announcements.xml — RSS 2.0 feed of three.ws news/announcements.
+// GET /rss/announcements.xml: RSS 2.0 feed of three.ws news/announcements.
// Default source: data/rss/items.json (curated, hand-edited).
// Mirror modes: ?source=trythreews | ?source=nichxbt | ?source=archive (X scrape).
@@ -17,9 +17,11 @@ export default async function handler(req, res) {
// A misspelled source used to fall through to the curated feed, so a reader
// subscribed to ?source=trythreewz silently received a different feed and had
- // no way to notice. Say so instead.
+ // no way to notice. Say so instead, echoing back only enough of what they
+ // sent to recognize the typo.
if (!VALID_SOURCES.includes(sourceParam)) {
- error(res, 400, 'unknown_source', `unknown source "${sourceParam}"; expected one of: ${VALID_SOURCES.join(', ')}`);
+ const echoed = sourceParam.slice(0, 40);
+ error(res, 400, 'unknown_source', `unknown source "${echoed}"; expected one of: ${VALID_SOURCES.join(', ')}`);
return;
}
diff --git a/api/share/x.js b/api/share/x.js
index 46f4c29dc..ac916df54 100644
--- a/api/share/x.js
+++ b/api/share/x.js
@@ -11,7 +11,10 @@
*
* No connected X account → 409 not_connected with a connect_url the client can
* route the user to (/api/auth/x/connect). The OAuth scope requested there
- * includes media.write so the upload is authorized.
+ * includes media.write so the upload is authorized. An X token that can no
+ * longer be refreshed (reauth_required) takes the same 409 + connect_url shape:
+ * it is the same recovery, and answering 401 there would collide with this
+ * endpoint's own auth_required and send a signed-in user to /login instead.
*/
import { cors, method, wrap, error, json, readBody } from '../_lib/http.js';
@@ -22,7 +25,7 @@ import { publishTweet, XPostError, MAX_TWEET_LEN } from '../_lib/x-post.js';
// X media ceilings we enforce up front so an oversized body fails fast with a
// clear message instead of deep inside the chunked upload.
const MAX_IMAGE_BYTES = 5 * 1024 * 1024; // 5 MB (X still image limit)
-const MAX_VIDEO_BYTES = 64 * 1024 * 1024; // 64 MB — generous for a ≤10s 1080p clip
+const MAX_VIDEO_BYTES = 64 * 1024 * 1024; // 64 MB, generous for a 10s 1080p clip
const ALLOWED = {
'image/png': { kind: 'image', max: MAX_IMAGE_BYTES },
'image/jpeg': { kind: 'image', max: MAX_IMAGE_BYTES },
@@ -44,7 +47,7 @@ function captionFor(avatarId, override) {
const url = avatarId
? `three.ws/walk?avatar=${avatarId}`
: 'three.ws/walk';
- return `I walked my avatar around three.ws — try yours: ${url}`;
+ return `I walked my avatar around three.ws. Try yours: ${url}`;
}
export default wrap(async (req, res) => {
@@ -99,10 +102,11 @@ export default wrap(async (req, res) => {
} catch (err) {
if (err instanceof XPostError) {
const extra = { ...err.extra };
- if (err.code === 'not_connected') {
+ const needsConnect = err.code === 'not_connected' || err.code === 'reauth_required';
+ if (needsConnect) {
extra.connect_url = '/api/auth/x/connect';
}
- return json(res, err.code === 'not_connected' ? 409 : err.status, {
+ return json(res, needsConnect ? 409 : err.status, {
error: err.code,
error_description: err.message,
...extra,
diff --git a/api/skills/[id].js b/api/skills/[id].js
index 9ddb011ee..b955d860b 100644
--- a/api/skills/[id].js
+++ b/api/skills/[id].js
@@ -194,8 +194,20 @@ async function handleUpdate(req, res, id) {
? await sql`SELECT id, display_name FROM users WHERE id = ${updated.author_id}`
: [null];
updated.author_display_name = author?.display_name ?? null;
- updated.avg_rating = 0;
- updated.rating_count = 0;
+
+ // Re-read the live aggregate. Hardcoding zeros here reported a freshly
+ // edited skill as unrated, and the marketplace detail view re-renders from
+ // this response, so an author editing a description watched their rating
+ // disappear until the next reload.
+ const [stats] = await sql`
+ SELECT
+ ROUND(COALESCE(AVG(rating), 0)::numeric, 1)::float AS avg_rating,
+ COUNT(rating)::int AS rating_count
+ FROM skill_ratings
+ WHERE skill_id = ${id}
+ `;
+ updated.avg_rating = stats?.avg_rating ?? 0;
+ updated.rating_count = stats?.rating_count ?? 0;
return json(res, 200, { skill: toSkill(updated) });
}
diff --git a/api/skills/[id]/install.js b/api/skills/[id]/install.js
index d024a9269..aa457f9a9 100644
--- a/api/skills/[id]/install.js
+++ b/api/skills/[id]/install.js
@@ -1,6 +1,7 @@
import { sql } from '../../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
import { cors, json, error, method, wrap, rateLimited } from '../../_lib/http.js';
+import { requireCsrf } from '../../_lib/csrf.js';
import { limits } from '../../_lib/rate-limit.js';
import { isUuid } from '../../_lib/validate.js';
@@ -16,6 +17,14 @@ export default wrap(async (req, res) => {
if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
const userId = session?.id ?? bearer.userId;
+ // Install takes no request body, which made the POST a CORS-*simple* request:
+ // any page could fire `fetch(url, {method:'POST', credentials:'include'})` at
+ // it with no preflight and silently install skills into a signed-in visitor's
+ // account. Every sibling mutation here (rate, publish, mint, review) is
+ // preflight-protected by its JSON content-type; this one was not, so it needs
+ // the explicit token. Bearer callers are exempt inside requireCsrf.
+ if (session && !(await requireCsrf(req, res, userId))) return;
+
const rl = await limits.chatUser(userId);
if (!rl.success) return rateLimited(res, rl);
@@ -38,7 +47,7 @@ export default wrap(async (req, res) => {
return json(res, 200, { installed: true, schema_json: skill.schema_json, content: skill.content });
}
- // DELETE — uninstall
+ // DELETE: uninstall
await sql`
WITH del AS (
DELETE FROM skill_installs
diff --git a/api/skills/index.js b/api/skills/index.js
index 021c19d86..40424a52c 100644
--- a/api/skills/index.js
+++ b/api/skills/index.js
@@ -141,14 +141,20 @@ async function handleList(req, res) {
FROM marketplace_skills
WHERE id = ${cursor} AND is_public = true
`;
- if (cr) {
- cursorInstallCount = cr.install_count;
- cursorCreatedAt = cr.created_at;
- cursorName = cr.name;
+ // A cursor whose pivot row is gone (deleted, or flipped private between
+ // pages) leaves every keyset predicate inert, which used to hand the
+ // caller page 1 again with the SAME next_cursor: "load more" then
+ // re-appended the first page forever. Terminate the sequence instead so
+ // the client stops cleanly and no duplicates land in the grid.
+ if (!cr) {
+ return json(res, 200, { skills: [], next_cursor: null }, { 'cache-control': 'no-store' });
}
+ cursorInstallCount = cr.install_count;
+ cursorCreatedAt = cr.created_at;
+ cursorName = cr.name;
}
- // Neon's tagged-template `sql` does not compose nested fragments — each
+ // Neon's tagged-template `sql` does not compose nested fragments: each
// interpolation becomes a positional `$N` parameter. So we branch the full
// query per sort instead of building it from sql`...` fragments.
const rows = await runListQuery({
diff --git a/api/skills/license-onchain.js b/api/skills/license-onchain.js
index 0760eb059..2f7025ef4 100644
--- a/api/skills/license-onchain.js
+++ b/api/skills/license-onchain.js
@@ -5,15 +5,15 @@
* an active on-chain `SkillLicense` for a given skill on a given agent? Reads
* the license PDA directly from the `skill_license` Solana program (see
* contracts/skill-license/) and reports ownership. This is the *alternative*
- * access check described in the on-chain-licenses design — anyone can call it,
+ * access check described in the on-chain-licenses design. Anyone can call it,
* no auth required, because it only reads public chain state.
*
* Query (one of agent_mint | agent_id required, plus skill + wallet):
- * wallet — base58 Solana pubkey of the holder (required)
- * skill — skill name/slug (required)
- * agent_mint — the agent's on-chain grouping mint (base58)
- * agent_id — three.ws agent uuid; resolves to that agent's skill collection mint
- * network — 'mainnet' (default) | 'devnet'
+ * wallet base58 Solana pubkey of the holder (required)
+ * skill skill name/slug (required)
+ * agent_mint the agent's on-chain grouping mint (base58)
+ * agent_id three.ws agent uuid; resolves to that agent's skill collection mint
+ * network 'mainnet' (default) | 'devnet'
*
* Response: { data: { owned, exists, revoked, deployed, license, nft_mint,
* owner_token_account, program_id, network, explorer, record } }
@@ -90,7 +90,7 @@ export default wrap(async (req, res) => {
res,
409,
'no_collection',
- 'agent has no on-chain skill collection yet — nothing can be licensed on-chain',
+ 'agent has no on-chain skill collection yet; nothing can be licensed on-chain',
);
}
agentMint = agent.skill_collection_mint;
diff --git a/api/skills/mint.js b/api/skills/mint.js
index bf7fd17d6..45c12b043 100644
--- a/api/skills/mint.js
+++ b/api/skills/mint.js
@@ -12,7 +12,7 @@
* proven by the existing confirmation pipeline (api/_lib/purchase-confirm.js),
* which locates the tx on-chain and asserts the correct amount reached the
* agent's payout wallet. If the purchase is still pending we run that same
- * confirmation here before minting — so a caller cannot mint without a real,
+ * confirmation here before minting, so a caller cannot mint without a real,
* correctly-routed payment. The recipient wallet must also be linked to the
* buyer's account, so nobody can mint a license into a stranger's wallet.
*
@@ -81,7 +81,7 @@ export default wrap(async (req, res) => {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
- // Cookie-session mutation — CSRF required (bearer callers exempt inside requireCsrf).
+ // Cookie-session mutation: CSRF required (bearer callers exempt inside requireCsrf).
if (auth.viaSession && !(await requireCsrf(req, res, auth.userId))) return;
const rl = await limits.authIp(clientIp(req));
@@ -91,7 +91,7 @@ export default wrap(async (req, res) => {
const skill = body.skill_name || body.skill;
const { agent_id: agentId, user_wallet: userWallet, transaction_signature: txSig } = body;
- // The NFT recipient wallet must belong to the caller — never mint a license
+ // The NFT recipient wallet must belong to the caller. Never mint a license
// into a wallet the buyer hasn't linked to their account.
const [linked] = await sql`
SELECT id FROM user_wallets
@@ -128,11 +128,11 @@ export default wrap(async (req, res) => {
`;
}
if (!purchase) {
- return error(res, 404, 'no_purchase', 'no purchase found for this skill — buy it first');
+ return error(res, 404, 'no_purchase', 'no purchase found for this skill; buy it first');
}
// A caller-supplied signature that contradicts the recorded one is a red
- // flag — refuse rather than mint against the wrong payment.
+ // flag: refuse rather than mint against the wrong payment.
if (txSig && purchase.tx_signature && purchase.tx_signature !== txSig) {
return error(
res,
@@ -148,7 +148,7 @@ export default wrap(async (req, res) => {
}
// Confirm the payment if it hasn't been confirmed yet. This is the on-chain
- // verification step — it locates the tx and asserts the correct amount
+ // verification step: it locates the tx and asserts the correct amount
// reached the agent's payout wallet before we mint anything.
if (purchase.status !== 'confirmed') {
let result;
@@ -205,7 +205,7 @@ export default wrap(async (req, res) => {
`;
} catch (e) {
if (e?.code === '23505') {
- // Another call recorded a mint first — return the canonical one.
+ // Another call recorded a mint first, so return the canonical one.
const [row] = await sql`SELECT * FROM skill_purchases WHERE id = ${purchase.id}`;
return json(res, 200, { data: mintResponse(row, { alreadyMinted: true }) });
}
@@ -213,7 +213,7 @@ export default wrap(async (req, res) => {
}
if (!recorded) {
// Lost the race; the persisted mint wins. Our freshly minted asset is a
- // harmless orphan — surface the canonical one.
+ // harmless orphan. Surface the canonical one.
const [row] = await sql`SELECT * FROM skill_purchases WHERE id = ${purchase.id}`;
console.warn('[skills/mint] mint recorded by concurrent call; orphaned asset', {
purchase_id: purchase.id,
diff --git a/api/skills/review.js b/api/skills/review.js
index 2e2b9762b..ef2e02699 100644
--- a/api/skills/review.js
+++ b/api/skills/review.js
@@ -1,5 +1,5 @@
/**
- * Per-skill ratings & reviews — paid skills sold on an agent.
+ * Per-skill ratings and reviews for paid skills sold on an agent.
* ──────────────────────────────────────────────────────────
* GET /api/skills/review?agent_id=<uuid>&skill=<name>&page=<n>&page_size=<n>
* → { data: { summary: { rating_avg, rating_count, breakdown }, reviews, page,
@@ -17,8 +17,8 @@
* One review per (agent_id, skill, reviewer); POST upserts in place.
*
* Schema: api/_lib/migrations/20260621180000_skill_reviews.sql.
- * Ownership is verified with the canonical hasSkillAccess() helper — the same
- * gate the paid-skill execution path uses — so a review can only follow real,
+ * Ownership is verified with the canonical hasSkillAccess() helper, the same
+ * gate the paid-skill execution path uses, so a review can only follow real,
* on-chain-confirmed access.
*/
@@ -191,7 +191,7 @@ async function handleUpsert(req, res) {
return error(res, 422, 'self_review_forbidden', 'you cannot review your own skill');
}
- // Ownership gate: the reviewer must have real access to this paid skill —
+ // Ownership gate: the reviewer must have real access to this paid skill:
// a confirmed purchase, time-pass, agent/creator subscription, or active
// trial. hasSkillAccess is the canonical gate used by the execution path.
const access = await hasSkillAccess(auth.userId, agentId, skill);
@@ -237,7 +237,7 @@ async function handleUpsert(req, res) {
});
}
- // Anchor the review on Solana — fire-and-forget, never blocks the response.
+ // Anchor the review on Solana. Fire-and-forget, never blocks the response.
attestReview({
reviewId: row.id,
updatedAt: row.updated_at,
diff --git a/api/social/sentiment-pulse.js b/api/social/sentiment-pulse.js
index abc8a5501..66789f6f5 100644
--- a/api/social/sentiment-pulse.js
+++ b/api/social/sentiment-pulse.js
@@ -1,19 +1,27 @@
// POST /api/social/sentiment-pulse
//
-// One-call sentiment pulse for a Solana token. Pulls recent commentary
-// from pump.fun's frontend-api-v3 comments endpoint (the same source the
-// pump.fun coin page renders) and scores it with the in-repo lexicon
-// scorer. Optionally accepts a list of additional text snippets to fold
-// into the score (e.g. X posts the caller has already collected).
+// One-call sentiment pulse for a Solana token. Pulls the coin's live
+// community commentary from pump.fun and scores it with the in-repo lexicon
+// scorer. Optionally accepts a list of additional text snippets to fold into
+// the score (e.g. X posts the caller has already collected).
+//
+// Source note: pump.fun retired the `/replies/:mint` comments route this
+// endpoint used to read (it now 404s for every mint, including $THREE), so
+// the pulse silently scored an empty set and reported a confident neutral
+// reading. Coin commentary lives in "callouts" now, the feed the coin page
+// renders via frontend-api-v3 `/callout/top/:mint`, where each entry carries
+// the poster's thesis, handle and timestamp. That is the source below, read
+// through the shared pump.fun fetch helper (identified user-agent, bounded
+// timeout, one retry on a rate limit or 5xx).
//
// This is the unauthenticated, no-key endpoint behind the paid
-// `sentiment_pulse` MCP tool — it does no caching of its own (callers
-// should hit /api/social/sentiment if they already have the texts).
+// `sentiment_pulse` MCP tool. It does no caching of its own (callers should
+// hit /api/social/sentiment if they already have the texts).
//
// Body:
// {
// token: string, // Solana SPL or pump.fun mint pubkey
-// limit?: number, // max comments to fetch (default 100, max 200)
+// limit?: number, // max callouts to score (default 100, max 200)
// extraTexts?: string[], // additional snippets to score
// }
//
@@ -23,16 +31,22 @@
// token,
// overall: { score, posPct, negPct, neuPct, count, examples },
// breakdown: { pumpfun: <result>, extra: <result> },
-// sources: { pumpfun: 'https://...', extra: <n> },
+// sources: { pumpfun: 'https://...', pumpfunStatus, pumpfunCount, extraCount },
// fetchedAt
// }
+//
+// A pump.fun outage with no caller-supplied texts answers 502
+// `upstream_unavailable`, never a fabricated neutral score. A coin that is
+// simply quiet (upstream fine, zero callouts) still answers 200 with
+// `count: 0`, because an empty feed is data, not an outage.
import { z } from 'zod';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { PUMP_FRONTEND_BASE, pumpFetchJson } from '../_lib/pump-feed-fetch.js';
-const PUMPFUN_BASE = 'https://frontend-api-v3.pump.fun';
const SOLANA_MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const FETCH_TIMEOUT_MS = 8000;
const bodySchema = z.object({
token: z.string().regex(SOLANA_MINT_RE, 'token must be a base58 Solana mint pubkey'),
@@ -40,35 +54,49 @@ const bodySchema = z.object({
extraTexts: z.array(z.string().max(2000)).max(200).optional(),
});
-async function fetchPumpFunComments(mint, limit) {
- // frontend-api-v3 returns the most recent comments first. The endpoint
- // supports limit + offset; we just take the most recent batch.
- const url = `${PUMPFUN_BASE}/replies/${mint}?limit=${limit}&offset=0`;
- let res;
- try {
- const controller = new AbortController();
- const t = setTimeout(() => controller.abort(), 8000);
- try {
- res = await fetch(url, { signal: controller.signal });
- } finally {
- clearTimeout(t);
- }
- } catch (err) {
- return { error: err?.message || 'fetch failed', url };
+/**
+ * Map raw pump.fun callout rows into the scorer's post shape, newest first.
+ * Rows with no thesis carry no sentiment and are dropped rather than counted
+ * as neutral, which would drag every score toward zero.
+ *
+ * @param {any[]} callouts
+ * @param {number} limit
+ * @returns {Array<{ id?: string, ts?: string, text: string, author?: string }>}
+ */
+export function calloutsToPosts(callouts, limit) {
+ if (!Array.isArray(callouts)) return [];
+ return callouts
+ .map((c) => {
+ const at = Number(c?.createdAt);
+ const ms = Number.isFinite(at) && at > 0 ? at : null;
+ return {
+ id: c?.calloutId ? String(c.calloutId) : undefined,
+ ts: ms ? new Date(ms).toISOString() : undefined,
+ text: String(c?.thesis || '').trim().slice(0, 2000),
+ author: c?.username ? String(c.username) : undefined,
+ _at: ms ?? 0,
+ };
+ })
+ .filter((p) => p.text)
+ .sort((a, b) => b._at - a._at)
+ .slice(0, limit)
+ .map(({ _at, ...post }) => post);
+}
+
+/**
+ * Fetch a coin's most recent pump.fun callouts. Never throws: an upstream
+ * failure is reported as `{ error, url }` for the handler to surface.
+ */
+async function fetchPumpFunCallouts(mint, limit) {
+ const url =
+ `${PUMP_FRONTEND_BASE}/callout/top/${encodeURIComponent(mint)}` +
+ `?limit=${limit}&sortBy=TIMESTAMP&sortOrder=DESC`;
+ const { ok, status, body } = await pumpFetchJson(url, { timeoutMs: FETCH_TIMEOUT_MS });
+ if (!ok) {
+ return { error: status ? `pump.fun returned ${status}` : 'pump.fun unreachable', url };
}
- if (!res.ok) return { error: `pump.fun returned ${res.status}`, url };
- const data = await res.json().catch(() => null);
- if (!data) return { error: 'invalid json from pump.fun', url };
- const replies = Array.isArray(data?.replies) ? data.replies : Array.isArray(data) ? data : [];
- const posts = replies
- .map((r) => ({
- id: r.id || r.signature || undefined,
- ts: r.timestamp ? new Date(r.timestamp).toISOString() : undefined,
- text: String(r.text || r.message || '').slice(0, 2000),
- author: r.user || r.username || undefined,
- }))
- .filter((p) => p.text);
- return { posts, url };
+ const rows = Array.isArray(body?.callouts) ? body.callouts : Array.isArray(body) ? body : [];
+ return { posts: calloutsToPosts(rows, limit), url };
}
export default wrap(async (req, res) => {
@@ -82,7 +110,7 @@ export default wrap(async (req, res) => {
try {
raw = await readJson(req);
} catch {
- return error(res, 400, 'invalid_json', 'invalid json');
+ return error(res, 400, 'validation_error', 'invalid json');
}
const parsed = bodySchema.safeParse(raw);
if (!parsed.success) {
@@ -92,16 +120,26 @@ export default wrap(async (req, res) => {
const { scoreSentiment } = await import('../../src/social/sentiment.js');
- const pumpfun = await fetchPumpFunComments(token, limit);
+ const pumpfun = await fetchPumpFunCallouts(token, limit);
const pumpfunPosts = pumpfun.error ? [] : pumpfun.posts;
- const extraPosts = extraTexts.map((t, i) => ({ id: `extra-${i}`, text: t }));
+ const extraPosts = extraTexts
+ .map((t, i) => ({ id: `extra-${i}`, text: String(t).trim() }))
+ .filter((p) => p.text);
+
+ // With the only live source down and nothing supplied by the caller there
+ // is nothing to score. Scoring the empty set would answer "neutral, 100%"
+ // with the same confidence as a real reading, so report the outage.
+ if (pumpfun.error && extraPosts.length === 0) {
+ return error(res, 502, 'upstream_unavailable', pumpfun.error, {
+ token,
+ source: 'pump.fun',
+ });
+ }
const all = [...pumpfunPosts, ...extraPosts];
const overall = scoreSentiment(all);
const breakdown = {
- pumpfun: pumpfun.error
- ? { error: pumpfun.error, count: 0 }
- : scoreSentiment(pumpfunPosts),
+ pumpfun: pumpfun.error ? { error: pumpfun.error, count: 0 } : scoreSentiment(pumpfunPosts),
extra: scoreSentiment(extraPosts),
};
@@ -112,6 +150,7 @@ export default wrap(async (req, res) => {
breakdown,
sources: {
pumpfun: pumpfun.error ? null : pumpfun.url,
+ pumpfunStatus: pumpfun.error ? 'unavailable' : 'ok',
pumpfunCount: pumpfunPosts.length,
extraCount: extraPosts.length,
},
diff --git a/api/subscriptions/index.js b/api/subscriptions/index.js
index fe7dc8e25..6fd12d9b5 100644
--- a/api/subscriptions/index.js
+++ b/api/subscriptions/index.js
@@ -12,7 +12,7 @@ import { z } from 'zod';
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
-import { parse } from '../_lib/validate.js';
+import { parse, isUuid } from '../_lib/validate.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
import { chargeSubscription } from '../_lib/subscription-billing.js';
@@ -29,10 +29,15 @@ export default wrap(async (req, res) => {
const pathMatch = url.match(/\/api\/subscriptions\/([^?/]+)/);
const segment = pathMatch ? pathMatch[1] : null;
- if (segment === 'mine' && req.method === 'GET') return handleMine(req, res);
- if (!segment && req.method === 'POST') return handleSubscribe(req, res);
- if (segment && req.method === 'DELETE') return handleCancel(req, res, segment);
- if (segment && req.method === 'GET') return handleDetail(req, res, segment);
+ // HEAD must reach whatever GET reaches (RFC 9110 9.3.2); Node strips the body
+ // on the way out. Without this a HEAD probe matched no branch and fell through
+ // to the 405 below.
+ const verb = req.method === 'HEAD' ? 'GET' : req.method;
+
+ if (segment === 'mine' && verb === 'GET') return handleMine(req, res);
+ if (!segment && verb === 'POST') return handleSubscribe(req, res);
+ if (segment && verb === 'DELETE') return handleCancel(req, res, segment);
+ if (segment && verb === 'GET') return handleDetail(req, res, segment);
return error(res, 405, 'method_not_allowed', 'method not allowed');
});
@@ -132,6 +137,13 @@ async function handleCancel(req, res, subId) {
// CSRF on state-changing session-cookie requests; bearer tokens are exempt.
if (!(await requireCsrf(req, res, user.id))) return;
+ // The path segment goes straight into a uuid comparison, and Postgres answers
+ // a malformed one with 22P02, which surfaced as a 500 instead of telling the
+ // caller their id was wrong.
+ if (!isUuid(subId)) {
+ return error(res, 400, 'validation_error', 'subscription id must be a valid UUID');
+ }
+
const [sub] = await sql`
UPDATE creator_subscriptions
SET status = 'cancelled', cancelled_at = now()
@@ -148,6 +160,10 @@ async function handleDetail(req, res, subId) {
const user = await getSessionUser(req);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!isUuid(subId)) {
+ return error(res, 400, 'validation_error', 'subscription id must be a valid UUID');
+ }
+
const [sub] = await sql`
SELECT
cs.*, sp.name AS plan_name, sp.price_usd, sp.interval, sp.creator_id,
diff --git a/api/subscriptions/plans.js b/api/subscriptions/plans.js
index 93f77e8c2..f4deae3fa 100644
--- a/api/subscriptions/plans.js
+++ b/api/subscriptions/plans.js
@@ -3,8 +3,10 @@
*
* Routes (via vercel.json):
* GET /api/subscriptions/plans?creator_id= list active plans (public)
+ * GET /api/subscriptions/plans/:id one plan (public if active, owner otherwise)
* POST /api/subscriptions/plans create plan (auth, max 3)
* PATCH /api/subscriptions/plans/:id update name/price/perks (auth, owner)
+ * PUT /api/subscriptions/plans/:id alias of PATCH (the dashboard editor sends PUT)
* DELETE /api/subscriptions/plans/:id soft-delete (auth, owner)
*/
@@ -36,17 +38,27 @@ const patchSchema = z.object({
});
export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,PATCH,DELETE,OPTIONS', credentials: true })) return;
+ if (cors(req, res, { methods: 'GET,POST,PATCH,PUT,DELETE,OPTIONS', credentials: true })) return;
// Extract path param: /api/subscriptions/plans/:id
const url = req.url || '';
const pathMatch = url.match(/\/api\/subscriptions\/plans\/([^?/]+)/);
const planId = pathMatch ? pathMatch[1] : null;
- if (req.method === 'GET') return handleList(req, res);
- if (req.method === 'POST' && !planId) return handleCreate(req, res);
- if (req.method === 'PATCH' && planId) return handlePatch(req, res, planId);
- if (req.method === 'DELETE' && planId) return handleDelete(req, res, planId);
+ // HEAD must reach whatever GET reaches (RFC 9110 9.3.2); Node strips the body
+ // on the way out. Without this a HEAD probe matched no branch and fell through
+ // to the 405 below.
+ const verb = req.method === 'HEAD' ? 'GET' : req.method;
+
+ if (verb === 'GET' && planId) return handleGetOne(req, res, planId);
+ if (verb === 'GET') return handleList(req, res);
+ if (verb === 'POST' && !planId) return handleCreate(req, res);
+ // PUT is accepted alongside PATCH: the dashboard plan editor
+ // (src/dashboard-next/pages/monetize.js) saves an edit with PUT, and the body
+ // is a partial update either way. Without this the whole "edit tier" path
+ // answered 405 and the creator's change was silently lost.
+ if ((verb === 'PATCH' || verb === 'PUT') && planId) return handlePatch(req, res, planId);
+ if (verb === 'DELETE' && planId) return handleDelete(req, res, planId);
return error(res, 405, 'method_not_allowed', 'method not allowed');
});
@@ -115,6 +127,32 @@ async function handleList(req, res) {
return json(res, 200, { plans: rows });
}
+// Single plan by id. Active plans are public (they are what the marketplace
+// renders); a draft is visible only to its creator, matching the visibility rule
+// handleList applies to include_inactive.
+async function handleGetOne(req, res, planId) {
+ if (!isUuid(planId)) {
+ return error(res, 400, 'validation_error', 'plan id must be a valid UUID');
+ }
+
+ const ip = clientIp(req);
+ const rl = await limits.publicIp(ip);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const [plan] = await sql`
+ SELECT id, creator_id, agent_id, name, price_usd, interval, perks, included_skills, active, created_at
+ FROM subscription_plans WHERE id = ${planId}
+ `;
+ if (!plan) return error(res, 404, 'not_found', 'plan not found');
+ if (!plan.active) {
+ const user = await getSessionUser(req);
+ if (!user || user.id !== plan.creator_id) {
+ return error(res, 404, 'not_found', 'plan not found');
+ }
+ }
+ return json(res, 200, { plan });
+}
+
async function handleCreate(req, res) {
if (!method(req, res, ['POST'])) return;
const user = await getSessionUser(req);
@@ -159,13 +197,21 @@ async function handleCreate(req, res) {
}
async function handlePatch(req, res, planId) {
- if (!method(req, res, ['PATCH'])) return;
+ if (!method(req, res, ['PATCH', 'PUT'])) return;
const user = await getSessionUser(req);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
// CSRF on state-changing session-cookie requests; bearer tokens are exempt.
if (!(await requireCsrf(req, res, user.id))) return;
+ // The id goes straight into a uuid comparison below, and Postgres answers a
+ // malformed one with 22P02, which surfaced as a 500 instead of telling the
+ // caller their id was wrong. Reject it here, as handleList already does for
+ // the creator_id/agent_id query params.
+ if (!isUuid(planId)) {
+ return error(res, 400, 'validation_error', 'plan id must be a valid UUID');
+ }
+
const body = parse(patchSchema, await readJson(req));
const [existing] = await sql`
@@ -238,6 +284,10 @@ async function handleDelete(req, res, planId) {
// CSRF on state-changing session-cookie requests; bearer tokens are exempt.
if (!(await requireCsrf(req, res, user.id))) return;
+ if (!isUuid(planId)) {
+ return error(res, 400, 'validation_error', 'plan id must be a valid UUID');
+ }
+
const [plan] = await sql`
UPDATE subscription_plans
SET active = false
diff --git a/api/subscriptions/verify.js b/api/subscriptions/verify.js
index 9755249d0..ca043e33c 100644
--- a/api/subscriptions/verify.js
+++ b/api/subscriptions/verify.js
@@ -93,7 +93,7 @@ export default wrap(async (req, res) => {
}
if (checkout.expires_at && new Date(checkout.expires_at) < new Date()) {
await sql`UPDATE subscription_checkouts SET status = 'expired' WHERE id = ${checkout.id} AND status = 'pending'`;
- return error(res, 410, 'checkout_expired', 'this checkout expired — start a new subscription');
+ return error(res, 410, 'checkout_expired', 'this checkout expired, start a new subscription');
}
const result = await verifySubscriptionPayment(checkout, transactionSignature || null);
diff --git a/api/token/[action].js b/api/token/[action].js
index 36dddb207..227b6c7e6 100644
--- a/api/token/[action].js
+++ b/api/token/[action].js
@@ -12,8 +12,8 @@
// on its own and powers shared UI (price display, the pay helper in src).
import { z } from 'zod';
-import { env } from '../_lib/env.js';
import { getSessionUser } from '../_lib/auth.js';
+import { isAdminUser } from '../_lib/admin.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { parse } from '../_lib/validate.js';
@@ -58,13 +58,6 @@ const QUOTE_UNAVAILABLE_DETAIL = {
rewards_unavailable: 'The $THREE payment rail is briefly unavailable. Try again shortly.',
};
-function isAdmin(user) {
- if (!user) return false;
- if (user.is_admin) return true;
- const w = (user.wallet_address || '').toLowerCase();
- return Boolean(w) && env.ADMIN_ADDRESSES.has(w);
-}
-
// ── GET /api/token/config ────────────────────────────────────────────────────
async function handleConfig(req, res) {
@@ -85,7 +78,9 @@ async function handlePrice(req, res) {
const usdParam = url.searchParams.get('usd');
let quote = null;
if (usdParam != null) {
- const q = await quoteTokenForUsd(Number(usdParam));
+ // Quote against the price this response reports, not a second lookup that
+ // could cross the cache boundary and disagree with the `price_usd` beside it.
+ const q = await quoteTokenForUsd(Number(usdParam), { price });
quote = { usd: q.usd, token_amount: q.tokenAmount, atomics: q.atomics.toString() };
}
return json(res, 200, {
@@ -362,7 +357,7 @@ async function handlePayments(req, res) {
if (!method(req, res, ['GET'])) return;
const user = await getSessionUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
- if (!isAdmin(user)) return error(res, 403, 'forbidden', 'admin access required');
+ if (!(await isAdminUser(user))) return error(res, 403, 'forbidden', 'admin access required');
const url = new URL(req.url, 'http://x');
const page = await listPayments({
diff --git a/api/trade-og.js b/api/trade-og.js
index fb5346a56..58af57e76 100644
--- a/api/trade-og.js
+++ b/api/trade-og.js
@@ -23,6 +23,7 @@
import { cors, wrap } from './_lib/http.js';
import { loadTradeCard } from './_lib/trade-card-store.js';
+import { fetchOgImage } from './_lib/og-avatar.js';
import { env } from './_lib/env.js';
const CACHE = 'public, max-age=300, s-maxage=86400, stale-while-revalidate=600';
@@ -55,21 +56,12 @@ export default wrap(async (req, res) => {
const origin = env.APP_ORIGIN || 'https://three.ws';
const card = await loadTradeCard(id, { origin });
- if (!card) return fallback(res);
-
- // Embed the agent portrait so the card is self-contained. A slow or dead
- // avatar host degrades to the initial monogram, never to a broken unfurl.
- let avatar = null;
- if (card.agentImage && /^https?:\/\//.test(card.agentImage)) {
- try {
- const resp = await fetch(card.agentImage, { signal: AbortSignal.timeout(3000) });
- if (resp.ok) {
- const ct = resp.headers.get('content-type') || 'image/jpeg';
- const b64 = Buffer.from(await resp.arrayBuffer()).toString('base64');
- avatar = { ct, b64 };
- }
- } catch { /* non-fatal: monogram fallback below */ }
- }
+ if (!card) return fallback(res, origin);
+
+ // Embed the agent portrait so the card is self-contained. A slow, dead, or
+ // oversized avatar host degrades to the initial monogram below, never to a
+ // broken unfurl and never to an unbounded read (see _lib/og-avatar.js).
+ const avatar = await fetchOgImage(card.agentImage);
const accent = card.accent;
const initial = (card.agentName[0] || 'A').toUpperCase();
@@ -175,9 +167,9 @@ function chipRect(x0, y0, w, label, color) {
}
/** Unknown / open / deleted: fall back to the site card rather than a broken image. */
-function fallback(res) {
+function fallback(res, origin) {
res.statusCode = 302;
- res.setHeader('location', 'https://three.ws/og-image.png');
+ res.setHeader('location', `${origin}/og-image.png`);
res.setHeader('cache-control', 'no-cache');
res.end();
}
diff --git a/api/trader-og.js b/api/trader-og.js
index 3014dbbe4..bc8d7d185 100644
--- a/api/trader-og.js
+++ b/api/trader-og.js
@@ -21,6 +21,8 @@
import { cors, wrap } from './_lib/http.js';
import { sql } from './_lib/db.js';
import { isUuid } from './_lib/validate.js';
+import { fetchOgImage } from './_lib/og-avatar.js';
+import { env } from './_lib/env.js';
const LAMPORTS = 1e9;
const CACHE = 'public, max-age=120, s-maxage=900, stale-while-revalidate=60';
@@ -50,12 +52,13 @@ export default wrap(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
const agentId = (url.searchParams.get('agent_id') || '').trim();
const walletParam = (url.searchParams.get('wallet') || '').trim();
+ const origin = env.APP_ORIGIN || 'https://three.ws';
const wallet = BASE58_RE.test(walletParam) ? walletParam
: (!isUuid(agentId) && BASE58_RE.test(agentId)) ? agentId
: '';
if (!isUuid(agentId) && !wallet) {
- return fallback(res);
+ return fallback(res, origin);
}
// Unified card shape, filled by whichever identity we were given.
@@ -80,9 +83,9 @@ export default wrap(async (req, res) => {
where wallet = ${wallet}
`;
} catch {
- return fallback(res);
+ return fallback(res, origin);
}
- if (!rep) return fallback(res);
+ if (!rep) return fallback(res, origin);
name = `${wallet.slice(0, 4)}…${wallet.slice(-4)}`;
initial = wallet[0].toUpperCase();
@@ -104,7 +107,7 @@ export default wrap(async (req, res) => {
where id = ${agentId} and deleted_at is null
limit 1
`;
- if (!agent) return fallback(res);
+ if (!agent) return fallback(res, origin);
[stats] = await sql`
select
@@ -117,7 +120,7 @@ export default wrap(async (req, res) => {
where agent_id = ${agentId} and network = 'mainnet'
`;
} catch {
- return fallback(res);
+ return fallback(res, origin);
}
name = trunc(agent.name || 'Agent', 28);
@@ -168,19 +171,9 @@ export default wrap(async (req, res) => {
const largeArcTrack = 1;
const largeArcFill = sweepAngle > 180 ? 1 : 0;
- // Fetch avatar if URL available (base64 embed)
- let avatarData = null;
- if (avatarUrl && avatarUrl.startsWith('http')) {
- try {
- const imgResp = await fetch(avatarUrl, { signal: AbortSignal.timeout(3000) });
- if (imgResp.ok) {
- const ct = imgResp.headers.get('content-type') || 'image/jpeg';
- const ab = await imgResp.arrayBuffer();
- const b64 = Buffer.from(ab).toString('base64');
- avatarData = { ct, b64 };
- }
- } catch { /* non-fatal */ }
- }
+ // Inline the portrait so the card is self-contained. A dead, slow, or
+ // oversized host degrades to the monogram below (see _lib/og-avatar.js).
+ const avatarData = await fetchOgImage(avatarUrl);
const svg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
width="1200" height="630" viewBox="0 0 1200 630">
@@ -246,7 +239,7 @@ export default wrap(async (req, res) => {
<!-- separator -->
<line x1="24" y1="282" x2="1176" y2="282" stroke="#1f2937" stroke-width="1"/>
- <!-- recent trade placeholder hint -->
+ <!-- the standing claim under every number on this card -->
<text x="308" y="316" font-family="Inter,system-ui,sans-serif" font-size="14" fill="#374151">
Every number is traceable to its on-chain transaction.
</text>
@@ -276,9 +269,9 @@ function metricCard(x0, y0, label, value, color) {
</g>`;
}
-function fallback(res) {
+function fallback(res, origin) {
res.statusCode = 302;
- res.setHeader('location', 'https://three.ws/og-image.png');
+ res.setHeader('location', `${origin}/og-image.png`);
res.setHeader('cache-control', 'no-cache');
res.end();
}
diff --git a/api/trending.js b/api/trending.js
index a44195c69..85251f3ba 100644
--- a/api/trending.js
+++ b/api/trending.js
@@ -32,6 +32,32 @@ import { thumbnailUrl } from './_lib/r2.js';
const WINDOWS = new Set(['24h', '7d', 'all']);
const WINDOW_INTERVAL = { '24h': '1 day', '7d': '7 days' };
const COIN_INTERVAL = { '24h': '24 hours', '7d': '7 days' };
+const DEFAULT_LIMIT = 10;
+const MAX_LIMIT = 20;
+
+/**
+ * A non-numeric `limit` used to reach Postgres as `limit NaN`, which fails both
+ * queries; the degrade-to-empty catch below then rendered that as "nothing is
+ * trending" instead of a bad request. Unparseable now falls back to the default,
+ * matching how an unknown `window` falls back to 24h.
+ */
+export function parseLimit(raw) {
+ const n = Number.parseInt(raw ?? '', 10);
+ if (!Number.isFinite(n)) return DEFAULT_LIMIT;
+ return Math.min(MAX_LIMIT, Math.max(1, n));
+}
+
+/**
+ * Either ranking may degrade to empty rather than 500 the whole board, but a
+ * swallowed failure that logs nothing is indistinguishable from a genuinely quiet
+ * window, which is how the `limit NaN` bug above survived. Always leave a trace.
+ */
+function degradeToEmpty(label) {
+ return (err) => {
+ console.error(`[trending] ${label} ranking failed, serving it empty:`, err?.message || err);
+ return [];
+ };
+}
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
@@ -42,7 +68,7 @@ export default wrap(async (req, res) => {
const p = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;
const win = WINDOWS.has(p.get('window')) ? p.get('window') : '24h';
- const limit = Math.min(20, Math.max(1, Number(p.get('limit') || 10)));
+ const limit = parseLimit(p.get('limit'));
// ── Agents ─────────────────────────────────────────────────────────────
let agentRows;
@@ -70,7 +96,7 @@ export default wrap(async (req, res) => {
where t.chat_count > 0
order by t.chat_count desc
limit ${limit}
- `.catch(() => []);
+ `.catch(degradeToEmpty('agent'));
} else {
// Count real LLM usage events in the time window per public agent. The
// all-time chat_count is derived via a correlated subquery (no stored col).
@@ -99,7 +125,7 @@ export default wrap(async (req, res) => {
a.thumbnail_key, a.visibility
order by window_chats desc
limit ${limit}
- `.catch(() => []);
+ `.catch(degradeToEmpty('agent'));
}
const agents = agentRows.map((r, idx) => {
@@ -184,7 +210,7 @@ export default wrap(async (req, res) => {
where score is not null
order by score desc, momentum desc, smart_wallet_count desc, scored_at desc, mint
limit ${limit}
- `).catch(() => []);
+ `).catch(degradeToEmpty('coin'));
const coins = coinRows.map((r, idx) => ({
rank: idx + 1,
diff --git a/api/u-og.js b/api/u-og.js
index ff5991a7e..7e4940786 100644
--- a/api/u-og.js
+++ b/api/u-og.js
@@ -17,6 +17,8 @@ import { PARENT_LABEL } from './_lib/threews-sns.js';
const CACHE_OK = 'public, max-age=300, s-maxage=3600';
const CACHE_404 = 'public, max-age=60';
+// A degraded card must never be the one a crawler keeps.
+const CACHE_DEGRADED = 'no-store';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
@@ -32,34 +34,50 @@ export default wrap(async (req, res) => {
});
}
- const [user] = await sql`
- SELECT id, username, display_name
- FROM users
- WHERE lower(username) = ${raw} AND deleted_at IS NULL
- LIMIT 1
- `;
- if (!user) {
- return send(res, 404, CACHE_404, {
+ // This URL is what a crawler resolves for <meta og:image>. A thrown error here
+ // would answer an image request with a JSON error body and get the broken
+ // unfurl cached, so a database blip degrades to a real, uncached card of the
+ // handle we already know instead.
+ let user, claimRow, statRow;
+ try {
+ [user] = await sql`
+ SELECT id, username, display_name
+ FROM users
+ WHERE lower(username) = ${raw} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!user) {
+ return send(res, 404, CACHE_404, {
+ handle: raw,
+ display: 'User not found',
+ subdomain: null,
+ stats: null,
+ });
+ }
+
+ [claimRow] = await sql`
+ SELECT label FROM user_subdomains
+ WHERE user_id = ${user.id} AND parent = ${PARENT_LABEL}
+ LIMIT 1
+ `;
+
+ // Lightweight stat strip, the same numbers the showcase shows.
+ [statRow] = await sql`
+ SELECT
+ (SELECT count(*) FROM avatars WHERE owner_id = ${user.id} AND visibility = 'public' AND deleted_at IS NULL) AS avatars,
+ (SELECT count(*) FROM agent_identities WHERE user_id = ${user.id} AND is_public = true AND deleted_at IS NULL) AS agents
+ `;
+ } catch (err) {
+ console.error('[u-og] profile lookup failed, serving the degraded card:', err?.message || err);
+ return send(res, 200, CACHE_DEGRADED, {
handle: raw,
- display: 'User not found',
+ display: raw,
subdomain: null,
stats: null,
});
}
- const [claimRow] = await sql`
- SELECT label FROM user_subdomains
- WHERE user_id = ${user.id} AND parent = ${PARENT_LABEL}
- LIMIT 1
- `;
const subdomain = claimRow ? `${claimRow.label}.${PARENT_LABEL}.sol` : null;
-
- // Lightweight stat strip — same numbers the showcase shows.
- const [statRow] = await sql`
- SELECT
- (SELECT count(*) FROM avatars WHERE owner_id = ${user.id} AND visibility = 'public' AND deleted_at IS NULL) AS avatars,
- (SELECT count(*) FROM agent_identities WHERE user_id = ${user.id} AND is_public = true AND deleted_at IS NULL) AS agents
- `;
const stats = {
avatars: Number(statRow?.avatars || 0),
agents: Number(statRow?.agents || 0),
diff --git a/api/users/me/feed.js b/api/users/me/feed.js
index 7cf5744df..26fe18266 100644
--- a/api/users/me/feed.js
+++ b/api/users/me/feed.js
@@ -12,7 +12,9 @@
// first-time visitor's feed use.
// ?limit=… (1..50, default 30)
// ?before=<iso timestamp> — cursor for the next page (pass the last
-// item's created_at back for infinite scroll)
+// item's created_at back for infinite scroll).
+// A value that is not a parseable timestamp is
+// rejected with 400 validation_error.
//
// Every item: { kind, id, created_at, actor{username,display_name,avatar_url},
// title, subtitle?, href, image?, external?, isRemix?, isVariant? }
@@ -58,13 +60,22 @@ export default wrap(async (req, res) => {
const url = new URL(req.url, 'http://x');
const scope = url.searchParams.get('scope') === 'all' ? 'all' : 'following';
const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit'), 10) || 30));
- const before = (url.searchParams.get('before') || '').trim() || undefined;
const perKind = limit;
const followPerKind = Math.max(3, Math.ceil(limit / 4));
const rl = await limits.authedReadIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
+ // The cursor is compared against `created_at` inside every kind's query, so a
+ // value Postgres cannot cast to a timestamptz aborts the whole fan-out and
+ // surfaces as a 500 on what is really a malformed request. Validate it here
+ // and hand the queries a normalized ISO string.
+ const beforeParam = (url.searchParams.get('before') || '').trim();
+ if (beforeParam && !Number.isFinite(Date.parse(beforeParam))) {
+ return error(res, 400, 'validation_error', 'before must be an ISO 8601 timestamp');
+ }
+ const before = beforeParam ? new Date(beforeParam).toISOString() : undefined;
+
const viewer = await getSessionUser(req).catch(() => null);
if (scope === 'following' && !viewer) {
return error(res, 401, 'unauthorized', 'sign in to view your feed');
@@ -244,6 +255,7 @@ export default wrap(async (req, res) => {
from user_follows f
join users uf on uf.id = f.follower_id and uf.deleted_at is null and uf.username is not null
join users ut on ut.id = f.following_id and ut.deleted_at is null and ut.username is not null
+ where true
${before ? sql`and f.created_at < ${before}` : sql``}
order by f.created_at desc
limit ${followPerKind}
diff --git a/api/users/me/transaction-history.js b/api/users/me/transaction-history.js
index 2eaf5777c..5fef353fc 100644
--- a/api/users/me/transaction-history.js
+++ b/api/users/me/transaction-history.js
@@ -3,9 +3,9 @@
* Returns the authenticated caller's skill purchase/sale history.
*
* Query params:
- * ?role=buyer — only purchases where the caller bought (default when role omitted)
+ * ?role=buyer : only purchases where the caller bought
* ?role=seller — only sales where the caller's agent was the seller
- * ?role=all — both, merged and sorted by date desc
+ * ?role=all : both, merged and sorted by date desc (the default)
* ?limit=50 — number of rows (max 200, default 50)
* ?offset=0 — pagination offset
*
@@ -117,14 +117,10 @@ export default wrap(async (req, res) => {
return tb - ta;
});
- // Deduplicate (same purchase can appear as both buyer and seller if the user
- // bought their own agent's skill — extremely rare but handle cleanly)
- const seen = new Set();
- const deduped = [];
- for (const row of all) {
- const key = `${row.role}:${row.id}`;
- if (!seen.has(key)) { seen.add(key); deduped.push(row); }
- }
+ // A user who bought a skill on their own agent legitimately appears once per
+ // leg (one 'buyer' row, one 'seller' row): the two rows report different
+ // money (what they paid vs. what they netted), so both are kept and the
+ // merge above is the whole story.
const toUnits = (atomics, decimals) => {
const n = Number(atomics);
@@ -132,7 +128,7 @@ export default wrap(async (req, res) => {
return (n / 10 ** decimals).toFixed(2);
};
- const transactions = deduped.slice(0, limit).map((row) => {
+ const transactions = all.slice(0, limit).map((row) => {
const decimals = Number(row.mint_decimals ?? 6) || 6;
// 'tipped' rows settled for a different amount than the quote — report what
// actually moved on-chain, not the original ask. Everything else uses amount.
diff --git a/api/walk-og.js b/api/walk-og.js
index 809c4dd87..cebea35d3 100644
--- a/api/walk-og.js
+++ b/api/walk-og.js
@@ -13,6 +13,7 @@
import { getAvatar } from './_lib/avatars.js';
import { cors, wrap } from './_lib/http.js';
+import { fetchOgImage } from './_lib/og-avatar.js';
const CACHE = 'public, max-age=3600, s-maxage=86400';
@@ -27,14 +28,8 @@ export default wrap(async (req, res) => {
if (id) {
try {
const avatar = await getAvatar({ id });
- if (avatar?.thumbnail_url) {
- const r = await fetch(avatar.thumbnail_url, { signal: AbortSignal.timeout(6000) });
- if (r.ok) {
- const buf = await r.arrayBuffer();
- const ct = r.headers.get('content-type') || 'image/jpeg';
- thumbDataUri = `data:${ct};base64,${Buffer.from(buf).toString('base64')}`;
- }
- }
+ const img = await fetchOgImage(avatar?.thumbnail_url, { timeoutMs: 6000 });
+ if (img) thumbDataUri = `data:${img.ct};base64,${img.b64}`;
} catch {
// degrade gracefully
}
diff --git a/packages/kol-mcp/src/tools/get-wallet-portfolio.js b/packages/kol-mcp/src/tools/get-wallet-portfolio.js
index bc650ecb9..d57ac555e 100644
--- a/packages/kol-mcp/src/tools/get-wallet-portfolio.js
+++ b/packages/kol-mcp/src/tools/get-wallet-portfolio.js
@@ -25,6 +25,8 @@ export const def = {
'A null P&L field (with `pnl_source: null`) means three.ws has no trade history for ' +
'that wallet in the window, which is an honest "unknown", NOT a flat or losing record: ' +
'never report it as zero profit. `has_activity:false` means no holdings and no trades. ' +
+ 'If the holdings provider is down or rate-limited the call fails with `upstream_unavailable` ' +
+ 'rather than answering with an empty card, so an outage is never reported as a quiet wallet. ' +
'Read-only live data.',
inputSchema: {
wallet: z
@@ -36,9 +38,22 @@ export const def = {
const wallet = String(args?.wallet ?? '').trim();
const data = await apiRequest('/api/kol/wallets', { query: { addresses: wallet } });
// The proxy returns one row per requested address, and omits an address whose
- // upstream fetch failed rather than inventing a row for it.
+ // upstream fetch failed rather than inventing a row for it. A wallet with no
+ // holdings still gets a row (zeroed holdings, null P&L), so a MISSING row means
+ // the holdings provider failed, not that the wallet is quiet. Say so: shaping
+ // that gap into an all-null card would render an outage as "no activity", the
+ // exact confusion the omission upstream exists to prevent.
const rows = Array.isArray(data?.data) ? data.data : [];
- const row = rows.find((r) => r?.address === wallet) ?? rows[0] ?? {};
+ const row = rows.find((r) => r?.address === wallet);
+ if (!row) {
+ throw Object.assign(
+ new Error(
+ `three.ws returned no portfolio row for ${wallet}: the holdings provider is ` +
+ 'unavailable or rate-limited right now. That is an outage, not an empty wallet. Retry shortly.',
+ ),
+ { code: 'upstream_unavailable', status: 503 },
+ );
+ }
const holdings = row.holdings ?? 0;
const totalTrades = row.totalTrades ?? null;
diff --git a/packages/kol-mcp/test/handlers.test.mjs b/packages/kol-mcp/test/handlers.test.mjs
new file mode 100644
index 000000000..3f0a3079d
--- /dev/null
+++ b/packages/kol-mcp/test/handlers.test.mjs
@@ -0,0 +1,275 @@
+// Handler behavior for @three-ws/kol-mcp: request building, response shaping,
+// and error normalization. Global fetch is stubbed for every test, so nothing
+// here touches the network.
+//
+// Env is pinned BEFORE the dynamic imports because src/config.js reads
+// process.env at module load.
+//
+// Run: node --test packages/kol-mcp/test/handlers.test.mjs
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+process.env.THREE_WS_BASE = 'https://kol.test/';
+delete process.env.THREE_WS_TIMEOUT_MS;
+
+const { def: getWalletPortfolio } = await import('../src/tools/get-wallet-portfolio.js');
+const { def: getWalletTrades } = await import('../src/tools/get-wallet-trades.js');
+const { apiRequest } = await import('../src/lib/api.js');
+const { THREE_WS_BASE } = await import('../src/config.js');
+
+// Synthetic wallets: shaped like Solana addresses, owned by nobody.
+const WALLET = 'THREEwa11etAudit1111111111111111111111111111';
+const OTHER = 'THREEwa11etOther1111111111111111111111111111';
+// The one coin this platform promotes.
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+// Swap globalThis.fetch for the duration of fn, always restoring it.
+async function withFetch(stub, fn) {
+ const original = globalThis.fetch;
+ globalThis.fetch = stub;
+ try {
+ return await fn();
+ } finally {
+ globalThis.fetch = original;
+ }
+}
+
+function jsonResponse(body, status = 200) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'content-type': 'application/json' },
+ });
+}
+
+function recordingFetch(body, log, status = 200) {
+ return async (url, init) => {
+ log.push({ url: String(url), init });
+ return jsonResponse(body, status);
+ };
+}
+
+test('config strips trailing slashes off THREE_WS_BASE', () => {
+ assert.equal(THREE_WS_BASE, 'https://kol.test');
+});
+
+// -- get_wallet_portfolio ---------------------------------------------------
+
+test('get_wallet_portfolio asks /api/kol/wallets for exactly the requested address', async () => {
+ const log = [];
+ const body = { data: [{ address: WALLET, totalUsd: 1200.5, holdings: 3 }] };
+ await withFetch(recordingFetch(body, log), () => getWalletPortfolio.handler({ wallet: ` ${WALLET} ` }));
+ const url = new URL(log[0].url);
+ assert.equal(url.origin + url.pathname, 'https://kol.test/api/kol/wallets');
+ assert.equal(url.searchParams.get('addresses'), WALLET, 'the wallet is trimmed before it is sent');
+ assert.equal(log[0].init.method, 'GET');
+});
+
+test('get_wallet_portfolio maps the proxy row onto the documented card', async () => {
+ const body = {
+ data: [
+ {
+ address: WALLET,
+ totalUsd: 38120,
+ holdings: 14,
+ topToken: { symbol: 'THREE', valueUsd: 21500 },
+ realizedPnl: 124300,
+ winRate: 0.64,
+ totalTrades: 412,
+ volumeUsd: 2840000,
+ pnlSource: 'onchain-fifo',
+ pnlWindow: '30d',
+ },
+ ],
+ };
+ const out = await withFetch(async () => jsonResponse(body), () =>
+ getWalletPortfolio.handler({ wallet: WALLET }),
+ );
+ assert.deepEqual(out, {
+ ok: true,
+ wallet: WALLET,
+ has_activity: true,
+ portfolio_value_usd: 38120,
+ holdings: 14,
+ top_token: { symbol: 'THREE', valueUsd: 21500 },
+ realized_pnl_usd: 124300,
+ win_rate: 0.64,
+ total_trades: 412,
+ volume_usd: 2840000,
+ pnl_source: 'onchain-fifo',
+ pnl_window: '30d',
+ });
+});
+
+test('a wallet with no holdings and no trades is has_activity:false, never a fake zero P&L', async () => {
+ const body = { data: [{ address: WALLET, totalUsd: 0, holdings: 0, topToken: null, pnlWindow: '30d' }] };
+ const out = await withFetch(async () => jsonResponse(body), () =>
+ getWalletPortfolio.handler({ wallet: WALLET }),
+ );
+ assert.equal(out.has_activity, false);
+ assert.equal(out.holdings, 0);
+ for (const field of ['realized_pnl_usd', 'win_rate', 'total_trades', 'volume_usd', 'pnl_source']) {
+ assert.equal(out[field], null, `${field} is an honest unknown, not 0`);
+ }
+});
+
+test('holdings alone (no trade history) still counts as activity', async () => {
+ const body = { data: [{ address: WALLET, totalUsd: 40, holdings: 2, totalTrades: null }] };
+ const out = await withFetch(async () => jsonResponse(body), () =>
+ getWalletPortfolio.handler({ wallet: WALLET }),
+ );
+ assert.equal(out.has_activity, true);
+ assert.equal(out.total_trades, null);
+});
+
+test('a missing row is reported as an outage, not as an empty wallet', async () => {
+ // The proxy omits an address whose holdings fetch failed rather than
+ // inventing a row, so an empty `data` for a requested wallet is an outage.
+ await withFetch(async () => jsonResponse({ data: [] }), () =>
+ assert.rejects(getWalletPortfolio.handler({ wallet: WALLET }), (err) => {
+ assert.equal(err.code, 'upstream_unavailable');
+ assert.equal(err.status, 503);
+ assert.match(err.message, /not an empty wallet/);
+ return true;
+ }),
+ );
+});
+
+test("another wallet's row is never substituted for the one that was asked for", async () => {
+ await withFetch(async () => jsonResponse({ data: [{ address: OTHER, holdings: 9 }] }), () =>
+ assert.rejects(
+ getWalletPortfolio.handler({ wallet: WALLET }),
+ (err) => err.code === 'upstream_unavailable',
+ ),
+ );
+});
+
+// -- get_wallet_trades ------------------------------------------------------
+
+test('get_wallet_trades pulls the upstream max and narrows the feed to one wallet', async () => {
+ const log = [];
+ const body = {
+ mint: MINT,
+ trades: [
+ { wallet: WALLET, side: 'buy', amountSol: 4.2 },
+ { wallet: OTHER, side: 'sell', amountSol: 1 },
+ { wallet: WALLET, side: 'sell', amountSol: 2.1 },
+ ],
+ };
+ const out = await withFetch(recordingFetch(body, log), () =>
+ getWalletTrades.handler({ wallet: WALLET, mint: MINT }),
+ );
+ const url = new URL(log[0].url);
+ assert.equal(url.origin + url.pathname, 'https://kol.test/api/kol/trades');
+ assert.equal(url.searchParams.get('mint'), MINT);
+ assert.equal(url.searchParams.get('limit'), '100', 'always pulls the upstream max before narrowing');
+ assert.equal(out.count, 2);
+ assert.deepEqual(
+ out.trades.map((t) => t.side),
+ ['buy', 'sell'],
+ 'feed order is preserved, newest first',
+ );
+ assert.equal(out.wallet, WALLET);
+ assert.equal(out.mint, MINT);
+});
+
+test('get_wallet_trades clamps limit into 1-100 and applies it after filtering', async () => {
+ const trades = Array.from({ length: 30 }, (_, i) => ({ wallet: i % 2 ? OTHER : WALLET, i }));
+ for (const [limit, expected] of [
+ [3, 3],
+ [undefined, 15],
+ [500, 15],
+ [0, 15],
+ ]) {
+ const out = await withFetch(async () => jsonResponse({ trades }), () =>
+ getWalletTrades.handler({ wallet: WALLET, mint: MINT, limit }),
+ );
+ assert.equal(out.count, expected, `limit ${limit}`);
+ }
+});
+
+test('get_wallet_trades answers a wallet with no trades on that mint with an empty page', async () => {
+ const out = await withFetch(async () => jsonResponse({ trades: [{ wallet: OTHER }] }), () =>
+ getWalletTrades.handler({ wallet: WALLET, mint: MINT }),
+ );
+ assert.deepEqual(out, { ok: true, wallet: WALLET, mint: MINT, count: 0, trades: [] });
+});
+
+test('a malformed upstream body shapes into an empty page, never a crash', async () => {
+ for (const body of [{}, { trades: 'not-an-array' }, { trades: null }]) {
+ const out = await withFetch(async () => jsonResponse(body), () =>
+ getWalletTrades.handler({ wallet: WALLET, mint: MINT }),
+ );
+ assert.deepEqual(out.trades, []);
+ assert.equal(out.count, 0);
+ }
+});
+
+// -- apiRequest -------------------------------------------------------------
+
+test('apiRequest identifies itself and asks for JSON', async () => {
+ const log = [];
+ await withFetch(recordingFetch({ data: [] }, log), () => apiRequest('/api/kol/wallets'));
+ assert.equal(log[0].init.headers.accept, 'application/json');
+ assert.equal(log[0].init.headers['user-agent'], '@three-ws/kol-mcp');
+ assert.equal(log[0].init.body, undefined, 'GET carries no body');
+});
+
+test('apiRequest surfaces the platform error_description, not just the bare code', async () => {
+ // api/_lib/http.js answers { error, error_description }; the sentence is the
+ // half a caller can act on.
+ const body = {
+ error: 'provider_unavailable',
+ error_description: 'KOL trade provider unavailable: helius 429',
+ };
+ await withFetch(async () => jsonResponse(body, 502), () =>
+ assert.rejects(apiRequest('/api/kol/trades'), (err) => {
+ assert.equal(err.code, 'upstream_error');
+ assert.equal(err.status, 502);
+ assert.equal(err.message, 'KOL trade provider unavailable: helius 429');
+ assert.deepEqual(err.body, body);
+ return true;
+ }),
+ );
+});
+
+test('apiRequest falls back to a generic message when the error body is not JSON', async () => {
+ await withFetch(async () => new Response('<html>oops</html>', { status: 500 }), () =>
+ assert.rejects(apiRequest('/api/kol/wallets'), (err) => {
+ assert.equal(err.code, 'upstream_error');
+ assert.match(err.message, /returned HTTP 500/);
+ assert.deepEqual(err.body, { raw: '<html>oops</html>' });
+ return true;
+ }),
+ );
+});
+
+test('apiRequest maps a transport failure to network_error and an abort to timeout', async () => {
+ await withFetch(
+ async () => {
+ throw new TypeError('fetch failed');
+ },
+ () => assert.rejects(apiRequest('/api/kol/wallets'), (err) => err.code === 'network_error'),
+ );
+ await withFetch(
+ async () => {
+ throw Object.assign(new Error('aborted'), { name: 'AbortError' });
+ },
+ () => assert.rejects(apiRequest('/api/kol/wallets'), (err) => err.code === 'timeout'),
+ );
+});
+
+test('apiRequest skips undefined/null/empty query values but keeps zero', async () => {
+ const log = [];
+ await withFetch(recordingFetch({ data: [] }, log), () =>
+ apiRequest('/api/kol/trades', { query: { a: undefined, b: null, c: '', d: 0, e: 'x' } }),
+ );
+ const url = new URL(log[0].url);
+ assert.deepEqual(
+ [...url.searchParams.entries()],
+ [
+ ['d', '0'],
+ ['e', 'x'],
+ ],
+ );
+});
diff --git a/packages/loom-mcp/src/tools/get-creation.js b/packages/loom-mcp/src/tools/get-creation.js
index 640e0e40a..beca09f92 100644
--- a/packages/loom-mcp/src/tools/get-creation.js
+++ b/packages/loom-mcp/src/tools/get-creation.js
@@ -25,7 +25,22 @@ export const def = {
async handler(args) {
const id = String(args?.id ?? '').trim();
if (!id) throw Object.assign(new Error('id is required.'), { code: 'invalid_input', status: 400 });
- const data = await apiRequest('/api/loom', { query: { c: id } });
+ let data;
+ try {
+ data = await apiRequest('/api/loom', { query: { c: id } });
+ } catch (err) {
+ // The gallery answers an unknown id with a 404, which the HTTP layer
+ // normalizes to the generic `upstream_error`. Re-type it as the
+ // `not_found` this tool documents, so a client can branch on "no such
+ // creation" without string-matching a message.
+ if (err?.status === 404) {
+ throw Object.assign(new Error(`No Loom creation found with id "${id}".`), {
+ code: 'not_found',
+ status: 404,
+ });
+ }
+ throw err;
+ }
const creation = decorateCreation(data?.creation);
if (!creation) {
throw Object.assign(new Error(`No Loom creation found with id "${id}".`), { code: 'not_found', status: 404 });
diff --git a/packages/names/src/index.js b/packages/names/src/index.js
index b20b6bbd5..094542f89 100644
--- a/packages/names/src/index.js
+++ b/packages/names/src/index.js
@@ -40,9 +40,23 @@ export function createNames(options = {}) {
throw new ThreeWsError('resolve() needs a non-empty name.', { code: 'invalid_input' });
}
if (ETH_RE.test(trimmed)) {
- const res = await request(`/api/agents/ens/${encodeURIComponent(trimmed.toLowerCase())}`, {
- signal: opts.signal,
- });
+ const lower = trimmed.toLowerCase();
+ let res;
+ try {
+ res = await request(`/api/agents/ens/${encodeURIComponent(lower)}`, { signal: opts.signal });
+ } catch (err) {
+ // An unregistered `.eth` is a routine answer, not a fault: the ENS
+ // endpoint reports it as a 404 while the `.sol` lane reports the same
+ // miss as `resolved: false` at 200. Normalize here so one `resolve()`
+ // has one contract across both registries, and a caller never has to
+ // try/catch to ask "does this name exist".
+ if (err?.status === 404 && err?.code === 'not_found') {
+ // `raw` stays the untouched wire body, here the 404 envelope, so a
+ // caller can still see exactly what the registry said.
+ return { ...shapeEns({ name: lower }), raw: err.body ?? null };
+ }
+ throw err;
+ }
return shapeEns(res);
}
if (!SOL_NAME_RE.test(trimmed)) {
diff --git a/prompts/swarm-100/api-signals-01.md b/prompts/swarm-100/api-signals-01.md
deleted file mode 100644
index e6d805ba8..000000000
--- a/prompts/swarm-100/api-signals-01.md
+++ /dev/null
@@ -1,106 +0,0 @@
-# API audit: api/signals batch 01 (6 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/signals/_common.js
-- api/signals/feed.js
-- api/signals/feeds.js
-- api/signals/marketplace.js
-- api/signals/stream.js
-- api/signals/subscribe.js
-
-For every routed handler:
-
-1. Exercise it with curl against the local server: the success path returns
- real data with the correct status; malformed input returns a 4xx JSON
- error, never a stack trace or an HTML error page; auth is enforced where
- the code intends it; CORS matches neighboring handlers.
-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
- responses, no unfinished markers. Errors are handled at the boundary and
- internal code trusts itself.
-3. Do not spend funds or sign anything on-chain while probing. Payment and
- trading handlers get their validation and error paths exercised, never a
- live settlement.
-
-For every internal (non-routed) module:
-
-4. Something must import it; if nothing does, delete it as dead code (verify
- with a repo-wide grep first).
-5. Its main path and one failure path must be covered in tests/; add the
- missing test if not.
-
-## Definition of done
-
-- [ ] Every listed file has recorded evidence: a curl transcript for routed
- handlers, a passing test or a deletion for internal modules.
-- [ ] Zero hard-rule violations remain in these files.
-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
- exits 0.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/api-signals-01.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.