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
fix(mcp): stop a spoofed host, a url() background, and a DB outage from lying to MCP callers
nirholas60291282e602
diff --git a/api/_mcp/origin.js b/api/_mcp/origin.jsindex 4f859f9e8..399d33490 100644--- a/api/_mcp/origin.js+++ b/api/_mcp/origin.js@@ -4,12 +4,19 @@// request Host header, then VERCEL_URL. Shared by every tool that emits links// (animation catalogue fetches, embed snippets) so origin resolution lives in// exactly one place.+// Loopback hosts are the only ones served over plain http; everything else is+// https. Anchored on the whole header value (with its optional port) because an+// unanchored alternation matched the loopback literal ANYWHERE in the host, so+// remote names like "evil-127.0.0.1.example.com" and "localhost.evil.com" got+// http:// links built for them.+const LOOPBACK_HOST = /^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/i;+export function resolveOrigin(req) {const env =process.env.APP_ORIGIN || process.env.PUBLIC_ORIGIN || process.env.PUBLIC_APP_ORIGIN;if (env) return env.replace(/\/$/, '');const host = req?.headers?.host;- if (host) return `${/^localhost|127\.0\.0\.1/.test(host) ? 'http' : 'https'}://${host}`;+ if (host) return `${LOOPBACK_HOST.test(host) ? 'http' : 'https'}://${host}`;if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`;throw new Error('cannot resolve site origin');}diff --git a/api/_mcp/render.js b/api/_mcp/render.jsindex f72a39518..e41973bc1 100644--- a/api/_mcp/render.js+++ b/api/_mcp/render.js@@ -18,6 +18,11 @@ export function safeCssValue(s, fallback) {if (!s) return fallback;const str = String(s).trim();if (!/^[a-zA-Z0-9 .,%#()\-_/+]+$/.test(str)) return fallback;+ // The character class alone still admits `url(//host/pixel.png)`: parens and+ // slashes are legal in gradients, so a caller-supplied background could make+ // the rendered viewer fetch an arbitrary external resource (a beacon that+ // leaks the viewer's IP and referrer). Colors and gradients never need url().+ if (/url\s*\(/i.test(str)) return fallback;if (str.length > 120) return fallback;return str;}@@ -42,6 +47,16 @@ export function safeHttpsUrl(s) {}export function renderModelViewerHtml({ src, name, poster, background, height, width, autoRotate, ar, arHref, cameraOrbit }) {+ // Re-sanitize here rather than trusting each call site. The CSS values land+ // inside a <style> declaration where attribute-escaping does not stop a+ // `;}body{...}` breakout, and every helper below is idempotent, so a caller+ // that already ran them (the avatar + studio tools) is unaffected while a+ // future one that forgets cannot open a hole.+ const bg = safeCssValue(background, 'transparent');+ const h = safeCssLength(height, '480px');+ const w = safeCssLength(width, '100%');+ const orbit = safeCssValue(cameraOrbit, '');+ const posterUrl = safeHttpsUrl(poster);const attrs = [`src="${attr(src)}"`,'camera-controls',@@ -50,8 +65,8 @@ export function renderModelViewerHtml({ src, name, poster, background, height, w'tone-mapping="aces"',autoRotate ? 'auto-rotate' : '',ar ? 'ar ar-modes="webxr scene-viewer quick-look"' : '',- poster ? `poster="${attr(poster)}"` : '',- cameraOrbit ? `camera-orbit="${attr(cameraOrbit)}"` : '',+ posterUrl ? `poster="${attr(posterUrl)}"` : '',+ orbit ? `camera-orbit="${attr(orbit)}"` : '',`alt="${attr(name || 'Avatar')}"`,].filter(Boolean)@@ -67,8 +82,8 @@ export function renderModelViewerHtml({ src, name, poster, background, height, w'<!doctype html>','<html><head><meta charset="utf-8"><title>' + esc(name || 'Avatar') + '</title>','<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>',- '<style>html,body{margin:0;height:100%;background:' + attr(background) + '}',- 'model-viewer{width:' + attr(width) + ';height:' + attr(height) + ';--progress-bar-color:#6a5cff}',+ '<style>html,body{margin:0;height:100%;background:' + attr(bg) + '}',+ 'model-viewer{width:' + attr(w) + ';height:' + attr(h) + ';--progress-bar-color:#6a5cff}','a.ar{position:absolute;left:50%;transform:translateX(-50%);bottom:14px;font-family:ui-sans-serif,system-ui,sans-serif;' +'font-size:13px;font-weight:700;color:#0b0c10;background:#6ea8fe;border-radius:999px;padding:9px 16px;' +'text-decoration:none;box-shadow:0 2px 10px rgba(0,0,0,.35)}',diff --git a/api/_mcp/tools/animations.js b/api/_mcp/tools/animations.jsindex 6929325b6..219be6e1a 100644--- a/api/_mcp/tools/animations.js+++ b/api/_mcp/tools/animations.js@@ -61,6 +61,15 @@ async function loadSignatures(origin) {return index;}+// Own-property lookup only. The index comes back from JSON.parse, so it carries+// Object.prototype: a caller-supplied clip name of "constructor" or "toString"+// would otherwise resolve an inherited member, sail past the not-found guard,+// and be measured as if it were a motion signature. Same defense dispatch.js+// applies to the tool table.+function signatureFor(index, clip) {+ return Object.hasOwn(index.clips, clip) ? index.clips[clip] : null;+}+async function loadClipJSON(origin, def) {// def.url is a site-relative path like /animations/clips/idle.jsonconst res = await fetch(`${origin}${def.url}`, { cache: 'no-store' });@@ -251,7 +260,7 @@ export const toolDefs = [async handler(args, auth, req) {const origin = resolveOrigin(req);const index = await loadSignatures(origin);- const sig = index.clips[String(args.clip)];+ const sig = signatureFor(index, String(args.clip));if (!sig) {throw rpcError(-32602, `No signature for "${args.clip}". Use list_animations for valid names.`);}@@ -305,7 +314,7 @@ export const toolDefs = [async handler(args, auth, req) {const origin = resolveOrigin(req);const index = await loadSignatures(origin);- if (!index.clips[String(args.clip)]) {+ if (!signatureFor(index, String(args.clip))) {throw rpcError(-32602, `No signature for "${args.clip}". Use list_animations for valid names.`);}const limit = Math.max(1, Math.min(20, Number.parseInt(args.limit ?? 5, 10) || 5));diff --git a/api/_mcp/tools/avatars.js b/api/_mcp/tools/avatars.jsindex 22a08b82d..25d0df105 100644--- a/api/_mcp/tools/avatars.js+++ b/api/_mcp/tools/avatars.js@@ -185,11 +185,14 @@ export const toolDefs = [// surfaces.mcp gate — check if a registered agent owns this avatarconst _mcpPolicy = await readMcpPolicyByAvatar(avatar.id);if (_mcpPolicy && _mcpPolicy.surfaces?.mcp === false) {- throw rpcError(- -32000,- 'embed_denied_surface',- 'This agent disallows the MCP surface.',- );+ // Slug in `message`, detail in the `data` object: the shape every+ // other rpcError call site in the MCP tools uses. Passing the+ // sentence as `data` instead left clients with a bare+ // "embed_denied_surface" and no explanation to show a user.+ throw rpcError(-32000, 'embed_denied_surface', {+ reason: 'This agent disallows the MCP surface.',+ avatar_id: avatar.id,+ });}const urlInfo = await resolveAvatarUrl(avatar, { expiresIn: 3600 });const html = renderModelViewerHtml({diff --git a/api/_mcp/tools/trader.js b/api/_mcp/tools/trader.jsindex 000677cb9..e123f7822 100644--- a/api/_mcp/tools/trader.js+++ b/api/_mcp/tools/trader.js@@ -17,7 +17,7 @@// copy_status — auth-gated (agents:read). Check the caller's active// copy subscriptions and their execution counts.-import { sql } from '../../_lib/db.js';+import { sql, isDbUnavailableError } from '../../_lib/db.js';import { limits } from '../../_lib/rate-limit.js';import { getLeaderboard, getTraderStats, WINDOWS, LEADERBOARD_SORTS } from '../../_lib/trader-stats.js';import { normalizeSubscriptionInput } from '../../_lib/copy-engine.js';@@ -38,6 +38,18 @@ function mcpErr(msg) {return { content: [{ type: 'text', text: msg }], isError: true };}+// A DB outage and a genuine "no such row" used to look identical here: every+// query was wrapped in `.catch(() => [])`, so a dropped Neon connection told the+// caller their leader did not exist or that they had no subscriptions. That is a+// wrong answer, not a degraded one, and an agent acts on it. Now only transport+// and configuration failures are folded into an explicit "temporarily+// unavailable" reply; a real SQL fault propagates to the MCP dispatcher, which+// sanitizes it, logs it with an id, and returns isError.+function unavailable(err, what) {+ if (!isDbUnavailableError(err)) throw err;+ return mcpErr(`${what} is temporarily unavailable. Retry in a moment.`);+}+const LIVE = { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true };const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };@@ -95,14 +107,21 @@ export const toolDefs = [const network = NETWORKS.has(args?.network) ? args.network : 'mainnet';const window = WINDOWS.has(args?.window) ? args.window : '30d';const sort = SORTS.has(args?.sort) ? args.sort : 'score';- const limit = Math.min(50, Math.max(1, Number(args?.limit ?? 10)));+ const asked = Number(args?.limit ?? 10);+ // A non-finite limit reached getLeaderboard's `.slice(0, NaN)` and+ // silently returned an empty board that read as "no traders".+ 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');- if (!rl.success) return mcpErr('Rate limit exceeded — try again in a moment.');+ if (!rl.success) return mcpErr('Rate limit exceeded, try again in a moment.');- const result = await getLeaderboard({ network, window, sort, limit, verifiedOnly }).catch(() => null);- if (!result) return mcpErr('Leaderboard unavailable — try again shortly.');+ let result;+ try {+ result = await getLeaderboard({ network, window, sort, limit, verifiedOnly });+ } catch (err) {+ return unavailable(err, 'The trader leaderboard');+ }const traders = (result.leaderboard || []).map(shapeLeaderboardRow);const copyCount = traders.filter((t) => t.recommendation === 'copy').length;@@ -149,9 +168,14 @@ export const toolDefs = [const window = WINDOWS.has(args?.window) ? args.window : 'all';const rl = await limits.mcpIp(auth.rateKey || 'anon');- if (!rl.success) return mcpErr('Rate limit exceeded — try again in a moment.');+ if (!rl.success) return mcpErr('Rate limit exceeded, try again in a moment.');- const stats = await getTraderStats({ agentId, network, window }).catch(() => null);+ let stats;+ try {+ stats = await getTraderStats({ agentId, network, window });+ } catch (err) {+ return unavailable(err, 'This trader profile');+ }if (!stats) return mcpErr(`Agent ${agentId} not found or has no public trading history.`);if (!stats.agent.is_public) return mcpErr('This agent\'s track record is not public.');@@ -168,6 +192,19 @@ export const toolDefs = [proof_url: t.sell_solscan || t.buy_solscan || null,}));+ // The tool description promises open positions; only the count was ever+ // returned, so an agent vetting a leader could not see what they are+ // currently holding. Same shape the /trader page renders.+ const openPositions = (stats.open || []).map((p) => ({+ symbol: p.symbol,+ mint: p.mint,+ entry_sol: p.entry_sol,+ current_sol: p.current_sol,+ unrealized_pct: p.unrealized_pct,+ opened_at: p.opened_at,+ 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 payload = {@@ -199,6 +236,7 @@ export const toolDefs = [copiers: stats.agent.copiers,oracle: stats.oracle ?? null,recent_trades: topTrades,+ open_positions: openPositions,profile_url: `https://three.ws/trader/${agentId}`,generated_at: new Date().toISOString(),};@@ -248,13 +286,21 @@ export const toolDefs = [const network = NETWORKS.has(args?.network) ? args.network : 'mainnet';+ const rl = await limits.mcpIp(auth.rateKey || 'anon');+ if (!rl.success) return mcpErr('Rate limit exceeded, try again in a moment.');+// Validate leader exists and is public- const [leader] = await sql`- select id, name, is_public from agent_identities- where id = ${leaderId} and deleted_at is null limit 1- `.catch(() => []);+ let leader;+ try {+ [leader] = await sql`+ select id, name, is_public from agent_identities+ where id = ${leaderId} and deleted_at is null limit 1+ `;+ } catch (err) {+ return unavailable(err, 'Copy-trading setup');+ }if (!leader) return mcpErr(`Leader agent ${leaderId} not found.`);- if (leader.is_public === false) return mcpErr('That agent\'s trades are not public — cannot copy them.');+ if (leader.is_public === false) return mcpErr('That agent\'s trades are not public, so they cannot be copied.');const raw = {sizing_rule: args?.sizing_rule ?? 'fixed',@@ -276,60 +322,75 @@ export const toolDefs = [if (!norm.ok) return mcpErr(`Invalid subscription parameters: ${norm.error}`);const cfg = norm.value;- // Upsert: create or update existing subscription for this user+leader+network- const [existing] = await sql`- select id, status from copy_subscriptions- where copier_user_id = ${auth.userId}- and leader_agent_id = ${leaderId}- and network = ${network}- limit 1- `.catch(() => []);+ // Denormalize the leader's trading wallet from their most recent position,+ // exactly as POST /api/copy/subscriptions does. Without it the row carries a+ // null leader_wallet and /api/copy/settle-fee refuses the leader's+ // performance fee with leader_wallet_unknown, so an MCP-created+ // subscription could never pay its leader. coalesce on update keeps a+ // previously recorded wallet when the leader has no position on this+ // network yet.+ let leaderWallet;+ try {+ const [pos] = await sql`+ select wallet from agent_sniper_positions+ where agent_id = ${leaderId} and network = ${network}+ order by opened_at desc limit 1+ `;+ leaderWallet = pos?.wallet || null;+ } catch (err) {+ return unavailable(err, 'Copy-trading setup');+ }+ // One atomic upsert against the (copier_user_id, leader_agent_id, network)+ // unique key. The previous select-then-insert lost the race between two+ // concurrent calls and failed the second with a raw unique violation.+ // `xmax = 0` is true only for the row this statement inserted, which is how+ // 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.let sub;- if (existing) {- [sub] = await sql`- update copy_subscriptions set- copier_wallet = ${wallet},- sizing_rule = ${cfg.sizing_rule},- fixed_sol = ${cfg.fixed_sol ?? null},- multiplier = ${cfg.multiplier ?? null},- pct_balance = ${cfg.pct_balance ?? null},- per_trade_cap_sol = ${cfg.per_trade_cap_sol},- min_order_sol = ${cfg.min_order_sol},- daily_budget_sol = ${cfg.daily_budget_sol},- max_open_copies = ${cfg.max_open_copies},- min_oracle_score = ${cfg.min_oracle_score ?? null},- mcap_floor_usd = ${cfg.mcap_floor_usd ?? null},- mcap_ceiling_usd = ${cfg.mcap_ceiling_usd ?? null},- telegram_chat_id = ${cfg.telegramChatId ?? null},- perf_fee_bps = ${cfg.perf_fee_bps},- status = 'active',- updated_at = now()- where id = ${existing.id}- returning id, status, created_at, updated_at- `;- } else {+ try {[sub] = await sql`insert into copy_subscriptions (- copier_user_id, leader_agent_id, network, copier_wallet,+ copier_user_id, leader_agent_id, leader_wallet, network, copier_wallet,sizing_rule, fixed_sol, multiplier, pct_balance,per_trade_cap_sol, min_order_sol, daily_budget_sol, max_open_copies,min_oracle_score, mcap_floor_usd, mcap_ceiling_usd, telegram_chat_id,perf_fee_bps, status) values (- ${auth.userId}, ${leaderId}, ${network}, ${wallet},- ${cfg.sizing_rule}, ${cfg.fixed_sol ?? null}, ${cfg.multiplier ?? null}, ${cfg.pct_balance ?? null},+ ${auth.userId}, ${leaderId}, ${leaderWallet}, ${network}, ${wallet},+ ${cfg.sizing_rule}, ${cfg.fixed_sol}, ${cfg.multiplier}, ${cfg.pct_balance},${cfg.per_trade_cap_sol}, ${cfg.min_order_sol}, ${cfg.daily_budget_sol}, ${cfg.max_open_copies},- ${cfg.min_oracle_score ?? null}, ${cfg.mcap_floor_usd ?? null}, ${cfg.mcap_ceiling_usd ?? null},- ${cfg.telegramChatId ?? null}, ${cfg.perf_fee_bps}, 'active'+ ${cfg.min_oracle_score}, ${cfg.mcap_floor_usd}, ${cfg.mcap_ceiling_usd}, ${cfg.telegramChatId ?? null},+ ${cfg.perf_fee_bps}, 'active')- returning id, status, created_at, updated_at+ on conflict (copier_user_id, leader_agent_id, network) do update set+ copier_wallet = excluded.copier_wallet,+ leader_wallet = coalesce(excluded.leader_wallet, copy_subscriptions.leader_wallet),+ sizing_rule = excluded.sizing_rule,+ fixed_sol = excluded.fixed_sol,+ multiplier = excluded.multiplier,+ pct_balance = excluded.pct_balance,+ per_trade_cap_sol = excluded.per_trade_cap_sol,+ 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,+ perf_fee_bps = excluded.perf_fee_bps,+ status = 'active',+ updated_at = now()+ returning id, status, created_at, updated_at, (xmax = 0) as inserted`;+ } catch (err) {+ return unavailable(err, 'Copy-trading setup');}- if (!sub) return mcpErr('Failed to save copy subscription — try again.');+ if (!sub) return mcpErr('Failed to save the copy subscription. Try again.');- const isNew = !existing;+ const isNew = sub.inserted !== false;const sizeLabel = cfg.sizing_rule === 'fixed'? `${cfg.fixed_sol} SOL fixed`: cfg.sizing_rule === 'multiplier'@@ -382,26 +443,31 @@ export const toolDefs = [if (!auth.userId) return mcpErr('Sign in to view your copy subscriptions.');const rl = await limits.mcpIp(auth.rateKey || 'anon');- if (!rl.success) return mcpErr('Rate limit exceeded — try again in a moment.');+ if (!rl.success) return mcpErr('Rate limit exceeded, try again in a moment.');const network = NETWORKS.has(args?.network) ? args.network : 'mainnet';- const rows = await sql`- select s.id, s.leader_agent_id, s.status, s.network,- s.copier_wallet, s.sizing_rule, s.fixed_sol, s.multiplier, s.pct_balance,- s.per_trade_cap_sol, s.daily_budget_sol, s.max_open_copies,- s.min_oracle_score, s.perf_fee_bps, s.created_at, s.updated_at,- a.name as leader_name, a.profile_image_url as leader_image,- (select count(*) from copy_executions e- where e.subscription_id = s.id and e.status = 'pending') as pending_count,- (select count(*) from copy_executions e- where e.subscription_id = s.id and e.status = 'acted') as acted_count- from copy_subscriptions s- join agent_identities a on a.id = s.leader_agent_id- where s.copier_user_id = ${auth.userId} and s.network = ${network}- and s.status not in ('stopped')- order by s.created_at desc- `.catch(() => []);+ let rows;+ try {+ rows = await sql`+ select s.id, s.leader_agent_id, s.status, s.network,+ s.copier_wallet, s.sizing_rule, s.fixed_sol, s.multiplier, s.pct_balance,+ s.per_trade_cap_sol, s.daily_budget_sol, s.max_open_copies,+ s.min_oracle_score, s.perf_fee_bps, s.created_at, s.updated_at,+ a.name as leader_name, a.profile_image_url as leader_image,+ (select count(*) from copy_executions e+ where e.subscription_id = s.id and e.status = 'pending') as pending_count,+ (select count(*) from copy_executions e+ where e.subscription_id = s.id and e.status = 'acted') as acted_count+ from copy_subscriptions s+ join agent_identities a on a.id = s.leader_agent_id+ where s.copier_user_id = ${auth.userId} and s.network = ${network}+ and s.status not in ('stopped')+ order by s.created_at desc+ `;+ } catch (err) {+ return unavailable(err, 'Your copy subscriptions list');+ }const subs = rows.map((s) => ({id: s.id,@@ -426,16 +492,24 @@ export const toolDefs = [profile_url: `https://three.ws/trader/${s.leader_agent_id}`,}));+ // The query keeps paused rows (only 'stopped' is filtered out), so counting+ // them all as active misreported a paused subscription as live.+ const activeCount = subs.filter((s) => s.status === 'active').length;+ const pausedCount = subs.length - activeCount;+ const pendingTotal = subs.reduce((n, s) => n + s.pending_intents, 0);+const payload = {user_id: auth.userId,network,count: subs.length,+ active_count: activeCount,+ paused_count: pausedCount,subscriptions: subs,- pending_total: subs.reduce((n, s) => n + s.pending_intents, 0),+ pending_total: pendingTotal,acted_total: subs.reduce((n, s) => n + s.acted_intents, 0),hint: subs.length === 0- ? 'No active copy subscriptions. Use trader_leaderboard to find top performers, then copy_subscribe to mirror them.'- : `${subs.length} active subscription${subs.length !== 1 ? 's' : ''}. ${subs.reduce((n, s) => n + s.pending_intents, 0)} intents waiting to be acted on.`,+ ? 'No copy subscriptions yet. Use trader_leaderboard to find top performers, then copy_subscribe to mirror them.'+ : `${activeCount} active subscription${activeCount !== 1 ? 's' : ''}${pausedCount ? ` (plus ${pausedCount} paused)` : ''}. ${pendingTotal} intent${pendingTotal !== 1 ? 's' : ''} waiting to be acted on.`,links: {dashboard: 'https://three.ws/dashboard/copy',leaderboard: 'https://three.ws/leaderboard',diff --git a/tests/api/mcp-payments-embed-policy.test.js b/tests/api/mcp-payments-embed-policy.test.jsnew file mode 100644index 000000000..1b95d5742--- /dev/null+++ b/tests/api/mcp-payments-embed-policy.test.js@@ -0,0 +1,159 @@+// api/_mcp/payments.js and api/_mcp/embed-policy.js — the two small shared+// modules the MCP servers reach for on the paid path and the embed gate.+//+// payments.js is the single error boundary for every hand-rolled x402 MCP+// endpoint (/api/mcp, /api/mcp-3d, /api/mcp-agent, /api/mcp-bazaar,+// /api/ibm-mcp, /api/okx/3d/*). It has to tell three cases apart: a genuine+// "pay me" (402 with the full payment envelope), a client's own fault (the+// X402Error's own status and code), and an unexpected server fault (a 500 that+// leaks nothing but a support reference). Getting the third case wrong is how a+// driver stack trace reaches a paying agent, so all three are pinned here.+//+// embed-policy.js is the MCP surface's view of an agent's embed policy. The one+// thing render_avatar depends on is that a caller-supplied avatar id that is not+// a uuid never reaches the database.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const send402Mock = vi.fn(async (res) => {+ res.statusCode = 402;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.end(JSON.stringify({ x402Version: 1, accepts: [] }));+});++vi.mock('../../api/_lib/x402-spec.js', async (importOriginal) => ({+ ...(await importOriginal()),+ send402: (...a) => send402Mock(...a),+}));++const reportServerErrorMock = vi.fn(() => 'ref_abc123');+vi.mock('../../api/_lib/http.js', async (importOriginal) => ({+ ...(await importOriginal()),+ reportServerError: (...a) => reportServerErrorMock(...a),+}));++const sqlMock = vi.fn(async () => []);+vi.mock('../../api/_lib/db.js', () => ({+ sql: (...a) => sqlMock(...a),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const { X402Error } = await import('../../api/_lib/x402-errors.js');+const { sendX402Error, reservePaymentProof } = await import('../../api/_mcp/payments.js');+const { readMcpPolicyByAvatar } = await import('../../api/_mcp/embed-policy.js');++function mkRes() {+ const headers = {};+ return {+ statusCode: 200,+ body: null,+ headers,+ setHeader(k, v) {+ headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return headers[k.toLowerCase()];+ },+ end(body) {+ this.body = body;+ },+ };+}++const CTX = { resourceUrl: 'https://three.ws/api/mcp', accepts: [{ scheme: 'exact' }] };++beforeEach(() => {+ send402Mock.mockClear();+ reportServerErrorMock.mockClear();+ sqlMock.mockReset();+ sqlMock.mockResolvedValue([]);+});++// ── payments.js ─────────────────────────────────────────────────────────────+describe('sendX402Error', () => {+ it('re-issues the full payment envelope for a 402 X402Error', async () => {+ const res = mkRes();+ await sendX402Error(res, CTX, new X402Error('payment_required', 'pay first', 402));++ expect(send402Mock).toHaveBeenCalledTimes(1);+ const [, opts] = send402Mock.mock.calls[0];+ expect(opts.resourceUrl).toBe(CTX.resourceUrl);+ expect(opts.accepts).toBe(CTX.accepts);+ expect(opts.error).toBe('pay first');+ expect(res.statusCode).toBe(402);+ // A payment fault is the caller's problem, never ours to report.+ expect(reportServerErrorMock).not.toHaveBeenCalled();+ });++ it('passes a non-402 X402Error through with its own status and code', async () => {+ const res = mkRes();+ await sendX402Error(res, CTX, new X402Error('unsupported_network', 'unsupported network: foo', 400));++ expect(send402Mock).not.toHaveBeenCalled();+ expect(res.statusCode).toBe(400);+ expect(res.headers['content-type']).toBe('application/json; charset=utf-8');+ expect(JSON.parse(res.body)).toEqual({+ error: 'unsupported_network',+ error_description: 'unsupported network: foo',+ });+ expect(reportServerErrorMock).not.toHaveBeenCalled();+ });++ // Failure path: an unexpected fault must reach the shared boundary and come+ // back as an opaque 500 carrying only a support reference.+ it('routes an unexpected fault to the error boundary and leaks nothing', async () => {+ const res = mkRes();+ const err = new Error('relation "x402_settlements" does not exist');+ err.code = '42P01';+ await sendX402Error(res, CTX, err);++ expect(reportServerErrorMock).toHaveBeenCalledTimes(1);+ const [reported, opts] = reportServerErrorMock.mock.calls[0];+ expect(reported).toBe(err);+ expect(opts.code).toBe('mcp_x402_failed');+ expect(opts.context).toEqual({ resourceUrl: CTX.resourceUrl });++ expect(res.statusCode).toBe(500);+ const body = JSON.parse(res.body);+ expect(body.error).toBe('internal');+ expect(body.ref).toBe('ref_abc123');+ expect(body.error_description).toContain('ref_abc123');+ // The driver detail stays server-side.+ expect(res.body).not.toContain('x402_settlements');+ expect(res.body).not.toContain('42P01');+ expect(send402Mock).not.toHaveBeenCalled();+ });++ it('re-exports the shared replay guard so every MCP server uses one implementation', () => {+ expect(typeof reservePaymentProof).toBe('function');+ });+});++// ── embed-policy.js ─────────────────────────────────────────────────────────+describe('readMcpPolicyByAvatar', () => {+ it('returns the normalized policy for an avatar owned by a registered agent', async () => {+ sqlMock.mockResolvedValue([{ embed_policy: { surfaces: { mcp: false } } }]);+ const policy = await readMcpPolicyByAvatar('11111111-1111-4111-8111-111111111111');++ expect(sqlMock).toHaveBeenCalledTimes(1);+ expect(policy).toBeTruthy();+ // Normalization fills the rest of the policy in around the stored override.+ expect(policy.surfaces.mcp).toBe(false);+ expect(policy.version).toBeDefined();+ expect(policy.origins).toBeDefined();+ });++ it('returns null when no agent claims the avatar, leaving the surface open', async () => {+ sqlMock.mockResolvedValue([]);+ expect(await readMcpPolicyByAvatar('11111111-1111-4111-8111-111111111111')).toBeNull();+ });++ // Failure path: a caller-supplied id that is not a uuid never reaches the DB.+ it('rejects a non-uuid avatar id without querying', async () => {+ for (const bad of ["'; DROP TABLE avatars; --", '', 'not-a-uuid', null, undefined]) {+ expect(await readMcpPolicyByAvatar(bad)).toBeNull();+ }+ expect(sqlMock).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/mcp-render-origin.test.js b/tests/api/mcp-render-origin.test.jsnew file mode 100644index 000000000..f51d9c022--- /dev/null+++ b/tests/api/mcp-render-origin.test.js@@ -0,0 +1,213 @@+// api/_mcp/render.js and api/_mcp/origin.js — the two shared helpers behind+// every MCP tool that emits viewer HTML or an absolute link.+//+// render.js builds an HTML document from caller-supplied values, so its whole+// job is escaping: attribute values are one hazard, but the CSS ones are worse+// because they land inside a <style> declaration where HTML escaping does not+// stop a `;}` breakout. renderModelViewerHtml re-runs the sanitizers itself, so+// these tests hold that line for a caller that forgets them entirely.+//+// origin.js resolves the site origin used to build absolute URLs. It is the+// only place in the MCP tools allowed to guess, so both its precedence order+// and its refusal to invent an origin are pinned here.++import { describe, it, expect, afterEach } from 'vitest';++const {+ renderModelViewerHtml,+ formatAvatarList,+ safeCssValue,+ safeCssLength,+ safeHttpsUrl,+} = await import('../../api/_mcp/render.js');+const { resolveOrigin } = await import('../../api/_mcp/origin.js');++const ORIGIN_VARS = ['APP_ORIGIN', 'PUBLIC_ORIGIN', 'PUBLIC_APP_ORIGIN', 'VERCEL_URL'];+const SAVED = Object.fromEntries(ORIGIN_VARS.map((k) => [k, process.env[k]]));++function clearOriginEnv() {+ for (const k of ORIGIN_VARS) delete process.env[k];+}++afterEach(() => {+ for (const k of ORIGIN_VARS) {+ if (SAVED[k] === undefined) delete process.env[k];+ else process.env[k] = SAVED[k];+ }+});++// ── CSS + URL sanitizers ────────────────────────────────────────────────────+describe('render.js sanitizers', () => {+ it('passes ordinary CSS values and rejects anything that could close the rule', () => {+ expect(safeCssValue('transparent', 'fallback')).toBe('transparent');+ expect(safeCssValue('#0b0c10', 'fallback')).toBe('#0b0c10');+ expect(safeCssValue('rgb(11, 12, 16)', 'fallback')).toBe('rgb(11, 12, 16)');+ // A breakout attempt falls back rather than being partially escaped.+ expect(safeCssValue('red;}body{display:none', 'fallback')).toBe('fallback');+ expect(safeCssValue('url("javascript:alert(1)")', 'fallback')).toBe('fallback');+ expect(safeCssValue('a'.repeat(121), 'fallback')).toBe('fallback');+ expect(safeCssValue('', 'fallback')).toBe('fallback');+ });++ it('is idempotent, so re-sanitizing an already-clean value is a no-op', () => {+ for (const value of ['transparent', '#6a5cff', '0deg 80deg 2m', 'rgb(1, 2, 3)']) {+ expect(safeCssValue(safeCssValue(value, 'x'), 'x')).toBe(value);+ }+ for (const value of ['480px', '100%', '12.5rem', 'auto']) {+ expect(safeCssLength(safeCssLength(value, 'x'), 'x')).toBe(value);+ }+ });++ it('accepts only real CSS lengths', () => {+ expect(safeCssLength('480px', '1px')).toBe('480px');+ expect(safeCssLength('100%', '1px')).toBe('100%');+ expect(safeCssLength('auto', '1px')).toBe('auto');+ expect(safeCssLength('480px;}html{x:y', '1px')).toBe('1px');+ expect(safeCssLength('calc(100% - 10px)', '1px')).toBe('1px');+ });++ it('accepts only https posters, dropping script-bearing schemes', () => {+ expect(safeHttpsUrl('https://three.ws/p.png')).toBe('https://three.ws/p.png');+ expect(safeHttpsUrl('http://three.ws/p.png')).toBeUndefined();+ expect(safeHttpsUrl('javascript:alert(1)')).toBeUndefined();+ expect(safeHttpsUrl('data:text/html,<script>alert(1)</script>')).toBeUndefined();+ expect(safeHttpsUrl('not a url')).toBeUndefined();+ expect(safeHttpsUrl(undefined)).toBeUndefined();+ });+});++// ── renderModelViewerHtml ───────────────────────────────────────────────────+describe('renderModelViewerHtml', () => {+ const BASE = {+ src: 'https://cdn.three.ws/a.glb',+ name: 'Nova',+ background: 'transparent',+ height: '480px',+ width: '100%',+ autoRotate: true,+ ar: true,+ };++ it('renders a complete viewer document with the caller-supplied model', () => {+ const html = renderModelViewerHtml(BASE);+ expect(html.startsWith('<!doctype html>')).toBe(true);+ expect(html).toContain('src="https://cdn.three.ws/a.glb"');+ expect(html).toContain('<title>Nova</title>');+ expect(html).toContain('alt="Nova"');+ expect(html).toContain('auto-rotate');+ expect(html).toContain('ar-modes="webxr scene-viewer quick-look"');+ expect(html).toContain('background:transparent');+ expect(html).toContain('width:100%;height:480px');+ // No AR link unless an arHref was supplied.+ expect(html).not.toContain('View in your space');+ });++ it('omits the optional attributes the caller left out', () => {+ const html = renderModelViewerHtml({ ...BASE, autoRotate: false, ar: false });+ expect(html).not.toContain('auto-rotate');+ expect(html).not.toContain('ar-modes');+ expect(html).not.toContain('poster=');+ expect(html).not.toContain('camera-orbit=');+ });++ it('renders the AR link when an arHref is supplied', () => {+ const html = renderModelViewerHtml({ ...BASE, arHref: 'https://three.ws/api/ar?u=x' });+ expect(html).toContain('href="https://three.ws/api/ar?u=x"');+ expect(html).toContain('View in your space');+ expect(html).toContain('rel="noopener"');+ });++ // The failure path that matters: a caller that skipped safeCssValue /+ // safeHttpsUrl must still not be able to escape the <style> declaration or+ // smuggle a script URL into an attribute.+ it('neutralizes unsanitized CSS and poster input from a forgetful caller', () => {+ const html = renderModelViewerHtml({+ ...BASE,+ background: 'red;}body{background:url(https://evil.test/x)}',+ height: '480px;}*{display:none',+ width: '100%"><script>alert(1)</script>',+ cameraOrbit: '0deg 80deg 2m;}html{x:y}',+ poster: 'javascript:alert(1)',+ });+ expect(html).not.toContain('evil.test');+ expect(html).not.toContain('<script>alert(1)</script>');+ expect(html).not.toContain('javascript:alert(1)');+ expect(html).not.toContain('poster=');+ expect(html).not.toContain('camera-orbit=');+ // Fell back to the safe defaults instead.+ expect(html).toContain('background:transparent');+ expect(html).toContain('width:100%;height:480px');+ });++ it('escapes HTML metacharacters in the avatar name', () => {+ const html = renderModelViewerHtml({ ...BASE, name: '<img src=x onerror=alert(1)>' });+ expect(html).not.toContain('<img src=x');+ expect(html).toContain('<img src=x onerror=alert(1)>');+ });+});++// ── formatAvatarList ────────────────────────────────────────────────────────+describe('formatAvatarList', () => {+ const AVATARS = [+ { name: 'Nova', slug: 'nova', id: 'a1', visibility: 'private', model_url: 'https://c/1.glb' },+ { name: 'Rex', slug: 'rex', id: 'a2', visibility: 'public', model_url: null },+ ];++ it('lists each avatar with its slug, id, and visibility', () => {+ const text = formatAvatarList(AVATARS);+ expect(text).toContain('Nova (slug: nova, id: a1)');+ expect(text).toContain('[private]');+ expect(text).toContain('https://c/1.glb');+ expect(text.split('\n')).toHaveLength(2);+ });++ it('hides visibility on the public gallery listing', () => {+ const text = formatAvatarList(AVATARS, { public: true });+ expect(text).not.toContain('[private]');+ expect(text).not.toContain('[public]');+ });++ it('tells the caller nothing matched instead of returning an empty string', () => {+ expect(formatAvatarList([])).toBe('No avatars found.');+ });+});++// ── resolveOrigin ───────────────────────────────────────────────────────────+describe('resolveOrigin', () => {+ it('prefers explicit env over the request Host header, without a trailing slash', () => {+ clearOriginEnv();+ process.env.APP_ORIGIN = 'https://three.ws/';+ expect(resolveOrigin({ headers: { host: 'preview.example' } })).toBe('https://three.ws');+ });++ it('falls back through the alternate env names', () => {+ clearOriginEnv();+ process.env.PUBLIC_ORIGIN = 'https://public.three.ws';+ expect(resolveOrigin({ headers: {} })).toBe('https://public.three.ws');++ clearOriginEnv();+ process.env.PUBLIC_APP_ORIGIN = 'https://app.three.ws';+ expect(resolveOrigin({ headers: {} })).toBe('https://app.three.ws');+ });++ it('derives https from the Host header, and http for local development', () => {+ clearOriginEnv();+ expect(resolveOrigin({ headers: { host: 'three.ws' } })).toBe('https://three.ws');+ expect(resolveOrigin({ headers: { host: 'localhost:3000' } })).toBe('http://localhost:3000');+ expect(resolveOrigin({ headers: { host: '127.0.0.1:3000' } })).toBe('http://127.0.0.1:3000');+ });++ it('falls back to VERCEL_URL when there is no env origin and no Host', () => {+ clearOriginEnv();+ process.env.VERCEL_URL = 'three-ws.vercel.app';+ expect(resolveOrigin({ headers: {} })).toBe('https://three-ws.vercel.app');+ });++ // Failure path: guessing an origin would produce links that silently point at+ // the wrong host, so it throws instead.+ it('throws rather than invent an origin when nothing resolves', () => {+ clearOriginEnv();+ expect(() => resolveOrigin({ headers: {} })).toThrow(/cannot resolve site origin/);+ expect(() => resolveOrigin(undefined)).toThrow(/cannot resolve site origin/);+ });+});