Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: A2A client/server, MCP bridge + server, spending ledger, receipts storage + admin, DID, paid asset download

nirholas4c08053d74c7
diff --git a/.env.example b/.env.example
index fe9de65ea..9d3794cf3 100644
--- a/.env.example
+++ b/.env.example
@@ -216,6 +216,11 @@ X402_ASSET_MINT_SOLANA=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
X402_ASSET_ADDRESS_BASE=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
# Price in base units (USDC = 6 decimals; 1000 = 0.001 USDC).
X402_MAX_AMOUNT_REQUIRED=1000
+# USE-15 — TTL (seconds) for the payment-identifier idempotency cache.
+# Same paymentId within the window returns the cached response without
+# re-charging. Per-route override via paidEndpoint({ paymentIdentifier:
+# { ttlSeconds } }). 3600s = "long TTL" per x402 docs.
+X402_IDEMPOTENCY_TTL_SECONDS=3600
# Per-network facilitators. PayAI supports both Solana and Base mainnet;
# x402.org's reference facilitator only supports base-sepolia, so do not point
# X402_FACILITATOR_URL_BASE at it for production.
@@ -227,6 +232,42 @@ X402_FACILITATOR_TOKEN_BASE=
# Solana fee payer advertised to clients (must match facilitator's /supported).
X402_FEE_PAYER_SOLANA=2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4
+# ERC-8021 Schema 2 builder-code app identifier (USE-20). When set, every 402
+# challenge advertises the `builder-code` extension, every paid request must
+# echo it (anti-tamper), and settlement-tx calldata is suffixed with a CBOR
+# map for on-chain attribution. Pattern: ^[a-z0-9_]{1,32}$. Leave unset to
+# disable. Coinbase builder rewards / x402scan analytics use this to credit
+# the app that exposed the paid endpoint.
+X402_BUILDER_CODE_APP=three_d_agent
+
+# ── x402 Offer & Receipt extension (USE-17) ────────────────────────────────
+# Signs every 402 offer and every settled-payment receipt so buyers get
+# cryptographic proof of the interaction. Verifiers resolve the signer key via
+# /.well-known/did.json (rewritten to /api/x402/did). Buyers can re-query their
+# own receipts later via /api/x402/my-receipts.
+#
+# Key separation is CRITICAL — this MUST be a dedicated EOA/JWK, never one of
+# the X402_PAY_TO_* wallets. Receipts are server claims about transactions;
+# co-mingling with the funds-receiving wallet would imply the payment cosigner
+# endorses every receipt ever issued. The issuer module fails loudly on boot
+# if the derived address collides with any X402_PAY_TO_* key.
+#
+# EIP-712 mode (default): set OFFER_RECEIPT_SIGNING_PRIVATE_KEY to a fresh
+# 0x-hex EVM private key. Generate with:
+# node -e "console.log(require('viem/accounts').generatePrivateKey())"
+# JWS mode (did:web): set OFFER_RECEIPT_FORMAT=jws + OFFER_RECEIPT_JWK to a
+# JSON-encoded JWK private key. Vercel has no KMS; for production-grade key
+# custody, swap the issuer for a Google KMS / AWS KMS / HashiCorp Vault signer.
+# When all signing keys are unset, the extension is silently disabled and the
+# 402/200 wire format stays valid (extension is purely additive).
+OFFER_RECEIPT_SIGNING_PRIVATE_KEY=
+OFFER_RECEIPT_FORMAT=eip712
+OFFER_RECEIPT_JWK=
+OFFER_RECEIPT_JWS_ALG=EdDSA
+# Bare hostname used to build did:web identifiers (no scheme, no path).
+# Defaults to the host parsed from PUBLIC_APP_ORIGIN.
+SERVER_DOMAIN=
+
# Coinbase Developer Platform (CDP) facilitator. REQUIRED for agentic.market /
# CDP Bazaar listing — only endpoints whose first verify+settle is processed
# by CDP get cataloged. PayAI is a fine fallback for non-Bazaar use.
diff --git a/agent-payments-sdk/src/solana/x402/types.ts b/agent-payments-sdk/src/solana/x402/types.ts
index 7f5578259..7afb01cf7 100644
--- a/agent-payments-sdk/src/solana/x402/types.ts
+++ b/agent-payments-sdk/src/solana/x402/types.ts
@@ -111,6 +111,41 @@ export interface PaymentRequired {
error?: string;
resource: ResourceInfo;
accepts: PaymentRequirements[];
+ /** Per-spec extension envelope keyed by extension name. */
+ extensions?: Record<string, unknown>;
+}
+
+// ─── auth-hints extension (server → client) ─────────────────────────────────
+//
+// Spec: /tmp/x402-docs/specs/extensions/extension-auth-hints.md
+//
+// When a 402 response contains an `auth-hints` extension, certain accepts[]
+// entries are gated by authentication rather than (or in addition to)
+// payment. The client picks an auth method it can satisfy, attaches the
+// matching header on the retry, and skips the X-PAYMENT dance entirely.
+
+export type AuthHintsMethod =
+ | { type: "oauth2"; tokenType?: "Bearer" | "DPoP"; authorizationServer?: string; tokenEndpoint?: string; registrationEndpoint?: string }
+ | { type: "sign-in-with-x" };
+
+export interface AuthHintsRequirement {
+ acceptIndexes: number[];
+ methods: AuthHintsMethod[];
+}
+
+export interface AuthHintsExtension {
+ info: { authRequirements: AuthHintsRequirement[] };
+ schema?: Record<string, unknown>;
+}
+
+/** Headers a buyer can attach to satisfy an `auth-hints` requirement. */
+export interface AuthHintsCredentials {
+ /** Pre-fetched OAuth 2.0 access token. Sent as `Authorization: Bearer …`. */
+ oauth2AccessToken?: string;
+ /** Base64-encoded SIGN-IN-WITH-X header value. The client must produce a
+ * CAIP-122 message + signature itself (or via the sign-in-with-x extension)
+ * before invoking the request. */
+ siwxHeader?: string;
}
// ─── Payment Payload (client → server proof in X-PAYMENT header) ───────────
@@ -212,4 +247,23 @@ export interface X402ClientConfig {
network?: string;
/** Max time to wait for tx confirmation in ms (default: 30_000) */
confirmationTimeoutMs?: number;
+ /**
+ * auth-hints handler. When the server's 402 includes an `auth-hints`
+ * extension, the client invokes this callback with the offered methods so
+ * the caller can attach OAuth2 / SIWX credentials and bypass payment.
+ *
+ * Return value semantics:
+ * • `AuthHintsCredentials` with at least one filled field → the wrapper
+ * retries with the matching header and returns the response.
+ * • `null` / `undefined` → fall through
+ * to the regular payment flow (sign + pay).
+ *
+ * If the callback throws or returns nothing, the wrapper proceeds with
+ * payment instead — auth-hints are advisory, not mandatory.
+ */
+ onAuthRequired?: (ctx: {
+ extension: AuthHintsExtension;
+ accepts: PaymentRequirements[];
+ resource: ResourceInfo;
+ }) => Promise<AuthHintsCredentials | null | undefined> | AuthHintsCredentials | null | undefined;
}
diff --git a/api/_lib/env.js b/api/_lib/env.js
index ffbca8058..8c509ffe3 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -175,6 +175,14 @@ export const env = {
get X402_MAX_AMOUNT_REQUIRED() {
return opt('X402_MAX_AMOUNT_REQUIRED', '1000');
},
+ // USE-15 — TTL (seconds) for the payment-identifier idempotency cache.
+ // Keyed by ${route}|${paymentId}; a second hit with the same id within the
+ // window replays the cached response without re-charging. 1h default matches
+ // the x402 docs' "long TTL" guidance for infrequently changing resources.
+ // Per-route override via paidEndpoint({ paymentIdentifier: { ttlSeconds } }).
+ get X402_IDEMPOTENCY_TTL_SECONDS() {
+ return opt('X402_IDEMPOTENCY_TTL_SECONDS', '3600');
+ },
// Per-network facilitators. PayAI supports both Solana and Base mainnet;
// x402.org's reference facilitator only supports base-sepolia, so it cannot
// be the default for Base mainnet payments.
@@ -223,6 +231,24 @@ export const env = {
return opt('X402_FEE_PAYER_SOLANA', '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4');
},
+ // ERC-8021 builder-code app identifier. When set, every 402 challenge
+ // advertises the `builder-code` extension declaring this as `info.a`,
+ // every paid request must echo it (anti-tamper), and the facilitator
+ // appends a CBOR suffix to settlement-tx calldata so off-chain parsers
+ // can attribute payment volume to this app. Pattern: `^[a-z0-9_]{1,32}$`.
+ // Leave unset to disable on-chain attribution.
+ get X402_BUILDER_CODE_APP() {
+ return opt('X402_BUILDER_CODE_APP');
+ },
+
+ // USE-23: shared secret that lets internal Vercel functions skip the 402
+ // challenge on our own paid endpoints by sending X-API-Key: <this value>.
+ // Compared with constant-time equality in api/_lib/x402/access-control.js.
+ // Generate with: openssl rand -base64 32
+ get INTERNAL_API_KEY() {
+ return opt('INTERNAL_API_KEY');
+ },
+
// EVM mainnet chains accepted by /api/x402/* paid endpoints — defaults to
// Base + Arbitrum because those are the two CDP-Bazaar-supported networks
// the seller wizard currently exposes. Comma-separated CAIP-2 IDs.
diff --git a/api/_lib/siwx-storage.js b/api/_lib/siwx-storage.js
index 440fe2d5e..30e5595f5 100644
--- a/api/_lib/siwx-storage.js
+++ b/api/_lib/siwx-storage.js
@@ -14,8 +14,11 @@
// addresses in their canonical-per-chain form, which differs by namespace:
// eip155:* → lowercase hex (NOT EIP-55 checksummed)
// solana:* → Base58 (case-sensitive, leave as-is)
-// Every read + write goes through normalizeAddress() so lookups are
-// case-insensitive on EVM while staying byte-for-byte exact on Solana.
+//
+// Every WRITE normalizes via normalizeAddress(network, address) — the network
+// is known at recordPayment time. READS go through a chain-aware OR query
+// because the SIWxStorage contract only passes (resource, address) to
+// hasPaid: we lower-case the EVM branch and leave the Solana branch exact.
import { sql } from './db.js';
@@ -28,45 +31,58 @@ function namespaceOf(chainId) {
return colon === -1 ? chainId.toLowerCase() : chainId.slice(0, colon).toLowerCase();
}
+// Public — also used by siwx-server.js after verifying the signature.
export function normalizeAddress(chainId, address) {
- if (!address) return address;
+ if (!chainId || !address) throw new Error('siwx-storage: network+address required');
const ns = namespaceOf(chainId);
if (ns === 'eip155') return String(address).toLowerCase();
- return String(address);
+ if (ns === 'solana') return String(address);
+ throw new Error(`siwx-storage: unsupported CAIP-2 namespace "${chainId}"`);
}
async function hasPaid(resource, address) {
if (!resource || !address) return false;
+ const evm = String(address).toLowerCase();
+ const sol = String(address);
const rows = await sql`
- select expires_at
+ select expires_at, network
from siwx_payments
where resource = ${resource}
- and address = ${address}
+ and (
+ (network like 'eip155:%' and address = ${evm})
+ or
+ (network like 'solana:%' and address = ${sol})
+ )
limit 1
`;
if (!rows.length) return false;
const exp = rows[0].expires_at;
if (exp && new Date(exp).getTime() <= Date.now()) return false;
+ const matched = String(rows[0].network).startsWith('eip155:') ? evm : sol;
await sql`
update siwx_payments
set last_used_at = now(),
use_count = use_count + 1
where resource = ${resource}
- and address = ${address}
+ and address = ${matched}
`;
return true;
}
async function recordPayment(resource, address, opts = {}) {
if (!resource || !address) return;
- const network = opts.network || null;
+ if (!opts.network) {
+ throw new Error('siwx-storage.recordPayment: opts.network is required');
+ }
+ const normalized = normalizeAddress(opts.network, address);
const ttlSeconds = Number.isFinite(opts.ttlSeconds) ? Number(opts.ttlSeconds) : null;
- const expiresAt = ttlSeconds && ttlSeconds > 0
- ? new Date(Date.now() + ttlSeconds * 1000).toISOString()
- : null;
+ const expiresAt =
+ ttlSeconds && ttlSeconds > 0
+ ? new Date(Date.now() + ttlSeconds * 1000).toISOString()
+ : null;
await sql`
insert into siwx_payments (resource, address, network, paid_at, expires_at)
- values (${resource}, ${address}, ${network}, now(), ${expiresAt})
+ values (${resource}, ${normalized}, ${opts.network}, now(), ${expiresAt})
on conflict (resource, address) do update
set network = excluded.network,
paid_at = excluded.paid_at,
@@ -89,6 +105,39 @@ async function recordNonce(nonce, ctx = {}) {
`;
}
+// Cron helpers exported for api/cron/siwx-gc.js + tests. Both return the
+// number of rows deleted so the cron can emit a sensible summary log.
+
+// Compute the cutoff inside Postgres so the comparison uses the same clock
+// as the now()-defaulted columns above — JS Date.now() can drift seconds
+// from the Neon primary, and at the 0-grace boundary (cron-driven cleanup)
+// the difference manifests as rows that should be deleted but aren't.
+
+export async function pruneExpiredPayments(graceSeconds = 7 * 24 * 3600) {
+ const rows = await sql`
+ with deleted as (
+ delete from siwx_payments
+ where expires_at is not null
+ and expires_at < now() - make_interval(secs => ${Number(graceSeconds)})
+ returning 1
+ )
+ select count(*)::int as n from deleted
+ `;
+ return rows[0]?.n ?? 0;
+}
+
+export async function pruneOldNonces(maxAgeSeconds = 600) {
+ const rows = await sql`
+ with deleted as (
+ delete from siwx_nonces
+ where used_at < now() - make_interval(secs => ${Number(maxAgeSeconds)})
+ returning 1
+ )
+ select count(*)::int as n from deleted
+ `;
+ return rows[0]?.n ?? 0;
+}
+
export const siwxStorage = {
hasPaid,
recordPayment,
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index 5ba9ac6dd..77f3e2d63 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -1,16 +1,32 @@
// Helper for building paid x402 endpoints with minimal boilerplate.
//
-// A paid endpoint goes through the same 7-step dance every time: CORS →
-// method-check → 402 challenge (when no payment header) → verify → run the
-// actual work → settle → respond with the X-PAYMENT-RESPONSE header. We
-// factor that into `paidEndpoint(spec)` so each new /api/x402/* file only
-// has to declare its route metadata + a handler that returns JSON.
+// A paid endpoint runs an 8-step dance: CORS → method-check → access-control
+// hook (optional bypass) → SIWX short-circuit (when opted in) → 402 challenge
+// (when no payment header) → verify → run the handler → settle → respond
+// with the X-PAYMENT-RESPONSE header. We factor that into `paidEndpoint(spec)`
+// so each new /api/x402/* file only has to declare its route metadata + a
+// handler that returns JSON.
//
// Pricing: each endpoint gets its own `priceAtomics` (USDC has 6 decimals,
// so "1000" = $0.001). Networks default to Base mainnet only; pass
// `networks: ['base', 'solana']` to advertise both. The bazaar discovery
// extension is required — agentic.market's catalog rejects entries without
// it. See api/_lib/x402-spec.js for the v2 wire-format details.
+//
+// SIWX opt-in (Sign-In-With-X, CAIP-122). Add `siwx: { statement, ttlSeconds?,
+// expirationSeconds? }` to opt the endpoint into wallet-signature re-access:
+// - statement: human-readable purpose shown to the wallet on signing.
+// - ttlSeconds: how long the payment grant lasts (null = permanent).
+// - expirationSeconds: SIWX message validity window (default 300s).
+// When set, the 402 body declares the `sign-in-with-x` extension, and an
+// incoming `SIGN-IN-WITH-X` header skips the X-PAYMENT path for any wallet
+// already in siwx_payments. Fresh settlements record a grant automatically.
+//
+// Per-asset payouts. Pass `payTo: { base?, solana?, bsc? }` to override the
+// shared env.X402_PAY_TO_* receivers — used by /api/x402/asset-download so
+// each creator can collect USDC to their own wallet without forking the
+// helper. Missing keys fall back to env (so a single override doesn't
+// disable the other networks).
import { cors, error } from './http.js';
import { env } from './env.js';
@@ -40,6 +56,22 @@ import {
writeCachedResponse,
writeConflict,
} from './x402/payment-identifier-server.js';
+import {
+ authenticateSiwx,
+ declareSiwxExtensionFor,
+ recordSiwxPayment,
+} from './siwx-server.js';
+import { normalizeAddress } from './siwx-storage.js';
+import {
+ buildOffersExtension,
+ buildReceiptExtension,
+} from './x402/offer-receipt-server.js';
+import { recordReceipt } from './x402/receipt-storage.js';
+import {
+ authenticateAuthHintsRequest,
+ declareAuthHintsExtension,
+ freeEvmAcceptForAuth,
+} from './x402/auth-hints.js';
const NETWORK_ALIASES = {
base: NETWORK_BASE_MAINNET,
@@ -54,7 +86,7 @@ function resolveNetwork(name) {
return NETWORK_ALIASES[name] || name;
}
-function buildAccept(network, priceAtomics, resourceUrl) {
+function buildAccept(network, priceAtomics, resourceUrl, payToOverride) {
const common = {
scheme: 'exact',
amount: String(priceAtomics),
@@ -65,7 +97,7 @@ function buildAccept(network, priceAtomics, resourceUrl) {
return {
...common,
network: NETWORK_BASE_MAINNET,
- payTo: env.X402_PAY_TO_BASE,
+ payTo: payToOverride?.base || env.X402_PAY_TO_BASE,
asset: env.X402_ASSET_ADDRESS_BASE,
// EIP-712 domain name must match the on-chain USDC contract — Base
// USDC's domain is "USD Coin" (not "USDC"), or signatures fail.
@@ -76,25 +108,26 @@ function buildAccept(network, priceAtomics, resourceUrl) {
return {
...common,
network: NETWORK_SOLANA_MAINNET,
- payTo: env.X402_PAY_TO_SOLANA,
+ payTo: payToOverride?.solana || env.X402_PAY_TO_SOLANA,
asset: env.X402_ASSET_MINT_SOLANA,
// PayAI requires this account as fee payer; without it /verify rejects.
extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
};
}
if (network === NETWORK_BSC_MAINNET) {
+ const contract = payToOverride?.bsc || env.X402_PAY_TO_BSC;
// Contract-mediated "direct" scheme — the client calls
// ThreeWSPayments.pay(bytes32) from their own wallet (see x402-bsc-direct.js).
return {
...common,
scheme: 'direct',
network: NETWORK_BSC_MAINNET,
- payTo: env.X402_PAY_TO_BSC,
+ payTo: contract,
asset: env.X402_ASSET_ADDRESS_BSC,
extra: {
name: 'Binance-Peg USD Coin',
decimals: 6,
- contract: env.X402_PAY_TO_BSC,
+ contract,
method: 'pay(bytes32)',
eventTopic: BSC_PAYMENT_EVENT_TOPIC,
},
@@ -103,14 +136,17 @@ function buildAccept(network, priceAtomics, resourceUrl) {
throw new X402Error('unsupported_network', `paidEndpoint: unsupported network ${network}`, 500);
}
-function buildRequirements({ priceAtomics, networks, resourceUrl }) {
+function buildRequirements({ priceAtomics, networks, resourceUrl, payToOverride }) {
const out = [];
for (const name of networks) {
const net = resolveNetwork(name);
- if (net === NETWORK_BASE_MAINNET && !env.X402_PAY_TO_BASE) continue;
- if (net === NETWORK_SOLANA_MAINNET && !env.X402_PAY_TO_SOLANA) continue;
- if (net === NETWORK_BSC_MAINNET && !env.X402_PAY_TO_BSC) continue;
- const accept = buildAccept(net, priceAtomics, resourceUrl);
+ const baseTo = payToOverride?.base || env.X402_PAY_TO_BASE;
+ const solTo = payToOverride?.solana || env.X402_PAY_TO_SOLANA;
+ const bscTo = payToOverride?.bsc || env.X402_PAY_TO_BSC;
+ if (net === NETWORK_BASE_MAINNET && !baseTo) continue;
+ if (net === NETWORK_SOLANA_MAINNET && !solTo) continue;
+ if (net === NETWORK_BSC_MAINNET && !bscTo) continue;
+ const accept = buildAccept(net, priceAtomics, resourceUrl, payToOverride);
out.push(accept);
// For EVM `exact` networks, advertise a Permit2 sibling so @x402/* SDK
// clients can pick the gasless Permit2-via-EIP-2612 path. The EIP-3009
@@ -175,6 +211,45 @@ export function paidEndpoint(spec) {
// submissions, fact-check writes, on-chain mints). `ttlSeconds`
// overrides the env default (X402_IDEMPOTENCY_TTL_SECONDS).
paymentIdentifier = {},
+ // Optional per-route payout overrides — { base?, solana?, bsc? }. When
+ // set, replaces env.X402_PAY_TO_* on a network-by-network basis.
+ // Missing keys fall back to env so a single override doesn't disable
+ // the other networks.
+ payTo,
+ // Optional SIWX (Sign-In-With-X, CAIP-122) opt-in. See file header.
+ siwx,
+ // Optional per-request resource URL. Default = route path. For routes
+ // that serve multiple distinct goods through query params (e.g.
+ // /api/x402/asset-download?slug=…), pass (req) => string to make each
+ // good its own SIWX grant key. The 402 challenge AND the SIWX message
+ // both use this URL, so the client signs against the same string we
+ // look up in siwx_payments.
+ resourceUrlBuilder,
+ // USE-21: `auth-hints` extension. Declares OAuth2 and/or SIWX as
+ // alternatives to paying for this endpoint. When set, the 402 body
+ // surfaces an `auth-hints` extension AND one zero-amount accepts[]
+ // entry per declared method, mapping authRequirements → acceptIndexes.
+ // A valid `Authorization: Bearer …` or `SIGN-IN-WITH-X: …` header
+ // short-circuits the payment dance with no facilitator settle and no
+ // X-PAYMENT-RESPONSE — the handler runs with `auth = { method, ... }`
+ // in place of `requirement`/`payer`.
+ //
+ // Shape:
+ // authHints: {
+ // oauth2: { requiredScope, tokenType?, authorizationServer?,
+ // tokenEndpoint?, registrationEndpoint? } | true,
+ // siwx: true,
+ // }
+ // Passing `true` for either method opts in with sensible defaults.
+ authHints,
+ // USE-17: Offer & Receipt extension. Defaults to `{}` which enables the
+ // extension when OFFER_RECEIPT_SIGNING_PRIVATE_KEY (eip712) or
+ // OFFER_RECEIPT_JWK (jws) is configured. Set `offerReceipt: false` to
+ // opt out, or `offerReceipt: { includeTxHash: true }` on routes that
+ // feed reputation systems where on-chain verifiability is more
+ // important than payer privacy. `offerValiditySeconds` overrides the
+ // 300-second default for how long signed offers stay valid.
+ offerReceipt = {},
} = spec;
if (!route) throw new Error('paidEndpoint: route is required');
@@ -184,6 +259,9 @@ export function paidEndpoint(spec) {
if (accessControl != null && typeof accessControl !== 'function') {
throw new Error('paidEndpoint: accessControl must be a function when provided');
}
+ if (siwx && typeof siwx.statement !== 'string') {
+ throw new Error('paidEndpoint: siwx.statement is required when siwx is set');
+ }
const routeConfig = { path: route, method: method.toUpperCase(), requiredScope };
const allowMethods = `${method.toUpperCase()},OPTIONS`;
@@ -198,10 +276,18 @@ export function paidEndpoint(spec) {
return error(res, 405, 'method_not_allowed', `use ${method.toUpperCase()}`);
}
- const resourceUrl = resolveResourceUrl(req, route);
+ const resourceUrl =
+ typeof resourceUrlBuilder === 'function'
+ ? resourceUrlBuilder(req)
+ : resolveResourceUrl(req, route);
let requirements;
try {
- requirements = buildRequirements({ priceAtomics, networks, resourceUrl });
+ requirements = buildRequirements({
+ priceAtomics,
+ networks,
+ resourceUrl,
+ payToOverride: payTo,
+ });
} catch (err) {
return error(
res,
@@ -211,6 +297,50 @@ export function paidEndpoint(spec) {
);
}
+ // USE-21 auth-hints: append zero-amount accept entries for each declared
+ // auth method and build the auth-hints extension. The free entries
+ // reuse the Base USDC asset block so schema-checking clients accept
+ // them; amount="0" is the actual paywall bypass — these entries can
+ // only be "settled" by presenting the matching auth header, never via
+ // X-PAYMENT. The auth-hints extension maps each method to the index
+ // of its free entry so the buyer client knows which entry corresponds
+ // to which auth method.
+ let authHintsExtension = null;
+ if (authHints) {
+ const baseTo = payTo?.base || env.X402_PAY_TO_BASE;
+ if (baseTo) {
+ const declarations = {};
+ if (authHints.oauth2) {
+ const oauthCfg = authHints.oauth2 === true ? {} : authHints.oauth2;
+ const idx = requirements.length;
+ requirements.push(
+ freeEvmAcceptForAuth({
+ network: NETWORK_BASE_MAINNET,
+ asset: env.X402_ASSET_ADDRESS_BASE,
+ payTo: baseTo,
+ authType: 'oauth2',
+ }),
+ );
+ declarations.oauth2 = { ...oauthCfg, acceptIndexes: [idx] };
+ }
+ if (authHints.siwx) {
+ const idx = requirements.length;
+ requirements.push(
+ freeEvmAcceptForAuth({
+ network: NETWORK_BASE_MAINNET,
+ asset: env.X402_ASSET_ADDRESS_BASE,
+ payTo: baseTo,
+ authType: 'sign-in-with-x',
+ }),
+ );
+ declarations.siwx = { acceptIndexes: [idx] };
+ }
+ if (declarations.oauth2 || declarations.siwx) {
+ authHintsExtension = declareAuthHintsExtension(declarations);
+ }
+ }
+ }
+
// Build the builder-code extension once per challenge so the same block
// is advertised in the 402 body AND passed to verifyPayment for echo
// validation. If a route declares services, override the auto-declared
@@ -223,10 +353,37 @@ export function paidEndpoint(spec) {
? declareBuilderCodeExtension({ a: appCode })
: null;
+ // SIWX extension advertised on every 402 when the endpoint opts in.
+ // `requirements[].network` lists every CAIP-2 chain we'll accept a
+ // signature for — the upstream helper turns it into supportedChains.
+ const siwxExtensions = siwx
+ ? declareSiwxExtensionFor({
+ networks: requirements.map((r) => r.network),
+ statement: siwx.statement,
+ expirationSeconds: siwx.expirationSeconds,
+ })
+ : null;
+
const extraExtensions = {
[PAYMENT_IDENTIFIER]: pidExtension,
...(builderCode ? { [BUILDER_CODE]: builderCode } : {}),
+ ...(siwxExtensions || {}),
+ ...(authHintsExtension || {}),
};
+
+ // USE-17: sign one offer per accepts[] entry (when issuer is
+ // configured AND the route hasn't opted out). Failing here returns
+ // null — we never want a missing signing key to break the 402 dance,
+ // since the protocol stays valid without the extension.
+ if (offerReceipt !== false) {
+ const offersFragment = await buildOffersExtension(
+ resourceUrl,
+ requirements,
+ offerReceipt || {},
+ );
+ if (offersFragment) Object.assign(extraExtensions, offersFragment);
+ }
+
const challenge = {
resourceUrl,
accepts: requirements,
@@ -236,6 +393,81 @@ export function paidEndpoint(spec) {
extensions: extraExtensions,
};
+ // USE-21: auth-hints fast path. If the endpoint declared OAuth/SIWX as
+ // payment alternatives and the request carries a valid Authorization
+ // Bearer or SIGN-IN-WITH-X header, bypass the payment dance entirely.
+ // Runs BEFORE the generic access-control hook so the auth-hints
+ // principal is what reaches the handler. The SIWX path here does NOT
+ // require a prior on-chain payment (unlike the USE-16 returning-buyer
+ // SIWX flow further down).
+ if (authHintsExtension) {
+ const result = await authenticateAuthHintsRequest(req, {
+ audience: env.MCP_RESOURCE,
+ requiredScope: authHints?.oauth2?.requiredScope || requiredScope || null,
+ resourceUrl,
+ }).catch((err) => ({ ok: false, reason: 'auth_hints_failure', detail: err.message }));
+ if (result && !result.ok) {
+ return error(
+ res,
+ result.reason === 'insufficient_scope' ? 403 : 401,
+ result.reason || 'auth_failed',
+ result.detail || 'auth-hints verification failed',
+ );
+ }
+ if (result?.ok) {
+ let bypassResult;
+ try {
+ bypassResult = await handler({
+ req,
+ res,
+ bypass: {
+ reason: `auth-hints:${result.principal.method}`,
+ callerId: result.principal.userId
+ ? `oauth:${result.principal.userId}`
+ : `siwx:${result.principal.address}`,
+ subscription: null,
+ oauth:
+ result.principal.method === 'oauth2'
+ ? {
+ userId: result.principal.userId,
+ scope: result.principal.scope,
+ clientId: result.principal.clientId,
+ }
+ : null,
+ siwx:
+ result.principal.method === 'sign-in-with-x'
+ ? {
+ address: result.principal.address,
+ network: result.principal.network,
+ }
+ : null,
+ },
+ auth: result.principal,
+ requirement: null,
+ payer: null,
+ });
+ } catch (err) {
+ if (err instanceof X402Error && err.status === 402) {
+ return send402(res, { ...challenge, error: err.message });
+ }
+ return error(
+ res,
+ err.status || 500,
+ err.code || 'internal_error',
+ err.message,
+ );
+ }
+ if (res.writableEnded) return;
+ res.setHeader('x-payment-bypass', `auth-hints:${result.principal.method}`);
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('content-type', `${mimeType}; charset=utf-8`);
+ res.end(
+ typeof bypassResult === 'string' ? bypassResult : JSON.stringify(bypassResult),
+ );
+ return;
+ }
+ }
+
// Access-control hook (USE-23). Runs before the 402 so internal /
// subscription / OAuth callers can bypass payment entirely. Headers
// from `acResult.headers` are applied in both grant + abort paths.
@@ -303,6 +535,53 @@ export function paidEndpoint(spec) {
}
const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];
+
+ // SIWX short-circuit. A returning wallet sends `SIGN-IN-WITH-X: <base64>`
+ // instead of paying; we verify the CAIP-122 signature and skip the
+ // facilitator round-trip entirely. Only runs when the endpoint opted
+ // in and no X-PAYMENT was sent — paid requests still take precedence.
+ if (siwx && !paymentHeader) {
+ const auth = await authenticateSiwx({ req, resourceUrl });
+ if (auth?.ok) {
+ let result;
+ try {
+ result = await handler({
+ req,
+ res,
+ requirement: null,
+ payer: auth.address,
+ siwx: { address: auth.address, network: auth.network },
+ });
+ } catch (err) {
+ if (err instanceof X402Error && err.status === 402) {
+ return send402(res, { ...challenge, error: err.message });
+ }
+ return error(
+ res,
+ err.status || 500,
+ err.code || 'internal_error',
+ err.message,
+ );
+ }
+ if (res.writableEnded) return;
+ res.setHeader('x-siwx-address', auth.address);
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('content-type', `${mimeType}; charset=utf-8`);
+ res.end(typeof result === 'string' ? result : JSON.stringify(result));
+ return;
+ }
+ if (auth && !auth.ok) {
+ // 402 from siwx means "valid signature, no grant" → re-issue the
+ // challenge so the client can fall back to paying. Anything else
+ // (parse / signature failure) is a hard client error.
+ if (auth.status === 402) {
+ return send402(res, { ...challenge, error: auth.error });
+ }
+ return error(res, auth.status, auth.code, auth.error);
+ }
+ // auth === null → no SIGN-IN-WITH-X header → fall through to 402.
+ }
+
if (!paymentHeader) return send402(res, challenge);
// USE-15: required-mode rejects the call before we burn an RPC round-trip.
@@ -377,7 +656,46 @@ export function paidEndpoint(spec) {
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
- const paymentResponseHeader = encodePaymentResponseHeader(settled);
+ // Record the SIWX grant so the wallet can re-access via signature next
+ // time. siwx-storage.recordPayment is idempotent (upsert on PK), so a
+ // retried settle is safe. The on-chain payment is final; if Neon
+ // hiccups we surface 502 — the buyer can retry without paying twice.
+ if (siwx && verified.payer) {
+ try {
+ await recordSiwxPayment({
+ resourceUrl,
+ payer: normalizeAddress(verified.requirement.network, verified.payer),
+ network: verified.requirement.network,
+ ttlSeconds: siwx.ttlSeconds ?? null,
+ });
+ } catch (err) {
+ return error(res, 502, 'siwx_record_failed', err.message);
+ }
+ }
+
+ // USE-17: issue a signed receipt for the settled payment and stash it
+ // in the response extensions envelope. Persist asynchronously so the
+ // /api/x402/my-receipts buyer-lookup path can serve it later — the
+ // recordReceipt write is fire-and-forget so a Neon hiccup never
+ // surfaces as a 5xx on a payment that already settled on-chain.
+ let responseExtensions;
+ if (offerReceipt !== false) {
+ const receiptBuilt = await buildReceiptExtension(
+ resourceUrl,
+ settled,
+ offerReceipt || {},
+ );
+ if (receiptBuilt) {
+ responseExtensions = receiptBuilt.extensionFragment;
+ recordReceipt({
+ resourceUrl,
+ signedReceipt: receiptBuilt.signedReceipt,
+ settled,
+ });
+ }
+ }
+
+ const paymentResponseHeader = encodePaymentResponseHeader(settled, responseExtensions);
const contentType = `${mimeType}; charset=utf-8`;
const body = typeof result === 'string' ? result : JSON.stringify(result);
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index e5e038ffd..22109d803 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -503,14 +503,24 @@ function selectRequirement(paymentPayload, allRequirements) {
// resource server enforces the echo invariant the spec normally puts on the
// facilitator — important because not every facilitator implements it yet,
// and the on-chain calldata suffix needs trustworthy `a` to be useful.
+//
+// When the caller doesn't pass `builderCode`, we derive it from
+// X402_BUILDER_CODE_APP so the raw-verifyPayment routes (model-check,
+// mint-to-mesh, revenue-vision, mcp/auth) get echo enforcement symmetric
+// with build402Body's auto-declaration. Pass `builderCode: null`
+// explicitly to opt out (e.g. test harnesses).
export async function verifyPayment({ paymentHeader, requirements, builderCode }) {
const all = Array.isArray(requirements) ? requirements : [requirements];
const paymentPayload = decodePaymentHeader(paymentHeader);
const requirement = selectRequirement(paymentPayload, all);
- if (builderCode) {
+ const effectiveBuilderCode =
+ builderCode === undefined && env.X402_BUILDER_CODE_APP
+ ? declareBuilderCodeExtension({ a: env.X402_BUILDER_CODE_APP })
+ : builderCode;
+ if (effectiveBuilderCode) {
const payloadBuilder = paymentPayload?.extensions?.[BUILDER_CODE];
const echo = verifyBuilderCodeEcho({
- required: builderCode,
+ required: effectiveBuilderCode,
payload: payloadBuilder,
});
if (!echo.ok) {
@@ -572,13 +582,20 @@ export async function settlePayment({ paymentPayload, requirement, directVerifie
return result;
}
-export function encodePaymentResponseHeader(settleResult) {
+// `extensions` is the extension envelope returned with the success body
+// (e.g. `{ "offer-receipt": { info: { receipt: ... }, schema: ... } }` per the
+// Offer & Receipt extension §5.1). Callers leave it undefined when no
+// extensions are configured for the route.
+export function encodePaymentResponseHeader(settleResult, extensions) {
const body = {
success: true,
transaction: settleResult.transaction,
network: settleResult.network,
payer: settleResult.payer,
};
+ if (extensions && Object.keys(extensions).length > 0) {
+ body.extensions = extensions;
+ }
return Buffer.from(JSON.stringify(body), 'utf8').toString('base64');
}
diff --git a/api/_lib/x402-spending-ledger.js b/api/_lib/x402-spending-ledger.js
new file mode 100644
index 000000000..59888db9b
--- /dev/null
+++ b/api/_lib/x402-spending-ledger.js
@@ -0,0 +1,194 @@
+// Durable spending ledger for x402 buyer clients (USE-22).
+//
+// Records every payment attempt + outcome so onBeforePaymentCreation hooks
+// can enforce sliding-window caps (per-call / per-hour / per-day). The
+// strict-cap path uses Redis INCRBY-on-insert with a rollback hook: the
+// cap check increments first, the after-payment hook commits, and any
+// abort/error path decrements back. This closes the race where two
+// concurrent calls would both pass a relaxed read-before-write check.
+//
+// Cross-network: amounts are stored in micro-USD (6 decimals) regardless
+// of source token. The cap module normalizes via x402-spending-price.js
+// before recording so $0.001 USDC and $0.001 worth of SOL aggregate cleanly.
+//
+// Storage shape (Redis):
+// x402:spend:hr:<address>:<UTC_HOUR> → integer microUSD (TTL 7200s)
+// x402:spend:day:<address>:<UTC_DAY> → integer microUSD (TTL 172800s)
+// Falls back to an in-process Map when UPSTASH_REDIS_REST_* is unset so
+// local dev / tests work, with the documented caveat that caps are then
+// per-instance and not enforced across Vercel function replicas.
+
+import { Redis } from '@upstash/redis';
+import { env } from './env.js';
+
+const KEY_PREFIX = 'x402:spend:';
+const HOUR_TTL_SECONDS = 7200; // keep one extra hour for slow-cron debugging
+const DAY_TTL_SECONDS = 60 * 60 * 48;
+
+let redisClient = null;
+function getRedis() {
+ if (redisClient !== null) return redisClient;
+ if (!env.UPSTASH_REDIS_REST_URL || !env.UPSTASH_REDIS_REST_TOKEN) {
+ redisClient = false; // sentinel: configured-as-absent
+ return null;
+ }
+ redisClient = new Redis({
+ url: env.UPSTASH_REDIS_REST_URL,
+ token: env.UPSTASH_REDIS_REST_TOKEN,
+ });
+ return redisClient;
+}
+
+// In-memory fallback. Each slot holds { count, expiresAt }.
+const memoryStore = new Map();
+
+function now() {
+ return Date.now();
+}
+
+function utcHourBucket(timestampMs = now()) {
+ return Math.floor(timestampMs / 3_600_000);
+}
+
+function utcDayBucket(timestampMs = now()) {
+ return Math.floor(timestampMs / 86_400_000);
+}
+
+function hourKey(address, bucket) {
+ return `${KEY_PREFIX}hr:${address}:${bucket}`;
+}
+
+function dayKey(address, bucket) {
+ return `${KEY_PREFIX}day:${address}:${bucket}`;
+}
+
+function memoryIncr(key, delta, ttlSec) {
+ const slot = memoryStore.get(key);
+ const current = slot && (!slot.expiresAt || slot.expiresAt > now()) ? slot.value : 0n;
+ const next = current + BigInt(delta);
+ memoryStore.set(key, {
+ value: next < 0n ? 0n : next,
+ expiresAt: ttlSec > 0 ? now() + ttlSec * 1000 : 0,
+ });
+ return next < 0n ? 0n : next;
+}
+
+function memoryGet(key) {
+ const slot = memoryStore.get(key);
+ if (!slot) return 0n;
+ if (slot.expiresAt && slot.expiresAt < now()) {
+ memoryStore.delete(key);
+ return 0n;
+ }
+ return slot.value;
+}
+
+async function redisIncrby(redis, key, delta, ttlSec) {
+ // INCRBY returns the new value. EXPIRE refreshes the TTL — fine to call
+ // on every increment, the key just gets a sliding TTL window.
+ const next = await redis.incrby(key, Number(delta));
+ if (ttlSec > 0) {
+ // EXPIRE w/ NX would be slightly cheaper but Upstash supports plain
+ // EXPIRE returning 1/0; this works for both first-create and refresh.
+ await redis.expire(key, ttlSec);
+ }
+ return BigInt(next);
+}
+
+// Increment hour + day buckets for `address` by `microUsd` (BigInt-safe number
+// or BigInt). Returns the post-increment running totals { hour, day }.
+//
+// Use this for pessimistic admission: increment first, check the cap returns
+// false, then call rollback() if the payment is rejected upstream. The cost
+// is exactly one round-trip in the success path.
+export async function reserve({ address, microUsd, timestamp = now() }) {
+ if (!address || typeof address !== 'string') {
+ throw new Error('spending-ledger.reserve: address required');
+ }
+ const delta = BigInt(microUsd);
+ if (delta <= 0n) {
+ // No-op increments would corrupt the bucket; treat <=0 as a peek.
+ return current({ address, timestamp });
+ }
+ const hBucket = utcHourBucket(timestamp);
+ const dBucket = utcDayBucket(timestamp);
+ const hKey = hourKey(address, hBucket);
+ const dKey = dayKey(address, dBucket);
+ const redis = getRedis();
+ if (!redis) {
+ return {
+ hour: memoryIncr(hKey, delta, HOUR_TTL_SECONDS),
+ day: memoryIncr(dKey, delta, DAY_TTL_SECONDS),
+ };
+ }
+ const [hour, day] = await Promise.all([
+ redisIncrby(redis, hKey, delta, HOUR_TTL_SECONDS),
+ redisIncrby(redis, dKey, delta, DAY_TTL_SECONDS),
+ ]);
+ return { hour, day };
+}
+
+// Inverse of reserve(). Decrements the same buckets by the same amount.
+// Used by the cap hook when admission passed but the payment subsequently
+// failed (signing rejected, facilitator returned 402, network error, etc.)
+// so the budget doesn't drain on aborted attempts.
+//
+// Idempotency: callers should track a `reserved` flag and only roll back
+// once. We don't dedupe here — that's a property of the caller, not the
+// store, because the same physical reservation can be rolled back by
+// different code paths (catch block vs. retry policy).
+export async function rollback({ address, microUsd, timestamp = now() }) {
+ if (!address || !microUsd) return;
+ const delta = BigInt(microUsd);
+ const hKey = hourKey(address, utcHourBucket(timestamp));
+ const dKey = dayKey(address, utcDayBucket(timestamp));
+ const redis = getRedis();
+ if (!redis) {
+ memoryIncr(hKey, -delta, HOUR_TTL_SECONDS);
+ memoryIncr(dKey, -delta, DAY_TTL_SECONDS);
+ return;
+ }
+ await Promise.all([
+ redis.incrby(hKey, -Number(delta)),
+ redis.incrby(dKey, -Number(delta)),
+ ]);
+}
+
+// Snapshot of the current hour + day spend without modifying. Used by
+// dashboards and the relaxed (non-strict) cap path that's willing to
+// race for a higher-throughput win.
+export async function current({ address, timestamp = now() }) {
+ if (!address) return { hour: 0n, day: 0n };
+ const hKey = hourKey(address, utcHourBucket(timestamp));
+ const dKey = dayKey(address, utcDayBucket(timestamp));
+ const redis = getRedis();
+ if (!redis) {
+ return { hour: memoryGet(hKey), day: memoryGet(dKey) };
+ }
+ const [h, d] = await Promise.all([redis.get(hKey), redis.get(dKey)]);
+ const toBig = (v) => (v == null ? 0n : BigInt(String(v)));
+ return { hour: toBig(h), day: toBig(d) };
+}
+
+// Called by the onAfterPaymentCreation hook once the buyer has signed and
+// the wire is on its way. The reservation already accounted for the spend
+// — record() is a no-op on the totals and is primarily here so callers can
+// also persist a richer audit log if they want one. We keep the public
+// surface simple: pass through to ensure idempotent semantics; callers
+// that store a separate per-payment audit table do that themselves.
+export async function record(_event) {
+ // Intentionally empty: reserve() did the accounting. This is the
+ // API surface the cap module's lifecycle docs reference, so callers
+ // have a single mental model (reserve → commit-or-rollback).
+}
+
+export const _internal = {
+ utcHourBucket,
+ utcDayBucket,
+ hourKey,
+ dayKey,
+ resetMemoryStore() {
+ memoryStore.clear();
+ redisClient = null;
+ },
+};
diff --git a/api/_lib/x402-spending-price.js b/api/_lib/x402-spending-price.js
new file mode 100644
index 000000000..0a2e9094b
--- /dev/null
+++ b/api/_lib/x402-spending-price.js
@@ -0,0 +1,125 @@
+// Cross-network amount normalization for x402 spending caps (USE-22).
+//
+// Caps are enforced in micro-USD (6 decimals) so $0.10 cap === 100_000.
+// Most x402 transfers today are USDC, which is already pegged 1:1 to USD
+// and whose `amount` is already in micro-USD (6 decimals). For tokens
+// pegged differently (e.g. USDT-on-BSC is still ~1:1 USD; SOL would not
+// be), this module exposes a lightweight price oracle that pulls from
+// Coinbase's spot API. Results are cached for 5 minutes so we don't
+// hammer the API in tight loops.
+//
+// We deliberately avoid `import { fetch }` — Node 18+ + browsers ship
+// global fetch, and this module needs to run unchanged in both.
+
+const PRICE_TTL_MS = 5 * 60 * 1000;
+const PRICE_API = 'https://api.coinbase.com/v2/prices';
+
+// Tokens known to be 1:1 USD pegged. The asset address on the requirement
+// + the symbol from `extra.name` are matched against these.
+const USD_STABLECOINS = new Set([
+ 'usdc',
+ 'usd coin',
+ 'usdt',
+ 'tether',
+ 'binance-peg usd coin',
+ 'usdcw', // wormhole variants
+ 'dai',
+]);
+
+// Decimals defaults — when accept.extra.decimals isn't present.
+const DEFAULT_TOKEN_DECIMALS = 6;
+
+const priceCache = new Map();
+
+function isStablecoin(name) {
+ if (!name) return false;
+ return USD_STABLECOINS.has(String(name).trim().toLowerCase());
+}
+
+// Pull a fresh spot price (in USD) for a symbol like 'SOL' or 'ETH'. Uses
+// Coinbase's public spot endpoint — no API key, ~30 req/sec rate limit.
+// Cached for PRICE_TTL_MS.
+async function fetchSpotUsd(symbol) {
+ const key = symbol.toUpperCase();
+ const cached = priceCache.get(key);
+ if (cached && cached.expiresAt > Date.now()) return cached.value;
+ let res;
+ try {
+ res = await fetch(`${PRICE_API}/${key}-USD/spot`, {
+ signal: AbortSignal.timeout(5_000),
+ });
+ } catch (err) {
+ throw new Error(`spending-price: spot fetch for ${key}-USD failed: ${err.message}`);
+ }
+ if (!res.ok) {
+ throw new Error(`spending-price: ${key}-USD returned ${res.status}`);
+ }
+ const json = await res.json();
+ const raw = json?.data?.amount;
+ const value = Number(raw);
+ if (!Number.isFinite(value) || value <= 0) {
+ throw new Error(`spending-price: ${key}-USD invalid response: ${raw}`);
+ }
+ priceCache.set(key, { value, expiresAt: Date.now() + PRICE_TTL_MS });
+ return value;
+}
+
+// Resolve `(amountAtomics, requirement)` → BigInt micro-USD. For stablecoins
+// the amount is already in micro-USD (USDC, USDT, DAI all have 6 decimals);
+// we just rescale to 6 if the token uses different decimals. For non-pegged
+// tokens we multiply by the spot price.
+//
+// The function NEVER throws on a missing price for a stablecoin path —
+// that's the dominant flow. It only reaches out to Coinbase when the
+// requirement explicitly declares a non-pegged token.
+export async function toMicroUsd(amount, requirement) {
+ const atomic = BigInt(amount);
+ const decimals = Number(requirement?.extra?.decimals ?? DEFAULT_TOKEN_DECIMALS);
+ const name = requirement?.extra?.name || '';
+ if (isStablecoin(name)) {
+ return rescaleAtomics(atomic, decimals, 6);
+ }
+ // Non-stable: rescale to whole-token units then multiply by USD spot.
+ // Use a 1e9 fixed-point intermediate to preserve precision when
+ // the spot price has decimals (e.g. SOL at $147.83).
+ const symbol = inferSymbol(requirement);
+ const spot = await fetchSpotUsd(symbol);
+ const spotMicro = BigInt(Math.round(spot * 1_000_000));
+ const denom = 10n ** BigInt(decimals);
+ return (atomic * spotMicro) / denom;
+}
+
+function rescaleAtomics(atomic, fromDec, toDec) {
+ if (fromDec === toDec) return atomic;
+ if (fromDec > toDec) return atomic / 10n ** BigInt(fromDec - toDec);
+ return atomic * 10n ** BigInt(toDec - fromDec);
+}
+
+// Best-effort symbol inference from the requirement when callers don't
+// hand us one. Looks at `extra.name` first, then the network namespace.
+function inferSymbol(requirement) {
+ const name = requirement?.extra?.symbol || requirement?.extra?.name || '';
+ if (name) {
+ const up = String(name).toUpperCase();
+ const match = up.match(/\b(SOL|ETH|BTC|MATIC|POL|BNB)\b/);
+ if (match) return match[1];
+ }
+ if (typeof requirement?.network === 'string') {
+ if (requirement.network.startsWith('solana:')) return 'SOL';
+ if (requirement.network.startsWith('eip155:1')) return 'ETH';
+ if (requirement.network.startsWith('eip155:56')) return 'BNB';
+ if (requirement.network.startsWith('eip155:137')) return 'POL';
+ }
+ throw new Error(
+ `spending-price: cannot infer symbol for ${JSON.stringify(requirement?.extra || {})}`,
+ );
+}
+
+export const _internal = {
+ isStablecoin,
+ rescaleAtomics,
+ inferSymbol,
+ resetCache() {
+ priceCache.clear();
+ },
+};
diff --git a/api/_lib/x402/a2a-client.js b/api/_lib/x402/a2a-client.js
new file mode 100644
index 000000000..f652c81d1
--- /dev/null
+++ b/api/_lib/x402/a2a-client.js
@@ -0,0 +1,332 @@
+// A2A (Agent-to-Agent) x402 transport — client side.
+//
+// Drives the two-leg handshake from the caller's perspective:
+// 1. POST `{ method: "message/send", params: { message: { … } } }` to the
+// peer's A2A endpoint with the X-A2A-Extensions header. The peer replies
+// with a task in state `input-required` carrying `x402.payment.required`.
+// 2. Build a `PaymentPayload` (EIP-3009 transferWithAuthorization for EVM
+// `exact` scheme), POST it back with the same `taskId` and
+// `x402.payment.status: payment-submitted`. The peer verifies, runs the
+// handler, settles, and replies with state `completed` +
+// `x402.payment.receipts`.
+//
+// Sign function:
+// The client takes a pluggable `signer` so callers can wire in a viem
+// wallet, a hardware wallet, or a custodial signer. We provide
+// `createPrivateKeySigner(privateKey)` as a default that uses viem's
+// accounts API for Base / EVM `exact` scheme.
+
+import { randomBytes, randomUUID } from 'node:crypto';
+
+import {
+ A2A_EXTENSIONS_HEADER,
+ A2A_X402_EXTENSION_URI,
+} from './a2a-server.js';
+
+export { A2A_EXTENSIONS_HEADER, A2A_X402_EXTENSION_URI };
+
+// ── Errors ────────────────────────────────────────────────────────────────
+
+export class A2AClientError extends Error {
+ constructor(code, message, details) {
+ super(message);
+ this.code = code;
+ this.details = details;
+ }
+}
+
+// ── Signers ───────────────────────────────────────────────────────────────
+
+// EIP-3009 transferWithAuthorization signer powered by viem. Returns an
+// object `{ address, network, signAuthorization }` consumable by
+// payA2A() / buildEvmExactPayload().
+export async function createPrivateKeySigner(privateKey) {
+ if (!privateKey || typeof privateKey !== 'string') {
+ throw new A2AClientError(
+ 'invalid_signer',
+ 'createPrivateKeySigner: privateKey hex string required',
+ );
+ }
+ const { privateKeyToAccount } = await import('viem/accounts');
+ const account = privateKeyToAccount(privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`);
+ return {
+ address: account.address,
+ signAuthorization: async ({ domain, message }) => {
+ const types = {
+ TransferWithAuthorization: [
+ { name: 'from', type: 'address' },
+ { name: 'to', type: 'address' },
+ { name: 'value', type: 'uint256' },
+ { name: 'validAfter', type: 'uint256' },
+ { name: 'validBefore', type: 'uint256' },
+ { name: 'nonce', type: 'bytes32' },
+ ],
+ };
+ return account.signTypedData({
+ domain,
+ types,
+ primaryType: 'TransferWithAuthorization',
+ message,
+ });
+ },
+ };
+}
+
+// ── Payload builders ──────────────────────────────────────────────────────
+
+function randomHex32() {
+ return `0x${randomBytes(32).toString('hex')}`;
+}
+
+const CHAIN_ID_BY_NETWORK = {
+ 'eip155:8453': 8453, // Base mainnet
+ 'eip155:84532': 84532, // Base sepolia
+ 'eip155:1': 1, // Ethereum mainnet
+ 'eip155:137': 137, // Polygon
+ 'eip155:42161': 42161, // Arbitrum
+};
+
+function chainIdFor(network) {
+ if (CHAIN_ID_BY_NETWORK[network]) return CHAIN_ID_BY_NETWORK[network];
+ const m = /^eip155:(\d+)$/.exec(network);
+ if (m) return Number(m[1]);
+ throw new A2AClientError('unsupported_network', `a2a-client: cannot derive chainId from ${network}`);
+}
+
+// Build an EIP-3009 `exact` PaymentPayload for an EVM `accepts` entry.
+export async function buildEvmExactPayload({ accept, signer, resource }) {
+ if (accept.scheme !== 'exact') {
+ throw new A2AClientError(
+ 'unsupported_scheme',
+ `a2a-client: only exact scheme supported here, got ${accept.scheme}`,
+ );
+ }
+ const chainId = chainIdFor(accept.network);
+ const validAfter = 0;
+ const validBefore = Math.floor(Date.now() / 1000) + (accept.maxTimeoutSeconds || 600);
+ const nonce = randomHex32();
+ const domain = {
+ name: accept.extra?.name || 'USD Coin',
+ version: accept.extra?.version || '2',
+ chainId,
+ verifyingContract: accept.asset,
+ };
+ const message = {
+ from: signer.address,
+ to: accept.payTo,
+ value: accept.amount,
+ validAfter,
+ validBefore,
+ nonce,
+ };
+ const signature = await signer.signAuthorization({ domain, message });
+ return {
+ x402Version: 2,
+ scheme: 'exact',
+ network: accept.network,
+ resource,
+ accepted: accept,
+ payload: {
+ signature,
+ authorization: {
+ from: signer.address,
+ to: accept.payTo,
+ value: accept.amount,
+ validAfter: String(validAfter),
+ validBefore: String(validBefore),
+ nonce,
+ },
+ },
+ };
+}
+
+// ── A2A protocol helpers ──────────────────────────────────────────────────
+
+function buildJsonRpcRequest({ id, message }) {
+ return {
+ jsonrpc: '2.0',
+ id: id || randomUUID(),
+ method: 'message/send',
+ params: { message },
+ };
+}
+
+async function postJsonRpc(endpoint, body, extraHeaders) {
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ accept: 'application/json',
+ [A2A_EXTENSIONS_HEADER]: A2A_X402_EXTENSION_URI,
+ ...(extraHeaders || {}),
+ },
+ body: JSON.stringify(body),
+ });
+ const text = await res.text();
+ let parsed;
+ try {
+ parsed = text ? JSON.parse(text) : {};
+ } catch (err) {
+ throw new A2AClientError('parse_error', `non-JSON A2A reply: ${err.message}`, { text });
+ }
+ if (!res.ok) {
+ throw new A2AClientError(
+ 'transport_error',
+ `A2A peer returned HTTP ${res.status}`,
+ { status: res.status, body: parsed },
+ );
+ }
+ if (parsed.error) {
+ throw new A2AClientError(
+ 'jsonrpc_error',
+ parsed.error.message || 'JSON-RPC error',
+ parsed.error,
+ );
+ }
+ return parsed.result;
+}
+
+function readTaskStatus(task) {
+ if (!task || task.kind !== 'task') {
+ throw new A2AClientError('invalid_reply', 'expected `kind: "task"` in A2A reply');
+ }
+ return task.status?.state;
+}
+
+function readPaymentRequired(task) {
+ const meta = task.status?.message?.metadata;
+ if (meta?.['x402.payment.status'] !== 'payment-required') return null;
+ const required = meta['x402.payment.required'];
+ if (!required || !Array.isArray(required.accepts) || !required.accepts.length) {
+ throw new A2AClientError(
+ 'malformed_payment_required',
+ 'task carries payment-required status but no accepts list',
+ required,
+ );
+ }
+ return required;
+}
+
+function readReceipts(task) {
+ const meta = task.status?.message?.metadata;
+ if (!meta) return null;
+ return {
+ status: meta['x402.payment.status'] || null,
+ receipts: Array.isArray(meta['x402.payment.receipts']) ? meta['x402.payment.receipts'] : [],
+ error: meta['x402.payment.error'] || null,
+ lifecycle: meta['x402.payment.lifecycle'] || null,
+ };
+}
+
+// Default network preference list. Callers can override by passing
+// `networkPreference` to `payA2A`.
+const DEFAULT_NETWORK_PREFERENCE = ['eip155:8453', 'eip155:84532', 'eip155:1'];
+
+function pickAccept(accepts, preference) {
+ const order = preference?.length ? preference : DEFAULT_NETWORK_PREFERENCE;
+ for (const net of order) {
+ const match = accepts.find((a) => a.network === net && a.scheme === 'exact');
+ if (match) return match;
+ }
+ // Fall back to the first `exact` EVM accept on a chain we recognise.
+ for (const a of accepts) {
+ if (a.scheme === 'exact' && /^eip155:\d+$/.test(a.network)) return a;
+ }
+ throw new A2AClientError(
+ 'no_supported_accept',
+ 'a2a-client: peer offered no supported (scheme=exact, EVM) accept',
+ { accepts: accepts.map(({ network, scheme }) => ({ network, scheme })) },
+ );
+}
+
+// ── Public client ─────────────────────────────────────────────────────────
+
+// Send an initial unpaid message and return the peer's payment-required task.
+export async function requestQuote({ endpoint, text = 'Initiate paid skill.', taskId }) {
+ const message = {
+ kind: 'message',
+ role: 'user',
+ messageId: randomUUID(),
+ ...(taskId ? { taskId } : {}),
+ parts: [{ kind: 'text', text }],
+ };
+ const task = await postJsonRpc(endpoint, buildJsonRpcRequest({ message }));
+ const required = readPaymentRequired(task);
+ if (!required) {
+ throw new A2AClientError(
+ 'unexpected_state',
+ `expected payment-required, got state ${readTaskStatus(task) || 'unknown'}`,
+ { task },
+ );
+ }
+ return { task, required, taskId: task.id };
+}
+
+// Submit a signed PaymentPayload for the given taskId and return the
+// completed (or failed) task.
+export async function submitPayment({
+ endpoint,
+ taskId,
+ paymentPayload,
+ text = 'Here is the payment authorization.',
+}) {
+ const message = {
+ kind: 'message',
+ role: 'user',
+ messageId: randomUUID(),
+ taskId,
+ parts: [{ kind: 'text', text }],
+ metadata: {
+ 'x402.payment.status': 'payment-submitted',
+ 'x402.payment.payload': paymentPayload,
+ },
+ };
+ const task = await postJsonRpc(endpoint, buildJsonRpcRequest({ message }));
+ const receipts = readReceipts(task);
+ const state = readTaskStatus(task);
+ return { task, state, ...receipts };
+}
+
+// End-to-end: quote → sign → submit. Returns the completed task plus parsed
+// receipt fields. Throws A2AClientError on transport / signing / settlement
+// failure.
+export async function payA2A({
+ endpoint,
+ signer,
+ text,
+ networkPreference,
+ onQuote,
+}) {
+ if (!endpoint) throw new A2AClientError('invalid_args', 'payA2A: endpoint is required');
+ if (!signer || typeof signer.signAuthorization !== 'function') {
+ throw new A2AClientError(
+ 'invalid_signer',
+ 'payA2A: signer with signAuthorization() is required (try createPrivateKeySigner)',
+ );
+ }
+
+ const { task: quoteTask, required, taskId } = await requestQuote({ endpoint, text });
+ if (typeof onQuote === 'function') {
+ try {
+ await onQuote({ task: quoteTask, required, taskId });
+ } catch (err) {
+ throw new A2AClientError('quote_rejected', err.message || 'caller rejected the quote');
+ }
+ }
+
+ const accept = pickAccept(required.accepts, networkPreference);
+ const resource = required.resource || { url: endpoint, mimeType: 'application/json' };
+ const paymentPayload = await buildEvmExactPayload({ accept, signer, resource });
+
+ const result = await submitPayment({ endpoint, taskId, paymentPayload });
+
+ if (result.state !== 'completed') {
+ throw new A2AClientError(
+ result.error || 'payment_failed',
+ result.receipts?.[0]?.errorReason ||
+ `A2A task ended in state ${result.state}`,
+ result,
+ );
+ }
+ return result;
+}
diff --git a/api/_lib/x402/a2a-server.js b/api/_lib/x402/a2a-server.js
new file mode 100644
index 000000000..b446cf69c
--- /dev/null
+++ b/api/_lib/x402/a2a-server.js
@@ -0,0 +1,657 @@
+// A2A (Agent-to-Agent) x402 transport — server side.
+//
+// USE-12: Implements the google-a2a/a2a-x402 v0.1 extension. The A2A protocol
+// uses JSON-RPC `message/send` calls with task-based state. Payment is
+// signalled via the task's `status.state` plus `x402.payment.*` metadata
+// fields on the agent reply message — distinct from the HTTP 402 + X-PAYMENT
+// dance we use for /api/x402/*.
+//
+// Wire shape (per spec):
+// • First call (no payment metadata) → reply task with
+// state = 'input-required'
+// message.metadata['x402.payment.status'] = 'payment-required'
+// message.metadata['x402.payment.required'] = PaymentRequirements
+// • Retry with `x402.payment.payload` + `x402.payment.status = payment-submitted`
+// and `taskId` set → server verifies via facilitator, runs handler, settles,
+// replies with state = 'completed' (or 'failed') and
+// message.metadata['x402.payment.status'] = 'payment-completed'
+// message.metadata['x402.payment.receipts'] = [SettlementResponse]
+//
+// Extension activation: both peers MUST attach
+// `X-A2A-Extensions: https://github.com/google-a2a/a2a-x402/v0.1`
+// on their HTTP transport. We emit it on every reply and require it on the
+// inbound side per spec (treat-as-disabled-when-absent is opt-in by the
+// AgentCard, but our card declares `required: true`).
+//
+// Verification + settlement reuse the existing facilitator client in
+// api/_lib/x402-spec.js so A2A inherits Base / Solana / BSC support, builder
+// code echo enforcement, and direct-scheme handling automatically.
+
+import { randomUUID } from 'node:crypto';
+
+import { env } from '../env.js';
+import {
+ BUILDER_CODE,
+ NETWORK_BASE_MAINNET,
+ NETWORK_BSC_MAINNET,
+ NETWORK_SOLANA_MAINNET,
+ X402Error,
+ X402_VERSION,
+ permit2VariantOf,
+ settlePayment,
+ verifyPayment,
+} from '../x402-spec.js';
+import { declareBuilderCodeExtension } from '../x402-builder-code.js';
+import { PAYMENT_EVENT_TOPIC as BSC_PAYMENT_EVENT_TOPIC } from '../x402-bsc-direct.js';
+
+export const A2A_X402_EXTENSION_URI = 'https://github.com/google-a2a/a2a-x402/v0.1';
+export const A2A_EXTENSIONS_HEADER = 'X-A2A-Extensions';
+
+const NETWORK_ALIASES = {
+ base: NETWORK_BASE_MAINNET,
+ 'base-mainnet': NETWORK_BASE_MAINNET,
+ bsc: NETWORK_BSC_MAINNET,
+ 'bsc-mainnet': NETWORK_BSC_MAINNET,
+ solana: NETWORK_SOLANA_MAINNET,
+ 'solana-mainnet': NETWORK_SOLANA_MAINNET,
+};
+
+function resolveNetwork(name) {
+ return NETWORK_ALIASES[name] || name;
+}
+
+function buildAccept(network, priceAtomics, resourceUrl, payToOverride) {
+ const common = {
+ scheme: 'exact',
+ amount: String(priceAtomics),
+ maxTimeoutSeconds: 600,
+ resource: resourceUrl,
+ };
+ if (network === NETWORK_BASE_MAINNET) {
+ return {
+ ...common,
+ network: NETWORK_BASE_MAINNET,
+ payTo: payToOverride?.base || env.X402_PAY_TO_BASE,
+ asset: env.X402_ASSET_ADDRESS_BASE,
+ extra: { name: 'USD Coin', version: '2', decimals: 6 },
+ };
+ }
+ if (network === NETWORK_SOLANA_MAINNET) {
+ return {
+ ...common,
+ network: NETWORK_SOLANA_MAINNET,
+ payTo: payToOverride?.solana || env.X402_PAY_TO_SOLANA,
+ asset: env.X402_ASSET_MINT_SOLANA,
+ extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
+ };
+ }
+ if (network === NETWORK_BSC_MAINNET) {
+ const contract = payToOverride?.bsc || env.X402_PAY_TO_BSC;
+ return {
+ ...common,
+ scheme: 'direct',
+ network: NETWORK_BSC_MAINNET,
+ payTo: contract,
+ asset: env.X402_ASSET_ADDRESS_BSC,
+ extra: {
+ name: 'Binance-Peg USD Coin',
+ decimals: 6,
+ contract,
+ method: 'pay(bytes32)',
+ eventTopic: BSC_PAYMENT_EVENT_TOPIC,
+ },
+ };
+ }
+ throw new X402Error('unsupported_network', `a2a: unsupported network ${network}`, 500);
+}
+
+function buildAccepts({ priceAtomics, networks, resourceUrl, payToOverride }) {
+ const out = [];
+ for (const name of networks) {
+ const net = resolveNetwork(name);
+ const baseTo = payToOverride?.base || env.X402_PAY_TO_BASE;
+ const solTo = payToOverride?.solana || env.X402_PAY_TO_SOLANA;
+ const bscTo = payToOverride?.bsc || env.X402_PAY_TO_BSC;
+ if (net === NETWORK_BASE_MAINNET && !baseTo) continue;
+ if (net === NETWORK_SOLANA_MAINNET && !solTo) continue;
+ if (net === NETWORK_BSC_MAINNET && !bscTo) continue;
+ const accept = buildAccept(net, priceAtomics, resourceUrl, payToOverride);
+ out.push(accept);
+ const sibling = permit2VariantOf(accept);
+ if (sibling) out.push(sibling);
+ }
+ if (!out.length) {
+ throw new X402Error(
+ 'no_payto_configured',
+ 'a2a: no X402_PAY_TO_* configured for any requested network',
+ 500,
+ );
+ }
+ return out;
+}
+
+function paymentRequiredObject({ resourceUrl, description, mimeType, accepts }) {
+ return {
+ x402Version: X402_VERSION,
+ error: 'Payment required to access this resource',
+ resource: { url: resourceUrl, description, mimeType },
+ accepts,
+ };
+}
+
+function agentMessage({ taskId, text, metadata }) {
+ return {
+ kind: 'message',
+ role: 'agent',
+ messageId: randomUUID(),
+ taskId,
+ parts: [{ kind: 'text', text }],
+ metadata,
+ };
+}
+
+function task({ id, state, message, artifacts }) {
+ const out = {
+ kind: 'task',
+ id,
+ status: { state, message },
+ };
+ if (Array.isArray(artifacts) && artifacts.length) out.artifacts = artifacts;
+ return out;
+}
+
+function jsonrpcResult(id, result) {
+ return { jsonrpc: '2.0', id, result };
+}
+
+function jsonrpcError(id, code, message, data) {
+ const err = { code, message };
+ if (data !== undefined) err.data = data;
+ return { jsonrpc: '2.0', id, error: err };
+}
+
+function readClientPaymentStatus(metadata) {
+ const status = metadata?.['x402.payment.status'];
+ return typeof status === 'string' ? status : null;
+}
+
+function readClientPaymentPayload(metadata) {
+ const payload = metadata?.['x402.payment.payload'];
+ return payload && typeof payload === 'object' ? payload : null;
+}
+
+function encodePaymentHeaderFromPayload(payload) {
+ // verifyPayment() decodes the X-PAYMENT header value back to JSON. We
+ // re-encode the A2A-supplied payload object to base64-JSON so we can reuse
+ // that path without forking the verifier. The spec's payload shape (with
+ // `accepted` instead of `paymentRequirements`) is structurally compatible
+ // with what selectRequirement() needs once we normalise the field name.
+ const normalised = { ...payload };
+ if (payload.accepted && !payload.paymentRequirements) {
+ normalised.paymentRequirements = payload.accepted;
+ }
+ if (!normalised.x402Version) normalised.x402Version = X402_VERSION;
+ return Buffer.from(JSON.stringify(normalised), 'utf8').toString('base64');
+}
+
+function clientAcceptsExtension(headers) {
+ // Per the A2A x402 spec: clients activate the extension by listing its URI
+ // in the X-A2A-Extensions header. We require it when the AgentCard
+ // declared the extension as `required: true`. Header names are
+ // case-insensitive — Node lowercases them on `req.headers`.
+ const raw = headers['x-a2a-extensions'];
+ if (!raw) return false;
+ const values = Array.isArray(raw) ? raw : String(raw).split(',');
+ for (const v of values) {
+ if (v.trim() === A2A_X402_EXTENSION_URI) return true;
+ }
+ return false;
+}
+
+function activateExtensionHeader(res) {
+ res.setHeader(A2A_EXTENSIONS_HEADER, A2A_X402_EXTENSION_URI);
+}
+
+// Build the agent's payment-required reply. Returned synchronously so callers
+// can decide whether to emit it as a JSON-RPC result, an SSE event, or wrap it
+// in an A2A `streamingResponse`.
+export function buildPaymentRequiredTask({
+ taskId = randomUUID(),
+ resourceUrl,
+ description,
+ mimeType = 'application/json',
+ priceAtomics,
+ networks = ['base', 'solana'],
+ payTo,
+ prompt = 'Payment required to invoke this skill.',
+}) {
+ const accepts = buildAccepts({
+ priceAtomics,
+ networks,
+ resourceUrl,
+ payToOverride: payTo,
+ });
+ const required = paymentRequiredObject({ resourceUrl, description, mimeType, accepts });
+ const message = agentMessage({
+ taskId,
+ text: prompt,
+ metadata: {
+ 'x402.payment.status': 'payment-required',
+ 'x402.payment.required': required,
+ },
+ });
+ return { task: task({ id: taskId, state: 'input-required', message }), accepts, required };
+}
+
+function builderCodeForServices(services) {
+ const appCode = env.X402_BUILDER_CODE_APP;
+ if (!appCode) return null;
+ if (Array.isArray(services) && services.length) {
+ return declareBuilderCodeExtension({ a: appCode, s: services });
+ }
+ return declareBuilderCodeExtension({ a: appCode });
+}
+
+// Run a single inbound `message/send` JSON-RPC call. The caller owns reading
+// the body off the wire — we want `body` parsed and the framework-agnostic
+// `req` only for `req.headers` access (extension activation check).
+//
+// `handler({ taskId, payer, requirement, payload, message })` returns either:
+// • { text, artifacts? } — wrapped in a `completed` task message + artifacts.
+// • A string — wrapped as the text reply with no artifacts.
+// • undefined / null — defaults to "Payment settled." text.
+//
+// Any thrown Error with `.status === 402` re-emits the payment-required task
+// (e.g. payment for the wrong network). Other errors become a `failed` task
+// with `x402.payment.status = payment-failed`.
+export async function handleA2ARequest({
+ req,
+ body,
+ route,
+ resourceUrl,
+ description,
+ mimeType = 'application/json',
+ priceAtomics = env.X402_MAX_AMOUNT_REQUIRED,
+ networks = ['base', 'solana'],
+ payTo,
+ services,
+ prompt,
+ handler,
+}) {
+ if (!body || typeof body !== 'object') {
+ return jsonrpcError(null, -32700, 'Parse error: body must be JSON');
+ }
+ if (body.jsonrpc !== '2.0') {
+ return jsonrpcError(body.id ?? null, -32600, 'Invalid Request: jsonrpc must be "2.0"');
+ }
+ if (body.method !== 'message/send') {
+ return jsonrpcError(body.id ?? null, -32601, `Method not found: ${body.method}`);
+ }
+
+ const reqId = body.id ?? null;
+ const message = body.params?.message;
+ if (!message || typeof message !== 'object') {
+ return jsonrpcError(reqId, -32602, 'Invalid params: message is required');
+ }
+
+ if (!clientAcceptsExtension(req.headers || {})) {
+ const failed = task({
+ id: message.taskId || randomUUID(),
+ state: 'failed',
+ message: agentMessage({
+ taskId: message.taskId,
+ text: `This agent requires the x402 extension. Send the ${A2A_EXTENSIONS_HEADER} header with ${A2A_X402_EXTENSION_URI}.`,
+ metadata: {
+ 'x402.payment.status': 'payment-rejected',
+ 'x402.payment.error': 'EXTENSION_REQUIRED',
+ },
+ }),
+ });
+ return jsonrpcResult(reqId, failed);
+ }
+
+ const status = readClientPaymentStatus(message.metadata);
+ const payload = readClientPaymentPayload(message.metadata);
+
+ // First-leg: no payment payload → return the payment-required task.
+ if (!payload || status === 'payment-required' || status === null) {
+ const built = buildPaymentRequiredTask({
+ taskId: message.taskId,
+ resourceUrl,
+ description,
+ mimeType,
+ priceAtomics,
+ networks,
+ payTo,
+ prompt,
+ });
+ return jsonrpcResult(reqId, built.task);
+ }
+
+ const taskId = message.taskId || randomUUID();
+
+ // Second-leg: client supplied a payment payload. Verify → run → settle.
+ const builderCode = builderCodeForServices(services);
+ const paymentHeader = encodePaymentHeaderFromPayload(payload);
+
+ // Reconstruct the same accepts list we advertised on the first leg so the
+ // facilitator sees the resource/network/payTo trio it expects.
+ let requirements;
+ try {
+ requirements = buildAccepts({
+ priceAtomics,
+ networks,
+ resourceUrl,
+ payToOverride: payTo,
+ });
+ } catch (err) {
+ return jsonrpcResult(
+ reqId,
+ task({
+ id: taskId,
+ state: 'failed',
+ message: agentMessage({
+ taskId,
+ text: err.message,
+ metadata: {
+ 'x402.payment.status': 'payment-failed',
+ 'x402.payment.error': err.code || 'INVALID_CONFIGURATION',
+ },
+ }),
+ }),
+ );
+ }
+
+ let verified;
+ try {
+ verified = await verifyPayment({ paymentHeader, requirements, builderCode });
+ } catch (err) {
+ // 402 from verify → re-issue payment-required (e.g. wrong network).
+ if (err instanceof X402Error && err.status === 402) {
+ const built = buildPaymentRequiredTask({
+ taskId,
+ resourceUrl,
+ description,
+ mimeType,
+ priceAtomics,
+ networks,
+ payTo,
+ prompt: err.message,
+ });
+ return jsonrpcResult(reqId, built.task);
+ }
+ const receipt = {
+ success: false,
+ errorReason: err.message,
+ network: payload?.accepted?.network || payload?.paymentRequirements?.network || '',
+ transaction: '',
+ };
+ return jsonrpcResult(
+ reqId,
+ task({
+ id: taskId,
+ state: 'failed',
+ message: agentMessage({
+ taskId,
+ text: `Payment verification failed: ${err.message}`,
+ metadata: {
+ 'x402.payment.status': 'payment-failed',
+ 'x402.payment.error': err.code || 'INVALID_PAYMENT',
+ 'x402.payment.receipts': [receipt],
+ },
+ }),
+ }),
+ );
+ }
+
+ // payment-verified milestone — the spec lists this between submitted and
+ // completed. We don't stream intermediate task updates from a single
+ // request/response pair, but we surface it on the final reply's lifecycle
+ // trail (see `lifecycle` field below) for clients that want to log it.
+
+ let handlerResult;
+ try {
+ handlerResult = await handler({
+ taskId,
+ payer: verified.payer,
+ requirement: verified.requirement,
+ payload,
+ message,
+ });
+ } catch (err) {
+ const receipt = {
+ success: false,
+ errorReason: err.message,
+ network: verified.requirement.network,
+ transaction: '',
+ };
+ return jsonrpcResult(
+ reqId,
+ task({
+ id: taskId,
+ state: 'failed',
+ message: agentMessage({
+ taskId,
+ text: `Skill execution failed: ${err.message}`,
+ metadata: {
+ 'x402.payment.status': 'payment-failed',
+ 'x402.payment.error': err.code || 'HANDLER_FAILED',
+ 'x402.payment.receipts': [receipt],
+ },
+ }),
+ }),
+ );
+ }
+
+ let settled;
+ try {
+ settled = await settlePayment({
+ paymentPayload: verified.paymentPayload,
+ requirement: verified.requirement,
+ directVerified: verified.directVerified,
+ });
+ } catch (err) {
+ const receipt = {
+ success: false,
+ errorReason: err.message,
+ network: verified.requirement.network,
+ transaction: '',
+ };
+ return jsonrpcResult(
+ reqId,
+ task({
+ id: taskId,
+ state: 'failed',
+ message: agentMessage({
+ taskId,
+ text: `Settlement failed: ${err.message}`,
+ metadata: {
+ 'x402.payment.status': 'payment-failed',
+ 'x402.payment.error': err.code || 'SETTLEMENT_FAILED',
+ 'x402.payment.receipts': [receipt],
+ },
+ }),
+ }),
+ );
+ }
+
+ const receipts = [
+ {
+ success: true,
+ transaction: settled.transaction,
+ network: settled.network,
+ payer: settled.payer || verified.payer || null,
+ },
+ ];
+
+ const text =
+ typeof handlerResult === 'string'
+ ? handlerResult
+ : handlerResult?.text || 'Payment settled. Skill executed.';
+ const artifacts =
+ Array.isArray(handlerResult?.artifacts) && handlerResult.artifacts.length
+ ? handlerResult.artifacts
+ : undefined;
+
+ const completedMessage = agentMessage({
+ taskId,
+ text,
+ metadata: {
+ 'x402.payment.status': 'payment-completed',
+ 'x402.payment.receipts': receipts,
+ 'x402.payment.lifecycle': [
+ 'payment-required',
+ 'payment-submitted',
+ 'payment-verified',
+ 'payment-completed',
+ ],
+ ...(handlerResult?.metadata && typeof handlerResult.metadata === 'object'
+ ? handlerResult.metadata
+ : {}),
+ },
+ });
+
+ return jsonrpcResult(
+ reqId,
+ task({ id: taskId, state: 'completed', message: completedMessage, artifacts }),
+ );
+}
+
+// Compose a Vercel-style HTTP handler around `handleA2ARequest`. POSTs are
+// JSON-RPC; GETs return the AgentCard fragment so clients can verify the
+// extension declaration without a separate /.well-known fetch.
+export function a2aPaidEndpoint(spec) {
+ const {
+ route,
+ description,
+ priceAtomics = env.X402_MAX_AMOUNT_REQUIRED,
+ networks = ['base', 'solana'],
+ mimeType = 'application/json',
+ payTo,
+ services,
+ prompt,
+ handler,
+ skill,
+ } = spec;
+
+ if (!route) throw new Error('a2aPaidEndpoint: route is required');
+ if (!description) throw new Error('a2aPaidEndpoint: description is required');
+ if (typeof handler !== 'function') {
+ throw new Error('a2aPaidEndpoint: handler must be a function');
+ }
+
+ return async function a2aHandler(req, res) {
+ const origin = req.headers.origin;
+ res.setHeader('access-control-allow-origin', origin || '*');
+ res.setHeader('access-control-allow-methods', 'GET,POST,OPTIONS');
+ res.setHeader(
+ 'access-control-allow-headers',
+ `content-type, authorization, ${A2A_EXTENSIONS_HEADER.toLowerCase()}`,
+ );
+ res.setHeader('access-control-expose-headers', A2A_EXTENSIONS_HEADER);
+ if (req.method === 'OPTIONS') {
+ res.statusCode = 204;
+ res.end();
+ return;
+ }
+
+ activateExtensionHeader(res);
+
+ const resourceUrl = `${env.APP_ORIGIN}${route}`;
+
+ if (req.method === 'GET') {
+ // Discovery: emit a minimal AgentCard fragment so a client can confirm
+ // our extension support before sending a paid message.
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('cache-control', 'public, max-age=300');
+ res.end(
+ JSON.stringify({
+ name: skill?.name || 'three.ws A2A paid skill',
+ description,
+ url: resourceUrl,
+ capabilities: {
+ streaming: false,
+ pushNotifications: false,
+ stateTransitionHistory: false,
+ extensions: [
+ {
+ uri: A2A_X402_EXTENSION_URI,
+ description: 'Supports payments using the x402 protocol for on-chain settlement.',
+ required: true,
+ },
+ ],
+ },
+ defaultInputModes: ['application/json'],
+ defaultOutputModes: [mimeType],
+ skills: skill ? [skill] : [],
+ }),
+ );
+ return;
+ }
+
+ if (req.method !== 'POST') {
+ res.setHeader('allow', 'GET,POST,OPTIONS');
+ res.statusCode = 405;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify({ error: 'method_not_allowed' }));
+ return;
+ }
+
+ let body;
+ try {
+ body = await readJsonBody(req);
+ } catch (err) {
+ res.statusCode = err.status || 400;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: err.message } }));
+ return;
+ }
+
+ const rpcReply = await handleA2ARequest({
+ req,
+ body,
+ route,
+ resourceUrl,
+ description,
+ mimeType,
+ priceAtomics,
+ networks,
+ payTo,
+ services,
+ prompt,
+ handler,
+ });
+
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ res.end(JSON.stringify(rpcReply));
+ };
+}
+
+function readJsonBody(req) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ let total = 0;
+ const limit = 1_000_000;
+ req.on('data', (c) => {
+ total += c.length;
+ if (total > limit) {
+ reject(Object.assign(new Error('payload too large'), { status: 413 }));
+ req.destroy();
+ return;
+ }
+ chunks.push(c);
+ });
+ req.on('end', () => {
+ if (!chunks.length) return resolve({});
+ try {
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
+ } catch (err) {
+ reject(Object.assign(new Error(`invalid JSON: ${err.message}`), { status: 400 }));
+ }
+ });
+ req.on('error', reject);
+ });
+}
diff --git a/api/_lib/x402/auth-hints.js b/api/_lib/x402/auth-hints.js
index 9aadf783b..cb2819f22 100644
--- a/api/_lib/x402/auth-hints.js
+++ b/api/_lib/x402/auth-hints.js
@@ -1,17 +1,14 @@
// x402 `auth-hints` extension — declare authentication paths a client can use
-// instead of (or in addition to) paying via x402.
+// instead of paying via x402.
//
// Spec: /tmp/x402-docs/specs/extensions/extension-auth-hints.md
//
// The extension surfaces in a 402 response under `extensions["auth-hints"]`
// and maps specific `accepts[]` entries to required authentication methods.
-// Per spec, when a client picks an entry referenced by `acceptIndexes`, the
-// listed authentication is REQUIRED for that entry.
-//
-// We use the extension to advertise FREE-tier accept entries (amount=0) that
-// require either an OAuth 2.0 access token or a Sign-In-With-X proof. The
-// paid-endpoint helper short-circuits the payment dance when a valid auth
-// header is present, granting access without settling on-chain.
+// We use it to advertise FREE-tier accept entries (amount=0) that require
+// either an OAuth 2.0 access token or a Sign-In-With-X proof. The paid-
+// endpoint helper short-circuits the payment dance when a valid auth header
+// is present, granting access without settling on-chain.
//
// Auth credentials travel as standard HTTP headers — NOT inside the x402
// PaymentPayload:
@@ -19,15 +16,26 @@
// OAuth 2.0 (Bearer): Authorization: Bearer <access-token>
// Sign-In-With-X: SIGN-IN-WITH-X: <base64-encoded-siwx-proof>
//
-// The base64 SIWX proof is JSON-encoded with the shape:
-// { "type": "siwe"|"siws", "message": "...", "signature": "..." }
-// matching the existing /api/auth/{siwe,siws} verification flows.
+// The base64 SIWX proof format is the standard CAIP-122 envelope used by the
+// `sign-in-with-x` extension (parsed via @x402/extensions/sign-in-with-x).
+//
+// Difference from the existing `siwx-server.js` flow:
+// - siwx-server.js gates SIWX on a PRIOR paid grant (the wallet must have
+// paid once for this resource before SIWX re-entry works).
+// - auth-hints SIWX is a free alternative to payment — the wallet just
+// needs to sign a fresh CAIP-122 challenge.
+
+import {
+ parseSIWxHeader,
+ validateSIWxMessage,
+ verifySIWxSignature,
+} from '@x402/extensions/sign-in-with-x';
+import { createPublicClient, http } from 'viem';
+import { base } from 'viem/chains';
-import { verifyMessage, getAddress } from 'ethers';
import { env } from '../env.js';
import { authenticateBearer, hasScope } from '../auth.js';
-import { parseSiweMessage } from '../siwe.js';
-import { parseSiwsMessage, verifySiwsSignature } from '../siws.js';
+import { siwxStorage, normalizeAddress } from '../siwx-storage.js';
export const AUTH_HINTS_EXTENSION_KEY = 'auth-hints';
export const SIWX_HEADER = 'sign-in-with-x';
@@ -58,9 +66,7 @@ const AUTH_HINTS_SCHEMA = {
items: {
type: 'object',
required: ['type'],
- properties: {
- type: { type: 'string' },
- },
+ properties: { type: { type: 'string' } },
},
},
},
@@ -89,9 +95,6 @@ function buildSiwxMethod() {
return { type: 'sign-in-with-x' };
}
-// Validate that the requirements reference at least one accept entry and that
-// each method has a recognized shape. Throws when misconfigured so the route
-// fails closed at boot instead of silently emitting an invalid 402.
function validateAuthRequirements(authRequirements) {
if (!Array.isArray(authRequirements) || authRequirements.length === 0) {
throw new Error('declareAuthHintsExtension: authRequirements must be a non-empty array');
@@ -100,6 +103,9 @@ function validateAuthRequirements(authRequirements) {
if (!Array.isArray(r.acceptIndexes) || r.acceptIndexes.length === 0) {
throw new Error('declareAuthHintsExtension: acceptIndexes must be a non-empty array');
}
+ if (!r.acceptIndexes.every((i) => Number.isInteger(i) && i >= 0)) {
+ throw new Error('declareAuthHintsExtension: acceptIndexes must be non-negative integers');
+ }
if (!Array.isArray(r.methods) || r.methods.length === 0) {
throw new Error('declareAuthHintsExtension: methods must be a non-empty array');
}
@@ -121,7 +127,7 @@ function validateAuthRequirements(authRequirements) {
* full authRequirements entry with one method.
*
* Returns an object suitable for spreading into `build402Body`'s `extensions`
- * argument, e.g. `extensions: { ...declareAuthHintsExtension({...}) }`.
+ * argument: `extensions: { ...declareAuthHintsExtension({...}) }`.
*/
export function declareAuthHintsExtension(input) {
if (!input || typeof input !== 'object') {
@@ -163,10 +169,31 @@ export function declareAuthHintsExtension(input) {
};
}
+// Zero-amount EVM accept that signals "free when authenticated". The payment
+// dance for such entries is short-circuited in paid-endpoint.js when a valid
+// auth header is presented. Asset + payTo are still real values so schema
+// validators that don't special-case amount=0 still accept the entry.
+export function freeEvmAcceptForAuth({ network, asset, payTo, authType }) {
+ return {
+ scheme: 'exact',
+ network,
+ amount: '0',
+ asset,
+ payTo,
+ maxTimeoutSeconds: 60,
+ extra: {
+ name: 'USD Coin',
+ version: '2',
+ decimals: 6,
+ authRequired: authType,
+ },
+ };
+}
+
// ─── Header verification ────────────────────────────────────────────────────
function extractBearerToken(req) {
- const h = req.headers.authorization || req.headers.Authorization || '';
+ const h = req.headers?.authorization || req.headers?.Authorization || '';
if (typeof h !== 'string') return null;
if (!h.toLowerCase().startsWith('bearer ')) return null;
return h.slice(7).trim() || null;
@@ -174,110 +201,103 @@ function extractBearerToken(req) {
function readSiwxHeader(req) {
const raw =
- req.headers[SIWX_HEADER] ||
- req.headers['SIGN-IN-WITH-X'] ||
- req.headers['Sign-In-With-X'];
+ req.headers?.[SIWX_HEADER] ||
+ req.headers?.['SIGN-IN-WITH-X'] ||
+ req.headers?.['Sign-In-With-X'];
return typeof raw === 'string' && raw.length > 0 ? raw : null;
}
-function decodeSiwxProof(raw) {
- let json;
- try {
- json = Buffer.from(String(raw), 'base64').toString('utf8');
- } catch {
- return null;
+// Lazy viem client used to verify EIP-1271 / EIP-6492 smart-wallet signatures.
+// Mirrors siwx-server.js so both code paths share the same RPC.
+let _baseClient;
+function getEvmVerifier() {
+ if (!env.BASE_RPC_URL) return undefined;
+ if (!_baseClient) {
+ _baseClient = createPublicClient({ chain: base, transport: http(env.BASE_RPC_URL) });
}
- let parsed;
- try {
- parsed = JSON.parse(json);
- } catch {
- return null;
- }
- if (!parsed || typeof parsed !== 'object') return null;
- const { type, message, signature } = parsed;
- if (typeof message !== 'string' || typeof signature !== 'string') return null;
- if (type !== 'siwe' && type !== 'siws') return null;
- return { type, message, signature };
+ return _baseClient.verifyMessage.bind(_baseClient);
}
-// Domain check matches /api/auth/siwe + /api/auth/siws — the SIWX message
-// MUST be addressed to this deployment's host (or localhost in dev) so a
-// proof issued for another resource can't be replayed here.
-function siwxDomainOk(domain) {
- if (!domain) return false;
- let appHost;
+/**
+ * Verify a SIGN-IN-WITH-X header against the auth-hints contract:
+ * - parse the CAIP-122 envelope (delegated to @x402/extensions)
+ * - validate the message belongs to this resource and hasn't expired
+ * - verify the signature (EOA, EIP-1271, EIP-6492, or Solana ed25519)
+ * - burn the nonce so the same proof can't be replayed
+ *
+ * Returns `{ ok: true, principal: { ... } }` on success.
+ * Returns `{ ok: false, reason }` when a header was presented but failed any
+ * step — the caller should reject the request rather than silently falling
+ * through to the payment flow.
+ */
+export async function verifyAuthHintsSiwx({ req, resourceUrl }) {
+ const header = readSiwxHeader(req);
+ if (!header) return null;
+
+ let payload;
try {
- appHost = new URL(env.APP_ORIGIN).host;
+ payload = parseSIWxHeader(String(header));
} catch {
- return false;
+ return { ok: false, reason: 'invalid_siwx_proof' };
}
- const vercelHost = process.env.VERCEL_URL || null;
- const isLocalDev =
- process.env.VERCEL_ENV !== 'production' && process.env.VERCEL_ENV !== 'preview';
- const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));
- if (allowedHosts.has(domain)) return true;
- if (isLocalDev && /^localhost(:\d+)?$/.test(domain)) return true;
- return false;
-}
-function withinTemporalBounds(fields) {
- const now = Date.now();
- if (fields.expirationTime && Date.parse(fields.expirationTime) < now) return false;
- if (fields.notBefore && Date.parse(fields.notBefore) > now) return false;
- if (fields.issuedAt) {
- const issued = Date.parse(fields.issuedAt);
- if (Number.isFinite(issued)) {
- const skew = 10 * 60 * 1000;
- if (issued < now - skew) return false;
- if (issued > now + skew) return false;
- }
+ const validation = await validateSIWxMessage(payload, resourceUrl, {
+ maxAge: 5 * 60 * 1000,
+ checkNonce: async (n) => !(await siwxStorage.hasUsedNonce(n)),
+ });
+ if (!validation.valid) {
+ return { ok: false, reason: 'invalid_siwx_message', detail: validation.error };
}
- return true;
-}
-async function verifySiweProof({ message, signature }) {
- const fields = parseSiweMessage(message);
- if (!fields) return null;
- if (!siwxDomainOk(fields.domain)) return null;
- if (!withinTemporalBounds(fields)) return null;
- let recovered;
- try {
- recovered = verifyMessage(message, signature);
- } catch {
- return null;
+ const verification = await verifySIWxSignature(payload, { evmVerifier: getEvmVerifier() });
+ if (!verification.valid || !verification.address) {
+ return { ok: false, reason: 'invalid_siwx_signature', detail: verification.error };
}
- let claimed;
- try {
- claimed = getAddress(fields.address);
- } catch {
- return null;
- }
- if (recovered.toLowerCase() !== claimed.toLowerCase()) return null;
+
+ const address = normalizeAddress(payload.chainId, verification.address);
+
+ // Burn the nonce so the proof can't be replayed against this endpoint.
+ await siwxStorage.recordNonce(payload.nonce, {
+ resource: resourceUrl,
+ address,
+ });
+
return {
- method: 'sign-in-with-x',
- chain: 'eip155',
- address: claimed,
- chainId: fields.chainId || null,
+ ok: true,
+ principal: {
+ method: 'sign-in-with-x',
+ address,
+ network: payload.chainId,
+ },
};
}
-function verifySiwsProof({ message, signature }) {
- const fields = parseSiwsMessage(message);
- if (!fields) return null;
- if (!siwxDomainOk(fields.domain)) return null;
- if (!withinTemporalBounds(fields)) return null;
- let valid;
- try {
- valid = verifySiwsSignature(message, signature, fields.address);
- } catch {
- return null;
+/**
+ * Try OAuth Bearer auth as advertised by an `auth-hints` extension.
+ * Returns:
+ * • null → header absent, caller should fall through.
+ * • { ok: false, reason } → header present but invalid (reject).
+ * • { ok: true, principal: {...} } → authenticated.
+ */
+export async function verifyAuthHintsOauth(req, { audience, requiredScope } = {}) {
+ const bearer = extractBearerToken(req);
+ if (!bearer) return null;
+ const claims = await authenticateBearer(bearer, {
+ audience: audience || env.MCP_RESOURCE,
+ });
+ if (!claims) return { ok: false, reason: 'invalid_token' };
+ if (requiredScope && !hasScope(claims.scope, requiredScope)) {
+ return { ok: false, reason: 'insufficient_scope' };
}
- if (!valid) return null;
return {
- method: 'sign-in-with-x',
- chain: 'solana',
- address: fields.address,
- chainId: fields.chainId || null,
+ ok: true,
+ principal: {
+ method: 'oauth2',
+ source: claims.source,
+ userId: claims.userId,
+ scope: claims.scope,
+ clientId: claims.clientId || null,
+ },
};
}
@@ -285,82 +305,23 @@ function verifySiwsProof({ message, signature }) {
* Attempt to authenticate a request via the headers signaled by an `auth-hints`
* extension. Tries OAuth Bearer first (cheap, in-process verify), then SIWX.
*
- * Returns `null` when no auth header was presented (so the caller can fall
- * through to the regular x402 payment flow). Returns
- * `{ ok: true, principal: {...} }` on success and
- * `{ ok: false, reason: '...' }` when a header was presented but failed to
- * verify — callers should reject the request rather than silently downgrading
- * to the payment flow (otherwise an invalid Bearer would be quietly ignored).
- *
- * @param {import('http').IncomingMessage} req
- * @param {object} [opts]
- * @param {string} [opts.audience] — OAuth token audience (defaults to MCP resource).
- * @param {string} [opts.requiredScope] — OAuth scope required for this route.
+ * Returns null when no auth header was presented, `{ ok: false, reason }` when
+ * a header was presented but failed verification, and
+ * `{ ok: true, principal }` on success.
*/
export async function authenticateAuthHintsRequest(req, opts = {}) {
- const bearer = extractBearerToken(req);
- if (bearer) {
- const audience = opts.audience || env.MCP_RESOURCE;
- const principal = await authenticateBearer(bearer, { audience });
- if (!principal) return { ok: false, reason: 'invalid_token' };
- if (opts.requiredScope && !hasScope(principal.scope, opts.requiredScope)) {
- return { ok: false, reason: 'insufficient_scope' };
- }
- return {
- ok: true,
- principal: {
- method: 'oauth2',
- source: principal.source,
- userId: principal.userId,
- scope: principal.scope,
- clientId: principal.clientId || null,
- },
- };
+ const oauthResult = await verifyAuthHintsOauth(req, opts);
+ if (oauthResult) return oauthResult;
+ if (opts.resourceUrl) {
+ const siwxResult = await verifyAuthHintsSiwx({ req, resourceUrl: opts.resourceUrl });
+ if (siwxResult) return siwxResult;
}
-
- const siwxRaw = readSiwxHeader(req);
- if (siwxRaw) {
- const proof = decodeSiwxProof(siwxRaw);
- if (!proof) return { ok: false, reason: 'invalid_siwx_proof' };
- const verified =
- proof.type === 'siwe'
- ? await verifySiweProof(proof)
- : verifySiwsProof(proof);
- if (!verified) return { ok: false, reason: 'invalid_siwx_signature' };
- return { ok: true, principal: verified };
- }
-
return null;
}
-// ─── Helpers for building free accept entries paired with auth-hints ───────
-
-// Zero-amount EVM accept that signals "free when authenticated". The payment
-// dance for such entries is short-circuited in paid-endpoint.js when a valid
-// auth header is presented. The asset + payTo still need to be valid for
-// schema validators that don't know to special-case amount=0.
-export function freeEvmAcceptForAuth({ network, asset, payTo, authType }) {
- return {
- scheme: 'exact',
- network,
- amount: '0',
- asset,
- payTo,
- maxTimeoutSeconds: 60,
- extra: {
- name: 'USD Coin',
- version: '2',
- decimals: 6,
- authRequired: authType,
- },
- };
-}
-
export const __test = {
AUTH_HINTS_SCHEMA,
buildOauth2Method,
buildSiwxMethod,
- decodeSiwxProof,
- siwxDomainOk,
- withinTemporalBounds,
+ validateAuthRequirements,
};
diff --git a/api/_lib/x402/bazaar-client.js b/api/_lib/x402/bazaar-client.js
index 446e4503d..356f7ab65 100644
--- a/api/_lib/x402/bazaar-client.js
+++ b/api/_lib/x402/bazaar-client.js
@@ -86,7 +86,8 @@ export function normalizeItem(item, facilitator) {
const accepts = Array.isArray(item.accepts) ? item.accepts : [];
const primary = accepts[0] || {};
- const bazaarInfo = item?.extensions?.bazaar?.info || item?.inputSchema || null;
+ const bazaarExt = item?.extensions?.bazaar || null;
+ const bazaarInfo = bazaarExt?.info || item?.inputSchema || null;
const input = bazaarInfo?.input || bazaarInfo || null;
const isMcp = input?.type === 'mcp';
const toolName = isMcp ? input?.toolName || '' : '';
@@ -97,15 +98,31 @@ export function normalizeItem(item, facilitator) {
: item.resource?.url || primary?.resource || '';
const resourceMeta = typeof item.resource === 'object' ? item.resource : {};
+ const serviceMeta = bazaarInfo?.service || {};
const description =
- item.description || resourceMeta.description || primary?.description || '';
- const serviceName = resourceMeta.serviceName || resourceMeta.name || '';
- const iconUrl = resourceMeta.iconUrl || resourceMeta.icon || '';
- const tags = Array.isArray(resourceMeta.tags)
- ? resourceMeta.tags
- : Array.isArray(item.tags)
- ? item.tags
- : [];
+ item.description || resourceMeta.description || serviceMeta.description || bazaarExt?.description || primary?.description || '';
+ const serviceName =
+ resourceMeta.serviceName ||
+ resourceMeta.name ||
+ serviceMeta.name ||
+ bazaarExt?.name ||
+ '';
+ const iconUrl =
+ resourceMeta.iconUrl ||
+ resourceMeta.icon ||
+ serviceMeta.icon ||
+ serviceMeta.iconUrl ||
+ bazaarExt?.icon ||
+ bazaarExt?.iconUrl ||
+ '';
+ const rawTags =
+ (Array.isArray(resourceMeta.tags) && resourceMeta.tags) ||
+ (Array.isArray(item.tags) && item.tags) ||
+ (Array.isArray(serviceMeta.tags) && serviceMeta.tags) ||
+ (Array.isArray(bazaarExt?.tags) && bazaarExt.tags) ||
+ [];
+ const category = bazaarExt?.category || serviceMeta.category || resourceMeta.category;
+ const tags = category && !rawTags.includes(category) ? [category, ...rawTags] : rawTags;
const normalizedAccepts = accepts.map((a) => {
const net = normalizeNetwork(a.network);
@@ -219,7 +236,11 @@ export class Bazaar {
const settled = await Promise.allSettled(
this.facilitators.map(async (f) => {
const items = await listOneFacilitator(f, { type, limit, maxItems });
- return items.map((it) => normalizeItem(it, f)).filter(Boolean);
+ const normalized = items.map((it) => normalizeItem(it, f)).filter(Boolean);
+ // Some facilitators (PayAI) ignore the `type` query param and return
+ // HTTP items regardless. Apply the filter ourselves so callers get a
+ // consistent catalog.
+ return normalized.filter((it) => it.type === type);
}),
);
const items = [];
diff --git a/api/_lib/x402/bazaar-helpers.js b/api/_lib/x402/bazaar-helpers.js
new file mode 100644
index 000000000..e557f4974
--- /dev/null
+++ b/api/_lib/x402/bazaar-helpers.js
@@ -0,0 +1,208 @@
+// Bazaar discovery helpers — wraps the @x402/extensions/bazaar declarators
+// with the bits our paidEndpoint() wrapper expects.
+//
+// USE-13: every paid endpoint in the repo advertises a v2 `bazaar` extension
+// so the CDP / agentic.market / x402.org facilitators can index it. The
+// declared shape MUST match the BazaarServerExtension's expectations exactly
+// — deviating causes the validator to reject the endpoint with "v2 discovery
+// extension validation failed" even when the 402 challenge is otherwise
+// well-formed.
+//
+// We expose three things:
+// 1. declareHttpDiscovery({...}) — returns the bazaar inner object
+// ({discoverable, info, schema}) for an HTTP endpoint. Pass it directly
+// as paidEndpoint({ bazaar: ... }).
+// 2. declareMcpDiscovery({...}) — same shape for an MCP tool. Each paid
+// tool needs its own entry: facilitators key MCP catalog rows on
+// (resourceUrl, toolName), not on resourceUrl alone.
+// 3. THREEWS_SERVICE — default resource-level service metadata
+// (serviceName, tags, iconUrl) the facilitator surfaces in search
+// results. Per-route helpers below merge specific tags on top of this.
+//
+// Spec: /tmp/x402-docs/specs/extensions/bazaar.md
+// /tmp/x402-docs/docs/extensions/bazaar.mdx
+
+import { declareDiscoveryExtension } from '@x402/extensions';
+
+import { buildBazaarSchema } from '../x402-spec.js';
+import { env } from '../env.js';
+
+// Resource-level service metadata. Per spec §"Service Metadata":
+// • serviceName: ≤32 printable ASCII chars
+// • tags: up to 5 entries, each ≤32 printable ASCII chars
+// • iconUrl: absolute http(s) URL (≤2048 chars, no IP literals)
+// Facilitators apply soft-drop rules: a field that fails validation is
+// silently discarded but the rest survive, so keeping every field within
+// the limits is purely a matter of getting cataloged with full metadata.
+export const THREEWS_SERVICE = Object.freeze({
+ serviceName: 'three.ws',
+ tags: ['x402', 'mcp', '3d', 'agent', 'solana'],
+ iconUrl: 'https://three.ws/favicon.ico',
+});
+
+// Merge per-route service metadata on top of the three.ws defaults. Pass
+// `{ serviceName, tags, iconUrl }` per endpoint; missing fields fall back
+// to the default. `tags` REPLACES the default tag list when provided —
+// callers know which tags actually describe their route.
+export function withService(custom = {}) {
+ const out = {
+ serviceName: THREEWS_SERVICE.serviceName,
+ tags: [...THREEWS_SERVICE.tags],
+ iconUrl: THREEWS_SERVICE.iconUrl,
+ };
+ if (typeof custom.serviceName === 'string' && custom.serviceName.length) {
+ out.serviceName = custom.serviceName;
+ }
+ if (Array.isArray(custom.tags) && custom.tags.length) {
+ out.tags = custom.tags.slice(0, 5);
+ }
+ if (typeof custom.iconUrl === 'string' && custom.iconUrl.length) {
+ out.iconUrl = custom.iconUrl;
+ }
+ // Anchor relative icon paths against APP_ORIGIN — facilitators reject
+ // non-absolute iconUrl per the SSRF defense in the spec.
+ if (out.iconUrl && !/^https?:\/\//i.test(out.iconUrl)) {
+ out.iconUrl = `${env.APP_ORIGIN}${out.iconUrl.startsWith('/') ? '' : '/'}${out.iconUrl}`;
+ }
+ return out;
+}
+
+// Build the v2 HTTP bazaar discovery entry for a route. Returns the inner
+// `{ discoverable, info, schema }` object (NOT wrapped in `{ bazaar: ... }`)
+// because our paidEndpoint helper takes that inner shape directly.
+//
+// Args (mirrors agentic.market's declareDiscoveryExtension):
+// method — 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD'
+// input — example query params or body (for the spec UI)
+// inputSchema — JSON Schema for the query/body params
+// output — { example, schema } for the response body
+// bodyType — 'json' | 'form-data' | 'text' (required for POST/PUT/PATCH)
+//
+// The wrapped declareDiscoveryExtension call asserts our payload matches the
+// SDK's runtime expectations — when the SDK ships a stricter validator we
+// pick it up automatically rather than silently emitting a stale shape.
+export function declareHttpDiscovery({
+ method = 'GET',
+ input,
+ inputSchema,
+ output,
+ bodyType,
+} = {}) {
+ const upper = String(method).toUpperCase();
+ const isBody = ['POST', 'PUT', 'PATCH'].includes(upper);
+
+ // Run the SDK declarator for its side effect: in v2 it returns
+ // `{ bazaar: { info, schema, ... } }`. We extract the inner entry so
+ // our paidEndpoint helper can plug it straight into the 402 challenge.
+ const sdkConfig = isBody
+ ? {
+ method: upper,
+ bodyType: bodyType || 'json',
+ input: input ?? {},
+ inputSchema: inputSchema || { properties: {} },
+ output: output || undefined,
+ }
+ : {
+ method: upper,
+ input: input ?? undefined,
+ inputSchema: inputSchema || undefined,
+ output: output || undefined,
+ };
+
+ let sdkBlock;
+ try {
+ sdkBlock = declareDiscoveryExtension(sdkConfig);
+ } catch (err) {
+ throw new Error(`declareHttpDiscovery: SDK rejected config: ${err.message}`);
+ }
+ const sdkInner = sdkBlock?.bazaar || Object.values(sdkBlock || {})[0];
+
+ // Belt-and-braces: rebuild the meta-schema with our own buildBazaarSchema
+ // so it stays in sync with what agentic.market's validator expects. The
+ // SDK's schema is structurally equivalent but slightly more permissive in
+ // `additionalProperties` placement — running through buildBazaarSchema
+ // guarantees the exact shape that has been validated against the CDP
+ // Bazaar's discovery probe.
+ const schema = buildBazaarSchema({
+ method: upper,
+ queryParamsSchema: isBody ? undefined : inputSchema,
+ bodyType: isBody ? bodyType || 'json' : undefined,
+ bodySchema: isBody ? inputSchema : undefined,
+ outputSchema: output?.schema,
+ });
+
+ const info = sdkInner?.info || {};
+ const inputInfo = info.input || {};
+
+ // Surface the response example/schema in the same shape buildBazaarSchema
+ // expects. The SDK already nests these under info.output but only when an
+ // `output` arg was passed; we re-normalize so consumers can rely on the
+ // shape unconditionally.
+ const outputInfo = output
+ ? {
+ type: 'json',
+ ...(output.example !== undefined ? { example: output.example } : {}),
+ }
+ : info.output;
+
+ return {
+ discoverable: true,
+ info: {
+ input: { ...inputInfo, type: 'http', method: upper },
+ ...(outputInfo ? { output: outputInfo } : {}),
+ },
+ schema,
+ };
+}
+
+// Build the v2 MCP bazaar discovery entry for a paid tool. The catalog
+// uniqueness key is (resource, toolName) — every paid tool needs its own
+// entry so search can find them individually.
+//
+// Args:
+// toolName — the MCP tool name (matches the `tools/call` `name` arg)
+// description — human-readable summary (optional but recommended)
+// transport — 'streamable-http' (default) | 'sse'
+// inputSchema — MCP Tool.inputSchema (JSON Schema object)
+// example — example arguments object (for the spec UI)
+// output — { example, schema } for the result payload
+export function declareMcpDiscovery({
+ toolName,
+ description,
+ transport = 'streamable-http',
+ inputSchema,
+ example,
+ output,
+} = {}) {
+ if (!toolName || typeof toolName !== 'string') {
+ throw new Error('declareMcpDiscovery: toolName is required');
+ }
+ if (!inputSchema || typeof inputSchema !== 'object') {
+ throw new Error('declareMcpDiscovery: inputSchema is required');
+ }
+
+ const sdkConfig = {
+ toolName,
+ description,
+ transport,
+ inputSchema,
+ example,
+ output,
+ };
+ let sdkBlock;
+ try {
+ sdkBlock = declareDiscoveryExtension(sdkConfig);
+ } catch (err) {
+ throw new Error(`declareMcpDiscovery: SDK rejected config: ${err.message}`);
+ }
+ const sdkInner = sdkBlock?.bazaar || Object.values(sdkBlock || {})[0];
+ return sdkInner;
+}
+
+// Convenience: returns the full extensions block `{ bazaar: <inner> }` for
+// callers that want to spread it straight into a payment-wrapper config.
+// Matches the v2 SDK call signature ({ method, input, inputSchema, output, … })
+// but always returns OUR canonical inner shape via declareHttpDiscovery.
+export function declareDiscovery(config = {}) {
+ return { bazaar: declareHttpDiscovery(config) };
+}
diff --git a/api/_lib/x402/receipt-storage.js b/api/_lib/x402/receipt-storage.js
new file mode 100644
index 000000000..f70926d1c
--- /dev/null
+++ b/api/_lib/x402/receipt-storage.js
@@ -0,0 +1,95 @@
+// Durable log of x402 offer-receipt artifacts (USE-17).
+//
+// Every signed receipt we emit on a successful payment gets written here so:
+// 1. Buyers can later replay them via /api/x402/my-receipts (proof of past
+// purchase even if they lost the original PAYMENT-RESPONSE header).
+// 2. Operators have an audit trail for dispute resolution.
+// 3. Reputation systems can pull on demand instead of having to capture
+// every receipt at issue time.
+//
+// Backed by Postgres (Neon) — see migrations/2026-05-24-x402-receipts.sql.
+// Writes are fire-and-forget from the paid-endpoint hot path: a Neon hiccup
+// must not surface as a 5xx on a paid response that already settled on-chain.
+
+import { sql } from '../db.js';
+
+import { extractReceiptPayload } from '@x402/extensions';
+
+/** Normalize a payer address for lookup: EVM → lowercase, Solana stays as-is. */
+function normalisePayer(payer) {
+ if (!payer) return null;
+ const s = String(payer).trim();
+ return s.startsWith('0x') ? s.toLowerCase() : s;
+}
+
+/**
+ * Persist a signed receipt. Returns nothing — caller does not await.
+ *
+ * @param {object} args
+ * @param {string} args.resourceUrl
+ * @param {object} args.signedReceipt
+ * @param {{ payer?: string, network?: string, transaction?: string }} args.settled
+ */
+export function recordReceipt({ resourceUrl, signedReceipt, settled }) {
+ if (!signedReceipt) return;
+ const payer = normalisePayer(settled?.payer);
+ if (!payer) return;
+ const format = signedReceipt.format;
+ let payload;
+ try {
+ payload = extractReceiptPayload(signedReceipt);
+ } catch (err) {
+ console.error(
+ `[x402-receipt-log] could not extract payload for storage: ${err.message}`,
+ );
+ return;
+ }
+ const network = payload.network || settled?.network || null;
+ const transaction = payload.transaction || null;
+ sql`
+ insert into x402_receipts
+ (payer, network, resource_url, format, receipt, transaction)
+ values
+ (${payer}, ${network}, ${resourceUrl}, ${format},
+ ${JSON.stringify(signedReceipt)}::jsonb, ${transaction})
+ `.catch((err) => {
+ console.error('[x402-receipt-log] insert failed:', err?.message || err);
+ });
+}
+
+/**
+ * Fetch receipts for a payer address. Used by /api/x402/my-receipts after
+ * verifying a buyer-signed SIWE message proving wallet ownership.
+ *
+ * @param {object} args
+ * @param {string} args.payer - wallet address (will be lower-cased for EVM)
+ * @param {number} [args.sinceUnix] - return receipts issued >= this time (seconds)
+ * @param {number} [args.limit] - clamp 1..200, default 50
+ */
+export async function listReceiptsForPayer({ payer, sinceUnix, limit }) {
+ const normPayer = normalisePayer(payer);
+ if (!normPayer) return [];
+ const clampedLimit = Math.min(Math.max(parseInt(limit, 10) || 50, 1), 200);
+ const sinceDate =
+ sinceUnix && Number.isFinite(Number(sinceUnix))
+ ? new Date(Number(sinceUnix) * 1000)
+ : new Date(0);
+ const rows = await sql`
+ select id, payer, network, resource_url, format, receipt, transaction, issued_at
+ from x402_receipts
+ where payer = ${normPayer}
+ and issued_at >= ${sinceDate.toISOString()}
+ order by issued_at desc
+ limit ${clampedLimit}
+ `;
+ return rows.map((r) => ({
+ id: r.id,
+ payer: r.payer,
+ network: r.network,
+ resourceUrl: r.resource_url,
+ format: r.format,
+ receipt: r.receipt,
+ transaction: r.transaction,
+ issuedAt: r.issued_at instanceof Date ? r.issued_at.toISOString() : r.issued_at,
+ }));
+}
diff --git a/api/insights/revenue-vision.js b/api/insights/revenue-vision.js
index e33cf6d66..51ecd2022 100644
--- a/api/insights/revenue-vision.js
+++ b/api/insights/revenue-vision.js
@@ -20,6 +20,16 @@ import {
resolveResourceUrl,
} from '../_lib/x402-spec.js';
import { env } from '../_lib/env.js';
+import {
+ PAYMENT_IDENTIFIER,
+ checkCache,
+ extractIdFromHeader,
+ hashRequestPayload,
+ paymentIdentifierExtension,
+ storeResponse,
+ writeCachedResponse,
+ writeConflict,
+} from '../_lib/x402/payment-identifier-server.js';
const ROUTE = '/api/insights/revenue-vision';
@@ -175,11 +185,31 @@ export default wrap(async (req, res) => {
accepts: requirements,
description: ROUTE_DESCRIPTION,
bazaar: ROUTE_BAZAAR,
+ extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },
};
const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];
if (!paymentHeader) return send402(res, challenge);
+ // USE-15: idempotency cache lookup before paying for /verify.
+ const paymentId = extractIdFromHeader(paymentHeader);
+ const payloadHash = hashRequestPayload({
+ method: req.method,
+ url: req.url,
+ body: null,
+ });
+ if (paymentId) {
+ const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash });
+ if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);
+ if (lookup.kind === 'conflict') {
+ return writeConflict(res, {
+ route: ROUTE,
+ attemptedHash: lookup.attemptedHash,
+ existingHash: lookup.existingHash,
+ });
+ }
+ }
+
let verified;
try {
verified = await verifyPayment({ paymentHeader, requirements });
@@ -216,8 +246,24 @@ export default wrap(async (req, res) => {
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
- res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));
+ const paymentResponseHeader = encodePaymentResponseHeader(settled);
+ const contentType = 'application/json; charset=utf-8';
+ const body = JSON.stringify(result);
+
+ res.setHeader('x-payment-response', paymentResponseHeader);
res.setHeader('cache-control', 'no-store');
- res.setHeader('content-type', 'application/json; charset=utf-8');
- res.end(JSON.stringify(result));
+ res.setHeader('content-type', contentType);
+ res.end(body);
+
+ if (paymentId) {
+ await storeResponse({
+ route: ROUTE,
+ paymentId,
+ payloadHash,
+ status: 200,
+ body,
+ contentType,
+ paymentResponseHeader,
+ });
+ }
});
diff --git a/api/wk.js b/api/wk.js
index d9f601f99..cf0d9fb5b 100644
--- a/api/wk.js
+++ b/api/wk.js
@@ -125,6 +125,10 @@ function handleOauthAuthServer(req, res) {
'avatars:delete',
'profile',
'offline_access',
+ // USE-21 auth-hints: paid endpoints advertise these scopes for
+ // Bearer-token bypass via the auth-hints extension.
+ 'read:agent-reputation',
+ 'x402:bypass',
],
service_documentation: `${base}/docs/mcp`,
ui_locales_supported: ['en'],
@@ -353,6 +357,10 @@ function handleX402Discovery(req, res) {
environment: 'apex',
origin,
},
+ // `.filter(Boolean)` drops any resource whose IIFE returned null —
+ // e.g. permit2-paid-demo is omitted when CDP creds are missing,
+ // matching the runtime 402 behavior so we don't catalog a route that
+ // would fail at first paid call.
resources: [
{
path: '/api/x402/model-check',
@@ -576,6 +584,50 @@ function handleX402Discovery(req, res) {
}),
};
})(),
+ (() => {
+ // Permit2-only demo: skip the EIP-3009 entry that acceptsForPrice
+ // would push first, so SDK clients are forced through the gasless
+ // EIP-2612 → settleWithPermit path the endpoint is meant to prove.
+ // permit2VariantOf returns null without CDP creds, in which case we
+ // omit the resource from discovery (matches the runtime 402 behavior).
+ const price = RAW_AMOUNT_TO_USDC('1000');
+ const baseAccept = env.X402_PAY_TO_BASE
+ ? {
+ scheme: 'exact',
+ network: NETWORK_BASE_MAINNET,
+ network_label: 'base-mainnet',
+ amount: '1000',
+ price,
+ payTo: env.X402_PAY_TO_BASE,
+ asset: env.X402_ASSET_ADDRESS_BASE,
+ asset_symbol: 'USDC',
+ maxTimeoutSeconds: 60,
+ extra: { name: 'USD Coin', version: '2', decimals: 6 },
+ }
+ : null;
+ const permit2 = baseAccept ? permit2VariantOf(baseAccept) : null;
+ if (!permit2) return null;
+ const accepts = [permit2];
+ return {
+ path: '/api/x402/permit2-paid-demo',
+ url: `${origin}/api/x402/permit2-paid-demo`,
+ method: 'GET',
+ description:
+ 'Permit2 + EIP-2612 Gas Sponsoring Demo — forces the gasless Permit2 path so a fresh wallet holding USDC but ZERO ETH can complete the flow. CDP\'s x402ExactPermit2Proxy submits the EIP-2612 permit + Permit2 transfer atomically via settleWithPermit. Response surfaces the on-chain tx hash and a Basescan link.',
+ mimeType: 'application/json',
+ accepts,
+ extensions: extensionsForAccepts(accepts, {
+ method: 'GET',
+ discoverable: true,
+ input: {},
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ additionalProperties: false,
+ },
+ }),
+ };
+ })(),
(() => {
const accepts = acceptsForPrice('50000');
return {
@@ -610,7 +662,7 @@ function handleX402Discovery(req, res) {
}),
};
})(),
- ],
+ ].filter(Boolean),
},
{ 'cache-control': 'public, max-age=300' },
);
diff --git a/api/x402-checkout.js b/api/x402-checkout.js
index a2636ada2..3f0750caf 100644
--- a/api/x402-checkout.js
+++ b/api/x402-checkout.js
@@ -67,10 +67,19 @@ const prepareSchema = z.object({
buyer: z.string().min(32).max(44),
});
+const builderCodeBlockSchema = z
+ .object({
+ a: z.string().regex(/^[a-z0-9_]{1,32}$/),
+ w: z.string().regex(/^[a-z0-9_]{1,32}$/).optional(),
+ s: z.array(z.string().regex(/^[a-z0-9_]{1,32}$/)).max(32).optional(),
+ })
+ .optional();
+
const encodeSchema = z.object({
accept: acceptSchema,
signed_tx_base64: z.string().min(40).max(20_000),
resource_url: z.string().url(),
+ builder_code: builderCodeBlockSchema,
});
export default wrap(async (req, res) => {
@@ -181,7 +190,7 @@ async function handlePrepare(req, res) {
async function handleEncode(req, res) {
const body = parse(encodeSchema, await readJson(req));
- const { accept, signed_tx_base64, resource_url } = body;
+ const { accept, signed_tx_base64, resource_url, builder_code } = body;
const payload = {
x402Version: 2,
scheme: 'exact',
@@ -190,6 +199,9 @@ async function handleEncode(req, res) {
accepted: accept,
payload: { transaction: signed_tx_base64 },
};
+ if (builder_code) {
+ payload.extensions = { 'builder-code': builder_code };
+ }
const xPayment = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64');
return json(res, 200, { x_payment: xPayment });
}
diff --git a/api/x402-status.js b/api/x402-status.js
index 5e8724b49..7800b0126 100644
--- a/api/x402-status.js
+++ b/api/x402-status.js
@@ -17,6 +17,35 @@ import {
probeFacilitators,
X402_VERSION,
} from './_lib/x402-spec.js';
+import { sql } from './_lib/db.js';
+import { hasEvmVerifier } from './_lib/siwx-server.js';
+
+// Read SIWX table counts so operators can confirm at-a-glance whether the
+// SIWX rails are wired and active. The tables may not exist on a brand-new
+// database (migrations not yet run) — surface that explicitly via
+// `configured: false` instead of failing the whole status endpoint.
+async function probeSiwx() {
+ try {
+ const [{ n: paymentsRowCount }] = await sql`
+ select count(*)::int as n from siwx_payments
+ `;
+ const [{ n: noncesRowCount }] = await sql`
+ select count(*)::int as n from siwx_nonces
+ `;
+ return {
+ configured: true,
+ paymentsRowCount,
+ noncesRowCount,
+ evmVerifierConfigured: hasEvmVerifier(),
+ };
+ } catch (err) {
+ return {
+ configured: false,
+ error: err.message,
+ evmVerifierConfigured: hasEvmVerifier(),
+ };
+ }
+}
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
@@ -24,6 +53,7 @@ export default wrap(async (req, res) => {
const accepts = paymentRequirements();
const facilitators = await probeFacilitators();
+ const siwx = await probeSiwx();
const ok = facilitators.every((f) => f.ok);
// Surface what we advertise in 402 challenges so operators can confirm at a
@@ -75,6 +105,7 @@ export default wrap(async (req, res) => {
X402_FEE_PAYER_SOLANA: env.X402_FEE_PAYER_SOLANA || null,
X402_MAX_AMOUNT_REQUIRED: env.X402_MAX_AMOUNT_REQUIRED || null,
},
+ siwx,
},
{ 'cache-control': 'no-store' },
);
diff --git a/api/x402/admin/subscriptions.js b/api/x402/admin/subscriptions.js
new file mode 100644
index 000000000..22ba54c58
--- /dev/null
+++ b/api/x402/admin/subscriptions.js
@@ -0,0 +1,70 @@
+// /api/x402/admin/subscriptions
+// GET → list active subscriptions (?includeInactive=1 → revoked / expired too)
+// POST → issue a new subscription. Returns the plaintext API key ONCE.
+//
+// Admin-only (api/_lib/admin.js requireAdmin gate). Backing tables and the
+// runtime hook live in api/_lib/x402/api-keys.js + access-control.js.
+
+import { z } from 'zod';
+import { cors, json, error, method, readJson, wrap } from '../../_lib/http.js';
+import { requireAdmin } from '../../_lib/admin.js';
+import { parse } from '../../_lib/validate.js';
+import { logAudit } from '../../_lib/audit.js';
+import { createSubscription, listSubscriptions } from '../../_lib/x402/api-keys.js';
+
+const createSchema = z.object({
+ name: z.string().trim().min(1).max(120),
+ rate_limit_per_minute: z.number().int().min(1).max(100_000).optional().default(60),
+ expires_at: z.string().datetime().optional().nullable(),
+ meta: z.record(z.unknown()).optional().nullable(),
+ id: z
+ .string()
+ .trim()
+ .regex(/^[a-z0-9_-]{3,64}$/i, 'id must be 3-64 chars, alphanumeric/underscore/dash')
+ .optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const admin = await requireAdmin(req, res);
+ if (!admin) return;
+
+ if (req.method === 'GET') {
+ const includeInactive =
+ req.query?.includeInactive === '1' || req.query?.includeInactive === 'true';
+ const rows = await listSubscriptions({ includeInactive });
+ return json(res, 200, { data: rows });
+ }
+
+ // POST — create
+ const body = parse(createSchema, await readJson(req));
+ let created;
+ try {
+ created = await createSubscription({
+ name: body.name,
+ id: body.id,
+ rateLimitPerMinute: body.rate_limit_per_minute,
+ expiresAt: body.expires_at ?? null,
+ meta: body.meta ?? null,
+ createdBy: admin.id,
+ });
+ } catch (err) {
+ if (err?.code === '23505' || /duplicate/i.test(err?.message || '')) {
+ return error(res, 409, 'duplicate_subscription', 'id already exists');
+ }
+ return error(res, err.status || 500, err.code || 'internal_error', err.message);
+ }
+
+ logAudit({
+ userId: admin.id,
+ action: 'x402.subscription.create',
+ resourceId: created.id,
+ meta: { name: created.name, rate_limit_per_minute: created.rate_limit_per_minute },
+ });
+
+ // The token field is the ONLY time we ever surface the plaintext key.
+ // Operators must store it on their side immediately.
+ return json(res, 201, { data: created });
+});
diff --git a/api/x402/admin/subscriptions/[id].js b/api/x402/admin/subscriptions/[id].js
new file mode 100644
index 000000000..9407e5e2d
--- /dev/null
+++ b/api/x402/admin/subscriptions/[id].js
@@ -0,0 +1,33 @@
+// /api/x402/admin/subscriptions/<id>
+// DELETE → revoke. Idempotent — re-revoking a revoked sub is a 200.
+//
+// Admin-only. Audit-trailed via api/_lib/audit.js. Usage stats for a given
+// subscription live at /api/x402/admin/subscriptions/<id>/usage.
+
+import { cors, json, error, method, wrap } from '../../../_lib/http.js';
+import { requireAdmin } from '../../../_lib/admin.js';
+import { logAudit } from '../../../_lib/audit.js';
+import { revokeSubscription } from '../../../_lib/x402/api-keys.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['DELETE'])) return;
+
+ const admin = await requireAdmin(req, res);
+ if (!admin) return;
+
+ const id = String(req.query?.id || '').trim();
+ if (!id) return error(res, 400, 'missing_id', 'subscription id required');
+
+ const row = await revokeSubscription(id);
+ if (!row) return error(res, 404, 'not_found', 'subscription not found');
+
+ logAudit({
+ userId: admin.id,
+ action: 'x402.subscription.revoke',
+ resourceId: id,
+ meta: { name: row.name },
+ });
+
+ return json(res, 200, { data: row });
+});
diff --git a/api/x402/admin/subscriptions/[id]/usage.js b/api/x402/admin/subscriptions/[id]/usage.js
new file mode 100644
index 000000000..74e88fd67
--- /dev/null
+++ b/api/x402/admin/subscriptions/[id]/usage.js
@@ -0,0 +1,29 @@
+// GET /api/x402/admin/subscriptions/<id>/usage
+//
+// Admin-only. Returns aggregate counts (granted vs. denied), per-route breakdown,
+// and the most recent N access-log rows for the given subscription. Sourced
+// from x402_access_log written by api/_lib/x402/access-control.js on every
+// bypass / abort.
+
+import { cors, json, error, method, wrap } from '../../../../_lib/http.js';
+import { requireAdmin } from '../../../../_lib/admin.js';
+import { getUsage } from '../../../../_lib/x402/api-keys.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const admin = await requireAdmin(req, res);
+ if (!admin) return;
+
+ const id = String(req.query?.id || '').trim();
+ if (!id) return error(res, 400, 'missing_id', 'subscription id required');
+
+ const recentRaw = parseInt(req.query?.limit, 10);
+ const recentLimit = Number.isFinite(recentRaw) ? Math.min(Math.max(recentRaw, 1), 500) : 50;
+
+ const usage = await getUsage(id, { recentLimit });
+ if (!usage) return error(res, 404, 'not_found', 'subscription not found');
+
+ return json(res, 200, { data: usage });
+});
diff --git a/api/x402/agent-reputation.js b/api/x402/agent-reputation.js
index b3caeec68..6ef9342d1 100644
--- a/api/x402/agent-reputation.js
+++ b/api/x402/agent-reputation.js
@@ -14,6 +14,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 { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/agent-reputation';
@@ -290,6 +291,16 @@ export default paidEndpoint({
networks: ['base', 'solana'],
description: DESCRIPTION,
bazaar: BAZAAR,
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+ // USE-21: declare auth-hints. Buyers with an OAuth2 access token granted
+ // scope `read:agent-reputation` skip payment, as do wallets that present
+ // a fresh CAIP-122 SIGN-IN-WITH-X proof for this resource. Without either,
+ // the regular USDC accepts entries apply.
+ authHints: {
+ oauth2: { requiredScope: 'read:agent-reputation', tokenType: 'Bearer' },
+ siwx: true,
+ },
async handler({ req }) {
const agentId = String(req.query?.agent_id || '').trim().toLowerCase();
if (!agentId) {
diff --git a/api/x402/asset-download.js b/api/x402/asset-download.js
new file mode 100644
index 000000000..b4f12c6cb
--- /dev/null
+++ b/api/x402/asset-download.js
@@ -0,0 +1,171 @@
+// GET /api/x402/asset-download?slug=<slug>
+//
+// Canonical "buy once, re-download forever" 3D-asset bazaar. A creator uploads
+// a GLB / avatar / accessory to R2, prices it, and lists it in the paid_assets
+// table. The first download is paid via x402 USDC (Base or Solana); every
+// subsequent download from the same wallet is free via Sign-In-With-X (CAIP-122).
+//
+// The response is JSON with a short-lived presigned R2 URL — proxying the
+// bytes through Vercel would blow past the function response-size limit on
+// real GLBs. The client fetches the file directly from R2 with the URL.
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { sql } from '../_lib/db.js';
+import { presignGet } from '../_lib/r2.js';
+import { error } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+
+const ROUTE = '/api/x402/asset-download';
+
+const DESCRIPTION =
+ 'three.ws Asset Bazaar — pay once in USDC to unlock a 3D asset (GLB, ' +
+ 'avatar, or accessory) hosted on R2. Wallets that have already paid can ' +
+ 're-download for free by signing in with SIWX (CAIP-122). Each asset has ' +
+ 'its own price and creator payout address; the response carries a short- ' +
+ 'lived presigned URL the client uses to fetch the file directly from R2.';
+
+const INPUT_EXAMPLE = { slug: 'pole-dancer-rumba' };
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['slug'],
+ properties: {
+ slug: {
+ type: 'string',
+ description: 'Unique asset slug from the paid_assets catalog.',
+ minLength: 1,
+ maxLength: 128,
+ },
+ },
+};
+
+const OUTPUT_EXAMPLE = {
+ ok: true,
+ slug: 'pole-dancer-rumba',
+ title: 'Pole Dancer (Rumba)',
+ description: 'The default three.ws dancer rigged for the /club Rumba routine.',
+ mimeType: 'model/gltf-binary',
+ sizeBytes: 6_492_840,
+ expiresAt: '2026-05-21T18:48:09.000Z',
+ downloadUrl:
+ 'https://three-ws-public.r2.dev/assets/pole-dancer-rumba.glb?X-Amz-Algorithm=...',
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['ok', 'slug', 'title', 'mimeType', 'sizeBytes', 'downloadUrl', 'expiresAt'],
+ properties: {
+ ok: { type: 'boolean', const: true },
+ slug: { type: 'string' },
+ title: { type: 'string' },
+ description: { type: 'string' },
+ mimeType: { type: 'string' },
+ sizeBytes: { type: 'integer', minimum: 0 },
+ expiresAt: { type: 'string', format: 'date-time' },
+ downloadUrl: { type: 'string', format: 'uri' },
+ },
+};
+
+const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'GET', queryParams: INPUT_EXAMPLE },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+// Presigned URL lifetime. Keep this short — once the buyer has the URL, R2
+// will serve the file to anyone who holds it for the next N seconds. 60s is
+// enough for any reasonable client to start the download; the URL becomes
+// useless once the file finishes streaming.
+const PRESIGN_TTL_SECONDS = 60;
+
+async function loadAsset(slug) {
+ const rows = await sql`
+ SELECT id, slug, title, description, mime_type, size_bytes, r2_key,
+ price_atomics, creator_payto_base, creator_payto_solana,
+ creator_payto_bsc
+ FROM paid_assets
+ WHERE slug = ${slug}
+ LIMIT 1
+ `;
+ return rows[0] || null;
+}
+
+function buildPayToOverride(asset) {
+ const out = {};
+ if (asset.creator_payto_base) out.base = asset.creator_payto_base;
+ if (asset.creator_payto_solana) out.solana = asset.creator_payto_solana;
+ if (asset.creator_payto_bsc) out.bsc = asset.creator_payto_bsc;
+ return Object.keys(out).length ? out : undefined;
+}
+
+// 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) {
+ const slug = req.query?.slug ? String(req.query.slug).trim() : '';
+ if (!slug) {
+ return error(res, 400, 'slug_required', 'query parameter "slug" is required');
+ }
+
+ let asset;
+ try {
+ asset = await loadAsset(slug);
+ } catch (err) {
+ return error(res, 502, 'paid_assets_lookup_failed', err.message);
+ }
+ if (!asset) {
+ return error(res, 404, 'asset_not_found', `no paid_assets row with slug "${slug}"`);
+ }
+
+ const inner = paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: String(asset.price_atomics),
+ networks: ['base', 'solana'],
+ description: `${DESCRIPTION} — currently delivering: ${asset.title}.`,
+ mimeType: 'application/json',
+ bazaar: BAZAAR,
+ payTo: buildPayToOverride(asset),
+ // Make the SIWX grant key per-asset by baking the slug into the
+ // resource URL. Without this, paying for any one asset would unlock
+ // every other asset via signature — the SIWX storage row is keyed on
+ // (resource, address) only. The 402 challenge advertises the same URL
+ // the client signs against, so verification stays consistent.
+ resourceUrlBuilder: () =>
+ `${env.APP_ORIGIN}${ROUTE}?slug=${encodeURIComponent(asset.slug)}`,
+ siwx: {
+ statement: `Sign in to re-download "${asset.title}" without re-paying.`,
+ // Permanent grant per (asset, wallet) — once a wallet has paid for
+ // this asset it can re-download forever by signing.
+ ttlSeconds: null,
+ expirationSeconds: 300,
+ },
+ async handler() {
+ const url = await presignGet({
+ key: asset.r2_key,
+ expiresIn: PRESIGN_TTL_SECONDS,
+ });
+ return {
+ ok: true,
+ slug: asset.slug,
+ title: asset.title,
+ description: asset.description,
+ mimeType: asset.mime_type,
+ sizeBytes: Number(asset.size_bytes),
+ expiresAt: new Date(Date.now() + PRESIGN_TTL_SECONDS * 1000).toISOString(),
+ downloadUrl: url,
+ };
+ },
+ });
+
+ return inner(req, res);
+}
diff --git a/api/x402/dance-tip.js b/api/x402/dance-tip.js
index 42a47f11f..5335e4b98 100644
--- a/api/x402/dance-tip.js
+++ b/api/x402/dance-tip.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 { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/dance-tip';
@@ -259,19 +260,33 @@ export default paidEndpoint({
networks: ['base', 'solana'],
description: DESCRIPTION,
bazaar: BAZAAR,
- async handler({ req, requirement, payer }) {
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+ siwx: {
+ statement: 'Sign in to retrigger a dance you already tipped for.',
+ // Permanent grant — once a wallet has tipped on this endpoint, it can
+ // retrigger any (dancer, dance) combo for free. The ticket itself is
+ // still per-performance (new ticketId each call); SIWX only skips the
+ // payment step, the handler still issues a fresh ticket each call.
+ ttlSeconds: null,
+ expirationSeconds: 300,
+ },
+ async handler({ req, requirement, payer, bypass }) {
const dancer = pickDancer(req.query?.dancer);
const style = pickStyle(req.query?.dance);
const ticketId = crypto.randomUUID();
const now = new Date();
+ // Bypass callers don't carry a paid `requirement`; mark the ticket so the
+ // club_tips ledger + live feed can distinguish free passes from real tips.
const ticket = buildTicket({
dancer,
style,
now,
ticketId,
- payer: payer ?? null,
+ payer: payer ?? (bypass ? bypass.callerId : null),
requirement,
});
+ if (bypass) ticket.bypass = bypass.reason;
// Fire-and-forget: the caller has already paid + the payment is settled
// by the time we reach this handler. A Neon hiccup must not surface as
diff --git a/api/x402/did.js b/api/x402/did.js
new file mode 100644
index 000000000..1ff26a8bb
--- /dev/null
+++ b/api/x402/did.js
@@ -0,0 +1,95 @@
+// /.well-known/did.json — W3C DID Document for the x402 Offer & Receipt
+// extension signing key (USE-17).
+//
+// Verifiers use this to resolve our `kid` back to a public key when checking
+// EIP-712 / JWS signatures on offers and receipts. Per spec §4.5.1, the
+// resolved key is "authorized to sign for the service identified by the
+// payload's resourceUrl" so listing the signer address (eip712) or public JWK
+// (jws) here is the binding between our HTTPS origin and the signing material.
+//
+// Routed via `vercel.json`:
+// /.well-known/did.json → /api/x402/did
+//
+// When no issuer is configured, we return 404 — there's nothing to publish.
+
+import { cors, json, method, error } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { getIssuer } from '../_lib/x402/offer-receipt-issuer.js';
+
+export default async function handler(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ let built;
+ try {
+ built = await getIssuer();
+ } catch (err) {
+ return error(res, 500, 'issuer_misconfigured', err.message);
+ }
+ if (!built) {
+ return error(
+ res,
+ 404,
+ 'not_configured',
+ 'no offer-receipt signing key is configured for this deployment',
+ );
+ }
+
+ const domain = env.SERVER_DOMAIN;
+ const id = `did:web:${domain}`;
+ const verificationMethod = [];
+
+ if (built.format === 'eip712') {
+ // did:pkh authorization for EIP-712 verifiers. The recovered signer
+ // address from any EIP-712 signature MUST match the address embedded
+ // in this entry's blockchainAccountId for the offer/receipt to be
+ // accepted as originating from this resource server.
+ verificationMethod.push({
+ id: built.kid,
+ // EcdsaSecp256k1RecoveryMethod2020 covers Ethereum-style key
+ // recovery; verifiers that pin to a specific scheme (e.g. did:pkh
+ // resolvers) will accept this without further interpretation.
+ type: 'EcdsaSecp256k1RecoveryMethod2020',
+ controller: id,
+ blockchainAccountId: `eip155:1:${built.signerAddress}`,
+ });
+ } else if (built.format === 'jws' && built.publicKey) {
+ verificationMethod.push({
+ id: built.kid,
+ type: 'JsonWebKey2020',
+ controller: id,
+ publicKeyJwk: {
+ ...built.publicKey.jwk,
+ alg: built.publicKey.alg,
+ },
+ });
+ }
+
+ const doc = {
+ '@context': [
+ 'https://www.w3.org/ns/did/v1',
+ 'https://w3id.org/security/suites/jws-2020/v1',
+ 'https://w3id.org/security/suites/secp256k1recovery-2020/v1',
+ ],
+ id,
+ verificationMethod,
+ // The same key authorizes both offer and receipt signing — assertionMethod
+ // is the W3C term that maps cleanly onto "this key signs claims about the
+ // service". authentication is included so DID-aware clients can also use
+ // the key for SIWX-style flows if we wire them up later.
+ assertionMethod: [built.kid],
+ authentication: [built.kid],
+ service: [
+ {
+ id: `${id}#x402`,
+ type: 'x402PaymentService',
+ serviceEndpoint: env.APP_ORIGIN,
+ },
+ ],
+ };
+
+ json(res, 200, doc, {
+ 'content-type': 'application/did+json; charset=utf-8',
+ 'cache-control': 'public, max-age=300',
+ });
+}
diff --git a/api/x402/mint-to-mesh-batch.js b/api/x402/mint-to-mesh-batch.js
index 35336c3f9..624c3aecc 100644
--- a/api/x402/mint-to-mesh-batch.js
+++ b/api/x402/mint-to-mesh-batch.js
@@ -14,6 +14,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 { readJson } from '../_lib/http.js';
import { createThemedGLB, colorFromMint } from '../_lib/glb-themer.js';
import { fetchTokenMeta } from '../_lib/solana-token-meta.js';
@@ -159,6 +160,8 @@ export default paidEndpoint({
networks: ['base', 'solana'],
description: DESCRIPTION,
bazaar: BAZAAR,
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
async handler({ req }) {
let body;
try {
diff --git a/api/x402/mint-to-mesh.js b/api/x402/mint-to-mesh.js
index 3ea65d731..a01d200a3 100644
--- a/api/x402/mint-to-mesh.js
+++ b/api/x402/mint-to-mesh.js
@@ -29,6 +29,21 @@ import {
import { env } from '../_lib/env.js';
import { createThemedGLB, colorFromMint } from '../_lib/glb-themer.js';
import { fetchTokenMeta } from '../_lib/solana-token-meta.js';
+import {
+ PAYMENT_IDENTIFIER,
+ checkCache,
+ extractIdFromHeader,
+ hashRequestPayload,
+ paymentIdentifierExtension,
+ storeResponse,
+ writeCachedResponse,
+ writeConflict,
+} from '../_lib/x402/payment-identifier-server.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+
+const REQUIRED_SCOPE = 'x402:bypass';
+const accessControl = installAccessControl({ requiredScope: REQUIRED_SCOPE });
+const routeConfig = { path: '/api/x402/mint-to-mesh', method: 'GET', requiredScope: REQUIRED_SCOPE };
const ROUTE = '/api/x402/mint-to-mesh';
@@ -211,11 +226,65 @@ export default wrap(async (req, res) => {
accepts: requirements,
description: ROUTE_DESCRIPTION,
bazaar: ROUTE_BAZAAR,
+ extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },
};
+ // USE-23: bypass payment for internal / subscription / OAuth callers.
+ const acResult = await accessControl(req, routeConfig);
+ if (acResult?.abort) {
+ if (acResult.headers) {
+ for (const [k, v] of Object.entries(acResult.headers)) res.setHeader(k, v);
+ }
+ return error(
+ res,
+ acResult.status || 403,
+ acResult.code || 'access_denied',
+ acResult.reason || 'access denied',
+ );
+ }
+ if (acResult?.grantAccess) {
+ const mint = String(req.query?.mint || '').trim();
+ if (!mint) return error(res, 400, 'missing_mint', 'query param "mint" is required');
+ if (!BASE58_RE.test(mint))
+ return error(res, 400, 'invalid_mint', 'mint must be a base58 SPL address (32–44 chars)');
+ let result;
+ try {
+ result = await buildMesh(mint);
+ } catch (err) {
+ return error(res, err.status || 500, err.code || 'internal_error', err.message);
+ }
+ if (acResult.headers) {
+ for (const [k, v] of Object.entries(acResult.headers)) res.setHeader(k, v);
+ }
+ res.setHeader('x-payment-bypass', acResult.reason || 'granted');
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify(result));
+ return;
+ }
+
const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];
if (!paymentHeader) return send402(res, challenge);
+ // USE-15: idempotency cache lookup before paying for /verify.
+ const paymentId = extractIdFromHeader(paymentHeader);
+ const payloadHash = hashRequestPayload({
+ method: req.method,
+ url: req.url,
+ body: null,
+ });
+ if (paymentId) {
+ const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash });
+ if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);
+ if (lookup.kind === 'conflict') {
+ return writeConflict(res, {
+ route: ROUTE,
+ attemptedHash: lookup.attemptedHash,
+ existingHash: lookup.existingHash,
+ });
+ }
+ }
+
let verified;
try {
verified = await verifyPayment({ paymentHeader, requirements });
@@ -246,8 +315,24 @@ export default wrap(async (req, res) => {
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
- res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));
+ const paymentResponseHeader = encodePaymentResponseHeader(settled);
+ const contentType = 'application/json; charset=utf-8';
+ const body = JSON.stringify(result);
+
+ res.setHeader('x-payment-response', paymentResponseHeader);
res.setHeader('cache-control', 'no-store');
- res.setHeader('content-type', 'application/json; charset=utf-8');
- res.end(JSON.stringify(result));
+ res.setHeader('content-type', contentType);
+ res.end(body);
+
+ if (paymentId) {
+ await storeResponse({
+ route: ROUTE,
+ paymentId,
+ payloadHash,
+ status: 200,
+ body,
+ contentType,
+ paymentResponseHeader,
+ });
+ }
});
diff --git a/api/x402/model-check.js b/api/x402/model-check.js
index 3224e8e9f..f24a6d494 100644
--- a/api/x402/model-check.js
+++ b/api/x402/model-check.js
@@ -25,6 +25,21 @@ import {
import { env } from '../_lib/env.js';
import { inspectModel, suggestOptimizations } from '../_lib/model-inspect.js';
import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';
+import {
+ PAYMENT_IDENTIFIER,
+ checkCache,
+ extractIdFromHeader,
+ hashRequestPayload,
+ paymentIdentifierExtension,
+ storeResponse,
+ writeCachedResponse,
+ writeConflict,
+} from '../_lib/x402/payment-identifier-server.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+
+const REQUIRED_SCOPE = 'x402:bypass';
+const accessControl = installAccessControl({ requiredScope: REQUIRED_SCOPE });
+const routeConfig = { path: '/api/x402/model-check', method: 'GET', requiredScope: REQUIRED_SCOPE };
const ROUTE = '/api/x402/model-check';
const MAX_FETCH_BYTES = 16 * 1024 * 1024;
@@ -245,11 +260,64 @@ export default wrap(async (req, res) => {
accepts: requirements,
description: ROUTE_DESCRIPTION,
bazaar: ROUTE_BAZAAR,
+ extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },
};
+ // USE-23: access-control hook short-circuits payment for internal /
+ // subscription / OAuth callers before we even read the X-PAYMENT header.
+ const acResult = await accessControl(req, routeConfig);
+ if (acResult?.abort) {
+ if (acResult.headers) {
+ for (const [k, v] of Object.entries(acResult.headers)) res.setHeader(k, v);
+ }
+ return error(
+ res,
+ acResult.status || 403,
+ acResult.code || 'access_denied',
+ acResult.reason || 'access denied',
+ );
+ }
+ if (acResult?.grantAccess) {
+ const target = String(req.query?.url || '').trim();
+ if (!target) return error(res, 400, 'missing_url', 'query param "url" is required');
+ let result;
+ try {
+ result = await fetchAndInspect(target);
+ } catch (err) {
+ return error(res, err.status || 500, err.code || 'internal_error', err.message);
+ }
+ if (acResult.headers) {
+ for (const [k, v] of Object.entries(acResult.headers)) res.setHeader(k, v);
+ }
+ res.setHeader('x-payment-bypass', acResult.reason || 'granted');
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify(result));
+ return;
+ }
+
const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];
if (!paymentHeader) return send402(res, challenge);
+ // USE-15: idempotency cache lookup before paying for /verify.
+ const paymentId = extractIdFromHeader(paymentHeader);
+ const payloadHash = hashRequestPayload({
+ method: req.method,
+ url: req.url,
+ body: null,
+ });
+ if (paymentId) {
+ const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash });
+ if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);
+ if (lookup.kind === 'conflict') {
+ return writeConflict(res, {
+ route: ROUTE,
+ attemptedHash: lookup.attemptedHash,
+ existingHash: lookup.existingHash,
+ });
+ }
+ }
+
let verified;
try {
verified = await verifyPayment({ paymentHeader, requirements });
@@ -278,8 +346,24 @@ export default wrap(async (req, res) => {
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
- res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));
+ const paymentResponseHeader = encodePaymentResponseHeader(settled);
+ const contentType = 'application/json; charset=utf-8';
+ const body = JSON.stringify(result);
+
+ res.setHeader('x-payment-response', paymentResponseHeader);
res.setHeader('cache-control', 'no-store');
- res.setHeader('content-type', 'application/json; charset=utf-8');
- res.end(JSON.stringify(result));
+ res.setHeader('content-type', contentType);
+ res.end(body);
+
+ if (paymentId) {
+ await storeResponse({
+ route: ROUTE,
+ paymentId,
+ payloadHash,
+ status: 200,
+ body,
+ contentType,
+ paymentResponseHeader,
+ });
+ }
});
diff --git a/api/x402/my-receipts.js b/api/x402/my-receipts.js
new file mode 100644
index 000000000..87b353ec2
--- /dev/null
+++ b/api/x402/my-receipts.js
@@ -0,0 +1,105 @@
+// GET /api/x402/my-receipts?address=0x...&signature=0x...&issuedAt=<iso>&sinceUnix=<n>
+//
+// Buyer-side read endpoint for the x402 Offer & Receipt extension (USE-17).
+// Returns every signed receipt we issued to the requested wallet so a buyer
+// can re-fetch their proof-of-purchase artifacts long after the original
+// payment-response header was dropped from their client.
+//
+// Authentication: the buyer signs a personal_sign message proving control of
+// the wallet whose receipts they're requesting. We recover the signer with
+// viem.verifyMessage; if the recovered address matches `address`, we return
+// the receipt log entries. The signed message includes an `issuedAt` ISO
+// timestamp so old signatures can't be replayed indefinitely (5-minute window).
+//
+// This is EVM-only for now. Solana-payer receipts ARE stored (the receipt log
+// is network-agnostic) but querying them needs a Solana signature flow that
+// isn't wired up here yet — a follow-up endpoint can hit the same storage
+// helper with `payer=<solana-address>`.
+
+import { createPublicClient, http } from 'viem';
+import { mainnet } from 'viem/chains';
+
+import { cors, error, json, method } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { listReceiptsForPayer } from '../_lib/x402/receipt-storage.js';
+
+const MAX_AGE_SECONDS = 300;
+
+// Lightweight viem client used purely for verifyMessage (which works for EOAs
+// and EIP-1271 contract signatures). Mainnet RPC is fine — verifyMessage only
+// hits the chain for contract-wallet sigs, and we use the public default.
+let _client;
+function getClient() {
+ if (!_client) _client = createPublicClient({ chain: mainnet, transport: http() });
+ return _client;
+}
+
+function buildExpectedMessage(address, issuedAt) {
+ return `three.ws x402 receipts read\nAddress: ${address.toLowerCase()}\nIssued At: ${issuedAt}`;
+}
+
+function withinFreshnessWindow(issuedAt) {
+ const ts = Date.parse(issuedAt);
+ if (!Number.isFinite(ts)) return false;
+ const ageSec = (Date.now() - ts) / 1000;
+ return ageSec >= 0 && ageSec <= MAX_AGE_SECONDS;
+}
+
+export default async function handler(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const address = String(url.searchParams.get('address') || '').trim();
+ const signature = String(url.searchParams.get('signature') || '').trim();
+ const issuedAt = String(url.searchParams.get('issuedAt') || '').trim();
+ const sinceUnix = url.searchParams.get('sinceUnix');
+ const limit = url.searchParams.get('limit');
+
+ if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {
+ return error(res, 400, 'invalid_address', 'address must be an EVM 0x-hex address');
+ }
+ if (!/^0x[a-fA-F0-9]+$/.test(signature)) {
+ return error(res, 400, 'invalid_signature', 'signature must be 0x-hex');
+ }
+ if (!issuedAt || !withinFreshnessWindow(issuedAt)) {
+ return error(
+ res,
+ 401,
+ 'stale_signature',
+ `issuedAt must be a recent ISO timestamp (within ${MAX_AGE_SECONDS}s)`,
+ );
+ }
+
+ const message = buildExpectedMessage(address, issuedAt);
+ let valid;
+ try {
+ valid = await getClient().verifyMessage({ address, message, signature });
+ } catch (err) {
+ return error(res, 400, 'signature_check_failed', err.message);
+ }
+ if (!valid) {
+ return error(
+ res,
+ 401,
+ 'invalid_signature',
+ 'signature does not recover to the requested address',
+ );
+ }
+
+ let rows;
+ try {
+ rows = await listReceiptsForPayer({ payer: address, sinceUnix, limit });
+ } catch (err) {
+ return error(res, 502, 'receipt_query_failed', err.message);
+ }
+
+ json(res, 200, {
+ address: address.toLowerCase(),
+ count: rows.length,
+ receipts: rows,
+ });
+}
diff --git a/api/x402/onchain-identity-verify.js b/api/x402/onchain-identity-verify.js
index 6d404e48e..c62d1ba6f 100644
--- a/api/x402/onchain-identity-verify.js
+++ b/api/x402/onchain-identity-verify.js
@@ -14,6 +14,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 { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/onchain-identity-verify';
@@ -170,6 +171,8 @@ export default paidEndpoint({
networks: ['base', 'solana'],
description: DESCRIPTION,
bazaar: BAZAAR,
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
async handler({ req }) {
const agentId = String(req.query?.agent_id || '').trim().toLowerCase();
const chain = String(req.query?.chain || '').trim();
diff --git a/api/x402/permit2-paid-demo.js b/api/x402/permit2-paid-demo.js
index 6a61f4d2f..21266d9b3 100644
--- a/api/x402/permit2-paid-demo.js
+++ b/api/x402/permit2-paid-demo.js
@@ -34,8 +34,12 @@ import {
verifyPayment,
} from '../_lib/x402-spec.js';
import { env } from '../_lib/env.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
const ROUTE = '/api/x402/permit2-paid-demo';
+const REQUIRED_SCOPE = 'x402:bypass';
+const accessControl = installAccessControl({ requiredScope: REQUIRED_SCOPE });
+const routeConfig = { path: ROUTE, method: 'GET', requiredScope: REQUIRED_SCOPE };
const PRICE_ATOMICS = '1000'; // $0.001 USDC (6 decimals)
const ROUTE_DESCRIPTION =
@@ -210,6 +214,47 @@ export default wrap(async (req, res) => {
bazaar: ROUTE_BAZAAR,
};
+ // USE-23: bypass payment for internal / subscription / OAuth callers.
+ // The Permit2 demo skips its payload-shape check on bypass — the bypass
+ // caller never signed a payment, so there's nothing to validate.
+ const acResult = await accessControl(req, routeConfig);
+ if (acResult?.abort) {
+ if (acResult.headers) {
+ for (const [k, v] of Object.entries(acResult.headers)) res.setHeader(k, v);
+ }
+ return error(
+ res,
+ acResult.status || 403,
+ acResult.code || 'access_denied',
+ acResult.reason || 'access denied',
+ );
+ }
+ if (acResult?.grantAccess) {
+ const result = {
+ ok: true,
+ demo: 'permit2-eip2612-gas-sponsoring',
+ method: 'permit2',
+ supportsEip2612: true,
+ bypass: acResult.reason,
+ payer: null,
+ network: requirements[0]?.network || null,
+ asset: requirements[0]?.asset || null,
+ amountAtomics: requirements[0]?.amount || null,
+ transaction: null,
+ explorer: null,
+ settledAt: null,
+ proxy: X402_EXACT_PERMIT2_PROXY,
+ };
+ if (acResult.headers) {
+ for (const [k, v] of Object.entries(acResult.headers)) res.setHeader(k, v);
+ }
+ res.setHeader('x-payment-bypass', acResult.reason || 'granted');
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify(result));
+ return;
+ }
+
const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];
if (!paymentHeader) return send402(res, challenge);
diff --git a/api/x402/pump-agent-audit.js b/api/x402/pump-agent-audit.js
index e076d0eb0..f9a20d128 100644
--- a/api/x402/pump-agent-audit.js
+++ b/api/x402/pump-agent-audit.js
@@ -14,6 +14,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 { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/pump-agent-audit';
@@ -241,6 +242,8 @@ export default paidEndpoint({
networks: ['base', 'solana'],
description: DESCRIPTION,
bazaar: BAZAAR,
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
async handler({ req }) {
const mint = String(req.query?.mint || '').trim();
if (!mint) {
diff --git a/api/x402/skill-marketplace.js b/api/x402/skill-marketplace.js
index ea219dfc7..adb5e3b63 100644
--- a/api/x402/skill-marketplace.js
+++ b/api/x402/skill-marketplace.js
@@ -12,6 +12,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 { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/skill-marketplace';
@@ -187,6 +188,8 @@ export default paidEndpoint({
ttlSeconds: 24 * 3600,
expirationSeconds: 300,
},
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
async handler({ req }) {
const skill = req.query?.skill ? String(req.query.skill).trim() : null;
const limitRaw = parseInt(req.query?.limit, 10);
diff --git a/api/x402/symbol-availability.js b/api/x402/symbol-availability.js
index c2777470d..a50b14070 100644
--- a/api/x402/symbol-availability.js
+++ b/api/x402/symbol-availability.js
@@ -14,6 +14,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 { sql } from '../_lib/db.js';
const ROUTE = '/api/x402/symbol-availability';
@@ -155,6 +156,8 @@ export default paidEndpoint({
networks: ['base', 'solana'],
description: DESCRIPTION,
bazaar: BAZAAR,
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
async handler({ req }) {
const ticker = String(req.query?.ticker || '').trim();
const network = String(req.query?.network || 'mainnet').trim();
diff --git a/mcp-bridge/README.md b/mcp-bridge/README.md
new file mode 100644
index 000000000..cdd89b876
--- /dev/null
+++ b/mcp-bridge/README.md
@@ -0,0 +1,129 @@
+# @3d-agent/mcp-bridge
+
+MCP stdio bridge that turns **any x402-paid HTTP endpoint** into a Claude-callable tool.
+The bridge handles 402 → sign → retry transparently using the [@x402](https://github.com/x402-foundation/x402) SDK.
+
+## What it exposes
+
+On startup the bridge registers:
+
+| Tool | What it does |
+| --------------------- | --------------------------------------------------------------------------------------------------------- |
+| `call_paid_endpoint` | Fallback: hit any URL, auto-pay if it returns 402. Returns the resource response + parsed settlement. |
+| `list_bazaar_tools` | Returns the cached list of Bazaar-discovered tools (name, resource, accepted payment terms). |
+| `refresh_bazaar` | Re-queries the x402 Bazaar and re-registers dynamic tools without restarting. |
+| `paid_<derived>` … | One tool per discovered Bazaar resource (up to `MCP_BRIDGE_DISCOVER_LIMIT`), with that endpoint's schema. |
+
+Payment paths registered on the buyer client:
+
+- `eip155:*` → `BatchSettlementEvmScheme` (preferred when the server advertises it; voucher-based, no per-call gas)
+- `eip155:*` → `ExactEvmScheme` (used when the server advertises `scheme: "exact"`)
+- `solana:*` → `ExactSvmScheme` (USDC SPL transfer co-signed by the advertised fee payer)
+
+Batch-settlement channel state is persisted to `~/.x402-mcp-bridge/channels/client/` so
+Claude Desktop restarts do not re-deposit on the next call.
+
+## Environment
+
+| Variable | Required | Default | Notes |
+| ----------------------------------------- | ----------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
+| `MCP_BRIDGE_EVM_PRIVATE_KEY` | one of EVM/SVM required | — | 0x-prefixed 32-byte hex. Funds USDC payments on Base, Arbitrum, etc. |
+| `MCP_BRIDGE_SVM_PRIVATE_KEY` | one of EVM/SVM required | — | base58 64-byte secret key (Phantom/solana-keygen format) **or** 64-int JSON array. |
+| `MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC` | no | `100000` (= $0.10 USDC at 6 decimals) | Per-call spending cap. Payment aborts above this with a clear reason. |
+| `MCP_BRIDGE_DISCOVER_LIMIT` | no | `20` | Max number of Bazaar tools to register dynamically. Set `0` to disable discovery. |
+| `MCP_BRIDGE_BAZAAR_URL` | no | `https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources` | Override to point at a self-hosted or alternative bazaar. |
+| `MCP_BRIDGE_BATCH_DEPOSIT_MULTIPLIER` | no | `5` | How many request-amounts to deposit at once when opening a batch channel. |
+| `MCP_BRIDGE_MAX_DEPOSIT_ATOMIC` | no | `5000000` (= $5.00 USDC) | Hard cap on the deposit amount per channel open / top-up. |
+| `X402_MCP_BRIDGE_CHANNELS_DIR` | no | `~/.x402-mcp-bridge/channels` | Override the directory used by `FileClientChannelStorage`. |
+| `RPC_URL_<chainId>` | no | viem default public RPC | Per-chain RPC override. Example: `RPC_URL_8453=https://mainnet.base.org`. |
+
+`MCP_BRIDGE_*` env vars also fall back to `EVM_PRIVATE_KEY` / `SVM_PRIVATE_KEY` if you
+already have those set for the rest of this repo.
+
+## Smoke test (without Claude Desktop)
+
+```bash
+# Once env is set, list the registered tools via the MCP inspector
+npx @modelcontextprotocol/inspector node mcp-bridge/src/index.js
+```
+
+The inspector connects over stdio, lists the static tools (`call_paid_endpoint`,
+`list_bazaar_tools`, `refresh_bazaar`), and one dynamic tool per discovered Bazaar entry.
+
+## Claude Desktop config
+
+Paste this into `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS
+(or `%APPDATA%\Claude\claude_desktop_config.json` on Windows):
+
+```json
+{
+ "mcpServers": {
+ "x402-bridge": {
+ "command": "node",
+ "args": ["/absolute/path/to/three.ws/mcp-bridge/src/index.js"],
+ "env": {
+ "MCP_BRIDGE_EVM_PRIVATE_KEY": "0x…your buyer key…",
+ "MCP_BRIDGE_SVM_PRIVATE_KEY": "…base58 64-byte secret key…",
+ "MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC": "100000",
+ "MCP_BRIDGE_DISCOVER_LIMIT": "20"
+ }
+ }
+ }
+}
+```
+
+Restart Claude Desktop. The bridge appears under **Settings → Developer → MCP servers**;
+expand it to confirm the tool list. Asking Claude something like
+"pay $0.01 on Base for a weather report" causes it to pick a matching Bazaar tool, call
+the bridge, and the bridge auto-pays via x402.
+
+## Cursor config
+
+`~/.cursor/mcp.json`:
+
+```json
+{
+ "mcpServers": {
+ "x402-bridge": {
+ "command": "node",
+ "args": ["/absolute/path/to/three.ws/mcp-bridge/src/index.js"],
+ "env": {
+ "MCP_BRIDGE_EVM_PRIVATE_KEY": "0x…",
+ "MCP_BRIDGE_SVM_PRIVATE_KEY": "…"
+ }
+ }
+ }
+}
+```
+
+## Server-to-server use
+
+Inside this repo, any module that wants to consume an x402 endpoint can import
+the buyer factory directly:
+
+```js
+import { buildBuyerAxios } from '../mcp-bridge/src/x402-axios-client.js';
+
+const { api } = await buildBuyerAxios();
+const res = await api.get('https://api.example.com/some-paid-resource');
+```
+
+The same spending cap and channel-storage rules apply.
+
+## Spending cap behavior
+
+`onBeforePaymentCreation` inspects the selected `accepts` entry and aborts payload
+creation if `amount` (atomic units) exceeds `MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC`.
+The tool result then carries a clear error message naming the network, asset, and
+the cap that was exceeded — useful for the LLM to decide whether to ask the user
+to raise the limit.
+
+## Cooperative refunds
+
+Idle batch channels can be refunded out-of-band with the SDK:
+
+```js
+import { buildBuyerAxios } from './mcp-bridge/src/x402-axios-client.js';
+// then call client.refund(resourceUrl, { amount }) once USE-09's
+// scripts/x402-batch-refund.mjs lands; until then refunds run via the SDK directly.
+```
diff --git a/mcp-bridge/package.json b/mcp-bridge/package.json
new file mode 100644
index 000000000..659c45823
--- /dev/null
+++ b/mcp-bridge/package.json
@@ -0,0 +1,29 @@
+{
+ "name": "@3d-agent/mcp-bridge",
+ "version": "1.0.0",
+ "private": true,
+ "description": "MCP stdio bridge that turns any x402-paid HTTP endpoint into a Claude-callable tool. Auto-pays via the @x402 client (EVM exact, SVM exact, EVM batch-settlement) and pre-loads tools from the Coinbase x402 Bazaar.",
+ "type": "module",
+ "bin": {
+ "x402-mcp-bridge": "./src/index.js"
+ },
+ "main": "./src/index.js",
+ "scripts": {
+ "start": "node src/index.js"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.29.0",
+ "@solana/kit": "^6.8.0",
+ "@x402/axios": "^2.12.0",
+ "@x402/core": "^2.12.0",
+ "@x402/evm": "^2.12.0",
+ "@x402/svm": "^2.12.0",
+ "axios": "^1.7.0",
+ "bs58": "^6.0.0",
+ "viem": "^2.18.0",
+ "zod": "^3.23.8"
+ }
+}
diff --git a/mcp-bridge/src/bazaar-discover.js b/mcp-bridge/src/bazaar-discover.js
new file mode 100644
index 000000000..29b9daa26
--- /dev/null
+++ b/mcp-bridge/src/bazaar-discover.js
@@ -0,0 +1,165 @@
+// Queries the Coinbase x402 Bazaar (and any other configured catalog) for
+// discoverable resources and returns a normalized list of MCP tool specs.
+//
+// The Bazaar `/discovery/resources` endpoint returns items shaped roughly:
+// {
+// resource: "https://...",
+// type: "http" | "mcp",
+// description: "...",
+// accepts: [{ scheme, network, amount, asset, payTo, extra, maxTimeoutSeconds }, ...],
+// extensions: { bazaar: { info: { input: {...}, output: {...} }, schema: {...} } },
+// quality: { l30DaysTotalCalls, ... },
+// }
+//
+// We use `extensions.bazaar.info.input` to know HOW to call the resource
+// (HTTP method, body/queryParams shape) and `extensions.bazaar.schema` to
+// surface a concrete JSON Schema for the tool's input parameters in the
+// tool description.
+//
+// Tools whose accepts entries are ALL above the configured spending cap are
+// filtered out at discovery time so the LLM doesn't see tools it can't afford.
+
+import axios from 'axios';
+
+const DEFAULT_LIMIT = 20;
+const DEFAULT_BAZAAR_URL = 'https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources';
+
+function bazaarUrl() {
+ const override = process.env.MCP_BRIDGE_BAZAAR_URL;
+ return override && override.trim() ? override.trim() : DEFAULT_BAZAAR_URL;
+}
+
+function discoverLimit() {
+ const raw = process.env.MCP_BRIDGE_DISCOVER_LIMIT;
+ if (!raw) return DEFAULT_LIMIT;
+ const v = Number(raw);
+ if (!Number.isFinite(v) || v < 0) {
+ throw new Error('MCP_BRIDGE_DISCOVER_LIMIT must be a non-negative number');
+ }
+ return Math.floor(v);
+}
+
+function maxPriceAtomic() {
+ const raw = process.env.MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC;
+ if (!raw) return null;
+ return BigInt(raw);
+}
+
+// Derive a stable MCP tool name from a Bazaar item.
+//
+// MCP tool names must be unique and conventionally are snake_case identifiers.
+// We start from the description's first segment (everything before "—" or "·")
+// and fall back to the URL path. Sanitize to [a-z0-9_], cap length, and
+// disambiguate collisions with a numeric suffix in the caller.
+const NAME_PREFIX = 'paid_';
+
+export function deriveToolName(item) {
+ const desc = String(item.description || '').trim();
+ const first = desc.split(/[—·:|]/)[0]?.trim() || '';
+ let base = first || new URL(item.resource).pathname.split('/').filter(Boolean).pop() || 'tool';
+ base = base
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '_')
+ .replace(/^_+|_+$/g, '')
+ .slice(0, 48);
+ if (!base) base = 'tool';
+ return `${NAME_PREFIX}${base}`;
+}
+
+function pickInputJsonSchema(item) {
+ const schema = item?.extensions?.bazaar?.schema;
+ if (schema && typeof schema === 'object' && schema.properties?.input) {
+ return schema.properties.input;
+ }
+ // Some entries publish inputSchema at the top level (legacy v1 shape).
+ const legacy = item?.extensions?.bazaar?.inputSchema || item?.inputSchema;
+ return legacy && typeof legacy === 'object' ? legacy : undefined;
+}
+
+function summarizeAccepts(accepts) {
+ return accepts
+ .map((a) => `${a.scheme}@${a.network} ${a.amount} ${a.asset}`)
+ .join(' | ');
+}
+
+function affordable(accepts) {
+ const cap = maxPriceAtomic();
+ if (cap === null) return true;
+ return accepts.some((a) => {
+ try {
+ return BigInt(a.amount) <= cap;
+ } catch {
+ return false;
+ }
+ });
+}
+
+export async function fetchBazaarResources({ url = bazaarUrl(), limit = discoverLimit() } = {}) {
+ if (limit === 0) return [];
+ const res = await axios.get(url, {
+ params: { limit },
+ timeout: 15_000,
+ validateStatus: (s) => s >= 200 && s < 300,
+ });
+ const items = Array.isArray(res.data?.items) ? res.data.items : [];
+ return items;
+}
+
+export function buildToolSpec(item) {
+ const accepts = Array.isArray(item.accepts) ? item.accepts : [];
+ if (accepts.length === 0) return null;
+ if (!affordable(accepts)) return null;
+
+ const info = item?.extensions?.bazaar?.info;
+ const input = info?.input || {};
+ const method = (input.method || 'GET').toUpperCase();
+ const type = info?.type || item.type || 'http';
+ const inputJsonSchema = pickInputJsonSchema(item);
+
+ const acceptSummary = summarizeAccepts(accepts);
+ const descriptionLines = [
+ item.description?.trim() || `Paid endpoint at ${item.resource}`,
+ '',
+ `Auto-paid via x402 (${acceptSummary}).`,
+ `Method: ${method}. Resource: ${item.resource}`,
+ ];
+ if (inputJsonSchema) {
+ descriptionLines.push('', 'Input JSON Schema:', JSON.stringify(inputJsonSchema));
+ }
+ if (info?.output?.example) {
+ descriptionLines.push('', 'Output example:', JSON.stringify(info.output.example).slice(0, 1500));
+ }
+
+ return {
+ name: deriveToolName(item),
+ description: descriptionLines.join('\n'),
+ resource: item.resource,
+ method,
+ type,
+ bodyType: input.bodyType || 'json',
+ inputJsonSchema,
+ acceptSummary,
+ };
+}
+
+export async function discoverBazaarTools(opts = {}) {
+ const items = await fetchBazaarResources(opts);
+ const specs = [];
+ const seen = new Set();
+ for (const item of items) {
+ try {
+ const spec = buildToolSpec(item);
+ if (!spec) continue;
+ let name = spec.name;
+ let i = 1;
+ while (seen.has(name)) {
+ name = `${spec.name}_${i++}`;
+ }
+ seen.add(name);
+ specs.push({ ...spec, name });
+ } catch {
+ // Malformed entry — skip so one bad item doesn't take the whole bridge down.
+ }
+ }
+ return specs;
+}
diff --git a/mcp-bridge/src/index.js b/mcp-bridge/src/index.js
new file mode 100755
index 000000000..d7fb8557e
--- /dev/null
+++ b/mcp-bridge/src/index.js
@@ -0,0 +1,278 @@
+#!/usr/bin/env node
+// MCP stdio bridge: exposes the x402 ecosystem as Claude-callable tools.
+//
+// Tools registered on startup:
+// 1. call_paid_endpoint(url, method?, body?, params?, headers?) — universal
+// fallback. Hits ANY x402-paid URL with auto-payment.
+// 2. list_bazaar_tools() — returns the cached set of Bazaar-discovered tools.
+// 3. refresh_bazaar() — re-runs Bazaar discovery and re-registers tools.
+// 4. One dynamic tool per Bazaar resource (up to MCP_BRIDGE_DISCOVER_LIMIT).
+// Each dynamic tool's input shape is permissive (body/queryParams/pathParams)
+// so we can pass through whatever the LLM constructs. The bazaar's
+// published JSON Schema is included in the tool DESCRIPTION so the LLM
+// can see required fields without us converting the schema to Zod.
+//
+// Transport: stdio. Claude Desktop launches the bridge with this server file
+// as `command` and reads/writes JSON-RPC frames over stdin/stdout.
+
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
+import { z } from 'zod';
+
+import { buildBuyerAxios, extractReceipt } from './x402-axios-client.js';
+import { discoverBazaarTools } from './bazaar-discover.js';
+
+const BRIDGE_NAME = '3d-agent-x402-bridge';
+const BRIDGE_VERSION = '1.0.0';
+
+const log = (...args) => {
+ // MCP stdio: stdout is reserved for protocol frames. Diagnostics MUST go
+ // to stderr so the transport stays parseable.
+ process.stderr.write(`[${BRIDGE_NAME}] ${args.map(String).join(' ')}\n`);
+};
+
+function asTextContent(value) {
+ const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
+ return { content: [{ type: 'text', text }] };
+}
+
+function asErrorContent(message) {
+ return {
+ isError: true,
+ content: [{ type: 'text', text: message }],
+ };
+}
+
+function decodePaymentResponseFromHeaders(headers) {
+ if (!headers) return undefined;
+ const raw = headers['x-payment-response'] ?? headers['X-PAYMENT-RESPONSE'];
+ if (!raw || typeof raw !== 'string') return undefined;
+ try {
+ return JSON.parse(Buffer.from(raw, 'base64').toString('utf8'));
+ } catch {
+ return undefined;
+ }
+}
+
+async function callPaidEndpoint({ api, httpClient }, args) {
+ const { url, method = 'GET', body, params, headers } = args;
+ const normalizedMethod = String(method).toUpperCase();
+ const hasBody = body !== undefined && body !== null;
+ const res = await api.request({
+ url,
+ method: normalizedMethod,
+ data: hasBody ? body : undefined,
+ params,
+ headers: headers ?? undefined,
+ });
+ const receipt =
+ extractReceipt(httpClient, res) ?? decodePaymentResponseFromHeaders(res.headers);
+ return {
+ status: res.status,
+ data: res.data,
+ paymentReceipt: receipt ?? null,
+ };
+}
+
+function registerCallPaidEndpoint(server, deps) {
+ server.registerTool(
+ 'call_paid_endpoint',
+ {
+ title: 'Call any x402-paid endpoint',
+ description:
+ 'Calls any HTTP URL that returns 402 with x402 payment requirements, automatically signing and paying. ' +
+ 'Supports EVM exact, EVM batch-settlement, and Solana exact schemes. ' +
+ 'Returns the resource response plus the parsed settlement receipt.',
+ inputSchema: {
+ url: z.string().url().describe('Full URL of the x402-paid resource'),
+ method: z
+ .enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD'])
+ .optional()
+ .describe('HTTP method. Defaults to GET.'),
+ body: z
+ .any()
+ .optional()
+ .describe('Request body for POST/PUT/PATCH. Will be JSON-encoded.'),
+ params: z
+ .record(z.any())
+ .optional()
+ .describe('Query string parameters as an object.'),
+ headers: z
+ .record(z.string())
+ .optional()
+ .describe('Additional request headers (do NOT set X-PAYMENT manually).'),
+ },
+ },
+ async (args) => {
+ try {
+ const result = await callPaidEndpoint(deps, args);
+ return asTextContent(result);
+ } catch (err) {
+ return asErrorContent(`call_paid_endpoint failed: ${err?.message || err}`);
+ }
+ },
+ );
+}
+
+function registerListBazaarTools(server, getCached) {
+ server.registerTool(
+ 'list_bazaar_tools',
+ {
+ title: 'List Bazaar-discovered tools',
+ description:
+ 'Returns the cached list of x402 Bazaar resources registered as MCP tools on this bridge.',
+ inputSchema: {},
+ },
+ async () => {
+ const cached = getCached();
+ return asTextContent(
+ cached.map(({ name, resource, method, acceptSummary, description }) => ({
+ name,
+ resource,
+ method,
+ accepts: acceptSummary,
+ description: description.split('\n')[0],
+ })),
+ );
+ },
+ );
+}
+
+function registerRefreshBazaar(server, refresh) {
+ server.registerTool(
+ 'refresh_bazaar',
+ {
+ title: 'Refresh Bazaar discovery',
+ description:
+ 'Re-queries the x402 Bazaar discovery endpoint and re-registers dynamic tools. Use when new paid services have been added since the bridge started.',
+ inputSchema: {},
+ },
+ async () => {
+ const { added, removed, total } = await refresh();
+ return asTextContent({ added, removed, total });
+ },
+ );
+}
+
+function buildDynamicHandler(deps, spec) {
+ return async (args) => {
+ try {
+ const { body, params, pathParams, headers } = args || {};
+ let url = spec.resource;
+ if (pathParams && typeof pathParams === 'object') {
+ // Replace `{name}` placeholders with the supplied path params.
+ for (const [key, value] of Object.entries(pathParams)) {
+ url = url.replace(`{${key}}`, encodeURIComponent(String(value)));
+ }
+ }
+ const result = await callPaidEndpoint(deps, {
+ url,
+ method: spec.method,
+ body,
+ params,
+ headers,
+ });
+ return asTextContent(result);
+ } catch (err) {
+ return asErrorContent(`${spec.name} failed: ${err?.message || err}`);
+ }
+ };
+}
+
+function buildDynamicInputSchema() {
+ return {
+ body: z
+ .any()
+ .optional()
+ .describe(
+ 'Request body (object). Required when the bazaar input schema declares body fields. JSON-encoded automatically.',
+ ),
+ params: z
+ .record(z.any())
+ .optional()
+ .describe('Query string parameters as an object.'),
+ pathParams: z
+ .record(z.union([z.string(), z.number()]))
+ .optional()
+ .describe('Values for `{name}` placeholders in the resource URL.'),
+ headers: z.record(z.string()).optional().describe('Additional request headers.'),
+ };
+}
+
+function registerDynamic(server, deps, spec) {
+ const inputSchema = buildDynamicInputSchema();
+ const registered = server.registerTool(
+ spec.name,
+ {
+ title: spec.name,
+ description: spec.description,
+ inputSchema,
+ },
+ buildDynamicHandler(deps, spec),
+ );
+ return registered;
+}
+
+async function main() {
+ const deps = await buildBuyerAxios();
+ log('signers ready, building MCP server');
+
+ const server = new McpServer({ name: BRIDGE_NAME, version: BRIDGE_VERSION });
+
+ let cachedSpecs = [];
+ const dynamicRegs = new Map();
+
+ const refresh = async () => {
+ const next = await discoverBazaarTools();
+ const nextByName = new Map(next.map((s) => [s.name, s]));
+ const prevByName = new Map(cachedSpecs.map((s) => [s.name, s]));
+
+ let removed = 0;
+ for (const [name, reg] of dynamicRegs.entries()) {
+ if (!nextByName.has(name)) {
+ if (typeof reg.remove === 'function') {
+ reg.remove();
+ } else if (typeof reg.disable === 'function') {
+ reg.disable();
+ }
+ dynamicRegs.delete(name);
+ removed++;
+ }
+ }
+
+ let added = 0;
+ for (const spec of next) {
+ if (prevByName.has(spec.name)) continue;
+ try {
+ const reg = registerDynamic(server, deps, spec);
+ dynamicRegs.set(spec.name, reg);
+ added++;
+ } catch (err) {
+ log(`failed to register dynamic tool ${spec.name}:`, err?.message || err);
+ }
+ }
+
+ cachedSpecs = next;
+ log(`bazaar discovery: ${next.length} tools (added=${added}, removed=${removed})`);
+ return { added, removed, total: next.length };
+ };
+
+ registerCallPaidEndpoint(server, deps);
+ registerListBazaarTools(server, () => cachedSpecs);
+ registerRefreshBazaar(server, refresh);
+
+ try {
+ await refresh();
+ } catch (err) {
+ log('bazaar discovery failed at startup (continuing without dynamic tools):', err?.message || err);
+ }
+
+ const transport = new StdioServerTransport();
+ await server.connect(transport);
+ log('connected via stdio');
+}
+
+main().catch((err) => {
+ log('fatal:', err?.stack || err?.message || err);
+ process.exit(1);
+});
diff --git a/mcp-bridge/src/signers.js b/mcp-bridge/src/signers.js
new file mode 100644
index 000000000..d54b0310f
--- /dev/null
+++ b/mcp-bridge/src/signers.js
@@ -0,0 +1,77 @@
+// EVM and SVM signer factories for the bridge.
+//
+// EVM: viem account from `MCP_BRIDGE_EVM_PRIVATE_KEY` (0x-prefixed 32-byte hex).
+// We attach a viem PublicClient so the extension-enrichment paths
+// (EIP-2612 permit, ERC-20 approval) can read on-chain state — required
+// for Permit2 endpoints that opt into gas sponsoring.
+//
+// SVM: @solana/kit KeyPairSigner from `MCP_BRIDGE_SVM_PRIVATE_KEY`. Accepts
+// either a base58-encoded 64-byte secret key (the format Phantom and
+// `solana-keygen` print) or a JSON array of 64 integers (the format
+// `~/.config/solana/id.json` stores). The 64 bytes are the secret-key
+// pair: 32-byte private seed followed by 32-byte public key.
+//
+// Both functions throw with an explicit message naming the missing env var
+// the first time a network is needed. They return `null` if the env is unset,
+// so the caller can decide whether to fail fast or skip that network.
+
+import bs58 from 'bs58';
+import { createKeyPairSignerFromBytes } from '@solana/kit';
+import { privateKeyToAccount } from 'viem/accounts';
+import { createPublicClient, http, publicActions, createWalletClient } from 'viem';
+import { base, baseSepolia, mainnet, polygon, arbitrum } from 'viem/chains';
+import { toClientEvmSigner } from '@x402/evm';
+
+const VIEM_CHAIN_BY_ID = new Map(
+ [mainnet, base, baseSepolia, polygon, arbitrum].map((c) => [c.id, c]),
+);
+
+function rpcUrlFor(chainId) {
+ const explicit = process.env[`RPC_URL_${chainId}`];
+ if (explicit) return explicit;
+ return undefined;
+}
+
+export function getEvmSigner({ chainId } = {}) {
+ const key = process.env.MCP_BRIDGE_EVM_PRIVATE_KEY || process.env.EVM_PRIVATE_KEY;
+ if (!key) return null;
+ const normalized = key.startsWith('0x') ? key : `0x${key}`;
+ const account = privateKeyToAccount(normalized);
+
+ // Pick a chain for the publicClient. Default to Base mainnet — the
+ // extension-enrichment readContract calls only matter for assets on the
+ // chain we're actually paying on, and Base is the dominant x402 EVM chain.
+ const chain = (chainId && VIEM_CHAIN_BY_ID.get(chainId)) || base;
+ const transport = http(rpcUrlFor(chain.id));
+ const publicClient = createPublicClient({ chain, transport });
+ const walletClient = createWalletClient({ account, chain, transport }).extend(publicActions);
+
+ // `toClientEvmSigner` composes the optional readContract / nonce / fee
+ // helpers off the public client onto the account so Permit2 flows work.
+ return toClientEvmSigner(walletClient, publicClient);
+}
+
+function decodeSvmSecretKey(raw) {
+ const trimmed = raw.trim();
+ if (trimmed.startsWith('[')) {
+ const arr = JSON.parse(trimmed);
+ if (!Array.isArray(arr) || arr.length !== 64) {
+ throw new Error('MCP_BRIDGE_SVM_PRIVATE_KEY JSON must be a 64-element byte array');
+ }
+ return Uint8Array.from(arr);
+ }
+ const bytes = bs58.decode(trimmed);
+ if (bytes.length !== 64) {
+ throw new Error(
+ `MCP_BRIDGE_SVM_PRIVATE_KEY decoded to ${bytes.length} bytes, expected 64 (secret-key pair).`,
+ );
+ }
+ return bytes;
+}
+
+export async function getSvmSigner() {
+ const raw = process.env.MCP_BRIDGE_SVM_PRIVATE_KEY || process.env.SVM_PRIVATE_KEY;
+ if (!raw) return null;
+ const bytes = decodeSvmSecretKey(raw);
+ return createKeyPairSignerFromBytes(bytes);
+}
diff --git a/mcp-bridge/src/storage.js b/mcp-bridge/src/storage.js
new file mode 100644
index 000000000..9a06cf31b
--- /dev/null
+++ b/mcp-bridge/src/storage.js
@@ -0,0 +1,17 @@
+// Channel storage directory for the batch-settlement scheme.
+//
+// FileClientChannelStorage writes one JSON per channel into `{root}/client/`.
+// We pin the root at `~/.x402-mcp-bridge/channels` so the bridge survives
+// Claude Desktop restarts — the second call to a batch endpoint reads the
+// voucher state written by the first, instead of redepositing.
+
+import { mkdirSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+
+export function getChannelsDirectory() {
+ const override = process.env.X402_MCP_BRIDGE_CHANNELS_DIR;
+ const root = override && override.trim() ? override : join(homedir(), '.x402-mcp-bridge', 'channels');
+ mkdirSync(join(root, 'client'), { recursive: true });
+ return root;
+}
diff --git a/mcp-bridge/src/x402-axios-client.js b/mcp-bridge/src/x402-axios-client.js
new file mode 100644
index 000000000..5955d5c7a
--- /dev/null
+++ b/mcp-bridge/src/x402-axios-client.js
@@ -0,0 +1,142 @@
+// Builds a single axios instance wrapped with the @x402 client.
+//
+// Registers, in order of priority:
+// - eip155:* → BatchSettlementEvmScheme (cheaper per-call, channel-backed)
+// - eip155:* → ExactEvmScheme (used when a server doesn't advertise
+// batch-settlement for the network)
+// - solana:* → ExactSvmScheme (USDC SPL transfers, fee-payer co-signed)
+//
+// The @x402 core client picks scheme-per-network based on what the 402
+// response advertises in `accepts[].scheme`, so registering both EVM schemes
+// against the same wildcard is correct: the scheme whose name matches the
+// server's selected accept wins.
+//
+// Spending cap: `onBeforePaymentCreation` aborts payload creation when the
+// selected accept's `amount` (atomic units) exceeds
+// `MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC`. The default cap is 100_000 atomic
+// units of USDC = $0.10. Set the env explicitly for higher-cost endpoints.
+//
+// Channel storage: `FileClientChannelStorage` persists voucher + cumulative
+// amount per channel under `~/.x402-mcp-bridge/channels/client/`. Restart-safe.
+
+import axios from 'axios';
+import { x402Client, x402HTTPClient } from '@x402/core/client';
+import { wrapAxiosWithPayment } from '@x402/axios';
+import { ExactEvmScheme } from '@x402/evm/exact/client';
+import {
+ BatchSettlementEvmScheme,
+ FileClientChannelStorage,
+} from '@x402/evm/batch-settlement/client';
+import { ExactSvmScheme } from '@x402/svm/exact/client';
+
+import { getEvmSigner, getSvmSigner } from './signers.js';
+import { getChannelsDirectory } from './storage.js';
+
+const DEFAULT_MAX_PRICE_ATOMIC = 100_000n; // $0.10 USDC
+const DEFAULT_DEPOSIT_MULTIPLIER = 5;
+const DEFAULT_MAX_DEPOSIT_ATOMIC = 5_000_000n; // $5.00 USDC cap on a single deposit
+
+function maxPriceAtomic() {
+ const raw = process.env.MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC;
+ if (!raw) return DEFAULT_MAX_PRICE_ATOMIC;
+ const v = BigInt(raw);
+ if (v < 0n) throw new Error('MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC must be non-negative');
+ return v;
+}
+
+function maxDepositAtomic() {
+ const raw = process.env.MCP_BRIDGE_MAX_DEPOSIT_ATOMIC;
+ if (!raw) return DEFAULT_MAX_DEPOSIT_ATOMIC;
+ return BigInt(raw);
+}
+
+function depositMultiplier() {
+ const raw = process.env.MCP_BRIDGE_BATCH_DEPOSIT_MULTIPLIER;
+ if (!raw) return DEFAULT_DEPOSIT_MULTIPLIER;
+ const v = Number(raw);
+ if (!Number.isFinite(v) || v < 1) {
+ throw new Error('MCP_BRIDGE_BATCH_DEPOSIT_MULTIPLIER must be a number >= 1');
+ }
+ return v;
+}
+
+function buildSpendingCapHook() {
+ const cap = maxPriceAtomic();
+ return async ({ selectedRequirements }) => {
+ const amount = BigInt(selectedRequirements?.amount ?? '0');
+ if (amount > cap) {
+ return {
+ abort: true,
+ reason: `selected accept amount ${amount} exceeds spending cap ${cap} (set MCP_BRIDGE_MAX_PRICE_PER_CALL_ATOMIC to override) — network=${selectedRequirements?.network}, asset=${selectedRequirements?.asset}`,
+ };
+ }
+ return undefined;
+ };
+}
+
+function buildDepositStrategy() {
+ const cap = maxDepositAtomic();
+ return ({ depositAmount }) => {
+ const amt = BigInt(depositAmount);
+ if (amt > cap) return cap.toString();
+ return undefined;
+ };
+}
+
+let cachedAxios;
+
+export async function buildBuyerAxios() {
+ if (cachedAxios) return cachedAxios;
+
+ const client = new x402Client();
+ client.onBeforePaymentCreation(buildSpendingCapHook());
+
+ const evmSigner = getEvmSigner();
+ if (evmSigner) {
+ // Register batch-settlement first so it wins when a server advertises
+ // scheme="batch-settlement". For scheme="exact" the core client picks
+ // ExactEvmScheme — both are registered under the same wildcard.
+ const batchScheme = new BatchSettlementEvmScheme(evmSigner, {
+ storage: new FileClientChannelStorage({ directory: getChannelsDirectory() }),
+ depositPolicy: { depositMultiplier: depositMultiplier() },
+ depositStrategy: buildDepositStrategy(),
+ });
+ client.register('eip155:*', batchScheme);
+ client.register('eip155:*', new ExactEvmScheme(evmSigner));
+ }
+
+ const svmSigner = await getSvmSigner();
+ if (svmSigner) {
+ client.register('solana:*', new ExactSvmScheme(svmSigner));
+ }
+
+ if (!evmSigner && !svmSigner) {
+ throw new Error(
+ 'No payment signers configured. Set MCP_BRIDGE_EVM_PRIVATE_KEY and/or MCP_BRIDGE_SVM_PRIVATE_KEY before starting the bridge.',
+ );
+ }
+
+ const httpClient = new x402HTTPClient(client);
+ const api = wrapAxiosWithPayment(
+ axios.create({
+ timeout: 60_000,
+ // Surface 4xx/5xx as rejections so the bridge returns errors to the LLM
+ // instead of silently producing a "success" tool result with an error body.
+ validateStatus: (s) => s >= 200 && s < 300,
+ }),
+ client,
+ );
+
+ cachedAxios = { api, client, httpClient };
+ return cachedAxios;
+}
+
+export function extractReceipt(httpClient, response) {
+ if (!response || !response.headers) return undefined;
+ const getHeader = (name) => response.headers[name] ?? response.headers[name.toLowerCase()];
+ try {
+ return httpClient.getPaymentSettleResponse(getHeader);
+ } catch {
+ return undefined;
+ }
+}
diff --git a/mcp-server/package.json b/mcp-server/package.json
new file mode 100644
index 000000000..69e1ee999
--- /dev/null
+++ b/mcp-server/package.json
@@ -0,0 +1,33 @@
+{
+ "name": "@3d-agent/mcp-server",
+ "version": "1.0.0",
+ "description": "Paid MCP tools for the 3d-agent stack — pose generation, pump.fun snapshots, ERC-8004 agent reputation, Solana vanity grinder. Settled in USDC via x402.",
+ "type": "module",
+ "private": true,
+ "bin": {
+ "3d-agent-mcp": "./src/index.js"
+ },
+ "main": "./src/index.js",
+ "exports": {
+ ".": "./src/index.js"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "scripts": {
+ "start": "node src/index.js",
+ "inspect": "npx -y @modelcontextprotocol/inspector node src/index.js"
+ },
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.29.0",
+ "@solana/web3.js": "latest",
+ "@x402/core": "^2.12.0",
+ "@x402/evm": "^2.12.0",
+ "@x402/extensions": "^2.12.0",
+ "@x402/mcp": "^2.12.0",
+ "@x402/svm": "^2.12.0",
+ "@coinbase/x402": "^2.1.0",
+ "ethers": "^6.16.0",
+ "zod": "^3.23.8"
+ }
+}
diff --git a/mcp-server/src/payments.js b/mcp-server/src/payments.js
new file mode 100644
index 000000000..3681c361a
--- /dev/null
+++ b/mcp-server/src/payments.js
@@ -0,0 +1,277 @@
+// Shared x402 payment wiring for paid MCP tools.
+//
+// Every tool in mcp-server/src/tools/*.js wraps its handler in
+// `paid(toolName, { schemeName, priceUsd, networks, inputSchema, ...}, fn)`.
+// This file builds the single shared x402ResourceServer (one per process)
+// that verifies + settles against the configured facilitators, and exposes
+// `paid()` that produces the McpServer.tool() callback per the @x402/mcp
+// transport spec (PaymentRequired in structuredContent + content[0].text,
+// settlement response under _meta["x402/payment-response"]).
+//
+// Networks supported here:
+// - Base mainnet (eip155:8453) via CDP when CDP_API_KEY_ID/CDP_API_KEY_SECRET
+// are set, else via PayAI's facilitator. Receiver: MCP_EVM_PAYMENT_ADDRESS
+// (falls back to X402_PAY_TO_BASE).
+// - Solana mainnet via PayAI's Solana facilitator. Receiver:
+// MCP_SVM_PAYMENT_ADDRESS (falls back to X402_PAY_TO_SOLANA).
+//
+// Both EVM `exact` + `upto` are registered so the vanity grinder can use
+// upto-style metered billing while the other tools stay on exact.
+//
+// `createPaymentWrapper` from @x402/mcp returns a function that wraps your
+// async tool handler into an MCP-compatible callback. It handles the entire
+// 402 dance: returns a 402 PaymentRequired result with both structuredContent
+// + content[0].text when the client calls without _meta["x402/payment"];
+// verifies the payment, runs the handler, settles, and attaches the
+// SettleResponse to _meta["x402/payment-response"].
+
+import { createCdpAuthHeaders } from '@coinbase/x402';
+import { HTTPFacilitatorClient, x402ResourceServer } from '@x402/core/server';
+import { registerExactEvmScheme } from '@x402/evm/exact/server';
+import { UptoEvmScheme as UptoEvmServerScheme } from '@x402/evm/upto/server';
+import { registerExactSvmScheme } from '@x402/svm/exact/server';
+import { createPaymentWrapper, createToolResourceUrl } from '@x402/mcp';
+import { declareDiscoveryExtension } from '@x402/extensions/bazaar';
+
+// CAIP-2 IDs we care about (mirrors api/_lib/x402-spec.js).
+const NETWORK_BASE_MAINNET = 'eip155:8453';
+const NETWORK_SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
+
+const DEFAULT_BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
+const DEFAULT_SOLANA_USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+const env = (key, fallback) => {
+ const v = process.env[key];
+ return v && v.trim() ? v.trim() : fallback;
+};
+
+function requireEvmPayTo() {
+ const addr = env('MCP_EVM_PAYMENT_ADDRESS') || env('X402_PAY_TO_BASE');
+ if (!addr) {
+ throw new Error(
+ 'mcp-server: set MCP_EVM_PAYMENT_ADDRESS (or X402_PAY_TO_BASE) to receive Base USDC payments',
+ );
+ }
+ return addr;
+}
+
+function requireSvmPayTo() {
+ const addr = env('MCP_SVM_PAYMENT_ADDRESS') || env('X402_PAY_TO_SOLANA') || env('X402_PAY_TO');
+ if (!addr) {
+ throw new Error(
+ 'mcp-server: set MCP_SVM_PAYMENT_ADDRESS (or X402_PAY_TO_SOLANA / X402_PAY_TO) to receive Solana USDC payments',
+ );
+ }
+ return addr;
+}
+
+function svmFeePayer() {
+ return env('X402_FEE_PAYER_SOLANA', '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4');
+}
+
+// Build the CDP auth-headers async factory once and adapt it to the
+// HTTPFacilitatorClient's per-path createAuthHeaders contract. The CDP SDK
+// returns { verify, settle, supported, list } per call — we pick the slot
+// matching the requested path.
+function buildCdpFacilitator() {
+ const id = env('CDP_API_KEY_ID');
+ const secret = env('CDP_API_KEY_SECRET');
+ if (!id || !secret) return null;
+ const url = env('X402_CDP_FACILITATOR_URL', 'https://api.cdp.coinbase.com/platform/v2/x402');
+ const factory = createCdpAuthHeaders(id, secret);
+ return new HTTPFacilitatorClient({
+ url,
+ createAuthHeaders: async (path) => {
+ const all = await factory();
+ const map = { '/verify': 'verify', '/settle': 'settle', '/supported': 'supported' };
+ const op = map[path] || (path?.includes('verify') ? 'verify' : path?.includes('settle') ? 'settle' : 'supported');
+ return { headers: all?.[op] || {} };
+ },
+ });
+}
+
+function buildPayAiBaseFacilitator() {
+ const url = env('X402_FACILITATOR_URL_BASE') || env('X402_FACILITATOR_URL', 'https://facilitator.payai.network');
+ const token = env('X402_FACILITATOR_TOKEN_BASE') || env('X402_FACILITATOR_TOKEN');
+ return new HTTPFacilitatorClient({
+ url,
+ createAuthHeaders: token
+ ? async () => ({ headers: { Authorization: `Bearer ${token}` } })
+ : undefined,
+ });
+}
+
+function buildPayAiSolanaFacilitator() {
+ const url = env('X402_FACILITATOR_URL_SOLANA') || env('X402_FACILITATOR_URL', 'https://facilitator.payai.network');
+ const token = env('X402_FACILITATOR_TOKEN_SOLANA') || env('X402_FACILITATOR_TOKEN');
+ return new HTTPFacilitatorClient({
+ url,
+ createAuthHeaders: token
+ ? async () => ({ headers: { Authorization: `Bearer ${token}` } })
+ : undefined,
+ });
+}
+
+let resourceServerPromise = null;
+let lastInitError = null;
+
+// Build a single shared x402ResourceServer, register every scheme/network we
+// advertise on a tool, and call .initialize() to fetch facilitator /supported
+// (caches kinds + extensions for the per-network/per-scheme path).
+//
+// `initialize()` MUST run before any verify/settle — without it the server
+// has no notion of which facilitator handles which network and will throw on
+// the first paid call. We memoize the promise so concurrent tool calls don't
+// race during startup.
+export function getResourceServer() {
+ if (resourceServerPromise) return resourceServerPromise;
+ resourceServerPromise = (async () => {
+ const facilitators = [];
+ const cdp = buildCdpFacilitator();
+ if (cdp) facilitators.push(cdp);
+ facilitators.push(buildPayAiBaseFacilitator());
+ facilitators.push(buildPayAiSolanaFacilitator());
+
+ const server = new x402ResourceServer(facilitators);
+ registerExactEvmScheme(server, {});
+ // upto on EVM is needed by the vanity grinder (metered billing).
+ server.register('eip155:*', new UptoEvmServerScheme());
+ registerExactSvmScheme(server, {});
+ try {
+ await server.initialize();
+ } catch (err) {
+ lastInitError = err;
+ // Don't fatally throw — the server can still emit 402 challenges and
+ // /supported may have been partially populated. Operators will see
+ // the real failure when a tool tries to verify a payment.
+ console.error(`[mcp-server] facilitator initialize() failed: ${err.message}`);
+ }
+ return server;
+ })();
+ return resourceServerPromise;
+}
+
+export function getLastFacilitatorInitError() {
+ return lastInitError;
+}
+
+// Build the per-tool `accepts` list. Default networks are Base + Solana for
+// `exact`-priced tools; `upto` tools only support EVM today because @x402/svm
+// doesn't ship an upto scheme.
+async function buildAcceptsForTool({ resourceServer, scheme, priceUsd, networks, resourceUrl, extra }) {
+ const opts = [];
+ for (const net of networks) {
+ if (net === NETWORK_BASE_MAINNET) {
+ opts.push({
+ scheme,
+ network: NETWORK_BASE_MAINNET,
+ payTo: requireEvmPayTo(),
+ price: priceUsd,
+ maxTimeoutSeconds: 60,
+ extra: {
+ name: 'USD Coin',
+ version: '2',
+ decimals: 6,
+ asset: env('X402_ASSET_ADDRESS_BASE', DEFAULT_BASE_USDC),
+ ...(extra?.evm || {}),
+ },
+ });
+ } else if (net === NETWORK_SOLANA_MAINNET) {
+ if (scheme !== 'exact') continue; // upto on SVM not supported by @x402/[email protected].
+ opts.push({
+ scheme,
+ network: NETWORK_SOLANA_MAINNET,
+ payTo: requireSvmPayTo(),
+ price: priceUsd,
+ maxTimeoutSeconds: 60,
+ extra: {
+ name: 'USDC',
+ decimals: 6,
+ asset: env('X402_ASSET_MINT_SOLANA', DEFAULT_SOLANA_USDC),
+ feePayer: svmFeePayer(),
+ ...(extra?.svm || {}),
+ },
+ });
+ } else {
+ throw new Error(`mcp-server: unsupported network ${net}`);
+ }
+ }
+ if (opts.length === 0) {
+ throw new Error(`mcp-server: no networks resolved for scheme=${scheme}`);
+ }
+ return resourceServer.buildPaymentRequirementsFromOptions(opts, { resourceUrl });
+}
+
+/**
+ * Wrap a tool handler with x402 payment.
+ *
+ * @param {object} cfg
+ * @param {string} cfg.toolName — e.g. "get_pose_seed"
+ * @param {string} cfg.description — human-readable description
+ * @param {string} [cfg.scheme='exact'] — 'exact' or 'upto'
+ * @param {string|number} cfg.priceUsd — Price like "$0.001" (max for `upto`)
+ * @param {string[]} [cfg.networks] — default ['eip155:8453','solana:...']
+ * @param {object} cfg.inputSchema — JSON Schema for the tool's args
+ * @param {object} [cfg.example] — example invocation for bazaar
+ * @param {object} [cfg.outputExample] — example output for bazaar
+ * @param {object} [cfg.extra] — extra fields per-network
+ * @param {object} [cfg.hooks] — { onBeforeExecution, onAfterExecution, onAfterSettlement }
+ * @param {Function} handler — async (args, { settle? }) → { content }
+ * @returns {Promise<Function>} MCP tool callback for McpServer.tool()
+ */
+export async function paid(cfg, handler) {
+ const {
+ toolName,
+ description,
+ scheme = 'exact',
+ priceUsd,
+ networks = scheme === 'upto' ? [NETWORK_BASE_MAINNET] : [NETWORK_BASE_MAINNET, NETWORK_SOLANA_MAINNET],
+ inputSchema,
+ example,
+ outputExample,
+ extra,
+ hooks,
+ } = cfg;
+
+ if (!toolName) throw new Error('paid(): toolName is required');
+ if (!description) throw new Error('paid(): description is required');
+ if (!priceUsd) throw new Error('paid(): priceUsd is required (e.g. "$0.001")');
+ if (!inputSchema) throw new Error('paid(): inputSchema is required');
+
+ const resourceServer = await getResourceServer();
+ const resourceUrl = createToolResourceUrl(toolName);
+ const accepts = await buildAcceptsForTool({
+ resourceServer,
+ scheme,
+ priceUsd,
+ networks,
+ resourceUrl,
+ extra,
+ });
+
+ const bazaar = declareDiscoveryExtension({
+ toolName,
+ description,
+ transport: 'stdio',
+ inputSchema,
+ example,
+ output: outputExample ? { example: outputExample } : undefined,
+ });
+
+ const wrap = createPaymentWrapper(resourceServer, {
+ accepts,
+ resource: { url: resourceUrl, description, mimeType: 'application/json' },
+ extensions: bazaar,
+ hooks,
+ });
+
+ return wrap(async (args, context) => {
+ const result = await handler(args, context);
+ const text = typeof result === 'string' ? result : JSON.stringify(result);
+ return {
+ content: [{ type: 'text', text }],
+ };
+ });
+}
+
+export { NETWORK_BASE_MAINNET, NETWORK_SOLANA_MAINNET };
diff --git a/package-lock.json b/package-lock.json
index b9f4fbf1e..512081351 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -66,10 +66,10 @@
"@upstash/redis": "^1.34.3",
"@vercel/og": "^0.11.1",
"@x402/axios": "^2.12.0",
- "@x402/core": "^2.11.0",
- "@x402/evm": "^2.11.0",
- "@x402/express": "^2.11.0",
- "@x402/extensions": "^2.11.0",
+ "@x402/core": "^2.12.0",
+ "@x402/evm": "^2.12.0",
+ "@x402/express": "^2.12.0",
+ "@x402/extensions": "^2.12.0",
"@x402/svm": "^2.12.0",
"@zauthx402/sdk": "^0.1.14",
"agent0-sdk": "^1.7.1",
@@ -109,8 +109,7 @@
},
"devDependencies": {
"@gltf-transform/functions": "^4.3.0",
- "@playwright/test": "^1.60.0",
- "@x402/fetch": "^2.11.0",
+ "@x402/fetch": "^2.12.0",
"ajv": "^8.17.1",
"ajv-formats": "^3.0.1",
"jsdom": "^29.1.0",
@@ -14885,22 +14884,6 @@
"url": "https://opencollective.com/pkgr"
}
},
- "node_modules/@playwright/test": {
- "version": "1.60.0",
- "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.60.0.tgz",
- "integrity": "sha512-O71yZIbAh/PxDMNGns37GHBIfrVkEVyn+AXyIa5dOTfb4/xNvRWV+Vv/NMbNCtODB/pO7vLlF2OTmMVLhmr7Ag==",
- "dev": true,
- "license": "Apache-2.0",
- "dependencies": {
- "playwright": "1.60.0"
- },
- "bin": {
- "playwright": "cli.js"
- },
- "engines": {
- "node": ">=18"
- }
- },
"node_modules/@poppinss/colors": {
"version": "4.1.6",
"resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz",
@@ -26567,7 +26550,7 @@
"axios": "^1.7.9"
}
},
- "node_modules/@x402/axios/node_modules/@x402/core": {
+ "node_modules/@x402/core": {
"version": "2.12.0",
"resolved": "https://registry.npmjs.org/@x402/core/-/core-2.12.0.tgz",
"integrity": "sha512-dLae9AbZRN/W7GsKe9ngqGsflnP+esE72s0GjmqDZbPihM/tlHCA6UnDdgM0qfOiDOf9iL+mmCs1OyLWpwnGLQ==",
@@ -26576,39 +26559,28 @@
"zod": "^3.24.2"
}
},
- "node_modules/@x402/core": {
- "version": "2.11.0",
- "resolved": "https://registry.npmjs.org/@x402/core/-/core-2.11.0.tgz",
- "integrity": "sha512-aqTfZc/BULrlWnd3I0lsqRQaH4gjJd8CsPcL16XqK2Lx5c6QDm+zCljgUVS1yj9BGJoZeQWTzI5hE+SVFkqMTw==",
- "license": "Apache-2.0",
- "dependencies": {
- "zod": "^3.24.2"
- }
- },
"node_modules/@x402/evm": {
- "version": "2.11.0",
- "resolved": "https://registry.npmjs.org/@x402/evm/-/evm-2.11.0.tgz",
- "integrity": "sha512-F8uU1txDZA+wc/sEnmaHAyYvoTi/w39r7K3a44MmQHSxECDTEuB3A0FwbxOxUPLN1eyCxTAFKEiqlGe3bwybKA==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@x402/evm/-/evm-2.12.0.tgz",
+ "integrity": "sha512-kZUoHPVdBS8wlTg5K1eoh/1V0+5n9ABGRPC5DOQwRlkAwIrAFOEi2pQE+jgvOx0iM5ib2xj9gJjpldRbasX12w==",
"license": "Apache-2.0",
"dependencies": {
- "@x402/core": "~2.11.0",
- "viem": "^2.39.3",
+ "@x402/core": "~2.12.0",
+ "viem": "^2.48.11",
"zod": "^3.24.2"
}
},
"node_modules/@x402/express": {
- "version": "2.11.0",
- "resolved": "https://registry.npmjs.org/@x402/express/-/express-2.11.0.tgz",
- "integrity": "sha512-0HhvBJgtAQ4yqbFdql/0i8UlrXMi5BNKbD92fFIkK3VoSTjD6ArBYSzLt5twLYpj7ZfVODbSHqYEBwnPL5dasA==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@x402/express/-/express-2.12.0.tgz",
+ "integrity": "sha512-bPc6jpRr4iCh7KRJETK/2/bVTKHy/EeybQd9s+Mz4Ab+C64F1IH20GeW4gyj27dtAd2YgOiFrk8uyxSbZPKhkQ==",
"license": "Apache-2.0",
"dependencies": {
- "@x402/core": "~2.11.0",
- "@x402/extensions": "~2.11.0",
- "viem": "^2.39.3",
- "zod": "^3.24.2"
+ "@x402/core": "~2.12.0",
+ "@x402/extensions": "~2.12.0"
},
"peerDependencies": {
- "@x402/paywall": "^2.11.0",
+ "@x402/paywall": "^2.12.0",
"express": "^4.0.0 || ^5.0.0"
},
"peerDependenciesMeta": {
@@ -26618,19 +26590,19 @@
}
},
"node_modules/@x402/extensions": {
- "version": "2.11.0",
- "resolved": "https://registry.npmjs.org/@x402/extensions/-/extensions-2.11.0.tgz",
- "integrity": "sha512-S0SOoUsx4WtWqiWZuqslSzhopW/JcrEbnEC5l2sIQH/TABWzR0DgJLy36C43tD6TOJc0tEPN9bHuD+V8DYWomA==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@x402/extensions/-/extensions-2.12.0.tgz",
+ "integrity": "sha512-1B6a/ubCiAoNrVbrZ4btUcWXjM5e71fB2rxSrtW+mINGVonW4w7QDjAKdOlKzi6xqRSoGRVQm5ajL9hIGvkE2A==",
"license": "Apache-2.0",
"dependencies": {
"@noble/curves": "^1.9.0",
"@scure/base": "^1.2.6",
"@signinwithethereum/siwe": "^4.1.0",
- "@x402/core": "~2.11.0",
+ "@x402/core": "~2.12.0",
"ajv": "^8.17.1",
"jose": "^5.9.6",
"tweetnacl": "^1.0.3",
- "viem": "^2.43.5",
+ "viem": "^2.48.11",
"zod": "^3.24.2"
}
},
@@ -26662,15 +26634,13 @@
}
},
"node_modules/@x402/fetch": {
- "version": "2.11.0",
- "resolved": "https://registry.npmjs.org/@x402/fetch/-/fetch-2.11.0.tgz",
- "integrity": "sha512-sDkoq1ZZt10/UVa75bCXTbWkXMbPOOQpkdSxWB0ybHtlmqT7PM6hU4DVCov4iL792W1Oi38VtxfUw5EkvdvYtw==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@x402/fetch/-/fetch-2.12.0.tgz",
+ "integrity": "sha512-lkN/fzkZjnbJreLwI3fessKAaTKsOrrc0mFPGHWwZy0W/s8KFusLwdHuS8ul/XdUyNcYYrwcV6z0faGGSWNUNA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
- "@x402/core": "~2.11.0",
- "viem": "^2.39.3",
- "zod": "^3.24.2"
+ "@x402/core": "~2.12.0"
}
},
"node_modules/@x402/svm": {
@@ -26698,15 +26668,6 @@
"@solana/sysvars": "^5.0"
}
},
- "node_modules/@x402/svm/node_modules/@x402/core": {
- "version": "2.12.0",
- "resolved": "https://registry.npmjs.org/@x402/core/-/core-2.12.0.tgz",
- "integrity": "sha512-dLae9AbZRN/W7GsKe9ngqGsflnP+esE72s0GjmqDZbPihM/tlHCA6UnDdgM0qfOiDOf9iL+mmCs1OyLWpwnGLQ==",
- "license": "Apache-2.0",
- "dependencies": {
- "zod": "^3.24.2"
- }
- },
"node_modules/@xrplf/isomorphic": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@xrplf/isomorphic/-/isomorphic-1.0.1.tgz",
@@ -45276,9 +45237,9 @@
}
},
"node_modules/ox": {
- "version": "0.14.17",
- "resolved": "https://registry.npmjs.org/ox/-/ox-0.14.17.tgz",
- "integrity": "sha512-jOzNb2Wlfzsr8z/GoCtd1bf6OSRuWuysvbhnHGD+7fV1WRbcBR6B0RYoe3xWnUedF7zp4l5APmS7CzAhUok/lA==",
+ "version": "0.14.22",
+ "resolved": "https://registry.npmjs.org/ox/-/ox-0.14.22.tgz",
+ "integrity": "sha512-nb5msL8qWbPglhIfZbGJAfw3cqiJjFMiWmACt7kgyWtLib12tcctbHufMT9Hb0Lr6Pt4k9I3dbpueTpbhvbqvA==",
"funding": [
{
"type": "github",
@@ -45920,12 +45881,12 @@
}
},
"node_modules/playwright": {
- "version": "1.60.0",
- "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.60.0.tgz",
- "integrity": "sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==",
+ "version": "1.59.1",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.1.tgz",
+ "integrity": "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw==",
"license": "Apache-2.0",
"dependencies": {
- "playwright-core": "1.60.0"
+ "playwright-core": "1.59.1"
},
"bin": {
"playwright": "cli.js"
@@ -45938,9 +45899,9 @@
}
},
"node_modules/playwright-core": {
- "version": "1.60.0",
- "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.60.0.tgz",
- "integrity": "sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==",
+ "version": "1.59.1",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.1.tgz",
+ "integrity": "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg==",
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
@@ -52801,9 +52762,9 @@
"license": "MIT"
},
"node_modules/viem": {
- "version": "2.48.0",
- "resolved": "https://registry.npmjs.org/viem/-/viem-2.48.0.tgz",
- "integrity": "sha512-0uLzTAUNKPpY9Cf3OBCPdwClXx9CEHAkoVYnxMPdHt7cRI1DobMso+pHZvU7itD+hFwE4htmp9QfP+5lb+kn0g==",
+ "version": "2.50.4",
+ "resolved": "https://registry.npmjs.org/viem/-/viem-2.50.4.tgz",
+ "integrity": "sha512-rf98F4s3Vlb+uJZEKfay3IbBw3CNCbVtx5Y3UIljlO2tSX420g/J0WQSYsjzBSasUFgxgsXabji14O9kGbiqgg==",
"funding": [
{
"type": "github",
@@ -52818,8 +52779,8 @@
"@scure/bip39": "1.6.0",
"abitype": "1.2.3",
"isows": "1.0.7",
- "ox": "0.14.17",
- "ws": "8.18.3"
+ "ox": "0.14.22",
+ "ws": "8.20.1"
},
"peerDependencies": {
"typescript": ">=5.0.4"
@@ -52857,27 +52818,6 @@
"url": "https://paulmillr.com/funding/"
}
},
- "node_modules/viem/node_modules/ws": {
- "version": "8.18.3",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
- "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
- "license": "MIT",
- "engines": {
- "node": ">=10.0.0"
- },
- "peerDependencies": {
- "bufferutil": "^4.0.1",
- "utf-8-validate": ">=5.0.2"
- },
- "peerDependenciesMeta": {
- "bufferutil": {
- "optional": true
- },
- "utf-8-validate": {
- "optional": true
- }
- }
- },
"node_modules/vite": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz",
@@ -54489,9 +54429,9 @@
}
},
"node_modules/ws": {
- "version": "8.20.0",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",
- "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
+ "version": "8.20.1",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.1.tgz",
+ "integrity": "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
diff --git a/package.json b/package.json
index c5c916b90..8c5bd7232 100644
--- a/package.json
+++ b/package.json
@@ -26,6 +26,7 @@
"agent-payments-sdk",
"avatar-sdk",
"character-studio",
+ "mcp-server",
"multiplayer"
],
"main": "src/app.js",
@@ -141,10 +142,10 @@
"@upstash/redis": "^1.34.3",
"@vercel/og": "^0.11.1",
"@x402/axios": "^2.12.0",
- "@x402/core": "^2.11.0",
- "@x402/evm": "^2.11.0",
- "@x402/express": "^2.11.0",
- "@x402/extensions": "^2.11.0",
+ "@x402/core": "^2.12.0",
+ "@x402/evm": "^2.12.0",
+ "@x402/express": "^2.12.0",
+ "@x402/extensions": "^2.12.0",
"@x402/svm": "^2.12.0",
"@zauthx402/sdk": "^0.1.14",
"agent0-sdk": "^1.7.1",
@@ -184,8 +185,7 @@
},
"devDependencies": {
"@gltf-transform/functions": "^4.3.0",
- "@playwright/test": "^1.60.0",
- "@x402/fetch": "^2.11.0",
+ "@x402/fetch": "^2.12.0",
"ajv": "^8.17.1",
"ajv-formats": "^3.0.1",
"jsdom": "^29.1.0",
diff --git a/pages/club.html b/pages/club.html
index cab0d6ba3..9bacfaff6 100644
--- a/pages/club.html
+++ b/pages/club.html
@@ -571,13 +571,20 @@
border-top: 1px solid var(--border-strong);
border-top-left-radius: 16px;
border-top-right-radius: 16px;
+ /* dvh (dynamic viewport height) tracks the real visible
+ area on iOS Safari — vh alone uses the largest possible
+ viewport, so the sheet pops up by ~80px when the URL
+ bar collapses on scroll. vh fallback for very old
+ browsers that don't recognise dvh. */
max-height: 85vh;
+ max-height: 85dvh;
height: 85vh;
+ height: 85dvh;
/* Slide the bulk of the panel below the fold; only the
handle + the "Poles" section peek above. Bumped to
include both the safe-area inset and the iOS bottom
bar so the tip buttons stay reachable. */
- transform: translateY(calc(85vh - 240px));
+ transform: translateY(calc(85dvh - 240px));
transition: transform 0.28s cubic-bezier(0.2, 0.7, 0.2, 1);
box-shadow: 0 -12px 32px rgba(0, 0, 0, 0.55);
z-index: 12;
@@ -673,7 +680,8 @@
}
}
</style>
- </head>
+ <link rel="stylesheet" href="/mobile.css" />
+</head>
<body>
<div id="club-app">
<!-- TOP BAR -->
diff --git a/pages/create-selfie.html b/pages/create-selfie.html
index cb3b804e1..5ce9a7239 100644
--- a/pages/create-selfie.html
+++ b/pages/create-selfie.html
@@ -320,6 +320,7 @@
}
.cam-bar .spacer { flex: 1; }
</style>
+ <link rel="stylesheet" href="/mobile.css" />
</head>
<body>
<main class="stage">
diff --git a/pages/launchpad.html b/pages/launchpad.html
index d4a3a612a..18f0df911 100644
--- a/pages/launchpad.html
+++ b/pages/launchpad.html
@@ -22,7 +22,8 @@
height: 100vh;
}
</style>
- </head>
+ <link rel="stylesheet" href="/mobile.css" />
+</head>
<body>
<div id="root"></div>
<script type="module">
diff --git a/pages/pricing.html b/pages/pricing.html
index 988222512..d12bbe750 100644
--- a/pages/pricing.html
+++ b/pages/pricing.html
@@ -40,6 +40,7 @@
header { padding:18px 24px; border-bottom:1px solid var(--border); }
header a { color:#aaa; text-decoration:none; font-size:14px; }
</style>
+ <link rel="stylesheet" href="/mobile.css" />
</head>
<body>
<header><a href="/">← three.ws</a></header>
diff --git a/pages/pump-3d-agent.html b/pages/pump-3d-agent.html
index e4d975e06..344e4b629 100644
--- a/pages/pump-3d-agent.html
+++ b/pages/pump-3d-agent.html
@@ -7,6 +7,7 @@
<link rel="canonical" href="/pump-live">
<meta http-equiv="refresh" content="0; url=/pump-live">
<script>location.replace('/pump-live');</script>
+ <link rel="stylesheet" href="/mobile.css" />
</head>
<body>
<p>Moved to <a href="/pump-live">/pump-live</a>.</p>
diff --git a/pages/pumpfun-buy.html b/pages/pumpfun-buy.html
index a290d9fba..b8e97b91c 100644
--- a/pages/pumpfun-buy.html
+++ b/pages/pumpfun-buy.html
@@ -39,7 +39,8 @@
font-weight: bold;
}
</style>
- </head>
+ <link rel="stylesheet" href="/mobile.css" />
+</head>
<body>
<div class="container">
<div id="token-info">Loading...</div>
diff --git a/pages/pumpfun-counter.html b/pages/pumpfun-counter.html
index d3e724c40..83cb52594 100644
--- a/pages/pumpfun-counter.html
+++ b/pages/pumpfun-counter.html
@@ -22,7 +22,8 @@
text-align: center;
}
</style>
- </head>
+ <link rel="stylesheet" href="/mobile.css" />
+</head>
<body>
<div id="counter">0</div>
<script type="module">
diff --git a/pages/pumpfun-search.html b/pages/pumpfun-search.html
index 3d5b0c875..b6cadc384 100644
--- a/pages/pumpfun-search.html
+++ b/pages/pumpfun-search.html
@@ -48,7 +48,8 @@
.entry .meta-row { display: flex; gap: 12px; flex-wrap: wrap; font-size: 11px; color: #666; margin-top: 3px; }
.entry .mcap { color: #b366ff; font-weight: bold; }
</style>
- </head>
+ <link rel="stylesheet" href="/mobile.css" />
+</head>
<body>
<input type="text" id="search-input" placeholder="Search tokens...">
<div id="results"></div>
diff --git a/pages/pumpfun-trending.html b/pages/pumpfun-trending.html
index 8b91d176e..7842ea26f 100644
--- a/pages/pumpfun-trending.html
+++ b/pages/pumpfun-trending.html
@@ -44,7 +44,8 @@
.entry .meta-row { display: flex; gap: 12px; flex-wrap: wrap; font-size: 11px; color: #666; margin-top: 3px; }
.entry .mcap { color: #b366ff; font-weight: bold; }
</style>
- </head>
+ <link rel="stylesheet" href="/mobile.css" />
+</head>
<body>
<div id="root"></div>
<script type="module">
diff --git a/public/marketplace-v2.css b/public/marketplace-v2.css
index 069027df5..0eff9e96b 100644
--- a/public/marketplace-v2.css
+++ b/public/marketplace-v2.css
@@ -390,10 +390,16 @@ body.market-sidebar-open .market-sidebar-backdrop {
top: 0;
left: -260px;
width: 240px;
+ /* dvh (dynamic viewport height) tracks the actual visible viewport on
+ iOS Safari as the URL bar collapses, so the sidebar drawer no longer
+ spills below the home indicator. vh kept as a fallback for older UAs. */
height: 100vh;
+ height: 100dvh;
background: #0a0a0a;
z-index: 45;
transition: left 0.2s ease;
+ overflow-y: auto;
+ padding-bottom: env(safe-area-inset-bottom, 0);
}
body.market-sidebar-open .market-sidebar {
left: 0;
diff --git a/public/siwx-test.html b/public/siwx-test.html
new file mode 100644
index 000000000..b5471e59e
--- /dev/null
+++ b/public/siwx-test.html
@@ -0,0 +1,127 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width,initial-scale=1" />
+<title>x402 SIWX — manual test page</title>
+<meta name="robots" content="noindex" />
+<style>
+ html, body { margin: 0; padding: 0; background: #0c0e15; color: #e6e8f0; font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, sans-serif; }
+ main { max-width: 760px; margin: 0 auto; padding: 32px 20px 64px; }
+ h1 { font-size: 22px; margin: 0 0 4px; letter-spacing: -0.01em; }
+ .sub { color: #8a90a8; font-size: 13px; margin: 0 0 24px; line-height: 1.5; }
+ .row { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 20px; }
+ .row button {
+ flex: 1 1 280px;
+ padding: 14px 18px;
+ background: #1a1d29; border: 1px solid #2a2e3d; border-radius: 12px;
+ color: #e6e8f0; font-size: 14px; font-weight: 600; cursor: pointer;
+ text-align: left; line-height: 1.4;
+ transition: border-color 0.12s, background 0.12s;
+ }
+ .row button:hover { border-color: #0a84ff; background: #20243a; }
+ .row button small { display: block; font-weight: 400; color: #8a90a8; margin-top: 4px; font-size: 11px; font-family: ui-monospace, Menlo, monospace; }
+ .log-head {
+ display: flex; align-items: center; justify-content: space-between;
+ margin: 28px 0 8px;
+ }
+ .log-head h2 { font-size: 13px; font-weight: 600; color: #b0b6cc; letter-spacing: 0.04em; text-transform: uppercase; margin: 0; }
+ .log-head button {
+ background: transparent; border: 1px solid #2a2e3d; color: #8a90a8;
+ padding: 4px 10px; border-radius: 6px; font-size: 11px; cursor: pointer;
+ }
+ .log-head button:hover { color: #e6e8f0; border-color: #5a6378; }
+ pre {
+ background: #14161f; border: 1px solid #232636; border-radius: 10px;
+ padding: 14px 16px; font-family: ui-monospace, Menlo, monospace; font-size: 12px;
+ line-height: 1.55; color: #b0b6cc; white-space: pre-wrap; word-break: break-word;
+ min-height: 200px; max-height: 60vh; overflow: auto; margin: 0;
+ }
+ pre .siwx { color: #60a5fa; }
+ pre .result { color: #4ade80; }
+ pre .error { color: #fca5a5; }
+ pre .ts { color: #6b7088; }
+ .note {
+ font-size: 12px; color: #8a90a8; background: #14161f; border: 1px solid #232636;
+ border-radius: 8px; padding: 10px 12px; margin-top: 24px; line-height: 1.5;
+ }
+ .note code { font-family: ui-monospace, Menlo, monospace; color: #e6e8f0; }
+</style>
+</head>
+<body>
+<main>
+ <h1>x402 SIWX — manual test</h1>
+ <p class="sub">
+ Click a button to open the drop-in modal. When the endpoint advertises the
+ <code>sign-in-with-x</code> extension, the modal offers "Sign in with wallet"
+ as the primary action — the wallet signs a CAIP-122 message, the modal
+ retries the endpoint with a <code>SIGN-IN-WITH-X</code> header, and the
+ endpoint returns 200 without charging. Without the extension, the modal
+ runs the normal pay-with-USDC flow.
+ </p>
+
+ <div class="row">
+ <button
+ data-x402-endpoint="/api/x402/asset-download?slug=pole-dancer-rumba"
+ data-x402-method="GET"
+ data-x402-merchant="three.ws"
+ data-x402-action="Download pole-dancer-rumba.glb">
+ Buy GLB · pole-dancer-rumba
+ <small>/api/x402/asset-download?slug=pole-dancer-rumba</small>
+ </button>
+ <button
+ data-x402-endpoint="/api/x402/dance-tip?dancer=1&amp;dance=rumba"
+ data-x402-method="GET"
+ data-x402-merchant="three.ws"
+ data-x402-action="Tip dancer · rumba">
+ Tip dancer · rumba
+ <small>/api/x402/dance-tip?dancer=1&amp;dance=rumba</small>
+ </button>
+ </div>
+
+ <div class="log-head">
+ <h2>Event log</h2>
+ <button id="clear">Clear</button>
+ </div>
+ <pre id="log">(no events yet — click a button above)</pre>
+
+ <div class="note">
+ <strong>What to look for.</strong> First click on a paid endpoint runs the
+ <code>x402:result</code> event (pay flow). After paying once with a given
+ wallet, reload the page and click again — if the endpoint opts into SIWX,
+ the modal shows "Sign in with wallet". Approving the signature fires
+ <code>x402:siwx-signed</code> first, then <code>x402:result</code>, and the
+ network tab shows the request hitting the endpoint with a
+ <code>SIGN-IN-WITH-X</code> header (no <code>X-PAYMENT</code>).
+ </div>
+</main>
+
+<script type="module" src="/x402.js"></script>
+<script>
+ const log = document.getElementById('log');
+ let first = true;
+ function append(kind, label, detail) {
+ if (first) { log.textContent = ''; first = false; }
+ const ts = new Date().toISOString().slice(11, 23);
+ const head = document.createElement('span');
+ head.className = 'ts';
+ head.textContent = `[${ts}] `;
+ const tag = document.createElement('span');
+ tag.className = kind;
+ tag.textContent = label;
+ const body = document.createTextNode(' ' + JSON.stringify(detail, null, 2) + '\n\n');
+ log.appendChild(head);
+ log.appendChild(tag);
+ log.appendChild(body);
+ log.scrollTop = log.scrollHeight;
+ }
+ document.addEventListener('x402:siwx-signed', (e) => append('siwx', 'x402:siwx-signed', e.detail));
+ document.addEventListener('x402:result', (e) => append('result', 'x402:result', e.detail));
+ document.addEventListener('x402:error', (e) => append('error', 'x402:error', e.detail));
+ document.getElementById('clear').addEventListener('click', () => {
+ log.textContent = '(cleared — click a button above)';
+ first = true;
+ });
+</script>
+</body>
+</html>
diff --git a/public/x402-discover.js b/public/x402-discover.js
new file mode 100644
index 000000000..61be2d1e7
--- /dev/null
+++ b/public/x402-discover.js
@@ -0,0 +1,85 @@
+// x402-discover.js — optional companion to x402.js for buyer-side discovery.
+//
+// Merchants embedding x402.js for payments can opt into the Bazaar discovery
+// layer by also loading this module. It calls /api/bazaar/list and
+// /api/bazaar/search on the origin that hosts the script (same as x402.js),
+// so the merging across facilitators + CORS handling happens server-side.
+//
+// <script type="module" src="https://3d.irish/x402.js"></script>
+// <script type="module" src="https://3d.irish/x402-discover.js"></script>
+// <script>
+// const { items } = await X402.discover.list({ type: 'http', maxPrice: 100000 });
+// await X402.pay({ endpoint: items[0].resource });
+// </script>
+
+const ORIGIN = (() => {
+ try {
+ const script = document.currentScript;
+ if (script?.src) return new URL(script.src).origin;
+ const found = document.querySelector('script[src*="/x402-discover.js"]');
+ if (found?.src) return new URL(found.src).origin;
+ } catch (_) {}
+ return location.origin;
+})();
+
+function appendFilters(u, filters) {
+ const set = (k, v) => v != null && v !== '' && u.searchParams.set(k, String(v));
+ set('type', filters.type || 'http');
+ set('network', filters.network);
+ set('maxPrice', filters.maxPrice);
+ set('asset', filters.asset);
+ set('extension', filters.extension);
+ set('tag', filters.tag);
+ set('sort', filters.sort);
+ set('maxItems', filters.maxItems);
+ set('limit', filters.limit);
+ if (Array.isArray(filters.facilitators) && filters.facilitators.length) {
+ u.searchParams.set('facilitators', filters.facilitators.join(','));
+ }
+}
+
+async function call(path, filters) {
+ const u = new URL(`${ORIGIN}${path}`);
+ appendFilters(u, filters);
+ const r = await fetch(u.toString(), { headers: { accept: 'application/json' } });
+ if (!r.ok) {
+ const body = await r.json().catch(() => ({}));
+ throw new Error(body?.error_description || body?.error || `discover HTTP ${r.status}`);
+ }
+ return r.json();
+}
+
+export const discover = Object.freeze({
+ list(filters = {}) {
+ return call('/api/bazaar/list', filters);
+ },
+ search({ query, ...rest } = {}) {
+ const u = new URL(`${ORIGIN}/api/bazaar/search`);
+ if (query) u.searchParams.set('query', query);
+ appendFilters(u, rest);
+ return fetch(u.toString(), { headers: { accept: 'application/json' } }).then(async (r) => {
+ if (!r.ok) {
+ const body = await r.json().catch(() => ({}));
+ throw new Error(body?.error_description || body?.error || `discover HTTP ${r.status}`);
+ }
+ return r.json();
+ });
+ },
+});
+
+if (typeof window !== 'undefined') {
+ const existing = window.X402;
+ if (existing && !existing.discover) {
+ // `existing` is Object.freeze'd by x402.js — we replace it with a new
+ // frozen object that includes the discover surface, preserving pay/init.
+ try {
+ window.X402 = Object.freeze({ ...existing, discover });
+ } catch (_) {
+ // If reassignment is blocked (defineProperty configurable:false), fall
+ // back to a sibling global so callers can still reach discover.
+ window.X402Discover = discover;
+ }
+ } else {
+ window.X402Discover = discover;
+ }
+}
diff --git a/public/x402-stripe.html b/public/x402-stripe.html
index 15632422e..e13fddb5a 100644
--- a/public/x402-stripe.html
+++ b/public/x402-stripe.html
@@ -389,8 +389,50 @@
</div>
</section>
+ <section id="siwx">
+ <h2><span class="num">04</span>Sign in with wallet (re-entry)</h2>
+ <p class="sub">
+ For re-downloadable content — GLBs, avatars, agent skills, lobby
+ characters — buyers shouldn't pay again every time they fetch the same
+ asset. When an endpoint opts into <a href="https://github.com/x402/x402/blob/main/typescript/site/CHANGELOG-v2.md" target="_blank">SIWX (Sign-In-With-X, CAIP-122)</a>,
+ the modal grows a second option:
+ </p>
+ <pre style="background:var(--panel);border:1px solid var(--border);border-radius:10px;padding:14px 16px;font-family:var(--mono);font-size:12px;color:var(--text);line-height:1.5;overflow:auto;"><code>┌──────────────────────────────────────────┐
+│ three.ws ✕ │
+│ Download pole-dancer-rumba.glb │
+├──────────────────────────────────────────┤
+│ 0.05 USDC [Base · live ●] │
+├──────────────────────────────────────────┤
+│ ┌────────────────────────────────────┐ │
+│ │ Sign in with wallet │ │ ← primary
+│ └────────────────────────────────────┘ │
+│ ┌────────────────────────────────────┐ │
+│ │ Pay 0.05 USDC instead │ │ ← secondary
+│ └────────────────────────────────────┘ │
+│ Already paid for this once? Sign in to │
+│ re-enter without paying again. │
+└──────────────────────────────────────────┘</code></pre>
+ <p class="sub" style="margin-top:18px;">
+ Click <strong>Sign in with wallet</strong> → wallet pops with a CAIP-122
+ message naming the resource, the connected address, and a fresh nonce →
+ modal posts the signed payload as a <code style="font-family:var(--mono);">SIGN-IN-WITH-X</code>
+ header → endpoint looks the wallet up in its payment ledger → returns
+ 200 without charging. If the wallet hasn't actually paid for this
+ resource (or the signature is rejected), the modal falls back to the
+ normal pay flow with a one-line notice.
+ </p>
+ <p class="sub" style="margin-top:8px;">
+ Programmatic callers see the same flow: <code style="font-family:var(--mono);">await window.X402.pay(...)</code>
+ resolves with <code style="font-family:var(--mono);">{ result, siwx: { address, network } }</code>
+ (instead of <code style="font-family:var(--mono);">payment</code>) when SIWX was used. The element-bound API also
+ dispatches an <code style="font-family:var(--mono);">x402:siwx-signed</code> event right before
+ <code style="font-family:var(--mono);">x402:result</code> so analytics can distinguish a sign-in from a paid
+ call. A manual test surface lives at <a href="/siwx-test.html">/siwx-test.html</a>.
+ </p>
+ </section>
+
<section id="programmatic" class="alt">
- <h2><span class="num">04</span>Or call it programmatically</h2>
+ <h2><span class="num">05</span>Or call it programmatically</h2>
<p class="sub">Same modal, called from JavaScript. The promise resolves with the API result and a settlement receipt.</p>
<div class="snippet" id="progSnippet"><button class="copy-btn" data-copy="progSnippetCode">Copy</button><span id="progSnippetCode"><span class="k">const</span> { result, payment } = <span class="k">await</span> window.X402.<span class="a">pay</span>({
<span class="a">endpoint</span>: <span class="s">'/api/x402/symbol-availability'</span>,
diff --git a/public/x402.js b/public/x402.js
index 597c73fa8..ebd511983 100644
--- a/public/x402.js
+++ b/public/x402.js
@@ -114,6 +114,27 @@ function b64decode(str) {
}
}
+// ──────────────────────────────────────────── ERC-8021 builder-code echo ────
+// The server-side x402-spec.js enforces that any client-echoed builder-code
+// `a` matches what the 402 challenge declared (anti-tamper). Builders/wallets
+// can append their own service code in `s` and set their wallet code `w`
+// — for our own demo modal we self-attribute `w: "3d_agent"` and `s: ["3d_agent_modal"]`.
+
+const BUILDER_CODE_KEY = 'builder-code';
+const BUILDER_CODE_PATTERN = /^[a-z0-9_]{1,32}$/;
+const OUR_WALLET_CODE = '3d_agent';
+const OUR_SERVICE_CODE = '3d_agent_modal';
+
+function buildBuilderCodeEcho(challenge) {
+ const ext = challenge?.extensions?.[BUILDER_CODE_KEY];
+ const declaredA = ext?.info?.a;
+ if (!declaredA || !BUILDER_CODE_PATTERN.test(declaredA)) return null;
+ const out = { a: declaredA };
+ if (BUILDER_CODE_PATTERN.test(OUR_SERVICE_CODE)) out.s = [OUR_SERVICE_CODE];
+ if (BUILDER_CODE_PATTERN.test(OUR_WALLET_CODE)) out.w = OUR_WALLET_CODE;
+ return out;
+}
+
// ─────────────────────────────────────────────────────────── SIWX helpers ────
function extractSiwxExtension(body) {
@@ -615,17 +636,10 @@ class CheckoutModal {
// button, or after a 401/402 siwx_not_paid retry told us this wallet
// hasn't actually paid for this resource yet).
if (this.siwx && !this.payFlowOverride) {
- const siwxSolana = phantomDetected && solanaAccept ? pickSiwxChain(this.siwx, 'solana') : null;
- const siwxEvm = evmDetected && evmAccept ? pickSiwxChain(this.siwx, 'evm') : null;
+ const siwxSolana = phantomDetected ? pickSiwxChain(this.siwx, 'solana') : null;
+ const siwxEvm = evmDetected ? pickSiwxChain(this.siwx, 'evm') : null;
if (siwxSolana || siwxEvm) {
- this.renderSiwxChoice({
- siwxSolana,
- siwxEvm,
- solanaAccept,
- evmAccept,
- phantomDetected,
- evmDetected,
- });
+ this.renderSiwxChoice({ siwxSolana, siwxEvm });
return;
}
}
@@ -667,14 +681,14 @@ class CheckoutModal {
this.bodyEl.querySelectorAll('[data-wallet]').forEach((b) => b.addEventListener('click', onClick));
}
- renderSiwxChoice({ siwxSolana, siwxEvm, solanaAccept, evmAccept }) {
+ renderSiwxChoice({ siwxSolana, siwxEvm }) {
const priceText = formatAmount(this.accept.amount, this.accept.extra?.decimals ?? 6);
// One primary button — internally we pick the wallet kind that matches
// the supported SIWX chains AND the detected wallets. Phantom wins ties
// to match the existing modal's default preference.
const siwxTarget = siwxSolana
- ? { kind: 'solana', chain: siwxSolana.chain, payAccept: solanaAccept }
- : { kind: 'evm', chain: siwxEvm.chain, payAccept: evmAccept };
+ ? { kind: 'solana', chain: siwxSolana.chain }
+ : { kind: 'evm', chain: siwxEvm.chain };
const siwxLabel = siwxTarget.kind === 'solana' ? 'Sign in with Phantom' : 'Sign in with wallet';
this.bodyEl.innerHTML = `
${this.renderSteps('connect', { discover: 'done' })}
@@ -683,8 +697,8 @@ class CheckoutModal {
<div class="x402-siwx-hint">Already paid for this once? Sign in to re-enter without paying again.</div>
`;
this.bodyEl.querySelector('[data-action="siwx"]').addEventListener('click', () => {
- if (siwxTarget.kind === 'solana') this.runSiwxSolana(siwxTarget.chain, siwxTarget.payAccept);
- else this.runSiwxEvm(siwxTarget.chain, siwxTarget.payAccept);
+ if (siwxTarget.kind === 'solana') this.runSiwxSolana(siwxTarget.chain);
+ else this.runSiwxEvm(siwxTarget.chain);
});
this.bodyEl.querySelector('[data-action="pay"]').addEventListener('click', () => {
this.payFlowOverride = true;
@@ -717,29 +731,54 @@ class CheckoutModal {
this.bodyEl.querySelector('[data-retry]').addEventListener('click', () => this.start());
}
- renderDone({ result, payment }) {
- const explorer = explorerUrl(payment?.network, payment?.transaction);
- const txShort = payment?.transaction ? `${payment.transaction.slice(0, 8)}…${payment.transaction.slice(-6)}` : '—';
+ renderDone({ result, payment, siwx }) {
const resultStr = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
- this.bodyEl.innerHTML = `
- <div class="x402-receipt">
- <div class="x402-receipt-title">Paid</div>
- <div class="x402-receipt-row">
- <span class="x402-k">network</span>
- <span class="x402-v">${escapeHtml(networkLabel(payment?.network) || '—')}</span>
+ let receiptHtml;
+ if (siwx) {
+ const addrShort = siwx.address ? `${siwx.address.slice(0, 8)}…${siwx.address.slice(-6)}` : '—';
+ receiptHtml = `
+ <div class="x402-receipt">
+ <div class="x402-receipt-title">Signed in</div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">network</span>
+ <span class="x402-v">${escapeHtml(networkLabel(siwx.network) || siwx.network || '—')}</span>
+ </div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">wallet</span>
+ <span class="x402-v">${escapeHtml(addrShort)}</span>
+ </div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">paid</span>
+ <span class="x402-v">previously · re-entered free</span>
+ </div>
</div>
- <div class="x402-receipt-row">
- <span class="x402-k">payer</span>
- <span class="x402-v">${escapeHtml(payment?.payer ? `${payment.payer.slice(0, 8)}…${payment.payer.slice(-6)}` : '—')}</span>
+ `;
+ } else {
+ const explorer = explorerUrl(payment?.network, payment?.transaction);
+ const txShort = payment?.transaction ? `${payment.transaction.slice(0, 8)}…${payment.transaction.slice(-6)}` : '—';
+ receiptHtml = `
+ <div class="x402-receipt">
+ <div class="x402-receipt-title">Paid</div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">network</span>
+ <span class="x402-v">${escapeHtml(networkLabel(payment?.network) || '—')}</span>
+ </div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">payer</span>
+ <span class="x402-v">${escapeHtml(payment?.payer ? `${payment.payer.slice(0, 8)}…${payment.payer.slice(-6)}` : '—')}</span>
+ </div>
+ ${
+ payment?.transaction
+ ? `<div class="x402-receipt-row"><span class="x402-k">tx</span><span class="x402-v">${
+ explorer ? `<a href="${explorer}" target="_blank" rel="noopener">${txShort} ↗</a>` : txShort
+ }</span></div>`
+ : ''
+ }
</div>
- ${
- payment?.transaction
- ? `<div class="x402-receipt-row"><span class="x402-k">tx</span><span class="x402-v">${
- explorer ? `<a href="${explorer}" target="_blank" rel="noopener">${txShort} ↗</a>` : txShort
- }</span></div>`
- : ''
- }
- </div>
+ `;
+ }
+ this.bodyEl.innerHTML = `
+ ${receiptHtml}
<div class="x402-result">${escapeHtml(resultStr).slice(0, 4000)}</div>
<button class="x402-pay-btn" data-done>Done</button>
`;
@@ -800,10 +839,12 @@ class CheckoutModal {
const signed = await provider.signTransaction(tx);
const signedB64 = uint8ArrayToBase64(signed.serialize());
+ const builderCodeBlock = buildBuilderCodeEcho(this.challenge);
const enc = await postJson(`${ORIGIN}/api/x402-checkout?action=encode`, {
accept,
signed_tx_base64: signedB64,
resource_url: this.opts.endpoint,
+ ...(builderCodeBlock ? { builder_code: builderCodeBlock } : {}),
});
await this.executePaid(enc.x_payment);
@@ -897,6 +938,10 @@ class CheckoutModal {
authorization: { from: payerAddress, to: accept.payTo, value: accept.amount, validAfter, validBefore, nonce },
},
};
+ const builderCodeBlock = buildBuilderCodeEcho(this.challenge);
+ if (builderCodeBlock) {
+ paymentPayload.extensions = { 'builder-code': builderCodeBlock };
+ }
const xPayment = b64encode(paymentPayload);
await this.executePaid(xPayment);
} catch (err) {
@@ -941,7 +986,7 @@ class CheckoutModal {
}
}
- async runSiwxEvm(chain, payAccept) {
+ async runSiwxEvm(chain) {
this.renderProgress('connect', { text: 'Opening browser wallet…' });
try {
const eth = window.ethereum;
@@ -978,13 +1023,13 @@ class CheckoutModal {
signatureScheme: 'eip191',
signature,
};
- await this.executeSiwx(payload, payAccept, chain.chainId);
+ await this.executeSiwx(payload, chain.chainId);
} catch (err) {
this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
}
}
- async runSiwxSolana(chain, payAccept) {
+ async runSiwxSolana(chain) {
this.renderProgress('connect', { text: 'Opening Phantom…' });
try {
const provider = window.phantom?.solana || window.solana;
@@ -1021,13 +1066,13 @@ class CheckoutModal {
signatureScheme: 'siws',
signature,
};
- await this.executeSiwx(payload, payAccept, chain.chainId);
+ await this.executeSiwx(payload, chain.chainId);
} catch (err) {
this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
}
}
- async executeSiwx(payload, payAccept, chainId) {
+ async executeSiwx(payload, chainId) {
this.renderProgress('verify', { text: 'Verifying sign-in…' });
const headerValue = encodeSiwxHeaderValue(payload);
let res;
@@ -1090,7 +1135,7 @@ class CheckoutModal {
}
const text = await res.text().catch(() => '');
- throw new Error(`SIWX retry failed: HTTP ${res.status}${text ? ` · ${text.slice(0, 120)}` : ''}`);
+ this.renderError('verify', `SIWX retry failed: HTTP ${res.status}${text ? ` · ${text.slice(0, 120)}` : ''}`);
}
}
@@ -1182,12 +1227,14 @@ async function discoverChallenge(opts) {
}
let body = await res.json().catch(() => null);
if (!body || !Array.isArray(body.accepts) || !body.accepts.length) {
- // Try to read from the PAYMENT-REQUIRED header per v2 spec
+ // send402 (api/_lib/x402-spec.js) only emits `{error}` in the body and
+ // puts the full v2 PaymentRequired envelope (accepts + extensions) in
+ // the base64-JSON PAYMENT-REQUIRED header. b64decode returns already-
+ // parsed JSON, so use its result directly.
const prHeader = res.headers.get('payment-required');
- if (prHeader) {
- try {
- body = JSON.parse(b64decode(prHeader));
- } catch (err) {}
+ const decoded = b64decode(prHeader);
+ if (decoded && Array.isArray(decoded.accepts) && decoded.accepts.length) {
+ body = decoded;
}
}
if (!body || !Array.isArray(body.accepts) || !body.accepts.length) {
@@ -1215,6 +1262,9 @@ function bindElement(el) {
const opts = readOptsFrom(el);
try {
const out = await pay(opts);
+ if (out?.siwx) {
+ el.dispatchEvent(new CustomEvent('x402:siwx-signed', { detail: out.siwx, bubbles: true }));
+ }
el.dispatchEvent(new CustomEvent('x402:result', { detail: out, bubbles: true }));
} catch (err) {
if (err?.code === 'cancelled') return;
diff --git a/scripts/apply-paid-assets-migration.mjs b/scripts/apply-paid-assets-migration.mjs
index 591463ec6..e5df752b9 100644
--- a/scripts/apply-paid-assets-migration.mjs
+++ b/scripts/apply-paid-assets-migration.mjs
@@ -42,13 +42,22 @@ const text = await readFile(
'utf8',
);
+// Neon HTTP API runs one statement per call. Split on top-level semicolons,
+// then strip `--` comment lines per chunk so the migration's header block
+// doesn't cause the first CREATE statement to be filtered out as comment-only.
const statements = text
.split(/;\s*$/m)
- .map((s) => s.trim())
- .filter((s) => s && !/^--/.test(s));
+ .map((s) =>
+ s
+ .split('\n')
+ .filter((line) => !/^\s*--/.test(line))
+ .join('\n')
+ .trim(),
+ )
+ .filter((s) => s.length > 0);
for (const s of statements) {
- await sql.query(s);
+ await sql(s, [], {});
console.log('OK:', s.slice(0, 80).replace(/\s+/g, ' '));
}
console.log('paid_assets table ready');
diff --git a/scripts/apply-siwx-migration.mjs b/scripts/apply-siwx-migration.mjs
index 748ebf471..fdaeae896 100644
--- a/scripts/apply-siwx-migration.mjs
+++ b/scripts/apply-siwx-migration.mjs
@@ -43,11 +43,19 @@ const text = await readFile(
);
// Neon HTTP API runs one statement per call. Split on top-level semicolons —
-// the SIWX migration uses no DO blocks / dollar-quoted strings.
+// the SIWX migration uses no DO blocks / dollar-quoted strings. Strip leading
+// `--` comment lines per chunk so the migration's header block doesn't cause
+// the first CREATE statement to be filtered out as a comment-only chunk.
const statements = text
.split(/;\s*$/m)
- .map((s) => s.trim())
- .filter((s) => s && !/^--/.test(s));
+ .map((s) =>
+ s
+ .split('\n')
+ .filter((line) => !/^\s*--/.test(line))
+ .join('\n')
+ .trim(),
+ )
+ .filter((s) => s.length > 0);
for (const s of statements) {
await sql(s, [], {});
diff --git a/scripts/inject-mobile-css.mjs b/scripts/inject-mobile-css.mjs
index 1291f9bce..b6348532e 100644
--- a/scripts/inject-mobile-css.mjs
+++ b/scripts/inject-mobile-css.mjs
@@ -35,13 +35,21 @@ function injectLink(html) {
let lastMatch = null;
let m;
while ((m = stylesheetTag.exec(html)) !== null) lastMatch = m;
- if (!lastMatch) return { html, changed: false };
- const end = lastMatch.index + lastMatch[0].length;
- // Preserve the indentation of the matched tag for the new line.
- const lineStart = html.lastIndexOf('\n', lastMatch.index) + 1;
- const indent = html.slice(lineStart, lastMatch.index).match(/^[\t ]*/)[0];
- const insertion = `\n${indent}${LINK}`;
- return { html: html.slice(0, end) + insertion + html.slice(end), changed: true };
+ if (lastMatch) {
+ const end = lastMatch.index + lastMatch[0].length;
+ const lineStart = html.lastIndexOf('\n', lastMatch.index) + 1;
+ const indent = html.slice(lineStart, lastMatch.index).match(/^[\t ]*/)[0];
+ const insertion = `\n${indent}${LINK}`;
+ return { html: html.slice(0, end) + insertion + html.slice(end), changed: true };
+ }
+ // Fallback for pages that use only inline <style> blocks: insert just
+ // before </head> so the file stays a valid HTML document.
+ const headClose = html.search(/<\/head\s*>/i);
+ if (headClose === -1) return { html, changed: false };
+ const lineStart = html.lastIndexOf('\n', headClose) + 1;
+ const indent = html.slice(lineStart, headClose).match(/^[\t ]*/)[0] + '\t';
+ const insertion = `${indent}${LINK}\n`;
+ return { html: html.slice(0, headClose) + insertion + html.slice(headClose), changed: true };
}
const files = readdirSync(PAGES_DIR).filter((f) => f.endsWith('.html'));
diff --git a/scripts/seed-paid-assets.mjs b/scripts/seed-paid-assets.mjs
new file mode 100644
index 000000000..1682eb9ee
--- /dev/null
+++ b/scripts/seed-paid-assets.mjs
@@ -0,0 +1,206 @@
+#!/usr/bin/env node
+/**
+ * seed-paid-assets.mjs
+ * ────────────────────
+ * Upload two real GLBs from the repo to R2 under assets/<slug>.glb, then
+ * insert a paid_assets row for each. Both rows are priced at $0.005 USDC
+ * (5000 atomics). Idempotent: slug is UNIQUE, and the row insert uses
+ * ON CONFLICT (slug) DO NOTHING — re-running just re-uploads bytes when
+ * R2 differs and leaves rows alone.
+ *
+ * Required env:
+ * DATABASE_URL, S3_ENDPOINT, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY,
+ * S3_BUCKET, S3_PUBLIC_DOMAIN.
+ *
+ * Usage:
+ * DATABASE_URL=... S3_*=... node scripts/seed-paid-assets.mjs
+ * node scripts/seed-paid-assets.mjs --dry-run # plan only
+ */
+
+import { readFileSync } from 'node:fs';
+import { readFile, stat } from 'node:fs/promises';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { neon } from '@neondatabase/serverless';
+import {
+ S3Client,
+ PutObjectCommand,
+ HeadObjectCommand,
+} from '@aws-sdk/client-s3';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = resolve(__dirname, '..');
+
+// ── load .env.local / .env so the script works the same as the dev server ──
+for (const envFile of ['.env.local', '.env']) {
+ try {
+ const raw = readFileSync(resolve(REPO_ROOT, envFile), 'utf8');
+ for (const line of raw.split('\n')) {
+ const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
+ if (!m || process.env[m[1]]) continue;
+ let val = m[2].trim();
+ if (
+ (val.startsWith('"') && val.endsWith('"')) ||
+ (val.startsWith("'") && val.endsWith("'"))
+ ) {
+ val = val.slice(1, -1);
+ }
+ process.env[m[1]] = val;
+ }
+ break;
+ } catch {
+ /* file not present */
+ }
+}
+
+const args = Object.fromEntries(
+ process.argv.slice(2).map((a) => {
+ const [k, v] = a.replace(/^--/, '').split('=');
+ return [k, v ?? true];
+ }),
+);
+const DRY_RUN = !!args['dry-run'];
+
+if (!process.env.DATABASE_URL) {
+ console.error('Missing DATABASE_URL');
+ process.exit(1);
+}
+if (!DRY_RUN) {
+ for (const k of [
+ 'S3_ENDPOINT',
+ 'S3_ACCESS_KEY_ID',
+ 'S3_SECRET_ACCESS_KEY',
+ 'S3_BUCKET',
+ ]) {
+ if (!process.env[k]) {
+ console.error(`Missing ${k}`);
+ process.exit(1);
+ }
+ }
+}
+
+const sql = neon(process.env.DATABASE_URL);
+const s3 = DRY_RUN
+ ? null
+ : new S3Client({
+ region: 'auto',
+ endpoint: process.env.S3_ENDPOINT.replace(/\/$/, ''),
+ credentials: {
+ accessKeyId: process.env.S3_ACCESS_KEY_ID,
+ secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
+ },
+ requestChecksumCalculation: 'WHEN_REQUIRED',
+ responseChecksumValidation: 'WHEN_REQUIRED',
+ });
+
+// The two seed entries the prompt asks for:
+// 1. pole-dancer-rumba — points at the same default.glb the /club page uses
+// for the Rumba routine (see src/club.js AVATAR_URL).
+// 2. cz-avatar — the stylized CZ avatar in public/avatars/cz.glb.
+// Both priced at 5000 atomics = $0.005 USDC.
+const CATALOG = [
+ {
+ slug: 'pole-dancer-rumba',
+ title: 'Pole Dancer (Rumba)',
+ description:
+ 'The three.ws default dancer rigged for the /club Rumba routine. ' +
+ 'Drop this GLB into any Three.js scene and play the "rumba" clip from ' +
+ 'the bundled AnimationMixer.',
+ file: 'public/avatars/default.glb',
+ mimeType: 'model/gltf-binary',
+ priceAtomics: '5000',
+ },
+ {
+ slug: 'cz-avatar',
+ title: 'CZ Avatar',
+ description:
+ 'Stylized humanoid CZ avatar — humanoid skeleton, single mesh, ' +
+ 'low-poly silhouette. Ready for the three.ws Character Studio or ' +
+ 'any humanoid retargeter.',
+ file: 'public/avatars/cz.glb',
+ mimeType: 'model/gltf-binary',
+ priceAtomics: '5000',
+ },
+];
+
+async function objectExists(key) {
+ if (!s3) return false;
+ try {
+ await s3.send(
+ new HeadObjectCommand({ Bucket: process.env.S3_BUCKET, Key: key }),
+ );
+ return true;
+ } catch (err) {
+ if (err?.$metadata?.httpStatusCode === 404) return false;
+ throw err;
+ }
+}
+
+async function uploadAsset(localPath, key, mimeType) {
+ const buf = await readFile(localPath);
+ if (DRY_RUN) {
+ console.log(` [dry-run] would PUT ${key} (${buf.length} bytes)`);
+ return buf.length;
+ }
+ await s3.send(
+ new PutObjectCommand({
+ Bucket: process.env.S3_BUCKET,
+ Key: key,
+ Body: buf,
+ ContentType: mimeType,
+ }),
+ );
+ return buf.length;
+}
+
+async function ensureRow(row) {
+ if (DRY_RUN) {
+ console.log(` [dry-run] would upsert paid_assets row slug=${row.slug}`);
+ return;
+ }
+ await sql`
+ insert into paid_assets
+ (slug, title, description, mime_type, size_bytes, r2_key, price_atomics)
+ values
+ (${row.slug}, ${row.title}, ${row.description}, ${row.mimeType},
+ ${row.sizeBytes}, ${row.r2Key}, ${row.priceAtomics})
+ on conflict (slug) do nothing
+ `;
+}
+
+async function main() {
+ for (const entry of CATALOG) {
+ const localPath = resolve(REPO_ROOT, entry.file);
+ const stats = await stat(localPath);
+ const sizeBytes = stats.size;
+ const r2Key = `assets/${entry.slug}.glb`;
+ console.log(
+ `→ ${entry.slug} ${entry.file} (${sizeBytes} bytes) → s3://${process.env.S3_BUCKET || '?'}/${r2Key}`,
+ );
+
+ const exists = await objectExists(r2Key);
+ if (!exists) {
+ const uploaded = await uploadAsset(localPath, r2Key, entry.mimeType);
+ console.log(` uploaded ${uploaded} bytes`);
+ } else {
+ console.log(' already present in R2 — skipping upload');
+ }
+
+ await ensureRow({
+ slug: entry.slug,
+ title: entry.title,
+ description: entry.description,
+ mimeType: entry.mimeType,
+ sizeBytes,
+ r2Key,
+ priceAtomics: entry.priceAtomics,
+ });
+ console.log(` paid_assets row ready`);
+ }
+ console.log('seed-paid-assets: done');
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/scripts/x402-first-paid-request.mjs b/scripts/x402-first-paid-request.mjs
index d82df0f5e..327c92760 100755
--- a/scripts/x402-first-paid-request.mjs
+++ b/scripts/x402-first-paid-request.mjs
@@ -9,6 +9,7 @@
// X402_BUYER_PRIVATE_KEY=0x... # funded wallet, USDC + gas on the chosen network
// X402_TARGET=https://three.ws/api/x402/model-check
// X402_NETWORK=base # "base" or "arbitrum"
+// X402_PAYMENT_ID=pay_xyz... # optional: pin a stable idempotency id
// node scripts/x402-first-paid-request.mjs
//
// Pre-flight: needs ≥0.001 USDC of the target network's native USDC and a
@@ -20,6 +21,7 @@ import { x402Client } from '@x402/core/client';
import { registerExactEvmScheme } from '@x402/evm/exact/client/index.js';
import { privateKeyToAccount } from 'viem/accounts';
import { base, arbitrum } from 'viem/chains';
+import { installIdempotency } from '../api/_lib/x402/payment-identifier-client.js';
const PRIVATE_KEY = process.env.X402_BUYER_PRIVATE_KEY;
if (!PRIVATE_KEY) {
@@ -49,8 +51,15 @@ registerExactEvmScheme(client, {
}
});
+// USE-15: idempotency. When the server advertises payment-identifier, the
+// hook appends an id to the payload so retries with the same id return the
+// cached response without re-charging. Set X402_PAYMENT_ID to pin one across
+// runs; otherwise a fresh id is generated per request.
+installIdempotency(client, { paymentId: process.env.X402_PAYMENT_ID || undefined });
+
console.log(`[x402] buyer ${account.address} on ${CHAIN.name}`);
console.log(`[x402] GET ${TARGET}`);
+if (process.env.X402_PAYMENT_ID) console.log(`[x402] payment-id: ${process.env.X402_PAYMENT_ID}`);
const fetchWithPayment = wrapFetchWithPayment(fetch, client);
diff --git a/scripts/x402-pay.mjs b/scripts/x402-pay.mjs
index 2d0df655e..9f6f6eba5 100644
--- a/scripts/x402-pay.mjs
+++ b/scripts/x402-pay.mjs
@@ -21,6 +21,10 @@
// * BUYER_PRIVATE_KEY — hex EVM private key (0x...). Wallet must hold USDC on
// Base mainnet (or Arbitrum One — script auto-selects whichever the endpoint
// accepts that's listed first). $0.001 USDC + a tiny amount of ETH for gas.
+// * X402_PAYMENT_ID (optional) — pin a stable payment-identifier across
+// retries; otherwise a fresh id is generated per call. Use this when
+// scripting against an endpoint that may be flaky so the second run
+// replays the cached response instead of paying again.
// * Node 20+ (uses native fetch).
//
// BAZAAR INDEXING
@@ -28,9 +32,11 @@
// agentic.market to index your endpoint. Run this script once with a real
// buyer wallet and you're listed.
-import { wrapFetchWithPaymentFromConfig, decodePaymentResponseHeader } from '@x402/fetch';
+import { wrapFetchWithPayment, decodePaymentResponseHeader } from '@x402/fetch';
+import { x402Client } from '@x402/core/client';
import { ExactEvmScheme } from '@x402/evm/exact/client';
import { privateKeyToAccount } from 'viem/accounts';
+import { installIdempotency } from '../api/_lib/x402/payment-identifier-client.js';
const BUYER_PRIVATE_KEY = process.env.BUYER_PRIVATE_KEY;
if (!BUYER_PRIVATE_KEY) {
@@ -73,9 +79,17 @@ console.log();
// `eip155:*` registers the same scheme for any EVM chain — the facilitator's
// first-listed accepts entry decides which one we actually pay on.
-const fetchWithPayment = wrapFetchWithPaymentFromConfig(fetch, {
- schemes: [{ network: 'eip155:*', client: new ExactEvmScheme(account) }],
-});
+const client = new x402Client();
+client.register('eip155:*', new ExactEvmScheme(account));
+
+// USE-15: idempotency. When the server advertises payment-identifier, the
+// hook appends an id to the payload so retries with the same id return the
+// cached response without re-charging. Set X402_PAYMENT_ID to pin one across
+// runs; otherwise a fresh id is generated per request.
+installIdempotency(client, { paymentId: process.env.X402_PAYMENT_ID || undefined });
+if (process.env.X402_PAYMENT_ID) console.log(`payment-id: ${process.env.X402_PAYMENT_ID}`);
+
+const fetchWithPayment = wrapFetchWithPayment(fetch, client);
const t0 = Date.now();
let res;
diff --git a/tests/api/siwx-storage.test.js b/tests/api/siwx-storage.test.js
new file mode 100644
index 000000000..3077d9327
--- /dev/null
+++ b/tests/api/siwx-storage.test.js
@@ -0,0 +1,160 @@
+// Round-trips siwx-storage.js against the real Neon database pointed at by
+// $DATABASE_URL. With no DATABASE_URL the suite skips cleanly so CI can run
+// without leaking secrets; locally, run after applying
+// api/_lib/migrations/2026-05-21-siwx.sql.
+//
+// Every test scopes its rows to a per-run resource string and tears down at
+// the end so concurrent runs (and prior crashes) don't poison each other.
+
+import { describe, it, expect, afterAll, beforeAll } from 'vitest';
+import crypto from 'node:crypto';
+
+import { sql } from '../../api/_lib/db.js';
+import {
+ siwxStorage,
+ normalizeAddress,
+ pruneExpiredPayments,
+ pruneOldNonces,
+} from '../../api/_lib/siwx-storage.js';
+
+const HAS_DB = !!process.env.DATABASE_URL;
+const itDb = HAS_DB ? it : it.skip;
+
+const RUN_TAG = `test-${crypto.randomUUID()}`;
+const resourceFor = (suffix) => `test-resource-${RUN_TAG}-${suffix}`;
+
+const EVM_NETWORK = 'eip155:8453';
+const EVM_ADDR_CHECKSUM = '0xAbC0000000000000000000000000000000000001';
+const EVM_ADDR_LOWER = EVM_ADDR_CHECKSUM.toLowerCase();
+
+// A 44-char Base58 string — same length as a real Solana pubkey, but our
+// adapter only stores/normalizes the string, it doesn't decode it.
+const SOL_NETWORK = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
+const SOL_ADDR = '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpLHpzMhsbAVQ2';
+
+describe('normalizeAddress', () => {
+ it('lowercases EVM addresses', () => {
+ expect(normalizeAddress(EVM_NETWORK, EVM_ADDR_CHECKSUM)).toBe(EVM_ADDR_LOWER);
+ });
+
+ it('leaves Solana addresses untouched', () => {
+ expect(normalizeAddress(SOL_NETWORK, SOL_ADDR)).toBe(SOL_ADDR);
+ });
+
+ it('rejects unsupported namespaces', () => {
+ expect(() => normalizeAddress('cosmos:cosmoshub-4', 'cosmos1abc')).toThrow(/unsupported/);
+ });
+
+ it('rejects missing args', () => {
+ expect(() => normalizeAddress('', '0xabc')).toThrow();
+ expect(() => normalizeAddress(EVM_NETWORK, '')).toThrow();
+ });
+});
+
+describe('siwxStorage against real Postgres', () => {
+ beforeAll(() => {
+ if (!HAS_DB) {
+ console.log('[siwx-storage.test] DATABASE_URL unset — skipping DB-backed cases');
+ }
+ });
+
+ afterAll(async () => {
+ if (!HAS_DB) return;
+ // Belt-and-suspenders cleanup keyed by RUN_TAG so a partial-failure run
+ // can't leak rows into the dev DB.
+ await sql`delete from siwx_payments where resource like ${'test-resource-' + RUN_TAG + '-%'}`;
+ await sql`delete from siwx_nonces where resource like ${'test-resource-' + RUN_TAG + '-%'}`;
+ });
+
+ itDb('hasPaid returns false for an unknown wallet', async () => {
+ const r = resourceFor('unknown');
+ expect(await siwxStorage.hasPaid(r, EVM_ADDR_CHECKSUM)).toBe(false);
+ });
+
+ itDb('EVM round-trip: checksum input → lowercase stored, hasPaid hits', async () => {
+ const r = resourceFor('evm-roundtrip');
+ await siwxStorage.recordPayment(r, EVM_ADDR_CHECKSUM, { network: EVM_NETWORK });
+
+ expect(await siwxStorage.hasPaid(r, EVM_ADDR_CHECKSUM)).toBe(true);
+ expect(await siwxStorage.hasPaid(r, EVM_ADDR_LOWER)).toBe(true);
+
+ const [row] = await sql`
+ select address, network, use_count, last_used_at
+ from siwx_payments
+ where resource = ${r}
+ `;
+ expect(row.address).toBe(EVM_ADDR_LOWER);
+ expect(row.network).toBe(EVM_NETWORK);
+ expect(row.use_count).toBeGreaterThanOrEqual(2);
+ expect(row.last_used_at).toBeTruthy();
+ });
+
+ itDb('Solana round-trip: Base58 stored case-sensitive, hasPaid hits', async () => {
+ const r = resourceFor('sol-roundtrip');
+ await siwxStorage.recordPayment(r, SOL_ADDR, { network: SOL_NETWORK });
+
+ expect(await siwxStorage.hasPaid(r, SOL_ADDR)).toBe(true);
+ expect(await siwxStorage.hasPaid(r, SOL_ADDR.toLowerCase())).toBe(false);
+
+ const [row] = await sql`select address from siwx_payments where resource = ${r}`;
+ expect(row.address).toBe(SOL_ADDR);
+ });
+
+ itDb('ttlSeconds expires the grant', async () => {
+ const r = resourceFor('ttl');
+ await siwxStorage.recordPayment(r, EVM_ADDR_CHECKSUM, {
+ network: EVM_NETWORK,
+ ttlSeconds: 1,
+ });
+ expect(await siwxStorage.hasPaid(r, EVM_ADDR_CHECKSUM)).toBe(true);
+
+ await new Promise((resolve) => setTimeout(resolve, 1500));
+ expect(await siwxStorage.hasPaid(r, EVM_ADDR_CHECKSUM)).toBe(false);
+ });
+
+ itDb('recordNonce + hasUsedNonce round-trip and is idempotent', async () => {
+ const r = resourceFor('nonce');
+ const nonce = `nonce-${RUN_TAG}-${crypto.randomBytes(8).toString('hex')}`;
+
+ expect(await siwxStorage.hasUsedNonce(nonce)).toBe(false);
+
+ await siwxStorage.recordNonce(nonce, { resource: r, address: EVM_ADDR_LOWER });
+ expect(await siwxStorage.hasUsedNonce(nonce)).toBe(true);
+
+ // Second insert must not throw (ON CONFLICT DO NOTHING).
+ await siwxStorage.recordNonce(nonce, { resource: r, address: EVM_ADDR_LOWER });
+ expect(await siwxStorage.hasUsedNonce(nonce)).toBe(true);
+ });
+
+ itDb('pruneOldNonces(0) clears nonces inserted by this run', async () => {
+ const r = resourceFor('gc');
+ const nonce = `nonce-${RUN_TAG}-prune-${crypto.randomBytes(6).toString('hex')}`;
+ await siwxStorage.recordNonce(nonce, { resource: r, address: EVM_ADDR_LOWER });
+ expect(await siwxStorage.hasUsedNonce(nonce)).toBe(true);
+
+ // Force the row to look old by backdating used_at.
+ await sql`update siwx_nonces set used_at = now() - interval '1 hour' where nonce = ${nonce}`;
+
+ const deleted = await pruneOldNonces(0);
+ expect(deleted).toBeGreaterThanOrEqual(1);
+ expect(await siwxStorage.hasUsedNonce(nonce)).toBe(false);
+ });
+
+ itDb('pruneExpiredPayments respects the grace window', async () => {
+ const r = resourceFor('payment-prune');
+ await siwxStorage.recordPayment(r, EVM_ADDR_CHECKSUM, {
+ network: EVM_NETWORK,
+ ttlSeconds: 1,
+ });
+
+ // Just-expired: still inside the default 7-day grace, so the default call
+ // must NOT delete it. Backdate expires_at to confirm a 0-grace call does.
+ await new Promise((resolve) => setTimeout(resolve, 1500));
+ const deletedWithGrace = await pruneExpiredPayments();
+ expect(deletedWithGrace).toBe(0);
+
+ await sql`update siwx_payments set expires_at = now() - interval '8 days' where resource = ${r}`;
+ const deletedNoGrace = await pruneExpiredPayments(0);
+ expect(deletedNoGrace).toBeGreaterThanOrEqual(1);
+ });
+});
diff --git a/tests/api/x402-payment-identifier.test.js b/tests/api/x402-payment-identifier.test.js
new file mode 100644
index 000000000..c9bb1a65c
--- /dev/null
+++ b/tests/api/x402-payment-identifier.test.js
@@ -0,0 +1,325 @@
+// USE-15 tests: payment-identifier idempotency.
+//
+// Exercises the helpers in api/_lib/x402/ directly so they don't depend on
+// Redis. The in-process Map fallback in idempotency-cache.js is what the
+// test runner uses (no UPSTASH_REDIS_REST_URL set in CI).
+//
+// Coverage:
+// • Cache get/set with TTL eviction (in-memory fallback).
+// • Cache hit replays the stored response.
+// • Same id + different payload → conflict signal (server emits 409).
+// • required=true rejects requests with no payment-identifier.
+// • The 402 challenge from paidEndpoint declares the extension.
+// • Buyer hook appends an id when the server advertises support.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+import * as cache from '../../api/_lib/x402/idempotency-cache.js';
+import {
+ checkCache,
+ enforceRequired,
+ extractIdFromHeader,
+ hashRequestPayload,
+ paymentIdentifierExtension,
+ storeResponse,
+ writeCachedResponse,
+ writeConflict,
+ PAYMENT_IDENTIFIER,
+} from '../../api/_lib/x402/payment-identifier-server.js';
+import { installIdempotency } from '../../api/_lib/x402/payment-identifier-client.js';
+
+const ROUTE = '/api/x402/test-route';
+const VALID_ID = 'pay_0123456789abcdef0123456789abcdef';
+const OTHER_ID = 'pay_fedcba9876543210fedcba9876543210';
+
+function encodeHeader(payload) {
+ return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64');
+}
+
+function makeRes() {
+ const res = {
+ statusCode: 200,
+ headers: {},
+ _body: null,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(body) {
+ this._body = body;
+ },
+ };
+ return res;
+}
+
+beforeEach(() => {
+ cache._resetMemoryStore();
+});
+
+describe('idempotency-cache (in-memory fallback)', () => {
+ it('returns null for missing keys', async () => {
+ const got = await cache.get(ROUTE, VALID_ID);
+ expect(got).toBeNull();
+ });
+
+ it('round-trips a response entry within TTL', async () => {
+ const entry = { status: 200, body: '{"ok":true}', payloadHash: 'h1' };
+ await cache.set(ROUTE, VALID_ID, entry, 60);
+ const got = await cache.get(ROUTE, VALID_ID);
+ expect(got).toMatchObject(entry);
+ });
+
+ it('expires entries past the TTL', async () => {
+ vi.useFakeTimers();
+ try {
+ vi.setSystemTime(new Date('2026-05-21T00:00:00Z'));
+ await cache.set(ROUTE, VALID_ID, { body: 'x', payloadHash: 'h1' }, 1);
+ expect(await cache.get(ROUTE, VALID_ID)).toBeTruthy();
+ vi.setSystemTime(new Date('2026-05-21T00:00:02Z'));
+ expect(await cache.get(ROUTE, VALID_ID)).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('hashes the request URL stably', () => {
+ const a = hashRequestPayload({ method: 'GET', url: '/api/x402/dance-tip?dancer=1' });
+ const b = hashRequestPayload({ method: 'GET', url: '/api/x402/dance-tip?dancer=1' });
+ const c = hashRequestPayload({ method: 'GET', url: '/api/x402/dance-tip?dancer=2' });
+ expect(a).toBe(b);
+ expect(a).not.toBe(c);
+ expect(a).toMatch(/^[0-9a-f]{64}$/);
+ });
+});
+
+describe('checkCache + storeResponse', () => {
+ it('reports miss when no entry exists', async () => {
+ const result = await checkCache({ route: ROUTE, paymentId: VALID_ID, payloadHash: 'h1' });
+ expect(result.kind).toBe('miss');
+ });
+
+ it('reports miss when no paymentId is provided', async () => {
+ const result = await checkCache({ route: ROUTE, paymentId: null, payloadHash: 'h1' });
+ expect(result.kind).toBe('miss');
+ });
+
+ it('reports hit when the stored payloadHash matches', async () => {
+ await storeResponse({
+ route: ROUTE,
+ paymentId: VALID_ID,
+ payloadHash: 'h1',
+ status: 200,
+ body: '{"ok":true}',
+ contentType: 'application/json; charset=utf-8',
+ paymentResponseHeader: 'cmVwbGF5',
+ ttlSeconds: 60,
+ });
+ const result = await checkCache({ route: ROUTE, paymentId: VALID_ID, payloadHash: 'h1' });
+ expect(result.kind).toBe('hit');
+ expect(result.entry.body).toBe('{"ok":true}');
+ expect(result.entry.paymentResponseHeader).toBe('cmVwbGF5');
+ });
+
+ it('reports conflict when payloadHash differs from the stored one', async () => {
+ await storeResponse({
+ route: ROUTE,
+ paymentId: VALID_ID,
+ payloadHash: 'h1',
+ status: 200,
+ body: 'a',
+ contentType: 'application/json',
+ paymentResponseHeader: '',
+ ttlSeconds: 60,
+ });
+ const result = await checkCache({
+ route: ROUTE,
+ paymentId: VALID_ID,
+ payloadHash: 'h2',
+ });
+ expect(result.kind).toBe('conflict');
+ expect(result.existingHash).toBe('h1');
+ expect(result.attemptedHash).toBe('h2');
+ });
+});
+
+describe('extractIdFromHeader', () => {
+ it('returns null for missing header', () => {
+ expect(extractIdFromHeader('')).toBeNull();
+ expect(extractIdFromHeader(null)).toBeNull();
+ });
+
+ it('returns null for malformed base64/json', () => {
+ expect(extractIdFromHeader('not-base64-!!!!')).toBeNull();
+ });
+
+ it('extracts a valid id from a base64-encoded payment payload', () => {
+ const header = encodeHeader({
+ x402Version: 2,
+ extensions: {
+ [PAYMENT_IDENTIFIER]: {
+ info: { required: false, id: VALID_ID },
+ },
+ },
+ });
+ expect(extractIdFromHeader(header)).toBe(VALID_ID);
+ });
+
+ it('returns null when the id fails format validation', () => {
+ const header = encodeHeader({
+ extensions: {
+ [PAYMENT_IDENTIFIER]: { info: { required: false, id: 'too-short' } },
+ },
+ });
+ expect(extractIdFromHeader(header)).toBeNull();
+ });
+});
+
+describe('enforceRequired', () => {
+ it('is a no-op when required=false', () => {
+ expect(() => enforceRequired({ paymentHeader: '', required: false })).not.toThrow();
+ });
+
+ it('throws a 400 X402Error when required=true and no id is present', () => {
+ const header = encodeHeader({ x402Version: 2 });
+ let caught;
+ try {
+ enforceRequired({ paymentHeader: header, required: true });
+ } catch (e) {
+ caught = e;
+ }
+ expect(caught).toBeTruthy();
+ expect(caught.status).toBe(400);
+ expect(caught.code).toBe('payment_identifier_required');
+ });
+
+ it('passes when required=true and an id is provided', () => {
+ const header = encodeHeader({
+ extensions: {
+ [PAYMENT_IDENTIFIER]: { info: { required: true, id: VALID_ID } },
+ },
+ });
+ expect(() => enforceRequired({ paymentHeader: header, required: true })).not.toThrow();
+ });
+});
+
+describe('paymentIdentifierExtension declaration', () => {
+ it('builds a v2-shaped extension with `required` and the JSON schema', () => {
+ const ext = paymentIdentifierExtension(true);
+ expect(ext.info.required).toBe(true);
+ expect(ext.schema).toBeDefined();
+ expect(ext.schema.type).toBe('object');
+ expect(ext.schema.properties.id).toMatchObject({ type: 'string' });
+ });
+});
+
+describe('writeCachedResponse + writeConflict', () => {
+ it('writeCachedResponse mirrors stored headers + body and tags as replay', () => {
+ const res = makeRes();
+ writeCachedResponse(res, {
+ status: 200,
+ body: '{"hello":"world"}',
+ contentType: 'application/json; charset=utf-8',
+ paymentResponseHeader: 'cmVwbGF5',
+ });
+ expect(res.statusCode).toBe(200);
+ expect(res.headers['content-type']).toBe('application/json; charset=utf-8');
+ expect(res.headers['x-x402-idempotent']).toBe('replay');
+ expect(res.headers['x-payment-response']).toBe('cmVwbGF5');
+ expect(res._body).toBe('{"hello":"world"}');
+ });
+
+ it('writeConflict emits 409 with the conflicting hashes', () => {
+ const res = makeRes();
+ writeConflict(res, { route: ROUTE, attemptedHash: 'h2', existingHash: 'h1' });
+ expect(res.statusCode).toBe(409);
+ expect(res.headers['x-x402-idempotent']).toBe('conflict');
+ const body = JSON.parse(res._body);
+ expect(body.error).toBe('payment_identifier_conflict');
+ expect(body.attemptedPayloadHash).toBe('h2');
+ expect(body.existingPayloadHash).toBe('h1');
+ });
+});
+
+describe('installIdempotency client hook', () => {
+ it('appends the configured id only when the server declared the extension', async () => {
+ const captured = [];
+ const fakeClient = {
+ onBeforePaymentCreation(fn) {
+ captured.push(fn);
+ return this;
+ },
+ };
+ installIdempotency(fakeClient, { paymentId: VALID_ID });
+ expect(captured).toHaveLength(1);
+
+ // Server does NOT declare the extension → hook should not mutate.
+ const noDeclare = { paymentRequired: { extensions: { other: {} } } };
+ await captured[0](noDeclare);
+ expect(noDeclare.paymentRequired.extensions[PAYMENT_IDENTIFIER]).toBeUndefined();
+
+ // Server DOES declare it → the hook appends our id.
+ const declared = {
+ paymentRequired: {
+ extensions: {
+ [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false),
+ },
+ },
+ };
+ await captured[0](declared);
+ expect(declared.paymentRequired.extensions[PAYMENT_IDENTIFIER].info.id).toBe(VALID_ID);
+ });
+
+ it('generates a fresh id when no paymentId/getPaymentId is provided', async () => {
+ let hook;
+ const fakeClient = { onBeforePaymentCreation: (fn) => { hook = fn; } };
+ installIdempotency(fakeClient);
+ const ctx = {
+ paymentRequired: {
+ extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },
+ },
+ };
+ await hook(ctx);
+ const id = ctx.paymentRequired.extensions[PAYMENT_IDENTIFIER].info.id;
+ expect(typeof id).toBe('string');
+ expect(id.length).toBeGreaterThanOrEqual(16);
+ });
+
+ it('throws when the client does not expose .onBeforePaymentCreation', () => {
+ expect(() => installIdempotency({})).toThrow(/onBeforePaymentCreation/);
+ });
+});
+
+describe('reused-id miss-after-different-route', () => {
+ it('cache keys are scoped per-route so the same id can be reused across routes', async () => {
+ await storeResponse({
+ route: '/api/x402/a',
+ paymentId: VALID_ID,
+ payloadHash: 'h1',
+ status: 200,
+ body: 'a',
+ contentType: 'application/json',
+ paymentResponseHeader: '',
+ ttlSeconds: 60,
+ });
+ const otherRoute = await checkCache({
+ route: '/api/x402/b',
+ paymentId: VALID_ID,
+ payloadHash: 'h1',
+ });
+ expect(otherRoute.kind).toBe('miss');
+ });
+
+ it('different ids on the same route do not collide', async () => {
+ await storeResponse({
+ route: ROUTE,
+ paymentId: VALID_ID,
+ payloadHash: 'h1',
+ status: 200,
+ body: 'a',
+ contentType: 'application/json',
+ paymentResponseHeader: '',
+ ttlSeconds: 60,
+ });
+ const result = await checkCache({ route: ROUTE, paymentId: OTHER_ID, payloadHash: 'h1' });
+ expect(result.kind).toBe('miss');
+ });
+});
diff --git a/tests/siwx-storage.test.js b/tests/siwx-storage.test.js
new file mode 100644
index 000000000..7e2001c14
--- /dev/null
+++ b/tests/siwx-storage.test.js
@@ -0,0 +1,145 @@
+// Integration test for api/_lib/siwx-storage.js against the live Neon
+// Postgres pointed at by $DATABASE_URL. Hits real tables; each run namespaces
+// its rows under `test-resource-<uuid>` and deletes them afterwards so
+// concurrent CI runs don't collide. Skipped when DATABASE_URL is absent.
+
+import { randomUUID } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { beforeAll, afterAll, describe, expect, it } from 'vitest';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(HERE, '..');
+
+for (const envFile of ['.env.local', '.env']) {
+ try {
+ const raw = readFileSync(path.resolve(REPO_ROOT, envFile), 'utf8');
+ for (const line of raw.split('\n')) {
+ const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
+ if (!m || process.env[m[1]]) continue;
+ let val = m[2].trim();
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
+ val = val.slice(1, -1);
+ }
+ process.env[m[1]] = val;
+ }
+ break;
+ } catch {
+ /* file not present */
+ }
+}
+
+const hasDb = !!process.env.DATABASE_URL;
+const describeIfDb = hasDb ? describe : describe.skip;
+
+const RES_PREFIX = `test-resource-${randomUUID()}`;
+const NONCE_PREFIX = `test-nonce-${randomUUID()}`;
+
+describeIfDb('siwx-storage (real Postgres)', () => {
+ /** @type {import('../api/_lib/siwx-storage.js')} */
+ let mod;
+ /** @type {any} */
+ let sql;
+
+ beforeAll(async () => {
+ mod = await import('../api/_lib/siwx-storage.js');
+ ({ sql } = await import('../api/_lib/db.js'));
+ });
+
+ afterAll(async () => {
+ await sql`delete from siwx_payments where resource like ${RES_PREFIX + '%'}`;
+ await sql`delete from siwx_nonces where resource like ${RES_PREFIX + '%'} or nonce like ${NONCE_PREFIX + '%'}`;
+ });
+
+ it('hasPaid returns false for an unknown wallet', async () => {
+ const resource = `${RES_PREFIX}/unknown`;
+ const result = await mod.siwxStorage.hasPaid(
+ resource,
+ '0xdEAd000000000000000000000000000000000000',
+ );
+ expect(result).toBe(false);
+ });
+
+ it('round-trips an EVM payment with mixed-case address', async () => {
+ const resource = `${RES_PREFIX}/evm`;
+ const checksummed = '0xAaBbCcDdEeFf0011223344556677889900AaBbCc';
+ await mod.siwxStorage.recordPayment(resource, checksummed, {
+ network: 'eip155:8453',
+ });
+ expect(await mod.siwxStorage.hasPaid(resource, checksummed)).toBe(true);
+ expect(await mod.siwxStorage.hasPaid(resource, checksummed.toLowerCase())).toBe(true);
+ expect(await mod.siwxStorage.hasPaid(resource, checksummed.toUpperCase())).toBe(true);
+ const rows = await sql`
+ select address from siwx_payments where resource = ${resource}
+ `;
+ expect(rows[0].address).toBe(checksummed.toLowerCase());
+ });
+
+ it('round-trips a Solana payment with case-sensitive Base58', async () => {
+ const resource = `${RES_PREFIX}/sol`;
+ const address = 'BSmWDgE9ex6dZYbiTsJGcwMEgFp8q4aWh92hdErQPeVW';
+ await mod.siwxStorage.recordPayment(resource, address, {
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ });
+ expect(await mod.siwxStorage.hasPaid(resource, address)).toBe(true);
+ expect(await mod.siwxStorage.hasPaid(resource, address.toLowerCase())).toBe(false);
+ });
+
+ it('honors ttlSeconds — payment expires', async () => {
+ const resource = `${RES_PREFIX}/ttl`;
+ const address = '0x1111111111111111111111111111111111111111';
+ await mod.siwxStorage.recordPayment(resource, address, {
+ network: 'eip155:8453',
+ ttlSeconds: 1,
+ });
+ expect(await mod.siwxStorage.hasPaid(resource, address)).toBe(true);
+ await new Promise((r) => setTimeout(r, 1500));
+ expect(await mod.siwxStorage.hasPaid(resource, address)).toBe(false);
+ });
+
+ it('round-trips a nonce and is idempotent', async () => {
+ const nonce = `${NONCE_PREFIX}-once`;
+ const resource = `${RES_PREFIX}/nonce`;
+ expect(await mod.siwxStorage.hasUsedNonce(nonce)).toBe(false);
+ await mod.siwxStorage.recordNonce(nonce, {
+ resource,
+ address: '0xabc0000000000000000000000000000000000000',
+ });
+ expect(await mod.siwxStorage.hasUsedNonce(nonce)).toBe(true);
+ await mod.siwxStorage.recordNonce(nonce, {
+ resource,
+ address: '0xabc0000000000000000000000000000000000000',
+ });
+ expect(await mod.siwxStorage.hasUsedNonce(nonce)).toBe(true);
+ });
+
+ it('pruneOldNonces(0) clears all nonces inserted by the test', async () => {
+ const n1 = `${NONCE_PREFIX}-prune-1`;
+ const n2 = `${NONCE_PREFIX}-prune-2`;
+ await mod.siwxStorage.recordNonce(n1, { resource: `${RES_PREFIX}/p`, address: '0x' });
+ await mod.siwxStorage.recordNonce(n2, { resource: `${RES_PREFIX}/p`, address: '0x' });
+ const removed = await mod.pruneOldNonces(0);
+ expect(removed).toBeGreaterThanOrEqual(2);
+ expect(await mod.siwxStorage.hasUsedNonce(n1)).toBe(false);
+ expect(await mod.siwxStorage.hasUsedNonce(n2)).toBe(false);
+ });
+
+ it('pruneExpiredPayments deletes rows past grace window', async () => {
+ const resource = `${RES_PREFIX}/expired`;
+ const address = '0x2222222222222222222222222222222222222222';
+ await mod.siwxStorage.recordPayment(resource, address, {
+ network: 'eip155:8453',
+ ttlSeconds: 1,
+ });
+ await new Promise((r) => setTimeout(r, 1500));
+ const removed = await mod.pruneExpiredPayments(0);
+ expect(removed).toBeGreaterThanOrEqual(1);
+ expect(await mod.siwxStorage.hasPaid(resource, address)).toBe(false);
+ });
+
+ it('normalizeAddress rejects unknown CAIP-2 namespaces', () => {
+ expect(() => mod.normalizeAddress('cosmos:cosmoshub-4', 'cosmos1abc')).toThrow();
+ });
+});
diff --git a/vercel.json b/vercel.json
index 96a5006ba..40478e657 100644
--- a/vercel.json
+++ b/vercel.json
@@ -49,6 +49,10 @@
"src": "/\\.well-known/jwks\\.json",
"dest": "/api/auth/persona/[action]?action=jwks"
},
+ {
+ "src": "/\\.well-known/did\\.json",
+ "dest": "/api/x402/did"
+ },
{
"src": "/\\.well-known/oauth-authorization-server",
"dest": "/api/wk?name=oauth-authorization-server"
diff --git a/vite.config.js b/vite.config.js
index 22f9ef271..cf53b5622 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -284,6 +284,8 @@ const appConfig = {
'/agent': resolve(root, 'pages/agent-home.html'),
'/docs': resolve(root, 'docs/index.html'),
'/docs/': resolve(root, 'docs/index.html'),
+ '/bazaar': resolve(root, 'public/bazaar.html'),
+ '/bazaar/': resolve(root, 'public/bazaar.html'),
};
// Routes that resolve to public/<dir>/index.html — these need a
// trailing slash so relative imports (./foo.js) inside the HTML