Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(api): broaden labor, launchpad, and MCP coverage with KOL and livepeer docs
nirholasee4c1ff60438
diff --git a/.trader-audit-check.mjs b/.trader-audit-check.mjsnew file mode 100644index 000000000..2c14244ae--- /dev/null+++ b/.trader-audit-check.mjs@@ -0,0 +1,13 @@+import { Pool, neonConfig } from '@neondatabase/serverless';+import ws from 'ws';+neonConfig.webSocketConstructor = ws;+neonConfig.wsProxy = () => '127.0.0.1:54490/v2';+neonConfig.useSecureWebSocket = false;+neonConfig.pipelineConnect = false;+const pool = new Pool({ connectionString: 'postgres://postgres:[email protected]:5432/main' });+const q = async (t, p) => (await pool.query(t, p)).rows;+console.log('copy_subscriptions cols:', (await q(`select column_name from information_schema.columns where table_name='copy_subscriptions' order by 1`)).map(r=>r.column_name).join(','));+console.log('agent_identities has deleted_at:', (await q(`select 1 from information_schema.columns where table_name='agent_identities' and column_name='deleted_at'`)).length === 1);+console.log('agent_identities has profile_image_url:', (await q(`select 1 from information_schema.columns where table_name='agent_identities' and column_name='profile_image_url'`)).length === 1);+console.log('copy_executions cols:', (await q(`select column_name from information_schema.columns where table_name='copy_executions' order by 1`)).map(r=>r.column_name).join(','));+await pool.end();diff --git a/.trader-audit-db.mjs b/.trader-audit-db.mjsnew file mode 100644index 000000000..032744ea3--- /dev/null+++ b/.trader-audit-db.mjs@@ -0,0 +1,42 @@+import { readFileSync } from 'node:fs';+import { Pool, neonConfig } from '@neondatabase/serverless';+import ws from 'ws';++neonConfig.webSocketConstructor = ws;+neonConfig.wsProxy = () => '127.0.0.1:54490/v2';+neonConfig.useSecureWebSocket = false;+neonConfig.pipelineConnect = false;++// Split a .sql file into top-level statements. Handles $$ ... $$ bodies and+// single-quoted strings so a semicolon inside either does not split.+function statements(text) {+ const out = [];+ let buf = '';+ let inDollar = false;+ let inQuote = false;+ let inLineComment = false;+ for (let i = 0; i < text.length; i++) {+ const c = text[i];+ const next2 = text.slice(i, i + 2);+ if (inLineComment) { buf += c; if (c === '\n') inLineComment = false; continue; }+ if (!inQuote && !inDollar && next2 === '--') { inLineComment = true; buf += c; continue; }+ if (!inQuote && next2 === '$$') { inDollar = !inDollar; buf += next2; i++; continue; }+ if (!inDollar && c === "'") { inQuote = !inQuote; buf += c; continue; }+ if (c === ';' && !inDollar && !inQuote) { out.push(buf); buf = ''; continue; }+ buf += c;+ }+ if (buf.trim()) out.push(buf);+ return out.map((s) => s.trim()).filter((s) => s && !/^(--|\/\*)/.test(s) === true || s.length > 0).filter((s) => s.replace(/--[^\n]*\n/g, '').trim().length > 0);+}++const pool = new Pool({ connectionString: 'postgres://postgres:[email protected]:5432/main' });+let ok = 0; const failures = [];+for (const f of process.argv.slice(2)) {+ for (const stmt of statements(readFileSync(f, 'utf8'))) {+ try { await pool.query(stmt); ok++; }+ catch (err) { failures.push(`${f}: ${err.message.slice(0, 120)} :: ${stmt.slice(0, 90).replace(/\s+/g, ' ')}`); }+ }+}+console.log('statements applied:', ok, 'failed:', failures.length);+for (const f of failures.slice(0, 25)) console.log(' x', f);+await pool.end();diff --git a/.trader-audit-keys.mjs b/.trader-audit-keys.mjsnew file mode 100644index 000000000..4e1c6a3bc--- /dev/null+++ b/.trader-audit-keys.mjs@@ -0,0 +1,9 @@+import { neonConfig } from '@neondatabase/serverless';+neonConfig.fetchEndpoint = 'http://127.0.0.1:54490/sql';+neonConfig.useSecureWebSocket = false;+process.env.DATABASE_URL = 'postgres://postgres:[email protected]:5432/main';+const { getTraderStats } = await import('./api/_lib/trader-stats.js');+const s = await getTraderStats({ agentId: '22222222-2222-4222-8222-222222222222', network: 'mainnet', window: 'all' });+console.log('metrics keys:', Object.keys(s.metrics).join(','));+console.log('closed[0]:', JSON.stringify(s.closed[0], null, 1));+console.log('open[0]:', JSON.stringify(s.open[0], null, 1));diff --git a/.trader-audit-run.mjs b/.trader-audit-run.mjsnew file mode 100644index 000000000..e707d0ae3--- /dev/null+++ b/.trader-audit-run.mjs@@ -0,0 +1,76 @@+// Live exercise of api/_mcp/tools/trader.js against a real Postgres 16 reached+// through the Neon HTTP driver (local-neon-http-proxy). No stubs: the handlers+// run their real SQL against the repo's real schema.+import { neonConfig } from '@neondatabase/serverless';+neonConfig.fetchEndpoint = 'http://127.0.0.1:54490/sql';+neonConfig.useSecureWebSocket = false;+process.env.DATABASE_URL = 'postgres://postgres:[email protected]:5432/main';++const { sql } = await import('./api/_lib/db.js');+const { toolDefs } = await import('./api/_mcp/tools/trader.js');+const byName = Object.fromEntries(toolDefs.map((t) => [t.name, t]));++const USER = '11111111-1111-4111-8111-111111111111';+const LEADER = '22222222-2222-4222-8222-222222222222';+const PRIVATE = '33333333-3333-4333-8333-333333333333';+const WALLET = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const LEADERW = 'THREEsynthetic1111111111111111111111111111';++await sql`delete from copy_subscriptions where copier_user_id = ${USER}`;+await sql`delete from agent_sniper_positions where agent_id in (${LEADER}, ${PRIVATE})`;+await sql`delete from agent_identities where id in (${LEADER}, ${PRIVATE})`;+await sql`delete from users where id = ${USER}`;+await sql`insert into users (id, email) values (${USER}, '[email protected]')`;+await sql`insert into agent_identities (id, user_id, name, is_public)+ values (${LEADER}, ${USER}, 'Audit Leader', true)`;+await sql`insert into agent_identities (id, user_id, name, is_public)+ values (${PRIVATE}, ${USER}, 'Private Leader', false)`;+const [strategy] = await sql`insert into agent_sniper_strategies (agent_id, user_id, network, per_trade_lamports)+ values (${LEADER}, ${USER}, 'mainnet', 100000000) returning id`;++// Two closed wins and one open position, all with real lamport columns.+const mk = (mint, pnl, closed) => sql`+ insert into agent_sniper_positions+ (strategy_id, user_id, agent_id, wallet, mint, symbol, name, network, status,+ entry_quote_lamports, exit_quote_lamports, realized_pnl_lamports, realized_pnl_pct,+ buy_sig, sell_sig, opened_at, closed_at)+ values (${strategy.id}, ${USER}, ${LEADER}, ${LEADERW}, ${mint}, 'AUD', 'Audit Coin', 'mainnet', ${closed ? 'closed' : 'open'},+ ${1_000_000_000}, ${closed ? 1_000_000_000 + pnl : null}, ${closed ? pnl : null}, ${closed ? (pnl / 1e9) * 100 : null},+ ${'buysig' + mint}, ${closed ? 'sellsig' + mint : null}, now() - interval '2 days', ${closed ? new Date().toISOString() : null})`;+await mk('THREEsynthetica111111111111111111111111111', 400_000_000, true);+await mk('THREEsyntheticb111111111111111111111111111', 250_000_000, true);+await mk('THREEsyntheticc111111111111111111111111111', 0, false);++const authed = { userId: USER, rateKey: null, scope: 'agents:read agents:write' };+const anon = { userId: null, rateKey: null, scope: '' };++const show = (label, r) => {+ const text = r.content?.[0]?.text ?? '';+ console.log(`\n### ${label} ${r.isError ? '[isError]' : '[ok]'}\n${text.slice(0, 900)}`);+};++show('trader_leaderboard (real board)', await byName.trader_leaderboard.handler({ limit: 5, window: 'all' }, anon));+show('trader_profile (real agent)', await byName.trader_profile.handler({ agent_id: LEADER, window: 'all' }, anon));+show('trader_profile (bad uuid)', await byName.trader_profile.handler({ agent_id: 'nope' }, anon));+show('trader_profile (unknown uuid)', await byName.trader_profile.handler({ agent_id: '44444444-4444-4444-8444-444444444444' }, anon));+show('trader_profile (private agent)', await byName.trader_profile.handler({ agent_id: PRIVATE }, anon));+show('copy_status (anonymous)', await byName.copy_status.handler({}, anon));+show('copy_status (empty)', await byName.copy_status.handler({}, authed));+show('copy_subscribe (bad wallet)', await byName.copy_subscribe.handler({ leader_agent_id: LEADER, copier_wallet: 'nope' }, authed));+show('copy_subscribe (bad config)', await byName.copy_subscribe.handler({ leader_agent_id: LEADER, copier_wallet: WALLET, sizing_rule: 'fixed', fixed_sol: 0, per_trade_cap_sol: 1, daily_budget_sol: 1 }, authed));+show('copy_subscribe (private leader)', await byName.copy_subscribe.handler({ leader_agent_id: PRIVATE, copier_wallet: WALLET, fixed_sol: 0.1 }, authed));+show('copy_subscribe (create)', await byName.copy_subscribe.handler({ leader_agent_id: LEADER, copier_wallet: WALLET, fixed_sol: 0.1, per_trade_cap_sol: 0.2, daily_budget_sol: 1, telegram_chat_id: '-1002233445566', perf_fee_bps: 500 }, authed));+show('copy_subscribe (update, same key)', await byName.copy_subscribe.handler({ leader_agent_id: LEADER, copier_wallet: WALLET, sizing_rule: 'multiplier', multiplier: 2, per_trade_cap_sol: 0.3, daily_budget_sol: 2 }, authed));+show('copy_status (populated)', await byName.copy_status.handler({}, authed));++const [row] = await sql`select telegram_chat_id, leader_wallet, perf_fee_bps, sizing_rule, multiplier+ from copy_subscriptions where copier_user_id = ${USER}`;+console.log('\n### persisted row:', JSON.stringify(row));++const concurrent = await Promise.all([+ byName.copy_subscribe.handler({ leader_agent_id: LEADER, copier_wallet: WALLET, fixed_sol: 0.11, per_trade_cap_sol: 0.2, daily_budget_sol: 1 }, authed),+ byName.copy_subscribe.handler({ leader_agent_id: LEADER, copier_wallet: WALLET, fixed_sol: 0.12, per_trade_cap_sol: 0.2, daily_budget_sol: 1 }, authed),+]);+console.log('\n### concurrent upserts isError flags:', concurrent.map((r) => !!r.isError));+const [count] = await sql`select count(*)::int as n from copy_subscriptions where copier_user_id = ${USER}`;+console.log('### rows after concurrent upserts:', count.n);diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 24f9fed7b..d1886f4e7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,8 +7,14 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-08-13- **A shared walk card no longer sends people to an avatar that is gone**: Sharing a walk produces a card you can post on Farcaster, with a button that opens that avatar walking. A cast stays up forever, but the avatar behind it does not: it can be deleted, or switched to private. When that happened the button still pointed at the missing avatar, so anyone who tapped it landed on a walk that could never load, and the card's second button pointed at the same place as the first, so both said the same thing. The card now checks the avatar before it builds. If the avatar is gone or private it drops the link and invites you to walk your own instead of handing you a dead button, and if the check itself cannot run the link is kept rather than thrown away. The second button now goes to the avatar builder, so the two buttons finally offer two different things. The card also carries its image dimensions now, which stops the preview from reflowing while it loads. (`/walk`) `[fix]`+- **An avatar rendered through the MCP server can no longer be turned into a tracking beacon**: When an AI assistant renders one of your avatars through the three.ws MCP server, the server builds a small viewer page and the assistant displays it. The caller picks the background for that page. The check on that value blocked anything that could break out of the styling, but it still allowed a CSS url(), so a caller could point the background at an image on a server they control and quietly collect the address and referring page of everyone who ever viewed that avatar. Backgrounds and gradients never need url(), so it is refused outright now and the safe default is used instead. A second fix went in with it: the server works out its own public web address to build the links it hands back, and its test for a local development address matched anywhere in the name instead of the whole name, so a request arriving with a forged host like evil-127.0.0.1.example.com was treated as local and got plain http links rather than https. That test is now anchored to the whole host, and IPv6 loopback is recognised properly. The animation tools also stopped treating built-in JavaScript property names as though they were real animation clips, and the shared MCP helpers behind all of this are now covered by tests. (`/docs/mcp`) `[security, fix]`- **An expired Bitcoin inscription order now says so, instead of looking like a broken server**: The Forever page writes your message into Bitcoin, then keeps a pay screen open while you send the payment from your own wallet. That screen is restored when you come back to the tab. If the inscription order behind it had since expired, the page had no way to say so: the server reported an order it could not find as a server fault, so the pay screen either sat there polling an order that no longer existed, or repainted itself empty with no charge address and no explanation. An order that no longer exists is now reported as exactly that, and the page retires it, tells you nothing was charged, and puts you back at the message box to start a new one. Three related fixes went in with it. An inscription that the provider rejected could come back marked as success, which briefly showed a pay screen for an order that was never created; every provider failure is now reported as one. A receive address with a typo is now caught by its checksum before the order is created, and tells you to recopy it from your wallet, rather than failing later with a message that explained nothing. And an order that expired unpaid is no longer counted as paid. (`/forever`) `[fix]`- **Importing an agent you already own on-chain no longer fails because its metadata host is slow**: If you registered an agent on-chain, the hydrate page finds it from your connected wallets and offers to import it into three.ws. Importing read two things: the registry entry on the chain, and the registration file the registry points at, which usually lives on IPFS. If that file did not load in five seconds, the whole import was refused, even though the part that actually matters, the chain saying you own the agent, had already answered. Public IPFS gateways throttle constantly, so owners were locked out of their own agents by a slow third party. The import now only needs the chain read to succeed; a registration file that will not load means the agent lands under its on-chain name and the metadata fills in on the next crawl. Two more changes went in alongside it: ownership is now re-checked against the live registry rather than the crawler's cached copy, so an agent you transferred away cannot be imported by the old wallet, and a chain that is unreachable now says so plainly and asks you to retry instead of reporting a generic failure. Separately, confirming a new registration now reads the transaction receipt over the same priority provider list the rest of the platform uses, instead of the slowest public fallbacks, which is what made a freshly mined registration occasionally come back as "not yet mined". (`/hydrate`) `[fix]`+- **The $THREE tile on the live heatmap shows real buy pressure again**: The 3D market heatmap on agent screens pins $THREE as its anchor tile, and that tile was meant to carry a community pulse alongside price and volume. The pulse read pump.fun's public comments feed, which pump.fun has since removed from its open API, so the tile had been quietly shipping without it: no error, just a signal that never appeared. The anchor now carries its 24h order flow instead, read from the same live market data the tile already fetches: how many of the last day's swaps were buys versus sells, as a percentage and a leaning score. Hovering the anchor shows it, and the screen's spoken market narration calls it out. Two related fixes landed with it. The wallet and coin intel endpoints now reject a malformed address with a clear error instead of answering as though the address simply had no history. And a total market-data outage now returns a proper error rather than an anchor tile with no numbers in it. `[fix, improvement]`+- **The AI safety check stays available even when someone floods it with bad requests**: Every message and every autonomous money move an avatar makes is screened by the IBM Granite Guardian safety check before it runs. That check has an hourly platform-wide ceiling so one busy hour cannot run up an unbounded inference bill. The ceiling was being charged on every request that arrived, including ones that were rejected on the spot for a malformed body and never reached the safety model at all. A single client sending junk could therefore burn the whole platform hour and leave everyone else refused for real, valid checks. The ceiling is now charged only when an actual screening runs. Two error replies were also corrected: sending the wrong content type now answers 415 and an oversized body answers 413, instead of both being reported as generic bad input, so a caller can see which of the two to fix. (`/docs/ibm`) `[fix]`+- **The extra views behind a 3D generation stop being rejected for the wrong file type**: Before a prompt becomes a 3D model, the forge draws a reference picture, then draws two more views of it so the reconstruction can see the sides and back instead of guessing them. Those extra views sent the reference picture to the image model labelled as a PNG no matter what it actually was, so a JPEG or WebP reference could be refused outright and you would quietly get fewer views and a rougher model. The real format is now read from the picture and sent with it. A reference that is unreachable, oversized, or not actually an image is now refused with a clear reason instead of being forwarded as-is and failing further down. And every image this step fetches, including the optional edit mask, now goes through the same address safety check the rest of the platform uses, so a supplied link cannot be aimed at an internal address. (`/create`) `[fix, security]`+- **The Money-Cam stops going dark when its feed stumbles, and stops replaying old transfers as new light**: The Agent Galaxy renders real money moving between agent wallets: every pulse of light is one on-chain transfer you can open in an explorer. The map loads a window of recent flows, then asks every few seconds for only the ones newer than the last it saw. If the feed query failed or ran long, the map was supposed to fall back to the last good window it had built, so it kept its picture instead of blanking. It never could: the saved copy and the small update polls shared one slot, so each poll (which by design carries almost nothing) overwrote the saved window seconds after it was written, leaving nothing to fall back to. Worse, when an update poll itself failed it was answered with that saved window, which is older than what the viewer already had, so the map rewound its place in the stream and could re-animate long-past transfers as if the money were moving right now. The saved window now belongs to the full load alone. A failed update poll returns nothing new and hands the viewer's own position straight back, so it waits for the next poll instead of travelling backwards, and a failed request for older history honestly reports that there is no more to load. Separately, a fractional page size in the address bar (?limit=1.5) made the feed query fail outright and the whole galaxy report itself as quiet while it was busy; page sizes are now rounded before they are used. (`/galaxy`) `[fix]`+- **The Rankings remix board now counts only real remixes from other creators**: The Remixes Received board on /rankings was meant to answer one question: how many other people built on top of your work. It was counting more than that. Every time you refined one of your own models the forge recorded the new version as a derivative of the old one, and the board counted it, so re-refining your own model climbed the ranking exactly like someone else remixing you would. Generations that failed partway through were counted too. Both are gone: a row only counts when it is a finished model made by a different creator, and an anonymous remix of your work still counts because that really is someone else. Ranks on that one metric will shift accordingly. Separately, the Daily Match standings endpoint now sends the cross-origin header the rest of our public read-only endpoints send, so anything reading the board from outside three.ws (dashboards, agent tooling, embeds) gets the data instead of a blocked request. (`/rankings`) `[fix, improvement]`## 2026-08-12diff --git a/api/_lib/agent-labor.js b/api/_lib/agent-labor.jsindex a6760c9be..0c148db10 100644--- a/api/_lib/agent-labor.js+++ b/api/_lib/agent-labor.js@@ -13,13 +13,14 @@ import { sql } from './db.js';import { TOKEN_MINT } from './token/config.js';import {scoreBid, reputationFromStats, defaultRoyaltyBps, settlementSplit,- atomicsToThree, threeToAtomics, toBig, SCORE_WEIGHTS, ETA_HALF_LIFE_S,+ atomicsToThree, threeToAtomics, parseAtomics, parseThree, toBig,+ SCORE_WEIGHTS, ETA_HALF_LIFE_S,} from './labor-economics.js';// Re-export the pure economics so existing call sites keep importing from here.export {scoreBid, reputationFromStats, defaultRoyaltyBps, settlementSplit,- atomicsToThree, threeToAtomics, SCORE_WEIGHTS, ETA_HALF_LIFE_S,+ atomicsToThree, threeToAtomics, parseAtomics, parseThree, SCORE_WEIGHTS, ETA_HALF_LIFE_S,};// ── Lazy schema (self-heals if the formal migration hasn't run) ─────────────@@ -113,8 +114,16 @@ export async function createBounty(input) {return row;}+// The poster's display name is joined in here rather than left to each caller:+// the detail endpoint shapes this row for the UI, and without the join every+// bounty page rendered the fallback "Agent" while the feed (which does join)+// showed the real name for the same bounty.export async function getBounty(id) {- const [row] = await sql`SELECT * FROM agent_bounties WHERE id = ${id} LIMIT 1`;+ const [row] = await sql`+ SELECT b.*, pa.name AS poster_name+ FROM agent_bounties b+ LEFT JOIN agent_identities pa ON pa.id = b.poster_agent_id+ WHERE b.id = ${id} LIMIT 1`;return row || null;}@@ -408,7 +417,15 @@ export async function getLaborPolicy(agentId) {export async function upsertLaborPolicy(agentId, userId, patch) {await ensureLaborTables();- const skills = Array.isArray(patch.skills) ? patch.skills.filter((s) => typeof s === 'string').slice(0, 40) : [];+ // Clamp each entry to the same 80 chars a bounty's required_skill is clamped+ // to, so an oversized client payload can never bloat the text[] column or+ // produce a skill string no bounty could ever match.+ const skills = Array.isArray(patch.skills)+ ? patch.skills+ .filter((s) => typeof s === 'string' && s.trim())+ .map((s) => s.trim().slice(0, 80))+ .slice(0, 40)+ : [];const [row] = await sql`INSERT INTO agent_labor_policies(agent_id, user_id, worker_enabled, skills, max_bid_atomics, min_reward_atomics,diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 97d1ba7e2..11779cd19 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -1582,10 +1582,12 @@ export const env = {return opt('X_OAUTH_CLIENT_SECRET');},- // Livepeer AI Gateway — optional. When set, /api/inference/livepeer routes- // to https://livepeer.studio/api/generate/llm with bearer auth (higher quota).- // When unset, the demo falls back to the public dream gateway at- // https://dream-gateway.livepeer.cloud/llm (no key, rate-limited).+ // Livepeer AI Gateway, optional. When set, the Livepeer lanes route to+ // https://livepeer.studio/api/generate with bearer auth. When unset they+ // resolve to the no-key public dream gateway, which api/_lib/livepeer-+ // gateway.js marks unusable (its hostname stopped serving Livepeer in+ // 2026-08; see docs/ops/livepeer-federation.md), so an unkeyed deployment+ // reports the leg unavailable rather than dialing it.get LIVEPEER_API_KEY() {return opt('LIVEPEER_API_KEY');},@@ -1594,8 +1596,9 @@ export const env = {// the text-to-image chain (api/_mcp3d/text-to-image.js) routes one GPU job// class through api/_providers/livepeer.js on the Livepeer network, behind// the LIVEPEER_FEDERATION_ENABLED flag. LIVEPEER_GATEWAY_URL overrides the- // gateway base URL (self-hosted or staging); LIVEPEER_T2I_MODEL overrides- // the default ByteDance/SDXL-Lightning pipeline.+ // gateway base URL for BOTH Livepeer lanes (self-hosted or staging), and is+ // the only way to reach a working no-key gateway today; LIVEPEER_T2I_MODEL+ // overrides the default ByteDance/SDXL-Lightning pipeline.get LIVEPEER_GATEWAY_URL() {return opt('LIVEPEER_GATEWAY_URL');},diff --git a/api/_lib/friends-store.js b/api/_lib/friends-store.jsindex d19914d36..f3191b00a 100644--- a/api/_lib/friends-store.js+++ b/api/_lib/friends-store.js@@ -45,7 +45,11 @@ export async function getPublicProfile(userId) {export async function searchUsers(meId, q, limit = 12) {const term = String(q || '').trim();if (term.length < 2) return [];- const like = `%${term.replace(/[%_]/g, (m) => `\\${m}`)}%`;+ // Escape the escape character FIRST, then the wildcards. Escaping only % and _+ // left a trailing backslash in the term free to consume the closing wildcard+ // ("qa\" became the pattern %qa\%, matching a literal "qa%"), so a name holding+ // a backslash was unsearchable and a trailing one silently changed the query.+ const like = `%${term.replace(/[\\%_]/g, (m) => `\\${m}`)}%`;const rows = await sql`select ${publicUserCols()}from users udiff --git a/api/_lib/labor-auth.js b/api/_lib/labor-auth.jsindex 60189bd5d..30985b145 100644--- a/api/_lib/labor-auth.js+++ b/api/_lib/labor-auth.js@@ -6,6 +6,7 @@ import { authenticateBearer, extractBearer, getSessionUser } from './auth.js';import { requireCsrf } from './csrf.js';import { error } from './http.js';import { sql } from './db.js';+import { isUuid } from './validate.js';/*** Authenticate a write. Returns { userId, session } or null. When it returns@@ -24,6 +25,34 @@ export async function authWrite(req, res) {return { userId, session: !!session };}+/**+ * Boundary guard for every id a labor endpoint hands to Postgres. Each of+ * agent_bounties / agent_bids / agent_jobs / agent_identities keys on a uuid+ * column, so a malformed id used to reach the database and come back as+ * SQLSTATE 22P02: an opaque 500 on the read paths, and a 400 that published the+ * raw SQLSTATE and the Postgres message on the ownership paths. Validate first+ * and answer a clean 400 that names the field.+ *+ * Writes the response and returns false when the id is bad, so the caller+ * simply `return`s; returns true when it is safe to query.+ */+export function requireUuid(res, value, field) {+ if (isUuid(value)) return true;+ error(res, 400, 'validation_error', `${field} must be a uuid`);+ return false;+}++/**+ * Narrow a thrown ownership error to a client-safe response. loadOwnedAgent and+ * requireSolanaWallet throw typed errors carrying `status`; anything else is an+ * infrastructure fault (a DB outage, a driver error) whose message must never be+ * echoed to the caller, so it is rethrown for wrap() to log and correlate.+ */+export function ownershipError(res, e) {+ if (!e?.status) throw e;+ return error(res, e.status, e.code || 'bad_request', e.message);+}+/** Load an agent and assert the caller owns it. Throws typed 404/403 errors. */export async function loadOwnedAgent(agentId, userId) {const [agent] = await sql`diff --git a/api/_lib/labor-economics.js b/api/_lib/labor-economics.jsindex 3175be076..2acb81c63 100644--- a/api/_lib/labor-economics.js+++ b/api/_lib/labor-economics.js@@ -35,6 +35,33 @@ export function threeToAtomics(three) {return BigInt(Math.round(n * Number(ATOMICS_PER_TOKEN)));}+/**+ * Strict atomic-amount parse for UNTRUSTED input (request bodies). Returns a+ * non-negative BigInt, or null when the value is not a whole number of atomics.+ * toBig() above trusts its caller (it reads numeric(40,0) columns back) and+ * throws a SyntaxError on junk, which reaches an API client as an opaque 500.+ * Every endpoint boundary parses through this instead and answers 400.+ */+export function parseAtomics(value) {+ if (typeof value === 'bigint') return value >= 0n ? value : null;+ if (typeof value === 'number') return Number.isSafeInteger(value) && value >= 0 ? BigInt(value) : null;+ if (typeof value !== 'string') return null;+ const s = value.trim();+ return /^\d+$/.test(s) ? BigInt(s) : null;+}++/**+ * Strict $THREE-denominated parse for untrusted input: returns atomics, or null+ * when the value is missing or not a finite non-negative number. Separating+ * "not a number" from zero lets the caller say which of the two went wrong.+ */+export function parseThree(value) {+ if (value === null || value === undefined || value === '') return null;+ const n = Number(typeof value === 'string' ? value.trim() : value);+ if (!Number.isFinite(n) || n < 0) return null;+ return BigInt(Math.round(n * Number(ATOMICS_PER_TOKEN)));+}+/*** Transparent award score in [0,1]. Deterministic and explainable. A bid at or* above the full reward earns no price credit; a free, instant bid from adiff --git a/api/_lib/launcher-trends.js b/api/_lib/launcher-trends.jsindex ca39ede6e..98d9d7196 100644--- a/api/_lib/launcher-trends.js+++ b/api/_lib/launcher-trends.js@@ -37,6 +37,13 @@ const AGG_CACHE_TTL_S = 180; // ranked-narrative aggregate cacheconst PROVIDER_CACHE_TTL_S = 300; // per external-provider cacheconst EXTERNAL_TIMEOUT_MS = 6_000;const MAX_TERMS = 32;+// How many ranked terms the shared aggregate cache holds. The cache key is+// limit-free and shared by every consumer (the public /api/launcher/trends feed,+// /api/launcher/me, and the launcher engine that picks the coin to mint), so the+// cached list has to cover the largest limit anyone can ask for. The public API+// caps at 50; this sits above it so a small-limit request can never truncate the+// pool the next caller reads.+const CACHED_TERMS = 64;// Source weights — internal venue signals dominate; culture sources broaden.// knowyourmeme is the single best PURE-meme external feed (entries are literally@@ -527,7 +534,7 @@ export async function rankNarratives({ network = 'mainnet', sources, categoriesif (!fresh) {try {const hit = await cacheGet(cacheKey);- if (hit) return hit;+ if (hit) return takeTerms(hit, limit);} catch { /* compute live */ }}@@ -599,7 +606,7 @@ export async function rankNarratives({ network = 'mainnet', sources, categories};}).sort((a, b) => b.score - a.score)- .slice(0, limit);+ .slice(0, CACHED_TERMS);const result = {terms: ranked,@@ -608,10 +615,22 @@ export async function rankNarratives({ network = 'mainnet', sources, categoriesproviders,};+ // Cache the full ranked pool, then hand the caller its slice. Caching the+ // slice instead would let one `?limit=1` request on the public feed starve+ // every other consumer of this key for the whole TTL.if (ranked.length) {try { await cacheSet(cacheKey, result, AGG_CACHE_TTL_S); } catch { /* ignore */ }}- return result;+ return takeTerms(result, limit);+}++// Narrow a ranked pool to the caller's limit without disturbing what is cached.+function takeTerms(result, limit) {+ const all = Array.isArray(result?.terms) ? result.terms : [];+ const n = Number.isFinite(limit) ? Math.max(0, Math.floor(limit)) : MAX_TERMS;+ if (n >= all.length) return result;+ const terms = all.slice(0, n);+ return { terms, themes: terms.map((t) => t.term), top: terms[0] || null, providers: result.providers || [] };}export { EXTERNAL_SOURCES, DEFAULT_SOURCES };diff --git a/api/_lib/mcp-error-sanitize.js b/api/_lib/mcp-error-sanitize.jsindex 4f9e91704..fbbe73397 100644--- a/api/_lib/mcp-error-sanitize.js+++ b/api/_lib/mcp-error-sanitize.js@@ -12,6 +12,7 @@// never diverge in what they leak.import { randomBytes } from 'node:crypto';+import { isDbUnavailableError, isDbCapacityError } from './db.js';// Postgres driver errors carry a `severity` and/or SQLSTATE-ish `code` plus// fields like `schema`, `table`, `column`, `routine`. Treat anything with those@@ -71,6 +72,20 @@ export function sanitizeToolError(err, { tool, server, log } = {}) {if (log && typeof log.error === 'function') log.error('tool_error', meta);else console.error(`[${server || 'mcp'}] tool_error`, meta);+ // A DB outage is transient, not a fault in the caller's request. The Neon HTTP+ // driver reports it as a plain Error whose message ("Error connecting to+ // database: fetch failed") carries no SQLSTATE and trips none of the internal+ // markers above, so it used to reach MCP callers verbatim: driver text an+ // agent cannot act on. Answer with the same designed, actionable contract the+ // REST boundary already uses (api/_lib/http.js wrap answers 503 "database+ // temporarily unavailable, retry shortly"), so an agent retries instead of+ // concluding the tool is broken. Checked BEFORE the suppression branch: a+ // capacity error carries SQLSTATE 53100 and would otherwise collapse into the+ // opaque generic message.+ if (isDbUnavailableError(err) || isDbCapacityError(err)) {+ return { message: `database temporarily unavailable, retry shortly (ref ${logId})`, logId };+ }+if (isPostgresError(err) || leaksInternalText(rawMessage)) {return { message: `internal error (ref ${logId})`, logId };}diff --git a/api/_lib/memory-store.js b/api/_lib/memory-store.jsindex 2f058ad97..f44ef972c 100644--- a/api/_lib/memory-store.js+++ b/api/_lib/memory-store.js@@ -30,6 +30,11 @@ import { extractEntities } from './memory-entities.js';export const MEMORY_TIERS = ['working', 'recall', 'archival'];+// The four kinds a memory can be. Mirrors the CHECK constraint on+// agent_memories.type, so a caller filtering by type gets a 400 at the boundary+// instead of a silently empty result set from a typo.+export const MEMORY_TYPES = ['user', 'feedback', 'project', 'reference'];+// The working core is kept small on purpose — this is what's always paged into// the model's context. ~4 chars/token is the platform's standard estimate// (matches widget knowledge chunking).diff --git a/api/_mcp-studio/persona-tools.js b/api/_mcp-studio/persona-tools.jsindex 7cf301ef1..ee2286623 100644--- a/api/_mcp-studio/persona-tools.js+++ b/api/_mcp-studio/persona-tools.js@@ -21,7 +21,7 @@ import Ajv from 'ajv';import addFormats from 'ajv-formats';import { limits, clientIp } from '../_lib/rate-limit.js';-import { assertSafePublicUrl } from '../_lib/ssrf-guard.js';+import { assertSafePublicUrl, fetchSafePublicUrlPinned } from '../_lib/ssrf-guard.js';import { isValidGlbHeader, inspectGlb } from '../_lib/glb-inspect.js';import {createPersona,@@ -35,6 +35,7 @@ import { embodimentArtifact, buildEmbedUrl } from '../_lib/embodiment-artifact.jimport { PERSONA_COMPONENT_URI } from './component.js';const MAX_GLB_BYTES = 64 * 1024 * 1024;+const GLB_FETCH_TIMEOUT_MS = 30_000;function toolError(message) {return {@@ -56,16 +57,30 @@ async function isPublicHttpsUrl(s) {// Fetch a GLB into a Buffer with a hard size cap so a persona's body can be copied// into durable storage before the provider URL expires. Returns null on any// failure (caller surfaces a clean message).+//+// Goes through the IP-pinned safe fetch, the same one the material studio uses for+// exactly this job (api/_lib/material-studio-store.js). The bare global fetch this+// used before checked the caller's URL once with assertSafePublicUrl and then let+// the network do whatever it wanted: it followed redirects with no re-validation+// (a public host answering 302 -> 169.254.169.254 walked straight through the+// guard), re-resolved DNS on connect (a rebind swaps the address after the check),+// and carried no timeout. The size cap was post-hoc too, so the whole body was+// already buffered in memory before anything measured it, which a hostile host+// turns into an OOM on an unauthenticated public endpoint. The pinned fetch closes+// all four: per-hop revalidation, a socket pinned to the checked address, an abort+// signal, and a streaming ceiling that aborts mid-body.async function fetchGlbBuffer(url) {try {- const resp = await fetch(url);+ const resp = await fetchSafePublicUrlPinned(+ url,+ { signal: AbortSignal.timeout(GLB_FETCH_TIMEOUT_MS) },+ { maxBytes: MAX_GLB_BYTES },+ );if (!resp.ok) return null;- const declared = Number(resp.headers.get('content-length') || 0);- if (declared && declared > MAX_GLB_BYTES) return null;- const buf = Buffer.from(await resp.arrayBuffer());- if (buf.length > MAX_GLB_BYTES) return null;- return buf;+ return Buffer.from(await resp.arrayBuffer());} catch {+ // Blocked target, over-cap body, timeout: all mean "cannot use this body",+ // and the caller's one message covers every case.return null;}}diff --git a/api/_mcp/tools/garments.js b/api/_mcp/tools/garments.jsindex 9865c91c5..9bb3425a1 100644--- a/api/_mcp/tools/garments.js+++ b/api/_mcp/tools/garments.js@@ -151,8 +151,16 @@ export const toolDefs = [garment_id: job.garment_id || null,error: job.error || null,};+ // A job can finish without the worker reporting coverage. `null * 100`+ // is 0, so interpolating it directly announced a measured "0.0%" bind+ // coverage, a number the pipeline never produced and one that reads as+ // a failure of the 60% gate the garment actually passed.+ const coverageText =+ pub.coverage === null+ ? 'coverage not reported'+ : `coverage ${(pub.coverage * 100).toFixed(1)}%`;const line = pub.status === 'done'- ? `Garment ${pub.garment_id} published: ${pub.glb_url} (coverage ${(pub.coverage * 100).toFixed(1)}%, occludes ${pub.occludes?.join(', ') || 'nothing'}).`+ ? `Garment ${pub.garment_id} published: ${pub.glb_url} (${coverageText}, occludes ${pub.occludes?.join(', ') || 'nothing'}).`: pub.status === 'failed'? `Garment job failed: ${pub.error}`: `Garment job ${pub.status} — stage: ${pub.stage}.`;diff --git a/api/_mcp/tools/oracle.js b/api/_mcp/tools/oracle.jsindex 3778c8e2e..468ef8d10 100644--- a/api/_mcp/tools/oracle.js+++ b/api/_mcp/tools/oracle.js@@ -67,12 +67,16 @@ function mcpErr(msg) {return { content: [{ type: 'text', text: msg }], isError: true };}+// Throws on a DB fault rather than swallowing it. Swallowing turned an outage+// into "that agent does not belong to your account": a confident, false answer+// that sends the owner off to audit permissions that were never the problem.+// The dispatcher sanitizes the throw into the transient retry message instead.async function ownsAgent(userId, agentId) {const rows = await sql`select id from agent_identitieswhere id = ${agentId} and user_id = ${userId} and deleted_at is nulllimit 1- `.catch(() => []);+ `;return rows.length > 0;}@@ -110,9 +114,17 @@ export const toolDefs = [const rl = await limits.mcpIp(auth.rateKey || 'anon');if (!rl.success) return mcpErr('Rate limit exceeded — try again in a moment.');- const items = await readFeed({- network, limit, minScore, category, sinceSeconds: 6 * 3600,- }).catch(() => []);+ // A degraded feed store is NOT an empty feed. Returning [] on a fault+ // rendered "no plays at this conviction floor, try lowering min_score",+ // which reads as a real market answer and coaches the agent into+ // loosening its filters during an outage. Say it is transient instead,+ // the way oracle_coin already does.+ let items;+ try {+ items = await readFeed({ network, limit, minScore, category, sinceSeconds: 6 * 3600 });+ } catch {+ return mcpErr('Oracle is temporarily unavailable: the feed store is degraded. Retry shortly.');+ }const plays = items.map(shapePlay);const payload = {diff --git a/api/_mcp/tools/trader.js b/api/_mcp/tools/trader.jsindex 6b7e69d9a..7b1de9988 100644--- a/api/_mcp/tools/trader.js+++ b/api/_mcp/tools/trader.js@@ -53,13 +53,40 @@ function unavailable(err, what) {const LIVE = { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true };const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };-function traderScore(r) {- if (r.score >= 75 && r.verified) return 'copy';- if (r.score >= 60 || (r.win_rate >= 60 && r.closed >= 5)) return 'watch';+// computeTraderMetrics reports win_rate as a 0-to-1 ratio (wins / closed), and+// both payloads publish it under `win_rate_pct`. Without this scaling a flawless+// 2-for-2 leader was handed to the calling agent as a "1% win rate", and the+// `watch` tier below could never fire because a ratio never reaches 60.+function winRatePct(ratio) {+ return ratio == null ? null : Math.round(ratio * 1000) / 10;+}++function recommendationFor({ score, verified, winPct, closed }) {+ if (score >= 75 && verified) return 'copy';+ if (score >= 60 || (winPct >= 60 && closed >= 5)) return 'watch';return 'skip';}+// shapeClosed() carries opened_at/closed_at, never a duration, so the hold time+// the profile advertises has to be derived from the two timestamps.+function holdSeconds(trade) {+ const opened = Date.parse(trade.opened_at ?? '');+ const closed = Date.parse(trade.closed_at ?? '');+ return Number.isFinite(opened) && Number.isFinite(closed)+ ? Math.round((closed - opened) / 1000)+ : null;+}++// Only x402 principals carry a rateKey; OAuth and API-key callers carry a userId+// instead. Falling straight through to 'anon' put every signed-in caller into one+// shared bucket with every anonymous one, so a single busy account throttled the+// whole tool for everybody.+function rateKeyFor(auth) {+ return auth?.rateKey || (auth?.userId ? `user:${auth.userId}` : 'anon');+}+function shapeLeaderboardRow(r) {+ const winPct = winRatePct(r.win_rate);return {rank: r.rank,agent_id: r.agent_id,@@ -71,7 +98,7 @@ function shapeLeaderboardRow(r) {open_positions: r.open_positions,wins: r.wins,losses: r.losses,- win_rate_pct: r.win_rate,+ win_rate_pct: winPct,realized_pnl_sol: r.realized_pnl_sol,realized_pnl_usd: r.realized_pnl_usd ?? null,roi_pct: r.roi_pct,@@ -79,7 +106,7 @@ function shapeLeaderboardRow(r) {max_drawdown_pct: r.max_drawdown_pct,copiers: r.copiers,last_active_at: r.last_active_at,- recommendation: traderScore(r),+ recommendation: recommendationFor({ score: r.score, verified: r.verified, winPct, closed: r.closed }),profile_url: `https://three.ws/trader/${r.agent_id}`,};}@@ -113,7 +140,7 @@ export const toolDefs = [const limit = Number.isFinite(asked) ? Math.min(50, Math.max(1, Math.floor(asked))) : 10;const verifiedOnly = !!args?.verified_only;- const rl = await limits.mcpIp(auth.rateKey || 'anon');+ const rl = await limits.mcpIp(rateKeyFor(auth));if (!rl.success) return mcpErr('Rate limit exceeded, try again in a moment.');let result;@@ -167,7 +194,7 @@ export const toolDefs = [const network = NETWORKS.has(args?.network) ? args.network : 'mainnet';const window = WINDOWS.has(args?.window) ? args.window : 'all';- const rl = await limits.mcpIp(auth.rateKey || 'anon');+ const rl = await limits.mcpIp(rateKeyFor(auth));if (!rl.success) return mcpErr('Rate limit exceeded, try again in a moment.');let stats;@@ -180,16 +207,25 @@ export const toolDefs = [if (!stats.agent.is_public) return mcpErr('This agent\'s track record is not public.');const m = stats.metrics;+ // Field names here must track shapeClosed() in trader-stats.js. They did+ // not: realized_pnl_sol / realized_pnl_pct / sell_solscan never existed on+ // a closed trade, so every trade in this tool's headline "verifiable track+ // record" came back with a null P&L, no Solscan proof, and an outcome of+ // 'flat' regardless of how big the win was. moonbag_held and self_dealing+ // ride along because a partial exit and a self-launched coin are exactly+ // what an agent vetting a leader must not be shown a clean number for.const topTrades = (stats.closed || []).slice(0, 10).map((t) => ({symbol: t.symbol,mint: t.mint,- outcome: t.realized_pnl_pct > 5 ? 'win' : t.realized_pnl_pct < -5 ? 'loss' : 'flat',- pnl_sol: t.realized_pnl_sol,- pnl_pct: t.realized_pnl_pct,- hold_seconds: t.hold_seconds,+ outcome: t.pnl_pct > 5 ? 'win' : t.pnl_pct < -5 ? 'loss' : 'flat',+ pnl_sol: t.pnl_sol ?? null,+ pnl_pct: t.pnl_pct ?? null,+ hold_seconds: holdSeconds(t),exit_reason: t.exit_reason,closed_at: t.closed_at,- proof_url: t.sell_solscan || t.buy_solscan || null,+ moonbag_held: t.moonbag_held === true,+ self_dealing: t.self_dealing === true,+ proof_url: t.sell_url || t.buy_url || null,}));// The tool description promises open positions; only the count was ever@@ -205,7 +241,8 @@ export const toolDefs = [proof_url: p.buy_url || null,}));- const rec = traderScore({ score: m.score, verified: m.verified, win_rate: m.win_rate, closed: m.closed_count });+ const winPct = winRatePct(m.win_rate);+ const rec = recommendationFor({ score: m.score, verified: m.verified, winPct, closed: m.closed_count });const payload = {agent_id: agentId,@@ -222,7 +259,7 @@ export const toolDefs = [open_positions: m.open_count,wins: m.wins,losses: m.losses,- win_rate_pct: m.win_rate,+ win_rate_pct: winPct,realized_pnl_sol: m.realized_pnl_sol,realized_pnl_usd: m.realized_pnl_usd ?? null,roi_pct: m.roi_pct,@@ -286,7 +323,7 @@ export const toolDefs = [const network = NETWORKS.has(args?.network) ? args.network : 'mainnet';- const rl = await limits.mcpIp(auth.rateKey || 'anon');+ const rl = await limits.mcpIp(rateKeyFor(auth));if (!rl.success) return mcpErr('Rate limit exceeded, try again in a moment.');// Validate leader exists and is public@@ -348,6 +385,13 @@ export const toolDefs = [// we still report created vs updated. copy_sells and require_safety_pass are// deliberately absent: this tool does not expose them, so an insert takes// the table defaults and an update leaves whatever the dashboard set.+ //+ // The four filter/alert columns coalesce instead of overwriting. They are+ // the only inputs with no schema default, so omitting one means "leave it+ // alone", not "clear it". Overwriting silently wiped a copier's Telegram+ // alert route and, worse, dropped the Oracle-score floor and market-cap+ // band guarding their money the moment they called this tool again to+ // change sizing. Clearing a filter stays a dashboard action.let sub;try {[sub] = await sql`@@ -375,10 +419,10 @@ export const toolDefs = [min_order_sol = excluded.min_order_sol,daily_budget_sol = excluded.daily_budget_sol,max_open_copies = excluded.max_open_copies,- min_oracle_score = excluded.min_oracle_score,- mcap_floor_usd = excluded.mcap_floor_usd,- mcap_ceiling_usd = excluded.mcap_ceiling_usd,- telegram_chat_id = excluded.telegram_chat_id,+ min_oracle_score = coalesce(excluded.min_oracle_score, copy_subscriptions.min_oracle_score),+ mcap_floor_usd = coalesce(excluded.mcap_floor_usd, copy_subscriptions.mcap_floor_usd),+ mcap_ceiling_usd = coalesce(excluded.mcap_ceiling_usd, copy_subscriptions.mcap_ceiling_usd),+ telegram_chat_id = coalesce(excluded.telegram_chat_id, copy_subscriptions.telegram_chat_id),perf_fee_bps = excluded.perf_fee_bps,status = 'active',updated_at = now()@@ -442,7 +486,7 @@ export const toolDefs = [async handler(args, auth) {if (!auth.userId) return mcpErr('Sign in to view your copy subscriptions.');- const rl = await limits.mcpIp(auth.rateKey || 'anon');+ const rl = await limits.mcpIp(rateKeyFor(auth));if (!rl.success) return mcpErr('Rate limit exceeded, try again in a moment.');const network = NETWORKS.has(args?.network) ? args.network : 'mainnet';diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.jsindex 0a906ca93..2af291ec0 100644--- a/api/_mcp3d/text-to-image.js+++ b/api/_mcp3d/text-to-image.js@@ -356,6 +356,13 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = falseconst hasSeed = Number.isInteger(seed) && seed >= 0;const token = readEnv('REPLICATE_API_TOKEN');const hasVertex = !!readEnv('GOOGLE_CLOUD_PROJECT') && vertexImagenEnabled();+ // The federated lane is resolved UP FRONT, not at its position in the ladder,+ // because every upstream lane's "is anything left to try" test has to count+ // it. Reading it late made an enabled Livepeer lane invisible to that test, so+ // a deployment where it was the only lane downstream threw the upstream error+ // instead of handing off, and the configured lane never ran.+ const { livepeerFederationEnabled, livepeerTextToImage } = await import('../_providers/livepeer.js');+ const hasLivepeer = livepeerFederationEnabled();// Quality-first ordering: the Vertex Gemini image model outdraws 4-step// distilled FLUX for photoreal reference images, and it burns the GCP credit// pool the platform is funded to spend — so when the lane is configured it@@ -367,8 +374,9 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false// What remains DOWNSTREAM of the NIM lane. When Vertex leads it has already// been consumed by the time NIM runs, so it no longer counts as a fallback —// otherwise a NIM failure after a Vertex failure would "fall through" to a- // lane that was already tried and surface the wrong terminal error.- const hasFallback = (!vertexFirst && hasVertex) || !!token;+ // lane that was already tried and surface the wrong terminal error. Livepeer+ // and Replicate both sit after NIM either way, so both always count.+ const hasFallback = (!vertexFirst && hasVertex) || hasLivepeer || !!token;// One attempt at the Vertex lane, shared by both ladder positions. Returns// null to mean "hand off to the next lane" (unconfigured, or a failure with a@@ -386,7 +394,7 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false};if (vertexFirst) {- const served = await tryVertex(!!readEnv('NVIDIA_API_KEY') || !!token);+ const served = await tryVertex(!!readEnv('NVIDIA_API_KEY') || hasLivepeer || !!token);if (served) return served;}@@ -429,8 +437,7 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false// Replicate backstop (it costs real money per image): a successful federated// call is strictly cheaper than every remaining option. Off by default; the// measured case for flipping it is in docs/ops/livepeer-federation.md.- const { livepeerFederationEnabled, livepeerTextToImage } = await import('../_providers/livepeer.js');- if (livepeerFederationEnabled()) {+ if (hasLivepeer) {try {return logImageProvider(await livepeerTextToImage(prompt, { aspectRatio, seed }));} catch (err) {diff --git a/api/_mcpagent/tools.js b/api/_mcpagent/tools.jsindex 5386c30a2..5f52c566e 100644--- a/api/_mcpagent/tools.js+++ b/api/_mcpagent/tools.js@@ -158,6 +158,12 @@ export const toolDefs = [isError: true,};}+ // Address, balances and caps are account data, so the token has to+ // carry a wallet grant. wallet:write satisfies it too: a caller+ // allowed to spend may obviously read what it is spending.+ if (!hasScope(auth.scope, 'wallet:read') && !hasScope(auth.scope, 'wallet:write')) {+ return scopeRequired('wallet:read');+ }const status = await getUserWalletStatus(auth.userId);const lines = status.provisioned? [@@ -200,7 +206,10 @@ export const toolDefs = [type: 'string',description: 'CAIP-2 network filter, e.g. "solana:*" or "eip155:8453".',},- max_price_usdc: { type: 'number', minimum: 0 },+ // Bounded: past 1e21 the atomic conversion stringifies in+ // exponential notation, which filterByMaxPrice rejects with an+ // internal TypeError. A ceiling keeps it a designed -32602.+ max_price_usdc: { type: 'number', minimum: 0, maximum: 1_000_000 },limit: { type: 'integer', minimum: 1, maximum: 50, default: 15 },},required: ['query'],@@ -294,6 +303,12 @@ export const toolDefs = [};}+ // Spending the user's USDC needs the same wallet:write grant that+ // provision_wallet requires. Checked after the degrade branch so a+ // spend-disabled server still answers with the manual pay link, and+ // before payExternalX402 so no money can move without the grant.+ if (!hasScope(auth.scope, 'wallet:write')) return scopeRequired('wallet:write');+try {const res = await payExternalX402({userId: auth.userId,@@ -400,6 +415,9 @@ export const toolDefs = [`Cluster: ${cluster}`,`Balance: ${balances.sol ?? '?'} SOL, ${balances.usdc ?? '?'} USDC`,];+ if (cluster === 'mainnet' && args.airdrop) {+ lines.push('Airdrop skipped: the faucet is devnet only.');+ }if (airdrop) {lines.push(airdrop.okdiff --git a/api/_mcpibm/tools.js b/api/_mcpibm/tools.jsindex 222b270a6..6d48bfcfd 100644--- a/api/_mcpibm/tools.js+++ b/api/_mcpibm/tools.js@@ -9,6 +9,13 @@//// The server operator supplies WATSONX_* credentials; end users pay USDC per// call via x402 (gated in api/ibm-mcp.js) and never need an IBM Cloud account.+//+// Tool `name`, `title`, and `description` must stay STATIC string literals:+// scripts/build-mcp-catalog.mjs parses this file with acorn and reads those+// fields off the AST, so a template literal lands in public/mcp-catalog.json as+// the un-evaluated source. Prices quoted in them are held to TOOL_PRICING by+// tests/api/ibm-mcp.test.js instead. Runtime-only strings (the getting-started+// payload) read their prices from pricing.js directly.import { watsonxConfig, watsonxChatComplete, watsonxEmbed } from '../_lib/watsonx.js';import { watsonxForecast } from '../_lib/watsonx-forecast.js';@@ -73,13 +80,13 @@ const deterministicAnnotations = Object.freeze({openWorldHint: true,});-// MCP tool result helper. structuredContent carries the full machine-readable-// object (the same shape the npm package returns); content[0].text is a concise-// human-readable view for clients that render text.function isPlainObject(value) {return typeof value === 'object' && value !== null && !Array.isArray(value);}+// MCP tool result helper. structuredContent carries the full machine-readable+// object (the same shape the npm package returns); content[0].text is a concise+// human-readable view for clients that render text.function toolResult(humanText, structured) {return {content: [{ type: 'text', text: humanText }],diff --git a/api/_okx3d/identity.js b/api/_okx3d/identity.jsindex 52cd7edbc..3aa511734 100644--- a/api/_okx3d/identity.js+++ b/api/_okx3d/identity.js@@ -165,7 +165,7 @@ export function fallbackIdentityPrompt({ brief, styleHints }) {// usually is not, so that branch splits on a zero-width boundary instead, or// a whole Chinese brief counts as one sentence and crowds out the hints.const raw = String(brief ?? '').trim();- const firstSentence = raw.split(/(?<=[.!?])\s+|(?<=[。!?])\s*/)[0] || raw;+ const firstSentence = raw.split(/(?<=[.!?。!?])\s+/)[0] || raw;const subject = cleanClause(clampPrompt(firstSentence, MAX_GENERATION_PROMPT_CHARS - 140 - (hints ? hints.length + 2 : 0)),);diff --git a/api/friends/index.js b/api/friends/index.jsindex addf076ae..bc8f912a5 100644--- a/api/friends/index.js+++ b/api/friends/index.js@@ -90,8 +90,13 @@ async function graphWithPresence(me) {try {graph = await listGraph(me);} catch (err) {- // Friends tables may not be migrated yet — return an empty graph rather than 500.- if (err?.message?.includes('relation') || err?.message?.includes('does not exist')) {+ // Friends tables may not be migrated yet: return an empty graph rather than+ // 500. Keyed on the Postgres undefined_table code, never on a substring of+ // the message. A missing-COLUMN error reads "column X of relation Y does not+ // exist", so message matching also swallowed a half-applied migration and+ // answered 200 with an empty graph: the caller saw "you have no friends"+ // instead of an error, and nothing surfaced the broken schema.+ if (err?.code === '42P01') {return { friends: [], incoming: [], outgoing: [] };}throw err;diff --git a/api/labor/agent.js b/api/labor/agent.jsindex addc68ded..3c77c0f46 100644--- a/api/labor/agent.js+++ b/api/labor/agent.js@@ -4,6 +4,7 @@import { cors, error, json, method, wrap } from '../_lib/http.js';import { agentLaborStats, listBountiesForAgent, getLaborPolicy } from '../_lib/agent-labor.js';+import { requireUuid } from '../_lib/labor-auth.js';import { sql } from '../_lib/db.js';export default wrap(async (req, res) => {@@ -13,6 +14,7 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://localhost');const agentId = url.searchParams.get('agentId');if (!agentId) return error(res, 400, 'validation_error', 'agentId is required');+ if (!requireUuid(res, agentId, 'agentId')) return;const [stats, posted, policy, jobs] = await Promise.all([agentLaborStats(agentId),diff --git a/api/labor/bounty.js b/api/labor/bounty.jsindex 67bdd1623..6568e3d7d 100644--- a/api/labor/bounty.js+++ b/api/labor/bounty.js@@ -4,6 +4,7 @@import { cors, error, json, method, wrap } from '../_lib/http.js';import { getBounty, listBidsForBounty, getJobByBounty, atomicsToThree, _shapeBounty as shapeBounty } from '../_lib/agent-labor.js';+import { requireUuid } from '../_lib/labor-auth.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;@@ -12,6 +13,7 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://localhost');const id = url.searchParams.get('id');if (!id) return error(res, 400, 'validation_error', 'id is required');+ if (!requireUuid(res, id, 'id')) return;const raw = await getBounty(id);if (!raw) return error(res, 404, 'not_found', 'bounty not found');diff --git a/api/labor/feed.js b/api/labor/feed.jsindex 88f2228e1..4d2cab181 100644--- a/api/labor/feed.js+++ b/api/labor/feed.js@@ -2,11 +2,11 @@// Open bounties (filterable by skill + minimum reward), in-flight jobs, the most// recent settlements (the $THREE-flow ticker), and market totals. Public read.-import { cors, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap } from '../_lib/http.js';import { TOKEN_MINT, TOKEN_DECIMALS, TOKEN_SYMBOL } from '../_lib/token/config.js';import { escrowConfigured } from '../_lib/labor-escrow.js';import {- listOpenBounties, listInflightJobs, recentSettlements, marketTotals, threeToAtomics,+ listOpenBounties, listInflightJobs, recentSettlements, marketTotals, parseThree,} from '../_lib/agent-labor.js';export default wrap(async (req, res) => {@@ -14,9 +14,15 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const url = new URL(req.url, 'http://localhost');- const skill = url.searchParams.get('skill')?.trim() || null;+ const skill = url.searchParams.get('skill')?.trim().slice(0, 80) || null;+ // A junk minReward used to parse to zero and silently drop the filter, so the+ // caller got the unfiltered feed back and had no way to know their filter was+ // ignored. Reject it instead.const minRewardThree = url.searchParams.get('minReward');- const minRewardAtomics = minRewardThree ? threeToAtomics(minRewardThree) : null;+ const minRewardAtomics = minRewardThree ? parseThree(minRewardThree) : null;+ if (minRewardThree && minRewardAtomics == null) {+ return error(res, 400, 'validation_error', 'minReward must be a non-negative number of $THREE');+ }const [open, inflight, settlements, totals] = await Promise.all([listOpenBounties({ requiredSkill: skill, minRewardAtomics, limit: 60 }),diff --git a/api/labor/policy.js b/api/labor/policy.jsindex d03007cc7..4e6f6aedc 100644--- a/api/labor/policy.js+++ b/api/labor/policy.js@@ -3,16 +3,19 @@// PUT { agentId, … } → owner-gated upsert of the worker/poster autonomy config.import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';-import { authWrite, loadOwnedAgent } from '../_lib/labor-auth.js';-import { getLaborPolicy, upsertLaborPolicy, threeToAtomics } from '../_lib/agent-labor.js';+import { authWrite, loadOwnedAgent, ownershipError, requireUuid } from '../_lib/labor-auth.js';+import { getLaborPolicy, upsertLaborPolicy, parseAtomics, parseThree } from '../_lib/agent-labor.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;- if (req.method === 'GET') {+ // HEAD is the read, not the write: without this it fell past the GET branch,+ // passed the method gate (HEAD is allowed wherever GET is), and hit authWrite.+ if (req.method === 'GET' || req.method === 'HEAD') {const url = new URL(req.url, 'http://localhost');const agentId = url.searchParams.get('agentId');if (!agentId) return error(res, 400, 'validation_error', 'agentId is required');+ if (!requireUuid(res, agentId, 'agentId')) return;const policy = await getLaborPolicy(agentId);return json(res, 200, { data: policy || { agent_id: agentId, worker_enabled: false, poster_enabled: false, skills: [] } });}@@ -26,11 +29,37 @@ export default wrap(async (req, res) => {const body = (await readJson(req)) || {};const { agentId } = body;if (!agentId) return error(res, 400, 'validation_error', 'agentId is required');+ if (!requireUuid(res, agentId, 'agentId')) return;++ // Both ceilings are optional, but a malformed one must be refused rather than+ // coerced: silently storing zero would turn "bid up to 5 $THREE" into a policy+ // that can never bid, and a policy the owner cannot see is wrong.+ const ceilings = {};+ for (const [field, three, atomics] of [+ ['maxBid', body.maxBidThree, body.maxBidAtomics],+ ['minReward', body.minRewardThree, body.minRewardAtomics],+ ]) {+ if (three == null && atomics == null) {+ ceilings[field] = null;+ continue;+ }+ const parsed = three != null ? parseThree(three) : parseAtomics(atomics);+ if (parsed == null) {+ return error(res, 400, 'validation_error', `${field}Three/${field}Atomics must be a non-negative amount`);+ }+ ceilings[field] = parsed;+ }+ if (body.minBids != null && !(Number.isInteger(Number(body.minBids)) && Number(body.minBids) >= 1)) {+ return error(res, 400, 'validation_error', 'minBids must be an integer of at least 1');+ }+ if (body.meta != null && (typeof body.meta !== 'object' || Array.isArray(body.meta))) {+ return error(res, 400, 'validation_error', 'meta must be an object');+ }try {await loadOwnedAgent(agentId, userId);} catch (e) {- return error(res, e.status || 400, e.code || 'bad_request', e.message);+ return ownershipError(res, e);}const policy = await upsertLaborPolicy(agentId, userId, {@@ -39,8 +68,8 @@ export default wrap(async (req, res) => {autoAward: !!body.autoAward,skills: Array.isArray(body.skills) ? body.skills : [],minBids: body.minBids,- maxBidAtomics: body.maxBidThree != null ? threeToAtomics(body.maxBidThree) : body.maxBidAtomics ?? null,- minRewardAtomics: body.minRewardThree != null ? threeToAtomics(body.minRewardThree) : body.minRewardAtomics ?? null,+ maxBidAtomics: ceilings.maxBid,+ minRewardAtomics: ceilings.minReward,meta: body.meta || {},});diff --git a/api/labor/tick.js b/api/labor/tick.jsindex 3375fce77..8aab92dd8 100644--- a/api/labor/tick.js+++ b/api/labor/tick.js@@ -16,7 +16,7 @@// used to consume the entire job batch and no autonomous job was ever driven// again. The scan now requires worker_enabled, mirroring the policy join the// bounty scan already had.-// • an open bounty holding fewer pending bids than its poster's min_bids,+// • an open bounty holding fewer pending bids than its poster's min_bids.// autoAwardIfReady declines it until more bids arrive, which may be never.// Award-ready bounties now sort ahead of bid-gathering ones, so a bounty// whose money is ready to move cannot be blocked behind ten that are not.diff --git a/api/launch/mm.js b/api/launch/mm.jsindex 9d7949723..0c75b58d6 100644--- a/api/launch/mm.js+++ b/api/launch/mm.js@@ -5,7 +5,8 @@// GET /api/launch/mm/:mint?stream=1 → SSE: live action feed// GET /api/launch/mm?owner=1 → the caller's policies// POST /api/launch/mm → create/update a policy (owner + CSRF)-// POST /api/launch/mm?action=pause|resume|kill|withdraw → lifecycle controls (owner + CSRF)+// POST /api/launch/mm?action=pause|resume|kill|withdraw → lifecycle controls+// on an EXISTING policy (owner + CSRF); 404s when none is attached yet// DELETE /api/launch/mm?mint=&network= → remove the policy (owner + CSRF)//// A policy can only be attached to a coin launched THROUGH three.ws (a row in@@ -30,9 +31,15 @@ const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;const SSE_PING_MS = 15_000;const SSE_POLL_MS = 3_000;const SSE_MAX_MS = 10 * 60_000;--function netOf(url) {- return url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';+// Lifecycle controls, as opposed to a create/update POST (no `action` param).+const LIFECYCLE_ACTIONS = ['pause', 'resume', 'kill', 'withdraw'];++// An explicit network in the body wins over the query string: a POST carries its+// own mint + network pair, and honouring the query there let a stale `?network=`+// silently retarget the write at the other network's policy.+function netOf(url, bodyNetwork) {+ const raw = bodyNetwork ?? url.searchParams.get('network');+ return raw === 'devnet' ? 'devnet' : 'mainnet';}// Resolve the mint from the path (/api/launch/mm/:mint), query, or body.@@ -53,16 +60,22 @@ async function resolveAuth(req) {async function handler(req, res) {if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;+ // HEAD must answer wherever GET does (RFC 9110 §9.3.2). method() normalizes a+ // HEAD probe to GET and answers 405 + Allow for anything else, so the branches+ // below only ever see GET, POST, or DELETE. Checking the method AFTER the GET+ // branch is what made a plain `curl -I` on this endpoint answer 405.+ const headProbe = req.method === 'HEAD';+ if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;+const url = new URL(req.url, `http://${req.headers.host || 'x'}`);if (req.method === 'GET') {- if (url.searchParams.get('stream') === '1') return handleStream(req, res, url);+ if (url.searchParams.get('stream') === '1') return handleStream(req, res, url, headProbe);if (url.searchParams.get('owner') === '1') return handleListOwner(req, res);return handleGet(req, res, url);}if (req.method === 'POST') return handlePost(req, res, url);- if (req.method === 'DELETE') return handleDelete(req, res, url);- return method(req, res, ['GET', 'POST', 'DELETE']) ? error(res, 405, 'method_not_allowed', 'use GET, POST, or DELETE') : undefined;+ return handleDelete(req, res, url);}// ── GET policy (+ optional live state) ────────────────────────────────────────@@ -71,6 +84,11 @@ async function handleGet(req, res, url) {const network = netOf(url);if (!mint || !MINT_RE.test(mint)) return error(res, 400, 'invalid_mint', 'a valid mint is required');+ // Public read (anyone may inspect a disclosed policy), so it carries the same+ // per-IP ceiling every other public read on this platform does.+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+const auth = await resolveAuth(req);const policy = await getPolicyByMint(mint, network);@@ -138,9 +156,14 @@ async function handlePost(req, res, url) {try { body = await readJson(req); } catch (e) { return error(res, 400, 'bad_request', e?.message || 'invalid body'); }const mint = mintFrom(url, body?.mint);- const network = body?.network === 'devnet' ? 'devnet' : netOf(url);+ const network = netOf(url, body?.network);if (!mint || !MINT_RE.test(mint)) return error(res, 400, 'invalid_mint', 'a valid mint is required');+ const action = url.searchParams.get('action') || null;+ if (action && !LIFECYCLE_ACTIONS.includes(action)) {+ return error(res, 400, 'invalid_action', `action must be one of ${LIFECYCLE_ACTIONS.join(', ')}`);+ }+// Owner-only: the coin must be one this user launched through three.ws.const launch = await resolveOwnedLaunch({ userId: auth.userId, mint, network });const existing = await getPolicyByMint(mint, network);@@ -152,7 +175,14 @@ async function handlePost(req, res, url) {const agentId = launch?.agent_id || existing?.agent_id;if (!agentId) return error(res, 409, 'no_agent', 'this launch has no agent wallet to run the market-maker from');- const action = url.searchParams.get('action');+ // A lifecycle control acts on a maker that exists. Without this, pause/kill/+ // withdraw fell through to the upsert and CREATED the very market-maker they+ // were trying to stop: a zero-floor policy the owner never configured, which+ // then rendered as a live maker on the coin's public page.+ if (action && !existing) {+ return error(res, 404, 'no_policy', 'no market-maker is attached to this coin yet; configure one before pausing, killing, or withdrawing');+ }+try {if (action === 'pause') {const row = await upsertPolicy({ mint, network, agentId, userId: auth.userId, patch: { enabled: false } });@@ -205,19 +235,35 @@ async function handleDelete(req, res, url) {}// ── SSE live action feed ──────────────────────────────────────────────────────-async function handleStream(req, res, url) {+async function handleStream(req, res, url, headProbe = false) {const mint = mintFrom(url, null);const network = netOf(url);if (!mint || !MINT_RE.test(mint)) return error(res, 400, 'invalid_mint', 'a valid mint is required');++ // Every open stream costs a DB round trip every SSE_POLL_MS for up to+ // SSE_MAX_MS, so it takes the same per-IP ceiling the platform's other public+ // SSE feeds (api/pump/trades-stream.js, api/oracle/action-stream.js) take.+ const rl = await limits.mcpIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+const policy = await getPolicyByMint(mint, network);if (!policy) return error(res, 404, 'not_found', 'no market-maker is attached to this coin');- res.writeHead(200, {+ const head = {'Content-Type': 'text/event-stream; charset=utf-8','Cache-Control': 'no-cache, no-transform',Connection: 'keep-alive','X-Accel-Buffering': 'no',- });+ };+ // A HEAD probe gets the headers a GET would send and nothing else — holding+ // the socket open for the full stream duration would answer nothing.+ if (headProbe) {+ res.writeHead(200, head);+ res.end();+ return;+ }++ res.writeHead(200, head);res.flushHeaders?.();let active = true;@@ -237,7 +283,13 @@ async function handleStream(req, res, url) {send('open', { policy_id: policy.id, mint, network, actions: [] });}- const poll = setInterval(async () => {+ // Self-rearming rather than setInterval: a tick that outlives SSE_POLL_MS (a+ // slow DB) would otherwise overlap the next one, and since lastId only+ // advances after the await, both ticks read the same rows and the client sees+ // every action twice. Re-arming after the tick finishes also stops queries+ // piling up on a database that is already struggling.+ let poll = null;+ const tick = async () => {if (!active) return;try {const rows = await listActions(policy.id, { sinceId: lastId, limit: 50, includeSkips: true });@@ -248,15 +300,17 @@ async function handleStream(req, res, url) {// Refresh policy aggregates so the UI's PnL/inventory stays live.const fresh = await getPolicyByMint(mint, network);if (fresh) send('state', toPublicPolicy(fresh));- } catch { /* transient — next tick */ }- }, SSE_POLL_MS);+ } catch { /* transient, next tick */ }+ if (active) poll = setTimeout(tick, SSE_POLL_MS);+ };+ poll = setTimeout(tick, SSE_POLL_MS);const ping = setInterval(() => send('ping', { t: Date.now() }), SSE_PING_MS);const teardown = () => {if (!active) return;active = false;- clearInterval(poll);+ clearTimeout(poll);clearInterval(ping);clearTimeout(durationTimer);try { res.end(); } catch {}diff --git a/api/launcher/me.js b/api/launcher/me.jsindex 89598d3b3..451b91084 100644--- a/api/launcher/me.js+++ b/api/launcher/me.js@@ -81,7 +81,13 @@ export default wrap(async (req, res) => {if (req.method === 'GET') return getState(res, userId, config);- const body = (await readJson(req).catch(() => ({}))) || {};+ // A JSON body that is not an object (an array, a bare string) carries no+ // patch this endpoint can honour; say so instead of writing a silent no-op+ // row. An absent body stays valid: it reads back as an empty patch.+ const body = (await readJson(req).catch(() => ({}))) ?? {};+ if (typeof body !== 'object' || Array.isArray(body)) {+ return error(res, 400, 'invalid_body', 'body must be a JSON object');+ }if (body.action === 'preview') return previewCoin(res, config, body);if (body.action === 'funding') return fundingState(res, userId, config);if (body.action === 'resume') return resumeBreaker(res, userId);@@ -296,6 +302,11 @@ async function postConfig(res, userId, cur, body) {// On-demand single-coin synthesis: shows exactly what the launcher would mint next.// User-initiated only (it can call the LLM), so never wire this onto a poll.async function previewCoin(res, config, body) {+ // Same mode contract as a config patch: an explicit bad mode is an error, not+ // a silent substitution that previews something the caller never asked for.+ if (body.mode != null && !MODES.includes(body.mode)) {+ return error(res, 400, 'invalid_mode', `mode must be one of ${MODES.join(', ')}`);+ }const mode = MODES.includes(body.mode) ? body.mode : (config?.mode || 'hybrid');const network = config?.network || 'mainnet';const coin = await pickSource({diff --git a/api/launcher/trends.js b/api/launcher/trends.jsindex aea4e65cf..4bc42fad7 100644--- a/api/launcher/trends.js+++ b/api/launcher/trends.js@@ -76,7 +76,10 @@ export default wrap(async (req, res) => {about: 'Ranked cultural narratives the autonomous launcher rides, plus three.ws launches on those waves. Themes, not ticker calls.',};- await cacheSet(cacheKey, body, TTL_S).catch(() => {});+ // Only cache a response that actually carries signal. A ranking failure or an+ // empty provider sweep must not be frozen for a minute and served to every+ // polling agent as if it were the real state of the world.+ if (terms.length) await cacheSet(cacheKey, body, TTL_S).catch(() => {});return json(res, 200, body, { 'cache-control': 'public, max-age=30, s-maxage=60' });});@@ -97,11 +100,20 @@ async function recentLaunches(network) {symbol: r.symbol,mint: r.mint,kind: r.kind,- rode: r.trigger_detail?.top_narrative || r.trigger_source || null,+ rode: topNarrative(r.trigger_detail) || r.trigger_source || null,created_at: r.created_at,}));}+// trigger_detail is jsonb; depending on the driver it arrives as an object or as+// the raw JSON string. Read both so the narrative a coin rode never silently+// degrades to the bare provider id.+function topNarrative(detail) {+ let d = detail;+ if (typeof d === 'string') { try { d = JSON.parse(d); } catch { return null; } }+ return d && typeof d === 'object' ? d.top_narrative || null : null;+}+function clampInt(v, dflt, lo, hi) {if (v == null || v === '') return dflt; // absent param → default (Number(null) is 0, not NaN)const n = Math.floor(Number(v));diff --git a/api/launchpad/get.js b/api/launchpad/get.jsindex 520b6c480..935c372a2 100644--- a/api/launchpad/get.js+++ b/api/launchpad/get.js@@ -10,7 +10,10 @@ import { cors, error, json, method, wrap } from '../_lib/http.js';const SLUG_RE = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/;export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ // Same open policy as /api/launchpad/list: this is a public read of a page+ // that is already served to anyone at /p/<slug>, with no cookies involved, so+ // an embed hosted on the creator's own domain can hydrate it too.+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;const url = new URL(req.url, 'http://x');diff --git a/api/launchpad/invoke.js b/api/launchpad/invoke.jsindex a54d90718..bc395ea74 100644--- a/api/launchpad/invoke.js+++ b/api/launchpad/invoke.js@@ -7,7 +7,7 @@// price (USDC) to the CREATOR's wallet, then receives an answer generated// on the platform's free-first LLM chain, grounded in the page's brand copy.// • gated-showroom → an x402-gated unlock. Paying the one-time pass returns-// the private scene URL plus a signed 24h grant token.+// the private scene URL, which the public read withholds.//// This is a real x402 v2 endpoint with DYNAMIC pricing and payout: the price// and the recipient (`payTo`) are read per-slug from the published page's@@ -23,7 +23,7 @@// settle on-chain → 200 with the result + X-PAYMENT-RESPONSE header.import { sql } from '../_lib/db.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';import { env } from '../_lib/env.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { llmComplete } from '../_lib/llm.js';@@ -37,12 +37,12 @@ import {verifyPayment,} from '../_lib/x402-spec.js';import { reservePaymentProof } from '../_lib/x402/payment-identifier-server.js';+import { declareHttpDiscovery } from '../_lib/x402/bazaar-helpers.js';const SLUG_RE = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/;const SOL_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;const EVM_RE = /^0x[a-fA-F0-9]{40}$/;const USDC_DECIMALS = 6;-const UNLOCK_TTL_SECONDS = 24 * 60 * 60;// Map the page's configured chain to an x402 network id + an address validator.// Only chains the facilitator can settle are accepted; an unsupported chain is@@ -86,6 +86,83 @@ function buildAccept({ chain, priceAtomics, payTo, resourceUrl }) {};}+// Discovery metadata for the 402 challenge. build402Body() otherwise falls back+// to the MCP server's default entry, which told every crawler that a launchpad+// page takes a `tools/call` body for `validate_model` — an agent that indexed a+// concierge page from that would never send the one field it actually needs.+const CONCIERGE_BAZAAR = declareHttpDiscovery({+ method: 'POST',+ bodyType: 'json',+ input: { question: 'What does this project do?' },+ inputSchema: {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['question'],+ properties: {+ question: {+ type: 'string',+ minLength: 3,+ maxLength: 2000,+ description: 'The visitor question, answered in the page owner’s voice.',+ },+ },+ },+ output: {+ example: {+ slug: 'my-page',+ action: 'ask',+ answer: 'It is a 3D agent storefront you can talk to.',+ model: 'gemini-2.5-flash',+ },+ schema: {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['slug', 'action', 'answer'],+ properties: {+ slug: { type: 'string' },+ action: { type: 'string', const: 'ask' },+ answer: { type: 'string' },+ model: { type: ['string', 'null'] },+ payer: { type: ['string', 'null'] },+ transaction: { type: ['string', 'null'] },+ network: { type: 'string' },+ },+ },+ },+});++const UNLOCK_BAZAAR = declareHttpDiscovery({+ method: 'POST',+ bodyType: 'json',+ input: {},+ inputSchema: {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {},+ description: 'No body fields — the slug in the query string selects the showroom.',+ },+ output: {+ example: {+ slug: 'my-showroom',+ action: 'unlock',+ unlockUrl: 'https://cdn.three.ws/scenes/private.glb',+ },+ schema: {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['slug', 'action', 'unlockUrl'],+ properties: {+ slug: { type: 'string' },+ action: { type: 'string', const: 'unlock' },+ unlockUrl: { type: 'string', description: 'The private scene URL, revealed on payment.' },+ payer: { type: ['string', 'null'] },+ transaction: { type: ['string', 'null'] },+ network: { type: 'string' },+ },+ },+ },+});+async function loadPage(slug) {const [row] = await sql`SELECT slug, template, owner_wallet, config@@ -133,8 +210,7 @@ function fulfillUnlock({ page }) {err.code = 'scene_missing';throw err;}- const expiresAt = Math.floor(Date.now() / 1000) + UNLOCK_TTL_SECONDS;- return { unlockUrl: sceneSrc, expiresAt };+ return { unlockUrl: sceneSrc };}export default wrap(async (req, res) => {@@ -142,7 +218,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests — slow down');+ if (!rl.success) return rateLimited(res, rl, 'too many requests — slow down');const url = new URL(req.url, 'http://x');const slug = (url.searchParams.get('slug') || '').toLowerCase();diff --git a/api/launchpad/list.js b/api/launchpad/list.jsindex a2cc17375..440185868 100644--- a/api/launchpad/list.js+++ b/api/launchpad/list.js@@ -15,6 +15,22 @@ import { cors, error, json, method, wrap } from '../_lib/http.js';const TEMPLATES = ['token-launchpad', 'paid-concierge', 'gated-showroom'];+// Deepest page a caller may ask for. Postgres takes LIMIT/OFFSET as bigints, so+// a fractional value ("limit=1.5") or one past 2^63 ("offset=1e99") makes the+// driver reject the whole query and 500 the endpoint. Clamping to a whole+// number inside a sane window keeps junk query strings a 200 with an empty page+// instead of an error, which is what a crawler walking `?offset=` deserves.+const MAX_OFFSET = 100_000;++// Coerce a query-string integer. Missing, empty, non-numeric, and 0 all take the+// default (matching the previous `Number(x) || default`); anything else is+// floored and clamped into [min, max].+function pageInt(raw, fallback, { min, max }) {+ const n = Number(raw);+ if (!Number.isFinite(n) || n === 0) return fallback;+ return Math.min(Math.max(min, Math.floor(n)), max);+}+// Map a stored page row to the public card projection the gallery renders.// Pulls a single representative image (token logo when present) and the brand// color so a card is never a blank rectangle even before the 3D avatar loads.@@ -50,8 +66,8 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const url = new URL(req.url, 'http://x');- const limit = Math.min(Math.max(1, Number(url.searchParams.get('limit')) || 24), 60);- const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0);+ const limit = pageInt(url.searchParams.get('limit'), 24, { min: 1, max: 60 });+ const offset = pageInt(url.searchParams.get('offset'), 0, { min: 0, max: MAX_OFFSET });const template = url.searchParams.get('template') || '';if (template && !TEMPLATES.includes(template)) {return error(res, 400, 'validation_error', 'unknown template filter');@@ -80,11 +96,18 @@ export default wrap(async (req, res) => {const hasMore = rows.length > limit;const pages = rows.slice(0, limit).map(toCard);- // Cheap aggregate so the hero can show a real "N pages live" stat. Counts all- // public pages; harmless if it races slightly with the list above.+ // Cheap aggregate so the hero can show a real "N pages live" stat. Counts the+ // same set the caller is paging through — an unfiltered count next to a+ // template-filtered list reads as "24 gated showrooms" when only one exists.+ // Harmless if it races slightly with the list above.let total = null;if (offset === 0) {- const [agg] = await sql`SELECT count(*)::int AS n FROM launchpad_pages WHERE is_public = true`;+ const [agg] = template+ ? await sql`+ SELECT count(*)::int AS n FROM launchpad_pages+ WHERE is_public = true AND template = ${template}+ `+ : await sql`SELECT count(*)::int AS n FROM launchpad_pages WHERE is_public = true`;total = agg?.n ?? null;}diff --git a/api/launchpad/publish.js b/api/launchpad/publish.jsindex 81dfa2985..28b16f141 100644--- a/api/launchpad/publish.js+++ b/api/launchpad/publish.js@@ -202,7 +202,10 @@ export default wrap(async (req, res) => {owner_secret_hash = COALESCE(launchpad_pages.owner_secret_hash, EXCLUDED.owner_secret_hash),user_id = COALESCE(EXCLUDED.user_id, launchpad_pages.user_id),config = EXCLUDED.config,- token_mint = EXCLUDED.token_mint,+ -- A launched mint is a permanent on-chain fact. Re-publishing from a+ -- studio draft that predates the launch must not erase it (which would+ -- also drop the page out of list.js's "already minted" sort).+ token_mint = COALESCE(EXCLUDED.token_mint, launchpad_pages.token_mint),updated_at = now()`;diff --git a/api/ledger/[agentId].js b/api/ledger/[agentId].jsindex 62e73e966..fc73d1374 100644--- a/api/ledger/[agentId].js+++ b/api/ledger/[agentId].js@@ -117,8 +117,8 @@ export default wrap(async (req, res) => {// The track record is public by design; the agent's identity is not. An// unlisted or deleted agent renders as the bare id, exactly like an id with no- // identity row, this endpoint used to select is_public and never read it, so- // it published the name and avatar of every agent its owner had made private.+ // identity row. This endpoint used to select is_public and never read it, so it+ // published the name and avatar of every agent its owner had made private.const named = !!identity && identity.is_public !== false && !identity.deleted_at;const reputation = computeReputation(repRecords);diff --git a/api/mcp3d/persona-identity.js b/api/mcp3d/persona-identity.jsindex 609a3d305..03c4a341d 100644--- a/api/mcp3d/persona-identity.js+++ b/api/mcp3d/persona-identity.js@@ -1,4 +1,4 @@-// Persona identity resolve — the live chain-state feed behind the embodiment+// Persona identity resolve: the live chain-state feed behind the embodiment// embed's visual binding (prompt 17: "the avatar IS the wallet").//// GET /api/mcp3d/persona-identity?id=persona_xxx[&network=mainnet|devnet]@@ -7,7 +7,7 @@// pages/embodiment/embed.html polls this (only when opened with ?wallet=1) so// the body's aura/cosmetic/muted-state/nameplate track LIVE chain state, not a// snapshot frozen at the MCP tool call that minted the embed URL. Same core-// read the `persona_identity` MCP tool uses (api/_lib/persona-wallet.js) — one+// read the `persona_identity` MCP tool uses (api/_lib/persona-wallet.js): one// source of truth, two front doors. Read-only, no private key ever touches// this path: getPersonaIdentity only ever derives the PUBLIC key.//@@ -19,6 +19,11 @@ import { cors, json, wrap } from '../_lib/http.js';import { isPersonaId, getPersona, personaPublicView } from '../_lib/persona-store.js';import { getPersonaIdentity } from '../_lib/persona-wallet.js';+// Short CDN window: the embed polls roughly every 20s, so a 15s shared cache+// keeps a crowded room off the RPC/attestation/Bonfida upstreams without ever+// showing a viewer state older than one poll.+const CACHE_CONTROL = 'public, s-maxage=15, stale-while-revalidate=60';+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,HEAD,OPTIONS', origins: '*' })) return;@@ -39,7 +44,8 @@ export default wrap(async (req, res) => {let record;try {record = await getPersona(id);- } catch {+ } catch (err) {+ console.warn('[mcp3d/persona-identity] persona load failed:', err?.message || err);json(res, 503, { error: 'unavailable', message: 'Could not load that persona right now. Please try again.' });return;}@@ -51,15 +57,18 @@ export default wrap(async (req, res) => {let identity;try {identity = await getPersonaIdentity(id, { network });- } catch {- // Every sub-read inside getPersonaIdentity already degrades independently- // — reaching here means the derivation itself failed (e.g. no- // PERSONA_WALLET_SECRET configured). Report that honestly, not a 500.+ } catch (err) {+ // Every sub-read inside getPersonaIdentity already degrades independently,+ // so reaching here means the derivation itself failed (e.g. no+ // PERSONA_WALLET_SECRET configured). Report that honestly, not a 500, and+ // log the cause: this branch is a config fault, and an unlogged one costs+ // an ops session to rediscover.+ console.warn('[mcp3d/persona-identity] identity derivation failed:', err?.code || err?.message || err);json(res, 503, { error: 'wallet_unavailable', message: 'This persona wallet is not available right now.' });return;}- res.setHeader('cache-control', 'public, s-maxage=15, stale-while-revalidate=60');+ res.setHeader('cache-control', CACHE_CONTROL);res.setHeader('cross-origin-resource-policy', 'cross-origin');json(res, 200, { persona: personaPublicView(record), ...identity });});diff --git a/api/mcp3d/persona.js b/api/mcp3d/persona.jsindex ffebe4415..435fb27d7 100644--- a/api/mcp3d/persona.js+++ b/api/mcp3d/persona.js@@ -1,14 +1,14 @@-// Persona resolve — the durable-reload endpoint behind the embodiment embed.+// Persona resolve: the durable-reload endpoint behind the embodiment embed.//// GET /api/mcp3d/persona?id=persona_xxx → { persona_id, name, glb_url, … }//// The embodiment embed (pages/embodiment/embed.html) calls this when it is-// opened with only a persona id (no inline glb param) so a fresh session — a new-// ChatGPT/Claude turn, a reopened panel, a shared link — reloads the exact same+// opened with only a persona id (no inline glb param) so a fresh session (a new+// ChatGPT/Claude turn, a reopened panel, a shared link) reloads the exact same// body by id. The persona id is an unguessable capability, so no auth is// required to read; the response is the safe public projection only// (personaPublicView strips storage keys + owner ids). No token, wallet, or-// payment surface — a persona is a name and a body.+// payment surface: a persona is a name and a body.//// CORS is open and the response is CDN-cacheable for a short window because the// embed is framed cross-origin by arbitrary hosts and a persona's body rarely@@ -17,6 +17,8 @@import { cors, json, wrap } from '../_lib/http.js';import { getPersona, isPersonaId, personaPublicView } from '../_lib/persona-store.js';+const CACHE_CONTROL = 'public, s-maxage=60, stale-while-revalidate=300';+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,HEAD,OPTIONS', origins: '*' })) return;@@ -38,8 +40,11 @@ export default wrap(async (req, res) => {let record;try {record = await getPersona(id);- } catch {- // A storage hiccup must not leak internals — report a clean unavailable.+ } catch (err) {+ // A storage hiccup must not leak internals to the caller, but it must not+ // vanish either: a silently swallowed cause is an undiagnosable 503 in+ // production. Log the reason, return the clean unavailable.+ console.warn('[mcp3d/persona] persona load failed:', err?.message || err);json(res, 503, { error: 'unavailable', message: 'Could not load that persona right now. Please try again.' });return;}@@ -49,9 +54,9 @@ export default wrap(async (req, res) => {return;}- // Public projection only — never the storage key or owner id. Short CDN cache:+ // Public projection only, never the storage key or owner id. Short CDN cache:// the body is durable, and the embed re-fetches on each cold load anyway.- res.setHeader('cache-control', 'public, s-maxage=60, stale-while-revalidate=300');+ res.setHeader('cache-control', CACHE_CONTROL);res.setHeader('cross-origin-resource-policy', 'cross-origin');json(res, 200, personaPublicView(record));});diff --git a/api/memory/curate.js b/api/memory/curate.jsindex 9f6927f47..ef4e44c7d 100644--- a/api/memory/curate.js+++ b/api/memory/curate.js@@ -21,6 +21,11 @@ import { sql } from '../_lib/db.js';import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';import { MEMORY_TIERS, decorateMemory } from '../_lib/memory-store.js';+import { isUuid } from '../_lib/validate.js';++// A merge folds a handful of duplicates into one target. Bounding it keeps a+// runaway caller from building a multi-megabyte `id = ANY(...)` statement.+const MERGE_MAX_IDS = 50;async function resolveAuth(req) {const session = await getSessionUser(req);@@ -42,6 +47,9 @@ export default wrap(async (req, res) => {const agentId = body.agentId || body.agent_id;const op = body.op;if (!agentId) return error(res, 400, 'validation_error', 'agentId required');+ // Every id below addresses a uuid column: reject unparseable input here rather+ // than letting Postgres raise 22P02 and turn a caller mistake into a 500.+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agentId must be a uuid');if (!op) return error(res, 400, 'validation_error', 'op required');const [agentRow] = await sql`@@ -51,6 +59,8 @@ export default wrap(async (req, res) => {if (agentRow.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');const memoryId = body.memoryId;+ if (memoryId != null && !isUuid(memoryId)) return error(res, 400, 'validation_error', 'memoryId must be a uuid');+switch (op) {case 'pin': {if (!memoryId) return error(res, 400, 'validation_error', 'memoryId required');@@ -148,15 +158,28 @@ async function handleEdit(res, agentId, body) {`;if (!row) return error(res, 404, 'not_found', 'memory not found');// Editing tags also changes the entity surface — re-mine on next graph read.+ // Stays agent-scoped like every other write here so no curation statement can+ // ever address a row outside the agent the caller was authorized for.if (hasTags) {- await sql`UPDATE agent_memories SET entities_extracted = false WHERE id = ${body.memoryId}`;+ await sql`+ UPDATE agent_memories SET entities_extracted = false+ WHERE id = ${body.memoryId} AND agent_id = ${agentId}+ `;}return json(res, 200, { entry: decorateMemory(row) });}async function handleMerge(res, agentId, body) {- const ids = Array.isArray(body.memoryIds) ? body.memoryIds.filter(Boolean) : [];- if (ids.length < 2) return error(res, 400, 'validation_error', 'merge needs at least 2 memoryIds');+ // Dedupe before counting: a caller that repeats the target ("merge a into a")+ // must not end up with the target listed among its own duplicates, which would+ // delete the row the merge just wrote.+ const ids = [...new Set(Array.isArray(body.memoryIds) ? body.memoryIds.filter(Boolean) : [])];+ const badId = ids.find((id) => !isUuid(id));+ if (badId) return error(res, 400, 'validation_error', 'memoryIds must be uuids');+ if (ids.length < 2) return error(res, 400, 'validation_error', 'merge needs at least 2 distinct memoryIds');+ if (ids.length > MERGE_MAX_IDS) {+ return error(res, 400, 'validation_error', `merge accepts at most ${MERGE_MAX_IDS} memoryIds`);+ }const [targetId, ...dupeIds] = ids;const rows = await sql`diff --git a/api/memory/search.js b/api/memory/search.jsindex d724d3878..609b96908 100644--- a/api/memory/search.js+++ b/api/memory/search.js@@ -17,7 +17,8 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.import { sql } from '../_lib/db.js';import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';-import { searchMemories } from '../_lib/memory-store.js';+import { searchMemories, MEMORY_TIERS, MEMORY_TYPES } from '../_lib/memory-store.js';+import { isUuid } from '../_lib/validate.js';async function resolveAuth(req) {const session = await getSessionUser(req);@@ -35,12 +36,16 @@ async function ownsAgent(agentId, userId) {return !!row && row.user_id === userId;}+// Accepts a comma-separated string or an array. Returns { tiers, invalid }: an+// unknown tier is reported so the caller can 400, because silently dropping it+// would filter the search down to nothing and read as "no memories".function parseTiers(raw) {- if (!raw) return null;+ if (!raw) return { tiers: null, invalid: [] };const list = (Array.isArray(raw) ? raw : String(raw).split(',')).map((s) => String(s).trim()).filter(Boolean);- return list.length ? list : null;+ const invalid = list.filter((t) => !MEMORY_TIERS.includes(t));+ return { tiers: list.length ? list : null, invalid };}export default wrap(async (req, res) => {@@ -54,14 +59,21 @@ export default wrap(async (req, res) => {const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');const query = url.searchParams.get('q') || url.searchParams.get('query') || '';if (!agentId) return error(res, 400, 'validation_error', 'agentId required');+ // agent_identities.id is a uuid column: reject unparseable input here rather+ // than letting Postgres raise 22P02 and turn a caller mistake into a 500.+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agentId must be a uuid');+ const { tiers, invalid } = parseTiers(url.searchParams.get('tier'));+ if (invalid.length) return error(res, 400, 'validation_error', `unknown tier: ${invalid.join(', ')}`);+ const type = url.searchParams.get('type') || undefined;+ if (type && !MEMORY_TYPES.includes(type)) return error(res, 400, 'validation_error', `unknown type: ${type}`);// Anonymous / non-owner → empty (no leak, no console noise on public embeds).if (!auth || !(await ownsAgent(agentId, auth.userId))) return json(res, 200, { results: [] });const out = await searchMemories(agentId, query, {topK: clampInt(url.searchParams.get('topK'), 8, 1, 50),minScore: clampFloat(url.searchParams.get('minScore'), 0.25, 0, 1),- tiers: parseTiers(url.searchParams.get('tier')),- type: url.searchParams.get('type') || undefined,+ tiers,+ type,});return json(res, 200, out);}@@ -73,13 +85,18 @@ export default wrap(async (req, res) => {const body = await readJson(req);const agentId = body.agentId || body.agent_id;if (!agentId) return error(res, 400, 'validation_error', 'agentId required');+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agentId must be a uuid');+ const { tiers, invalid } = parseTiers(body.tiers);+ if (invalid.length) return error(res, 400, 'validation_error', `unknown tier: ${invalid.join(', ')}`);+ const type = body.type || undefined;+ if (type && !MEMORY_TYPES.includes(type)) return error(res, 400, 'validation_error', `unknown type: ${type}`);if (!(await ownsAgent(agentId, auth.userId))) return error(res, 403, 'forbidden', 'not your agent');const out = await searchMemories(agentId, String(body.query || ''), {topK: clampInt(body.topK, 8, 1, 50),minScore: clampFloat(body.minScore, 0.25, 0, 1),- tiers: parseTiers(body.tiers),- type: body.type || undefined,+ tiers,+ type,});return json(res, 200, out);});diff --git a/api/mocap/[id].js b/api/mocap/[id].jsindex c00601fc6..615d3b0e5 100644--- a/api/mocap/[id].js+++ b/api/mocap/[id].js@@ -4,9 +4,18 @@import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';import { sql } from '../_lib/db.js';+import { requireCsrf } from '../_lib/csrf.js';import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';import { z } from 'zod';+// `mocap_clips.id` is a uuid column, so anything that is not a well-formed UUID+// must be rejected here rather than handed to Postgres: binding e.g. "12345678"+// raises SQLSTATE 22P02 (invalid input syntax for type uuid), which wrap() can+// only classify as an unhandled 5xx, so a caller typo answered 500 and fired a+// Sentry event plus an ops alert. Matches what gen_random_uuid() emits, in any+// hex case, without demanding a specific version/variant nibble.+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const patchSchema = z.object({name: z.string().trim().min(1).max(120).optional(),description: z.string().trim().max(2000).optional(),@@ -29,14 +38,19 @@ export default wrap(async (req, res) => {const id =req.query?.id ||new URL(req.url, 'http://x').pathname.split('/').filter(Boolean).pop();- if (!id || !/^[0-9a-f-]{8,}$/i.test(id)) {- return error(res, 400, 'invalid_request', 'id required');+ if (!id || !UUID_RE.test(id)) {+ return error(res, 400, 'invalid_request', 'id must be a clip UUID');}const auth = await resolveAuth(req);if (req.method === 'GET') return handleGet(req, res, auth, id);if (!auth) return error(res, 401, 'unauthorized', 'authentication required');+ // Cookie-session mutations need a CSRF token; bearer callers self-exempt+ // inside requireCsrf. Mirrors api/avatars/[id].js — this endpoint is+ // credentialed CORS, and the allowlist includes partner origins, so a+ // same-site cookie alone is not proof of intent.+ if (!(await requireCsrf(req, res, auth.userId))) return;if (req.method === 'PATCH') return handlePatch(req, res, auth, id);return handleDelete(req, res, auth, id);});@@ -52,7 +66,13 @@ async function handleGet(req, res, auth, id) {limit 1`;if (!row) return error(res, 404, 'not_found', 'clip not found');- const ownerView = auth?.userId === row.owner_id;+ // A bearer credential only unlocks the owner's private view when it actually+ // carries avatars:read. Without this an API key scoped to something else+ // entirely (say wallet:read) could read its owner's private clips, while the+ // list endpoint next door correctly refuses. An under-scoped bearer degrades+ // to the anonymous view so public clips still resolve for it.+ const scoped = auth?.source === 'session' || hasScope(auth?.scope, 'avatars:read');+ const ownerView = !!auth && scoped && auth.userId === row.owner_id;if (!ownerView && row.visibility === 'private') {return error(res, 404, 'not_found', 'clip not found');}diff --git a/api/mocap/clips.js b/api/mocap/clips.jsindex c6126205e..d8126ae37 100644--- a/api/mocap/clips.js+++ b/api/mocap/clips.js@@ -6,7 +6,8 @@// We store that whole object plus owner / visibility / tagging fields.import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';-import { sql } from '../_lib/db.js';+import { sql, isDbUnavailableError, isDbCapacityError } from '../_lib/db.js';+import { requireCsrf } from '../_lib/csrf.js';import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits } from '../_lib/rate-limit.js';import { z } from 'zod';@@ -23,8 +24,13 @@ const FORMAT_KIND = {'three.ws.hand-mocap.v1': 'hand','three.ws.vmc.v1': 'vmc',};-const MAX_FRAMES_INLINE = 18_000; // 30s @ 600Hz upper bound — comfortably above realistic capture+const MAX_FRAMES_INLINE = 18_000; // 30s @ 600Hz upper bound, comfortably above realistic captureconst MAX_BYTES_INLINE = 2 * 1024 * 1024; // 2 MB JSONB inline cap+// Kinds the mocap_clips CHECK constraint accepts (see+// api/_lib/migrations/2026-05-24-mocap-clips.sql). Anything outside this set can+// never match a row, so the list filter rejects it instead of silently dropping+// the condition and answering 200 with an unfiltered page.+const CLIP_KINDS = new Set(['face', 'pose', 'hand', 'composite', 'vmc']);const slugRe = /^[a-z0-9][a-z0-9-]{0,79}$/;@@ -56,6 +62,9 @@ export default wrap(async (req, res) => {}if (req.method === 'GET') return handleList(req, res, auth);+ // Cookie-session writes need a CSRF token; bearer callers self-exempt inside+ // requireCsrf. Mirrors api/avatars/[id].js.+ if (!(await requireCsrf(req, res, auth.userId))) return;return handleCreate(req, res, auth);});@@ -67,11 +76,28 @@ async function handleList(req, res, auth) {const includePublic = url.searchParams.get('include_public') === 'true';const onlyPublic = !auth;- // Build the WHERE with a positional-parameter array. The Neon serverless- // client does not interpolate nested `sql`...`` fragments inside another- // tagged template — those degrade to a bound parameter and you get- // "syntax error at or near $1". Use the same string+params pattern that- // searchPublicAvatars() in api/_lib/avatars.js uses.+ if (kindFilter && !CLIP_KINDS.has(kindFilter)) {+ return error(+ res,+ 400,+ 'invalid_request',+ `kind must be one of: ${[...CLIP_KINDS].join(', ')}`,+ );+ }+ let cursorAt = null;+ if (cursor) {+ cursorAt = decodeCursor(cursor);+ // A cursor that does not decode to a real timestamp used to reach Postgres+ // as an Invalid Date, whose toISOString() throws inside the driver and+ // answered 500. It is caller input, so it answers 400 — and never a silent+ // restart at page one, which would loop a paginating client forever.+ if (!cursorAt) return error(res, 400, 'invalid_cursor', 'cursor is malformed');+ }++ // Build the WHERE with a positional-parameter array: the condition list is+ // dynamic and every branch pushes its own bound value, so the parameter+ // numbering has to stay under this function's control. Same string+params+ // pattern searchPublicAvatars() in api/_lib/avatars.js uses.const params = [];const conds = ['deleted_at is null'];@@ -84,16 +110,13 @@ async function handleList(req, res, auth) {params.push(auth.userId);conds.push(`owner_id = $${params.length}`);}- if (kindFilter && /^[a-z]+$/.test(kindFilter)) {+ if (kindFilter) {params.push(kindFilter);conds.push(`kind = $${params.length}`);}- if (cursor) {- const decoded = decodeCursor(cursor);- if (decoded) {- params.push(decoded.createdAt);- conds.push(`created_at < $${params.length}`);- }+ if (cursorAt) {+ params.push(cursorAt);+ conds.push(`created_at < $${params.length}`);}params.push(limit + 1);@@ -111,6 +134,11 @@ async function handleList(req, res, auth) {params,);} catch (err) {+ // An outage or a full branch is infrastructure, not a bug in this query:+ // rethrow so wrap() answers the platform-standard 503 + Retry-After with its+ // throttled single alert, instead of a 500 the CDN cannot back off from and+ // that reads as a code fault. Genuine statement-level faults still 500 here.+ if (isDbUnavailableError(err) || isDbCapacityError(err)) throw err;console.error('[mocap/clips/list]', err?.code, err?.message || err);return error(res, 500, 'db_error', 'Failed to list clips');}@@ -163,7 +191,10 @@ async function handleCreate(req, res, auth) {}const kind = FORMAT_KIND[clip.format] || 'face';const frameJson = JSON.stringify(clip.frames);- if (frameJson.length > MAX_BYTES_INLINE) {+ // byteLength, not .length: a JS string counts UTF-16 code units, so a clip+ // whose blendshape keys carry non-ASCII characters would clear a .length check+ // and still blow past the byte budget the JSONB column is sized for.+ if (Buffer.byteLength(frameJson, 'utf8') > MAX_BYTES_INLINE) {return error(res,413,@@ -204,7 +235,15 @@ async function handleCreate(req, res, auth) {)returning id, slug, name, description, kind, format, duration_ms, frame_count,tags, visibility, created_at, updated_at, avatar_id- `;+ `.catch((err) => {+ // The dupCheck above is advisory: two saves racing on the same slug both+ // read "free" before either insert lands, and the loser hits the+ // (owner_id, slug) unique index. That is the same user error the 409 above+ // describes, so answer it the same way rather than 500ing the second tab.+ if (String(err?.code) === '23505') return [null];+ throw err;+ });+ if (!row) return error(res, 409, 'duplicate_slug', `slug "${slug}" already exists`);return json(res, 201, { clip: row });}@@ -232,10 +271,17 @@ function autoSlug(name) {function encodeCursor({ createdAt }) {return Buffer.from(JSON.stringify({ c: createdAt })).toString('base64url');}+// Returns the cursor's Date, or null when the token is not one we issued. The+// validity check has to cover the decoded value too, not just the base64/JSON+// decode: `new Date("not-a-date")` yields an Invalid Date that throws inside the+// driver, and `new Date(null)` yields the epoch, which quietly returns an empty+// page instead of reporting the bad token.function decodeCursor(cursor) {try {const obj = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));- return { createdAt: new Date(obj.c) };+ if (typeof obj?.c !== 'string' && typeof obj?.c !== 'number') return null;+ const at = new Date(obj.c);+ return Number.isNaN(at.getTime()) ? null : at;} catch {return null;}diff --git a/api/news/archive.js b/api/news/archive.jsindex 25864c795..9a7bf35c8 100644--- a/api/news/archive.js+++ b/api/news/archive.js@@ -1,6 +1,6 @@// GET /api/news/archive// ----------------------------------------------------------------------------// The three.ws historical crypto-news archive: 662,047 enriched articles from+// The three.ws historical crypto-news archive: 660k+ enriched articles from// September 2017 onward (CryptoPanic english corpus + Odaily chinese corpus +// the cryptocurrency.cv live archiver), recovered from the cryptocurrency.cv// archive and hosted on the platform's own GCS bucket@@ -8,9 +8,10 @@// every record carries tickers, tags, sentiment, language, and (where// captured) market context at publication time.//-// The imported corpus ends 2025-12-03; api/cron/news-archive-append.js extends-// it hourly from the live feed. Never hardcode the end date here — read-// meta/stats.json (last_article_date), which the appender keeps current.+// The corpus grows hourly (api/cron/news-archive-append.js appends the live+// feed), so never hardcode its size or end date here: meta/stats.json+// (total_articles, last_article_date) is the live count, and ?stats=true+// serves it.//// Data layout and month-file access live in api/_lib/news-archive-store.js// (shared with the story pages and the news sitemap):@@ -190,7 +191,7 @@ async function archiveSearch(parsed) {},};if (monthsRemaining > 0) {- body.hint = `scanned the newest ${scannedMonths.length} months of this range — add start_date/end_date to reach older articles`;+ body.hint = `scanned the newest ${scannedMonths.length} months of this range; add start_date/end_date to reach older articles`;}return body;} catch (err) {@@ -205,7 +206,7 @@ async function archiveSearch(parsed) {const DESCRIPTION ='Search the largest open crypto-news archive over x402: 660,000+ enriched articles back to ' +'September 2017 (english + chinese corpora, refreshed hourly), queryable by keyword, ticker, ' +- 'source, date range, sentiment, and language — every record carries tickers, tags, sentiment, ' ++ 'source, date range, sentiment, and language. Every record carries tickers, tags, sentiment, ' +'and (where captured) BTC/ETH price + Fear & Greed at publication. $0.001 USDC per search; a ' +`free daily quota (${FREE_SEARCHES_PER_DAY} searches/day per IP) lets you try it before paying. ` +'Corpus stats and trending modes are always free.';diff --git a/api/news/digest.js b/api/news/digest.jsindex 65ed21bd8..65a3fab74 100644--- a/api/news/digest.js+++ b/api/news/digest.js@@ -207,7 +207,7 @@ export default wrap(async (req, res) => {if (windowed.length < 3) {return error(res, 503, 'insufficient_coverage',- `only ${windowed.length} articles published in the last ${hours}h — try a wider window`,+ `only ${windowed.length} articles published in the last ${hours}h; try a wider window`,);}diff --git a/api/news/feed.js b/api/news/feed.jsindex f02590dcc..e9485fc6e 100644--- a/api/news/feed.js+++ b/api/news/feed.js@@ -1,7 +1,9 @@// GET /api/news/feed// ---------------------------------------------------------------------------// Live aggregated crypto news across the native source registry-// (api/_lib/news-sources.js — 38 first-party publisher feeds). Powers+// (api/_lib/news-sources.js, the single source of truth for which first-party+// publisher feeds we carry; feeds are added and retired there, so read the+// count from `meta=1` rather than any number written here). Powers// /markets/news, the /markets hub strip, and anything else that wants a real// cross-source headline feed.//diff --git a/api/news/rss.js b/api/news/rss.jsindex fc6440599..d6e934ac6 100644--- a/api/news/rss.js+++ b/api/news/rss.js@@ -41,7 +41,7 @@ export default wrap(async (req, res) => {const { articles } = await getNews({ category, limit, curated: true });const feedUrl = `https://three.ws/api/news/rss${category ? `?category=${category}` : ''}`;const pageUrl = `https://three.ws/markets/news${category ? `?category=${category}` : ''}`;- const title = `three.ws Crypto News${category ? ` — ${category}` : ''}`;+ const title = `three.ws Crypto News${category ? `: ${category}` : ''}`;const items = articles.map((a) => {@@ -64,7 +64,7 @@ export default wrap(async (req, res) => {<title>${xml(title)}</title><link>${xml(pageUrl)}</link><atom:link href="${xml(feedUrl)}" rel="self" type="application/rss+xml" />- <description>Live crypto news aggregated by three.ws from ${SOURCE_COUNT} publisher feeds${category ? ` — ${category} category` : ''}.</description>+ <description>Live crypto news aggregated by three.ws from ${SOURCE_COUNT} publisher feeds${category ? ` (${category} category)` : ''}.</description><language>en</language><lastBuildDate>${new Date().toUTCString()}</lastBuildDate><ttl>5</ttl>diff --git a/api/news/story-page.js b/api/news/story-page.jsindex 0a2ff6e28..07944ecf6 100644--- a/api/news/story-page.js+++ b/api/news/story-page.js@@ -57,14 +57,32 @@ async function loadShell() {// Replace the content="…" of every <meta> whose property/name matches `key`,// tolerating either attribute order. Values are pre-escaped by the caller.+//+// The shell's meta tags carry data-i18n-attr hooks, and src/i18n.js rewrites+// those attributes from the active catalog on load. A story's own title and+// description are not translatable shell copy, so the hook is dropped from+// every tag this fills: otherwise a non-English visitor's i18n pass would+// overwrite the story-specific og:title/description with reader boilerplate.function setMetaContent(html, key, value) {return html.replace(/<meta\b[^>]*>/g, (tag) =>new RegExp(`(?:property|name)=["']${key}["']`).test(tag)- ? tag.replace(/content=["'][^"']*["']/, () => `content="${value}"`)+ ? tag+ .replace(/content=["'][^"']*["']/, () => `content="${value}"`)+ .replace(/\s*data-i18n-attr=["'][^"']*["']/g, ''): tag,);}+// Swap the whole <title> element, attributes and all. The shell ships+// `<title data-i18n="news_article.meta_title">`, so a bare /<title>/ pattern+// matches nothing and the permalink keeps the generic reader title: the very+// tag a crawler, a SERP, and a link preview read first. Emitting a plain+// <title> also hands the tag to the server, the same ownership handoff+// src/forge.js makes when a route owns the tab title.+function setTitle(html, title) {+ return html.replace(/<title\b[^>]*>[\s\S]*?<\/title>/, () => `<title>${title}</title>`);+}+function fmtDate(iso) {const d = new Date(iso);return Number.isNaN(d.getTime())@@ -157,13 +175,13 @@ function crawlerBodyHtml(a) {export function renderStoryHtml(shell, a) {const canonical = storyPath(a);const canonicalAbs = `${ORIGIN}${canonical}`;- const description = (a.description || `${a.title} — ${a.source} coverage on the three.ws crypto news reader.`).slice(0, 300);+ const description = (a.description || `${a.title}. ${a.source} coverage on the three.ws crypto news reader.`).slice(0, 300);const ogFallback = `${ORIGIN}/api/page-og?s=crypto&t=${encodeURIComponent(a.title.slice(0, 80))}&d=${encodeURIComponent(description.slice(0, 160))}&p=${encodeURIComponent(canonical)}`;const ogImage = a.image || ogFallback;const date = fmtDate(a.pub_date);- const title = `${a.title} — ${a.source}${date ? `, ${date}` : ''} · three.ws`;+ const title = `${a.title} (${a.source}${date ? `, ${date}` : ''}) · three.ws`;- let html = shell.replace(/<title>[\s\S]*?<\/title>/, () => `<title>${esc(title)}</title>`);+ let html = setTitle(shell, esc(title));html = setMetaContent(html, 'description', esc(description));html = setMetaContent(html, 'robots', 'index, follow');html = setMetaContent(html, 'og:title', esc(a.title));@@ -228,9 +246,10 @@ function removedHtml(shell, sup) {<p><a class="arc-btn" href="/markets/news">Latest crypto news</a><a class="arc-btn ghost" href="/markets/archive">Search the archive</a></p></div>`;- let html = shell- .replace(/<title>[\s\S]*?<\/title>/, () => `<title>Story removed · Crypto News · three.ws</title>`)- .replace(/<article id="art-root"[^>]*>[\s\S]*?<\/article>/, () => `<article id="art-root">${body}</article>`);+ let html = setTitle(shell, 'Story removed · Crypto News · three.ws').replace(+ /<article id="art-root"[^>]*>[\s\S]*?<\/article>/,+ () => `<article id="art-root">${body}</article>`,+ );// noindex is load-bearing here: this page must not be re-indexed under any// circumstance, including if a crawler ignores the 410.html = setMetaContent(html, 'robots', 'noindex, nofollow');@@ -250,9 +269,10 @@ function notFoundHtml(shell, month, slug) {<p><a class="arc-btn" href="${esc(searchHref)}">${q ? `Search the archive for “${esc(q)}”` : 'Search the 660k-article archive'}</a><a class="arc-btn ghost" href="/markets/news">Latest crypto news</a></p></div>`;- return shell- .replace(/<title>[\s\S]*?<\/title>/, () => `<title>Story not found · Crypto News · three.ws</title>`)- .replace(/<article id="art-root"[^>]*>[\s\S]*?<\/article>/, () => `<article id="art-root">${body}</article>`);+ return setTitle(shell, 'Story not found · Crypto News · three.ws').replace(+ /<article id="art-root"[^>]*>[\s\S]*?<\/article>/,+ () => `<article id="art-root">${body}</article>`,+ );}export default wrap(async (req, res) => {diff --git a/api/nft/mint-scene-confirm.js b/api/nft/mint-scene-confirm.jsindex 5d87fa582..41e81b583 100644--- a/api/nft/mint-scene-confirm.js+++ b/api/nft/mint-scene-confirm.js@@ -1,32 +1,49 @@import { env } from '../_lib/env.js';import { wrap, cors, error, json, readJson, method, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { solanaConnection } from '../_lib/solana/connection.js';import { confirmOrThrow } from '../_lib/solana/confirm.js';+// Base64 with no stray characters. Buffer.from(x, 'base64') never throws — it+// drops anything outside the alphabet — so the only way to reject a malformed+// payload up front is to check it before decoding.+const BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;+export default wrap(async (req, res) => {- if (cors(req, res)) return;+ // Mirrors /api/nft/mint-scene: the chat client posts here with+ // credentials:'include', so the preflight has to allow credentials or a+ // cross-origin embed loses the session cookie on the second leg of the flow.+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);+ // This broadcasts through the platform's own paid Solana RPC. /api/nft/mint-scene+ // already gates the first leg on a session or bearer token, so requiring the+ // same here costs a legitimate minter nothing and stops the endpoint doubling+ // as an open relay for arbitrary signed transactions.+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) {+ return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');+ }+const body = await readJson(req);const { signedTxBase64 } = body || {};if (!signedTxBase64 || typeof signedTxBase64 !== 'string')return error(res, 400, 'validation_error', 'signedTxBase64 required');+ const compact = signedTxBase64.replace(/\s+/g, '');+ if (!compact || compact.length % 4 !== 0 || !BASE64_RE.test(compact))+ return error(res, 400, 'validation_error', 'signedTxBase64 is not valid base64');+ const txBytes = Buffer.from(compact, 'base64');+const rpcUrl = env.SOLANA_RPC_URL;const connection = solanaConnection({ url: rpcUrl, commitment: 'confirmed' });- let txBytes;- try {- txBytes = Buffer.from(signedTxBase64, 'base64');- } catch {- return error(res, 400, 'validation_error', 'signedTxBase64 is not valid base64');- }-let signature;try {signature = await connection.sendRawTransaction(txBytes, {diff --git a/api/nft/mint-scene.js b/api/nft/mint-scene.jsindex 268a23a43..c7388bdef 100644--- a/api/nft/mint-scene.js+++ b/api/nft/mint-scene.js@@ -32,6 +32,19 @@ async function uploadToNftStorage(token, bytes, contentType) {return `ipfs://${data.value.cid}`;}+// Strict base64: the scene GLB and its thumbnail arrive base64-encoded, and+// Buffer.from(x, 'base64') never throws — it silently drops every character+// outside the alphabet. A truncated or accidentally-URL-encoded upload therefore+// used to sail through as a shorter, corrupt buffer that we then pinned to IPFS+// on the platform's own storage token and referenced from a real mint.+const BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;++function decodeBase64(value) {+ const compact = value.replace(/\s+/g, '');+ if (!compact || compact.length % 4 !== 0 || !BASE64_RE.test(compact)) return null;+ return Buffer.from(compact, 'base64');+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;@@ -50,7 +63,11 @@ export default wrap(async (req, res) => {return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');}- const body = await readJson(req);+ // A scene GLB plus its PNG thumbnail, base64-inflated by 4/3, comfortably+ // clears readJson's 1 MB default — which rejected every real mint with a 413+ // before the handler saw a byte. 8 MB matches server/index.mjs BODY_LIMIT, the+ // ceiling express enforces ahead of us anyway.+ const body = await readJson(req, 8 * 1024 * 1024);const { ownerPubkey, glbBase64, thumbnailBase64, name, description } = body || {};if (!ownerPubkey || typeof ownerPubkey !== 'string')@@ -62,11 +79,29 @@ export default wrap(async (req, res) => {if (!name || typeof name !== 'string' || !name.trim())return error(res, 400, 'validation_error', 'name required');+ const glbBytes = decodeBase64(glbBase64);+ if (!glbBytes) return error(res, 400, 'validation_error', 'glbBase64 is not valid base64');+ const thumbBytes = decodeBase64(thumbnailBase64);+ if (!thumbBytes) return error(res, 400, 'validation_error', 'thumbnailBase64 is not valid base64');++ // Resolve the owner key BEFORE anything is pinned. It used to be parsed only+ // after all three IPFS uploads, so a typo'd pubkey burned three writes on the+ // platform's storage token and then answered 400 anyway.+ const rpcUrl = env.SOLANA_RPC_URL;+ const umi = createUmi(solanaConnection({ url: rpcUrl })).use(mplCore());++ let ownerPk;+ try {+ ownerPk = umiPublicKey(ownerPubkey);+ } catch {+ return error(res, 400, 'validation_error', 'invalid ownerPubkey');+ }+let glbUri, thumbUri;try {[glbUri, thumbUri] = await Promise.all([- uploadToNftStorage(storageToken, Buffer.from(glbBase64, 'base64'), 'model/gltf-binary'),- uploadToNftStorage(storageToken, Buffer.from(thumbnailBase64, 'base64'), 'image/png'),+ uploadToNftStorage(storageToken, glbBytes, 'model/gltf-binary'),+ uploadToNftStorage(storageToken, thumbBytes, 'image/png'),]);} catch (e) {console.error('[nft/mint-scene] asset upload failed', e?.message);@@ -99,19 +134,10 @@ export default wrap(async (req, res) => {return respondError(res, e.status || 502, e.code || 'upstream_error', e);}- // Failover Connection rather than a bare URL: the mint's getLatestBlockhash and- // account reads rotate across the endpoint chain, so a single node's- // malformed/empty 200 body fails over instead of throwing the StructError crash.- const rpcUrl = env.SOLANA_RPC_URL;- const umi = createUmi(solanaConnection({ url: rpcUrl })).use(mplCore());-- let ownerPk;- try {- ownerPk = umiPublicKey(ownerPubkey);- } catch {- return error(res, 400, 'validation_error', 'invalid ownerPubkey');- }-+ // The umi instance above uses the failover Connection rather than a bare URL:+ // the mint's getLatestBlockhash and account reads rotate across the endpoint+ // chain, so a single node's malformed/empty 200 body fails over instead of+ // throwing the StructError crash.umi.use(signerIdentity(createNoopSigner(ownerPk)));const assetSigner = generateSigner(umi);@@ -122,8 +148,15 @@ export default wrap(async (req, res) => {uri: metadataUri,});- const txBytes = await builder.buildAndSign(umi);- const unsignedTxBase64 = Buffer.from(txBytes).toString('base64');+ // buildAndSign resolves to a umi Transaction object ({message, signatures,+ // serializedMessage}), NOT wire bytes. Handing that straight to Buffer.from+ // threw "The first argument must be of type string or an instance of Buffer,+ // ArrayBuffer, or Array" on every otherwise-successful mint, after the three+ // IPFS uploads had already been paid for. umi.transactions.serialize is the+ // wire encoder, and is what the sibling mint paths+ // (api/agents/onchain/[action].js, api/agents/solana/_handlers.js) use.+ const tx = await builder.buildAndSign(umi);+ const unsignedTxBase64 = Buffer.from(umi.transactions.serialize(tx)).toString('base64');const mint = assetSigner.publicKey.toString();return json(res, 200, { unsignedTxBase64, metadataUri, mint });diff --git a/api/nft/resolve.js b/api/nft/resolve.jsindex df4b881e1..d2d6c8d3e 100644--- a/api/nft/resolve.js+++ b/api/nft/resolve.js@@ -14,6 +14,30 @@ const RESOLVE_TTL_SECONDS = 6 * 60 * 60; // 6h// descriptor during a Helius/Alchemy outage is correct — far better than a 502.const RESOLVE_STALE_TTL_SECONDS = 30 * 24 * 60 * 60; // 30d+// Alchemy NFT API host per EVM chainId. An id of the form+// "chainId:contract:tokenId" (exactly what api/users/[username]/collectibles.js+// emits for every EVM collectible) used to have its chainId parsed and then+// thrown away, so a Base or Polygon NFT was always looked up on Ethereum+// mainnet and came back as a 404 or, worse, as an unrelated Ethereum token that+// happens to share the contract/tokenId pair. Keep this list aligned with the+// hosts in api/_lib/evm/rpc.js ALCHEMY_SUBDOMAIN.+const ALCHEMY_NFT_HOST = {+ 1: 'eth-mainnet',+ 10: 'opt-mainnet',+ 56: 'bnb-mainnet',+ 137: 'polygon-mainnet',+ 324: 'zksync-mainnet',+ 8453: 'base-mainnet',+ 42161: 'arb-mainnet',+ 43114: 'avax-mainnet',+ 59144: 'linea-mainnet',+ 534352: 'scroll-mainnet',+ 84532: 'base-sepolia',+ 421614: 'arb-sepolia',+ 11155111: 'eth-sepolia',+ 11155420: 'opt-sepolia',+};+export default wrap(async (req, res) => {if (cors(req, res)) return;if (!method(req, res, ['POST'])) return;@@ -21,7 +45,10 @@ export default wrap(async (req, res) => {const rl = await limits.authedReadIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const body = await readJson(req);+ // A bare `null` JSON body parses to null, and reading `.chain` off it threw a+ // TypeError that surfaced as an opaque 500 instead of the 400 every other+ // malformed body gets.+ const body = (await readJson(req)) || {};const chain = String(body.chain || '').toLowerCase();const id = String(body.id || '').trim();@@ -102,19 +129,34 @@ export default wrap(async (req, res) => {return json(res, 200, result);}- // EVM: id is "contract:tokenId" or "chainId:contract:tokenId"+ // EVM: id is "contract:tokenId" (Ethereum mainnet) or "chainId:contract:tokenId"const parts = id.split(':');- let contractAddress, tokenId;+ let contractAddress, tokenId, chainId;if (parts.length === 2) {[contractAddress, tokenId] = parts;+ chainId = 1;} else if (parts.length === 3) {[, contractAddress, tokenId] = parts;+ chainId = Number(parts[0]);} else {return error(res, 400, 'bad_request', 'evm id must be "contract:tokenId" or "chainId:contract:tokenId"');}- const apiKey = env.ALCHEMY_API_KEY;- const url = `https://eth-mainnet.g.alchemy.com/nft/v3/${apiKey}/getNFTMetadata?contractAddress=${encodeURIComponent(contractAddress)}&tokenId=${encodeURIComponent(tokenId)}`;+ const host = ALCHEMY_NFT_HOST[chainId];+ if (!host) {+ return error(res, 400, 'bad_request', `unsupported evm chainId ${parts[0]}`);+ }++ // `env` exposes no ALCHEMY getter, so the previous `env.ALCHEMY_API_KEY` read+ // was undefined in every environment: the whole EVM branch built a URL with a+ // literal "undefined" key and answered 502 on a 401 from Alchemy, configured+ // or not. Read the raw var (the same way collectibles.js, balances.js and+ // scene/gate-check.js do) and say plainly when it is missing.+ const apiKey = process.env.ALCHEMY_API_KEY;+ if (!apiKey) {+ return error(res, 503, 'not_configured', 'ALCHEMY_API_KEY not configured — evm nft resolution is unavailable');+ }+ const url = `https://${host}.g.alchemy.com/nft/v3/${apiKey}/getNFTMetadata?contractAddress=${encodeURIComponent(contractAddress)}&tokenId=${encodeURIComponent(tokenId)}`;let resp;try {resp = await fetch(url);diff --git a/api/oauth/[action].js b/api/oauth/[action].jsindex 3fb547a3a..c011cc0d9 100644--- a/api/oauth/[action].js+++ b/api/oauth/[action].js@@ -58,6 +58,13 @@ function canonicalResource(requested) {const REGISTERABLE_SCOPES = new Set(['avatars:read', 'avatars:write', 'avatars:delete', 'profile','memory:read', 'memory:write', 'agents:read', 'agents:write', 'offline_access',+ // The wallet/services scopes gate the agent-wallet MCP server+ // (api/mcp-agent). They are registerable because the user approves each one+ // by name on the consent screen and every spend they authorize is still+ // bounded by the server-side caps and THREEWS_AGENT_PAY_ENABLED. Omitting+ // them left wallet_status, pay_and_call, provision_wallet and+ // monetize_endpoint unreachable for every dynamically-registered client.+ 'wallet:read', 'wallet:write', 'services:write',]);function filterRegisterableScope(requested) {diff --git a/api/og/sealed-drop.js b/api/og/sealed-drop.jsindex ca14745db..ddc97e209 100644--- a/api/og/sealed-drop.js+++ b/api/og/sealed-drop.js@@ -16,6 +16,7 @@import { cors, wrap } from '../_lib/http.js';import { getDrop } from '../_lib/sealed-drop-store.js';+import { isValidDropId } from '../../src/solana/vanity/drop-protocol.js';const CACHE = 'public, max-age=60, s-maxage=600, stale-while-revalidate=120';@@ -108,7 +109,7 @@ export default wrap(async (req, res) => {const id = (url.searchParams.get('id') || '').trim();let drop = null;- if (/^[0-9a-f]{24}$/.test(id)) {+ if (isValidDropId(id)) {try {drop = await getDrop(id);} catch {@@ -131,3 +132,7 @@ export default wrap(async (req, res) => {res.setHeader('cache-control', CACHE);res.end(svg);});++// Exposed for unit tests: renders the card from fixed fields so a test can assert+// the SVG shape (and that no secret ever reaches it) without Redis or a network.+export const __testInternals = { buildCard, shortAddr, assetLabel, THEME_STYLE };diff --git a/api/og/three-token-badge.js b/api/og/three-token-badge.jsindex 4f299bb01..6fd08560c 100644--- a/api/og/three-token-badge.js+++ b/api/og/three-token-badge.js@@ -9,10 +9,12 @@* with image/svg+xml + a CDN cache header, no heavy canvas/satori deps in the* serverless bundle. Social crawlers accept image/svg+xml for og:image.*- * Every figure on the card is real: price, 24h change, market cap, holders,- * volume and on-chain agent count are pulled from the same source the- * /three-token page uses — GET /api/three-token/stats (Birdeye → DexScreener →- * GeckoTerminal failover with a stale cache, plus DB-derived protocol metrics).+ * Every figure on the card is real, and read from the same two sources that back+ * GET /api/three-token/stats (what the /three-token page renders), so the card+ * and the page can never disagree:+ * market data — fetchTokenMarketData() (Birdeye → DexScreener → GeckoTerminal+ * failover with a stale cache)+ * agent count — the same agent_identities count the stats endpoint runs* Nothing is hardcoded. $THREE is the only coin this card ever references.** The card degrades gracefully: if the stats fetch fails or a field is missing@@ -61,7 +63,24 @@ function fmtPrice(n) {if (n == null || !Number.isFinite(n)) return '—';if (n >= 1) return `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;if (n >= 0.01) return `$${n.toFixed(4)}`;- return `$${n.toPrecision(6).replace(/0+$/, '').replace(/\.$/, '')}`;+ if (n <= 0) return '$0';+ // Sub-cent: 6 significant figures, but always in plain decimal notation.+ // toPrecision() flips to exponent form below 1e-7 ("$1.00000e-8"), which is+ // unreadable on a share card, so derive the decimal count and render fixed.+ const decimals = Math.min(20, 5 - Math.floor(Math.log10(n)));+ return `$${n.toFixed(decimals).replace(/0+$/, '').replace(/\.$/, '')}`;+}++// Approximate advance width of a string in the hero face (Inter, weight 800) so+// the layout can flow around a rendered figure. SVG has no measurement API at+// render time and the card ships no font metrics, so the widths below are the+// per-glyph em advances Inter uses: digits and "$" are tabular-wide, separators+// are narrow. Used to keep the 24h pill clear of the price at any magnitude.+const EM_ADVANCE = { '.': 0.27, ',': 0.27 };+function heroTextWidth(s, fontSize) {+ let em = 0;+ for (const ch of String(s)) em += EM_ADVANCE[ch] ?? 0.6;+ return em * fontSize;}// Compact USD for market cap / volume: $1.2M, $640K, $12.3B.@@ -120,12 +139,19 @@ function renderCard(d) {const arrow = up ? '▲' : '▼';const mintShort = shortMint(THREE_MINT);- // 24h-change pill, only when we actually have the datum.+ // 24h-change pill, only when we actually have the datum. It sits to the right+ // of the price, so its x follows the price's rendered width: a hardcoded x+ // collides with the figure as soon as the price gets long (a dollar-plus+ // price, or a sub-cent one carrying six significant digits).const pillW = pct ? 40 + pct.length * 13 : 0;+ const pillX = Math.min(+ 1128 - pillW,+ Math.round(72 + heroTextWidth(priceStr, 84) + 28),+ );const changePill = pct- ? `<rect x="468" y="300" width="${pillW}" height="44" rx="22"+ ? `<rect x="${pillX}" y="300" width="${pillW}" height="44" rx="22"fill="${changeColor}" fill-opacity=".12" stroke="${changeColor}" stroke-opacity=".4" stroke-width="1.5"/>- <text x="${468 + pillW / 2}" y="329" text-anchor="middle"+ <text x="${pillX + pillW / 2}" y="329" text-anchor="middle"font-family="Inter,system-ui,sans-serif" font-size="20" font-weight="700"fill="${changeColor}">${x(arrow)} ${x(pct)}</text>`: '';@@ -214,4 +240,6 @@ export default wrap(async (req, res) => {// Exposed for unit tests: lets a test render the card from fixed figures and// assert the SVG shape without touching the network or DB.-export const __testInternals = { renderCard, fmtPrice, fmtCompactUsd, fmtPct, fmtInt, shortMint };+export const __testInternals = {+ renderCard, fmtPrice, fmtCompactUsd, fmtPct, fmtInt, shortMint, heroTextWidth,+};diff --git a/data/changelog.json b/data/changelog.jsonindex ec3af7925..0080bdafc 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,73 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-08-13",+ "title": "The decentralized inference demo stops sending your prompt to a gateway that is no longer Livepeer",+ "summary": "The decentralized inference lab runs the same prompt through our own inference chain and through a Livepeer AI gateway, side by side. The free no-key gateway it used has not been Livepeer since early August: that hostname now points at an unrelated server. The demo kept posting prompts to it on every run and showing a bare connection error. It no longer dials that host at all. The decentralized card now reports the gateway as unavailable and names the two settings that bring it back (a Livepeer Studio key, or the address of a self-hosted gateway), and a self-hosted address is now honored by both this demo and the Forge Livepeer lane from one shared setting. The call also has a time limit, so a gateway that accepts the connection and then goes quiet can no longer hold up the reply from the other side of the comparison.",+ "tags": [+ "fix",+ "improvement"+ ],+ "link": "/demos"+ },+ {+ "date": "2026-08-13",+ "title": "The extra views behind a 3D generation stop being rejected for the wrong file type",+ "summary": "Before a prompt becomes a 3D model, the forge draws a reference picture, then draws two more views of it so the reconstruction can see the sides and back instead of guessing them. Those extra views sent the reference picture to the image model labelled as a PNG no matter what it actually was, so a JPEG or WebP reference could be refused outright and you would quietly get fewer views and a rougher model. The real format is now read from the picture and sent with it. A reference that is unreachable, oversized, or not actually an image is now refused with a clear reason instead of being forwarded as-is and failing further down. And every image this step fetches, including the optional edit mask, now goes through the same address safety check the rest of the platform uses, so a supplied link cannot be aimed at an internal address.",+ "tags": [+ "fix",+ "security"+ ],+ "link": "/create"+ },+ {+ "date": "2026-08-13",+ "title": "The Money-Cam stops going dark when its feed stumbles, and stops replaying old transfers as new light",+ "summary": "The Agent Galaxy renders real money moving between agent wallets: every pulse of light is one on-chain transfer you can open in an explorer. The map loads a window of recent flows, then asks every few seconds for only the ones newer than the last it saw. If the feed query failed or ran long, the map was supposed to fall back to the last good window it had built, so it kept its picture instead of blanking. It never could: the saved copy and the small update polls shared one slot, so each poll (which by design carries almost nothing) overwrote the saved window seconds after it was written, leaving nothing to fall back to. Worse, when an update poll itself failed it was answered with that saved window, which is older than what the viewer already had, so the map rewound its place in the stream and could re-animate long-past transfers as if the money were moving right now. The saved window now belongs to the full load alone. A failed update poll returns nothing new and hands the viewer's own position straight back, so it waits for the next poll instead of travelling backwards, and a failed request for older history honestly reports that there is no more to load. Separately, a fractional page size in the address bar (?limit=1.5) made the feed query fail outright and the whole galaxy report itself as quiet while it was busy; page sizes are now rounded before they are used.",+ "tags": [+ "fix"+ ],+ "link": "/galaxy"+ },+ {+ "date": "2026-08-13",+ "title": "The Rankings remix board now counts only real remixes from other creators",+ "summary": "The Remixes Received board on /rankings was meant to answer one question: how many other people built on top of your work. It was counting more than that. Every time you refined one of your own models the forge recorded the new version as a derivative of the old one, and the board counted it, so re-refining your own model climbed the ranking exactly like someone else remixing you would. Generations that failed partway through were counted too. Both are gone: a row only counts when it is a finished model made by a different creator, and an anonymous remix of your work still counts because that really is someone else. Ranks on that one metric will shift accordingly. Separately, the Daily Match standings endpoint now sends the cross-origin header the rest of our public read-only endpoints send, so anything reading the board from outside three.ws (dashboards, agent tooling, embeds) gets the data instead of a blocked request.",+ "tags": [+ "fix",+ "improvement"+ ],+ "link": "/rankings"+ },+ {+ "date": "2026-08-13",+ "title": "An avatar rendered through the MCP server can no longer be turned into a tracking beacon",+ "summary": "When an AI assistant renders one of your avatars through the three.ws MCP server, the server builds a small viewer page and the assistant displays it. The caller picks the background for that page. The check on that value blocked anything that could break out of the styling, but it still allowed a CSS url(), so a caller could point the background at an image on a server they control and quietly collect the address and referring page of everyone who ever viewed that avatar. Backgrounds and gradients never need url(), so it is refused outright now and the safe default is used instead. A second fix went in with it: the server works out its own public web address to build the links it hands back, and its test for a local development address matched anywhere in the name instead of the whole name, so a request arriving with a forged host like evil-127.0.0.1.example.com was treated as local and got plain http links rather than https. That test is now anchored to the whole host, and IPv6 loopback is recognised properly. The animation tools also stopped treating built-in JavaScript property names as though they were real animation clips, and the shared MCP helpers behind all of this are now covered by tests.",+ "tags": [+ "security",+ "fix"+ ],+ "link": "/docs/mcp"+ },+ {+ "date": "2026-08-13",+ "title": "The $THREE tile on the live heatmap shows real buy pressure again",+ "summary": "The 3D market heatmap on agent screens pins $THREE as its anchor tile, and that tile was meant to carry a community pulse alongside price and volume. The pulse read pump.fun's public comments feed, which pump.fun has since removed from its open API, so the tile had been quietly shipping without it: no error, just a signal that never appeared. The anchor now carries its 24h order flow instead, read from the same live market data the tile already fetches: how many of the last day's swaps were buys versus sells, as a percentage and a leaning score. Hovering the anchor shows it, and the screen's spoken market narration calls it out. Two related fixes landed with it. The wallet and coin intel endpoints now reject a malformed address with a clear error instead of answering as though the address simply had no history. And a total market-data outage now returns a proper error rather than an anchor tile with no numbers in it.",+ "tags": [+ "fix",+ "improvement"+ ]+ },+ {+ "date": "2026-08-13",+ "title": "The AI safety check stays available even when someone floods it with bad requests",+ "summary": "Every message and every autonomous money move an avatar makes is screened by the IBM Granite Guardian safety check before it runs. That check has an hourly platform-wide ceiling so one busy hour cannot run up an unbounded inference bill. The ceiling was being charged on every request that arrived, including ones that were rejected on the spot for a malformed body and never reached the safety model at all. A single client sending junk could therefore burn the whole platform hour and leave everyone else refused for real, valid checks. The ceiling is now charged only when an actual screening runs. Two error replies were also corrected: sending the wrong content type now answers 415 and an oversized body answers 413, instead of both being reported as generic bad input, so a caller can see which of the two to fix.",+ "tags": [+ "fix"+ ],+ "link": "/docs/ibm"+ },{"date": "2026-08-13","title": "An expired Bitcoin inscription order now says so, instead of looking like a broken server",diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 7165759fe..2b858b1f0 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -3019,6 +3019,8 @@ The cross-surface leaderboard behind `/rankings`. Public; sending a session cook| `limit` | integer | 1..100 (default: 50) || `offset` | integer | Pagination offset |+`remixes_received` counts finished derivatives made by *other* creators: a creator's own refines of their own model write the same `parent_creation_id` and are deliberately excluded, as are generations that never finished.+---### Daily Match standings@@ -3027,7 +3029,7 @@ The cross-surface leaderboard behind `/rankings`. Public; sending a session cookGET /api/leaderboard/daily-match```-The agents' Daily Match board behind `/daily-match`. Ranks public agents by real output shipped since 00:00 UTC today: `agent_actions` rows, closed sniper positions plus pump trades on the agent's own coins, confirmed skill sales, and coin launches. `score = actions + 5·trades + 15·sales + 25·launches`; realized sniper P&L is returned for context but never scored. Public, anonymous, CDN-cached ~30s. Format adopted from Bowyer's Arena (bowyer.app), who run daily agent matches on top of three.ws avatars.+The agents' Daily Match board behind `/daily-match`. Ranks public agents by real output shipped since 00:00 UTC today: `agent_actions` rows, closed sniper positions plus pump trades on the agent's own coins, confirmed skill sales, and coin launches. `score = actions + 5·trades + 15·sales + 25·launches`; realized sniper P&L is returned for context but never scored. Public, anonymous, CDN-cached ~30s, and cross-origin readable (`Access-Control-Allow-Origin: *`, same as the unified board). Format adopted from Bowyer's Arena (bowyer.app), who run daily agent matches on top of three.ws avatars.**Query parameters**diff --git a/docs/ibm.md b/docs/ibm.mdindex 6f39483b2..0a7d7c4ac 100644--- a/docs/ibm.md+++ b/docs/ibm.md@@ -157,6 +157,8 @@ curl -s https://three.ws/api/guardian/assess \For autonomous sends, `governSend()` additionally enforces a per-period USD spend cap, so a request can be vetoed either for risk content **or** for exceeding the cap.+**Errors.** Every failure is JSON, never HTML: `400 bad_request` (missing or malformed `text`/`messages`/`risks`/`action`), `405 method_not_allowed`, `413 bad_request` (body over 100 KB), `415 bad_request` (content-type is not `application/json`), `429 rate_limited` (30 requests/min per IP, plus an hourly platform-wide ceiling on watsonx inference that only real assessments charge), `503 guardian_unconfigured` (no `WATSONX_API_KEY` + `WATSONX_PROJECT_ID`, so no verdict is fabricated), and `502 guardian_failed` when watsonx itself fails.+---## Granite Oracle — TimeSeries forecastingdiff --git a/docs/kol-tracker.md b/docs/kol-tracker.mdindex f7f7a7f33..9875a013b 100644--- a/docs/kol-tracker.md+++ b/docs/kol-tracker.md@@ -120,7 +120,7 @@ Writes the curated tracked-wallet list that the tracker merges in. Accepts `{ raThe tracker answers "who is making money"; the reputation surfaces answer "should this wallet's record earn trust". They meet at the wallet address:-- **`GET /api/intel/wallet/<WALLET_ADDRESS>`** returns one wallet's realized track record from the Smart-Money graph: a 0 to 100 realized score, win rate, average ATH multiple, winners and losers, labels (`smart_money`, `sybil`, `fresh`, and others), and its funder cluster. `computed: false` means no track record exists yet for that address; that is an honest zero, not an error. Any wallet you see on the tracker can be fed straight into it.+- **`GET /api/intel/wallet/<WALLET_ADDRESS>`** returns one wallet's realized track record from the Smart-Money graph: a 0 to 100 realized score, win rate, average ATH multiple, winners and losers, labels (`smart_money`, `sybil`, `fresh`, and others), and its funder cluster. `computed: false` means no track record exists yet for that address; that is an honest zero, not an error. A string that is not a base58 Solana address is a different case and returns `400 bad_request`, so a typo never reads as a wallet with no history. Any wallet you see on the tracker can be fed straight into it. The same card is served by `GET /api/intel/smart-money?wallet=<WALLET_ADDRESS>`, which applies the identical validation.- **[Smart Money Radar](./smart-money.md)** is the sibling leaderboard built from graduation outcomes rather than a KOL universe: reputation earned per wallet from which coins actually graduated. The tracker's footer links to it, and the two boards frequently disagree in instructive ways.- **[Trust primitives](./trust-primitives.md)** wrap the same question for autonomous agents: a paid endpoint that scores any counterparty wallet from real on-chain evidence before an agent transacts with it.diff --git a/docs/media-api.md b/docs/media-api.mdindex 0d64e8fa6..718906f81 100644--- a/docs/media-api.md+++ b/docs/media-api.md@@ -505,8 +505,12 @@ curl -s 'https://three.ws/api/avatars/library?limit=24&offset=0'**`GET /api/objects/library`** is the same manifest pattern for the CC0 3Dprop library: free, commercial-OK objects (Poly Haven and other CC0 sources)-staged as web-ready GLBs. Identical pagination (`?limit=1..1000`,-`?offset=`), identical empty-until-staged behavior, no auth.+staged as web-ready GLBs. Same pagination (`?limit=1..1000`, `?offset=`),+same empty-until-staged behavior, no auth. One difference from the character+library: this endpoint validates the cursors strictly, so a malformed+`?limit`/`?offset` returns `400 invalid_limit` / `400 invalid_offset` instead+of being coerced into a page. See [the object library doc](./object-library.md)+for the full parameter table.### Responsediff --git a/docs/object-library.md b/docs/object-library.mdindex 8f2282f52..dc4117888 100644--- a/docs/object-library.md+++ b/docs/object-library.md@@ -41,8 +41,10 @@ Public, no authentication, CORS-open to GET from web origins. The endpoint proxi| Parameter | Type | Default | Notes ||---|---|---|---|-| `limit` | integer, 1 to 1000 | none | Opt-in pagination. Omit it to get the entire library in one response. Values are clamped into 1..1000. |-| `offset` | integer, >= 0 | 0 | Only meaningful together with `limit`. |+| `limit` | integer, 1 to 1000 | none | Opt-in pagination. Omit it to get the entire library in one response. A value above 1000 is clamped to 1000. |+| `offset` | integer, >= 0 | 0 | Requires `limit`; sent on its own it is an error, not a silent no-op. |++Both cursors are validated strictly. Anything that is not a whole decimal number in range (`?limit=abc`, `?limit=0`, `?limit=2.7`, `?offset=-3`, or `?offset=` with no `limit`) returns `400` with a JSON body of `{ "error": "invalid_limit" | "invalid_offset", "error_description": "..." }` and `Cache-Control: no-store`. A bad cursor never degrades into a page you did not ask for.### Response shape@@ -72,7 +74,7 @@ Each entry in `objects`:| `license` | string | `"CC0"` || `source` | string | Origin catalog, e.g. `"polyhaven"` |-Before the manifest is first uploaded, the endpoint returns `{ "objects": [], "total": 0 }` rather than an error, so consumers feature-detect by emptiness.+Before the manifest is first uploaded, the endpoint returns `{ "objects": [], "total": 0 }` rather than an error, so consumers feature-detect by emptiness. A storage outage degrades the same way, but that response carries `Cache-Control: no-store` instead of the 300s edge cache, so the library reappears the moment storage recovers rather than staying empty for the rest of the cache window.### Examplediff --git a/docs/ops/livepeer-federation.md b/docs/ops/livepeer-federation.mdindex 680277252..a3b7350d4 100644--- a/docs/ops/livepeer-federation.md+++ b/docs/ops/livepeer-federation.md@@ -48,9 +48,20 @@ routes exactly that class:The same outage is visible from production, so it is not sandbox networkegress: `POST https://three.ws/api/inference/livepeer` (an existing demo-endpoint that calls the dream gateway's `/llm` surface from Cloud Run) returns-`livepeer.ok: false, error: "network_error"` on the public gateway while the-platform leg answers fine.+endpoint that calls the dream gateway's `/llm` surface from Cloud Run) returned+`livepeer.ok: false` on the public gateway while the platform leg answered+fine.++Both lanes resolve their gateway through one module,+[`api/_lib/livepeer-gateway.js`](../../api/_lib/livepeer-gateway.js)+(`LIVEPEER_GATEWAY_URL` override > keyed studio > public gateway), so a+gateway that moves is a one-file change. That module also marks the public+gateway unusable, and the LLM comparison lane acts on it: with no key and no+override, `/api/inference/livepeer` returns+`livepeer.error: "gateway_unavailable"` without dialing. The point is not the+failed request, it is that a POST there would hand the user's prompt text to+whoever now answers for that hostname. Point `LIVEPEER_GATEWAY_URL` at the+host to dial it again if the domain is ever restored.## Measured comparison (2026-08-12)diff --git a/prompts/swarm-100/api-internal-studio-01.md b/prompts/swarm-100/api-internal-studio-01.mddeleted file mode 100644index ff70e773d..000000000--- a/prompts/swarm-100/api-internal-studio-01.md+++ /dev/null@@ -1,103 +0,0 @@-# API audit: api/_studio batch 01 (3 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/_studio/catalog.js-- api/_studio/dispatch.js-- api/_studio/tools.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-internal-studio-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.diff --git a/public/changelog.json b/public/changelog.jsonindex d4422c2c8..9dfecc870 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-13T01:13:08.469Z",+ "generated_at": "2026-08-13T01:28:42.667Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -16,6 +16,17 @@"fix"]},+ {+ "date": "2026-08-13",+ "type": "update",+ "title": "An avatar rendered through the MCP server can no longer be turned into a tracking beacon",+ "summary": "When an AI assistant renders one of your avatars through the three.ws MCP server, the server builds a small viewer page and the assistant displays it. The caller picks the background for that page. The check on that value blocked anything that could break out of the styling, but it still allowed a CSS url(), so a caller could point the background at an image on a server they control and quietly collect the address and referring page of everyone who ever viewed that avatar. Backgrounds and gradients never need url(), so it is refused outright now and the safe default is used instead. A second fix went in with it: the server works out its own public web address to build the links it hands back, and its test for a local development address matched anywhere in the name instead of the whole name, so a request arriving with a forged host like evil-127.0.0.1.example.com was treated as local and got plain http links rather than https. That test is now anchored to the whole host, and IPv6 loopback is recognised properly. The animation tools also stopped treating built-in JavaScript property names as though they were real animation clips, and the shared MCP helpers behind all of this are now covered by tests.",+ "link": "/docs/mcp",+ "tags": [+ "security",+ "fix"+ ]+ },{"date": "2026-08-13","type": "update",@@ -36,6 +47,59 @@"fix"]},+ {+ "date": "2026-08-13",+ "type": "update",+ "title": "The $THREE tile on the live heatmap shows real buy pressure again",+ "summary": "The 3D market heatmap on agent screens pins $THREE as its anchor tile, and that tile was meant to carry a community pulse alongside price and volume. The pulse read pump.fun's public comments feed, which pump.fun has since removed from its open API, so the tile had been quietly shipping without it: no error, just a signal that never appeared. The anchor now carries its 24h order flow instead, read from the same live market data the tile already fetches: how many of the last day's swaps were buys versus sells, as a percentage and a leaning score. Hovering the anchor shows it, and the screen's spoken market narration calls it out. Two related fixes landed with it. The wallet and coin intel endpoints now reject a malformed address with a clear error instead of answering as though the address simply had no history. And a total market-data outage now returns a proper error rather than an anchor tile with no numbers in it.",+ "link": null,+ "tags": [+ "fix",+ "improvement"+ ]+ },+ {+ "date": "2026-08-13",+ "type": "update",+ "title": "The AI safety check stays available even when someone floods it with bad requests",+ "summary": "Every message and every autonomous money move an avatar makes is screened by the IBM Granite Guardian safety check before it runs. That check has an hourly platform-wide ceiling so one busy hour cannot run up an unbounded inference bill. The ceiling was being charged on every request that arrived, including ones that were rejected on the spot for a malformed body and never reached the safety model at all. A single client sending junk could therefore burn the whole platform hour and leave everyone else refused for real, valid checks. The ceiling is now charged only when an actual screening runs. Two error replies were also corrected: sending the wrong content type now answers 415 and an oversized body answers 413, instead of both being reported as generic bad input, so a caller can see which of the two to fix.",+ "link": "/docs/ibm",+ "tags": [+ "fix"+ ]+ },+ {+ "date": "2026-08-13",+ "type": "update",+ "title": "The extra views behind a 3D generation stop being rejected for the wrong file type",+ "summary": "Before a prompt becomes a 3D model, the forge draws a reference picture, then draws two more views of it so the reconstruction can see the sides and back instead of guessing them. Those extra views sent the reference picture to the image model labelled as a PNG no matter what it actually was, so a JPEG or WebP reference could be refused outright and you would quietly get fewer views and a rougher model. The real format is now read from the picture and sent with it. A reference that is unreachable, oversized, or not actually an image is now refused with a clear reason instead of being forwarded as-is and failing further down. And every image this step fetches, including the optional edit mask, now goes through the same address safety check the rest of the platform uses, so a supplied link cannot be aimed at an internal address.",+ "link": "/create",+ "tags": [+ "fix",+ "security"+ ]+ },+ {+ "date": "2026-08-13",+ "type": "update",+ "title": "The Money-Cam stops going dark when its feed stumbles, and stops replaying old transfers as new light",+ "summary": "The Agent Galaxy renders real money moving between agent wallets: every pulse of light is one on-chain transfer you can open in an explorer. The map loads a window of recent flows, then asks every few seconds for only the ones newer than the last it saw. If the feed query failed or ran long, the map was supposed to fall back to the last good window it had built, so it kept its picture instead of blanking. It never could: the saved copy and the small update polls shared one slot, so each poll (which by design carries almost nothing) overwrote the saved window seconds after it was written, leaving nothing to fall back to. Worse, when an update poll itself failed it was answered with that saved window, which is older than what the viewer already had, so the map rewound its place in the stream and could re-animate long-past transfers as if the money were moving right now. The saved window now belongs to the full load alone. A failed update poll returns nothing new and hands the viewer's own position straight back, so it waits for the next poll instead of travelling backwards, and a failed request for older history honestly reports that there is no more to load. Separately, a fractional page size in the address bar (?limit=1.5) made the feed query fail outright and the whole galaxy report itself as quiet while it was busy; page sizes are now rounded before they are used.",+ "link": "/galaxy",+ "tags": [+ "fix"+ ]+ },+ {+ "date": "2026-08-13",+ "type": "update",+ "title": "The Rankings remix board now counts only real remixes from other creators",+ "summary": "The Remixes Received board on /rankings was meant to answer one question: how many other people built on top of your work. It was counting more than that. Every time you refined one of your own models the forge recorded the new version as a derivative of the old one, and the board counted it, so re-refining your own model climbed the ranking exactly like someone else remixing you would. Generations that failed partway through were counted too. Both are gone: a row only counts when it is a finished model made by a different creator, and an anonymous remix of your work still counts because that really is someone else. Ranks on that one metric will shift accordingly. Separately, the Daily Match standings endpoint now sends the cross-origin header the rest of our public read-only endpoints send, so anything reading the board from outside three.ws (dashboards, agent tooling, embeds) gets the data instead of a blocked request.",+ "link": "/rankings",+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-08-12","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 901f207e7..4660fa25a 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -14,6 +14,14 @@<category>fix</category><description>Sharing a walk produces a card you can post on Farcaster, with a button that opens that avatar walking. A cast stays up forever, but the avatar behind it does not: it can be deleted, or switched to private. When that happened the button still pointed at the missing avatar, so anyone who tapped it landed on a walk that could never load, and the card's second button pointed at the same place as the first, so both said the same thing. The card now checks the avatar before it builds. If the avatar is gone or private it drops the link and invites you to walk your own instead of handing you a dead button, and if the check itself cannot run the link is kept rather than thrown away. The second button now goes to the avatar builder, so the two buttons finally offer two different things. The card also carries its image dimensions now, which stops the preview from reflowing while it loads.</description></item>+ <item>+ <title>An avatar rendered through the MCP server can no longer be turned into a tracking beacon</title>+ <link>https://three.ws/docs/mcp</link>+ <guid isPermaLink="false">2026-08-13:An avatar rendered through the MCP server can no longer be turned into a tracking beacon</guid>+ <pubDate>Thu, 13 Aug 2026 12:00:00 GMT</pubDate>+ <category>security</category>+ <description>When an AI assistant renders one of your avatars through the three.ws MCP server, the server builds a small viewer page and the assistant displays it. The caller picks the background for that page. The check on that value blocked anything that could break out of the styling, but it still allowed a CSS url(), so a caller could point the background at an image on a server they control and quietly collect the address and referring page of everyone who ever viewed that avatar. Backgrounds and gradients never need url(), so it is refused outright now and the safe default is used instead. A second fix went in with it: the server works out its own public web address to build the links it hands back, and its test for a local development address matched anywhere in the name instead of the whole name, so a request arriving with a forged host like evil-127.0.0.1.example.com was treated as local and got plain http links rather than https. That test is now anchored to the whole host, and IPv6 loopback is recognised properly. The animation tools also stopped treating built-in JavaScript property names as though they were real animation clips, and the shared MCP helpers behind all of this are now covered by tests.</description>+ </item><item><title>An expired Bitcoin inscription order now says so, instead of looking like a broken server</title><link>https://three.ws/forever</link>@@ -30,6 +38,46 @@<category>fix</category><description>If you registered an agent on-chain, the hydrate page finds it from your connected wallets and offers to import it into three.ws. Importing read two things: the registry entry on the chain, and the registration file the registry points at, which usually lives on IPFS. If that file did not load in five seconds, the whole import was refused, even though the part that actually matters, the chain saying you own the agent, had already answered. Public IPFS gateways throttle constantly, so owners were locked out of their own agents by a slow third party. The import now only needs the chain read to succeed; a registration file that will not load means the agent lands under its on-chain name and the metadata fills in on the next crawl. Two more changes went in alongside it: ownership is now re-checked against the live registry rather than the crawler's cached copy, so an agent you transferred away cannot be imported by the old wallet, and a chain that is unreachable now says so plainly and asks you to retry instead of reporting a generic failure. Separately, confirming a new registration now reads the transaction receipt over the same priority provider list the rest of the platform uses, instead of the slowest public fallbacks, which is what made a freshly mined registration occasionally come back as "not yet mined".</description></item>+ <item>+ <title>The $THREE tile on the live heatmap shows real buy pressure again</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-08-13:The $THREE tile on the live heatmap shows real buy pressure again</guid>+ <pubDate>Thu, 13 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The 3D market heatmap on agent screens pins $THREE as its anchor tile, and that tile was meant to carry a community pulse alongside price and volume. The pulse read pump.fun's public comments feed, which pump.fun has since removed from its open API, so the tile had been quietly shipping without it: no error, just a signal that never appeared. The anchor now carries its 24h order flow instead, read from the same live market data the tile already fetches: how many of the last day's swaps were buys versus sells, as a percentage and a leaning score. Hovering the anchor shows it, and the screen's spoken market narration calls it out. Two related fixes landed with it. The wallet and coin intel endpoints now reject a malformed address with a clear error instead of answering as though the address simply had no history. And a total market-data outage now returns a proper error rather than an anchor tile with no numbers in it.</description>+ </item>+ <item>+ <title>The AI safety check stays available even when someone floods it with bad requests</title>+ <link>https://three.ws/docs/ibm</link>+ <guid isPermaLink="false">2026-08-13:The AI safety check stays available even when someone floods it with bad requests</guid>+ <pubDate>Thu, 13 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Every message and every autonomous money move an avatar makes is screened by the IBM Granite Guardian safety check before it runs. That check has an hourly platform-wide ceiling so one busy hour cannot run up an unbounded inference bill. The ceiling was being charged on every request that arrived, including ones that were rejected on the spot for a malformed body and never reached the safety model at all. A single client sending junk could therefore burn the whole platform hour and leave everyone else refused for real, valid checks. The ceiling is now charged only when an actual screening runs. Two error replies were also corrected: sending the wrong content type now answers 415 and an oversized body answers 413, instead of both being reported as generic bad input, so a caller can see which of the two to fix.</description>+ </item>+ <item>+ <title>The extra views behind a 3D generation stop being rejected for the wrong file type</title>+ <link>https://three.ws/create</link>+ <guid isPermaLink="false">2026-08-13:The extra views behind a 3D generation stop being rejected for the wrong file type</guid>+ <pubDate>Thu, 13 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Before a prompt becomes a 3D model, the forge draws a reference picture, then draws two more views of it so the reconstruction can see the sides and back instead of guessing them. Those extra views sent the reference picture to the image model labelled as a PNG no matter what it actually was, so a JPEG or WebP reference could be refused outright and you would quietly get fewer views and a rougher model. The real format is now read from the picture and sent with it. A reference that is unreachable, oversized, or not actually an image is now refused with a clear reason instead of being forwarded as-is and failing further down. And every image this step fetches, including the optional edit mask, now goes through the same address safety check the rest of the platform uses, so a supplied link cannot be aimed at an internal address.</description>+ </item>+ <item>+ <title>The Money-Cam stops going dark when its feed stumbles, and stops replaying old transfers as new light</title>+ <link>https://three.ws/galaxy</link>+ <guid isPermaLink="false">2026-08-13:The Money-Cam stops going dark when its feed stumbles, and stops replaying old transfers as new light</guid>+ <pubDate>Thu, 13 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The Agent Galaxy renders real money moving between agent wallets: every pulse of light is one on-chain transfer you can open in an explorer. The map loads a window of recent flows, then asks every few seconds for only the ones newer than the last it saw. If the feed query failed or ran long, the map was supposed to fall back to the last good window it had built, so it kept its picture instead of blanking. It never could: the saved copy and the small update polls shared one slot, so each poll (which by design carries almost nothing) overwrote the saved window seconds after it was written, leaving nothing to fall back to. Worse, when an update poll itself failed it was answered with that saved window, which is older than what the viewer already had, so the map rewound its place in the stream and could re-animate long-past transfers as if the money were moving right now. The saved window now belongs to the full load alone. A failed update poll returns nothing new and hands the viewer's own position straight back, so it waits for the next poll instead of travelling backwards, and a failed request for older history honestly reports that there is no more to load. Separately, a fractional page size in the address bar (?limit=1.5) made the feed query fail outright and the whole galaxy report itself as quiet while it was busy; page sizes are now rounded before they are used.</description>+ </item>+ <item>+ <title>The Rankings remix board now counts only real remixes from other creators</title>+ <link>https://three.ws/rankings</link>+ <guid isPermaLink="false">2026-08-13:The Rankings remix board now counts only real remixes from other creators</guid>+ <pubDate>Thu, 13 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The Remixes Received board on /rankings was meant to answer one question: how many other people built on top of your work. It was counting more than that. Every time you refined one of your own models the forge recorded the new version as a derivative of the old one, and the board counted it, so re-refining your own model climbed the ranking exactly like someone else remixing you would. Generations that failed partway through were counted too. Both are gone: a row only counts when it is a finished model made by a different creator, and an anonymous remix of your work still counts because that really is someone else. Ranks on that one metric will shift accordingly. Separately, the Daily Match standings endpoint now sends the cross-origin header the rest of our public read-only endpoints send, so anything reading the board from outside three.ws (dashboards, agent tooling, embeds) gets the data instead of a blocked request.</description>+ </item><item><title>Docs · GitHub memory seeding</title><link>https://three.ws/docs/github-memory-seeding</link>diff --git a/public/demos/livepeer-inference.html b/public/demos/livepeer-inference.htmlindex 99d1f1418..858b79447 100644--- a/public/demos/livepeer-inference.html+++ b/public/demos/livepeer-inference.html@@ -264,6 +264,15 @@const info = await r.json();$('gateway-info').textContent =`gateway · ${info.gateway} · ${info.gateway_url}`;+ // A deployment with no key and no override has no Livepeer+ // gateway to dial, and the server says so rather than+ // dialling a host that stopped being Livepeer. Say it on the+ // card before the run instead of after a wasted Compare.+ if (info.usable === false) {+ const lb = $('livepeer-body');+ lb.textContent = info.hint || 'No Livepeer gateway is configured for this deployment.';+ lb.className = 'card-body error';+ }if (info.hint) logLine(info.hint, 'dim');if (Array.isArray(info.models) && info.models.length) {const sel = $('livepeer-model');diff --git a/public/features.json b/public/features.jsonindex cad78480a..7329ec5b0 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-13T01:13:08.397Z",+ "generated_at": "2026-08-13T01:28:42.436Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/genome-endpoints-proof.mjs b/scripts/genome-endpoints-proof.mjsindex f8338811f..fb6728058 100644--- a/scripts/genome-endpoints-proof.mjs+++ b/scripts/genome-endpoints-proof.mjs@@ -265,9 +265,9 @@ async function main() {const { rows: [a] } = await db.query(`insert into agent_identities (user_id, name, is_public, skills, persona_tone_tags,voice_provider, voice_id, voice_model, voice_settings, meta)- values ($1, $2, $3, $4::jsonb, $5::jsonb, 'elevenlabs', $6, 'eleven_flash_v2_5', $7::jsonb, $8::jsonb)+ values ($1, $2, $3, $4::text[], $5::jsonb, 'elevenlabs', $6, 'eleven_flash_v2_5', $7::jsonb, $8::jsonb)returning id`,- [userId, name, isPublic, JSON.stringify(['trading', 'research']), JSON.stringify(['precise']),+ [userId, name, isPublic, ['trading', 'research'], JSON.stringify(['precise']),`voice-${name}`, JSON.stringify({ stability: 0.4, similarity_boost: 0.8, style: 0.3, use_speaker_boost: true }),JSON.stringify(meta)],);diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.jsindex b709aa4ca..aafa66125 100644--- a/src/dashboard/dashboard.js+++ b/src/dashboard/dashboard.js@@ -2167,6 +2167,10 @@ async function renderKeys(root) {<label><input type="checkbox" name="scope" value="avatars:write" checked> write</label><label><input type="checkbox" name="scope" value="avatars:delete"> delete</label><label><input type="checkbox" name="scope" value="profile"> profile</label>+ <label><input type="checkbox" name="scope" value="memory:read"> memory:read</label>+ <label><input type="checkbox" name="scope" value="memory:write"> memory:write</label>+ <label><input type="checkbox" name="scope" value="agents:read"> agents:read</label>+ <label><input type="checkbox" name="scope" value="agents:write"> agents:write</label></fieldset><button class="btn" type="submit">Create key</button></form>diff --git a/tests/api/ibm-galaxy.test.js b/tests/api/ibm-galaxy.test.jsnew file mode 100644index 000000000..20ab5f774--- /dev/null+++ b/tests/api/ibm-galaxy.test.js@@ -0,0 +1,306 @@+// Unit tests for /api/ibm/galaxy, the IBM Granite Agent Galaxy.+//+// Covers both handlers with no network and no database:+// GET builds the constellation from Granite embeddings, caches it keyed by a+// fingerprint of the agent set, serves that cache on a repeat call, and+// rebuilds on ?refresh=1.+// POST embeds a natural-language query and ranks agents by cosine similarity.+// The cache regression this locks down: the layout used to be built from a+// SECOND read of the agent set, so an agent added between the two reads was+// embedded into the payload while the cache row carried the pre-add fingerprint,+// and the stale layout was then served as fresh until the TTL expired.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Readable } from 'node:stream';++const state = {+ wxConfigured: true,+ agents: [],+ cacheRow: null,+ sqlCalls: [],+};++// ── Mocks ─────────────────────────────────────────────────────────────────────+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ publicIp: vi.fn(async () => ({ success: true })),+ watsonxEmbedGlobal: vi.fn(async () => ({ success: true })),+ },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++// A tagged-template `sql` that answers by looking at the query text: the agent+// SELECT returns the current agent set, the cache SELECT returns the stored row,+// and the cache UPSERT records it. Every call is logged so a test can assert how+// many times the agent set was read for one request.+vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ const text = strings.join(' ');+ state.sqlCalls.push(text);+ if (text.includes('FROM agent_identities')) return state.agents;+ if (text.includes('CREATE TABLE IF NOT EXISTS agent_galaxy_cache')) return [];+ if (text.includes('SELECT payload')) return state.cacheRow ? [state.cacheRow] : [];+ if (text.includes('INSERT INTO agent_galaxy_cache')) {+ state.cacheRow = {+ data_version: values[0],+ payload: JSON.parse(values[1]),+ computed_at: new Date().toISOString(),+ };+ return [];+ }+ return [];+ }),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++vi.mock('../../api/_lib/r2.js', () => ({+ publicUrl: (k) => `https://cdn.test/${k}`,+ thumbnailUrl: (k) => `https://cdn.test/${k}`,+}));++vi.mock('../../api/_lib/watsonx.js', () => ({+ watsonxConfig: vi.fn(() =>+ state.wxConfigured+ ? {+ configured: true,+ url: 'https://wx',+ projectId: 'proj',+ apiVersion: '2024-05-31',+ chatModel: 'ibm/granite-3-8b-instruct',+ embedModel: 'ibm/granite-embedding-278m-multilingual',+ }+ : { configured: false },+ ),+ // A deterministic 4-dim "embedding" of the query: enough for cosine ranking.+ watsonxEmbed: vi.fn(async (_cfg, { inputs }) => ({+ vectors: inputs.map(() => [1, 0, 0, 0]),+ model: 'ibm/granite-embedding-278m-multilingual',+ })),+ watsonxChatComplete: vi.fn(async () => ({+ text: 'Solana Traders',+ model: 'ibm/granite-3-8b-instruct',+ })),+}));++// Agent vectors: agent N gets a unit vector leaning on axis N % 4, so clusters+// and neighbours are stable and the query vector [1,0,0,0] has an obvious best+// match (the agents leaning on axis 0).+const vectorFor = (i) => {+ const v = [0, 0, 0, 0];+ v[i % 4] = 1;+ return v;+};++vi.mock('../../api/_lib/agent-embeddings.js', () => ({+ agentEmbedText: (a) => `${a.name} ${a.description}`.trim(),+ ensureAgentEmbeddings: vi.fn(async (_cfg, agents) => ({+ vectors: agents.map((_, i) => vectorFor(i)),+ model: 'ibm/granite-embedding-278m-multilingual',+ dims: 4,+ })),+ readAgentVectors: vi.fn(async (ids) => new Map(ids.map((id, i) => [id, vectorFor(i)]))),+}));++import { limits } from '../../api/_lib/rate-limit.js';+import { sql } from '../../api/_lib/db.js';+import { watsonxEmbed } from '../../api/_lib/watsonx.js';+import { ensureAgentEmbeddings } from '../../api/_lib/agent-embeddings.js';++const handler = (await import('../../api/ibm/galaxy.js')).default;++// ── Helpers ───────────────────────────────────────────────────────────────────+function mkAgents(n) {+ return Array.from({ length: n }, (_, i) => ({+ id: `agent-${i}`,+ name: `Agent ${i}`,+ description: `A real agent that does thing number ${i} on Solana`,+ avatar_url: null,+ profile_image_url: null,+ home_url: null,+ persona_tone_tags: null,+ updated_at: `2026-0${(i % 9) + 1}-01T00:00:00.000Z`,+ created_at: '2026-01-01T00:00:00.000Z',+ }));+}++function makeReq({ method = 'GET', url = '/api/ibm/galaxy', body = null } = {}) {+ const req = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);+ req.method = method;+ req.url = url;+ req.headers = {+ host: 'localhost',+ 'content-type': 'application/json',+ origin: 'http://localhost',+ };+ return req;+}+function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ writableEnded: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(chunk) {+ if (chunk !== undefined) this.body += chunk;+ this.writableEnded = true;+ },+ };+}+async function invoke(opts) {+ const res = makeRes();+ await handler(makeReq(opts), res);+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null, res };+}++const agentSelects = () => state.sqlCalls.filter((t) => t.includes('FROM agent_identities')).length;++beforeEach(() => {+ vi.clearAllMocks();+ limits.publicIp.mockResolvedValue({ success: true });+ limits.watsonxEmbedGlobal.mockResolvedValue({ success: true });+ state.wxConfigured = true;+ state.agents = mkAgents(12);+ state.cacheRow = null;+ state.sqlCalls = [];+});++describe('GET /api/ibm/galaxy', () => {+ it('builds a constellation with real coordinates, clusters, and neighbours', async () => {+ const { status, body } = await invoke({});+ expect(status).toBe(200);+ expect(body.available).toBe(true);+ expect(body.agents).toHaveLength(12);+ expect(body.clusters.length).toBeGreaterThan(0);+ for (const a of body.agents) {+ expect(Number.isFinite(a.x)).toBe(true);+ expect(Number.isFinite(a.y)).toBe(true);+ expect(Number.isFinite(a.z)).toBe(true);+ expect(a.neighbors.length).toBeGreaterThan(0);+ expect(a.neighbors.every((n) => n.id !== a.id)).toBe(true);+ }+ expect(body.meta.cache).toBe('miss');+ expect(body.meta.model).toBe('ibm/granite-embedding-278m-multilingual');+ });++ it('names each theme with Granite', async () => {+ const { body } = await invoke({});+ expect(body.clusters.every((c) => c.label)).toBe(true);+ expect(body.clusters.some((c) => c.labelSource === 'granite')).toBe(true);+ });++ // The regression: one read of the agent set per request, so the fingerprint+ // stored in the cache always describes the payload stored beside it.+ it('reads the agent set exactly once per build', async () => {+ await invoke({});+ expect(agentSelects()).toBe(1);+ expect(ensureAgentEmbeddings).toHaveBeenCalledTimes(1);+ });++ it('serves the cached layout on a repeat request without re-embedding', async () => {+ await invoke({});+ state.sqlCalls = [];+ vi.clearAllMocks();+ const { body, res } = await invoke({});+ expect(body.meta.cache).toBe('hit');+ expect(res.headers['x-galaxy-cache']).toBe('hit');+ expect(ensureAgentEmbeddings).not.toHaveBeenCalled();+ });++ it('rebuilds when the agent set changes', async () => {+ await invoke({});+ state.agents = mkAgents(13); // a new agent joined+ const { body } = await invoke({});+ expect(body.meta.cache).toBe('miss');+ expect(body.agents).toHaveLength(13);+ });++ it('rebuilds on ?refresh=1 even when the cache is valid', async () => {+ await invoke({});+ const { body, res } = await invoke({ url: '/api/ibm/galaxy?refresh=1' });+ expect(body.meta.cache).toBe('refresh');+ expect(res.headers['x-galaxy-cache']).toBe('refresh');+ expect(ensureAgentEmbeddings).toHaveBeenCalled();+ });++ it('reports too_few_agents instead of a broken layout', async () => {+ state.agents = mkAgents(1);+ const { status, body } = await invoke({});+ expect(status).toBe(200);+ expect(body.agents).toEqual([]);+ expect(body.meta.reason).toBe('too_few_agents');+ // An empty layout must never poison the cache.+ expect(state.sqlCalls.some((t) => t.includes('INSERT INTO agent_galaxy_cache'))).toBe(false);+ });++ it('says so when watsonx is not configured', async () => {+ state.wxConfigured = false;+ const { status, body } = await invoke({});+ expect(status).toBe(200);+ expect(body.available).toBe(false);+ expect(body.reason).toBe('watsonx_not_configured');+ expect(sql).not.toHaveBeenCalled();+ });+});++describe('POST /api/ibm/galaxy (semantic search)', () => {+ it('ranks agents by cosine similarity to the query embedding', async () => {+ const { status, body } = await invoke({+ method: 'POST',+ body: { query: 'a witty Solana trading assistant' },+ });+ expect(status).toBe(200);+ expect(body.query).toBe('a witty Solana trading assistant');+ expect(body.results.length).toBeGreaterThan(0);+ expect(body.best.score).toBe(1); // the query vector matches axis-0 agents exactly+ const scores = body.results.map((r) => r.score);+ expect([...scores].sort((a, b) => b - a)).toEqual(scores); // descending+ expect(watsonxEmbed).toHaveBeenCalledTimes(1);+ });++ it('rejects an empty query', async () => {+ const { status, body } = await invoke({ method: 'POST', body: { query: ' ' } });+ expect(status).toBe(400);+ expect(body.error).toBe('bad_request');+ });++ it('returns 503 when watsonx is not configured', async () => {+ state.wxConfigured = false;+ const { status, body } = await invoke({ method: 'POST', body: { query: 'anything' } });+ expect(status).toBe(503);+ expect(body.error).toBe('watsonx_not_configured');+ });++ it('returns an empty result set when there are no embeddable agents', async () => {+ state.agents = [];+ const { status, body } = await invoke({ method: 'POST', body: { query: 'anything' } });+ expect(status).toBe(200);+ expect(body.results).toEqual([]);+ });+});++describe('guards', () => {+ it('returns 429 when the rate limit is exceeded', async () => {+ limits.publicIp.mockResolvedValue({ success: false });+ const { status, body } = await invoke({});+ expect(status).toBe(429);+ expect(body.error).toBe('rate_limited');+ });++ it('returns 429 when the global watsonx ceiling is reached', async () => {+ limits.watsonxEmbedGlobal.mockResolvedValue({ success: false });+ const { status } = await invoke({});+ expect(status).toBe(429);+ });++ it('returns 405 for unsupported methods', async () => {+ const { status } = await invoke({ method: 'DELETE' });+ expect(status).toBe(405);+ });+});diff --git a/tests/api/keys-endpoint.test.js b/tests/api/keys-endpoint.test.jsnew file mode 100644index 000000000..5b813fbc4--- /dev/null+++ b/tests/api/keys-endpoint.test.js@@ -0,0 +1,230 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { invoke } from '../_helpers/monetization.js';++// Contract pins for the developer API key endpoints (api/keys).+//+// Two behaviours here were live defects found by probing the deployed handlers:+// 1. DELETE /api/keys/<non-uuid> handed a malformed id straight to Postgres.+// api_keys.id is a uuid column, so 22P02 surfaced to the caller as a 500+// with a support ref for what is plainly bad input.+// 2. List, create, and revoke shared one 30/hour bucket, so the dashboard's+// list-on-load traffic could exhaust the budget and then refuse a revoke,+// locking an owner out of killing a leaked key.+// Each is pinned below, alongside the ordinary success and auth paths.++const authState = { session: null };+const sqlState = { queue: [], calls: [] };+const rlState = { calls: [], fail: new Set() };++vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => authState.session),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++vi.mock('../../api/_lib/db.js', () => {+ const sql = vi.fn(async (strings, ...values) => {+ sqlState.calls.push({+ query: Array.isArray(strings) ? strings.join('?') : String(strings),+ values,+ });+ return sqlState.queue.length ? sqlState.queue.shift() : [];+ });+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };+});++function limiter(name) {+ return vi.fn(async () => {+ rlState.calls.push(name);+ return rlState.fail.has(name)+ ? { success: false, limit: 1, remaining: 0, reset: Date.now() + 1000 }+ : { success: true, limit: 100, remaining: 99, reset: Date.now() + 1000 };+ });+}++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ apiKeyManage: limiter('manage'),+ apiKeyList: limiter('list'),+ apiKeyRevoke: limiter('revoke'),+ },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));++const auditState = { entries: [] };+vi.mock('../../api/_lib/audit.js', () => ({+ logAudit: vi.fn((entry) => {+ auditState.entries.push(entry);+ }),+}));++const { default: keysHandler } = await import('../../api/keys/index.js');+const { default: revokeHandler } = await import('../../api/keys/[id].js');++const USER = { id: 'user-1' };+const KEY_ID = '2c25ec0c-f1a3-475d-9a9f-fe926c832db5';++beforeEach(() => {+ authState.session = { ...USER };+ sqlState.queue = [];+ sqlState.calls = [];+ rlState.calls = [];+ rlState.fail = new Set();+ auditState.entries = [];+});++describe('GET /api/keys', () => {+ it('returns the caller keys without any secret material', async () => {+ sqlState.queue.push([+ {+ id: KEY_ID,+ name: 'prod server',+ prefix: 'sk_live_abcd',+ scope: 'avatars:read',+ last_used_at: null,+ expires_at: null,+ revoked_at: null,+ created_at: '2026-08-13T01:04:36.801Z',+ },+ ]);+ const { status, body } = await invoke(keysHandler, { method: 'GET', url: '/api/keys' });+ expect(status).toBe(200);+ expect(body.keys).toHaveLength(1);+ expect(body.keys[0].id).toBe(KEY_ID);+ expect(JSON.stringify(body)).not.toMatch(/token_hash|secret/);+ // Scoped to the caller, never a bare select over every user's keys.+ expect(sqlState.calls[0].values).toContain(USER.id);+ });++ it('reads on the list bucket, never the mint bucket', async () => {+ await invoke(keysHandler, { method: 'GET', url: '/api/keys' });+ expect(rlState.calls).toEqual(['list']);+ });++ it('401s an anonymous caller before touching the database', async () => {+ authState.session = null;+ const { status, body } = await invoke(keysHandler, { method: 'GET', url: '/api/keys' });+ expect(status).toBe(401);+ expect(body.error).toBe('unauthorized');+ expect(sqlState.calls).toHaveLength(0);+ });++ it('surfaces a 429 with retry metadata when the list bucket is spent', async () => {+ rlState.fail = new Set(['list']);+ const { status, res } = await invoke(keysHandler, { method: 'GET', url: '/api/keys' });+ expect(status).toBe(429);+ expect(res.headers['retry-after']).toBeDefined();+ });+});++describe('POST /api/keys', () => {+ it('mints a key, returns the secret once, and records the issuance', async () => {+ sqlState.queue.push([+ {+ id: KEY_ID,+ name: 'ci runner',+ prefix: 'sk_test_abcd',+ scope: 'avatars:read',+ expires_at: null,+ created_at: '2026-08-13T01:04:36.801Z',+ },+ ]);+ const { status, body } = await invoke(keysHandler, {+ method: 'POST',+ url: '/api/keys',+ body: { name: 'ci runner', scope: 'avatars:read', environment: 'test' },+ });+ expect(status).toBe(201);+ expect(body.key.secret).toMatch(/^sk_test_/);+ expect(rlState.calls).toEqual(['manage']);+ const audit = auditState.entries.find((e) => e.action === 'create_api_key');+ expect(audit).toBeTruthy();+ expect(audit.resourceId).toBe(KEY_ID);+ // The trail records which key was minted, never the credential itself.+ expect(JSON.stringify(audit)).not.toContain(body.key.secret);+ });++ it('rejects an unknown scope with a 400 and writes nothing', async () => {+ const { status, body } = await invoke(keysHandler, {+ method: 'POST',+ url: '/api/keys',+ body: { name: 'bad', scope: 'avatars:read bogus:scope' },+ });+ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ expect(body.error_description).toContain('bogus:scope');+ expect(sqlState.calls).toHaveLength(0);+ });++ it('rejects a missing name with a structured 400', async () => {+ const { status, body } = await invoke(keysHandler, {+ method: 'POST',+ url: '/api/keys',+ body: {},+ });+ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ expect(sqlState.calls).toHaveLength(0);+ });+});++describe('DELETE /api/keys/:id', () => {+ it('revokes the caller key and records the revocation', async () => {+ sqlState.queue.push([{ id: KEY_ID }]);+ const { status, body } = await invoke(revokeHandler, {+ method: 'DELETE',+ url: `/api/keys/${KEY_ID}`,+ query: { id: KEY_ID },+ });+ expect(status).toBe(200);+ expect(body.ok).toBe(true);+ expect(rlState.calls).toEqual(['revoke']);+ expect(auditState.entries.some((e) => e.action === 'revoke_api_key')).toBe(true);+ });++ it('rejects a non-uuid id with a 400 instead of a 500, and issues no query', async () => {+ const { status, body } = await invoke(revokeHandler, {+ method: 'DELETE',+ url: '/api/keys/not-a-uuid',+ query: { id: 'not-a-uuid' },+ });+ expect(status).toBe(400);+ expect(body.error).toBe('invalid_id');+ expect(sqlState.calls).toHaveLength(0);+ });++ it('404s a key that belongs to someone else or is already revoked', async () => {+ sqlState.queue.push([]);+ const { status, body } = await invoke(revokeHandler, {+ method: 'DELETE',+ url: `/api/keys/${KEY_ID}`,+ query: { id: KEY_ID },+ });+ expect(status).toBe(404);+ expect(body.error).toBe('not_found');+ expect(auditState.entries).toHaveLength(0);+ });++ it('401s an anonymous caller before touching the database', async () => {+ authState.session = null;+ const { status, body } = await invoke(revokeHandler, {+ method: 'DELETE',+ url: `/api/keys/${KEY_ID}`,+ query: { id: KEY_ID },+ });+ expect(status).toBe(401);+ expect(body.error).toBe('unauthorized');+ expect(sqlState.calls).toHaveLength(0);+ });++ it('rejects a method other than DELETE', async () => {+ const { status } = await invoke(revokeHandler, {+ method: 'GET',+ url: `/api/keys/${KEY_ID}`,+ query: { id: KEY_ID },+ });+ expect(status).toBe(405);+ });+});diff --git a/tests/api/kol-route-resolution.test.js b/tests/api/kol-route-resolution.test.jsnew file mode 100644index 000000000..d45a8d04e--- /dev/null+++ b/tests/api/kol-route-resolution.test.js@@ -0,0 +1,67 @@+// Pins which handler file serves each /api/kol/* path.+//+// The KOL surface is split across two files: api/kol/[action].js dispatches+// wallets / import-gmgn / leaderboard / tracker, while api/kol/trades.js serves+// the trade feed on its own. That split is not cosmetic. Vercel filesystem+// precedence (mirrored by server/index.mjs via resolveApi) puts an exact file+// ahead of a sibling [action].js, so once api/kol/trades.js exists, a `trades`+// branch inside the dispatcher can never run. One shipped that way and quietly+// drifted from the served copy (different limit clamping, different validation+// message) until this guard was written.+//+// The guard therefore asserts both halves: every dispatcher action resolves to+// [action].js and has a branch, and /api/kol/trades resolves to trades.js and is+// absent from the dispatcher.++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { resolveApiHandler } from '../../server/route-resolve.mjs';++const REPO = fileURLToPath(new URL('../..', import.meta.url));+const API_ROOT = join(REPO, 'api');++const DISPATCHER = join(API_ROOT, 'kol', '[action].js');+const TRADES = join(API_ROOT, 'kol', 'trades.js');++const dispatcherSource = readFileSync(DISPATCHER, 'utf8');++// The literal keys of the DISPATCH map, e.g. "leaderboard" / "'import-gmgn'".+function dispatchActions() {+ const map = dispatcherSource.match(/const DISPATCH = \{([\s\S]*?)\n\};/);+ if (!map) throw new Error('DISPATCH map not found in api/kol/[action].js');+ return [...map[1].matchAll(/^\t'?([a-z-]+)'?:/gm)].map((m) => m[1]);+}++describe('/api/kol route resolution', () => {+ const actions = dispatchActions();++ it('dispatches the four consolidated actions', () => {+ expect([...actions].sort()).toEqual(['import-gmgn', 'leaderboard', 'tracker', 'wallets']);+ });++ for (const action of actions) {+ it(`/api/kol/${action} resolves to the dispatcher`, () => {+ const route = resolveApiHandler(API_ROOT, `/api/kol/${action}`);+ expect(route?.file).toBe(DISPATCHER);+ expect(route?.params).toEqual({ action });+ });+ }++ it('/api/kol/trades resolves to its own file, not the dispatcher', () => {+ const route = resolveApiHandler(API_ROOT, '/api/kol/trades');+ expect(route?.file).toBe(TRADES);+ });++ it('the dispatcher carries no trades branch (it would be unreachable)', () => {+ expect(actions).not.toContain('trades');+ expect(dispatcherSource).not.toMatch(/fetchKolTrades/);+ });++ it('an unknown action still lands on the dispatcher, which answers 404', () => {+ const route = resolveApiHandler(API_ROOT, '/api/kol/not-an-action');+ expect(route?.file).toBe(DISPATCHER);+ expect(dispatcherSource).toMatch(/unknown kol action/);+ });+});diff --git a/tests/api/llm-health-handler.test.js b/tests/api/llm-health-handler.test.jsnew file mode 100644index 000000000..03ff44832--- /dev/null+++ b/tests/api/llm-health-handler.test.js@@ -0,0 +1,165 @@+// GET /api/llm/health — the gate in front of the provider report.+//+// The report names every configured provider and quotes the upstream's own+// error text, which is exactly the material an attacker wants: which vendor key+// is dead, which account is out of credits, which lane is currently carrying+// traffic. The probe itself is covered in llm-health-vertex.test.js; what is+// pinned here is the handler around it — the cron secret gate (both header+// forms), the method gate, the unconfigured-deployment response, and the ops+// page that fires on a degraded verdict.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++vi.mock('../../api/_lib/env.js', () => ({+ env: new Proxy({}, { get: (_t, k) => process.env[k] }),+}));++const healthState = { report: { overall: 'ok', anthropic: { status: 'ok' } } };+vi.mock('../../api/_lib/llm-health.js', () => ({+ probeLlmHealth: vi.fn(async () => healthState.report),+}));++const alerts = [];+vi.mock('../../api/_lib/alerts.js', () => ({+ sendOpsAlert: vi.fn(async (title, detail, opts) => {+ alerts.push({ title, detail, opts });+ }),+}));++const { default: handler } = await import('../../api/llm/health.js');+const { probeLlmHealth } = await import('../../api/_lib/llm-health.js');++const SECRET = 'test-cron-secret-llm-health';+const ORIGINAL_ENV = { ...process.env };++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(chunk) {+ if (chunk !== undefined) this.body += chunk;+ this.writableEnded = true;+ },+ };+}++async function invoke({ method = 'GET', headers = {} } = {}) {+ const req = { method, url: '/api/llm/health', headers };+ const res = makeRes();+ await handler(req, res);+ let body = null;+ try {+ body = res.body ? JSON.parse(res.body) : null;+ } catch {+ body = res.body;+ }+ return { res, status: res.statusCode, body };+}++beforeEach(() => {+ process.env.CRON_SECRET = SECRET;+ healthState.report = { overall: 'ok', anthropic: { status: 'ok' } };+ alerts.length = 0;+ probeLlmHealth.mockClear();+});++afterEach(() => {+ process.env = { ...ORIGINAL_ENV };+});++describe('/api/llm/health: cron secret gate', () => {+ it('rejects an unauthenticated caller without probing any provider', async () => {+ const { status, body } = await invoke();+ expect(status).toBe(403);+ expect(body.error).toBe('forbidden');+ // The gate runs before the probe: no provider names, no upstream calls.+ expect(JSON.stringify(body)).not.toContain('anthropic');+ expect(probeLlmHealth).not.toHaveBeenCalled();+ });++ it('rejects a wrong secret in either header form', async () => {+ const viaHeader = await invoke({ headers: { 'x-cron-secret': 'wrong' } });+ const viaBearer = await invoke({ headers: { authorization: 'Bearer wrong' } });+ expect(viaHeader.status).toBe(403);+ expect(viaBearer.status).toBe(403);+ expect(probeLlmHealth).not.toHaveBeenCalled();+ });++ it('rejects a repeated header that collapses into a comma-joined value', async () => {+ // Node hands a duplicated header through as an array; the comparison+ // stringifies it, so the smuggled copy must still fail closed.+ const { status } = await invoke({ headers: { 'x-cron-secret': [SECRET, 'wrong'] } });+ expect(status).toBe(403);+ });++ it('serves the report to the X-Cron-Secret header an operator sends', async () => {+ const { status, body } = await invoke({ headers: { 'x-cron-secret': SECRET } });+ expect(status).toBe(200);+ expect(body).toEqual({ overall: 'ok', anthropic: { status: 'ok' } });+ });++ it('serves the report to the Bearer form the scheduled invocation sends', async () => {+ const { status, body } = await invoke({ headers: { authorization: `Bearer ${SECRET}` } });+ expect(status).toBe(200);+ expect(body.overall).toBe('ok');+ });++ it('answers 503 not_configured when the deployment has no CRON_SECRET', async () => {+ delete process.env.CRON_SECRET;+ const { status, body } = await invoke({ headers: { 'x-cron-secret': SECRET } });+ expect(status).toBe(503);+ expect(body.error).toBe('not_configured');+ expect(probeLlmHealth).not.toHaveBeenCalled();+ });++ it('refuses a non-GET method', async () => {+ const { status, body } = await invoke({+ method: 'POST',+ headers: { 'x-cron-secret': SECRET },+ });+ expect(status).toBe(405);+ expect(body.error).toBe('method_not_allowed');+ });+});++describe('/api/llm/health: ops paging', () => {+ it('pages ops with the failing providers when the verdict is degraded', async () => {+ healthState.report = {+ overall: 'degraded',+ openrouter: { status: 'error', error: 'HTTP 402' },+ anthropic: { status: 'ok' },+ };+ const { status } = await invoke({ headers: { 'x-cron-secret': SECRET } });+ expect(status).toBe(200);+ expect(alerts).toHaveLength(1);+ expect(alerts[0].title).toContain('DEGRADED');+ expect(alerts[0].detail).toContain('openrouter: HTTP 402');+ // Healthy providers stay out of the page.+ expect(alerts[0].detail).not.toContain('anthropic');+ // Deduped on the failing set so a sustained outage pages once.+ expect(alerts[0].opts.signature).toBe('llm-health:degraded:openrouter: HTTP 402');+ });++ it('pages on a full outage too', async () => {+ healthState.report = { overall: 'down', anthropic: { status: 'error', error: 'HTTP 401' } };+ await invoke({ headers: { 'x-cron-secret': SECRET } });+ expect(alerts).toHaveLength(1);+ expect(alerts[0].title).toContain('DOWN');+ });++ it('stays quiet on a healthy or unconfigured verdict', async () => {+ await invoke({ headers: { 'x-cron-secret': SECRET } });+ healthState.report = { overall: 'unconfigured' };+ await invoke({ headers: { 'x-cron-secret': SECRET } });+ expect(alerts).toHaveLength(0);+ });+});diff --git a/tests/api/market-upstream-error.test.js b/tests/api/market-upstream-error.test.jsnew file mode 100644index 000000000..a889e6d23--- /dev/null+++ b/tests/api/market-upstream-error.test.js@@ -0,0 +1,117 @@+// Unit tests for the shared market-data upstream contract+// (api/_lib/market/upstream-error.js), which every Granite market handler+// (api/ibm/oracle.js, twin.js, attest.js) answers GeckoTerminal failures with.++import { describe, it, expect } from 'vitest';+import {+ classifyMarketError,+ marketUpstreamError,+ callMarket,+ isMarketUpstreamError,+} from '../../api/_lib/market/upstream-error.js';++const fault = (status) =>+ Object.assign(new Error(`GeckoTerminal ${status}: {"meta":{"ref_id":"abc"}}`), { status });++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(chunk) {+ if (chunk !== undefined) this.body += chunk;+ this.writableEnded = true;+ },+ };+}++describe('classifyMarketError', () => {+ it('maps a missing pool to a non-retryable 404', () => {+ expect(classifyMarketError(fault(404))).toMatchObject({+ status: 404,+ code: 'pool_not_found',+ retryable: false,+ });+ });++ it('maps a throttle to a retryable 503', () => {+ expect(classifyMarketError(fault(429))).toMatchObject({+ status: 503,+ code: 'upstream_rate_limited',+ retryable: true,+ });+ });++ it('maps an upstream outage to 502', () => {+ expect(classifyMarketError(fault(502))).toMatchObject({+ status: 502,+ code: 'upstream_error',+ });+ });++ it('maps an error with no status to 502 rather than guessing', () => {+ expect(classifyMarketError(new Error('socket hang up'))).toMatchObject({+ status: 502,+ code: 'upstream_error',+ });+ expect(classifyMarketError(undefined).status).toBe(502);+ });++ it('never echoes the upstream body', () => {+ for (const status of [404, 429, 502]) {+ expect(classifyMarketError(fault(status)).message).not.toMatch(/ref_id|GeckoTerminal/);+ }+ });+});++describe('marketUpstreamError', () => {+ it('writes the mapped status, code, and retryable flag', () => {+ const res = makeRes();+ marketUpstreamError(res, fault(429));+ expect(res.statusCode).toBe(503);+ const body = JSON.parse(res.body);+ // Always a real error code. An upstream error carries a status but never a+ // code, so forwarding `err.code` produced a body with no `error` field.+ expect(body.error).toBe('upstream_rate_limited');+ expect(body.retryable).toBe(true);+ });++ it('never caches an error response', () => {+ const res = makeRes();+ marketUpstreamError(res, fault(502));+ expect(res.headers['cache-control']).toBe('no-store');+ });+});++describe('callMarket', () => {+ it('passes a successful result straight through', async () => {+ await expect(callMarket(async () => ['pool'])).resolves.toEqual(['pool']);+ });++ it('tags whatever the call throws as an upstream fault', async () => {+ const err = await callMarket(async () => {+ throw fault(429);+ }).catch((e) => e);+ expect(isMarketUpstreamError(err)).toBe(true);+ expect(err.status).toBe(429); // the real status survives for classification+ });++ it('tags a non-Error rejection too', async () => {+ const err = await callMarket(async () => {+ throw 'upstream exploded';+ }).catch((e) => e);+ expect(isMarketUpstreamError(err)).toBe(true);+ expect(err).toBeInstanceOf(Error);+ });++ it('does not tag errors raised outside a market call', () => {+ expect(isMarketUpstreamError(new Error('bad_token'))).toBe(false);+ expect(isMarketUpstreamError(null)).toBe(false);+ });+});diff --git a/tests/api/mcp-bazaar.test.js b/tests/api/mcp-bazaar.test.jsindex ad2695bc6..567440023 100644--- a/tests/api/mcp-bazaar.test.js+++ b/tests/api/mcp-bazaar.test.js@@ -127,6 +127,43 @@ describe('x402 Bazaar MCP', () => {expect(r.result.structuredContent.services[0].resource).toBe('https://api.weather.test/now');});+ // A cap large enough that Number to String flips to exponential ("1e+21")+ // used to reach parseAtomicAmount as a non-integer string and throw a+ // TypeError out of filterByMaxPrice, failing the whole tool call.+ it('search_services treats an oversized max_price_usdc as no cap', async () => {+ bazState.search.mockResolvedValue({ resources: [item()], sources: [], errors: [] });+ const r = await call('search_services', { query: 'x', max_price_usdc: 1e21 });+ expect(r.error).toBeUndefined();+ expect(r.result.isError).toBeUndefined();+ expect(r.result.structuredContent.services).toHaveLength(1);+ });++ it('search_services caps at a large but representable price without erroring', async () => {+ bazState.search.mockResolvedValue({ resources: [item()], sources: [], errors: [] });+ const r = await call('search_services', { query: 'x', max_price_usdc: 1e15 });+ expect(r.result.structuredContent.services).toHaveLength(1);+ });++ // `network` is a user-supplied wildcard pattern compiled to a RegExp. A bare+ // "?" used to compile to /^?$/ and throw "Nothing to repeat"; a pattern that+ // matches no network must return no services, not an error.+ it('search_services returns no matches for a regex-metacharacter network', async () => {+ bazState.search.mockResolvedValue({ resources: [item()], sources: [], errors: [] });+ const r = await call('search_services', { query: 'x', network: '?' });+ expect(r.error).toBeUndefined();+ expect(r.result.isError).toBeUndefined();+ expect(r.result.structuredContent.count).toBe(0);+ });++ it('search_services still honors the * wildcard in a network filter', async () => {+ bazState.search.mockResolvedValue({ resources: [item()], sources: [], errors: [] });+ const hit = await call('search_services', { query: 'x', network: 'eip155:*' });+ expect(hit.result.structuredContent.count).toBe(1);+ bazState.search.mockResolvedValue({ resources: [item()], sources: [], errors: [] });+ const miss = await call('search_services', { query: 'x', network: 'solana:*' });+ expect(miss.result.structuredContent.count).toBe(0);+ });+it('browse_services lists without a query', async () => {bazState.list.mockResolvedValue({ items: [item()], sources: [], errors: [] });const r = await call('browse_services', {});diff --git a/tests/api/okx-identity-studio.test.js b/tests/api/okx-identity-studio.test.jsindex 56cb2f10e..6d970bc4c 100644--- a/tests/api/okx-identity-studio.test.js+++ b/tests/api/okx-identity-studio.test.js@@ -492,3 +492,67 @@ describe('pipeline state machine', () => {expect(s.result.structuredContent.error).toBe('invalid_job_id');});});++// The fallback template is what a keyless deployment (or a downed LLM chain)+// actually sends to the generator, so its budget math is load-bearing rather+// than a nicety: an over-budget prompt is silently mangled by the text encoder.+describe('prompt shaping', () => {+ it('leads with the first sentence of the brief plus the style hints, inside the generator budget', () => {+ const p = identity.fallbackIdentityPrompt({+ brief: 'A calm on-chain accounting agent. It also files quarterly taxes and audits vaults.',+ styleHints: 'deep navy and silver',+ });+ expect(p).toContain(+ 'full-body humanoid character embodying: A calm on-chain accounting agent, deep navy and silver',+ );+ // Later sentences are backstory, not a visual subject.+ expect(p).not.toContain('quarterly taxes');+ expect(p).toContain('standing neutral pose');+ expect(p.length).toBeLessThanOrEqual(identity.MAX_GENERATION_PROMPT_CHARS);+ });++ it('a CJK brief keeps its first sentence and never crowds out the hints', () => {+ const p = identity.fallbackIdentityPrompt({+ brief: '一个冷静精准的链上会计智能体。它还负责季度报税与金库审计工作。',+ styleHints: 'deep navy and silver',+ });+ // A CJK terminator carries no trailing space, so the sentence split has to+ // cut on a zero-width boundary or the whole brief counts as one sentence.+ expect(p).toContain('一个冷静精准的链上会计智能体');+ expect(p).not.toContain('季度报税');+ expect(p).toContain('deep navy and silver');+ });++ it('an over-long single-sentence brief is cut clean, hints survive, no dangling punctuation', () => {+ const p = identity.fallbackIdentityPrompt({+ brief: `${'a very long rambling description of the agent '.repeat(20)}and more`,+ styleHints: `${'ultra detailed cinematic lighting '.repeat(10)}chrome`,+ });+ expect(p.length).toBeLessThanOrEqual(identity.MAX_GENERATION_PROMPT_CHARS);+ expect(p).toContain('ultra detailed cinematic lighting');+ expect(p).not.toMatch(/[,;:.]\s*,/);+ expect(p).toMatch(/plain background$/);+ });++ it('shapeIdentityPrompt falls back when the director is down and reports it', async () => {+ const shaped = await identity.shapeIdentityPrompt({+ agentName: 'LedgerLynx',+ brief: 'a calm on-chain accounting agent',+ styleHints: null,+ });+ expect(shaped.directed).toBe(null);+ expect(shaped.effective).toContain('full-body humanoid character embodying');+ });++ it('shapeIdentityPrompt rejects a director answer that is prose rather than a prompt', async () => {+ llmSpy.fn = async () => ({ text: 'x'.repeat(1200) });+ const shaped = await identity.shapeIdentityPrompt({+ agentName: 'LedgerLynx',+ brief: 'a calm on-chain accounting agent',+ styleHints: null,+ });+ expect(shaped.directed).toBe(null);+ expect(shaped.effective).toContain('full-body humanoid character embodying');+ expect(shaped.effective.length).toBeLessThanOrEqual(identity.MAX_GENERATION_PROMPT_CHARS);+ });+});diff --git a/tests/api/text-to-image.test.js b/tests/api/text-to-image.test.jsindex ef86b1787..8d70f00d5 100644--- a/tests/api/text-to-image.test.js+++ b/tests/api/text-to-image.test.js@@ -46,6 +46,8 @@ const ENV_KEYS = ['REPLICATE_API_TOKEN','VERTEX_IMAGEN_ENABLED','VERTEX_IMAGEN_FIRST',+ 'LIVEPEER_FEDERATION_ENABLED',+ 'LIVEPEER_GATEWAY_URL',];const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));@@ -369,6 +371,64 @@ describe('textToImage — NIM FLUX free lane (legacy NIM-first order)', () => {});});+// The Livepeer federation lane sits between the first-party free lanes and the+// paid Replicate backstop. It is a real downstream lane, so the ladder's+// "is there anything left to try" test has to count it: before this cover, a+// deployment whose ONLY downstream lane was Livepeer threw the upstream lane's+// error instead of handing off, and the configured federated lane never ran.+function livepeerSuccessResponse(url = 'https://gateway.test/images/out.png') {+ return new Response(JSON.stringify({ images: [{ url, seed: 1, nsfw: false }] }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });+}++describe('textToImage — Livepeer federation lane counts as a real fallback', () => {+ beforeEach(() => {+ process.env.LIVEPEER_FEDERATION_ENABLED = '1';+ process.env.LIVEPEER_GATEWAY_URL = 'https://gateway.test';+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ });++ it('hands a failed NIM lane off to Livepeer when it is the only lane downstream', async () => {+ process.env.NVIDIA_API_KEY = 'nvapi-test';+ const calls = stubFetch([+ ['ai.api.nvidia.com', () => new Response('boom', { status: 500 })],+ ['gateway.test', () => livepeerSuccessResponse()],+ ]);++ const textToImage = await freshTextToImage();+ const result = await textToImage('a red teapot');++ expect(result.imageUrl).toBe('https://gateway.test/images/out.png');+ expect(calls.some((c) => c.url.includes('gateway.test'))).toBe(true);+ });++ it('hands a failed Vertex lead off to Livepeer when it is the only lane downstream', async () => {+ process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';+ vertexState.configured = true;+ vertexState.generate = async () => {+ throw new Error('vertex exploded');+ };+ const calls = stubFetch([['gateway.test', () => livepeerSuccessResponse()]]);++ const textToImage = await freshTextToImage();+ const result = await textToImage('a red teapot');++ expect(result.imageUrl).toBe('https://gateway.test/images/out.png');+ expect(calls.some((c) => c.url.includes('gateway.test'))).toBe(true);+ });++ it('still surfaces the upstream error when Livepeer federation is off', async () => {+ delete process.env.LIVEPEER_FEDERATION_ENABLED;+ process.env.NVIDIA_API_KEY = 'nvapi-test';+ stubFetch([['ai.api.nvidia.com', () => new Response('nope', { status: 401 })]]);++ const textToImage = await freshTextToImage();+ await expect(textToImage('a red teapot')).rejects.toThrow(/nim flux returned 401/);+ });+});+describe('textToImage — Vertex → Replicate fallback', () => {it('falls back to Replicate flux when the Vertex path throws', async () => {process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';diff --git a/tests/inference-livepeer-endpoint.test.js b/tests/inference-livepeer-endpoint.test.jsnew file mode 100644index 000000000..07f069784--- /dev/null+++ b/tests/inference-livepeer-endpoint.test.js@@ -0,0 +1,259 @@+// /api/inference/livepeer endpoint behavior tests.+//+// The endpoint is the side-by-side inference demo: one leg on the three.ws+// provider chain, one leg on a Livepeer AI gateway. These pin the contract the+// demo page renders against:+//+// 1. GET advertises the resolved gateway, and whether it is usable at all,+// so the client can say the Livepeer leg is dead before a run.+// 2. Input validation rejects a missing prompt before either leg is called.+// 3. The no-key public gateway is REFUSED, not dialled: the hostname stopped+// resolving to Livepeer on 2026-08-12, so a POST there would be an+// outbound copy of the user's prompt to an unidentified host.+// 4. One leg failing never fails the request: the demo's whole point is+// showing the surviving side, so both legs report their own ok/error.+// 5. The platform leg names the provider that actually answered. It is a+// chain, not a fixed vendor, and the card must not claim otherwise.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++vi.mock('../api/_lib/http.js', () => ({+ wrap: (fn) => fn,+ cors: () => false,+ method: (req, res, allowed) => {+ if (allowed.includes(req.method)) return true;+ res._json = { status: 405, body: { error: 'method_not_allowed' } };+ return false;+ },+ readJson: async (req) => req.body ?? {},+ rateLimited: (res) => {+ res._json = { status: 429, body: { error: 'rate_limited' } };+ return res;+ },+ error: (res, status, code, message) => {+ res._json = { status, body: { error: code, error_description: message } };+ return res;+ },+ json: (res, status, body) => {+ res._json = { status, body };+ return res;+ },+}));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { livepeerIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '1.2.3.4',+}));+vi.mock('../api/_lib/llm.js', () => ({ llmComplete: vi.fn() }));++import handler from '../api/inference/livepeer.js';+import { llmComplete } from '../api/_lib/llm.js';++const ENV_KEYS = ['LIVEPEER_API_KEY', 'LIVEPEER_GATEWAY_URL'];++let fetchMock;++beforeEach(() => {+ for (const k of ENV_KEYS) delete process.env[k];+ llmComplete.mockReset();+ llmComplete.mockResolvedValue({+ provider: 'groq',+ model: 'llama-3.3-70b-versatile',+ text: ' platform answer ',+ usage: { input: 11, output: 4 },+ });+ fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+ for (const k of ENV_KEYS) delete process.env[k];+});++function fakeRes() {+ return { setHeader() {}, end() {}, statusCode: 200 };+}++function call(method, body) {+ const res = fakeRes();+ return handler({ method, url: '/api/inference/livepeer', headers: {}, body }, res).then(() => res);+}++function gatewayResponse(status, payload) {+ return {+ ok: status >= 200 && status < 300,+ status,+ json: async () => payload,+ text: async () => (typeof payload === 'string' ? payload : JSON.stringify(payload)),+ };+}++describe('GET /api/inference/livepeer', () => {+ it('reports the public gateway as unusable with the env var that fixes it', async () => {+ const res = await call('GET');+ expect(res._json.status).toBe(200);+ expect(res._json.body.gateway).toBe('public');+ expect(res._json.body.keyed).toBe(false);+ expect(res._json.body.usable).toBe(false);+ expect(res._json.body.hint).toContain('LIVEPEER_API_KEY');+ expect(res._json.body.models.length).toBeGreaterThan(0);+ });++ it('reports a keyed studio gateway as usable, with no hint to show', async () => {+ process.env.LIVEPEER_API_KEY = 'lp-test-key';+ const res = await call('GET');+ expect(res._json.body.gateway).toBe('studio');+ expect(res._json.body.keyed).toBe(true);+ expect(res._json.body.usable).toBe(true);+ expect(res._json.body.gateway_url).toBe('https://livepeer.studio/api/generate/llm');+ expect(res._json.body.hint).toBeUndefined();+ });++ it('honors a self-hosted gateway override and appends the llm path', async () => {+ process.env.LIVEPEER_GATEWAY_URL = 'https://gateway.example.com/';+ const res = await call('GET');+ expect(res._json.body.gateway).toBe('override');+ expect(res._json.body.gateway_url).toBe('https://gateway.example.com/llm');+ expect(res._json.body.usable).toBe(true);+ });+});++describe('POST /api/inference/livepeer', () => {+ it('400s a missing prompt before either leg runs', async () => {+ const res = await call('POST', {});+ expect(res._json.status).toBe(400);+ expect(res._json.body.error).toBe('bad_request');+ expect(llmComplete).not.toHaveBeenCalled();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('400s a whitespace-only prompt', async () => {+ const res = await call('POST', { prompt: ' \n ' });+ expect(res._json.status).toBe(400);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('405s a method it does not serve', async () => {+ const res = await call('DELETE', {});+ expect(res._json.status).toBe(405);+ });++ it('refuses the unusable public gateway without dialing it', async () => {+ const res = await call('POST', { prompt: 'hello' });+ expect(res._json.status).toBe(200);+ expect(fetchMock).not.toHaveBeenCalled();+ expect(res._json.body.livepeer.ok).toBe(false);+ expect(res._json.body.livepeer.error).toBe('gateway_unavailable');+ expect(res._json.body.livepeer.hint).toContain('LIVEPEER_API_KEY');+ // The surviving leg still answers: a dead gateway must not blank the page.+ expect(res._json.body.livepeer.gateway).toBe('public');+ expect(res._json.body.platform.ok).toBe(true);+ });++ it('names the provider that actually answered the platform leg', async () => {+ const res = await call('POST', { prompt: 'hello' });+ const platform = res._json.body.platform;+ expect(platform.network).toBe('three.ws');+ expect(platform.provider).toBe('groq');+ expect(platform.model).toBe('llama-3.3-70b-versatile');+ expect(platform.reply).toBe('platform answer');+ expect(platform.prompt_tokens).toBe(11);+ expect(platform.completion_tokens).toBe(4);+ });++ it('clamps max_tokens and temperature, and echoes what it used', async () => {+ process.env.LIVEPEER_API_KEY = 'lp-test-key';+ fetchMock.mockResolvedValue(+ gatewayResponse(200, {+ choices: [{ message: { content: 'gateway answer' } }],+ usage: { prompt_tokens: 7, completion_tokens: 3 },+ }),+ );+ const res = await call('POST', { prompt: 'hello', max_tokens: 99_999, temperature: 42 });+ expect(res._json.body.max_tokens).toBe(2048);+ expect(res._json.body.temperature).toBe(2);+ const sent = JSON.parse(fetchMock.mock.calls[0][1].body);+ expect(sent.max_tokens).toBe(2048);+ expect(sent.temperature).toBe(2);+ expect(sent.messages).toEqual([{ role: 'user', content: 'hello' }]);+ expect(sent.stream).toBe(false);+ expect(fetchMock.mock.calls[0][1].headers.authorization).toBe('Bearer lp-test-key');+ });++ it('parses the OpenAI-style gateway shape into the card fields', async () => {+ process.env.LIVEPEER_API_KEY = 'lp-test-key';+ fetchMock.mockResolvedValue(+ gatewayResponse(200, {+ choices: [{ message: { content: ' decentralized answer ' } }],+ usage: { prompt_tokens: 7, completion_tokens: 3 },+ }),+ );+ const res = await call('POST', { prompt: 'hello' });+ const lp = res._json.body.livepeer;+ expect(lp.ok).toBe(true);+ expect(lp.reply).toBe('decentralized answer');+ expect(lp.prompt_tokens).toBe(7);+ expect(lp.completion_tokens).toBe(3);+ expect(lp.gateway).toBe('studio');+ });++ it('parses the legacy studio shape and splits its single token total', async () => {+ process.env.LIVEPEER_API_KEY = 'lp-test-key';+ fetchMock.mockResolvedValue(gatewayResponse(200, { response: 'legacy answer', tokens_used: 20 }));+ const res = await call('POST', { prompt: 'hello' });+ const lp = res._json.body.livepeer;+ expect(lp.ok).toBe(true);+ expect(lp.reply).toBe('legacy answer');+ expect(lp.prompt_tokens + lp.completion_tokens).toBe(20);+ });++ it('surfaces a gateway HTTP error with its status and body, never a throw', async () => {+ process.env.LIVEPEER_API_KEY = 'lp-test-key';+ fetchMock.mockResolvedValue(gatewayResponse(401, '{"errors":["request is not authenticated"]}'));+ const res = await call('POST', { prompt: 'hello' });+ expect(res._json.status).toBe(200);+ const lp = res._json.body.livepeer;+ expect(lp.ok).toBe(false);+ expect(lp.error).toBe('upstream_error');+ expect(lp.upstream_status).toBe(401);+ expect(lp.upstream_body).toContain('not authenticated');+ expect(res._json.body.platform.ok).toBe(true);+ });++ it('codes a socket failure and a timeout distinctly', async () => {+ process.env.LIVEPEER_API_KEY = 'lp-test-key';+ fetchMock.mockRejectedValueOnce(new Error('fetch failed'));+ const down = await call('POST', { prompt: 'hello' });+ expect(down._json.body.livepeer.error).toBe('gateway_unreachable');++ const abort = Object.assign(new Error('The operation was aborted'), { name: 'TimeoutError' });+ fetchMock.mockRejectedValueOnce(abort);+ const slow = await call('POST', { prompt: 'hello' });+ expect(slow._json.body.livepeer.error).toBe('gateway_timeout');+ expect(slow._json.body.livepeer.error_message).toContain('45s');+ });++ it('reports an unconfigured platform chain without failing the request', async () => {+ process.env.LIVEPEER_API_KEY = 'lp-test-key';+ llmComplete.mockRejectedValue(+ Object.assign(new Error('No LLM provider available.'), { code: 'llm_unavailable' }),+ );+ fetchMock.mockResolvedValue(+ gatewayResponse(200, { choices: [{ message: { content: 'gateway answer' } }] }),+ );+ const res = await call('POST', { prompt: 'hello' });+ expect(res._json.status).toBe(200);+ expect(res._json.body.platform.ok).toBe(false);+ expect(res._json.body.platform.error).toBe('no_provider_configured');+ expect(res._json.body.platform.provider).toBeNull();+ expect(res._json.body.livepeer.ok).toBe(true);+ });++ it('flags an empty gateway reply rather than rendering a blank card', async () => {+ process.env.LIVEPEER_API_KEY = 'lp-test-key';+ fetchMock.mockResolvedValue(gatewayResponse(200, { choices: [] }));+ const res = await call('POST', { prompt: 'hello' });+ expect(res._json.body.livepeer.ok).toBe(false);+ expect(res._json.body.livepeer.error).toBe('empty_response');+ });+});diff --git a/tests/jobs-flush-usage-events.test.js b/tests/jobs-flush-usage-events.test.jsnew file mode 100644index 000000000..a27980c32--- /dev/null+++ b/tests/jobs-flush-usage-events.test.js@@ -0,0 +1,168 @@+/**+ * QStash webhook guard on api/jobs/flush-usage-events.js.+ *+ * The signature check binds the delivery to an absolute URL (QStash signs it as+ * the JWT `sub`), so the handler has to rebuild the exact string the publisher+ * used. It previously read `process.env.APP_ORIGIN`, a var nothing in this repo+ * sets, while api/_lib/usage.js publishes to `${env.APP_ORIGIN}/...` (which+ * defaults to https://three.ws). Every genuinely signed job therefore compared+ * against a bare path and got 401, silently killing the threshold-triggered+ * flush lane and leaving only the 1-minute safety-net cron.+ *+ * These cases hold the contract: a real QStash JWT is accepted, everything that+ * is not one is rejected 401, and an unset signing key surfaces as a+ * configuration fault rather than a phantom signature failure.+ *+ * The @upstash/qstash Receiver runs for real here: only the Redis/Neon buffer+ * drains and the http.js envelope are substituted.+ */++import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { createHash, createHmac } from 'node:crypto';++const CURRENT_KEY = 'dGVzdC1jdXJyZW50LXNpZ25pbmcta2V5LWZvci11bml0cw==';+const NEXT_KEY = 'dGVzdC1uZXh0LXNpZ25pbmcta2V5LWZvci11bml0LXRlc3Q=';+const JOB_PATH = '/api/jobs/flush-usage-events';++process.env.QSTASH_CURRENT_SIGNING_KEY = CURRENT_KEY;+process.env.QSTASH_NEXT_SIGNING_KEY = NEXT_KEY;++const flushUsageBuffer = vi.fn(async () => ({ flushed: 4, remaining: 0, errors: 0 }));+const flushAuditBuffer = vi.fn(async () => ({ flushed: 2, remaining: 0, errors: 0 }));++vi.mock('../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'https://three.ws' } }));+vi.mock('../api/_lib/usage.js', () => ({ flushUsageBuffer: (...a) => flushUsageBuffer(...a) }));+vi.mock('../api/_lib/x402/audit-log.js', () => ({ flushAuditBuffer: (...a) => flushAuditBuffer(...a) }));+vi.mock('../api/_lib/http.js', () => ({+ wrap: (fn) => fn,+ readBody: async (req) => Buffer.from(req._raw ?? '', 'utf8'),+ method: (req, res, allowed) => {+ if (allowed.includes(req.method)) return true;+ res._json = { status: 405, body: { error: 'method_not_allowed' } };+ return false;+ },+ json: (res, status, body) => { res._json = { status, body }; return res; },+ error: (res, status, code, message) => {+ res._json = { status, body: { error: code, error_description: message } };+ return res;+ },+}));++const handler = (await import('../api/jobs/flush-usage-events.js')).default;++/** Mint the JWT QStash sends: HS256 over the signing key, `sub` = delivery URL. */+function sign(key, url, body) {+ const b64 = (o) => Buffer.from(JSON.stringify(o)).toString('base64url');+ const now = Math.floor(Date.now() / 1000);+ const header = b64({ alg: 'HS256', typ: 'JWT' });+ const payload = b64({+ iss: 'Upstash',+ sub: url,+ iat: now,+ nbf: now - 5,+ exp: now + 300,+ jti: `test-${now}-${Math.round(now / 7)}`,+ body: createHash('sha256').update(body).digest('base64url'),+ });+ const sig = createHmac('sha256', key).update(`${header}.${payload}`).digest('base64url');+ return `${header}.${payload}.${sig}`;+}++function post({ signature, body = '{}', headers = {}, method = 'POST' } = {}) {+ const req = { method, headers: { host: 'three-ws-api-xyz.a.run.app', ...headers }, _raw: body };+ if (signature) req.headers['upstash-signature'] = signature;+ return req;+}++const res = () => ({ _json: null });++beforeEach(() => {+ process.env.QSTASH_CURRENT_SIGNING_KEY = CURRENT_KEY;+ flushUsageBuffer.mockClear();+ flushAuditBuffer.mockClear();+ vi.spyOn(console, 'warn').mockImplementation(() => {});+});++afterAll(() => {+ delete process.env.QSTASH_CURRENT_SIGNING_KEY;+ delete process.env.QSTASH_NEXT_SIGNING_KEY;+});++describe('POST /api/jobs/flush-usage-events', () => {+ it('accepts a job signed for the publisher origin and drains both buffers', async () => {+ const r = res();+ await handler(post({ signature: sign(CURRENT_KEY, `https://three.ws${JOB_PATH}`, '{}') }), r);+ expect(r._json.status).toBe(200);+ expect(r._json.body).toEqual({+ usage: { flushed: 4, remaining: 0, errors: 0 },+ audit: { flushed: 2, remaining: 0, errors: 0 },+ });+ expect(flushUsageBuffer).toHaveBeenCalledWith({ limit: 500 });+ expect(flushAuditBuffer).toHaveBeenCalledWith({ limit: 1000 });+ });++ it('accepts the rotation (next) signing key', async () => {+ const r = res();+ await handler(post({ signature: sign(NEXT_KEY, `https://three.ws${JOB_PATH}`, '{}') }), r);+ expect(r._json.status).toBe(200);+ });++ it('accepts a delivery to a hostname other than the configured origin', async () => {+ const r = res();+ await handler(post({+ signature: sign(CURRENT_KEY, `https://preview.three.ws${JOB_PATH}`, '{}'),+ headers: { 'x-forwarded-host': 'preview.three.ws', 'x-forwarded-proto': 'https' },+ }), r);+ expect(r._json.status).toBe(200);+ });++ it('rejects a request with no signature header', async () => {+ const r = res();+ await handler(post(), r);+ expect(r._json).toEqual({+ status: 401,+ body: { error: 'unauthorized', error_description: 'invalid qstash signature' },+ });+ expect(flushUsageBuffer).not.toHaveBeenCalled();+ });++ it('rejects a signature minted with an unknown key', async () => {+ const r = res();+ const foreign = 'dW5rbm93bi1rZXktbm90LW91cnMtYXQtYWxsLWZvci10ZXN0';+ await handler(post({ signature: sign(foreign, `https://three.ws${JOB_PATH}`, '{}') }), r);+ expect(r._json.status).toBe(401);+ expect(flushUsageBuffer).not.toHaveBeenCalled();+ });++ it('rejects a valid signature replayed from another endpoint', async () => {+ const r = res();+ await handler(post({ signature: sign(CURRENT_KEY, 'https://three.ws/api/jobs/other', '{}') }), r);+ expect(r._json.status).toBe(401);+ });++ it('rejects a body that does not match the signed hash', async () => {+ const r = res();+ await handler(post({+ signature: sign(CURRENT_KEY, `https://three.ws${JOB_PATH}`, '{}'),+ body: '{"evil":1}',+ }), r);+ expect(r._json.status).toBe(401);+ expect(flushUsageBuffer).not.toHaveBeenCalled();+ });++ it('refuses anything but POST', async () => {+ const r = res();+ await handler(post({ method: 'GET' }), r);+ expect(r._json.status).toBe(405);+ expect(flushUsageBuffer).not.toHaveBeenCalled();+ });++ it('reports a missing signing key as a configuration fault, not a bad signature', async () => {+ delete process.env.QSTASH_CURRENT_SIGNING_KEY;+ const r = res();+ await expect(handler(post({ signature: 'anything' }), r))+ .rejects.toThrow('Missing required env var: QSTASH_CURRENT_SIGNING_KEY');+ expect(r._json).toBeNull();+ expect(flushUsageBuffer).not.toHaveBeenCalled();+ });+});diff --git a/tests/kol-trades-widget.test.js b/tests/kol-trades-widget.test.jsindex feb40a45d..253fb6426 100644--- a/tests/kol-trades-widget.test.js+++ b/tests/kol-trades-widget.test.js@@ -65,22 +65,26 @@ function mockRes() {// API endpoint shape// ---------------------------------------------------------------------------+// The platform's own coin, used as the fixture mint because the handler now+// requires a real base58 Solana address before it will fan out to the provider.+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+describe('GET /api/kol/trades — endpoint shape', () => {it('responds 200 with { mint, trades, wallets } for a valid mint', async () => {- const req = { headers: {}, method: 'GET', url: '/api/kol/trades?mint=ABC123Mint&limit=5' };+ const req = { headers: {}, method: 'GET', url: `/api/kol/trades?mint=${THREE_MINT}&limit=5` };const res = mockRes();await tradesHandler(req, res);expect(res.statusCode).toBe(200);expect(res.body).toMatchObject({- mint: 'ABC123Mint',+ mint: THREE_MINT,trades: expect.any(Array),wallets: 2,});});it('trades is an array', async () => {- const req = { headers: {}, method: 'GET', url: '/api/kol/trades?mint=MINT1' };+ const req = { headers: {}, method: 'GET', url: `/api/kol/trades?mint=${THREE_MINT}` };const res = mockRes();await tradesHandler(req, res);@@ -96,8 +100,18 @@ describe('GET /api/kol/trades — endpoint shape', () => {expect(res.body.error).toBe('validation_error');});+ it('responds 400 for a mint that cannot be a Solana address', async () => {+ const req = { headers: {}, method: 'GET', url: '/api/kol/trades?mint=NOT_A_MINT' };+ const res = mockRes();+ await tradesHandler(req, res);++ expect(res.statusCode).toBe(400);+ expect(res.body.error).toBe('validation_error');+ expect(res.body.error_description).toMatch(/base58/);+ });+it('wallets count matches the KOL_WALLETS stub length', async () => {- const req = { headers: {}, method: 'GET', url: '/api/kol/trades?mint=ANYMINT' };+ const req = { headers: {}, method: 'GET', url: `/api/kol/trades?mint=${THREE_MINT}` };const res = mockRes();await tradesHandler(req, res);diff --git a/tests/launch-mark-enforcement.test.js b/tests/launch-mark-enforcement.test.jsindex 22063700c..b4686afde 100644--- a/tests/launch-mark-enforcement.test.js+++ b/tests/launch-mark-enforcement.test.js@@ -191,6 +191,18 @@ async function invoke(handler, opts) {return { res, json: res.body ? JSON.parse(res.body) : null };}+// Every /api/pump/<action> path is rewritten onto the consolidated dispatcher+// (api/pump/[action].js), which routes on req.query.action the way the+// filesystem router populates it. Binding one action here keeps each test+// naming its endpoint while running exactly the code production serves.+function pumpAction(action) {+ return async (req, res) => {+ req.query = { ...(req.query ?? {}), action };+ const { default: dispatcher } = await import('../api/pump/[action].js');+ return dispatcher(req, res);+ };+}+function resetAll() {authState.session = null;sqlState.queue = [];@@ -233,8 +245,7 @@ describe('POST /api/pump/launch-prep — brand-mark enforcement', () => {[], // insert agent_registrations_pending];- const { default: handler } = await import('../api/pump/launch-prep.js');- const { res, json } = await invoke(handler, {+ const { res, json } = await invoke(pumpAction('launch-prep'), {method: 'POST', url: '/api/pump/launch-prep',body: basePrepBody,});@@ -251,8 +262,7 @@ describe('POST /api/pump/launch-prep — brand-mark enforcement', () => {[{ id: 'agent-1', name: 'Foo' }],];- const { default: handler } = await import('../api/pump/launch-prep.js');- const { res, json } = await invoke(handler, {+ const { res, json } = await invoke(pumpAction('launch-prep'), {method: 'POST', url: '/api/pump/launch-prep',body: { ...basePrepBody, mint_address: 'BadMintNoMark111111111111111111111' },});@@ -270,8 +280,7 @@ describe('POST /api/pump/launch-prep — brand-mark enforcement', () => {];const clientMint = '3wsVanityMintFromClient111111111111';- const { default: handler } = await import('../api/pump/launch-prep.js');- const { res, json } = await invoke(handler, {+ const { res, json } = await invoke(pumpAction('launch-prep'), {method: 'POST', url: '/api/pump/launch-prep',body: { ...basePrepBody, mint_address: clientMint },});@@ -294,8 +303,7 @@ describe('POST /api/pump/launch-prep — brand-mark enforcement', () => {[],];- const { default: handler } = await import('../api/pump/launch-prep.js');- const { res, json } = await invoke(handler, {+ const { res, json } = await invoke(pumpAction('launch-prep'), {method: 'POST', url: '/api/pump/launch-prep',body: basePrepBody,});@@ -355,8 +363,7 @@ describe('POST /api/pump/launch-agent — brand-mark enforcement', () => {// agent_actions insert has .catch → empty queue returns [] safely];- const { default: handler } = await import('../api/pump/launch-agent.js');- const { res, json } = await invoke(handler, {+ const { res, json } = await invoke(pumpAction('launch-agent'), {method: 'POST', url: '/api/pump/launch-agent',body: baseAgentBody,});@@ -379,8 +386,7 @@ describe('POST /api/pump/launch-agent — brand-mark enforcement', () => {const badSk = Buffer.alloc(64, 0xaa);const badMint = 'SomeBadMint1111111111111111111111111';- const { default: handler } = await import('../api/pump/launch-agent.js');- const { res, json } = await invoke(handler, {+ const { res, json } = await invoke(pumpAction('launch-agent'), {method: 'POST', url: '/api/pump/launch-agent',body: {...baseAgentBody,diff --git a/tests/lobehub-plugin-endpoint.test.js b/tests/lobehub-plugin-endpoint.test.jsnew file mode 100644index 000000000..0a4a5c5ba--- /dev/null+++ b/tests/lobehub-plugin-endpoint.test.js@@ -0,0 +1,217 @@+/**+ * api/lobehub/[action].js — the host-facing half of the LobeHub / LobeChat+ * plugin (manifest, .well-known config, handshake).+ *+ * `api/_lib/db.js` and `api/_lib/rate-limit.js` are mocked so every branch runs+ * deterministically without a database: the agent-found, agent-missing,+ * owner-policy, and database-outage paths are all reachable from here, and none+ * of them needs a live Neon branch.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const sqlMock = vi.fn();+vi.mock('../api/_lib/db.js', () => ({+ sql: (...a) => sqlMock(...a),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: async () => ({ pressured: false }),+}));++const rl = { ok: true };+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ widgetRead: vi.fn(async () => ({+ success: rl.ok,+ limit: 60,+ remaining: 0,+ reset: Date.now() + 60_000,+ })),+ },+ clientIp: () => '127.0.0.1',+}));++const { default: handler } = await import('../api/lobehub/[action].js');++const AGENT_ID = '11111111-2222-4333-8444-555555555555';++function makeReq({ method = 'GET', action, body = null, headers = {} } = {}) {+ const req = {+ method,+ url: `/api/lobehub/${action}`,+ query: { action },+ headers: { origin: 'https://chat.lobehub.com', ...headers },+ socket: { remoteAddress: '127.0.0.1' },+ };+ if (body !== null) {+ req.headers['content-type'] = req.headers['content-type'] || 'application/json';+ req.body = body;+ }+ return req;+}++function makeRes() {+ const r = { statusCode: 200, _h: {}, _b: null, writableEnded: false, headersSent: false };+ r.setHeader = (k, v) => { r._h[k.toLowerCase()] = v; };+ r.getHeader = (k) => r._h[k.toLowerCase()];+ r.end = (b) => { r._b = b ?? r._b; r.writableEnded = true; };+ r.json = () => (r._b ? JSON.parse(r._b) : undefined);+ return r;+}++async function call(opts) {+ const res = makeRes();+ await handler(makeReq(opts), res);+ return res;+}++beforeEach(() => {+ rl.ok = true;+ sqlMock.mockReset().mockResolvedValue([]);+});++describe('GET /api/lobehub/manifest', () => {+ it('serves the real plugin manifest with an open CORS policy', async () => {+ const res = await call({ action: 'manifest' });+ expect(res.statusCode).toBe(200);+ // LobeHub's plugin store fetches this URL straight from the browser, so a+ // restricted allow-origin breaks every install.+ expect(res.getHeader('access-control-allow-origin')).toBe('*');+ expect(res.getHeader('cache-control')).toBe('public, max-age=300');+ const body = res.json();+ expect(body.identifier).toBe('3d-agent');+ expect(body.ui.url).toContain('/lobehub/iframe/');+ expect(body.api.map((a) => a.name)).toEqual(+ expect.arrayContaining(['render_agent', 'speak', 'gesture', 'emote']),+ );+ });++ it('answers a preflight without running the handler body', async () => {+ const res = await call({ action: 'manifest', method: 'OPTIONS' });+ expect(res.statusCode).toBe(204);+ expect(res.getHeader('access-control-allow-origin')).toBe('*');+ });++ it('rejects a non-GET method with 405 and an Allow header', async () => {+ const res = await call({ action: 'manifest', method: 'POST' });+ expect(res.statusCode).toBe(405);+ expect(String(res.getHeader('allow'))).toContain('GET');+ expect(res.json().error).toBe('method_not_allowed');+ });+});++describe('GET /api/lobehub/config', () => {+ it('serves the .well-known descriptor openly', async () => {+ const res = await call({ action: 'config' });+ expect(res.statusCode).toBe(200);+ expect(res.getHeader('access-control-allow-origin')).toBe('*');+ expect(res.json().identifier).toBe('3d-agent');+ expect(res.json().ui.settings.agentId.type).toBe('string');+ });+});++describe('POST /api/lobehub/handshake', () => {+ it('requires an agentId', async () => {+ const res = await call({ action: 'handshake', method: 'POST', body: {} });+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('validation_error');+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('rejects a non-UUID agentId before it reaches Postgres', async () => {+ // agent_identities.id is a uuid column: passing a handle straight through+ // raised 22P02 and surfaced to the caller as an opaque 5xx.+ const res = await call({ action: 'handshake', method: 'POST', body: { agentId: 'my-agent' } });+ expect(res.statusCode).toBe(400);+ expect(res.json().error_description).toContain('UUID');+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('rejects a hostOrigin that is not an http(s) URL', async () => {+ const res = await call({+ action: 'handshake',+ method: 'POST',+ body: { agentId: AGENT_ID, hostOrigin: 'javascript:alert(1)' },+ });+ expect(res.statusCode).toBe(400);+ expect(res.json().error_description).toContain('http(s)');+ });++ it('404s an agent that does not exist', async () => {+ sqlMock.mockResolvedValue([]);+ const res = await call({ action: 'handshake', method: 'POST', body: { agentId: AGENT_ID } });+ expect(res.statusCode).toBe(404);+ expect(res.json().error).toBe('not_found');+ });++ it('returns the iframe URL, the agent name, and the plugin host allowlist', async () => {+ sqlMock+ .mockResolvedValueOnce([{ id: AGENT_ID, name: 'Ada' }])+ .mockResolvedValueOnce([{ embed_policy: null }]);+ const res = await call({+ action: 'handshake',+ method: 'POST',+ body: { agentId: AGENT_ID, hostOrigin: 'https://chat.example.com/some/path' },+ });+ expect(res.statusCode).toBe(200);+ const body = res.json();+ expect(body.ok).toBe(true);+ expect(body.verified).toBe(true);+ expect(body.agentName).toBe('Ada');+ expect(body.iframeUrl).toBe(`https://three.ws/lobehub/iframe/?agent=${AGENT_ID}`);+ expect(body.embedPolicy.origins.mode).toBe('allowlist');+ expect(body.embedPolicy.origins.hosts).toContain('chat.lobehub.com');+ // Only the hostname of the caller's origin is folded in, never a path.+ expect(body.embedPolicy.origins.hosts).toContain('chat.example.com');+ });++ it("unions the owner's own allowlist into the reported policy", async () => {+ sqlMock+ .mockResolvedValueOnce([{ id: AGENT_ID, name: 'Ada' }])+ .mockResolvedValueOnce([+ { embed_policy: { origins: { mode: 'allowlist', hosts: ['docs.example.org'] } } },+ ]);+ const res = await call({ action: 'handshake', method: 'POST', body: { agentId: AGENT_ID } });+ expect(res.statusCode).toBe(200);+ const hosts = res.json().embedPolicy.origins.hosts;+ expect(hosts).toContain('docs.example.org');+ expect(hosts).toContain('chat.lobehub.com');+ expect(new Set(hosts).size).toBe(hosts.length);+ });++ it("passes an owner's denylist through instead of inverting it", async () => {+ sqlMock+ .mockResolvedValueOnce([{ id: AGENT_ID, name: null }])+ .mockResolvedValueOnce([+ { embed_policy: { origins: { mode: 'denylist', hosts: ['Bad.example'] } } },+ ]);+ const res = await call({ action: 'handshake', method: 'POST', body: { agentId: AGENT_ID } });+ const origins = res.json().embedPolicy.origins;+ expect(origins.mode).toBe('denylist');+ expect(origins.hosts).toEqual(['bad.example']);+ });++ it('degrades to an unverified handshake when the database is unreachable', async () => {+ sqlMock.mockRejectedValue(new Error('connection refused'));+ const res = await call({ action: 'handshake', method: 'POST', body: { agentId: AGENT_ID } });+ expect(res.statusCode).toBe(200);+ expect(res.json().verified).toBe(false);+ expect(res.json().iframeUrl).toContain(AGENT_ID);+ });++ it('429s when the widget-read limiter is exhausted', async () => {+ rl.ok = false;+ const res = await call({ action: 'handshake', method: 'POST', body: { agentId: AGENT_ID } });+ expect(res.statusCode).toBe(429);+ expect(res.json().error).toBe('rate_limited');+ expect(res.getHeader('retry-after')).toBeDefined();+ });+});++describe('unknown lobehub action', () => {+ it('404s rather than falling through', async () => {+ const res = await call({ action: 'bogus' });+ expect(res.statusCode).toBe(404);+ expect(res.json().error).toBe('not_found');+ });+});diff --git a/tests/marketplace-skill-pricing-endpoints.test.js b/tests/marketplace-skill-pricing-endpoints.test.jsnew file mode 100644index 000000000..30caec712--- /dev/null+++ b/tests/marketplace-skill-pricing-endpoints.test.js@@ -0,0 +1,424 @@+// The three endpoints a seller's price actually flows through: set-skill-price+// (write), skill-promo (the public read the strikethrough renders from), and+// start-trial (the free-run grant that precedes a sale).+//+// What these pin, in order of how much money each one moves:+//+// 1. Retracting a proceeds split must LAND. All three retraction forms+// (delist, `split: null`, `split: []`) clear the row, and a clear that+// fails fails the request instead of leaving removed collaborators+// attached to the next sale. `split: []` also has to survive validation at+// all; while the array had a min-length of 1 it was rejected as malformed,+// so the documented way to retract a split answered 400.+// 2. A split is resolved BEFORE the price row moves, so a rejected split+// never leaves a repriced skill behind it.+// 3. start-trial answers a lost insert race as the 409 it is, not a 500.+// `skill_purchases_one_active_per_beneficiary` is the real guard; the+// SELECTs ahead of it are advisory and two clicks can pass both.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const sqlMock = vi.fn();+vi.mock('../api/_lib/db.js', () => ({+ sql: (...a) => sqlMock(...a),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const getSessionUserMock = vi.fn();+const authenticateBearerMock = vi.fn();+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: (...a) => getSessionUserMock(...a),+ authenticateBearer: (...a) => authenticateBearerMock(...a),+ extractBearer: (req) => {+ const h = req?.headers?.authorization || '';+ return h.startsWith('Bearer ') ? h.slice(7) : null;+ },+}));++const csrfOk = { value: true };+vi.mock('../api/_lib/csrf.js', () => ({+ requireCsrf: vi.fn(async (req, res) => {+ if (csrfOk.value) return true;+ res.statusCode = 403;+ res.end(JSON.stringify({ error: 'csrf_missing' }));+ return false;+ }),+}));++const rlOk = { value: true };+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ authIp: vi.fn(async () => ({ success: rlOk.value, reset: 1_000 })),+ authedReadIp: vi.fn(async () => ({ success: rlOk.value, reset: 1_000 })),+ },+ clientIp: () => '203.0.113.11',+}));++const invalidateSkillPriceCacheMock = vi.fn(async () => {});+vi.mock('../api/_lib/skill-price-cache.js', () => ({+ invalidateSkillPriceCache: (...a) => invalidateSkillPriceCacheMock(...a),+}));++const persistListingSplitMock = vi.fn();+const clearListingSplitMock = vi.fn();+vi.mock('../api/_lib/splits.js', () => ({+ persistListingSplit: (...a) => persistListingSplitMock(...a),+ clearListingSplit: (...a) => clearListingSplitMock(...a),+}));++const describeSkillPromoMock = vi.fn();+vi.mock('../api/_lib/skill-pricing-rules.js', () => ({+ describeSkillPromo: (...a) => describeSkillPromoMock(...a),+}));++const { default: setSkillPrice } = await import('../api/marketplace/set-skill-price.js');+const { default: skillPromo } = await import('../api/marketplace/skill-promo.js');+const { default: startTrial } = await import('../api/marketplace/start-trial.js');++const USER = '11111111-1111-4111-8111-111111111111';+const OTHER_USER = '22222222-2222-4222-8222-222222222222';+const AGENT = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';+// Clearly synthetic, so no third-party mainnet mint is pinned into a fixture.+const MINT = 'THREEsynthetic1111111111111111111111111116dp';++function mkReq({ url = '/', headers = {}, body = null, method = 'POST' } = {}) {+ const hdrs = { ...headers };+ if (body != null && !hdrs['content-type']) hdrs['content-type'] = 'application/json';+ return {+ method,+ url,+ headers: hdrs,+ // server/index.mjs pre-parses JSON bodies onto req.body; readJson reads it+ // from there rather than re-draining an already-ended stream.+ body: body == null ? undefined : body,+ on() {},+ destroy() {},+ };+}+function mkRes() {+ return {+ statusCode: 200, headers: {}, body: undefined, writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ end(b) { this.body = b; this.writableEnded = true; },+ };+}+const parseBody = (res) => (res.body ? JSON.parse(res.body) : undefined);++// Every sql`` call in these handlers, in order, so a test can hand back one row+// set per query and then assert on the SQL text that ran.+let sqlQueue = [];+const sqlText = () => sqlMock.mock.calls.map((c) => c[0].join('?').replace(/\s+/g, ' ').trim());++beforeEach(() => {+ sqlQueue = [];+ sqlMock.mockReset();+ sqlMock.mockImplementation(async () => (sqlQueue.length ? sqlQueue.shift() : []));+ getSessionUserMock.mockReset().mockResolvedValue(null);+ authenticateBearerMock.mockReset().mockResolvedValue(null);+ persistListingSplitMock.mockReset();+ clearListingSplitMock.mockReset().mockResolvedValue(undefined);+ describeSkillPromoMock.mockReset();+ invalidateSkillPriceCacheMock.mockClear();+ csrfOk.value = true;+ rlOk.value = true;+});++const priceReq = (body) => mkReq({ url: '/api/marketplace/set-skill-price', body });+const ownedAgent = () => { sqlQueue = [[{ id: AGENT, user_id: USER }]]; };++describe('POST /api/marketplace/set-skill-price', () => {+ it('refuses an anonymous caller before touching the database', async () => {+ const res = mkRes();+ await setSkillPrice(priceReq({ agent_id: AGENT, skill: 's', amount: 1, currency_mint: MINT }), res);+ expect(res.statusCode).toBe(401);+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('rejects a write method it does not implement', async () => {+ const res = mkRes();+ await setSkillPrice(mkReq({ url: '/api/marketplace/set-skill-price', method: 'GET' }), res);+ expect(res.statusCode).toBe(405);+ });++ it('demands a CSRF token from a cookie caller', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ csrfOk.value = false;+ const res = mkRes();+ await setSkillPrice(priceReq({ agent_id: AGENT, skill: 's', amount: 1, currency_mint: MINT }), res);+ expect(res.statusCode).toBe(403);+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('answers a malformed body with a field-level 400, never a stack trace', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ const res = mkRes();+ await setSkillPrice(priceReq({ agent_id: 'not-a-uuid', skill: '', amount: -1 }), res);+ expect(res.statusCode).toBe(400);+ expect(parseBody(res).error).toBe('validation_error');+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('will not price an agent the caller does not own', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ sqlQueue = [[{ id: AGENT, user_id: OTHER_USER }]];+ const res = mkRes();+ await setSkillPrice(priceReq({ agent_id: AGENT, skill: 's', amount: 1, currency_mint: MINT }), res);+ expect(res.statusCode).toBe(403);+ expect(parseBody(res).error).toBe('forbidden');+ });++ it('404s a missing agent', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ sqlQueue = [[]];+ const res = mkRes();+ await setSkillPrice(priceReq({ agent_id: AGENT, skill: 's', amount: 1, currency_mint: MINT }), res);+ expect(res.statusCode).toBe(404);+ });++ it('upserts a price and invalidates the quote cache', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ ownedAgent();+ const res = mkRes();+ await setSkillPrice(priceReq({ agent_id: AGENT, skill: 'icon-set', amount: 2_000_000, currency_mint: MINT }), res);+ expect(res.statusCode).toBe(200);+ expect(parseBody(res).data.ok).toBe(true);+ expect(sqlText()[1]).toMatch(/INSERT INTO agent_skill_prices/);+ expect(invalidateSkillPriceCacheMock).toHaveBeenCalledWith(AGENT);+ expect(clearListingSplitMock).not.toHaveBeenCalled();+ });++ it('deactivates the row on amount 0 and clears the split with it', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ ownedAgent();+ const res = mkRes();+ await setSkillPrice(priceReq({ agent_id: AGENT, skill: 'icon-set', amount: 0, currency_mint: MINT }), res);+ expect(res.statusCode).toBe(200);+ expect(clearListingSplitMock).toHaveBeenCalledWith(expect.anything(), AGENT, 'icon-set');+ expect(sqlText()[1]).toMatch(/UPDATE agent_skill_prices SET is_active = false/);+ });++ it('accepts an empty split array as the retraction it is documented to be', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ ownedAgent();+ const res = mkRes();+ await setSkillPrice(priceReq({ agent_id: AGENT, skill: 'icon-set', amount: 5, currency_mint: MINT, split: [] }), res);+ expect(res.statusCode).toBe(200);+ expect(clearListingSplitMock).toHaveBeenCalledWith(expect.anything(), AGENT, 'icon-set');+ expect(sqlText()[1]).toMatch(/INSERT INTO agent_skill_prices/);+ });++ it('treats an explicit null split as a retraction too', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ ownedAgent();+ const res = mkRes();+ await setSkillPrice(priceReq({ agent_id: AGENT, skill: 'icon-set', amount: 5, currency_mint: MINT, split: null }), res);+ expect(res.statusCode).toBe(200);+ expect(clearListingSplitMock).toHaveBeenCalled();+ });++ it('leaves an existing split alone when the caller does not mention one', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ ownedAgent();+ const res = mkRes();+ await setSkillPrice(priceReq({ agent_id: AGENT, skill: 'icon-set', amount: 5, currency_mint: MINT }), res);+ expect(res.statusCode).toBe(200);+ expect(clearListingSplitMock).not.toHaveBeenCalled();+ expect(persistListingSplitMock).not.toHaveBeenCalled();+ });++ it('fails the request when a retraction cannot be written, rather than repricing over a stale split', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ ownedAgent();+ clearListingSplitMock.mockRejectedValue(new Error('deadlock detected'));+ const res = mkRes();+ await expect(+ setSkillPrice(priceReq({ agent_id: AGENT, skill: 'icon-set', amount: 5, currency_mint: MINT, split: [] }), res),+ ).rejects.toThrow('deadlock detected');+ // The price row must NOT have moved: only the ownership SELECT ran.+ expect(sqlText()).toHaveLength(1);+ });++ it('persists a valid split and echoes the recipients back', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ ownedAgent();+ persistListingSplitMock.mockResolvedValue({+ split_mode: 'ledger',+ split_address: null,+ recipients: [+ { address: 'Aaa', share_bps: 6000, label: 'lead' },+ { address: 'Bbb', share_bps: 4000, label: null },+ ],+ });+ const res = mkRes();+ await setSkillPrice(+ priceReq({+ agent_id: AGENT, skill: 'icon-set', amount: 5, currency_mint: MINT,+ split: [{ address: 'Aaa', share_bps: 6000 }, { address: 'Bbb', share_bps: 4000 }],+ }),+ res,+ );+ expect(res.statusCode).toBe(200);+ expect(parseBody(res).data.split.mode).toBe('ledger');+ expect(parseBody(res).data.split.recipients).toHaveLength(2);+ });++ it('surfaces a split that does not sum to 100% as its own 4xx, before the price moves', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ ownedAgent();+ persistListingSplitMock.mockRejectedValue(+ Object.assign(new Error('shares must sum to 100%'), { status: 400, code: 'invalid_split' }),+ );+ const res = mkRes();+ await setSkillPrice(+ priceReq({+ agent_id: AGENT, skill: 'icon-set', amount: 5, currency_mint: MINT,+ split: [{ address: 'Aaa', share_bps: 6000 }],+ }),+ res,+ );+ expect(res.statusCode).toBe(400);+ expect(parseBody(res).error).toBe('invalid_split');+ expect(sqlText()).toHaveLength(1);+ expect(invalidateSkillPriceCacheMock).not.toHaveBeenCalled();+ });++ it('rejects a split larger than the recipient cap', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ const split = Array.from({ length: 51 }, (_, i) => ({ address: `A${i}`, share_bps: 196 }));+ const res = mkRes();+ await setSkillPrice(priceReq({ agent_id: AGENT, skill: 's', amount: 5, currency_mint: MINT, split }), res);+ expect(res.statusCode).toBe(400);+ expect(sqlMock).not.toHaveBeenCalled();+ });+});++describe('GET /api/marketplace/skill-promo', () => {+ const promoReq = (qs) => mkReq({ url: `/api/marketplace/skill-promo${qs}`, method: 'GET' });++ it('rejects a missing or malformed query with a 400, anonymously', async () => {+ const res = mkRes();+ await expect(skillPromo(promoReq('?agent_id=nope&skill='), res)).rejects.toMatchObject({ status: 400 });+ expect(describeSkillPromoMock).not.toHaveBeenCalled();+ });++ it('404s a skill with no active price', async () => {+ describeSkillPromoMock.mockResolvedValue(null);+ const res = mkRes();+ await skillPromo(promoReq(`?agent_id=${AGENT}&skill=icon-set`), res);+ expect(res.statusCode).toBe(404);+ expect(parseBody(res).error).toBe('not_found');+ });++ it('serves the live promo state to an anonymous reader with a short edge cache', async () => {+ describeSkillPromoMock.mockResolvedValue({+ base: { amount: '2000000' },+ effective: { amount: '1000000' },+ promo: { rule_type: 'first_n_purchases', threshold: 10, claimed: 4, spots_left: 6 },+ });+ const res = mkRes();+ await skillPromo(promoReq(`?agent_id=${AGENT}&skill=icon-set`), res);+ expect(res.statusCode).toBe(200);+ expect(parseBody(res).data.promo.spots_left).toBe(6);+ expect(res.headers['cache-control']).toMatch(/max-age=10/);+ expect(describeSkillPromoMock).toHaveBeenCalledWith(AGENT, 'icon-set');+ });++ it('rejects a write method', async () => {+ const res = mkRes();+ await skillPromo(promoReq('?agent_id=x&skill=y'), res, undefined);+ expect(res.statusCode).toBe(404);+ });+});++describe('POST /api/marketplace/start-trial', () => {+ const trialReq = (body, headers) => mkReq({ url: '/api/marketplace/start-trial', body, headers });+ const pricedSkill = (over = {}) => ({+ skill: 'icon-set', trial_uses: 3, amount: '2000000', currency_mint: MINT, chain: 'solana', ...over,+ });++ it('refuses an anonymous caller', async () => {+ const res = mkRes();+ await startTrial(trialReq({ agent_id: AGENT, skill: 'icon-set' }), res);+ expect(res.statusCode).toBe(401);+ });++ it('rejects a write method it does not implement', async () => {+ const res = mkRes();+ await startTrial(mkReq({ url: '/api/marketplace/start-trial', method: 'GET' }), res);+ expect(res.statusCode).toBe(405);+ });++ it('rejects a malformed body with a 400', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ const res = mkRes();+ await expect(startTrial(trialReq({ agent_id: 'nope', skill: '' }), res)).rejects.toMatchObject({ status: 400 });+ });++ it('refuses a skill that grants no free runs', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ sqlQueue = [[{ id: AGENT }], [pricedSkill({ trial_uses: 0 })]];+ const res = mkRes();+ await startTrial(trialReq({ agent_id: AGENT, skill: 'icon-set' }), res);+ expect(res.statusCode).toBe(422);+ expect(parseBody(res).error).toBe('no_trials');+ });++ it('tells an owner they already bought the skill', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ sqlQueue = [[{ id: AGENT }], [pricedSkill()], [{ id: 'p1', status: 'confirmed', trial_remaining: 0 }]];+ const res = mkRes();+ await startTrial(trialReq({ agent_id: AGENT, skill: 'icon-set' }), res);+ expect(res.statusCode).toBe(409);+ expect(parseBody(res).error).toBe('already_owned');+ });++ it('is idempotent for a trial already running', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ sqlQueue = [[{ id: AGENT }], [pricedSkill()], [{ id: 'p1', status: 'trial', trial_remaining: 2 }]];+ const res = mkRes();+ await startTrial(trialReq({ agent_id: AGENT, skill: 'icon-set' }), res);+ expect(res.statusCode).toBe(200);+ expect(parseBody(res).data).toMatchObject({ trial_remaining: 2, already_trialing: true });+ });++ it('grants the trial to a bearer caller, which needs no CSRF token', async () => {+ authenticateBearerMock.mockResolvedValue({ userId: USER });+ sqlQueue = [+ [{ id: AGENT }],+ [pricedSkill()],+ [],+ [],+ [{ id: 'p9', trial_remaining: 3, reference: 'ref', created_at: '2026-08-01T00:00:00.000Z' }],+ ];+ const res = mkRes();+ await startTrial(trialReq({ agent_id: AGENT, skill: 'icon-set' }, { authorization: 'Bearer k' }), res);+ expect(res.statusCode).toBe(201);+ expect(parseBody(res).data).toMatchObject({ trial_remaining: 3, purchase_id: 'p9' });+ });++ it('answers a lost insert race with the 409 it is, not a 500', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ sqlQueue = [[{ id: AGENT }], [pricedSkill()], [], []];+ sqlMock.mockImplementation(async () => {+ if (sqlQueue.length) return sqlQueue.shift();+ // The unique index catches the concurrent second click.+ throw Object.assign(new Error('duplicate key value violates unique constraint'), { code: '23505' });+ });+ const res = mkRes();+ await startTrial(trialReq({ agent_id: AGENT, skill: 'icon-set' }), res);+ expect(res.statusCode).toBe(409);+ expect(parseBody(res).error).toBe('trial_used');+ });++ it('lets a genuine database fault through instead of misreporting it as a used trial', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ sqlQueue = [[{ id: AGENT }], [pricedSkill()], [], []];+ sqlMock.mockImplementation(async () => {+ if (sqlQueue.length) return sqlQueue.shift();+ throw Object.assign(new Error('deadlock detected'), { code: '40P01' });+ });+ const res = mkRes();+ await expect(startTrial(trialReq({ agent_id: AGENT, skill: 'icon-set' }), res)).rejects.toThrow('deadlock');+ });+});diff --git a/tests/marketplace-trial-status.test.js b/tests/marketplace-trial-status.test.jsindex 55986b054..6012065ec 100644--- a/tests/marketplace-trial-status.test.js+++ b/tests/marketplace-trial-status.test.js@@ -1,9 +1,9 @@// GET /api/marketplace/trial-status is the marketplace's conversion surface, and// the number a seller acts on is the money sitting in the trial queue. That// number used to be summed across every mint at once and then labelled with-// whichever mint happened to head the queue, so a seller pricing one skill in-// MINT_6DP and another in an 8-decimal token read a headline that was wrong by-// orders of magnitude. These tests pin the per-mint totals, the trial lifecycle+// whichever mint happened to head the queue, so a seller pricing one skill in a+// 6-decimal mint and another in a 9-decimal one read a headline wrong by orders+// of magnitude. These tests pin the per-mint totals, the trial lifecycle// states the buyer view renders against, the atomic formatter (token amounts// overflow a JS number, so they never go through Number()), and the auth wall.@@ -148,7 +148,7 @@ describe('sellerView', () => {expect(out.role).toBe('seller');expect(out.summary.warmLeads).toBe(3);expect(out.summary.sold).toBe(2);- // MINT_6DP: 2 exhausted x 2 MINT_6DP. $THREE: 1 exhausted x 0.5.+ // 6dp mint: 2 exhausted buyers x 2 each. $THREE: 1 exhausted buyer x 0.5.expect(out.summary.potentials).toEqual([{ mint: MINT_6DP, decimals: 6, atomic: '4000000', display: '4' },{ mint: THREE, decimals: 9, atomic: '500000000', display: '0.5' },diff --git a/tests/oauth-endpoints.test.js b/tests/oauth-endpoints.test.jsnew file mode 100644index 000000000..e2a76fe1a--- /dev/null+++ b/tests/oauth-endpoints.test.js@@ -0,0 +1,512 @@+// api/oauth/[action].js: the OAuth 2.1 authorization server the MCP clients+// connect through (/oauth/authorize, /token, /register, /revoke, /introspect).+//+// It shipped with no test coverage at all, and an audit of it found four live+// defects that these tests pin shut:+// 1. the consent screen listed the scope the client ASKED for while the code+// it issued carried the client's registered scope, so a user could approve+// one set of permissions and grant another;+// 2. `resource` was passed straight through to the token audience, minting a+// credential that every consumer on the platform rejects instead of+// failing with RFC 8707 `invalid_target`;+// 3. dynamic registration accepted `javascript:` and `data:` redirect URIs,+// because zod's .url() is a bare `new URL()` check;+// 4. /oauth/revoke skipped the refresh-token lookup whenever the caller sent+// `token_type_hint=access_token`, answering 200 OK while leaving the token+// live for its full 30-day life (RFC 7009 section 2.1 requires extending+// the search past a hint that does not resolve).+//+// Only the database is doubled. auth.js is real, so PKCE, the JWT mint/verify+// round trip, and refresh-token rotation run their production code here.++import { describe, it, expect, vi, beforeEach } from 'vitest';++process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';+process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';++vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));+vi.mock('../api/_lib/sentry.js', () => ({ captureException: () => {} }));+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));+vi.mock('../api/_lib/streaks.js', () => ({ recordDailyActivity: vi.fn(async () => {}) }));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ authIp: vi.fn(async () => ({ success: true })),+ oauthToken: vi.fn(async () => ({ success: true })),+ oauthRegisterIp: vi.fn(async () => ({ success: true })),+ },+ clientIp: () => '127.0.0.1',+}));++// ── in-memory stand-in for the three oauth tables ────────────────────────────+const db = { clients: [], codes: [], refresh: [] };+const statements = [];++function future(seconds) {+ return new Date(Date.now() + seconds * 1000).toISOString();+}++const sqlMock = vi.fn(async (strings, ...values) => {+ const text = strings.join('?').replace(/\s+/g, ' ').trim();+ statements.push({ text, values });++ if (text.startsWith('select * from oauth_clients where client_id')) {+ const [clientId] = values;+ return db.clients.filter((c) => c.client_id === clientId).slice(0, 1);+ }+ if (text.startsWith('insert into oauth_clients')) {+ const [client_id, client_secret_hash, client_type, name, logo_uri, client_uri, redirect_uris, grant_types, response_types, token_endpoint_auth, scope] = values;+ db.clients.push({ client_id, client_secret_hash, client_type, name, logo_uri, client_uri, redirect_uris, grant_types, response_types, token_endpoint_auth, scope });+ return [];+ }+ if (text.startsWith('insert into oauth_auth_codes')) {+ const [code, client_id, user_id, redirect_uri, scope, resource, code_challenge] = values;+ db.codes.push({ code, client_id, user_id, redirect_uri, scope, resource, code_challenge, code_challenge_method: 'S256', consumed_at: null, expires_at: future(60) });+ return [];+ }+ if (text.startsWith('select * from oauth_auth_codes where code')) {+ const [code] = values;+ return db.codes.filter((c) => c.code === code).slice(0, 1);+ }+ if (text.startsWith('update oauth_auth_codes set consumed_at')) {+ const [code] = values;+ const row = db.codes.find((c) => c.code === code && !c.consumed_at);+ if (!row) return [];+ row.consumed_at = new Date().toISOString();+ return [{ code: row.code }];+ }+ if (text.startsWith('insert into oauth_refresh_tokens')) {+ const [token_hash, client_id, user_id, scope, resource] = values;+ const row = { id: `rt-${db.refresh.length + 1}`, token_hash, client_id, user_id, scope, resource, revoked_at: null, replaced_by: null, expires_at: future(2_592_000) };+ db.refresh.push(row);+ return [{ id: row.id }];+ }+ if (text.startsWith('select id, user_id, scope, resource, expires_at, revoked_at from oauth_refresh_tokens')) {+ const [hash, clientId] = values;+ return db.refresh.filter((r) => r.token_hash === hash && r.client_id === clientId).slice(0, 1);+ }+ if (text.startsWith('select user_id, scope, expires_at, revoked_at from oauth_refresh_tokens')) {+ const [hash, clientId] = values;+ return db.refresh.filter((r) => r.token_hash === hash && r.client_id === clientId).slice(0, 1);+ }+ if (text.startsWith('update oauth_refresh_tokens set revoked_at = now(), replaced_by')) {+ const [replacedBy, id] = values;+ const row = db.refresh.find((r) => r.id === id);+ if (row) { row.revoked_at = new Date().toISOString(); row.replaced_by = replacedBy; }+ return [];+ }+ if (text.startsWith('update oauth_refresh_tokens set revoked_at = now() where token_hash')) {+ const [hash, clientId] = values;+ const row = db.refresh.find((r) => r.token_hash === hash && r.client_id === clientId && !r.revoked_at);+ if (!row) return [];+ row.revoked_at = new Date().toISOString();+ return [{ id: row.id, user_id: row.user_id }];+ }+ if (text.startsWith('update oauth_refresh_tokens set revoked_at = now() where user_id')) {+ const [userId, clientId] = values;+ for (const r of db.refresh) {+ if (r.user_id === userId && r.client_id === clientId && !r.revoked_at) r.revoked_at = new Date().toISOString();+ }+ return [];+ }+ throw new Error(`unmodeled query: ${text}`);+});+vi.mock('../api/_lib/db.js', () => ({ sql: (strings, ...values) => sqlMock(strings, ...values) }));++const getSessionUser = vi.fn();+vi.mock('../api/_lib/auth.js', async () => {+ const actual = await vi.importActual('../api/_lib/auth.js');+ return { ...actual, getSessionUser: (...args) => getSessionUser(...args) };+});++const { default: handler } = await import('../api/oauth/[action].js');+const { csrfTokenFor, verifyAccessToken } = await import('../api/_lib/auth.js');+const { sha256, sha256Base64Url } = await import('../api/_lib/crypto.js');++// ── request/response doubles ─────────────────────────────────────────────────+const SESSION_COOKIE = '__Host-sid=session-token-for-tests';+const ORIGIN = 'https://three.ws';+const RESOURCE = 'https://three.ws/api/mcp';++function makeRes() {+ const r = { statusCode: 200, _h: {}, _b: null };+ r.setHeader = (k, v) => { r._h[k.toLowerCase()] = v; };+ r.getHeader = (k) => r._h[k.toLowerCase()];+ r.end = (b) => { r._b = b === undefined ? '' : b; };+ Object.defineProperty(r, 'body', { get: () => r._b ?? '' });+ Object.defineProperty(r, 'json', { value: () => JSON.parse(r._b) });+ return r;+}++async function call(action, { method = 'GET', query = {}, form, jsonBody, headers = {} } = {}) {+ const search = new URLSearchParams({ action, ...query }).toString();+ const req = {+ method,+ url: `/api/oauth/${action}?${search}`,+ query: { action, ...query },+ headers: { origin: ORIGIN, cookie: SESSION_COOKIE, ...headers },+ socket: { remoteAddress: '127.0.0.1' },+ };+ if (form) {+ req.headers['content-type'] = 'application/x-www-form-urlencoded';+ req.body = new URLSearchParams(form).toString();+ } else if (jsonBody) {+ req.headers['content-type'] = 'application/json';+ req.body = JSON.stringify(jsonBody);+ }+ const res = makeRes();+ await handler(req, res);+ return res;+}++const VERIFIER = 'a'.repeat(64);+let CHALLENGE;++function seedClient(overrides = {}) {+ const client = {+ client_id: 'mcp_test_client',+ client_secret_hash: null,+ client_type: 'public',+ name: 'Test MCP Client',+ redirect_uris: ['https://client.example/cb'],+ grant_types: ['authorization_code', 'refresh_token'],+ response_types: ['code'],+ token_endpoint_auth: 'none',+ scope: 'avatars:read profile',+ ...overrides,+ };+ db.clients.push(client);+ return client;+}++const authorizeQuery = (extra = {}) => ({+ response_type: 'code',+ client_id: 'mcp_test_client',+ redirect_uri: 'https://client.example/cb',+ code_challenge: CHALLENGE,+ code_challenge_method: 'S256',+ ...extra,+});++const csrf = () => csrfTokenFor({ headers: { cookie: SESSION_COOKIE } });++async function approve(extra = {}) {+ return call('authorize', { method: 'POST', form: { ...authorizeQuery(extra), csrf: await csrf(), decision: 'allow' } });+}++async function issueTokens() {+ const authorized = await approve();+ const code = new URL(authorized.getHeader('location')).searchParams.get('code');+ const res = await call('token', { method: 'POST', form: { grant_type: 'authorization_code', client_id: 'mcp_test_client', code, redirect_uri: 'https://client.example/cb', code_verifier: VERIFIER } });+ return res.json();+}++beforeEach(async () => {+ CHALLENGE ||= await sha256Base64Url(VERIFIER);+ db.clients.length = 0;+ db.codes.length = 0;+ db.refresh.length = 0;+ statements.length = 0;+ sqlMock.mockClear();+ getSessionUser.mockReset();+ getSessionUser.mockResolvedValue({ id: 'user-1', email: '[email protected]', display_name: 'Ada' });+});++describe('GET /oauth/authorize', () => {+ it('renders a consent screen listing the scope that will actually be granted', async () => {+ seedClient();+ // The client asks for a scope it never registered. intersectScopes drops it+ // and falls back to the registered scope, so the screen must say so.+ const res = await call('authorize', { query: authorizeQuery({ scope: 'memory:write' }) });+ expect(res.statusCode).toBe(200);+ expect(res.getHeader('content-type')).toContain('text/html');+ expect(res.body).toContain('Read your avatars');+ expect(res.body).toContain('See your name and email');+ expect(res.body).not.toContain('Store and forget');+ });++ it('allows the client origin in form-action so the post-consent 302 is not blocked', async () => {+ seedClient();+ const res = await call('authorize', { query: authorizeQuery() });+ expect(res.getHeader('content-security-policy')).toContain("form-action 'self' https://client.example");+ });++ it('sends an anonymous visitor to /login with the consent URL as the return target', async () => {+ seedClient();+ getSessionUser.mockResolvedValue(null);+ const res = await call('authorize', { query: authorizeQuery() });+ expect(res.statusCode).toBe(302);+ expect(decodeURIComponent(res.getHeader('location'))).toContain('/oauth/consent?');+ });++ it('rejects a redirect_uri the client never registered', async () => {+ seedClient();+ const res = await call('authorize', { query: authorizeQuery({ redirect_uri: 'https://attacker.example/cb' }) });+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('invalid_redirect_uri');+ expect(db.codes).toHaveLength(0);+ });++ it('rejects an unknown resource with invalid_target instead of minting an unusable token', async () => {+ seedClient();+ const res = await call('authorize', { query: authorizeQuery({ resource: 'https://someone-else.example/api' }) });+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('invalid_target');+ expect(db.codes).toHaveLength(0);+ });++ it('rejects a non-S256 PKCE challenge', async () => {+ seedClient();+ const res = await call('authorize', { query: authorizeQuery({ code_challenge_method: 'plain' }) });+ expect(res.statusCode).toBe(400);+ expect(res.json().error_description).toContain('S256');+ });+});++describe('POST /oauth/authorize', () => {+ it('issues a code carrying the intersected scope and the canonical resource', async () => {+ seedClient();+ const res = await approve({ scope: 'profile memory:write' });+ expect(res.statusCode).toBe(302);+ const back = new URL(res.getHeader('location'));+ expect(back.origin + back.pathname).toBe('https://client.example/cb');+ expect(back.searchParams.get('code')).toBeTruthy();+ expect(db.codes[0].scope).toBe('profile');+ expect(db.codes[0].resource).toBe(RESOURCE);+ });++ it('preserves state and returns access_denied when the user cancels', async () => {+ seedClient();+ const res = await call('authorize', { method: 'POST', form: { ...authorizeQuery({ state: 'xyz' }), csrf: await csrf(), decision: 'deny' } });+ const back = new URL(res.getHeader('location'));+ expect(back.searchParams.get('error')).toBe('access_denied');+ expect(back.searchParams.get('state')).toBe('xyz');+ expect(db.codes).toHaveLength(0);+ });++ it('refuses an approval without a valid CSRF token', async () => {+ seedClient();+ const res = await call('authorize', { method: 'POST', form: { ...authorizeQuery(), csrf: 'forged', decision: 'allow' } });+ expect(res.statusCode).toBe(403);+ expect(db.codes).toHaveLength(0);+ });++ it('refuses an approval posted from another origin', async () => {+ seedClient();+ const res = await call('authorize', { method: 'POST', form: { ...authorizeQuery(), csrf: await csrf(), decision: 'allow' }, headers: { origin: 'https://attacker.example' } });+ expect(res.statusCode).toBe(403);+ expect(db.codes).toHaveLength(0);+ });+});++describe('POST /oauth/token', () => {+ it('exchanges a code for a verifiable access token and a refresh token', async () => {+ seedClient();+ const out = await issueTokens();+ expect(out.token_type).toBe('Bearer');+ expect(out.scope).toBe('avatars:read profile');+ expect(out.refresh_token).toBeTruthy();+ const payload = await verifyAccessToken(out.access_token);+ expect(payload.sub).toBe('user-1');+ expect(payload.aud).toBe(RESOURCE);+ expect(payload.client_id).toBe('mcp_test_client');+ });++ it('rejects a wrong PKCE verifier without consuming the code', async () => {+ seedClient();+ const code = new URL((await approve()).getHeader('location')).searchParams.get('code');+ const res = await call('token', { method: 'POST', form: { grant_type: 'authorization_code', client_id: 'mcp_test_client', code, redirect_uri: 'https://client.example/cb', code_verifier: 'b'.repeat(64) } });+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('invalid_grant');+ expect(db.codes[0].consumed_at).toBeNull();+ });++ it('rejects a redirect_uri that differs from the one the code was issued for', async () => {+ seedClient({ redirect_uris: ['https://client.example/cb', 'https://client.example/other'] });+ const code = new URL((await approve()).getHeader('location')).searchParams.get('code');+ const res = await call('token', { method: 'POST', form: { grant_type: 'authorization_code', client_id: 'mcp_test_client', code, redirect_uri: 'https://client.example/other', code_verifier: VERIFIER } });+ expect(res.statusCode).toBe(400);+ expect(res.json().error_description).toContain('redirect_uri mismatch');+ });++ it('revokes the issued tokens when a code is replayed', async () => {+ seedClient();+ const code = new URL((await approve()).getHeader('location')).searchParams.get('code');+ const form = { grant_type: 'authorization_code', client_id: 'mcp_test_client', code, redirect_uri: 'https://client.example/cb', code_verifier: VERIFIER };+ await call('token', { method: 'POST', form });+ const replay = await call('token', { method: 'POST', form });+ expect(replay.statusCode).toBe(400);+ expect(replay.json().error_description).toContain('already used');+ expect(db.refresh.every((r) => r.revoked_at)).toBe(true);+ });++ it('rotates a refresh token and refuses to widen the scope back', async () => {+ seedClient();+ const first = await issueTokens();++ const narrowed = await call('token', { method: 'POST', form: { grant_type: 'refresh_token', client_id: 'mcp_test_client', refresh_token: first.refresh_token, scope: 'profile' } });+ expect(narrowed.statusCode).toBe(200);+ expect(narrowed.json().scope).toBe('profile');++ const widened = await call('token', { method: 'POST', form: { grant_type: 'refresh_token', client_id: 'mcp_test_client', refresh_token: narrowed.json().refresh_token, scope: 'avatars:read profile' } });+ expect(widened.statusCode).toBe(400);+ expect(widened.json().error).toBe('invalid_scope');+ });++ it('detects refresh-token reuse and kills the whole chain', async () => {+ seedClient();+ const first = await issueTokens();+ await call('token', { method: 'POST', form: { grant_type: 'refresh_token', client_id: 'mcp_test_client', refresh_token: first.refresh_token } });+ const reuse = await call('token', { method: 'POST', form: { grant_type: 'refresh_token', client_id: 'mcp_test_client', refresh_token: first.refresh_token } });+ expect(reuse.statusCode).toBe(400);+ expect(reuse.json().error).toBe('refresh_reuse_detected');+ expect(db.refresh.every((r) => r.revoked_at)).toBe(true);+ });++ it('rejects a confidential client presenting the wrong secret', async () => {+ seedClient({ client_type: 'confidential', client_secret_hash: await sha256('the-real-secret'), token_endpoint_auth: 'client_secret_post' });+ const res = await call('token', { method: 'POST', form: { grant_type: 'authorization_code', client_id: 'mcp_test_client', client_secret: 'guessed', code: 'x', redirect_uri: 'https://client.example/cb', code_verifier: VERIFIER } });+ expect(res.statusCode).toBe(401);+ expect(res.json().error).toBe('invalid_client');+ });++ it('reports an unsupported grant type', async () => {+ seedClient();+ const res = await call('token', { method: 'POST', form: { grant_type: 'client_credentials', client_id: 'mcp_test_client' } });+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('unsupported_grant_type');+ });+});++describe('POST /oauth/register', () => {+ it('registers a public client and drops privileged scopes it asked for', async () => {+ const res = await call('register', { method: 'POST', jsonBody: { redirect_uris: ['https://client.example/cb'], client_name: 'Probe', scope: 'avatars:read permissions:redeem' } });+ expect(res.statusCode).toBe(201);+ const out = res.json();+ expect(out.client_id).toMatch(/^mcp_/);+ expect(out.scope).toBe('avatars:read');+ expect(out.client_secret).toBeUndefined();+ });++ it('returns a one-time secret for a confidential client and stores only its hash', async () => {+ const res = await call('register', { method: 'POST', jsonBody: { redirect_uris: ['https://client.example/cb'], token_endpoint_auth_method: 'client_secret_basic' } });+ const out = res.json();+ expect(out.client_secret).toBeTruthy();+ expect(db.clients[0].client_secret_hash).toBe(await sha256(out.client_secret));+ expect(db.clients[0].client_secret_hash).not.toBe(out.client_secret);+ });++ it.each([+ ['javascript:alert(document.cookie)'],+ ['data:text/html,<script>alert(1)</script>'],+ ['file:///etc/passwd'],+ ['vbscript:msgbox(1)'],+ ])('refuses the executable redirect URI %s', async (uri) => {+ const res = await call('register', { method: 'POST', jsonBody: { redirect_uris: [uri] } });+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('invalid_redirect_uri');+ expect(db.clients).toHaveLength(0);+ });++ it('still accepts loopback http and native private-use redirect URIs', async () => {+ const res = await call('register', { method: 'POST', jsonBody: { redirect_uris: ['http://127.0.0.1:8976/cb', 'http://localhost:1410/cb', 'com.example.app:/oauth2redirect', 'myapp://callback'] } });+ expect(res.statusCode).toBe(201);+ });++ it('refuses plain http on a public host', async () => {+ const res = await call('register', { method: 'POST', jsonBody: { redirect_uris: ['http://attacker.example/cb'] } });+ expect(res.statusCode).toBe(400);+ expect(res.json().error_description).toContain('localhost');+ });++ it('refuses metadata naming a grant or response type this server does not support', async () => {+ const implicit = await call('register', { method: 'POST', jsonBody: { redirect_uris: ['https://client.example/cb'], grant_types: ['authorization_code', 'implicit'] } });+ expect(implicit.statusCode).toBe(400);+ expect(implicit.json().error).toBe('invalid_client_metadata');++ const token = await call('register', { method: 'POST', jsonBody: { redirect_uris: ['https://client.example/cb'], response_types: ['token'] } });+ expect(token.statusCode).toBe(400);+ expect(token.json().error).toBe('invalid_client_metadata');+ expect(db.clients).toHaveLength(0);+ });++ it('rejects a body that carries no redirect_uris at all', async () => {+ const res = await call('register', { method: 'POST', jsonBody: { redirect_uris: [] } });+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('validation_error');+ });+});++describe('POST /oauth/revoke', () => {+ it('revokes a refresh token', async () => {+ seedClient();+ const { refresh_token } = await issueTokens();+ const res = await call('revoke', { method: 'POST', form: { token: refresh_token, client_id: 'mcp_test_client' } });+ expect(res.statusCode).toBe(200);+ expect(db.refresh[0].revoked_at).toBeTruthy();+ });++ it('revokes a refresh token even when the caller hints the wrong token type', async () => {+ seedClient();+ const { refresh_token } = await issueTokens();+ const res = await call('revoke', { method: 'POST', form: { token: refresh_token, token_type_hint: 'access_token', client_id: 'mcp_test_client' } });+ expect(res.statusCode).toBe(200);+ expect(db.refresh[0].revoked_at).toBeTruthy();+ });++ it('answers 200 for an unknown client without disclosing that it is unknown', async () => {+ const res = await call('revoke', { method: 'POST', form: { token: 'whatever', client_id: 'mcp_nope' } });+ expect(res.statusCode).toBe(200);+ expect(res.json()).toEqual({});+ });+});++describe('POST /oauth/introspect', () => {+ it('reports an access token as active with its scope and subject', async () => {+ seedClient();+ const tokens = await issueTokens();+ const res = await call('introspect', { method: 'POST', form: { token: tokens.access_token, client_id: 'mcp_test_client' } });+ expect(res.json()).toMatchObject({ active: true, sub: 'user-1', scope: 'avatars:read profile', token_type: 'Bearer' });+ });++ it('reports a refresh token as active', async () => {+ seedClient();+ const tokens = await issueTokens();+ const res = await call('introspect', { method: 'POST', form: { token: tokens.refresh_token, client_id: 'mcp_test_client' } });+ expect(res.json()).toMatchObject({ active: true, sub: 'user-1', token_type: 'refresh_token' });+ });++ it('will not confirm a token that belongs to another client', async () => {+ seedClient();+ const tokens = await issueTokens();+ seedClient({ client_id: 'mcp_other', redirect_uris: ['https://other.example/cb'] });+ const res = await call('introspect', { method: 'POST', form: { token: tokens.access_token, client_id: 'mcp_other' } });+ expect(res.json()).toEqual({ active: false });+ });++ it('reports a revoked refresh token as inactive', async () => {+ seedClient();+ const tokens = await issueTokens();+ await call('revoke', { method: 'POST', form: { token: tokens.refresh_token, client_id: 'mcp_test_client' } });+ const res = await call('introspect', { method: 'POST', form: { token: tokens.refresh_token, client_id: 'mcp_test_client' } });+ expect(res.json()).toEqual({ active: false });+ });++ it('reports a garbage token as inactive rather than erroring', async () => {+ seedClient();+ const res = await call('introspect', { method: 'POST', form: { token: 'not-a-token', client_id: 'mcp_test_client' } });+ expect(res.json()).toEqual({ active: false });+ });+});++describe('dispatcher', () => {+ it('404s an unknown action', async () => {+ const res = await call('bogus');+ expect(res.statusCode).toBe(404);+ expect(res.json().error).toBe('not_found');+ });++ it('rejects a method the action does not serve', async () => {+ const res = await call('token', { method: 'GET' });+ expect(res.statusCode).toBe(405);+ });+});