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): x402 checkout replay guard, onchain-deploy + agent endpoint hardening

nirholas5025c7be663d
diff --git a/api/_lib/migrations/20260608020000_x402_checkout_replay_guard.sql b/api/_lib/migrations/20260608020000_x402_checkout_replay_guard.sql
new file mode 100644
index 000000000..045d1a154
--- /dev/null
+++ b/api/_lib/migrations/20260608020000_x402_checkout_replay_guard.sql
@@ -0,0 +1,21 @@
+-- Replay guard for x402 checkout analytics.
+--
+-- api/x402-checkout-record records a settled paid call against a SKU. Without a
+-- uniqueness constraint the same tx_signature could be recorded unlimited times,
+-- letting anyone replay one real payment to inflate a merchant's revenue and
+-- conversion stats (which sum amount_atomics over response_status < 400).
+--
+-- Dedupe any existing duplicate rows (keep the earliest per sku+tx), then enforce
+-- one record per (sku_id, tx_signature). Rows with a null tx_signature (failed or
+-- pre-settlement attempts) are intentionally exempt from the constraint.
+
+DELETE FROM x402_checkout_calls a
+USING x402_checkout_calls b
+WHERE a.tx_signature IS NOT NULL
+ AND a.tx_signature = b.tx_signature
+ AND a.sku_id = b.sku_id
+ AND (a.paid_at > b.paid_at OR (a.paid_at = b.paid_at AND a.ctid > b.ctid));
+
+CREATE UNIQUE INDEX IF NOT EXISTS x402_checkout_calls_sku_tx_uniq
+ ON x402_checkout_calls (sku_id, tx_signature)
+ WHERE tx_signature IS NOT NULL;
diff --git a/api/_lib/onchain-deploy.js b/api/_lib/onchain-deploy.js
index 9fdddf857..53fd94335 100644
--- a/api/_lib/onchain-deploy.js
+++ b/api/_lib/onchain-deploy.js
@@ -29,7 +29,6 @@ import { putObject, publicUrl as r2PublicUrl } from './r2.js';
import {
buildAgentManifest,
buildAgentOnchainAttributes,
- buildAgentRegistrationMetadata,
agentRoyaltyConfig,
agentHomeUrl,
} from './three-brand.js';
@@ -430,15 +429,12 @@ export async function registerAgentOnce({ umi, authoritySigner, agent, asset, co
}
const resolvedCollection = collectionAddr || net.collection || null;
- // Build + pin the registry document (distinct artifact from the asset manifest).
- const registration = buildAgentRegistrationMetadata({
- agentId: agent.id,
- name: agentName,
- description: agent.description || '',
- agentUrl: agentHomeUrl(agent.id),
- skills: Array.isArray(meta.skills) ? meta.skills : undefined,
- });
- const { uri: registrationUri } = await pinManifest(registration, `${agent.id}-registry`);
+ // The Agent Identity PDA stores this URI permanently — the registry program has
+ // no instruction to change it later. So point it at the agent's live, MUTABLE
+ // registration endpoint (served by api/agents/[id]/registration.js from current
+ // data) rather than an immutable pinned snapshot: that keeps `active`, services,
+ // the 3D model, and any future token link accurate without re-registering.
+ const registrationUri = `${env.APP_ORIGIN}/api/agents/${agent.id}/registration`;
const { identityPda, signature, alreadyRegistered } = await registerAgentIdentity({
umi,
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 716c15e4f..764e24ea6 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -243,6 +243,9 @@ export const limits = {
getLimiter('x402:pay:global', { limit: 600, window: '1 h', critical: true }).limit(
'global',
),
+ // x402 checkout analytics record (api/x402-checkout-record). Public + write,
+ // so bound per-IP to stop an attacker scripting fabricated revenue rows.
+ x402RecordIp: (ip) => getLimiter('x402:record:ip', { limit: 30, window: '1 m' }).limit(ip),
checkName: (ip) => getLimiter('check-name:ip', { limit: 60, window: '1 m' }).limit(ip),
ensResolve: (ip) => getLimiter('ens:resolve:ip', { limit: 60, window: '1 m' }).limit(ip),
snsResolve: (ip) => getLimiter('sns:resolve:ip', { limit: 60, window: '1 m' }).limit(ip),
diff --git a/api/_lib/x402/a2a-client.js b/api/_lib/x402/a2a-client.js
index 719145866..fb9845d13 100644
--- a/api/_lib/x402/a2a-client.js
+++ b/api/_lib/x402/a2a-client.js
@@ -4,17 +4,19 @@
// 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
+// 2. Build a `PaymentPayload`, 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.
+// Rails:
+// • Solana (primary) — `exact` scheme as an SPL TransferChecked, built via the
+// official @x402/svm ExactSvmScheme, partially signed by the payer and
+// co-signed by the peer's facilitator fee payer. `createSolanaSigner(secret)`
+// yields the @solana/kit signer; `buildSolanaExactPayload()` the payload.
+// • EVM (fallback) — `exact` scheme as an EIP-3009 transferWithAuthorization.
+// `createPrivateKeySigner(privateKey)` uses viem's accounts API for Base /
+// other EVM chains; `buildEvmExactPayload()` builds the payload.
import { randomBytes, randomUUID } from 'node:crypto';
@@ -399,15 +401,19 @@ export async function submitPayment({
export async function payA2A({
endpoint,
signer,
+ solanaSigner,
+ rpcUrl,
text,
networkPreference,
onQuote,
}) {
if (!endpoint) throw new A2AClientError('invalid_args', 'payA2A: endpoint is required');
- if (!signer || typeof signer.signAuthorization !== 'function') {
+ const hasEvmSigner = signer && typeof signer.signAuthorization === 'function';
+ const hasSolanaSigner = solanaSigner && typeof solanaSigner.address === 'string';
+ if (!hasEvmSigner && !hasSolanaSigner) {
throw new A2AClientError(
'invalid_signer',
- 'payA2A: signer with signAuthorization() is required (try createPrivateKeySigner)',
+ 'payA2A: a Solana signer (createSolanaSigner) or EVM signer (createPrivateKeySigner) is required',
);
}
@@ -420,9 +426,23 @@ export async function payA2A({
}
}
- const accept = pickAccept(required.accepts, networkPreference);
+ // Restrict selection to rails we actually hold a signer for, so we never
+ // pick a Solana accept with only an EVM signer in hand (or vice-versa).
+ const payable = required.accepts.filter((a) =>
+ isSolanaNetwork(a.network) ? hasSolanaSigner : hasEvmSigner,
+ );
+ if (!payable.length) {
+ throw new A2AClientError(
+ 'no_supported_accept',
+ 'payA2A: no peer accept matches an available signer',
+ { accepts: required.accepts.map(({ network, scheme }) => ({ network, scheme })) },
+ );
+ }
+ const accept = pickAccept(payable, networkPreference);
const resource = required.resource || { url: endpoint, mimeType: 'application/json' };
- const paymentPayload = await buildEvmExactPayload({ accept, signer, resource });
+ const paymentPayload = isSolanaNetwork(accept.network)
+ ? await buildSolanaExactPayload({ accept, signer: solanaSigner, resource, rpcUrl })
+ : await buildEvmExactPayload({ accept, signer, resource });
const result = await submitPayment({ endpoint, taskId, paymentPayload });
diff --git a/api/agents/[id].js b/api/agents/[id].js
index fa6acbb62..3d596a4e3 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -9,6 +9,7 @@
* /api/agents/:id/animations — owner-only: replace meta.animations
* /api/agents/:id/embed-policy — read/write embed policy
* /api/agents/:id/manifest — public canonical manifest JSON
+ * /api/agents/:id/registration — public EIP-8004 registry document (Metaplex Agent Registry URI)
* /api/agents/:id/sign — owner-only: sign message with server wallet
* /api/agents/:id/usage — owner-only: LLM usage stats
*
@@ -81,6 +82,11 @@ export default wrap(async function handler(req, res) {
return mod.handleManifest(req, res, id);
}
+ if (sub === 'registration') {
+ const mod = await import('./_id/_sub.js');
+ return mod.handleRegistration(req, res, id);
+ }
+
if (sub === 'sign') {
const mod = await import('./_id/_sub.js');
return mod.handleSign(req, res, id);
diff --git a/api/agents/_id/_sub.js b/api/agents/_id/_sub.js
index be7637eeb..cde570da1 100644
--- a/api/agents/_id/_sub.js
+++ b/api/agents/_id/_sub.js
@@ -271,6 +271,50 @@ export const handleManifest = wrap(async (req, res, id) => {
return json(res, 200, manifest, { 'cache-control': 'public, max-age=60, s-maxage=300, stale-while-revalidate=86400', 'access-control-allow-origin': '*' });
});
+// ── registration (Metaplex / EIP-8004 agent registry document) ─────────────────
+
+// Public EIP-8004 registration-v1 document for the agent. This is the URI the
+// agent's on-chain Agent Identity PDA (Metaplex Agent Registry) points at — the
+// program has no instruction to change the URI after registration, so it must be
+// a stable, MUTABLE endpoint: serving it live keeps `active`, services, the 3D
+// model, and any future token link current without re-registering on-chain.
+export const handleRegistration = wrap(async (req, res, id) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ if (!/^[0-9a-f-]{36}$/i.test(id)) return error(res, 400, 'invalid_request', 'agent id required');
+
+ const [row] = await sql`select a.id, a.name, a.description, a.skills, a.deleted_at, a.chain_id, a.erc8004_agent_id, a.erc8004_registry, av.id as avatar_db_id, av.storage_key, av.thumbnail_key, av.content_type from agent_identities a left join avatars av on av.id = a.avatar_id and av.deleted_at is null where a.id = ${id} and a.deleted_at is null limit 1`;
+ if (!row) return error(res, 404, 'not_found', 'agent not found');
+
+ let modelUri = '';
+ if (row.avatar_db_id) {
+ try { const u = await resolveAvatarUrl({ storage_key: row.storage_key, visibility: 'public' }); modelUri = u?.url || ''; } catch {}
+ }
+ const image = row.thumbnail_key ? r2PublicUrl(row.thumbnail_key) : '';
+
+ const proto = req.headers['x-forwarded-proto'] || 'https';
+ const host = req.headers['x-forwarded-host'] || req.headers.host || 'three.ws';
+ const origin = process.env.PUBLIC_APP_ORIGIN?.replace(/\/$/, '') || `${proto}://${host}`;
+
+ const doc = buildAgentRegistrationMetadata({
+ agentId: row.id,
+ name: row.name || 'Agent',
+ description: row.description || '',
+ image,
+ modelUri,
+ modelFormat: row.content_type || 'gltf-binary',
+ agentUrl: `${origin}/agent/${row.id}`,
+ origin,
+ skills: Array.isArray(row.skills) ? row.skills : [],
+ erc8004: row.chain_id && row.erc8004_agent_id
+ ? { chainId: row.chain_id, agentId: row.erc8004_agent_id, registry: row.erc8004_registry }
+ : null,
+ });
+
+ return json(res, 200, doc, { 'cache-control': 'public, max-age=60, s-maxage=300, stale-while-revalidate=86400', 'access-control-allow-origin': '*' });
+});
+
// ── sign ──────────────────────────────────────────────────────────────────────
const signBody = z.object({ message: z.string().min(1).max(8192), kind: z.enum(['personal']).default('personal') });
diff --git a/api/agents/a2a-call.js b/api/agents/a2a-call.js
index b4183d914..25e3615d0 100644
--- a/api/agents/a2a-call.js
+++ b/api/agents/a2a-call.js
@@ -14,7 +14,9 @@
// trust bar? Opt-in per call.
//
// Settlement itself reuses the existing A2A x402 client (api/_lib/x402/a2a-client.js)
-// so this inherits the spec-compliant two-leg handshake and EIP-3009 signing.
+// so this inherits the spec-compliant two-leg handshake. Solana is the primary
+// rail — USDC SPL TransferChecked, partially signed by the platform payer and
+// co-signed by the peer's facilitator fee payer — with EVM EIP-3009 as fallback.
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
import { cors, error, json, method, rateLimited, readJson, respondError, wrap } from '../_lib/http.js';
@@ -27,27 +29,40 @@ import { assertReputationOk, ReputationError } from '../_lib/a2a/reputation-gate
import {
A2AClientError,
buildEvmExactPayload,
+ buildSolanaExactPayload,
createPrivateKeySigner,
+ createSolanaSigner,
+ isSolanaNetwork,
+ NETWORK_SOLANA_MAINNET,
requestQuote,
submitPayment,
} from '../_lib/x402/a2a-client.js';
-const DEFAULT_NETWORK_PREFERENCE = ['eip155:8453', 'eip155:84532', 'eip155:1'];
+// Solana is the primary settlement rail; EVM chains are the fallback.
+const DEFAULT_NETWORK_PREFERENCE = [
+ NETWORK_SOLANA_MAINNET,
+ 'eip155:8453',
+ 'eip155:84532',
+ 'eip155:1',
+];
// Choose the accept entry to pay against, honoring the caller's network
-// preference and only ever picking an EVM `exact` scheme (what the client signs).
+// preference and only ever picking a `scheme=exact` entry on a rail we can
+// settle — Solana SPL or an EVM chain. Solana is preferred when both are
+// offered without an explicit preference.
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;
}
- for (const a of accepts) {
- if (a.scheme === 'exact' && /^eip155:\d+$/.test(a.network)) return a;
- }
+ const solana = accepts.find((a) => a.scheme === 'exact' && isSolanaNetwork(a.network));
+ if (solana) return solana;
+ const evm = accepts.find((a) => a.scheme === 'exact' && /^eip155:\d+$/.test(a.network));
+ if (evm) return evm;
throw new A2AClientError(
'no_supported_accept',
- 'peer offered no supported (scheme=exact, EVM) accept entry',
+ 'peer offered no supported (scheme=exact) accept entry on Solana or EVM',
{ accepts: accepts.map(({ network, scheme }) => ({ network, scheme })) },
);
}
@@ -171,21 +186,43 @@ export default wrap(async (req, res) => {
}
// ── Settle ──────────────────────────────────────────────────────────────
- const payerKey = env.A2A_PAYER_PRIVATE_KEY;
+ // Pick the payer wallet for the chosen rail. Solana is primary (SPL
+ // TransferChecked co-signed by the peer's facilitator fee payer); EVM is the
+ // fallback (EIP-3009 transferWithAuthorization).
+ const onSolana = isSolanaNetwork(network);
+ const payerKey = onSolana ? env.A2A_PAYER_SOLANA_SECRET : env.A2A_PAYER_PRIVATE_KEY;
if (!payerKey) {
await release(mandate.mandateId, amount);
return error(
res,
501,
'payer_not_configured',
- 'autonomous payer wallet is not configured (set A2A_PAYER_PRIVATE_KEY)',
+ onSolana
+ ? 'autonomous Solana payer wallet is not configured (set A2A_PAYER_SOLANA_SECRET)'
+ : 'autonomous EVM payer wallet is not configured (set A2A_PAYER_PRIVATE_KEY)',
+ { network },
);
}
try {
- const signer = await createPrivateKeySigner(payerKey);
const resource = quote.required.resource || { url: safeEndpoint, mimeType: 'application/json' };
- const paymentPayload = await buildEvmExactPayload({ accept, signer, resource });
+ let signer;
+ let paymentPayload;
+ let payerAddress;
+ if (onSolana) {
+ signer = await createSolanaSigner(payerKey);
+ payerAddress = signer.address;
+ paymentPayload = await buildSolanaExactPayload({
+ accept,
+ signer,
+ resource,
+ rpcUrl: env.SOLANA_RPC_URL,
+ });
+ } else {
+ signer = await createPrivateKeySigner(payerKey);
+ payerAddress = signer.address;
+ paymentPayload = await buildEvmExactPayload({ accept, signer, resource });
+ }
const result = await submitPayment({
endpoint: safeEndpoint,
taskId: quote.taskId,
@@ -208,7 +245,7 @@ export default wrap(async (req, res) => {
amount,
network,
currency: currencyOf(accept) || null,
- payer: signer.address,
+ payer: payerAddress,
spent: reservation.spent,
cap: reservation.cap,
receipts: result.receipts || [],
diff --git a/api/agents/a2a-mandate.js b/api/agents/a2a-mandate.js
index ea387600d..f9e8a2847 100644
--- a/api/agents/a2a-mandate.js
+++ b/api/agents/a2a-mandate.js
@@ -12,7 +12,7 @@
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
-import { issueIntentMandate, MandateError, MAX_TTL_SECONDS, SUPPORTED_NETWORKS } from '../_lib/a2a/mandate.js';
+import { DEFAULT_NETWORK, issueIntentMandate, MandateError, MAX_TTL_SECONDS, SUPPORTED_NETWORKS } from '../_lib/a2a/mandate.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
@@ -32,7 +32,7 @@ export default wrap(async (req, res) => {
maxAtomics,
perCallAtomics,
currency = 'USDC',
- networks = ['eip155:8453'],
+ networks = [DEFAULT_NETWORK],
resources = [],
purpose = '',
ttlSec = 24 * 60 * 60,
diff --git a/api/bounties/[id]/submissions.js b/api/bounties/[id]/submissions.js
index e18801f7b..40e8d9717 100644
--- a/api/bounties/[id]/submissions.js
+++ b/api/bounties/[id]/submissions.js
@@ -1,6 +1,7 @@
import { sql } from '../../_lib/db.js';
-import { cors, json, error, readJson, wrap, method } from '../../_lib/http.js';
+import { cors, json, error, readJson, wrap, method, rateLimited } from '../../_lib/http.js';
import { getSessionUser } from '../../_lib/auth.js';
+import { limits } from '../../_lib/rate-limit.js';
import { enrichLikes } from '../../_lib/bounty-likes.js';
export default wrap(async (req, res) => {
@@ -34,6 +35,10 @@ export default wrap(async (req, res) => {
} catch {
return error(res, 401, 'unauthorized', 'sign in to submit');
}
+ if (!user) return error(res, 401, 'unauthorized', 'sign in to submit');
+
+ const rl = await limits.bountySubmit(user.id);
+ if (!rl.success) return rateLimited(res, rl, 'too many submissions, slow down');
const [bounty] = await sql`
SELECT id, status, expires_at FROM bounties
@@ -45,11 +50,20 @@ export default wrap(async (req, res) => {
return error(res, 409, 'bounty_expired', 'bounty has expired');
}
- const body = await readJson(req);
+ const body = await readJson(req, 16_000);
const { content, media_url, media_type } = body;
if (!content?.trim() && !media_url?.trim()) {
return error(res, 400, 'bad_request', 'provide a description or media URL');
}
+ // Bound free-text and validate the media URL shape — it's rendered to every
+ // other user, so reject oversized content and non-http(s) links.
+ if (typeof content === 'string' && content.length > 4000)
+ return error(res, 400, 'bad_request', 'content too long (max 4000)');
+ if (typeof media_url === 'string' && media_url.trim()) {
+ const u = media_url.trim();
+ if (u.length > 2000 || !/^https?:\/\//i.test(u))
+ return error(res, 400, 'bad_request', 'media_url must be a valid http(s) URL');
+ }
const validTypes = ['image', 'video', 'link'];
const mtype =
diff --git a/scripts/test-registry-canary.mjs b/scripts/test-registry-canary.mjs
index e085d92e1..d3184c252 100644
--- a/scripts/test-registry-canary.mjs
+++ b/scripts/test-registry-canary.mjs
@@ -53,6 +53,10 @@ function explorer(addr, network) {
async function main() {
const network = arg('--network', 'devnet') === 'mainnet' ? 'mainnet' : 'devnet';
const count = Math.min(5, Math.max(1, Number(arg('--count', '2'))));
+ // The registry reads this URI live; the canonical EIP-8004 doc has active:true +
+ // x402Support:true, so the agent renders "Active" (vs the agent-card.json which
+ // lacks those fields and shows "Inactive"). Override with --uri.
+ const registrationUri = arg('--uri', 'https://three.ws/.well-known/agent-registration.json');
const kp = Keypair.fromSecretKey(bs58.decode(loadTestSecret()));
const address = kp.publicKey.toString();
@@ -97,7 +101,7 @@ async function main() {
asset,
owner: signer.publicKey,
name: `Registry Canary ${i}`,
- uri: 'https://three.ws/.well-known/agent-card.json',
+ uri: registrationUri,
}).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });
const assetAddr = asset.publicKey.toString();
console.log(` asset: ${assetAddr}`);
@@ -109,7 +113,7 @@ async function main() {
authoritySigner: signer,
asset: assetAddr,
// standalone asset — no collection; the wallet is its own update authority
- registrationUri: 'https://three.ws/.well-known/agent-card.json',
+ registrationUri,
});
ok++;
console.log(` ✓ identity PDA: ${r.identityPda}${r.alreadyRegistered ? ' (already)' : ''}`);