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(x402): charge only for answers the buyer receives, and stop caching key material
nirholas4af66b311c46
diff --git a/api/x402-pay/og.js b/api/x402-pay/og.jsindex a19af8e0f..862d56d0c 100644--- a/api/x402-pay/og.js+++ b/api/x402-pay/og.js@@ -4,15 +4,36 @@// paid x402 call (tool, amount, payer, timestamp).import { getRedis as _getSharedRedis } from '../_lib/redis.js';+import { cors, wrap } from '../_lib/http.js';import { logger } from '../_lib/usage.js';+import {+ NETWORK_SOLANA_MAINNET,+ NETWORK_SOLANA_DEVNET,+} from '../_lib/x402/solana-networks.js';const log = logger('x402-og');const FALLBACK_TITLE = 'three.ws · pay-per-call (x402)';-const FALLBACK_SUB = 'Live demo — agent pays $0.001 USDC per MCP tool call.';+const FALLBACK_SUB = 'Live demo: agent pays $0.001 USDC per MCP tool call.';+const UNKNOWN = 'n/a';++// A settled record is immutable, so it caches for an hour at the edge. A+// well-formed tx we could NOT resolve (Redis down, or the card was shared in+// the seconds before persistCall landed) must not be cached that long: an+// hour of CDN-cached generic card on a real permalink is how a transient+// outage turns into a whole afternoon of blank share previews.+const CACHE_RESOLVED = 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400';+const CACHE_UNRESOLVED = 'public, max-age=60, s-maxage=60';++// Base58 Solana signature. 64 to 90 chars covers every real 64-byte signature.+const TX_RE = /^[1-9A-HJ-NP-Za-km-z]{64,90}$/;function redis() { return _getSharedRedis(); }+function isRecord(v) {+ return v != null && typeof v === 'object' && !Array.isArray(v);+}+async function readCall(tx) {const r = redis();if (!r) return null;@@ -20,11 +41,15 @@ async function readCall(tx) {const row = await r.get(`x402:pay:call:${tx}`);if (typeof row === 'string') {try {- return JSON.parse(row);+ const parsed = JSON.parse(row);+ // A row that parses to a scalar or an array is corrupt, not a+ // record. Treating it as one renders a card of blank fields.+ if (isRecord(parsed)) return parsed;+ log.warn('og_row_not_object', { tx, type: Array.isArray(parsed) ? 'array' : typeof parsed });} catch (parseErr) {log.warn('og_row_parse_failed', { tx, message: parseErr?.message });}- } else if (row && typeof row === 'object') return row;+ } else if (isRecord(row)) return row;} catch (err) {log.warn('og_row_read_failed', { tx, message: err?.message });}@@ -32,44 +57,69 @@ async function readCall(tx) {}function escapeSvg(s) {- return String(s).replace(/[<>&"]/g, (c) => ({- '<': '<', '>': '>', '&': '&', '"': '"',+ return String(s).replace(/[<>&"']/g, (c) => ({+ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''',}[c]));}+// `tool` and `argsSummary` come from the caller's own request body, so they are+// unbounded caller-controlled text. Escaping keeps them from breaking the SVG;+// clamping keeps a 400-character tool name from painting over the whole card.+function truncate(s, n) {+ const str = String(s ?? '');+ return str.length <= n ? str : `${str.slice(0, n - 1)}…`;+}+function shortTx(tx) {- if (!tx) return '—';- return `${tx.slice(0, 10)}…${tx.slice(-6)}`;+ const s = String(tx ?? '');+ if (!s) return UNKNOWN;+ return s.length > 20 ? `${s.slice(0, 10)}…${s.slice(-6)}` : s;}function shortAddr(a) {- if (!a) return '—';- return `${a.slice(0, 6)}…${a.slice(-4)}`;+ const s = String(a ?? '');+ if (!s) return UNKNOWN;+ return s.length > 12 ? `${s.slice(0, 6)}…${s.slice(-4)}` : s;}function relativeAgo(ts) {- if (!ts) return '';- const d = Math.max(0, Date.now() - ts);+ const n = Number(ts);+ // A corrupt `ts` used to fall through every branch and render "NaNd ago".+ if (!Number.isFinite(n) || n <= 0) return '';+ const d = Math.max(0, Date.now() - n);if (d < 60_000) return `${Math.floor(d / 1000)}s ago`;if (d < 3_600_000) return `${Math.floor(d / 60_000)}m ago`;if (d < 86_400_000) return `${Math.floor(d / 3_600_000)}h ago`;return `${Math.floor(d / 86_400_000)}d ago`;}+// Records carry the CAIP-2 network id the payment settled on. Only the mainnet+// lane persists records today, but reading the id rather than hardcoding a+// label means a devnet receipt can never be captioned "mainnet".+function networkLabel(network) {+ if (network === NETWORK_SOLANA_MAINNET) return 'Solana mainnet';+ if (network === NETWORK_SOLANA_DEVNET) return 'Solana devnet';+ return 'Solana';+}++// Persisted records always carry `amount` (base units) from accept.amount; a+// malformed row renders "unknown" rather than a fabricated $0.001 figure.+function amountLabel(amount) {+ const raw = amount != null ? Number(amount) : null;+ if (raw == null || !Number.isFinite(raw)) return 'unknown';+ return `${(raw / 1e6).toFixed(6)} USDC`;+}+function svgFor(record, txParam) {- const tool = record?.tool || 'paid call';- const args = record?.argsSummary || '';+ const tool = truncate(record?.tool || 'paid call', 38);+ const args = truncate(record?.argsSummary || '', 80);const tx = record?.tx || txParam || '';const payer = record?.payer || '';- // Persisted records always carry `amount` from accept.amount; if a malformed- // row sneaks in, render '—' rather than fabricating a $0.001 figure.- const rawAmount = record?.amount != null ? Number(record.amount) : null;- const amount = rawAmount != null && Number.isFinite(rawAmount)- ? (rawAmount / 1e6).toFixed(6)- : '—';+ const amount = amountLabel(record?.amount);+ const network = networkLabel(record?.network);const ago = relativeAgo(record?.ts);- return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630">+ return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="${escapeSvg(tool)}, ${escapeSvg(amount)} on ${escapeSvg(network)}"><defs><linearGradient id="bg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#0a0b10"/>@@ -115,18 +165,18 @@ function svgFor(record, txParam) {<g transform="translate(72 200)"><rect x="0" y="-36" width="6" height="56" fill="url(#accent)" rx="3"/><text x="22" y="0" font-family="ui-monospace, Menlo, monospace" font-size="46" font-weight="700" fill="#e6e8f0">${escapeSvg(tool)}</text>- ${args ? `<text x="22" y="36" font-family="-apple-system, system-ui, Inter, Helvetica, Arial, sans-serif" font-size="22" fill="#8a90a8">${escapeSvg(args.slice(0, 80))}</text>` : ''}+ ${args ? `<text x="22" y="36" font-family="-apple-system, system-ui, Inter, Helvetica, Arial, sans-serif" font-size="22" fill="#8a90a8">${escapeSvg(args)}</text>` : ''}</g><!-- stat strip --><g transform="translate(72 320)" font-family="ui-monospace, Menlo, monospace"><g><text x="0" y="0" font-size="13" fill="#8a90a8" letter-spacing="1.6">AMOUNT</text>- <text x="0" y="30" font-size="28" fill="#e6e8f0" font-weight="600">${amount} USDC</text>+ <text x="0" y="30" font-size="28" fill="#e6e8f0" font-weight="600">${escapeSvg(amount)}</text></g><g transform="translate(280 0)"><text x="0" y="0" font-size="13" fill="#8a90a8" letter-spacing="1.6">NETWORK</text>- <text x="0" y="30" font-size="28" fill="#e6e8f0" font-weight="600">Solana mainnet</text>+ <text x="0" y="30" font-size="28" fill="#e6e8f0" font-weight="600">${escapeSvg(network)}</text></g><g transform="translate(660 0)"><text x="0" y="0" font-size="13" fill="#8a90a8" letter-spacing="1.6">PAYER</text>@@ -153,7 +203,7 @@ function svgFor(record, txParam) {}function fallbackSvg() {- return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630">+ return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="${escapeSvg(FALLBACK_TITLE)}"><defs><linearGradient id="bg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#0a0b10"/><stop offset="1" stop-color="#14161f"/></linearGradient><linearGradient id="logoG" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#8b5cf6"/><stop offset="1" stop-color="#22d3ee"/></linearGradient>@@ -168,31 +218,47 @@ function fallbackSvg() {</svg>`;}-export default async function handler(req, res) {- res.setHeader('access-control-allow-origin', '*');- if (req.method === 'OPTIONS') { res.statusCode = 204; return res.end(); }- if (req.method !== 'GET') { res.statusCode = 405; return res.end(); }+export default wrap(async function handler(req, res) {+ // Same shape as the neighboring card endpoint (api/agent-og.js): an OG+ // image is read cross-origin by every unfurler, so the origin is open.+ if (cors(req, res, { origins: '*', methods: 'GET,HEAD,OPTIONS' })) return;++ // Slack, Telegram and LinkedIn all HEAD an image URL to check its type and+ // size before they fetch it; answering 405 there drops the card entirely.+ if (req.method !== 'GET' && req.method !== 'HEAD') {+ res.statusCode = 405;+ res.setHeader('allow', 'GET, HEAD, OPTIONS');+ res.setHeader('content-type', 'application/json; charset=utf-8');+ return res.end(JSON.stringify({+ error: 'method_not_allowed',+ message: 'This card endpoint serves GET, HEAD and OPTIONS.',+ }));+ }const url = new URL(req.url, `http://${req.headers.host || 'three.ws'}`);const tx = url.searchParams.get('tx') || '';+ const wantsRecord = TX_RE.test(tx);- let record = null;- if (tx && /^[1-9A-HJ-NP-Za-km-z]{64,90}$/.test(tx)) {- record = await readCall(tx);- }+ const record = wantsRecord ? await readCall(tx) : null;const svg = record ? svgFor(record, tx) : fallbackSvg();- // Serve the card as SVG directly. The previous sharp→PNG raster relied on- // libvips' text shaping, which needs a system fontconfig that doesn't exist- // on the Vercel serverless runtime — so every render logged+ // Serve the card as SVG directly. The previous sharp to PNG raster relied on+ // libvips' text shaping, which needs a system fontconfig that does not exist+ // on the serverless runtime, so every render logged// "Fontconfig error: Cannot load default config file" and produced// glyph-less text before falling back to SVG anyway. SVG is the right output- // here: it's resolution-independent, needs no native font stack, and every+ // here: it is resolution-independent, needs no native font stack, and every// major unfurler (X, Discord, Slack, Telegram) accepts image/svg+xml OG- // images — the same approach api/agent-og.js already uses. The SVG specifies+ // images, the same approach api/agent-og.js already uses. The SVG specifies// system-font fallback stacks so the consumer renders it with its own fonts.res.statusCode = 200;res.setHeader('content-type', 'image/svg+xml; charset=utf-8');- res.setHeader('cache-control', 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400');+ res.setHeader('content-length', String(Buffer.byteLength(svg)));+ res.setHeader('cache-control', wantsRecord && !record ? CACHE_UNRESOLVED : CACHE_RESOLVED);+ // Every value in the card is escaped, but an SVG served from our own origin+ // is a script-execution surface if that ever regresses. Nothing in this+ // document needs a script, a fetch or a remote reference.+ res.setHeader('content-security-policy', "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'");+ if (req.method === 'HEAD') return res.end();return res.end(svg);-}+});diff --git a/api/x402/agent-bouncer.js b/api/x402/agent-bouncer.jsindex b1b639ecf..4f52681a5 100644--- a/api/x402/agent-bouncer.js+++ b/api/x402/agent-bouncer.js@@ -81,6 +81,7 @@ const INPUT_SCHEMA = {const OUTPUT_EXAMPLE = {ok: true,+ exists: true,admitted: true,banned: false,tier: 'trusted',diff --git a/api/x402/analytics.js b/api/x402/analytics.jsindex 94ea9a20e..d62d48524 100644--- a/api/x402/analytics.js+++ b/api/x402/analytics.js@@ -347,13 +347,18 @@ async function agentLeaderboardReport(limit, windowDays) {const AGENT_AUTONAMED_RE ='^(Agent|My Agent|My First Agent|Demo Agent|Untitled.*|TEST|Test|test|mo[a-z0-9]{4,}|draft-[a-z0-9]+|new_project_[0-9]+|Avatar[ ]*#[0-9a-f]{4,}([ ]*agent)?|https?://.+)$';-// Mints we can normalise to USD at query time.-// Keys are lower-cased for comparison; display form preserved per-row via currencyLabel().-const USDC_MINTS = new Set([- 'epjfwdd5aufqssqem2qn1xzybapC8G4wEGGkZwyTDt1v', // Solana mainnet USDC+// Mints we can normalise to USD at query time. Lookups compare against a+// lower-cased mint, so the sets are normalised at construction rather than by+// hand: a hand-lowered literal drifted (one entry kept its mixed-case tail),+// which silently made every Solana-priced listing unpriceable and dropped it+// out of the marketplace report's USD average. Display form is preserved+// per-row via currencyLabel().+const lowerSet = (mints) => new Set(mints.map((m) => m.toLowerCase()));+const USDC_MINTS = lowerSet([+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // Solana mainnet USDC'0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', // Base USDC]);-const SOL_MINTS = new Set(['native', 'so11111111111111111111111111111111111111112']);+const SOL_MINTS = lowerSet(['native', 'So11111111111111111111111111111111111111112']);function currencyLabel(mint) {const m = String(mint || '').toLowerCase();@@ -362,6 +367,11 @@ function currencyLabel(mint) {return mint && mint.length > 10 ? `${mint.slice(0, 4)}…${mint.slice(-4)}` : String(mint || 'unknown');}+// Exported for the currency-normalisation contract test: the marketplace+// report's USD maths is only correct while every mint in these sets matches a+// lower-cased lookup.+export const __test__ = { USDC_MINTS, SOL_MINTS, currencyLabel };+function roundNum(n, dp) {if (n == null || !Number.isFinite(Number(n))) return null;const f = 10 ** dp;diff --git a/api/x402/animation-download.js b/api/x402/animation-download.jsindex 530affbad..c81a2fa4b 100644--- a/api/x402/animation-download.js+++ b/api/x402/animation-download.js@@ -17,7 +17,7 @@ import { priceFor } from '../_lib/x402-prices.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { sql } from '../_lib/db.js';import { presignGet } from '../_lib/r2.js';-import { error, json } from '../_lib/http.js';+import { cors, error, json } from '../_lib/http.js';import { env } from '../_lib/env.js';import animationDownloadListing from '../_lib/service-catalog/services/animation-download.js';@@ -161,6 +161,15 @@ function sendDiscoveryChallenge(res, errText) {export const __test__ = { priceAtomics, buildSiwxStatement, buildPayToOverride, UUID_RE };export default async function handler(req, res) {+ // Install CORS before anything else, for the same reason as+ // asset-download.js: this handler answers the discovery challenge, the+ // 400/404/502 errors and the free-listing 200 itself, before it ever+ // delegates to paidEndpoint (which is what normally installs CORS). Without+ // it the OPTIONS preflight fell through to a 402 carrying no+ // Access-Control-Allow-Origin, leaving browser x402 clients unable to read+ // the challenge. Same options paidEndpoint uses for a GET route.+ if (cors(req, res, { methods: 'GET,HEAD,OPTIONS', origins: '*' })) return;+const paymentPresent = Boolean(req.headers['x-payment'] || req.headers['payment-signature']);const id = req.query?.id ? String(req.query.id).trim() : '';diff --git a/api/x402/asset-download.js b/api/x402/asset-download.jsindex 95a9d395a..7241855d1 100644--- a/api/x402/asset-download.js+++ b/api/x402/asset-download.js@@ -15,7 +15,7 @@ import { priceFor } from '../_lib/x402-prices.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { sql } from '../_lib/db.js';import { presignGet } from '../_lib/r2.js';-import { error } from '../_lib/http.js';+import { cors, error } from '../_lib/http.js';import { env } from '../_lib/env.js';import assetDownloadListing from '../_lib/service-catalog/services/asset-download.js';@@ -151,6 +151,16 @@ function sendDiscoveryChallenge(res, errText) {// Per-asset paidEndpoint built on the fly. The slug picks the row, which// dictates price + payout overrides + R2 key — everything else is shared.export default async function handler(req, res) {+ // Install CORS before anything else. Every other x402 handler gets this from+ // paidEndpoint's own first step, but this file answers the discovery probe,+ // the 400/404/502 errors and the free-listing 200 itself, long before it+ // delegates. Without it the OPTIONS preflight fell through to the discovery+ // challenge and returned a 402 with no Access-Control-Allow-Origin, so a+ // browser x402 client (the drop-in modal, x402-fetch) could never read the+ // challenge it is supposed to pay. Same options paidEndpoint uses for a GET+ // route, so the delegated path below stays byte-identical.+ if (cors(req, res, { methods: 'GET,HEAD,OPTIONS', origins: '*' })) return;+const slug = req.query?.slug ? String(req.query.slug).trim() : '';const paymentPresent = Boolean(req.headers['x-payment'] || req.headers['payment-signature']);if (!slug) {diff --git a/api/x402/auth-health.js b/api/x402/auth-health.jsindex ecb8d407b..271646aa2 100644--- a/api/x402/auth-health.js+++ b/api/x402/auth-health.js@@ -14,6 +14,7 @@import { SignJWT } from 'jose';import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { readBody as readRawBody } from '../_lib/http.js';import { buildBazaarSchema } from '../_lib/x402-spec.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { installAccessControl } from '../_lib/x402/access-control.js';@@ -27,19 +28,42 @@ const ROUTE = '/api/x402/auth-health';const CANARY_USER_ID = '00000000-0000-0000-0000-000000000000';const CANARY_CLIENT = 'x402-auth-health-canary';const CANARY_SCOPE = 'health:read';+const SUPPORTED_MODE = 'session_lifecycle';-async function readBody(req) {+// Read the JSON body through the shared reader. The local hand-rolled version+// this replaces drained the raw stream with no size cap and no stalled-stream+// timeout, so an oversized or never-finished body pinned a Cloud Run+// concurrency slot; _lib/http.js readBody enforces both and also handles the+// bodies Express already parsed ahead of the handler. 1 MB matches every+// neighbouring POST endpoint in this directory.+async function readJsonBody(req) {if (req.body && typeof req.body === 'object') return req.body;try {- const chunks = [];- for await (const c of req) chunks.push(c);- const raw = Buffer.concat(chunks).toString('utf8');+ const raw = (await readRawBody(req, 1_000_000)).toString('utf8').trim();return raw ? JSON.parse(raw) : {};} catch {return {};}}+// Resolve and validate the requested mode, throwing rather than returning on a+// bad one. paidEndpoint delivers before it settles, so a returned value is the+// buyer's receipt: returning an error object here billed $0.001 for a 200+// carrying no health check at all. A throw lands before settlement, so an+// unsupported mode costs the caller nothing.+function resolveMode(body) {+ const mode = typeof body?.mode === 'string' ? body.mode.trim() : SUPPORTED_MODE;+ if (mode !== SUPPORTED_MODE) {+ throw Object.assign(+ new Error(`unsupported mode "${mode}"; the only supported mode is "${SUPPORTED_MODE}"`),+ { status: 400, code: 'unsupported_mode' },+ );+ }+ return mode;+}++export const __test__ = { resolveMode };+async function runSessionLifecycle() {const t0 = Date.now();const steps = {};@@ -236,11 +260,7 @@ const authHealthEndpoint = paidEndpoint({accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),async handler({ req }) {- const body = await readBody(req);- const mode = typeof body.mode === 'string' ? body.mode.trim() : 'session_lifecycle';- if (mode !== 'session_lifecycle') {- return { error: 'unsupported_mode', supported: ['session_lifecycle'] };- }+ resolveMode(await readJsonBody(req));return runSessionLifecycle();},});diff --git a/api/x402/avatar-optimize-batch.js b/api/x402/avatar-optimize-batch.jsindex 91e237ed8..daef588b2 100644--- a/api/x402/avatar-optimize-batch.js+++ b/api/x402/avatar-optimize-batch.js@@ -18,6 +18,7 @@ import { readBody } from '../_lib/http.js';import { buildBazaarSchema } from '../_lib/x402-spec.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { installAccessControl } from '../_lib/x402/access-control.js';+import { priceFor } from '../_lib/x402-prices.js';import { sql } from '../_lib/db.js';import { publicUrl } from '../_lib/r2.js';import { inspectModel, suggestOptimizations } from '../_lib/model-inspect.js';@@ -140,7 +141,10 @@ async function fetchModelBytes(url) {export default paidEndpoint({route: ROUTE,method: 'POST',- priceAtomics: 1_000, // $0.001 USDC+ // $0.001 USDC. Goes through priceFor so the documented+ // X402_PRICE_AVATAR_OPTIMIZE_BATCH override actually applies; the literal it+ // replaces made this the one endpoint in the directory ops could not reprice.+ priceAtomics: priceFor('avatar-optimize-batch', '1000'),networks: ['solana', 'base'],description: DESCRIPTION,bazaar: BAZAAR,diff --git a/api/x402/club-cover.js b/api/x402/club-cover.jsindex 3dd2385a4..29d029a76 100644--- a/api/x402/club-cover.js+++ b/api/x402/club-cover.js@@ -19,7 +19,6 @@ import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { priceFor } from '../_lib/x402-prices.js';import {- issueCoverPass,PASS_TTL_SEC,normalizeWallet,findBan,@@ -195,8 +194,25 @@ const SNAPSHOT_INPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',type: 'object',properties: {- club: { type: 'string', description: 'Club label to snapshot.', default: 'three_holders' },- mode: { type: 'string', enum: ['snapshot'], default: 'snapshot' },+ club: {+ type: 'string',+ description: 'Club label to snapshot. Used by mode "snapshot".',+ default: 'three_holders',+ },+ mode: {+ type: 'string',+ enum: ['snapshot', 'revenue'],+ default: 'snapshot',+ description:+ '"snapshot" returns club membership growth/churn; "revenue" returns the ' ++ 'door + floor revenue summary for the requested period.',+ },+ period: {+ type: 'string',+ enum: ['24h', '7d', '14d', '30d', 'all'],+ default: '7d',+ description: 'Revenue window. Used by mode "revenue"; anything else falls back to 7d.',+ },},};@@ -219,14 +235,17 @@ const SNAPSHOT_OUTPUT_EXAMPLE = {asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',};+// Two shapes share this response, keyed on `mode`. Only the fields both modes+// always return are `required`; the membership block below is the "snapshot"+// shape, and the revenue block after it is the "revenue" shape.const SNAPSHOT_OUTPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',type: 'object',- required: ['ok', 'club', 'mode', 'member_count', 'active_last_7d', 'new_this_week', 'signal'],+ required: ['ok', 'mode'],properties: {ok: { type: 'boolean', const: true },club: { type: 'string' },- mode: { type: 'string', const: 'snapshot' },+ mode: { type: 'string', enum: ['snapshot', 'revenue'] },member_count: { type: 'integer', minimum: 0, description: 'Distinct wallets that ever paid into the club.' },active_last_7d: { type: 'integer', minimum: 0, description: 'Distinct wallets active in the last 7 days.' },new_this_week: { type: 'integer', minimum: 0, description: 'Distinct wallets whose first payment landed in the last 7 days.' },@@ -236,6 +255,40 @@ const SNAPSHOT_OUTPUT_SCHEMA = {headline: { type: 'string' },confidence: { type: 'number', minimum: 0, maximum: 1 },snapshot_at: { type: 'string', format: 'date-time' },+ // mode "revenue" only. Door + floor take over the requested window.+ period: { type: 'string', description: 'Canonical revenue window the summary covers.' },+ since: { type: 'string', format: 'date-time', description: 'Start of the revenue window.' },+ total_usdc: { type: 'string', description: 'Cover-charge (door) revenue over the window, in USDC.' },+ cover: {+ type: 'object',+ description: 'Door take: settled cover charges over the window.',+ properties: {+ total_usdc: { type: 'string' },+ total_atomics: { type: 'string' },+ count: { type: 'integer', minimum: 0 },+ unique_payers: { type: 'integer', minimum: 0 },+ },+ },+ floor: {+ type: 'object',+ description: 'Floor take: settled dance tips over the window.',+ properties: {+ total_usdc: { type: 'string' },+ total_atomics: { type: 'string' },+ tip_count: { type: 'integer', minimum: 0 },+ },+ },+ social_economy_usdc: { type: 'string', description: 'Door + floor combined, in USDC.' },+ clubs: {+ type: 'array',+ description: 'Per-act revenue roster, highest earning first.',+ items: { type: 'object' },+ },+ club_count: { type: 'integer', minimum: 0 },+ top_club_id: { type: ['string', 'null'] },+ top_club_revenue: { type: ['string', 'null'] },+ top_club_display_name: { type: ['string', 'null'] },+ generated_at: { type: 'string', format: 'date-time' },payer: { type: ['string', 'null'] },network: { type: ['string', 'null'] },amountAtomics: { type: ['string', 'null'] },@@ -265,9 +318,11 @@ const snapshotEndpoint = paidEndpoint({priceAtomics: priceFor('club-cover', '10000'), // $0.01 USDC — same cover chargenetworks: ['solana'],description:- 'three.ws Pole Club — pay $0.01 USDC for a live membership snapshot of the ' +- 'club: all-time member count, members active in the last 7 days, and members ' +- 'new this week, with a growth/churn signal. Pay-per-call in USDC on Solana mainnet.',+ 'three.ws Pole Club: pay $0.01 USDC for a live read of the club. mode:"snapshot" ' ++ '(default) returns membership: all-time member count, members active in the last 7 ' ++ 'days, and members new this week, with a growth/churn signal. mode:"revenue" returns ' ++ 'the door + floor take for a period (24h, 7d, 14d, 30d, all). Pay-per-call in USDC on ' ++ 'Solana mainnet.',bazaar: SNAPSHOT_BAZAAR,service: withService({serviceName: 'three.ws Club Membership',diff --git a/api/x402/cosmetic-purchase.js b/api/x402/cosmetic-purchase.jsindex f54334289..17940eb5c 100644--- a/api/x402/cosmetic-purchase.js+++ b/api/x402/cosmetic-purchase.js@@ -17,15 +17,22 @@// on-chain payment itself is single-use (the facilitator won't settle the same// signed proof twice), and the ownership SET is idempotent, so the flow is safe// against replay and can never double-grant.+//+// The SIWX grant is keyed on (resource, wallet) and the resource URL carries the+// cosmetic id, NOT the target account. So the free re-access path must re-check+// entitlement itself (siwxReGrantAllowed below): without that, one purchase+// would let the paying wallet sign the item onto an unlimited number of other+// accounts for free. Re-access re-confirms an unlock; it never sells a new one.import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';import { buildBazaarSchema, paymentRequirements, send402 } from '../_lib/x402-spec.js';+import { X402Error } from '../_lib/x402-errors.js';import { priceFor } from '../_lib/x402-prices.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { error } from '../_lib/http.js';import { env } from '../_lib/env.js';import { getCosmetic, priceUsdcAtomicsOf } from '../_lib/cosmetics.js';-import { grantCosmeticOwnership, normalizeAccountId } from '../_lib/cosmetics-ownership.js';+import { grantCosmeticOwnership, normalizeAccountId, ownsCosmetic } from '../_lib/cosmetics-ownership.js';import { recordSaleAndSplit, isMint } from '../_lib/cosmetics-economy.js';import cosmeticPurchaseListing from '../_lib/service-catalog/services/cosmetic-purchase.js';@@ -147,6 +154,18 @@ function sendDiscoveryChallenge(res, errText) {});}+// Who may be re-granted an item on the FREE SIWX re-access path (no payment in+// this request). Two cases are legitimate:+// • the signing wallet is the target account, the buyer re-confirming their+// own unlock from a new device or after a cache wipe;+// • the target account already owns the item, a guest profile re-confirming+// an unlock that was paid for earlier.+// Anything else is a fresh sale and must be paid for. Pure; exported for tests.+export function siwxReGrantAllowed({ account, payer, alreadyOwned }) {+ if (alreadyOwned) return true;+ return !!payer && normalizeAccountId(payer) === account;+}+// Per-item paidEndpoint built on the fly: the id picks the catalog row, which// dictates the USDC price; everything else is shared. Mirrors asset-download.js,// where the slug drives a per-row price + SIWX grant.@@ -229,7 +248,28 @@ export default async function handler(req, res) {ttlSeconds: null,expirationSeconds: 300,},- async handler({ requirement, payer }) {+ async handler({ requirement, payer, bypass }) {+ // Free SIWX re-access: nothing settled this call (no `requirement`) and+ // no authorized bypass granted it (a subscription or scoped caller keeps+ // its access). Only re-confirm an unlock the account is already entitled+ // to; a signature must never unlock the item for a THIRD account. 402,+ // not 403, so an x402 client falls straight through to paying for it.+ if (!requirement && !bypass) {+ const allowed = siwxReGrantAllowed({+ account,+ payer,+ alreadyOwned: await ownsCosmetic(account, item.id),+ });+ if (!allowed) {+ throw new X402Error(+ 'account_not_entitled',+ `account "${account}" does not own "${item.name}". Signing in re-confirms an ` ++ 'unlock you already paid for; pay the challenge to unlock it for this account',+ 402,+ );+ }+ }+// Record ownership BEFORE settlement returns to the buyer. grant throws// (503) if the durable store is missing — fail closed, so we never settle// a charge we can't record. Idempotent: a re-paid/replayed call justdiff --git a/api/x402/cross-chain.js b/api/x402/cross-chain.jsindex 96747258a..2c2e74ef5 100644--- a/api/x402/cross-chain.js+++ b/api/x402/cross-chain.js@@ -127,8 +127,9 @@ const BRIDGE_PROBES = [url: 'https://li.quest/v1/chains?chainTypes=SVM',check: (data) => {// Li.Fi chains endpoint returns { chains: [...] }. A non-empty array- // means the Solana lane is advertised. A maintenance_message on any- // chain signals partial degradation; we report that separately below.+ // means the Solana lane is advertised; an empty one (or a body without+ // the array) means Li.Fi is not routing SVM right now, which is the+ // outage this probe exists to catch.const chains = Array.isArray(data?.chains) ? data.chains : [];return chains.length > 0;},@@ -160,8 +161,12 @@ async function probebridge({ chain, provider, url, check }) {if (!res.ok) {status = 'down';} else {+ // A 200 whose body will not parse as JSON is an error page from an+ // edge/proxy in front of the provider, not a healthy API. Leave `data`+ // null and let check() judge it. Every probe below reads a required+ // field, so a null body classifies as down, which is the honest call.let data = null;- try { data = await res.json(); } catch { /* binary/non-JSON response = treat as up */ }+ try { data = await res.json(); } catch { /* null body → check() reports down */ }const isUp = check(data);if (!isUp) {status = 'down';diff --git a/api/x402/d/[...path].js b/api/x402/d/[...path].jsindex c2ccf7e4a..0521eabdd 100644--- a/api/x402/d/[...path].js+++ b/api/x402/d/[...path].js@@ -16,6 +16,7 @@// upstream outages throw AFTER verify but BEFORE settle — never charged.import { paidEndpoint } from '../../_lib/x402-paid-endpoint.js';+import { cors, error } from '../../_lib/http.js';import { buildBazaarSchema } from '../../_lib/x402-spec.js';import { installAccessControl } from '../../_lib/x402/access-control.js';import { withService } from '../../_lib/x402/bazaar-helpers.js';@@ -94,15 +95,6 @@ function instanceFor(parsed) {return inst;}-function sendJson(res, status, obj) {- res.statusCode = status;- if (typeof res.setHeader === 'function') {- res.setHeader('content-type', 'application/json; charset=utf-8');- res.setHeader('access-control-allow-origin', '*');- }- res.end(JSON.stringify(obj));-}-export default async function handler(req, res) {const pathname = (req.url || '').split('?')[0];const segments = pathname.startsWith(PREFIX)@@ -115,9 +107,12 @@ export default async function handler(req, res) {try {parsed = parseDatapointPath(segments);} catch (err) {- return sendJson(res, err.status || 404, {- error: err.code || 'not_found',- message: err.message,+ // Same error envelope every other api/ handler emits ({ error,+ // error_description }), plus the two fields that make this particular+ // 404 self-service: where the catalog lives and what the valid families+ // are. A bad path is never cacheable, which error() enforces.+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ return error(res, err.status || 404, err.code || 'not_found', err.message, {catalog: '/api/x402/d',families: Object.keys(DATAPOINT_FAMILIES),});diff --git a/api/x402/did.js b/api/x402/did.jsindex d0233c84d..8e095de9c 100644--- a/api/x402/did.js+++ b/api/x402/did.js@@ -260,6 +260,37 @@ async function readBody(req) {}}+// Turn one resolution attempt into the canary verdict. Pure (no I/O), so the+// verdict logic is unit-testable without a live resolver, same pattern as+// validateDidDocument above.+//+// `configured` answers "is a DID document published here", which only a real+// HTTP answer can settle: 404 proves no document, any other status proves one+// is being served. A transport failure (http_status 0: DNS, TLS, timeout)+// proves neither, so it reports false rather than claiming a document we never+// saw. `fetch_error` distinguishes that case from a genuine 404.+export function summarizeResolution({ httpStatus, doc, latency_ms, did, fetchError = null }) {+ const checks = validateDidDocument(doc);+ const configured = httpStatus > 0 && httpStatus !== 404;+ const malformed = httpStatus !== 200 || !checks.valid;+ const within_latency = latency_ms <= MAX_LATENCY_MS;++ return {+ verified: !malformed && within_latency,+ latency_ms,+ did,+ mode: 'verify',+ resolved_did: typeof doc?.id === 'string' ? doc.id : null,+ http_status: httpStatus,+ within_latency,+ malformed,+ configured,+ checks,+ ...(fetchError ? { fetch_error: fetchError } : {}),+ ts: new Date().toISOString(),+ };+}+async function runVerify({ did }) {const url = `${publicOrigin()}/.well-known/did.json`;const t0 = Date.now();@@ -277,27 +308,8 @@ async function runVerify({ did }) {} catch (err) {fetchError = err?.message || 'fetch_failed';}- const latency_ms = Date.now() - t0;- const configured = httpStatus !== 404;- const checks = validateDidDocument(doc);- const malformed = httpStatus !== 200 || !checks.valid;- const within_latency = latency_ms <= MAX_LATENCY_MS;- const verified = !malformed && within_latency;- return {- verified,- latency_ms,- did,- mode: 'verify',- resolved_did: typeof doc?.id === 'string' ? doc.id : null,- http_status: httpStatus,- within_latency,- malformed,- configured,- checks,- ...(fetchError ? { fetch_error: fetchError } : {}),- ts: new Date().toISOString(),- };+ return summarizeResolution({ httpStatus, doc, latency_ms: Date.now() - t0, did, fetchError });}// Sweep the N most recently created agent identities and check each for@@ -366,8 +378,15 @@ const verifyCanary = paidEndpoint({});// ── Dispatch by method ───────────────────────────────────────────────────────+// Only the two documented verbs are served. Anything else used to fall through+// to the GET publisher, so a PUT or DELETE answered with the DID document,+// which reads to a client (and to any cache in front of us) as if the write+// succeeded. 405 says plainly that the resource is read-or-pay only.export default function handler(req, res) {if (req.method === 'POST') return verifyCanary(req, res);- // GET / HEAD / OPTIONS → free DID document publisher.- return handleDidDocument(req, res);+ if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') {+ return handleDidDocument(req, res);+ }+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;+ return error(res, 405, 'method_not_allowed', 'use GET for the DID document or POST for the verification canary');}diff --git a/api/x402/fact-check.js b/api/x402/fact-check.jsindex 345e77c0a..67f745cce 100644--- a/api/x402/fact-check.js+++ b/api/x402/fact-check.js@@ -7,7 +7,7 @@//// Real-Time Fact Checker.// • Free tier: 3 checks/day per IP — the REAL search+LLM chain, never a-// degraded fake (see 00-CONTEXT.md's no-mocks rule). Response carries+// degraded fake (see CLAUDE.md's no-mocks rule). Response carries// `lane: "free"` and `free_remaining_today`.// • Above the free tier (quota exhausted OR an X-PAYMENT header is present)// the request falls through to the x402 rail: $0.10 base (100_000@@ -21,9 +21,10 @@// costBreakdown, cachedAt?, attestation, lane, free_remaining_today? }import { createHash } from 'crypto';-import { wrap, error, json, readBody } from '../_lib/http.js';+import { cors, wrap, error, json, readBody } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { priceFor } from '../_lib/x402-prices.js';import { buildBazaarSchema } from '../_lib/x402-spec.js';import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';@@ -574,7 +575,7 @@ function paidHandler() {_paid = paidEndpoint({route: ROUTE,method: 'POST',- priceAtomics: 100_000, // $0.10+ priceAtomics: priceFor('fact-check', '100000'), // $0.10networks: ['base', 'solana'],description: DESCRIPTION,bazaar: BAZAAR,@@ -601,6 +602,12 @@ function paidHandler() {// ── Entry point: free daily quota → x402 fall-through ────────────────────────export default wrap(async function handler(req, res) {+ // The paid rail sets these on every response it writes; the free lane runs+ // outside it, so without this a cross-origin caller passed the OPTIONS+ // preflight (answered by the paid rail) and then had the actual free-lane+ // 200/400 blocked by the browser for lacking allow-origin. Same header set,+ // same allowed methods, so both lanes look identical to a CORS reader.+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;if (req.method !== 'POST') return paidHandler()(req, res); // let the paid rail's own 405 speak// Buffer the body once; the paid rail re-reads the same bytesdiff --git a/api/x402/feed-health.js b/api/x402/feed-health.jsindex a7c91463f..1361f1132 100644--- a/api/x402/feed-health.js+++ b/api/x402/feed-health.js@@ -94,8 +94,9 @@ const BAZAAR = {const xmlParser = new XMLParser({ ignoreAttributes: false, parseTagValue: true });// Read the canonical changelog record from the compiled public asset. The file-// is bundled into the Vercel deployment alongside the API so readFileSync is-// safe here. We load it once per cold start — it only changes on deploy.+// is baked into the container image alongside the API (server/index.mjs serves+// both), so readFileSync is safe here. We load it once per cold start; it only+// changes on deploy.let _changelogEntries = null;function getChangelogEntries() {if (_changelogEntries) return _changelogEntries;diff --git a/api/x402/forge.js b/api/x402/forge.jsindex 31d21099b..908e11b78 100644--- a/api/x402/forge.js+++ b/api/x402/forge.js@@ -263,7 +263,7 @@ async function persistRemoteGlb(url) {const buf = Buffer.from(await res.arrayBuffer());if (!buf.length) return null;const { putObject, publicUrl } = await import('../_lib/r2.js');- const key = `forge/huggingface/${globalThis.crypto.randomUUID()}.glb`;+ const key = `forge/huggingface/${randomUUID()}.glb`;await putObject({ key, body: buf, contentType: 'model/gltf-binary' });return publicUrl(key);} catch {diff --git a/api/x402/gas-oracle.js b/api/x402/gas-oracle.jsindex 4c3633d80..654659835 100644--- a/api/x402/gas-oracle.js+++ b/api/x402/gas-oracle.js@@ -249,7 +249,13 @@ export default paidEndpoint({async handler() {let gas = null;- try { gas = await loadGas(); } catch { /* refund below */ }+ try {+ gas = await loadGas();+ } catch (err) {+ // Every chain's failover set was exhausted. The buyer gets the 503 below+ // (pre-settle, nothing charged); this is the only place the cause exists.+ console.warn(`[x402/gas-oracle] gas load failed on every chain: ${err?.message || err}`);+ }if (!gas) {throw Object.assign(new Error('gas data is temporarily unavailable on every chain'), {status: 503,diff --git a/api/x402/granite-health.js b/api/x402/granite-health.jsindex 097d7d8b5..a0e821ead 100644--- a/api/x402/granite-health.js+++ b/api/x402/granite-health.js@@ -31,13 +31,16 @@ export default wrap(async (req, res) => {// here would be indistinguishable from this endpoint being down.return json(res, 200, { ...health, generated_at: new Date().toISOString() });} catch (err) {- // Table absent (loop never ran) or DB hiccup — report empty-but-healthy so- // the dashboard shows "no data yet" instead of an error void.+ // Table absent (loop never ran) means the backend simply has no verdict yet:+ // report empty-but-healthy so the dashboard shows "no data yet" instead of+ // an error void, matching readGraniteHealth's own no-row default. A real DB+ // failure is different and must not claim healthy:true, or a dashboard reads+ // green through an outage it cannot see.const noData = /does not exist/i.test(err?.message || '');return json(res, noData ? 200 : 503, {ok: noData,server: 'ibm-x402-mcp',- healthy: true,+ healthy: noData,latest: null,window: { checks: 0, total_tokens: 0 },generated_at: new Date().toISOString(),diff --git a/api/x402/hack-check.js b/api/x402/hack-check.jsindex 0774cbbce..b2abb9874 100644--- a/api/x402/hack-check.js+++ b/api/x402/hack-check.js@@ -178,7 +178,14 @@ export default paidEndpoint({const limit = Math.min(50, Math.max(1, Number.isFinite(limitRaw) ? Math.floor(limitRaw) : 10));let data = null;- try { data = await loadDataset(); } catch { /* refund below */ }+ try {+ data = await loadDataset();+ } catch (err) {+ // The buyer gets the 503 below (pre-settle, so nothing is charged), but+ // the upstream reason only exists here. Log it, or an outage stays+ // invisible to ops until someone reads the refund count.+ console.warn(`[x402/hack-check] exploit dataset load failed: ${err?.message || err}`);+ }if (!data || !data.hacks.length) {throw Object.assign(new Error('exploit database is temporarily unavailable'), {status: 503,diff --git a/api/x402/llm-proxy.js b/api/x402/llm-proxy.jsindex 18f7f0609..f03ef8be7 100644--- a/api/x402/llm-proxy.js+++ b/api/x402/llm-proxy.js@@ -44,6 +44,7 @@ import {issueInferenceReceipt,} from '../_lib/inference-settlement.js';import { recordInferenceJob } from '../_lib/inference-jobs.js';+import { priceFor } from '../_lib/x402-prices.js';import llmProxyListing from '../_lib/service-catalog/services/llm-proxy.js';const ROUTE = '/api/x402/llm-proxy';@@ -170,7 +171,7 @@ const BAZAAR = {export default paidEndpoint({route: ROUTE,method: 'POST',- priceAtomics: 5_000, // $0.005 USDC+ priceAtomics: priceFor('llm-proxy', '5000'), // $0.005 USDCnetworks: ['base', 'solana'],description: DESCRIPTION,bazaar: BAZAAR,@@ -228,10 +229,11 @@ export default paidEndpoint({// Phase 4 metering: bind the job identity to hashes of the exact prompt// and completion plus the provider-reported token counts, and sign that- // core. Unsigned when INFERENCE_SIGNING_KEY is unset (the rollback- // toggl metering core still ships so callers can re-hash.+ // core. When INFERENCE_SIGNING_KEY is unset the signature is omitted but+ // the metering core still ships, so a caller can re-hash the prompt and+ // completion themselves and confirm the job identity.const job = meterInferenceJob({- jobId: crypto.randomUUID(),+ jobId: randomUUID(),route: ROUTE,model: result.model,provider: result.provider,diff --git a/api/x402/mcp-tool-catalog.js b/api/x402/mcp-tool-catalog.jsindex 9cc61a305..5f66d9c97 100644--- a/api/x402/mcp-tool-catalog.js+++ b/api/x402/mcp-tool-catalog.js@@ -28,6 +28,7 @@ import { readBody } from '../_lib/http.js';import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { priceFor as x402PriceFor } from '../_lib/x402-prices.js';import { sql } from '../_lib/db.js';@@ -188,6 +189,9 @@ export default paidEndpoint({serviceName: 'three.ws MCP Tool Discovery',tags: ['mcp', 'discovery', 'tools', 'catalog', 'feature-flag', 'agent'],}),+ // Same internal / subscription / OAuth bypass every other paid x402 route+ // carries, so first-party callers read the catalog without a payment leg.+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),async handler({ req }) {let mode = 'discover';diff --git a/api/x402/mint-to-mesh-batch.js b/api/x402/mint-to-mesh-batch.jsindex 4bac2c136..5755a5b1b 100644--- a/api/x402/mint-to-mesh-batch.js+++ b/api/x402/mint-to-mesh-batch.js@@ -35,8 +35,8 @@ const DESCRIPTION =const INPUT_EXAMPLE = {mints: [- 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi',- 'F7kXZYXWVUTSRQPONMLKJIHGFEDCba9876543210xyz',+ 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ 'THREEsynthetic1111111111111111111111111111',],};@@ -59,11 +59,21 @@ const OUTPUT_EXAMPLE = {results: [{ok: true,- mint: 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi',- theme: { name: 'Helios', symbol: 'HELIO', color: [220, 180, 80], hasImage: true },- glb: { mimeType: 'model/gltf-binary', bytes: 18000, base64: 'Z2xUR...' },+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ theme: {+ name: 'three.ws',+ symbol: 'three',+ color: [0.235, 0.382, 0.865],+ hasImage: true,+ },+ glb: { mimeType: 'model/gltf-binary', bytes: 583452, base64: 'Z2xURgIAAAAc5wgA...' },+ },+ {+ ok: false,+ mint: 'THREEsynthetic1111111111111111111111111111',+ error: 'invalid_mint',+ error_description: 'invalid mint address',},- { ok: false, mint: 'F7kXZ...', error: 'meta_fetch_failed', error_description: 'RPC 429' },],indexed_at: '2026-05-14T17:00:00Z',};diff --git a/api/x402/mint-to-mesh.js b/api/x402/mint-to-mesh.jsindex b55b512c8..ee3edfcac 100644--- a/api/x402/mint-to-mesh.js+++ b/api/x402/mint-to-mesh.js@@ -7,9 +7,10 @@//// Paid endpoint cataloged by the CDP x402 Bazaar (agentic.market) and the// pay-skills registry. For $0.001 USDC the server reads the token's on-chain-// Metaplex metadata, resolves the off-chain JSON, fetches the image (when one-// is exposed), and returns a themed binary glTF cube ready for any Three.js /-// Babylon.js / model-viewer instance to render.+// metadata (the Token-2022 TokenMetadata extension when the mint carries one,+// else the Metaplex PDA), resolves the off-chain JSON, fetches the image (when+// one is exposed), and returns a themed binary glTF cube ready for any+// Three.js / Babylon.js / model-viewer instance to render.//// The cube is procedurally synthesized per request via @gltf-transform — no// templated asset, no headless WebGL, no S3. Output ships as base64 inside a@@ -32,7 +33,6 @@ import {resolveResourceUrl,buildBazaarSchema,} from '../_lib/x402-spec.js';-import { env } from '../_lib/env.js';import { createThemedGLB, colorFromMint } from '../_lib/glb-themer.js';import { fetchTokenMeta } from '../_lib/solana-token-meta.js';import {@@ -92,10 +92,10 @@ const DISCOVERY_INPUT_SCHEMA = {const DISCOVERY_OUTPUT_EXAMPLE = {mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',theme: {- name: 'three',- symbol: 'THREE',- color: [0.92, 0.45, 0.18],- hasImage: false,+ name: 'three.ws',+ symbol: 'three',+ color: [0.235, 0.382, 0.865],+ hasImage: true,},glb: {mimeType: 'model/gltf-binary',@@ -261,7 +261,7 @@ export default wrap(async (req, res) => {res,400,'invalid_mint',- 'mint must be a base58 SPL address (32–44 chars)',+ 'mint must be a base58 SPL address (32 to 44 chars)',);let result;try {@@ -331,7 +331,7 @@ export default wrap(async (req, res) => {}if (!BASE58_RE.test(mint)) {if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });- return error(res, 400, 'invalid_mint', 'mint must be a base58 SPL address (32–44 chars)');+ return error(res, 400, 'invalid_mint', 'mint must be a base58 SPL address (32 to 44 chars)');}let result;diff --git a/api/x402/model-check.js b/api/x402/model-check.jsindex 2901028f7..de36e806e 100644--- a/api/x402/model-check.js+++ b/api/x402/model-check.js@@ -28,7 +28,6 @@ import {resolveResourceUrl,buildBazaarSchema,} from '../_lib/x402-spec.js';-import { env } from '../_lib/env.js';import { inspectModel, suggestOptimizations } from '../_lib/model-inspect.js';import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';import {diff --git a/api/x402/model-validation-sweep.js b/api/x402/model-validation-sweep.jsindex 58f15588c..5bb52bc35 100644--- a/api/x402/model-validation-sweep.js+++ b/api/x402/model-validation-sweep.js@@ -17,6 +17,7 @@import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { priceFor } from '../_lib/x402-prices.js';import { sql } from '../_lib/db.js';@@ -24,8 +25,7 @@ import { inspectModel, suggestOptimizations } from '../_lib/model-inspect.js';import { getObjectBuffer } from '../_lib/r2.js';const ROUTE = '/api/x402/model-validation-sweep';-const MAX_BYTES = 16 * 1024 * 1024; // 16 MB cap — mirrors model-check.js-const STALE_AFTER = "24 hours";+const MAX_BYTES = 16 * 1024 * 1024; // 16 MB cap, mirrors model-check.jsconst DESCRIPTION ='three.ws model quality sweep — picks the next public GLB avatar in the ' +@@ -67,6 +67,10 @@ const OUTPUT_SCHEMA = {ok: { type: 'boolean' },skipped: { type: 'boolean' },reason: { type: 'string' },+ error: {+ type: 'string',+ description: 'Set with ok:false when the queued model could not be downloaded or parsed.',+ },avatar_id: { type: 'string', format: 'uuid' },avatar_name: { type: ['string', 'null'] },score: { type: 'integer', minimum: 0, maximum: 100 },@@ -183,6 +187,9 @@ export default paidEndpoint({serviceName: 'three.ws Model Validation Sweep',tags: ['3d', 'gltf', 'glb', 'validation', 'quality', 'sweep'],}),+ // Same internal / subscription / OAuth bypass every other paid x402 route+ // carries, so an operator can run the sweep without a payment leg.+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),async handler() {await ensureSchema();diff --git a/api/x402/my-receipts.js b/api/x402/my-receipts.jsindex 63eaa1188..5edcbecda 100644--- a/api/x402/my-receipts.js+++ b/api/x402/my-receipts.js@@ -57,19 +57,22 @@ function withinFreshnessWindow(issuedAt) {// Decimals for the settlement assets THIS deployment actually pays in, read// from the same env config that builds the 402 accepts — so a client never has// to keep its own copy of our asset addresses (which would silently drift the-// day an asset is repointed). Every configured asset is 6-decimal USDC; an+// day an asset is repointed). Every asset advertised in an accept is covered:+// USDC on Solana/Base/BSC, USD₮0 on X Layer, and $THREE on the Solana rail. An// asset we don't recognise returns null and the client renders the raw atomic// amount rather than guessing a scale.function assetDecimals(asset) {if (!asset) return null;const want = String(asset).toLowerCase();const configured = [- env.X402_ASSET_MINT_SOLANA,- env.X402_ASSET_ADDRESS_BASE,- env.X402_ASSET_ADDRESS_BSC,+ [env.X402_ASSET_MINT_SOLANA, 6],+ [env.X402_ASSET_ADDRESS_BASE, 6],+ [env.X402_ASSET_ADDRESS_BSC, 6],+ [env.X402_ASSET_ADDRESS_XLAYER, 6],+ [env.THREE_TOKEN_MINT, env.THREE_TOKEN_DECIMALS],];- for (const known of configured) {- if (known && String(known).toLowerCase() === want) return 6;+ for (const [known, decimals] of configured) {+ if (known && String(known).toLowerCase() === want) return decimals;}return null;}diff --git a/api/x402/news-pulse.js b/api/x402/news-pulse.jsindex 365a739e0..260b2a321 100644--- a/api/x402/news-pulse.js+++ b/api/x402/news-pulse.js@@ -118,7 +118,7 @@ export default paidEndpoint({if (!/^[A-Z0-9]{2,10}$/.test(rawTicker)) {// Validation failure is thrown (not settled) so the buyer is not charged// for a malformed request — the wrapper maps this to a 422 before settle.- throw Object.assign(new Error('ticker must be 2–10 alphanumeric characters, e.g. BTC'), {+ throw Object.assign(new Error('ticker must be 2 to 10 alphanumeric characters, e.g. BTC'), {status: 422,code: 'invalid_ticker',});diff --git a/api/x402/rate-limit-probe.js b/api/x402/rate-limit-probe.jsindex 025c5cbb0..f0f81c287 100644--- a/api/x402/rate-limit-probe.js+++ b/api/x402/rate-limit-probe.js@@ -5,7 +5,8 @@// before scheduling high-frequency oracle calls — if remaining_calls is low,// lower-priority entries yield their slot so oracle throughput is preserved.//-// Body: { endpoint: "/api/x402/crypto-intel" }+// Body: { endpoint: "/api/x402/crypto-intel" }, a metered route (/api/x402*,+// /api/mcp*, /api/ibm-mcp); any other path is rejected 400 before the probe runs.//// Response:// endpoint — echoed from body@@ -44,15 +45,17 @@ const DESCRIPTION ='USDC spend cap. Returns remaining_calls, reset_at, and cooldown_active so agents ' +'can throttle dynamically instead of discovering the cap by failure.';-const INPUT_SCHEMA = {+export const INPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',type: 'object',required: ['endpoint'],properties: {endpoint: {type: 'string',- description: 'Relative path of the target x402 endpoint, e.g. "/api/x402/crypto-intel".',- pattern: '^/api/',+ description:+ 'Relative path of the target x402 endpoint, e.g. "/api/x402/crypto-intel". Must be a ' ++ 'metered route: /api/x402*, /api/mcp* or /api/ibm-mcp. Anything else is rejected 400.',+ pattern: '^/api/(x402|mcp|ibm-mcp)([/?-]|$)',},},};@@ -114,6 +117,24 @@ function dailySpendKey() {return `${DAILY_SPEND_PREFIX}${new Date().toISOString().slice(0, 10)}`;}+// The probe below makes the server POST to `origin + endpoint` with no auth, so+// a caller must not be able to aim it at an arbitrary internal route. Every HTTP+// path the autonomous registry actually meters sits under one of these prefixes+// (verified against getSelfRegistry()), which is also exactly the set of routes+// that answer a 402 challenge, so this costs the product nothing.+const PROBEABLE_PREFIXES = ['/api/x402', '/api/mcp', '/api/ibm-mcp'];++function isProbeableEndpoint(endpoint) {+ if (endpoint.includes('..')) return false;+ return PROBEABLE_PREFIXES.some(+ (prefix) =>+ endpoint === prefix ||+ endpoint.startsWith(`${prefix}/`) ||+ endpoint.startsWith(`${prefix}?`) ||+ endpoint.startsWith(`${prefix}-`),+ );+}+// Probe the target endpoint (no payment header) to learn its 402 challenge price.// Returns the smallest price_atomic across all offered accepts, or null on failure.async function probeEndpointPrice(origin, endpoint) {@@ -223,6 +244,14 @@ export default paidEndpoint({err.code = 'invalid_endpoint';throw err;}+ if (!isProbeableEndpoint(endpoint)) {+ const err = new Error(+ `"endpoint" must be a metered x402 route (${PROBEABLE_PREFIXES.join(', ')})`,+ );+ err.status = 400;+ err.code = 'endpoint_not_metered';+ throw err;+ }const origin = env.APP_ORIGIN || 'https://three.ws';const redis = getRedis();diff --git a/api/x402/remix-asset.js b/api/x402/remix-asset.jsindex 8fde67bc4..955bb0968 100644--- a/api/x402/remix-asset.js+++ b/api/x402/remix-asset.js@@ -20,7 +20,7 @@import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';import { buildBazaarSchema } from '../_lib/x402-spec.js';-import { readJson, json } from '../_lib/http.js';+import { readJson } from '../_lib/http.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { getRemixSource, linkRefinement } from '../_lib/forge-store.js';import { settleRemixRoyalty } from '../_lib/remix-settlement.js';@@ -221,15 +221,11 @@ export default paidEndpoint({serviceName: 'Remix a 3D asset + royalties',tags: ['3d', 'remix', 'royalties', 'generation'],}),- handler: async ({ req, res, requirement }) => {- try {- return await handleRemix({ req, requirement });- } catch (err) {- if (err instanceof RemixError) {- json(res, err.status, { error: err.code, message: err.message });- return undefined; // response already written; paidEndpoint skips settle- }- throw err;- }- },+ // RemixError carries .status + .code, which is exactly what paidEndpoint's own+ // catch maps to a clean error response before settlement runs. Writing the+ // response here instead made paidEndpoint see a handler that flushed without+ // settling: it logged a payment_unsettled_flush leak, recorded a failed+ // payment metric and threw, so every ordinary 400 (bad source id, empty+ // instruction) read as a money leak in the x402 telemetry.+ handler: handleRemix,});diff --git a/api/x402/schema-check.js b/api/x402/schema-check.jsindex 419ba8564..c8f700705 100644--- a/api/x402/schema-check.js+++ b/api/x402/schema-check.js@@ -89,8 +89,6 @@ const BAZAAR = {}),};-const SUPPORTED_APIS = new Set(['changelog_json']);-// Validate the /changelog.json feed against its declared schema.// Returns { valid, version, entry_count, schema_errors }.function validateChangelogJson(data) {@@ -160,14 +158,56 @@ function validateChangelogJson(data) {async function readBody(req) {if (req.body && typeof req.body === 'object') return req.body;try {- const chunks = [await readRawBody(req, 1_000_000)];- const raw = Buffer.concat(chunks).toString('utf8').trim();+ const raw = (await readRawBody(req, 1_000_000)).toString('utf8').trim();return raw ? JSON.parse(raw) : {};} catch {return {};}}+// Fetch /changelog.json and check it against the shape above. A fetch failure is+// itself a finding (the feed holders read is down), so it resolves to a report+// with valid:false rather than throwing: the buyer paid for a verdict and gets one.+async function checkChangelogJson(origin, fetched_at) {+ const url = `${origin}/changelog.json`;+ let data = null;+ let fetchError = null;++ try {+ const res = await fetch(url, {+ headers: { accept: 'application/json', 'user-agent': 'threews-schema-check/1.0' },+ signal: AbortSignal.timeout(10_000),+ });+ if (!res.ok) {+ fetchError = `http_${res.status}`;+ } else {+ data = await res.json();+ }+ } catch (err) {+ fetchError = err?.message || 'fetch_failed';+ }++ if (fetchError || data === null) {+ return {+ ok: false,+ api: 'changelog_json',+ valid: false,+ version: null,+ entry_count: 0,+ schema_errors: [fetchError || 'fetch_failed'],+ fetched_at,+ };+ }++ const { valid, version, entry_count, schema_errors } = validateChangelogJson(data);+ return { ok: true, api: 'changelog_json', valid, version, entry_count, schema_errors, fetched_at };+}++// Dispatch table: the enum in INPUT_SCHEMA, the 400 message and the runtime+// branch all read from these keys, so adding a target is one entry, not four.+const CHECKERS = { changelog_json: checkChangelogJson };+const SUPPORTED_APIS = Object.keys(CHECKERS);+export default paidEndpoint({route: ROUTE,method: 'POST',@@ -180,56 +220,26 @@ export default paidEndpoint({tags: ['schema', 'validation', 'changelog', 'health', 'api'],}),- async handler(req) {+ // paidEndpoint hands the handler a context object, NOT the request: taking+ // `req` positionally here read the body off the context, found none, and made+ // every paid call answer 'unsupported api "undefined"' after settling.+ async handler({ req }) {const body = await readBody(req);const api = body?.api;-- if (!api || !SUPPORTED_APIS.has(api)) {- return {- ok: false,- error: `unsupported api "${api}"; supported: ${[...SUPPORTED_APIS].join(', ')}`,- };+ // hasOwn, not a bare lookup: `{"api":"constructor"}` would otherwise resolve+ // to an inherited function and be called as if it were a checker.+ const check = typeof api === 'string' && Object.hasOwn(CHECKERS, api) ? CHECKERS[api] : undefined;++ // Thrown before settlement runs, so an unsupported target costs the caller+ // nothing instead of billing them for an error body.+ if (!check) {+ const err = new Error(`unsupported api "${api}"; supported: ${SUPPORTED_APIS.join(', ')}`);+ err.status = 400;+ err.code = 'unsupported_api';+ throw err;}const origin = (env.APP_ORIGIN || 'https://three.ws').replace(/\/$/, '');- const fetched_at = new Date().toISOString();-- if (api === 'changelog_json') {- const url = `${origin}/changelog.json`;- let data = null;- let fetchError = null;-- try {- const res = await fetch(url, {- headers: { accept: 'application/json', 'user-agent': 'threews-schema-check/1.0' },- signal: AbortSignal.timeout(10_000),- });- if (!res.ok) {- fetchError = `http_${res.status}`;- } else {- data = await res.json();- }- } catch (err) {- fetchError = err?.message || 'fetch_failed';- }-- if (fetchError || data === null) {- return {- ok: false,- api,- valid: false,- version: null,- entry_count: 0,- schema_errors: [fetchError || 'fetch_failed'],- fetched_at,- };- }-- const { valid, version, entry_count, schema_errors } = validateChangelogJson(data);- return { ok: true, api, valid, version, entry_count, schema_errors, fetched_at };- }-- // Unreachable given the SUPPORTED_APIS guard above, but keeps linting clean.- return { ok: false, error: 'unhandled_api' };+ return check(origin, new Date().toISOString());},});diff --git a/api/x402/skill-call.js b/api/x402/skill-call.jsindex 3f1c737c8..c4755324e 100644--- a/api/x402/skill-call.js+++ b/api/x402/skill-call.js@@ -22,7 +22,7 @@ import { buildBazaarSchema, paymentRequirements, send402 } from '../_lib/x402-spimport { withService } from '../_lib/x402/bazaar-helpers.js';import { priceFor } from '../_lib/x402-prices.js';import { sql } from '../_lib/db.js';-import { error } from '../_lib/http.js';+import { cors, error, respondError } from '../_lib/http.js';import { env } from '../_lib/env.js';import { accrueSkillCallRoyalty } from '../_lib/skill-royalty.js';import skillCallListing from '../_lib/service-catalog/services/skill-call.js';@@ -153,6 +153,12 @@ function sendDiscoveryChallenge(res, errText) {}export default async function handler(req, res) {+ // paidEndpoint answers CORS itself, but every branch below can respond BEFORE+ // one is built (discovery challenge, unknown slug, free skill), and an+ // X-PAYMENT header always triggers a preflight. Without this the preflight was+ // answered with a bare 402 and no allow-origin, so no browser wallet could pay.+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+const slug = req.query?.skill ? String(req.query.skill).trim() : '';const paymentPresent = Boolean(req.headers['x-payment'] || req.headers['payment-signature']);if (!slug) {@@ -169,7 +175,10 @@ export default async function handler(req, res) {try {skill = await loadSkill(slug);} catch (err) {- return error(res, 502, 'skill_lookup_failed', err.message);+ // respondError, not error(): a 5xx must not echo the driver's own message+ // back to a buyer (the DB outage path answered "Missing required env var:+ // DATABASE_URL"). It sanitizes and hands back a support ref instead.+ return respondError(res, 502, 'skill_lookup_failed', err);}if (!skill) {if (paymentPresent) {diff --git a/api/x402/skill-marketplace.js b/api/x402/skill-marketplace.jsindex 894e1c24e..a49b8bfc9 100644--- a/api/x402/skill-marketplace.js+++ b/api/x402/skill-marketplace.js@@ -313,7 +313,9 @@ function runCanaryExecute(skillName) {// ── Popular-skills query (POST mode="popular") ────────────────────────────────// Reads the real agent_hires ledger (completed hires, last 7 days) grouped by-// skill_name and returns the top N skills by purchase count.+// skill_name and returns the top N skills by purchase count. A database fault+// propagates: the wrapper maps it to a 503 BEFORE settlement, so a buyer is+// never charged for an empty list that reads like "nobody hired anything".async function loadPopularSkills(limit) {const rows = await sql`select@@ -327,9 +329,9 @@ async function loadPopularSkills(limit) {group by h.skill_nameorder by purchases desc, h.skill_name asclimit ${limit}- `.catch(() => []);+ `;- const skills = (rows || []).map((r) => ({+ const skills = rows.map((r) => ({id: r.id,name: r.name,purchases: Number(r.purchases || 0),@@ -409,6 +411,7 @@ const postEndpoint = paidEndpoint({'unsupported mode — use { mode: "canary_execute" }, { mode: "price_distribution" }, or { mode: "popular" }',);err.status = 400;+ err.code = 'invalid_mode';throw err;},});diff --git a/api/x402/spend-session.js b/api/x402/spend-session.jsindex 26cf7a622..9b231e98a 100644--- a/api/x402/spend-session.js+++ b/api/x402/spend-session.js@@ -61,6 +61,7 @@ const OUTPUT_EXAMPLE = {mode: 'canary',created: true,consumed: true,+ reason: null,latency_ms: 12,session_id: 'a3f3d6c2-1f1b-4f10-9b6c-1b1f5e0c9c34',budget: 0.01,@@ -80,6 +81,7 @@ const OUTPUT_SCHEMA = {// canary fieldscreated: { type: 'boolean', description: 'Canary: DB INSERT succeeded.' },consumed: { type: 'boolean', description: 'Canary: DB UPDATE (consume) succeeded.' },+ reason: { type: ['string', 'null'], description: 'Canary: why created/consumed is false; null when the cycle succeeded.' },latency_ms: { type: 'integer', minimum: 0, description: 'Canary: create+consume round-trip ms.' },session_id: { type: 'string', format: 'uuid' },budget: { type: ['number', 'null'] },@@ -151,6 +153,7 @@ async function handleCanary({ meta, mode, budget }) {const sessionId = randomUUID();let created = false;let consumed = false;+ let reason = null;const t0 = Date.now();try {@@ -171,8 +174,11 @@ async function handleCanary({ meta, mode, budget }) {WHERE session_id = ${sessionId}`;consumed = true;- } catch {- // DB failure — created/consumed stay false; latency still captured below.+ } catch (err) {+ // A DB failure IS the canary's verdict, not an endpoint error: created and+ // consumed stay false and the cause is reported so the alert is actionable+ // instead of an unexplained false.+ reason = err?.message ? String(err.message).slice(0, 300) : 'session_db_unavailable';}return {@@ -180,6 +186,7 @@ async function handleCanary({ meta, mode, budget }) {mode: 'canary',created,consumed,+ reason,latency_ms: Date.now() - t0,session_id: sessionId,budget,diff --git a/api/x402/stablecoin-health.js b/api/x402/stablecoin-health.jsindex ab5c2a48d..f984d0629 100644--- a/api/x402/stablecoin-health.js+++ b/api/x402/stablecoin-health.js@@ -32,7 +32,7 @@ function pctChange(now, prev) {return ((now - prev) / prev) * 100;}-function pegStatus(deviationBps) {+export function pegStatus(deviationBps) {if (deviationBps == null) return 'unknown';const abs = Math.abs(deviationBps);if (abs >= DEPEG_BPS) return 'depegged';@@ -40,6 +40,37 @@ function pegStatus(deviationBps) {return 'on-peg';}+// Normalize one upstream pegged asset into a scored coin row. Returns null for+// anything that is not a USD-pegged asset with real circulating supply, so the+// caller can skip it. Pure, so the peg verdict is testable without the network.+export function toCoin(a) {+ // USD-pegged assets only. The bps deviation math below is against $1.+ if (a?.pegType !== 'peggedUSD') return null;+ const circulating = Number(a?.circulating?.peggedUSD);+ if (!Number.isFinite(circulating) || circulating <= 0) return null;+ // Upstream omits `price` (null) for ~75 of the USD-pegged assets it tracks.+ // Number(null) is 0, so coercing first scored every one of them as a total+ // depeg (-10000 bps) and filled the alert list with coins that simply have+ // no quote. Only an actual number is a price; anything else is unknown.+ const price = typeof a.price === 'number' && Number.isFinite(a.price) ? a.price : null;+ const deviationBps = price != null ? Math.round((price - 1) * 10_000) : null;+ return {+ symbol: typeof a.symbol === 'string' ? a.symbol : null,+ name: typeof a.name === 'string' ? a.name : null,+ price,+ deviation_bps: deviationBps,+ status: pegStatus(deviationBps),+ mechanism: typeof a.pegMechanism === 'string' ? a.pegMechanism : null,+ circulating_usd: circulating,+ change_24h_pct: finite(pctChange(circulating, Number(a?.circulatingPrevDay?.peggedUSD))),+ change_7d_pct: finite(pctChange(circulating, Number(a?.circulatingPrevWeek?.peggedUSD))),+ change_30d_pct: finite(pctChange(circulating, Number(a?.circulatingPrevMonth?.peggedUSD))),+ chains: a.chainCirculating && typeof a.chainCirculating === 'object'+ ? Object.keys(a.chainCirculating).length+ : 0,+ };+}+async function loadStablecoins() {const now = Date.now();if (_cache && _cache.expiresAt > now) return _cache;@@ -55,28 +86,10 @@ async function loadStablecoins() {let totalCirculating = 0;const coins = [];for (const a of raw.peggedAssets) {- // USD-pegged assets only — the bps deviation math below is against $1.- if (a?.pegType !== 'peggedUSD') continue;- const circulating = Number(a?.circulating?.peggedUSD);- if (!Number.isFinite(circulating) || circulating <= 0) continue;- totalCirculating += circulating;- const price = finite(Number(a.price));- const deviationBps = price != null ? Math.round((price - 1) * 10_000) : null;- coins.push({- symbol: typeof a.symbol === 'string' ? a.symbol : null,- name: typeof a.name === 'string' ? a.name : null,- price,- deviation_bps: deviationBps,- status: pegStatus(deviationBps),- mechanism: typeof a.pegMechanism === 'string' ? a.pegMechanism : null,- circulating_usd: circulating,- change_24h_pct: finite(pctChange(circulating, Number(a?.circulatingPrevDay?.peggedUSD))),- change_7d_pct: finite(pctChange(circulating, Number(a?.circulatingPrevWeek?.peggedUSD))),- change_30d_pct: finite(pctChange(circulating, Number(a?.circulatingPrevMonth?.peggedUSD))),- chains: a.chainCirculating && typeof a.chainCirculating === 'object'- ? Object.keys(a.chainCirculating).length- : 0,- });+ const coin = toCoin(a);+ if (!coin) continue;+ totalCirculating += coin.circulating_usd;+ coins.push(coin);}coins.sort((a, b) => b.circulating_usd - a.circulating_usd);diff --git a/api/x402/symbol-availability.js b/api/x402/symbol-availability.jsindex 21310db2a..f7331e6d8 100644--- a/api/x402/symbol-availability.js+++ b/api/x402/symbol-availability.js@@ -272,9 +272,8 @@ const BATCH_BAZAAR = {};async function readJsonBody(req) {- const chunks = [await readBody(req, 1_000_000)];- if (!chunks.length) return {};- return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');+ const raw = (await readBody(req, 1_000_000)).toString('utf8');+ return JSON.parse(raw || '{}');}const batchEndpoint = paidEndpoint({diff --git a/api/x402/vanity-verifiable.js b/api/x402/vanity-verifiable.jsindex 6ed8beff6..dcef593ea 100644--- a/api/x402/vanity-verifiable.js+++ b/api/x402/vanity-verifiable.js@@ -385,6 +385,30 @@ async function grindAndBuildReceipt({ prefix, suffix, ignoreCase, sealTo, clientreturn response;}+// Cache-safe copy of a delivered receipt. The x402 replay/idempotency cache must+// never hold spendable key material at rest (same rule as api/x402/vanity.js),+// and TWO fields here are key-equivalent, so both have to go:+// 1. the plaintext secret (secretKeyBase58 / secretKey / seed), present+// whenever the buyer did not pass sealTo;+// 2. serverSeed, which is key-equivalent even on a SEALED delivery. The+// protocol is deterministic by design: masterSeed = HKDF(serverSeed ||+// clientSeed || requestNonce), and candidate `winningIndex` derives the+// Ed25519 secret from it. Anyone holding a full receipt can recompute the+// private key, which is exactly what makes the receipt verifiable.+// What stays is everything that cannot reconstruct the key: `commitment` is a+// preimage-resistant hash of serverSeed, and `sealedSecret` is ciphertext only+// the buyer's X25519 key opens. A replayed payment therefore gets the public+// metadata and an explicit marker, never a second copy of the secret.+export function cacheSafeBody(result) {+ const { secretKeyBase58, secretKey, seed, serverSeed, ...publicMeta } = result;+ void secretKeyBase58; void secretKey; void seed; void serverSeed;+ return JSON.stringify({+ ...publicMeta,+ secret_omitted_from_cache: true,+ note: 'The ground secret and the receipt\'s serverSeed are returned once, in the original response, and are never stored. Both are key-equivalent under three-vanity/v1, so neither is retained here. If you did not capture the receipt, grind again.',+ });+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (req.method !== 'GET') {@@ -510,7 +534,7 @@ export default wrap(async (req, res) => {payloadHash,paymentHash,status: 200,- body,+ body: cacheSafeBody(result),contentType,paymentResponseHeader,});diff --git a/api/x402/vanity.js b/api/x402/vanity.jsindex d50aeef64..e98672083 100644--- a/api/x402/vanity.js+++ b/api/x402/vanity.js@@ -649,6 +649,25 @@ export async function tryInstantFromInventory(pattern, { paymentId, purchaser })return { result: withCert, item };}+// Cache-safe copy of a delivered result. Never persist spendable key material at+// rest: the live response delivers the ground secret once over TLS (this+// endpoint's stated contract), and the x402 replay/idempotency cache must NOT+// hold it, or a cache read or compromise would recover spendable keys for the+// cache TTL. The plaintext secret fields are stripped from the STORED copy, so a+// replayed payment receives the public metadata plus an explicit marker rather+// than the key. A sealed response carries only ciphertext (sealedSecret), which+// is safe at rest, so it is cached unchanged.+export function cacheSafeBody(result) {+ if (result?.sealed) return JSON.stringify(result);+ const { secretKeyBase58, secretKey, mnemonic, ...publicMeta } = result;+ void secretKeyBase58; void secretKey; void mnemonic;+ return JSON.stringify({+ ...publicMeta,+ secret_omitted_from_cache: true,+ note: 'The ground secret is returned only once in the original response and is never stored. If you did not capture it, grind again.',+ });+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (req.method !== 'GET') {@@ -732,6 +751,21 @@ export default wrap(async (req, res) => {);}if (acResult?.grantAccess) {+ // The premium 4-5 char band is inventory-only. grindAndShape would reject+ // it as pattern_too_long (the live grinder tops out at+ // MAX_SERVER_PATTERN_LENGTH), and an access grant is not a purchase, so it+ // cannot claim stock either. Say that plainly rather than surfacing a+ // length error for a pattern we just confirmed IS in stock.+ if (pattern.premiumOnly) {+ return error(+ res,+ 409,+ 'purchase_required',+ `${pattern.combinedLength}-char patterns come only from the premium inventory, which is sold per item. ` ++ `An access grant covers the live grind (1-${MAX_SERVER_PATTERN_LENGTH} chars); buy this pattern at ` ++ `GET /api/x402/vanity-premium?prefix=${encodeURIComponent(pattern.prefix || '')}.`,+ );+ }let result;try {result = await grindAndShape(pattern);@@ -864,31 +898,13 @@ export default wrap(async (req, res) => {res.end(body);if (paymentId) {- // Never persist spendable key material at rest. The live response above- // delivers the ground secret once over TLS (this endpoint's stated- // contract); the x402 replay/idempotency cache must NOT hold it, or a- // Redis read or compromise would recover spendable keys for the cache TTL.- // Strip the plaintext secret fields from the STORED copy so a replayed- // payment receives the public metadata plus an explicit marker, not the- // key. Sealed responses carry only ciphertext (sealedSecret), which is- // safe at rest, so they are cached unchanged.- let storedBody = body;- if (!result?.sealed) {- const { secretKeyBase58, secretKey, mnemonic, ...publicMeta } = result;- void secretKeyBase58; void secretKey; void mnemonic;- storedBody = JSON.stringify({- ...publicMeta,- secret_omitted_from_cache: true,- note: 'The ground secret is returned only once in the original response and is never stored. If you did not capture it, grind again.',- });- }await storeResponse({route: ROUTE,paymentId,payloadHash,paymentHash,status: 200,- body: storedBody,+ body: cacheSafeBody(result),contentType,paymentResponseHeader,});diff --git a/api/x402/verify-receipt.js b/api/x402/verify-receipt.jsindex 2ce3d74e2..7455b13db 100644--- a/api/x402/verify-receipt.js+++ b/api/x402/verify-receipt.js@@ -18,11 +18,18 @@// attested fields (verdict, confidence, claim, sources).// tx.network — CAIP-2 ("solana:…", "eip155:8453") or shorthand// ("solana", "base").+//+// GET carries no body, so check 2 also reads ?hash=&network= from the query+// string: GET /api/x402/verify-receipt?hash=<sig>&network=solana. Check 1 needs+// the whole attested object and stays POST-only. On POST the body wins whenever+// it supplies `tx`.import { wrap, cors, method, json, error, readJson, rateLimited, setRateLimitHeaders } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { verifyAttestation } from '../_lib/x402/dev-tools.js';+const ROUTE = '/api/x402/verify-receipt';+// Map a network string (CAIP-2 or shorthand) to a chain family + EVM chainId.function resolveNetwork(network) {const n = String(network || '').toLowerCase().trim();@@ -70,6 +77,17 @@ async function confirmSettlementTx(hash, network) {}}+// Settlement inputs from the query string, so a plain GET (no body) can still+// run check 2. Returns undefined when neither param is present, which keeps the+// "nothing to verify" branch below intact for a bare GET.+function txFromQuery(req) {+ const q = req.query || {};+ const hash = typeof q.hash === 'string' ? q.hash.trim() : '';+ const network = typeof q.network === 'string' ? q.network.trim() : '';+ if (!hash && !network) return undefined;+ return { hash, network };+}+async function handle(req, res) {const ip = clientIp(req);const rl = await limits.x402DevToolIp(ip);@@ -81,15 +99,20 @@ async function handle(req, res) {try {body = (await readJson(req)) || {};} catch (err) {- return error(res, 400, 'invalid_json', err.message || 'request body must be valid JSON');+ // readJson rejects a non-JSON content-type with status 415; keep that+ // distinction instead of flattening every body problem into a 400.+ const status = err.status || 400;+ const code = status === 415 ? 'unsupported_media_type' : 'invalid_json';+ return error(res, status, code, err.message || 'request body must be valid JSON');}}const result = body.result;- const tx = body.tx;+ const tx = body.tx !== undefined ? body.tx : txFromQuery(req);if (result === undefined && tx === undefined) {- return error(res, 400, 'nothing_to_verify', 'provide `result` (an attested paid response) and/or `tx` ({ hash, network })', {+ return error(res, 400, 'nothing_to_verify', 'POST `result` (an attested paid response) and/or `tx` ({ hash, network }); or GET ?hash=<tx>&network=<chain> to confirm a settlement only', {example: { result: { verdict: 'true', confidence: 0.9, claim: '…', sources: ['https://…'], attestation: 'sha256:…' }, tx: { hash: '…', network: 'solana' } },+ getExample: `${ROUTE}?hash=<settlement-signature-or-hash>&network=solana`,});}diff --git a/api/x402/yield-scan.js b/api/x402/yield-scan.jsindex 94fa993fe..59a5bc8de 100644--- a/api/x402/yield-scan.js+++ b/api/x402/yield-scan.js@@ -155,7 +155,14 @@ export default paidEndpoint({const limit = Math.min(50, Math.max(1, Number.isFinite(limitRaw) ? Math.floor(limitRaw) : 20));let pools = null;- try { pools = await loadPools(); } catch { /* refund below */ }+ try {+ pools = await loadPools();+ } catch (err) {+ // Refuse BEFORE settlement (the throw below) so an upstream outage never+ // charges the buyer. Log the cause so an upstream shape or availability+ // change is diagnosable instead of surfacing only as a bare 503.+ console.error('[yield-scan] pool feed unavailable; refusing before settlement', err?.message || err);+ }if (!pools) {throw Object.assign(new Error('yield pool data is temporarily unavailable'), {status: 503,diff --git a/docs/x402-dev-tools.md b/docs/x402-dev-tools.mdindex 935615252..c826a1a65 100644--- a/docs/x402-dev-tools.md+++ b/docs/x402-dev-tools.md@@ -134,6 +134,17 @@ curl -s https://three.ws/api/x402/verify-receipt \{ "ok": true, "settlement": { "verified": true, "status": "confirmed", "detail": "settlement confirmed on Solana", "slot": 301234567 } }```+The settlement check also works over a plain `GET`, so you can confirm a+settlement from a browser address bar, a `curl` one-liner, or an uptime probe+with no request body:++```bash+curl -s 'https://three.ws/api/x402/verify-receipt?hash=<signature or txhash>&network=solana'+```++Attestation integrity stays `POST`-only, because it needs the whole attested+object. When a `POST` body supplies `tx`, the body wins over the query string.+---## The three probe endpoints@@ -161,6 +172,11 @@ endpoint today before hitting its daily USDC spend cap — `remaining_calls`,curl -s https://three.ws/api/x402/rate-limit-probe -d '{ "endpoint": "/api/x402/forge" }'```+`endpoint` must be a metered route: a path under `/api/x402`, `/api/mcp`, or+`/api/ibm-mcp`. Those are the only routes that answer a 402 challenge, so they+are the only ones with a price to report; anything else is rejected `400+endpoint_not_metered` before the probe runs.+### Permit2 paid demo: `GET /api/x402/permit2-paid-demo` *(paid, $0.001 USDC)*A target that advertises **only** the Permit2 + EIP-2612 gas-sponsoring acceptdiff --git a/tests/api/fact-check-v2.test.js b/tests/api/fact-check-v2.test.jsindex d288a4e40..87ec51798 100644--- a/tests/api/fact-check-v2.test.js+++ b/tests/api/fact-check-v2.test.js@@ -177,6 +177,35 @@ describe('POST /api/x402/fact-check — free daily lane', () => {expect(res.json().lane).not.toBe('free');});+ it('answers the free lane with the same allow-origin the paid rail sets', async () => {+ // A cross-origin caller preflights (answered by the paid rail, allow-origin *)+ // and then POSTs. Before the free lane set CORS itself, that second response+ // carried no allow-origin and the browser discarded a perfectly good 200,+ // so both a served check and a rejected one are asserted here.+ const ok = await callFactCheck(+ jsonReq({ claim: 'The sky is blue during the day.' }, { origin: 'https://example.com', ...freshIp() }),+ );+ expect(ok.statusCode).toBe(200);+ expect(ok.getHeader('access-control-allow-origin')).toBe('*');++ const bad = await callFactCheck(+ jsonReq({ claim: 'hi' }, { origin: 'https://example.com', ...freshIp() }),+ );+ expect(bad.statusCode).toBe(400);+ expect(bad.getHeader('access-control-allow-origin')).toBe('*');+ });++ it('answers an OPTIONS preflight with 204 and the paid rail header set', async () => {+ const pre = Readable.from([]);+ pre.method = 'OPTIONS';+ pre.url = '/api/x402/fact-check';+ pre.headers = { origin: 'https://example.com', ...freshIp() };+ const res = await callFactCheck(pre);+ expect(res.statusCode).toBe(204);+ expect(res.getHeader('access-control-allow-origin')).toBe('*');+ expect(String(res.getHeader('access-control-allow-methods'))).toContain('POST');+ });+it('GET (or any non-POST) is left entirely to the paid rail', async () => {// Credential-less wrong-method requests are discovery probes and receive// the 402 challenge (x402-paid-endpoint.js method gate); a requestdiff --git a/tests/api/stablecoin-health.test.js b/tests/api/stablecoin-health.test.jsnew file mode 100644index 000000000..f964f868d--- /dev/null+++ b/tests/api/stablecoin-health.test.js@@ -0,0 +1,115 @@+// Tests for /api/x402/stablecoin-health: the paid stablecoin peg monitor.+//+// Pure-logic only: we exercise the exported normalizer (toCoin) and the peg+// classifier (pegStatus) rather than the paidEndpoint HTTP wrapper, keeping the+// suite off the network while covering what a buyer actually pays for: the+// on-peg / drifting / depegged verdict and the depeg alert list.+//+// Regression under test: stablecoins.llama.fi reports `price: null` for a large+// minority of the USD-pegged assets it tracks (75 of them on 2026-08-14). The+// handler used to coerce that with Number(), which turns null into 0, so every+// unquoted asset was scored at -10000 bps and shipped in the `depegged` alert+// list. A paid depeg monitor must never invent a depeg out of a missing quote.++import { describe, it, expect } from 'vitest';+import { toCoin, pegStatus, OUTPUT_SCHEMA } from '../../api/x402/stablecoin-health.js';++const asset = (over = {}) => ({+ pegType: 'peggedUSD',+ symbol: 'TEST',+ name: 'Test Dollar',+ price: 1,+ pegMechanism: 'fiat-backed',+ circulating: { peggedUSD: 1_000_000 },+ circulatingPrevDay: { peggedUSD: 900_000 },+ chainCirculating: { Solana: {}, Ethereum: {} },+ ...over,+});++describe('pegStatus: deviation thresholds', () => {+ it('classifies a tight peg as on-peg', () => {+ expect(pegStatus(0)).toBe('on-peg');+ expect(pegStatus(24)).toBe('on-peg');+ expect(pegStatus(-24)).toBe('on-peg');+ });++ it('classifies 25 bps or more as drifting', () => {+ expect(pegStatus(25)).toBe('drifting');+ expect(pegStatus(-99)).toBe('drifting');+ });++ it('classifies 100 bps or more as depegged', () => {+ expect(pegStatus(100)).toBe('depegged');+ expect(pegStatus(-1_340)).toBe('depegged');+ });++ it('classifies a missing deviation as unknown, never as a depeg', () => {+ expect(pegStatus(null)).toBe('unknown');+ expect(pegStatus(undefined)).toBe('unknown');+ });+});++describe('toCoin: price normalization', () => {+ it('scores a real quote into a deviation and a status', () => {+ const c = toCoin(asset({ price: 0.9467 }));+ expect(c.price).toBe(0.9467);+ expect(c.deviation_bps).toBe(-533);+ expect(c.status).toBe('depegged');+ });++ it('reports an unquoted asset as unknown rather than a total depeg', () => {+ for (const price of [null, undefined, 'n/a']) {+ const c = toCoin(asset({ price }));+ expect(c.price).toBeNull();+ expect(c.deviation_bps).toBeNull();+ expect(c.status).toBe('unknown');+ }+ });++ it('still honors a genuine zero price as a total depeg', () => {+ const c = toCoin(asset({ price: 0 }));+ expect(c.price).toBe(0);+ expect(c.deviation_bps).toBe(-10_000);+ expect(c.status).toBe('depegged');+ });++ it('carries supply flow and chain count through', () => {+ const c = toCoin(asset());+ expect(c.circulating_usd).toBe(1_000_000);+ expect(c.change_24h_pct).toBeCloseTo(11.111, 3);+ expect(c.change_7d_pct).toBeNull();+ expect(c.chains).toBe(2);+ });+});++describe('toCoin: assets the monitor must skip', () => {+ it('skips anything that is not USD-pegged', () => {+ expect(toCoin(asset({ pegType: 'peggedEUR' }))).toBeNull();+ expect(toCoin(asset({ pegType: undefined }))).toBeNull();+ });++ it('skips assets with no real circulating supply', () => {+ expect(toCoin(asset({ circulating: { peggedUSD: 0 } }))).toBeNull();+ expect(toCoin(asset({ circulating: null }))).toBeNull();+ expect(toCoin(asset({ circulating: { peggedUSD: 'many' } }))).toBeNull();+ });++ it('never throws on a malformed upstream row', () => {+ for (const bad of [null, undefined, {}, { pegType: 'peggedUSD' }]) {+ expect(() => toCoin(bad)).not.toThrow();+ }+ });+});++describe('OUTPUT_SCHEMA: the wire contract buyers validate against', () => {+ it('declares every status the classifier can emit', () => {+ const statuses = OUTPUT_SCHEMA.properties.coins.items.properties.status.enum;+ expect(statuses).toEqual(expect.arrayContaining(['on-peg', 'drifting', 'depegged', 'unknown']));+ });++ it('allows a null price and a null deviation for unquoted coins', () => {+ const props = OUTPUT_SCHEMA.properties.coins.items.properties;+ expect(props.price.type).toContain('null');+ expect(props.deviation_bps.type).toContain('null');+ });+});diff --git a/tests/api/x402-analytics-currency.test.js b/tests/api/x402-analytics-currency.test.jsnew file mode 100644index 000000000..9d2fe0273--- /dev/null+++ b/tests/api/x402-analytics-currency.test.js@@ -0,0 +1,59 @@+// Currency-normalisation contract for POST /api/x402/analytics { report: 'marketplace' }.+//+// The marketplace report converts every listing price to USD before averaging.+// It decides whether a price is convertible by lower-casing the row's mint and+// looking it up in USDC_MINTS / SOL_MINTS. A set entry that is not itself fully+// lower-cased can therefore never match: the Solana USDC entry had kept its+// mixed-case tail, so every Solana-priced agent came back priceable:false and+// dropped silently out of avg/min/max USD, leaving a paid report that+// under-reported the catalog. These tests pin the invariant that makes the+// lookup work at all.++import { describe, it, expect } from 'vitest';+import { __test__ } from '../../api/x402/analytics.js';++const { USDC_MINTS, SOL_MINTS, currencyLabel } = __test__;++const SOLANA_USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';+const WRAPPED_SOL = 'So11111111111111111111111111111111111111112';++describe('analytics marketplace currency sets', () => {+ it('stores every mint lower-cased, so a lower-cased lookup can match', () => {+ for (const mint of [...USDC_MINTS, ...SOL_MINTS]) {+ expect(mint).toBe(mint.toLowerCase());+ }+ });++ it('recognises USDC on both chains from the canonical mixed-case mint', () => {+ expect(USDC_MINTS.has(SOLANA_USDC.toLowerCase())).toBe(true);+ expect(USDC_MINTS.has(BASE_USDC.toLowerCase())).toBe(true);+ });++ it('recognises SOL from both the native marker and wrapped mint', () => {+ expect(SOL_MINTS.has('native')).toBe(true);+ expect(SOL_MINTS.has(WRAPPED_SOL.toLowerCase())).toBe(true);+ });++ it('does not treat an unrelated mint as convertible', () => {+ expect(USDC_MINTS.has('notamint')).toBe(false);+ expect(SOL_MINTS.has('notamint')).toBe(false);+ });+});++describe('analytics currencyLabel', () => {+ it('labels the recognised assets by ticker regardless of input casing', () => {+ expect(currencyLabel(SOLANA_USDC)).toBe('USDC');+ expect(currencyLabel(SOLANA_USDC.toLowerCase())).toBe('USDC');+ expect(currencyLabel(BASE_USDC)).toBe('USDC');+ expect(currencyLabel('native')).toBe('SOL');+ expect(currencyLabel(WRAPPED_SOL)).toBe('SOL');+ });++ it('abbreviates an unknown long mint and passes a short one through', () => {+ const unknown = 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ';+ expect(currencyLabel(unknown)).toBe(`${unknown.slice(0, 4)}…${unknown.slice(-4)}`);+ expect(currencyLabel('short')).toBe('short');+ expect(currencyLabel(null)).toBe('unknown');+ });+});diff --git a/tests/api/x402-auth-health-mode.test.js b/tests/api/x402-auth-health-mode.test.jsnew file mode 100644index 000000000..0b9191520--- /dev/null+++ b/tests/api/x402-auth-health-mode.test.js@@ -0,0 +1,42 @@+// Billing contract for POST /api/x402/auth-health.+//+// paidEndpoint delivers before it settles: whatever the handler RETURNS becomes+// the buyer's paid response and the payment settles behind it, while a thrown+// error lands before settlement and costs the caller nothing. An unsupported+// mode used to be *returned* as { error: 'unsupported_mode' }, which billed+// $0.001 for a 200 that carried no health check at all. It must throw.++import { describe, it, expect } from 'vitest';+import { __test__ } from '../../api/x402/auth-health.js';++const { resolveMode } = __test__;++describe('auth-health resolveMode', () => {+ it('accepts the supported mode and defaults an absent one', () => {+ expect(resolveMode({ mode: 'session_lifecycle' })).toBe('session_lifecycle');+ expect(resolveMode({})).toBe('session_lifecycle');+ expect(resolveMode(undefined)).toBe('session_lifecycle');+ });++ it('tolerates surrounding whitespace rather than charging for a typo', () => {+ expect(resolveMode({ mode: ' session_lifecycle ' })).toBe('session_lifecycle');+ });++ it('throws a 400 on an unsupported mode instead of returning an error body', () => {+ let thrown;+ try {+ resolveMode({ mode: 'drop_tables' });+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(Error);+ expect(thrown.status).toBe(400);+ expect(thrown.code).toBe('unsupported_mode');+ expect(thrown.message).toContain('drop_tables');+ });++ it('treats a non-string mode as absent, but an empty string as a real typo', () => {+ expect(resolveMode({ mode: 42 })).toBe('session_lifecycle');+ expect(() => resolveMode({ mode: '' })).toThrow(/unsupported mode/);+ });+});diff --git a/tests/api/x402-download-cors.test.js b/tests/api/x402-download-cors.test.jsnew file mode 100644index 000000000..8848f18a7--- /dev/null+++ b/tests/api/x402-download-cors.test.js@@ -0,0 +1,66 @@+// CORS contract for the two x402 download handlers.+//+// api/x402/asset-download.js and api/x402/animation-download.js are the only+// endpoints in api/x402/ that answer requests themselves before delegating to+// paidEndpoint: they serve the discovery 402, the 400/404/502 errors, and (for+// animation-download) the free-listing 200 from their own code. paidEndpoint is+// what installs CORS for every other endpoint in the directory, so these two+// shipped with none: on production an OPTIONS preflight fell straight through+// to a 402 carrying no Access-Control-Allow-Origin, which left every browser+// x402 client (the drop-in modal, x402-fetch) unable to even read the challenge+// it was supposed to pay. These tests pin the headers on both handlers.++import { describe, it, expect } from 'vitest';+import assetDownload from '../../api/x402/asset-download.js';+import animationDownload from '../../api/x402/animation-download.js';++function makeRes() {+ const headers = {};+ return {+ headers,+ statusCode: 200,+ ended: false,+ body: undefined,+ setHeader(k, v) { headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return headers[String(k).toLowerCase()]; },+ status(code) { this.statusCode = code; return this; },+ json(payload) { this.body = payload; this.ended = true; return this; },+ end(payload) { this.body = payload; this.ended = true; return this; },+ };+}++const HANDLERS = [+ ['asset-download', assetDownload],+ ['animation-download', animationDownload],+];++describe.each(HANDLERS)('%s CORS', (name, handler) => {+ it('answers an OPTIONS preflight with 204 and the wildcard origin', async () => {+ const res = makeRes();+ await handler({ method: 'OPTIONS', headers: { origin: 'https://example.com' }, query: {} }, res);++ expect(res.statusCode).toBe(204);+ expect(res.ended).toBe(true);+ expect(res.getHeader('access-control-allow-origin')).toBe('*');+ expect(res.getHeader('access-control-allow-methods')).toBe('GET,HEAD,OPTIONS');+ });++ it('exposes the x402 payment headers a cross-origin client must read', async () => {+ const res = makeRes();+ await handler({ method: 'OPTIONS', headers: {}, query: {} }, res);++ const exposed = String(res.getHeader('access-control-expose-headers'));+ expect(exposed).toContain('PAYMENT-REQUIRED');+ expect(exposed).toContain('x-payment-response');+ });++ it('sets the origin header on the bare-route discovery challenge too', async () => {+ const res = makeRes();+ // No slug / no id: the discovery-probe branch, which builds its own 402+ // without ever reaching paidEndpoint.+ await handler({ method: 'GET', headers: {}, query: {} }, res);++ expect(res.getHeader('access-control-allow-origin')).toBe('*');+ expect(res.statusCode).toBe(402);+ });+});diff --git a/tests/api/x402-facilitator-dispatch.test.js b/tests/api/x402-facilitator-dispatch.test.jsnew file mode 100644index 000000000..b084865f7--- /dev/null+++ b/tests/api/x402-facilitator-dispatch.test.js@@ -0,0 +1,365 @@+// Dispatch and boundary contract for the self-hosted x402 facilitator endpoint+// (api/x402-facilitator/[action].js).+//+// The handler is one file serving five public actions behind a single+// [action].js route, and the split between them is pure string dispatch on a+// query param that vercel.json fills from the URL path. Everything downstream+// of that dispatch already has tests (self-facilitator.js, settle-credit.js,+// discovery-resources.js, wallet-fee-meter.js) and the audit-log write has its+// own regression file (x402-facilitator-log-durable.test.js), but the dispatch+// itself and the four rejection boundaries in front of the money path had none.+//+// Those boundaries are what an unauthenticated caller reaches first, and each+// one is load-bearing:+// - the disabled-503 is the only thing standing between a misconfigured+// deploy and a settle attempt with no sponsor key,+// - the Solana-only network check keeps an EVM payload from reaching a+// handler that would try to decode it as a Solana transaction,+// - the 400 on a missing payload is what makes callFacilitator's error path+// deterministic instead of a decode crash,+// - and the GET/POST split is what keeps /verify and /settle off a method+// that browsers and crawlers issue unprompted.+//+// The module boundaries below are mocked the same way the neighboring x402+// tests mock theirs: the DB, the settle engine, the rate limiter, the fee+// meter, and the catalog builder. The settle-credit gate is left REAL and+// driven through the mocked sql, so the credited and refused branches this+// file asserts are the actual gate's verdicts, not a stand-in's.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const h = vi.hoisted(() => ({+ enabled: true,+ verify: vi.fn(),+ settle: vi.fn(),+ list: vi.fn(),+ recordSettledFee: vi.fn(),+ // Statement text -> rows. The settle-credit gate reads any prior credit for+ // the signature (SELECT) and then claims it (INSERT ... RETURNING id).+ rows: { select: [], insert: [{ id: 1 }] },+ queries: [],+ sqlFails: false,+}));++vi.mock('../../api/_lib/db.js', () => ({+ sql: (strings) => {+ const query = Array.isArray(strings) ? strings.join(' ') : String(strings ?? '');+ h.queries.push(query);+ if (h.sqlFails) return Promise.reject(new Error('Error connecting to database'));+ return Promise.resolve(/INSERT/i.test(query) ? h.rows.insert : h.rows.select);+ },+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++// A getter, not a plain property: the handler reads SELF_FACILITATOR_ENABLED per+// request through the live import binding, so a getter lets one module instance+// serve both the enabled and disabled cases without resetting the module graph.+vi.mock('../../api/_lib/x402/self-facilitator.js', () => ({+ get SELF_FACILITATOR_ENABLED() { return h.enabled; },+ verifyRingPayment: (...a) => h.verify(...a),+ settleRingPayment: (...a) => h.settle(...a),+}));++vi.mock('../../api/_lib/x402/wallet-fee-meter.js', () => ({+ facilitatorFeeMeter: () => null,+ recordSettledFee: (...a) => h.recordSettledFee(...a),+}));++vi.mock('../../api/_lib/x402/discovery-resources.js', () => ({+ listDiscoveryResources: (...a) => h.list(...a),+}));++// The limiter's own buckets are covered in tests/rate-limit*.test.js; here it+// only has to admit, so the boundary under test is the handler's dispatch.+vi.mock('../../api/_lib/rate-limit.js', () => ({+ clientIp: () => '203.0.113.7',+ limits: {+ x402FacilitatorIp: async () => ({ success: true, limit: 60, remaining: 59, reset: Date.now() + 1000 }),+ x402FacilitatorGlobal: async () => ({ success: true, limit: 100, remaining: 99, reset: Date.now() + 1000 }),+ },+}));++const handler = (await import('../../api/x402-facilitator/[action].js')).default;++const SOLANA = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';++const PAYLOAD = {+ paymentPayload: { x402Version: 2, scheme: 'exact', network: SOLANA, payload: { transaction: 'BASE64' } },+ paymentRequirements: { scheme: 'exact', network: SOLANA, payTo: 'PAYTO', asset: 'MINT', amount: '10000' },+};++function makeRes() {+ return {+ statusCode: 200,+ headersSent: false,+ writableEnded: false,+ headers: {},+ body: null,+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },+ end(b) { this.writableEnded = true; this.body = b == null ? null : String(b); },+ };+}++// Drive the handler the way the server does: vercel.json rewrites the path to+// ?action=<segment>, so `action` is what the route table decided, and `url` is+// what the caller actually asked for.+async function call({ action, method = 'GET', body, query = {}, headers = {}, url } = {}) {+ const req = {+ method,+ url: url ?? `/api/x402-facilitator/${action}`,+ query: { action, ...query },+ headers: { host: 'three.ws', ...headers },+ body,+ };+ const res = makeRes();+ await handler(req, res);+ let json = null;+ try { json = res.body == null ? null : JSON.parse(res.body); } catch { json = null; }+ return { res, status: res.statusCode, json };+}++beforeEach(() => {+ h.enabled = true;+ h.sqlFails = false;+ h.queries = [];+ h.rows = { select: [], insert: [{ id: 1 }] };+ h.verify.mockReset();+ h.settle.mockReset();+ h.list.mockReset();+ h.recordSettledFee.mockReset();+});++describe('preflight and CORS', () => {+ it('answers OPTIONS with 204 and the wildcard CORS grant', async () => {+ const { res, status } = await call({ action: 'verify', method: 'OPTIONS' });+ expect(status).toBe(204);+ expect(res.writableEnded).toBe(true);+ expect(res.headers['access-control-allow-origin']).toBe('*');+ expect(res.headers['access-control-allow-methods']).toBe('GET,POST,OPTIONS');+ });++ it('sets the wildcard grant on a rejection too, so a browser can read the error', async () => {+ h.enabled = false;+ const { res, status } = await call({ action: 'verify', method: 'POST', body: {} });+ expect(status).toBe(503);+ expect(res.headers['access-control-allow-origin']).toBe('*');+ });+});++describe('GET / (index discovery document)', () => {+ it('describes the service, its four endpoints, and the exact/solana kind', async () => {+ const { status, json } = await call({ action: 'index', url: '/api/x402-facilitator' });+ expect(status).toBe(200);+ expect(json.service).toContain('facilitator');+ expect(json.x402Version).toBe(2);+ expect(json.kinds).toEqual([{ x402Version: 2, scheme: 'exact', network: SOLANA }]);+ expect(Object.keys(json.endpoints).sort()).toEqual(['discovery', 'settle', 'supported', 'verify']);+ expect(json.endpoints.verify).toEqual({ method: 'POST', path: '/api/x402-facilitator/verify' });+ expect(json.endpoints.discovery.path).toBe('/api/x402-facilitator/discovery/resources');+ });++ it('reports the live enabled flag rather than a constant', async () => {+ h.enabled = false;+ const off = await call({ action: 'index' });+ expect(off.json.enabled).toBe(false);+ h.enabled = true;+ const on = await call({ action: 'index' });+ expect(on.json.enabled).toBe(true);+ });++ it('resolves the index from the bare last path segment when no action param is set', async () => {+ const res = makeRes();+ await handler(+ { method: 'GET', url: '/api/x402-facilitator', query: {}, headers: { host: 'three.ws' } },+ res,+ );+ expect(res.statusCode).toBe(200);+ expect(JSON.parse(res.body).service).toContain('facilitator');+ });++ it('is read-only: POST is rejected 405, never treated as a settle', async () => {+ const { status, json } = await call({ action: 'index', method: 'POST', body: PAYLOAD });+ expect(status).toBe(405);+ expect(json.error).toBe('method_not_allowed');+ expect(h.settle).not.toHaveBeenCalled();+ });+});++describe('GET /supported (capability probe)', () => {+ it('advertises exact/solana without a payment, a secret, or the enabled flag', async () => {+ h.enabled = false;+ const { status, json } = await call({ action: 'supported' });+ expect(status).toBe(200);+ expect(json).toEqual({ kinds: [{ x402Version: 2, scheme: 'exact', network: SOLANA }] });+ });++ it('answers POST too, since x402 clients probe with either verb', async () => {+ const { status, json } = await call({ action: 'supported', method: 'POST', body: {} });+ expect(status).toBe(200);+ expect(json.kinds).toHaveLength(1);+ });+});++describe('GET /discovery/resources (crawler catalog)', () => {+ const PAGE = { x402Version: 1, items: [], pagination: { limit: 2, offset: 4, total: 0 } };++ it('serves the catalog page and lets a crawler cache it for the catalog TTL', async () => {+ h.list.mockResolvedValue(PAGE);+ const { res, status, json } = await call({ action: 'discovery-resources' });+ expect(status).toBe(200);+ expect(json).toEqual(PAGE);+ expect(res.headers['cache-control']).toBe('public, max-age=300');+ });++ it('passes the crawler pagination window through untouched', async () => {+ h.list.mockResolvedValue(PAGE);+ await call({ action: 'discovery-resources', query: { type: 'http', limit: '2', offset: '4' } });+ expect(h.list).toHaveBeenCalledWith({ type: 'http', limit: '2', offset: '4' });+ });++ it('serves the same catalog from the bare-segment alias the path fallback yields', async () => {+ h.list.mockResolvedValue(PAGE);+ const { status, json } = await call({ action: 'resources' });+ expect(status).toBe(200);+ expect(json).toEqual(PAGE);+ });++ it('rejects POST 405 instead of falling through to the money path', async () => {+ const { status } = await call({ action: 'discovery-resources', method: 'POST', body: PAYLOAD });+ expect(status).toBe(405);+ expect(h.list).not.toHaveBeenCalled();+ });+});++describe('the four boundaries in front of the money path', () => {+ it('503s every POST when the facilitator is disabled, before any settle work', async () => {+ h.enabled = false;+ for (const action of ['verify', 'settle']) {+ const { status, json } = await call({ action, method: 'POST', body: PAYLOAD });+ expect(status).toBe(503);+ expect(json.errorReason).toBe('self_facilitator_disabled');+ expect(json.invalidReason).toBe('self_facilitator_disabled');+ }+ expect(h.verify).not.toHaveBeenCalled();+ expect(h.settle).not.toHaveBeenCalled();+ });++ it('405s a GET on verify and settle', async () => {+ for (const action of ['verify', 'settle']) {+ const { status, json } = await call({ action });+ expect(status).toBe(405);+ expect(json.error).toBe('method_not_allowed');+ }+ });++ it('400s a body missing paymentPayload or paymentRequirements', async () => {+ for (const body of [{}, { paymentPayload: PAYLOAD.paymentPayload }, { paymentRequirements: PAYLOAD.paymentRequirements }]) {+ const { status, json } = await call({ action: 'verify', method: 'POST', body });+ expect(status).toBe(400);+ expect(json.isValid).toBe(false);+ expect(json.invalidReason).toBe('missing paymentPayload/paymentRequirements');+ }+ expect(h.verify).not.toHaveBeenCalled();+ });++ it('400s a non-Solana network naming the network it refused', async () => {+ const { status, json } = await call({+ action: 'settle',+ method: 'POST',+ body: { ...PAYLOAD, paymentRequirements: { ...PAYLOAD.paymentRequirements, network: 'eip155:8453' } },+ });+ expect(status).toBe(400);+ expect(json.errorReason).toBe('unsupported_network:eip155:8453');+ expect(h.settle).not.toHaveBeenCalled();+ });++ it('404s an unknown action rather than guessing verify or settle', async () => {+ const { status, json } = await call({ action: 'nonsense', method: 'POST', body: PAYLOAD });+ expect(status).toBe(404);+ expect(json.error).toBe('unknown_action:nonsense');+ expect(h.verify).not.toHaveBeenCalled();+ expect(h.settle).not.toHaveBeenCalled();+ });+});++describe('POST /verify', () => {+ it('returns the verdict at 200 so callFacilitator reads isValid, not a status code', async () => {+ h.verify.mockResolvedValue({ isValid: true, network: SOLANA, asset: 'MINT', payer: 'BUYER' });+ const { status, json } = await call({ action: 'verify', method: 'POST', body: PAYLOAD });+ expect(status).toBe(200);+ expect(json).toEqual({ isValid: true, network: SOLANA, asset: 'MINT', payer: 'BUYER' });+ });++ it('returns an invalid verdict at 200 as well, and trails it in the audit log', async () => {+ h.verify.mockResolvedValue({ isValid: false, invalidReason: 'payer_not_signer' });+ const { status, json } = await call({ action: 'verify', method: 'POST', body: PAYLOAD });+ expect(status).toBe(200);+ expect(json.isValid).toBe(false);+ expect(json.invalidReason).toBe('payer_not_signer');+ expect(h.queries.filter((q) => /INSERT INTO x402_self_facilitator_log/.test(q))).toHaveLength(1);+ });++ it('still answers when the audit-log write fails, since the trail is not the verdict', async () => {+ h.sqlFails = true;+ h.verify.mockResolvedValue({ isValid: true, network: SOLANA, asset: 'MINT', payer: 'BUYER' });+ const { status, json } = await call({ action: 'verify', method: 'POST', body: PAYLOAD });+ expect(status).toBe(200);+ expect(json.isValid).toBe(true);+ });+});++describe('POST /settle', () => {+ const OK = { success: true, transaction: 'SIG1', network: SOLANA, payer: 'BUYER', feeLamports: 5000, feePayer: 'SPONSOR' };++ it('credits a fresh settlement, meters its fee burn, and returns the signature', async () => {+ h.settle.mockResolvedValue(OK);+ const { status, json } = await call({+ action: 'settle', method: 'POST', body: PAYLOAD, headers: { 'idempotency-key': 'key-1' },+ });+ expect(status).toBe(200);+ expect(json).toEqual({ success: true, transaction: 'SIG1', network: SOLANA, payer: 'BUYER' });+ expect(h.recordSettledFee).toHaveBeenCalledWith('SPONSOR', 5000);+ });++ it('reports a settle failure as 200 + success:false so the caller does not retry a 5xx', async () => {+ h.settle.mockResolvedValue({ success: false, reason: 'fee_runway_exhausted' });+ const { status, json } = await call({ action: 'settle', method: 'POST', body: PAYLOAD });+ expect(status).toBe(200);+ expect(json).toEqual({ success: false, errorReason: 'fee_runway_exhausted' });+ expect(h.recordSettledFee).not.toHaveBeenCalled();+ });++ it('refuses a signature another payment already settled, and does not double-meter it', async () => {+ h.settle.mockResolvedValue(OK);+ h.rows.select = [{ id: 9, idempotency_key: 'someone-elses-key' }];+ const { status, json } = await call({+ action: 'settle', method: 'POST', body: PAYLOAD, headers: { 'idempotency-key': 'key-1' },+ });+ expect(status).toBe(200);+ expect(json).toEqual({ success: false, errorReason: 'signature_already_settled' });+ expect(h.recordSettledFee).not.toHaveBeenCalled();+ });++ it('answers an idempotent replay with the original success and meters the fee once', async () => {+ h.settle.mockResolvedValue(OK);+ h.rows.select = [{ id: 9, idempotency_key: 'key-1' }];+ const { status, json } = await call({+ action: 'settle', method: 'POST', body: PAYLOAD, headers: { 'idempotency-key': 'key-1' },+ });+ expect(status).toBe(200);+ expect(json.success).toBe(true);+ expect(json.transaction).toBe('SIG1');+ expect(h.recordSettledFee).not.toHaveBeenCalled();+ });++ it('fails the credit closed when the ledger is unreachable', async () => {+ h.settle.mockResolvedValue(OK);+ h.sqlFails = true;+ const { status, json } = await call({ action: 'settle', method: 'POST', body: PAYLOAD });+ expect(status).toBe(200);+ expect(json).toEqual({ success: false, errorReason: 'settle_credit_unavailable' });+ expect(h.recordSettledFee).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/x402-llm-proxy.test.js b/tests/api/x402-llm-proxy.test.jsnew file mode 100644index 000000000..f323ac85b--- /dev/null+++ b/tests/api/x402-llm-proxy.test.js@@ -0,0 +1,185 @@+/**+ * Tests for POST /api/x402/llm-proxy: the paid one-shot completion rail.+ *+ * Covers the two things a curl probe against a live server cannot reach+ * deterministically: the metered success path (the provider chain is a real+ * network dependency, so llmComplete is fixtured at the module boundary, the+ * same way tests/api/fact-check-v2.test.js fixtures the search+LLM chain) and+ * the price wiring, which must honor the X402_PRICE_LLM_PROXY ops override like+ * every other endpoint in api/x402/.+ *+ * The handler itself is never mocked. The internal-key bypass+ * (api/_lib/x402/access-control.js) is what lets the success path run without a+ * payment; nothing here signs, verifies, or settles anything.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { Readable } from 'node:stream';++const llmState = vi.hoisted(() => ({+ result: {+ text: '1, 2, 3.',+ model: 'test-model',+ provider: 'test-provider',+ usage: { input: 5, output: 6 },+ },+}));++vi.mock('../../api/_lib/llm.js', () => ({+ llmComplete: vi.fn(async () => llmState.result),+}));++const INTERNAL_KEY = 'llm-proxy-test-internal-key';+const ENV_KEYS = [+ 'INTERNAL_API_KEY',+ 'X402_PRICE_LLM_PROXY',+ 'X402_PAY_TO_BASE',+ 'X402_ASSET_ADDRESS_BASE',+ 'X402_ADVERTISE_BASE',+ 'X402_PAY_TO_SOLANA',+ 'INFERENCE_SIGNING_KEY',+];+const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));++let handler;++async function loadHandler() {+ vi.resetModules();+ ({ default: handler } = await import('../../api/x402/llm-proxy.js'));+}++beforeEach(async () => {+ Object.assign(process.env, {+ INTERNAL_API_KEY: INTERNAL_KEY,+ X402_PAY_TO_BASE: '0x0000000000000000000000000000000000000001',+ X402_ASSET_ADDRESS_BASE: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ // Base needs an explicit facilitator opt-in or the 402 quote itself throws+ // no_payto_configured (api/_lib/x402-paid-endpoint.js).+ X402_ADVERTISE_BASE: 'true',+ });+ delete process.env.X402_PAY_TO_SOLANA;+ delete process.env.X402_PRICE_LLM_PROXY;+ // Unsigned metering: the job core still ships, which is what the success-path+ // assertions below read. Signing is covered in tests/inference-settlement.js.+ delete process.env.INFERENCE_SIGNING_KEY;+ await loadHandler();+});++afterEach(() => {+ for (const k of ENV_KEYS) {+ if (ORIGINAL_ENV[k] === undefined) delete process.env[k];+ else process.env[k] = ORIGINAL_ENV[k];+ }+});++let ipCounter = 0;+function freshIp() {+ ipCounter += 1;+ return { 'x-forwarded-for': `198.51.${(ipCounter >> 8) & 0xff}.${ipCounter & 0xff}` };+}++function jsonReq(body, headers = {}) {+ const buf = Buffer.from(JSON.stringify(body));+ const req = Readable.from([buf]);+ req.method = 'POST';+ req.url = '/api/x402/llm-proxy';+ req.headers = {+ 'content-type': 'application/json',+ 'content-length': String(buf.length),+ ...freshIp(),+ ...headers,+ };+ return req;+}++function makeRes() {+ const chunks = [];+ return {+ statusCode: 200,+ _h: {},+ writableEnded: false,+ headersSent: false,+ setHeader(k, v) {+ this._h[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this._h[k.toLowerCase()];+ },+ write(c) {+ chunks.push(Buffer.from(c));+ },+ end(c) {+ if (c) chunks.push(Buffer.from(c));+ this.writableEnded = true;+ this.headersSent = true;+ },+ json() {+ return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');+ },+ };+}++async function call(req) {+ const res = makeRes();+ await handler(req, res);+ return res;+}++const internalKey = () => ({ 'x-api-key': INTERNAL_KEY });++describe('POST /api/x402/llm-proxy', () => {+ it('returns a completion with a uuid job id and a re-hashable metering core', async () => {+ const res = await call(jsonReq({ model: 'fast', prompt: 'Count to 3.', max_tokens: 16 }, internalKey()));+ expect(res.statusCode).toBe(200);+ const body = res.json();+ expect(body.content).toBe('1, 2, 3.');+ expect(body.provider).toBe('test-provider');+ expect(body.input_tokens).toBe(5);+ expect(body.output_tokens).toBe(6);+ expect(body.tokens_used).toBe(11);+ expect(typeof body.latency_ms).toBe('number');+ // jobId comes from node:crypto's randomUUID; a v4 uuid is the contract the+ // receipt verifier and inference_jobs rows both key on.+ expect(body.job_id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);+ expect(body.metering.type).toBe('three-inference-response/v1');+ expect(body.metering.jobId).toBe(body.job_id);+ expect(body.metering.route).toBe('/api/x402/llm-proxy');+ // No signing key configured, so the core ships unsigned.+ expect(body.response_signature).toBeUndefined();+ });++ it('rejects a missing prompt with 400 and never calls the provider', async () => {+ const { llmComplete } = await import('../../api/_lib/llm.js');+ llmComplete.mockClear();+ const res = await call(jsonReq({ model: 'fast' }, internalKey()));+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('missing_prompt');+ expect(llmComplete).not.toHaveBeenCalled();+ });++ it('rejects a prompt over the 4000-character cap with 400', async () => {+ const res = await call(jsonReq({ prompt: 'a'.repeat(4001) }, internalKey()));+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('prompt_too_long');+ });++ it('quotes $0.005 by default and honors the X402_PRICE_LLM_PROXY override', async () => {+ const probe = Readable.from([Buffer.from('{}')]);+ probe.method = 'POST';+ probe.url = '/api/x402/llm-proxy';+ probe.headers = { 'content-type': 'application/json', ...freshIp() };+ const res = await call(probe);+ expect(res.statusCode).toBe(402);+ expect(res.json().accepts[0].amount).toBe('5000');++ process.env.X402_PRICE_LLM_PROXY = '7500';+ await loadHandler();+ const repriced = Readable.from([Buffer.from('{}')]);+ repriced.method = 'POST';+ repriced.url = '/api/x402/llm-proxy';+ repriced.headers = { 'content-type': 'application/json', ...freshIp() };+ const res2 = await call(repriced);+ expect(res2.statusCode).toBe(402);+ expect(res2.json().accepts[0].amount).toBe('7500');+ });+});diff --git a/tests/api/x402-pay-og.test.js b/tests/api/x402-pay-og.test.jsnew file mode 100644index 000000000..bb88a7621--- /dev/null+++ b/tests/api/x402-pay-og.test.js@@ -0,0 +1,222 @@+// /api/x402-pay/og: the share card for a /pay/calls/<tx> permalink.+//+// This endpoint is read by unfurlers (X, Slack, Discord, Telegram), never by a+// signed-in user, so its failure modes are silent: a 405 on a HEAD probe, an+// hour of CDN-cached generic card after a transient Redis blip, or a "NaNd ago"+// stat all ship a broken preview that nothing in the app surfaces. Cover the+// resolved card, every unresolved path, and the caller-controlled text that+// lands inside the SVG.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const redisGet = vi.fn(async () => null);+let redisAvailable = true;+vi.mock('../../api/_lib/redis.js', () => ({+ getRedis: () => (redisAvailable ? { get: (...a) => redisGet(...a) } : null),+}));++vi.mock('../../api/_lib/usage.js', () => ({+ logger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+ recordEvent: vi.fn(),+}));++vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async () => []),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: async () => ({ pressured: false }),+}));++const { default: handler } = await import('../../api/x402-pay/og.js');++const MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';+const DEVNET = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';+// Synthetic 88-char base58 signature: the right shape, no real settlement.+const TX = '3'.repeat(88);+const PAYER = 'THREEsynthetic1111111111111111111111111111';++function makeRes() {+ const res = {+ statusCode: 200,+ headers: {},+ body: '',+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = String(v); },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(chunk) {+ if (chunk) this.body += chunk;+ this.headersSent = true;+ this.writableEnded = true;+ return this;+ },+ };+ return res;+}++async function call(url, { method = 'GET', headers = {} } = {}) {+ const req = { url, method, headers: { host: 'three.ws', ...headers }, query: {} };+ const res = makeRes();+ await handler(req, res);+ return res;+}++function record(over = {}) {+ return {+ ts: Date.now() - 90_000,+ tool: 'solana_balance',+ argsSummary: 'address=THREEsynthetic…',+ tx: TX,+ network: MAINNET,+ amount: 1000,+ payer: PAYER,+ ...over,+ };+}++beforeEach(() => {+ redisAvailable = true;+ redisGet.mockReset();+ redisGet.mockResolvedValue(null);+});++describe('GET /api/x402-pay/og: resolved card', () => {+ it('renders the settled call from the persisted record', async () => {+ redisGet.mockResolvedValue(JSON.stringify(record()));+ const res = await call(`/api/x402-pay/og?tx=${TX}`);++ expect(res.statusCode).toBe(200);+ expect(res.headers['content-type']).toBe('image/svg+xml; charset=utf-8');+ expect(redisGet).toHaveBeenCalledWith(`x402:pay:call:${TX}`);+ expect(res.body).toContain('solana_balance');+ expect(res.body).toContain('0.001000 USDC');+ expect(res.body).toContain('Solana mainnet');+ expect(res.body).toContain('1m ago');+ expect(res.body).toContain(`${PAYER.slice(0, 6)}…${PAYER.slice(-4)}`);+ // An immutable settled record is safe to cache at the edge for an hour.+ expect(res.headers['cache-control']).toContain('max-age=3600');+ expect(res.headers['content-length']).toBe(String(Buffer.byteLength(res.body)));+ });++ it('captions a devnet receipt as devnet instead of hardcoding mainnet', async () => {+ redisGet.mockResolvedValue(JSON.stringify(record({ network: DEVNET })));+ const res = await call(`/api/x402-pay/og?tx=${TX}`);+ expect(res.body).toContain('Solana devnet');+ expect(res.body).not.toContain('Solana mainnet');+ });++ it('escapes caller-controlled text instead of letting it into the markup', async () => {+ redisGet.mockResolvedValue(JSON.stringify(record({+ tool: '<script>alert(1)</script>',+ argsSummary: 'q="a"&b=\'c\'',+ })));+ const res = await call(`/api/x402-pay/og?tx=${TX}`);+ expect(res.body).not.toContain('<script>');+ expect(res.body).toContain('<script>');+ expect(res.body).toContain('"');+ expect(res.body).toContain(''');+ expect(res.headers['content-security-policy']).toContain("default-src 'none'");+ });++ it('clamps an unbounded tool name so it cannot paint over the card', async () => {+ redisGet.mockResolvedValue(JSON.stringify(record({ tool: 'z'.repeat(400) })));+ const res = await call(`/api/x402-pay/og?tx=${TX}`);+ expect(res.body).not.toContain('z'.repeat(60));+ expect(res.body).toContain(`${'z'.repeat(37)}…`);+ });++ it('renders a corrupt record without NaN or a fabricated amount', async () => {+ redisGet.mockResolvedValue(JSON.stringify(record({+ ts: 'not-a-time', amount: 'not-a-number', tx: 12345, payer: null, network: undefined,+ })));+ const res = await call(`/api/x402-pay/og?tx=${TX}`);+ expect(res.statusCode).toBe(200);+ expect(res.body).not.toContain('NaN');+ expect(res.body).toContain('unknown');+ expect(res.body).not.toContain('0.001000');+ expect(res.body).toContain('Solana');+ });+});++describe('GET /api/x402-pay/og: unresolved paths', () => {+ it('serves the generic card with a long cache when no tx is asked for', async () => {+ const res = await call('/api/x402-pay/og');+ expect(res.statusCode).toBe(200);+ expect(res.body).toContain('pay-per-call (x402)');+ expect(redisGet).not.toHaveBeenCalled();+ expect(res.headers['cache-control']).toContain('max-age=3600');+ });++ it('does not query Redis for a tx that is not a Solana signature', async () => {+ const res = await call('/api/x402-pay/og?tx=notavalidsignature');+ expect(res.statusCode).toBe(200);+ expect(redisGet).not.toHaveBeenCalled();+ expect(res.body).toContain('pay-per-call (x402)');+ });++ it('short-caches a well-formed tx it could not resolve, so a blip self-heals', async () => {+ const res = await call(`/api/x402-pay/og?tx=${TX}`);+ expect(res.statusCode).toBe(200);+ expect(res.headers['cache-control']).toBe('public, max-age=60, s-maxage=60');+ });++ it('falls back to the generic card when Redis is unavailable', async () => {+ redisAvailable = false;+ const res = await call(`/api/x402-pay/og?tx=${TX}`);+ expect(res.statusCode).toBe(200);+ expect(res.body).toContain('pay-per-call (x402)');+ expect(res.headers['cache-control']).toBe('public, max-age=60, s-maxage=60');+ });++ it('falls back to the generic card when a Redis read throws', async () => {+ redisGet.mockRejectedValue(new Error('upstream timeout'));+ const res = await call(`/api/x402-pay/og?tx=${TX}`);+ expect(res.statusCode).toBe(200);+ expect(res.body).toContain('pay-per-call (x402)');+ });++ it('rejects a stored row that parses to a scalar rather than a record', async () => {+ redisGet.mockResolvedValue('"corrupted"');+ const res = await call(`/api/x402-pay/og?tx=${TX}`);+ expect(res.statusCode).toBe(200);+ expect(res.body).toContain('pay-per-call (x402)');+ });++ it('falls back when the stored row is not valid JSON', async () => {+ redisGet.mockResolvedValue('{not json');+ const res = await call(`/api/x402-pay/og?tx=${TX}`);+ expect(res.statusCode).toBe(200);+ expect(res.body).toContain('pay-per-call (x402)');+ });+});++describe('/api/x402-pay/og: methods and CORS', () => {+ it('answers a HEAD probe with the card headers and no body', async () => {+ redisGet.mockResolvedValue(JSON.stringify(record()));+ const res = await call(`/api/x402-pay/og?tx=${TX}`, { method: 'HEAD' });+ expect(res.statusCode).toBe(200);+ expect(res.headers['content-type']).toBe('image/svg+xml; charset=utf-8');+ expect(Number(res.headers['content-length'])).toBeGreaterThan(0);+ expect(res.body).toBe('');+ });++ it('answers a preflight with 204 and an open origin', async () => {+ const res = await call('/api/x402-pay/og', { method: 'OPTIONS' });+ expect(res.statusCode).toBe(204);+ expect(res.headers['access-control-allow-origin']).toBe('*');+ expect(res.headers['access-control-allow-methods']).toBe('GET,HEAD,OPTIONS');+ });++ it('rejects a write method with a JSON 405 and an Allow header', async () => {+ const res = await call('/api/x402-pay/og', { method: 'POST' });+ expect(res.statusCode).toBe(405);+ expect(res.headers.allow).toBe('GET, HEAD, OPTIONS');+ expect(res.headers['content-type']).toBe('application/json; charset=utf-8');+ expect(JSON.parse(res.body).error).toBe('method_not_allowed');+ });++ it('sets an open CORS origin on the card itself', async () => {+ const res = await call('/api/x402-pay/og');+ expect(res.headers['access-control-allow-origin']).toBe('*');+ });+});diff --git a/tests/cosmetics-purchase.test.js b/tests/cosmetics-purchase.test.jsindex c851efc48..f1eb30e10 100644--- a/tests/cosmetics-purchase.test.js+++ b/tests/cosmetics-purchase.test.js@@ -192,6 +192,23 @@ describe('cosmetic-purchase endpoint boundary', () => {}});+ // The SIWX grant is keyed on (resource, wallet) and the resource URL carries+ // the cosmetic id, not the target account, so without this guard a wallet+ // that bought one skin could sign it onto unlimited other accounts for free.+ it('siwxReGrantAllowed lets a buyer re-confirm but never sells a third account a free unlock', async () => {+ const { siwxReGrantAllowed } = await import('../api/x402/cosmetic-purchase.js');+ const wallet = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++ // The signing wallet re-confirming its own unlock.+ expect(siwxReGrantAllowed({ account: wallet, payer: wallet, alreadyOwned: false })).toBe(true);+ // A guest profile that already owns the item re-confirming it.+ expect(siwxReGrantAllowed({ account: 'guest-1', payer: wallet, alreadyOwned: true })).toBe(true);+ // A third account that never paid: this is a fresh sale, not a re-access.+ expect(siwxReGrantAllowed({ account: 'guest-2', payer: wallet, alreadyOwned: false })).toBe(false);+ // No signer at all cannot re-grant anything it does not already own.+ expect(siwxReGrantAllowed({ account: 'guest-2', payer: null, alreadyOwned: false })).toBe(false);+ });+it('issues a 402 priced in USDC for a premium cosmetic', async () => {const r = await call({ id: 'skin-midnight', account: 'guest-1' });expect(r.status).toBe(402);diff --git a/tests/x402-did-verification-canary.test.js b/tests/x402-did-verification-canary.test.jsindex 3cddc34be..7e99d0a53 100644--- a/tests/x402-did-verification-canary.test.js+++ b/tests/x402-did-verification-canary.test.js@@ -8,7 +8,7 @@ import { describe, it, expect } from 'vitest';const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';process.env.X402_ASSET_MINT_SOLANA = USDC;-const { validateDidDocument } = await import('../api/x402/did.js');+const { validateDidDocument, summarizeResolution, default: didHandler } = await import('../api/x402/did.js');const { getFullRegistry } = await import('../api/_lib/x402/autonomous-registry.js');const goodJws = {@@ -100,6 +100,64 @@ describe('validateDidDocument', () => {});});+describe('summarizeResolution', () => {+ it('verifies a healthy, fast resolution', () => {+ const v = summarizeResolution({ httpStatus: 200, doc: goodJws, latency_ms: 120, did: 'did:three:canary' });+ expect(v.verified).toBe(true);+ expect(v.configured).toBe(true);+ expect(v.malformed).toBe(false);+ expect(v.within_latency).toBe(true);+ expect(v.resolved_did).toBe('did:web:three.ws');+ expect(v.fetch_error).toBeUndefined();+ });++ it('fails a healthy document that resolved too slowly', () => {+ const v = summarizeResolution({ httpStatus: 200, doc: goodJws, latency_ms: 4000, did: 'd' });+ expect(v.within_latency).toBe(false);+ expect(v.malformed).toBe(false);+ expect(v.verified).toBe(false);+ });++ it('reports not-configured on a 404 from the resolver', () => {+ const v = summarizeResolution({ httpStatus: 404, doc: { error: 'not_configured' }, latency_ms: 40, did: 'd' });+ expect(v.configured).toBe(false);+ expect(v.verified).toBe(false);+ });++ it('never claims configured when the resolver was unreachable', () => {+ // http_status 0 means DNS/TLS/timeout. We never saw an answer, so we+ // cannot claim a document is published. The old code read 0 as "not 404"+ // and reported configured:true for a resolver that was entirely dark.+ const v = summarizeResolution({+ httpStatus: 0, doc: null, latency_ms: 5000, did: 'd', fetchError: 'timeout',+ });+ expect(v.configured).toBe(false);+ expect(v.verified).toBe(false);+ expect(v.fetch_error).toBe('timeout');+ });+});++describe('did endpoint method gate', () => {+ function mockRes() {+ const res = { statusCode: 0, body: '', headers: {} };+ res.setHeader = (k, v) => { res.headers[k.toLowerCase()] = v; };+ res.getHeader = (k) => res.headers[k.toLowerCase()];+ res.status = (s) => { res.statusCode = s; return res; };+ res.json = (o) => { res.body = JSON.stringify(o); res.writableEnded = true; return res; };+ res.end = (b) => { res.body = b || res.body; res.writableEnded = true; };+ return res;+ }++ it('405s a write verb instead of serving the DID document', async () => {+ for (const method of ['PUT', 'DELETE', 'PATCH']) {+ const res = mockRes();+ await didHandler({ method, url: '/api/x402/did', headers: {} }, res);+ expect(res.statusCode).toBe(405);+ expect(JSON.parse(res.body).error).toBe('method_not_allowed');+ }+ });+});+describe('did-verification-canary registry entry', () => {const entry = getFullRegistry().find((e) => e.id === 'did-verification-canary');diff --git a/tests/x402-rate-limit-probe-target.test.js b/tests/x402-rate-limit-probe-target.test.jsnew file mode 100644index 000000000..3d751eaae--- /dev/null+++ b/tests/x402-rate-limit-probe-target.test.js@@ -0,0 +1,111 @@+// /api/x402/rate-limit-probe: which endpoints the paid capacity probe will aim at.+//+// The probe makes the SERVER issue an unauthenticated POST to `origin + endpoint`+// to read the target's 402 challenge price. Left open to any /api/ path, a paying+// caller could point that self-request at an arbitrary internal route. The handler+// now admits only the prefixes the autonomous registry actually meters, which is+// also the set of routes that answer a 402 at all.+//+// The companion assertion here is the one that keeps the allowlist honest: every+// real HTTP path in getSelfRegistry() must still be probeable, so the guard can+// never quietly shrink the product.++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../api/_lib/x402-paid-endpoint.js', () => ({ paidEndpoint: (cfg) => cfg }));+vi.mock('../api/_lib/x402-spec.js', () => ({ buildBazaarSchema: () => ({}) }));+vi.mock('../api/_lib/x402/bazaar-helpers.js', () => ({ withService: (x) => x }));+vi.mock('../api/_lib/x402/access-control.js', () => ({ installAccessControl: () => ({}) }));+vi.mock('../api/_lib/redis.js', () => ({ getRedis: () => null }));++const probeModule = await import('../api/x402/rate-limit-probe.js');+const spec = probeModule.default;+const { getSelfRegistry } = await import('../api/_lib/x402/autonomous-registry.js');++// The pattern agents pre-validate against, straight from the published schema.+const ADVERTISED = new RegExp(probeModule.INPUT_SCHEMA.properties.endpoint.pattern);++function call(body) {+ return spec.handler({+ req: { method: 'POST', headers: { 'content-type': 'application/json' }, body },+ res: {},+ requirement: null,+ payer: null,+ });+}++let fetchSpy;+beforeEach(() => {+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ status: 404, json: async () => ({}) });+});++describe('rate-limit-probe target gating', () => {+ it('rejects an absolute URL', async () => {+ await expect(call({ endpoint: 'https://evil.example/x' })).rejects.toMatchObject({+ status: 400,+ code: 'invalid_endpoint',+ });+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it('rejects an /api/ route that is not metered', async () => {+ await expect(call({ endpoint: '/api/creations' })).rejects.toMatchObject({+ status: 400,+ code: 'endpoint_not_metered',+ });+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it('rejects a traversal that would climb out of the metered prefix', async () => {+ await expect(call({ endpoint: '/api/x402/../creations' })).rejects.toMatchObject({+ status: 400,+ code: 'endpoint_not_metered',+ });+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it('rejects a prefix look-alike', async () => {+ await expect(call({ endpoint: '/api/x402evil' })).rejects.toMatchObject({+ status: 400,+ code: 'endpoint_not_metered',+ });+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it('probes a metered route and reports capacity from the live price', async () => {+ fetchSpy.mockResolvedValue({+ status: 402,+ json: async () => ({ accepts: [{ amount: '10000' }, { amount: '250000' }] }),+ });+ const out = await call({ endpoint: '/api/x402/crypto-intel' });+ expect(fetchSpy).toHaveBeenCalledOnce();+ expect(out.endpoint).toBe('/api/x402/crypto-intel');+ expect(out.price_atomic).toBe(10_000); // cheapest accept wins+ expect(out.limit).toBe(Math.floor(out.daily_cap_atomic / 10_000));+ expect(out.remaining_calls).toBe(Math.floor(out.remaining_capacity_atomic / 10_000));+ expect(out.cooldown_active).toBe(false);+ });++ it('still admits every HTTP path the autonomous registry meters', async () => {+ const paths = [+ ...new Set(+ getSelfRegistry()+ .map((e) => e.path)+ .filter((p) => typeof p === 'string' && p.startsWith('/api/') && !p.startsWith('/api/_')),+ ),+ ];+ expect(paths.length).toBeGreaterThan(20);+ for (const path of paths) {+ await expect(call({ endpoint: path })).resolves.toBeTruthy();+ }+ });++ it('advertises exactly what it admits', () => {+ for (const path of ['/api/x402/crypto-intel', '/api/x402-pay?balance=1', '/api/mcp', '/api/ibm-mcp']) {+ expect(ADVERTISED.test(path), path).toBe(true);+ }+ for (const path of ['/api/creations', '/api/x402evil', '/api/mcpevil']) {+ expect(ADVERTISED.test(path), path).toBe(false);+ }+ });+});diff --git a/tests/x402-remix-asset-errors.test.js b/tests/x402-remix-asset-errors.test.jsnew file mode 100644index 000000000..f619cbc82--- /dev/null+++ b/tests/x402-remix-asset-errors.test.js@@ -0,0 +1,90 @@+// /api/x402/remix-asset: the paid remix endpoint's rejection path.+//+// Regression cover for a live defect: the handler caught its own RemixError and+// wrote the 4xx to `res` itself. paidEndpoint treats a handler that flushed the+// response as a delivered-but-unsettled good: it logged a payment_unsettled_flush+// leak event, recorded a FAILED payment metric, and threw. So every ordinary+// validation refusal (empty instruction, unknown source, source not remixable)+// showed up in x402 telemetry as a money leak.+//+// The contract paidEndpoint actually wants is a thrown Error carrying .status ++// .code, which it maps to a clean error response with settlement skipped. These+// tests pin that: the handler throws and never touches `res`.++import { describe, it, expect, vi } from 'vitest';++const getRemixSource = vi.fn();+const generate = vi.fn();++vi.mock('../api/_lib/x402-paid-endpoint.js', () => ({ paidEndpoint: (cfg) => cfg }));+vi.mock('../api/_lib/x402-spec.js', () => ({ buildBazaarSchema: () => ({}) }));+vi.mock('../api/_lib/x402/bazaar-helpers.js', () => ({ withService: (x) => x }));+vi.mock('../api/_lib/forge-store.js', () => ({ getRemixSource, linkRefinement: vi.fn() }));+vi.mock('../api/_lib/remix-settlement.js', () => ({ settleRemixRoyalty: vi.fn() }));+vi.mock('../api/_lib/streaks.js', () => ({ unlockBadge: vi.fn(), BADGES: { FIRST_REMIX_RECEIVED: 'first_remix' } }));+vi.mock('../api/_lib/feed.js', () => ({ publishUserEvent: vi.fn() }));+vi.mock('../api/_mcp-studio/forge-client.js', () => ({+ generate,+ originFromReq: () => 'https://three.ws',+ viewerUrl: (base, url) => `${base}/view?src=${url}`,+}));++const spec = (await import('../api/x402/remix-asset.js')).default;++// A res that fails the test loudly if the handler ever writes to it: writing is+// exactly the behaviour this file exists to prevent.+function forbiddenRes() {+ const boom = () => {+ throw new Error('handler wrote to res; it must throw so paidEndpoint can skip settlement');+ };+ return { setHeader: boom, end: boom, writeHead: boom, status: boom, json: boom };+}++function call(body) {+ return spec.handler({+ req: { method: 'POST', headers: { host: 'three.ws', 'content-type': 'application/json' }, body },+ res: forbiddenRes(),+ requirement: { amount: '250000', network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' },+ payer: null,+ });+}++describe('remix-asset rejections throw instead of flushing the response', () => {+ it('rejects a missing source_creation_id with 400', async () => {+ await expect(call({ instruction: 'make it metallic' })).rejects.toMatchObject({+ status: 400,+ code: 'missing_source',+ });+ });++ it('rejects a missing instruction with 400', async () => {+ await expect(call({ source_creation_id: 'abc' })).rejects.toMatchObject({+ status: 400,+ code: 'missing_instruction',+ });+ });++ it('rejects an over-long instruction with 400', async () => {+ await expect(+ call({ source_creation_id: 'abc', instruction: 'x'.repeat(501) }),+ ).rejects.toMatchObject({ status: 400, code: 'instruction_too_long' });+ });++ it('rejects an unknown source with 404 and never starts a generation', async () => {+ getRemixSource.mockResolvedValueOnce(null);+ await expect(call({ source_creation_id: 'nope', instruction: 'shinier' })).rejects.toMatchObject({+ status: 404,+ code: 'source_not_found',+ });+ expect(generate).not.toHaveBeenCalled();+ });++ it('rejects a source that is not published as remixable with 403', async () => {+ getRemixSource.mockResolvedValueOnce({ id: 'abc', remixable: false, royaltyBps: 1000 });+ await expect(call({ source_creation_id: 'abc', instruction: 'shinier' })).rejects.toMatchObject({+ status: 403,+ code: 'not_remixable',+ });+ expect(generate).not.toHaveBeenCalled();+ });+});diff --git a/tests/x402-schema-check.test.js b/tests/x402-schema-check.test.jsnew file mode 100644index 000000000..f9d499de5--- /dev/null+++ b/tests/x402-schema-check.test.js@@ -0,0 +1,108 @@+// /api/x402/schema-check: the paid JSON-API conformance checker.+//+// Regression cover for a live defect: the handler took its request positionally+// (`async handler(req)`), but paidEndpoint calls it with a CONTEXT object+// ({ req, res, requirement, payer }). The body was therefore read off the+// context, never found, and every paid call settled and answered+// `unsupported api "undefined"`. These tests drive the real spec.handler with+// the shape paidEndpoint actually passes.+//+// paidEndpoint is stubbed to the identity so the default export IS the spec and+// the handler can be called directly without a payment rail (same pattern as+// tests/x402-pump-launch-listing.test.js).++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++vi.mock('../api/_lib/x402-paid-endpoint.js', () => ({ paidEndpoint: (cfg) => cfg }));+vi.mock('../api/_lib/x402-spec.js', () => ({ buildBazaarSchema: () => ({}) }));+vi.mock('../api/_lib/x402/bazaar-helpers.js', () => ({ withService: (x) => x }));++const spec = (await import('../api/x402/schema-check.js')).default;++const FEED = {+ generated_at: '2026-08-14T00:00:00.000Z',+ site: { name: 'three.ws', url: 'https://three.ws' },+ entries: [+ { date: '2026-08-14', title: 'A change', summary: 'What shipped.', tags: ['feature'] },+ ],+};++function ctx(body) {+ return { req: { method: 'POST', headers: {}, body }, res: {}, requirement: null, payer: null };+}++let fetchSpy;+afterEach(() => {+ fetchSpy?.mockRestore();+ fetchSpy = undefined;+});++describe('schema-check handler: happy path', () => {+ beforeEach(() => {+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => FEED,+ });+ });++ it('reads the body from the paidEndpoint context and validates the feed', async () => {+ const out = await spec.handler(ctx({ api: 'changelog_json' }));+ expect(out).toMatchObject({+ ok: true,+ api: 'changelog_json',+ valid: true,+ version: '2026-08-14',+ entry_count: 1,+ schema_errors: [],+ });+ expect(typeof out.fetched_at).toBe('string');+ expect(fetchSpy).toHaveBeenCalledOnce();+ expect(String(fetchSpy.mock.calls[0][0])).toMatch(/\/changelog\.json$/);+ });++ it('reports the exact schema violations when the feed breaks', async () => {+ fetchSpy.mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({ ...FEED, site: { name: 'three.ws' }, entries: [] }),+ });+ const out = await spec.handler(ctx({ api: 'changelog_json' }));+ expect(out.ok).toBe(true);+ expect(out.valid).toBe(false);+ expect(out.schema_errors).toContain('missing or invalid site.url');+ expect(out.schema_errors).toContain('entries array is empty');+ });++ it('turns a dead feed into a finding rather than a throw', async () => {+ fetchSpy.mockResolvedValue({ ok: false, status: 503, json: async () => ({}) });+ const out = await spec.handler(ctx({ api: 'changelog_json' }));+ expect(out).toMatchObject({ ok: false, valid: false, entry_count: 0, schema_errors: ['http_503'] });+ });+});++describe('schema-check handler: rejected before settlement', () => {+ beforeEach(() => {+ fetchSpy = vi.spyOn(globalThis, 'fetch');+ });++ it('throws a 400 for an unsupported api instead of billing for an error body', async () => {+ await expect(spec.handler(ctx({ api: 'not_a_feed' }))).rejects.toMatchObject({+ status: 400,+ code: 'unsupported_api',+ });+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it('throws a 400 when the body carries no api at all', async () => {+ await expect(spec.handler(ctx({}))).rejects.toMatchObject({ status: 400, code: 'unsupported_api' });+ });++ it('does not treat an inherited Object property as a checker', async () => {+ await expect(spec.handler(ctx({ api: 'constructor' }))).rejects.toMatchObject({+ status: 400,+ code: 'unsupported_api',+ });+ expect(fetchSpy).not.toHaveBeenCalled();+ });+});diff --git a/tests/x402-vanity-cache-secrets.test.js b/tests/x402-vanity-cache-secrets.test.jsnew file mode 100644index 000000000..29f9128f4--- /dev/null+++ b/tests/x402-vanity-cache-secrets.test.js@@ -0,0 +1,135 @@+// The x402 replay/idempotency cache must never hold spendable key material.+// Both vanity endpoints deliver a Solana secret exactly once in the live+// response; what they hand storeResponse() is a stripped copy. These pin that.+//+// The verifiable endpoint has a second, less obvious leak channel: its receipt+// is verifiable precisely BECAUSE serverSeed re-derives the key (masterSeed =+// HKDF(serverSeed || clientSeed || requestNonce), then candidate winningIndex).+// So serverSeed is key-equivalent and must be stripped even from a SEALED+// delivery, where the plaintext secret was never in the body to begin with.++import { describe, it, expect } from 'vitest';+import { cacheSafeBody as vanityCacheSafeBody } from '../api/x402/vanity.js';+import { cacheSafeBody as verifiableCacheSafeBody } from '../api/x402/vanity-verifiable.js';++const SECRET_B58 = '5JueXamPLEonLYnEvErAfUnDeDkEyMaTeRiAL111111111111111111111111111';+const SECRET_BYTES = Array.from({ length: 64 }, (_, i) => i);+const SERVER_SEED = 'a'.repeat(64);++function groundResult(extra = {}) {+ return {+ address: 'SoEXAMPLEdoNotUse1111111111111111111111111111',+ prefix: 'So',+ suffix: null,+ ignoreCase: false,+ format: 'keypair',+ secretKeyBase58: SECRET_B58,+ secretKey: SECRET_BYTES,+ mnemonic: null,+ attempts: 3042,+ network: 'solana',+ source: 'ground',+ certificate: { certId: 'cert_1', signature: 'ed25519:…' },+ ...extra,+ };+}++function receipt(extra = {}) {+ return {+ protocol: 'three-vanity/v1',+ address: 'SoEXAMPLEdoNotUse1111111111111111111111111111',+ commitment: 'b'.repeat(64),+ serverSeed: SERVER_SEED,+ clientSeed: 'c'.repeat(64),+ requestNonce: 'd'.repeat(32),+ winningIndex: 3041,+ attempts: 3042,+ sealed: false,+ signature: 'e'.repeat(128),+ servicePublicKey: 'SoServiceKey1111111111111111111111111111111',+ secretKeyBase58: SECRET_B58,+ secretKey: SECRET_BYTES,+ seed: 'f'.repeat(64),+ ...extra,+ };+}++describe('/api/x402/vanity cacheSafeBody', () => {+ it('strips the plaintext secret from an unsealed result and marks it', () => {+ const stored = JSON.parse(vanityCacheSafeBody(groundResult()));+ expect(stored.secretKeyBase58).toBeUndefined();+ expect(stored.secretKey).toBeUndefined();+ expect(stored).not.toHaveProperty('mnemonic');+ expect(stored.secret_omitted_from_cache).toBe(true);+ expect(stored.note).toMatch(/never stored/i);+ });++ it('keeps the public metadata a replayed payment still needs', () => {+ const stored = JSON.parse(vanityCacheSafeBody(groundResult()));+ expect(stored.address).toBe('SoEXAMPLEdoNotUse1111111111111111111111111111');+ expect(stored.attempts).toBe(3042);+ expect(stored.certificate.certId).toBe('cert_1');+ });++ it('strips a mnemonic delivery too (the phrase is key material)', () => {+ const stored = JSON.parse(+ vanityCacheSafeBody(+ groundResult({ format: 'mnemonic', mnemonic: 'legal winner thank year wave sausage worth useful legal winner thank yellow', wordCount: 12 }),+ ),+ );+ expect(stored.mnemonic).toBeUndefined();+ expect(stored.wordCount).toBe(12);+ });++ it('caches a sealed delivery unchanged (ciphertext is safe at rest)', () => {+ const sealed = {+ address: 'SoEXAMPLEdoNotUse1111111111111111111111111111',+ sealed: true,+ sealedSecret: { scheme: 'x25519-hkdf-sha256-aes256gcm', ciphertext: 'AAAA', recipient: 'r' },+ };+ expect(JSON.parse(vanityCacheSafeBody(sealed))).toEqual(sealed);+ });++ it('never emits the secret in the serialized string', () => {+ expect(vanityCacheSafeBody(groundResult())).not.toContain(SECRET_B58);+ });+});++describe('/api/x402/vanity-verifiable cacheSafeBody', () => {+ it('strips the plaintext secret and the key-equivalent serverSeed', () => {+ const stored = JSON.parse(verifiableCacheSafeBody(receipt()));+ expect(stored.secretKeyBase58).toBeUndefined();+ expect(stored.secretKey).toBeUndefined();+ expect(stored.seed).toBeUndefined();+ expect(stored.serverSeed).toBeUndefined();+ expect(stored.secret_omitted_from_cache).toBe(true);+ });++ it('strips serverSeed from a SEALED receipt as well', () => {+ const sealedReceipt = receipt({+ sealed: true,+ sealedSecret: { scheme: 'x25519-hkdf-sha256-aes256gcm', ciphertext: 'AAAA', recipient: 'r' },+ secretKeyBase58: undefined,+ secretKey: undefined,+ seed: undefined,+ });+ const stored = JSON.parse(verifiableCacheSafeBody(sealedReceipt));+ expect(stored.serverSeed).toBeUndefined();+ // The buyer's own ciphertext stays: only their X25519 key opens it.+ expect(stored.sealedSecret.ciphertext).toBe('AAAA');+ });++ it('keeps the non-reconstructing receipt fields', () => {+ const stored = JSON.parse(verifiableCacheSafeBody(receipt()));+ expect(stored.commitment).toBe('b'.repeat(64));+ expect(stored.winningIndex).toBe(3041);+ expect(stored.signature).toBe('e'.repeat(128));+ expect(stored.address).toBe('SoEXAMPLEdoNotUse1111111111111111111111111111');+ });++ it('never emits the secret or the serverSeed in the serialized string', () => {+ const body = verifiableCacheSafeBody(receipt());+ expect(body).not.toContain(SECRET_B58);+ expect(body).not.toContain(SERVER_SEED);+ });+});