Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(payments): scope redeem idempotency to the caller and stop pricing dead endpoints as free
nirholas7f4a7c5c00ec
diff --git a/api/_lib/pay/probe.js b/api/_lib/pay/probe.jsindex 1a78cc4d1..dd9619d98 100644--- a/api/_lib/pay/probe.js+++ b/api/_lib/pay/probe.js@@ -139,7 +139,18 @@ export async function probePrice(rawUrl, { method = 'GET', body = null, timeoutM}if (res.status !== 402) {- return { kind: 'free', status: res.status };+ // Only a SUCCESS without a challenge is free. An endpoint that answers 404,+ // 400, or 500 is broken, not free, and calling it free was the wrong answer+ // to the one question the simulator exists to answer: a workload whose every+ // call errored came back `feasible: true` at a cost of $0, because each dead+ // endpoint scored as a free call and free calls never enter the replay.+ if (res.ok) return { kind: 'free', status: res.status };+ return {+ kind: 'error',+ code: 'endpoint_error',+ message: `Endpoint answered HTTP ${res.status} with no payment challenge`,+ status: res.status,+ };}const challenge = readChallenge(res);diff --git a/api/pay/execute.js b/api/pay/execute.jsindex fe8fc8774..fda59ab2b 100644--- a/api/pay/execute.js+++ b/api/pay/execute.js@@ -77,7 +77,10 @@ function loadSolanaKeypair() {}// ── Probe a 402 endpoint and select a Solana USDC accept ────────────────────-async function probe402(rawUrl, { method, body }) {+// Exported for tests/pay-probe-endpoint-error.test.js: this is where a caller's+// URL turns into an amount the session is about to be charged, so its refusals+// are worth pinning independently of the signing path around them.+export async function probe402(rawUrl, { method, body }) {let res;try {res = await guardedFetch(rawUrl, { method, body });@@ -93,7 +96,26 @@ async function probe402(rawUrl, { method, body }) {}if (res.status !== 402) {- return { free: true, status: res.status, result: safeJson(res.text) ?? res.text };+ // A success without a challenge is genuinely free and is handed straight+ // back. An error status is not: answering `ok: true, paid: false, "no+ // payment needed"` for a 500 told the agent its call succeeded for free+ // when the endpoint had in fact failed. Nothing was signed and no budget+ // was reserved at this point, so this is a clean 502 about the endpoint.+ if (res.ok) {+ return { free: true, status: res.status, result: safeJson(res.text) ?? res.text };+ }+ const parsed = safeJson(res.text);+ throw Object.assign(+ new Error(`Endpoint answered HTTP ${res.status} with no payment challenge, so there was nothing to pay`),+ {+ status: 502,+ code: 'endpoint_error',+ detail: {+ upstream_status: res.status,+ upstream_body: parsed ?? String(res.text ?? '').slice(0, 500),+ },+ },+ );}const challenge = readChallenge(res);@@ -228,8 +250,13 @@ export default wrap(async (req, res) => {const rl = await limits.authIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const body = await readJson(req, res);- if (!body) return;+ // readJson's second argument is a byte limit, not the response. Passing `res`+ // there made every size comparison `n > [object]`, i.e. NaN, i.e. false, so+ // the 1 MB body cap this call was meant to apply never applied at all.+ const body = await readJson(req);+ if (!body || typeof body !== 'object') {+ return error(res, 400, 'invalid_body', 'a JSON object body is required');+ }const sessionToken = body.session_token;if (!sessionToken) return error(res, 400, 'missing_token', 'session_token is required');diff --git a/api/pay/session.js b/api/pay/session.jsindex f60555743..eb19fcb2c 100644--- a/api/pay/session.js+++ b/api/pay/session.js@@ -42,6 +42,24 @@ function parsePath(req) {return m ? { id: m[1], sub: m[2] ?? null } : { id: null, sub: null };}+/**+ * Read a JSON object body, answering the caller when it is not one.+ *+ * readJson's second parameter is a byte limit, not the response: passing `res`+ * there turned every `length > [object]` comparison into false and silently+ * disabled the 1 MB cap. Returning `null` on a non-object body (rather than+ * letting the caller return without writing a response) also closes the path+ * where a request would hang instead of getting an answer.+ */+async function readJsonObject(req, res) {+ const body = await readJson(req);+ if (!body || typeof body !== 'object') {+ error(res, 400, 'invalid_body', 'a JSON object body is required');+ return null;+ }+ return body;+}+/*** Read `limit` and `cursor` off the query string, clamped to values the SQL can* actually take. Both reach Postgres verbatim otherwise: a negative limit@@ -73,7 +91,7 @@ export default wrap(async (req, res) => {// POST /api/pay/session: createif (!id && httpMethod === 'POST') {if (!method(req, res, ['POST'])) return;- const body = await readJson(req, res);+ const body = await readJsonObject(req, res);if (!body) return;let result;@@ -165,7 +183,7 @@ export default wrap(async (req, res) => {// PATCH /api/pay/session/:id: update mutable fields on an active sessionif (httpMethod === 'PATCH') {- const body = await readJson(req, res);+ const body = await readJsonObject(req, res);if (!body) return;const updates = {};diff --git a/api/pay/simulate.js b/api/pay/simulate.jsindex a94f22c62..a953a7f5a 100644--- a/api/pay/simulate.js+++ b/api/pay/simulate.js@@ -367,8 +367,13 @@ export default wrap(async (req, res) => {const rl = await limits.authIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const body = await readJson(req, res);- if (!body) return;+ // The second argument is a byte limit, not the response object: passing `res`+ // silently disabled the 1 MB cap, since every `length > [object]` compare is+ // false. Returning without answering on a falsy body would hang the request.+ const body = await readJson(req);+ if (!body || typeof body !== 'object') {+ return bad(res, 'invalid_body', 'a JSON object body is required');+ }let calls;try {diff --git a/api/payments/evm/[action].js b/api/payments/evm/[action].jsindex d07768c83..861d36f89 100644--- a/api/payments/evm/[action].js+++ b/api/payments/evm/[action].js@@ -60,12 +60,23 @@ async function handleConfirm(req, res) {if (!rl.success) return rateLimited(res, rl);const body = parse(confirmSchema, await readJson(req));const { intent_id, tx_hash } = body;- const [intent] = await sql`select * from plan_payment_intents where id = ${intent_id} and user_id = ${user.id} limit 1`;+ // Scoped to this lane: the Solana lane writes into the same table, and an+ // unscoped lookup let an EVM confirm read (and expire) a Solana intent, which+ // then failed downstream as a confusing "chain null not supported".+ const [intent] = await sql`select * from plan_payment_intents where id = ${intent_id} and user_id = ${user.id} and chain_type = 'evm' limit 1`;if (!intent) return error(res, 404, 'not_found', 'intent not found');if (intent.status === 'confirmed') return error(res, 409, 'already_confirmed', 'payment already confirmed');- if (intent.status === 'expired' || new Date(intent.expires_at) < new Date()) {- await sql`update plan_payment_intents set status='expired' where id=${intent_id}`;- return error(res, 410, 'intent_expired', 'payment session expired — start a new checkout');+ if (intent.status === 'failed') return error(res, 410, 'intent_expired', 'payment session is no longer usable');+ // Confirming requires MIN_CONFIRMATIONS blocks of depth below, so a transfer+ // broadcast near the end of the session cannot possibly be confirmable before+ // the session lapses. Honor a confirm inside a bounded grace window rather+ // than stranding funds that are already on-chain: the USDC amount was pinned+ // at checkout and USDC is 1:1 with the USD price, so the window carries no+ // price-drift exposure. Mirrors the Solana lane's grace window.+ const CONFIRM_GRACE_MS = 60 * 60 * 1000;+ if (new Date(intent.expires_at).getTime() + CONFIRM_GRACE_MS < Date.now()) {+ await sql`update plan_payment_intents set status='expired' where id=${intent_id} and status='pending'`;+ return error(res, 410, 'intent_expired', 'payment session expired, start a new checkout');}const chainId = intent.chain_id;const chain = CHAINS[chainId];@@ -114,16 +125,18 @@ async function handleConfirm(req, res) {// All three writes are in a single transaction so a crash between intent-claim// and the subscription/user grant can't leave the user paid but unsubscribed.- // The intent UPDATE uses status='pending' (not != 'confirmed') so an already-- // expired intent can't slip through a race between the expiry check above and- // this write. On a unique-index violation (concurrent confirm with same tx_hash)- // the entire transaction rolls back and we return 409.+ // The intent UPDATE names the two claimable statuses explicitly (never+ // != 'confirmed') so a concurrent confirm can claim the row exactly once and+ // a 'failed' intent can never be revived; 'expired' is claimable because the+ // grace window above already decided this confirm is still in time. On a+ // unique-index violation (concurrent confirm with same tx_hash) the entire+ // transaction rolls back and we return 409.const planConfig = PLANS[intent.plan];const activeUntil = new Date(Date.now() + planConfig.duration_days * 86400 * 1000);let claimed;try {[claimed] = await sql.transaction([- sql`update plan_payment_intents set status='confirmed', tx_hash=${tx_hash}, confirmed_at=now() where id=${intent_id} and status = 'pending' returning id`,+ sql`update plan_payment_intents set status='confirmed', tx_hash=${tx_hash}, confirmed_at=now() where id=${intent_id} and status in ('pending', 'expired') returning id`,sql`insert into subscriptions (user_id, plan, chain_type, chain_id, token_address, tx_hash, amount_usd, status, active_until) values (${user.id}, ${intent.plan}, 'evm', ${chainId}, ${usdcAddress}, ${tx_hash}, ${intent.amount_usdc}, 'active', ${activeUntil}) on conflict (user_id) where status='active' do update set plan=excluded.plan, chain_type=excluded.chain_type, chain_id=excluded.chain_id, token_address=excluded.token_address, tx_hash=excluded.tx_hash, amount_usd=excluded.amount_usd, active_until=excluded.active_until, updated_at=now()`,sql`update users set plan=${intent.plan} where id=${user.id}`,]);diff --git a/api/payments/intent.js b/api/payments/intent.jsindex e6da53d07..333cb572b 100644--- a/api/payments/intent.js+++ b/api/payments/intent.js@@ -6,14 +6,26 @@* This is the agent_payment_intents–based flow (distinct from the* skill_purchases Solana Pay reference flow at /api/marketplace/purchase).*/+import { z } from 'zod';+import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';+import { parse } from '../_lib/validate.js';import { nanoid } from 'nanoid';const INTENT_TTL_MINUTES = 15;+// agent_id has to be uuid-shaped before it reaches Postgres: an unvalidated+// value went straight into a uuid-typed parameter, so "not-a-uuid" (or any+// non-string JSON value) raised SQLSTATE 22P02 and surfaced as a 500 plus an+// ops alert, when it is plain caller error and belongs in a 400.+const bodySchema = z.object({+ agent_id: z.string().uuid(),+ skill: z.string().trim().min(1).max(200),+});+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;@@ -24,13 +36,9 @@ export default wrap(async (req, res) => {const rl = await limits.authIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- let body;- try { body = await readJson(req); } catch { return error(res, 400, 'invalid_json', 'request body is not valid JSON'); }- const agent_id = body?.agent_id;- const skill = typeof body?.skill === 'string' ? body.skill.trim() : null;- if (!agent_id || !skill) {- return error(res, 400, 'validation_error', 'agent_id and skill are required');- }+ // readJson answers 415 on a wrong content-type and 400 on unparseable JSON,+ // and parse() answers 400 with the offending field, all through wrap().+ const { agent_id, skill } = parse(bodySchema, await readJson(req));// Fetch active skill priceconst [price] = await sql`diff --git a/api/payments/solana/[action].js b/api/payments/solana/[action].jsindex ae5aa5320..a3ffc5e45 100644--- a/api/payments/solana/[action].js+++ b/api/payments/solana/[action].js@@ -40,15 +40,25 @@ function usdToAtomicsCeil(usd, assetPriceUsd, decimals) {// ── checkout ──────────────────────────────────────────────────────────────────+// Devnet is only accepted in non-production environments. Accepting devnet+// USDC (free from a faucet) in production would let anyone upgrade for free.+// Checkout and confirm share this one enum on purpose: confirm picks both the+// RPC it queries and the USDC mint it accepts from its own `network` field, so+// a mainnet-only checkout paired with a devnet-tolerant confirm still hands out+// free plans (create a mainnet intent, pay its nonce with faucet USDC on devnet,+// confirm with network=devnet). The intent row carries no cluster column, so+// keeping the two schemas literally the same value is what closes that door.+const networkEnum = z+ .enum(process.env.NODE_ENV === 'production' ? ['mainnet'] : ['mainnet', 'devnet'])+ .default('mainnet');+const checkoutSchema = z.object({plan: z.enum(['pro', 'team', 'enterprise']),// USDC settles 1:1 with the USD price. SOL and $THREE are quoted at the// live market price when the session is created; paying in $THREE takes the// platform-coin discount (threePlanDiscountBps).asset: z.enum(['USDC', 'SOL', 'THREE']).default('USDC'),- // Devnet is only accepted in non-production environments. Accepting devnet- // USDC (free from faucet) in production would let anyone upgrade for free.- network: z.enum(process.env.NODE_ENV === 'production' ? ['mainnet'] : ['mainnet', 'devnet']).default('mainnet'),+ network: networkEnum,});async function handleCheckout(req, res) {@@ -126,7 +136,7 @@ async function handleCheckout(req, res) {const confirmSchema = z.object({intent_id: z.string().uuid(),tx_signature: z.string().min(80).max(100),- network: z.enum(['mainnet', 'devnet']).default('mainnet'),+ network: networkEnum,});async function handleConfirm(req, res) {diff --git a/api/permissions/[action].js b/api/permissions/[action].jsindex f61535ef1..5bdbf3442 100644--- a/api/permissions/[action].js+++ b/api/permissions/[action].js@@ -677,30 +677,6 @@ function periodStart(period) {return new Date(0);}-// Keyless single-endpoint defaults, used only when RPC_URL_<chainId> is unset.-// dRPC for chain 1 / Sepolia: cloudflare-eth.com is sunset and rpc.sepolia.org is-// dead, so the old defaults guaranteed a relayer failure on any deploy without an-// explicit RPC env. dRPC answers keyless from datacenter IPs (probed live).-const PERMISSIONS_PUBLIC_RPCS = {- 1: 'https://eth.drpc.org',- 8453: 'https://mainnet.base.org',- 84532: 'https://sepolia.base.org',- 11155111: 'https://sepolia.drpc.org',- 421614: 'https://sepolia-rollup.arbitrum.io/rpc',- 11155420: 'https://sepolia.optimism.io',-};--function getRpcUrl(chainId) {- return (- process.env[`RPC_URL_${chainId}`] ||- // Shared fallback names that might already exist in the project- (chainId === 84532 ? process.env.BASE_SEPOLIA_RPC_URL : null) ||- (chainId === 11155111 ? process.env.SEPOLIA_RPC_URL : null) ||- PERMISSIONS_PUBLIC_RPCS[chainId] ||- null- );-}-async function handleRedeem(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (!method(req, res, ['POST'])) return;@@ -740,9 +716,15 @@ async function handleRedeem(req, res) {}const { id, calls } = body;- // Idempotency-Key early return- if (idempotencyKey) {- const cached = idempotencyGet(`${id}:${idempotencyKey}`);+ // Idempotency-Key early return. The cache key carries the bearer principal+ // because this lookup runs before the ownership gate below: keyed on the+ // delegation id alone, a principal who does not own the delegation could+ // replay someone else's (id, key) pair and be handed their txHash and+ // receipt. Scoping to the principal makes a retry idempotent only for the+ // caller who made the original call.+ const idempotencyScope = idempotencyKey ? `${bearer.userId}:${id}:${idempotencyKey}` : null;+ if (idempotencyScope) {+ const cached = idempotencyGet(idempotencyScope);if (cached) return json(res, 200, cached);}@@ -791,6 +773,21 @@ async function handleRedeem(req, res) {const scope = row.scope;const chainId = row.chain_id;+ // The relayer redeems through the chain's DelegationManager, so a row on a+ // chain with no deployment can never settle. Grant, revoke, and verify all+ // gate on this map; redeem used to reach `redeemDelegation`, have+ // `managerAddress()` throw, and report it as a 502 rpc_error: a chain+ // support gap dressed up as a provider outage. Checked here, before the+ // spend reservation, so there is nothing to release.+ if (!DELEGATION_MANAGER_DEPLOYMENTS[chainId]) {+ return error(+ res,+ 409,+ 'chain_not_supported',+ `no DelegationManager deployment for chainId ${chainId}`,+ );+ }+// ── Server-side scope checks (cheap, prevent paying gas on doomed tx) ────// 1. Target allow-list@@ -906,24 +903,30 @@ async function handleRedeem(req, res) {);// ── Build signer ───────────────────────────────────────────────────────- const rpcUrl = getRpcUrl(chainId);- if (!rpcUrl) {- await releaseReservation();- return error(- res,- 502,- 'rpc_error',- `no RPC URL configured for chain ${chainId} (set RPC_URL_${chainId})`,- );- }-+ // evmFallbackProvider owns endpoint resolution for every chain: an explicit+ // RPC_URL_<chainId> override first, then Alchemy, then the curated public+ // endpoints, with sequential failover across all of them. This handler used+ // to carry its own hand-copied one-endpoint-per-chain table and 502 on any+ // chain missing from it, which would have failed the next DelegationManager+ // deployment on a chain the shared layer can already reach.let signer;try {- const provider = await evmFallbackProvider(chainId, { primaryUrl: rpcUrl });+ const provider = await evmFallbackProvider(chainId);// AGENT_RELAYER_KEY is never logged — only use it to construct the Walletsigner = new Wallet(env.AGENT_RELAYER_KEY, provider);- } catch {+ } catch (err) {await releaseReservation();+ // `no RPC endpoint for chain N` is a deployment gap, not a code fault:+ // report it as an upstream failure the operator can fix with RPC_URL_<id>+ // rather than as a generic internal error.+ if (/no RPC endpoint/i.test(err?.message || '')) {+ return error(+ res,+ 502,+ 'rpc_error',+ `no RPC endpoint available for chain ${chainId} (set RPC_URL_${chainId})`,+ );+ }return error(res, 500, 'internal_error', 'failed to initialise relayer signer');}@@ -971,8 +974,8 @@ async function handleRedeem(req, res) {const result = { ok: true, txHash, receipt };- if (idempotencyKey) {- idempotencySet(`${id}:${idempotencyKey}`, result);+ if (idempotencyScope) {+ idempotencySet(idempotencyScope, result);}return json(res, 200, result);diff --git a/tests/pay-probe-endpoint-error.test.js b/tests/pay-probe-endpoint-error.test.jsnew file mode 100644index 000000000..9b64ab513--- /dev/null+++ b/tests/pay-probe-endpoint-error.test.js@@ -0,0 +1,139 @@+/**+ * A dead endpoint is not a free endpoint.+ *+ * Both x402 probes (the dry-run simulator's `probePrice` and the executor's+ * `probe402`) used to treat every non-402 response as "served without a+ * challenge, so it costs nothing". That is only true of a SUCCESS. A 404, a 400,+ * or a 500 is an endpoint that failed, and calling it free produced the exact+ * wrong answer in the two places it matters most:+ *+ * - the simulator reported `feasible: true` at a cost of $0 for a workload+ * whose every call was erroring, because a free call never enters the policy+ * replay and so can never be refused. That is the one question /api/pay/simulate+ * exists to answer, answered backwards.+ * - the executor answered `200 {ok: true, paid: false, note: "Endpoint served+ * response without a 402. No payment needed."}` for an upstream 500, so an+ * agent read a failure as a successful free call.+ *+ * The network is stubbed at the fetch boundary; the SSRF guard chain is pinned by+ * its own suite (tests/x402-rate-limit-probe-target.test.js and friends), and the+ * address resolution below is inert because no socket is ever opened.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++vi.mock('../api/_lib/ssrf.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ resolvePublicHost: async () => ['203.0.113.10'],+ pinnedAgent: () => ({ close: async () => {} }),+ };+});++const { probePrice, USDC_SOLANA_MINT } = await import('../api/_lib/pay/probe.js');+const { probe402 } = await import('../api/pay/execute.js');++const URL_UNDER_TEST = 'https://api.example.com/data';++function reply(status, body, headers = {}) {+ globalThis.fetch = vi.fn(async () => new Response(body, { status, headers }));+}++function challengeBody(accepts) {+ return JSON.stringify({ x402Version: 2, resource: URL_UNDER_TEST, accepts });+}++const SOLANA_ACCEPT = {+ scheme: 'exact',+ network: 'solana',+ amount: '1000',+ asset: USDC_SOLANA_MINT,+ payTo: '9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM',+ extra: { feePayer: 'FEEPAYer1111111111111111111111111111111111' },+};++let realFetch;+beforeEach(() => { realFetch = globalThis.fetch; });+afterEach(() => { globalThis.fetch = realFetch; vi.restoreAllMocks(); });++describe('probePrice: only a success is free', () => {+ it('reports a 2xx with no challenge as free', async () => {+ reply(200, JSON.stringify({ ok: true }));+ const probe = await probePrice(URL_UNDER_TEST);+ expect(probe).toMatchObject({ kind: 'free', status: 200 });+ });++ it('reports a 404 as an endpoint error, never as free', async () => {+ reply(404, 'no such route');+ const probe = await probePrice(URL_UNDER_TEST);+ expect(probe.kind).toBe('error');+ expect(probe.code).toBe('endpoint_error');+ expect(probe.status).toBe(404);+ });++ it('reports a 500 as an endpoint error, never as free', async () => {+ reply(500, 'boom');+ const probe = await probePrice(URL_UNDER_TEST);+ expect(probe.kind).toBe('error');+ expect(probe.code).toBe('endpoint_error');+ expect(probe.message).toMatch(/HTTP 500/);+ });++ it('still parses a real 402 challenge into rails', async () => {+ reply(402, challengeBody([SOLANA_ACCEPT]));+ const probe = await probePrice(URL_UNDER_TEST);+ expect(probe.kind).toBe('priced');+ expect(probe.rails[0]).toMatchObject({ network: 'solana', amount_atomics: '1000' });+ });+});++describe('probe402: an upstream failure is not a free call', () => {+ it('passes a 2xx straight back as free', async () => {+ reply(200, JSON.stringify({ answer: 42 }));+ const result = await probe402(URL_UNDER_TEST, { method: 'GET', body: null });+ expect(result).toMatchObject({ free: true, status: 200 });+ expect(result.result).toEqual({ answer: 42 });+ });++ it('raises a 502 endpoint_error for an upstream 500, carrying the real status', async () => {+ reply(500, JSON.stringify({ error: 'upstream exploded' }));+ const err = await probe402(URL_UNDER_TEST, { method: 'GET', body: null }).catch((e) => e);+ expect(err).toBeInstanceOf(Error);+ expect(err.status).toBe(502);+ expect(err.code).toBe('endpoint_error');+ expect(err.detail).toEqual({+ upstream_status: 500,+ upstream_body: { error: 'upstream exploded' },+ });+ });++ it('raises the same error for a 4xx, so a bad request is never billed as free', async () => {+ reply(400, 'claim is required');+ const err = await probe402(URL_UNDER_TEST, { method: 'POST', body: {} }).catch((e) => e);+ expect(err.code).toBe('endpoint_error');+ expect(err.detail.upstream_status).toBe(400);+ expect(err.detail.upstream_body).toBe('claim is required');+ });++ it('selects the Solana USDC accept from a real challenge', async () => {+ reply(402, challengeBody([{ ...SOLANA_ACCEPT, network: 'base', asset: '0xdead' }, SOLANA_ACCEPT]));+ const result = await probe402(URL_UNDER_TEST, { method: 'GET', body: null });+ expect(result.accept.asset).toBe(USDC_SOLANA_MINT);+ expect(result.amountAtomics).toBe(1000n);+ });++ it('refuses a challenge that quotes an unreadable price rather than throwing raw', async () => {+ reply(402, challengeBody([{ ...SOLANA_ACCEPT, amount: 'free!' }]));+ const err = await probe402(URL_UNDER_TEST, { method: 'GET', body: null }).catch((e) => e);+ expect(err.status).toBe(422);+ expect(err.code).toBe('invalid_amount');+ });++ it('refuses a non-positive price, which cannot be paid', async () => {+ reply(402, challengeBody([{ ...SOLANA_ACCEPT, amount: '0' }]));+ const err = await probe402(URL_UNDER_TEST, { method: 'GET', body: null }).catch((e) => e);+ expect(err.status).toBe(422);+ expect(err.code).toBe('invalid_amount');+ });+});diff --git a/tests/permissions-api.test.js b/tests/permissions-api.test.jsindex 0842bb2ba..94c5fbb4d 100644--- a/tests/permissions-api.test.js+++ b/tests/permissions-api.test.js@@ -68,20 +68,26 @@ vi.mock('../api/_lib/usage.js', () => ({ recordEvent: vi.fn() }));const providerCalls = [];const chainDisabled = { value: false };const providerFails = { value: false };+// Set to simulate the shared RPC layer having no endpoint at all for a chain.+// The real evmFallbackProvider throws `no RPC endpoint for chain <id>` there.+const providerBuildFails = { value: false };vi.mock('../api/_lib/evm/rpc.js', () => ({- evmFallbackProvider: async () => ({- async call(tx) {- if (providerFails.value) throw new Error('rpc unreachable');- providerCalls.push(tx);- return AbiCoder.defaultAbiCoder().encode(['bool'], [chainDisabled.value]);- },- async getNetwork() {- return { chainId: 84532n, name: 'base-sepolia' };- },- async resolveName(n) {- return n;- },- }),+ evmFallbackProvider: async (chainId) => {+ if (providerBuildFails.value) throw new Error(`no RPC endpoint for chain ${chainId}`);+ return {+ async call(tx) {+ if (providerFails.value) throw new Error('rpc unreachable');+ providerCalls.push(tx);+ return AbiCoder.defaultAbiCoder().encode(['bool'], [chainDisabled.value]);+ },+ async getNetwork() {+ return { chainId: 84532n, name: 'base-sepolia' };+ },+ async resolveName(n) {+ return n;+ },+ };+ },}));// redeem must never reach a real chain from a unit test; the handler's own@@ -169,9 +175,9 @@ beforeEach(() => {providerCalls.length = 0;chainDisabled.value = false;providerFails.value = false;+ providerBuildFails.value = false;rlOk.value = true;envStub.PERMISSIONS_RELAYER_ENABLED = true;- delete process.env.RPC_URL_137;});describe('permissions dispatcher', () => {@@ -534,10 +540,11 @@ describe('POST /api/permissions/redeem', () => {// Regression: the reservation is written before the signer is built, so an exit// between the two has to release it. It used to leak, permanently consuming the// delegation's period budget for a request that never touched the chain.- it('releases the spend reservation when no RPC is configured for the chain', async () => {+ it('releases the spend reservation when the chain has no reachable RPC endpoint', async () => {bearer();+ providerBuildFails.value = true;sqlQueue.push(- [delegationRow({ chain_id: 137 })],+ [delegationRow()],[{ user_id: 'user-1' }],[{ id: 'usage-1', spent_before: '0' }],[],@@ -545,9 +552,64 @@ describe('POST /api/permissions/redeem', () => {const res = await call({ action: 'redeem', method: 'POST', body: okBody });expect(res.statusCode).toBe(502);expect(parse(res).error).toBe('rpc_error');+ expect(redeemDelegationMock).not.toHaveBeenCalled();// Last statement must be the release, keyed on the reservation just written.const lastArgs = sqlMock.mock.calls.at(-1);expect(lastArgs[0].join('?')).toContain("status = 'failed'");expect(lastArgs).toContain('usage-1');});++ // A delegation row on a chain with no DelegationManager can never settle.+ // It used to reach redeemDelegation, have managerAddress() throw, and come+ // back as a 502 rpc_error, which reads as a provider outage rather than the+ // chain-support gap it is. The gate also runs before the spend reservation,+ // so an unsettleable chain never touches the period budget.+ it('rejects a delegation on a chain with no DelegationManager before reserving spend', async () => {+ bearer();+ sqlQueue.push([delegationRow({ chain_id: 137 })], [{ user_id: 'user-1' }]);+ const res = await call({ action: 'redeem', method: 'POST', body: okBody });+ expect(res.statusCode).toBe(409);+ expect(parse(res).error).toBe('chain_not_supported');+ expect(redeemDelegationMock).not.toHaveBeenCalled();+ // Only the two lookups ran: no reservation INSERT, so nothing to release.+ expect(sqlMock).toHaveBeenCalledTimes(2);+ });++ // The Idempotency-Key lookup runs before the ownership gate, so a cache keyed+ // on the delegation id alone handed a non-owner the owner's txHash and receipt+ // if they replayed the same (id, key) pair. The key carries the principal now.+ it('does not replay one principal\'s idempotent result to another', async () => {+ const headers = { 'idempotency-key': 'k-1' };+ redeemDelegationMock.mockResolvedValue({+ txHash: '0xfeed',+ receipt: { status: 1, blockNumber: 7, gasUsed: '21000' },+ });++ bearer({ userId: 'user-1' });+ sqlQueue.push(+ [delegationRow()],+ [{ user_id: 'user-1' }],+ [{ id: 'usage-1', spent_before: '0' }],+ [],+ [],+ );+ const first = await call({ action: 'redeem', method: 'POST', body: okBody, headers });+ expect(first.statusCode).toBe(200);+ expect(parse(first).txHash).toBe('0xfeed');++ // A different principal replaying the same id + key must be refused by the+ // ownership gate, not served the cached receipt.+ bearer({ userId: 'user-2' });+ sqlQueue.push([delegationRow()], [{ user_id: 'user-1' }]);+ const replay = await call({ action: 'redeem', method: 'POST', body: okBody, headers });+ expect(replay.statusCode).toBe(404);+ expect(parse(replay).error).toBe('delegation_not_found');++ // The original caller still gets its cached result without a second submit.+ bearer({ userId: 'user-1' });+ const retry = await call({ action: 'redeem', method: 'POST', body: okBody, headers });+ expect(retry.statusCode).toBe(200);+ expect(parse(retry).txHash).toBe('0xfeed');+ expect(redeemDelegationMock).toHaveBeenCalledTimes(1);+ });});diff --git a/tests/plan-checkout-config.test.js b/tests/plan-checkout-config.test.jsindex 31c768384..14ec9bef8 100644--- a/tests/plan-checkout-config.test.js+++ b/tests/plan-checkout-config.test.js@@ -6,10 +6,25 @@ import {threePlanDiscountBps,INTENT_TTL_MINUTES,QUOTED_INTENT_TTL_MINUTES,+ EVM_USDC,+ getEvmRecipient,+ getSolanaRecipient,+ toUsdcAtomics,} from '../api/payments/_config.js';+const RECIPIENT_VARS = [+ 'PAYMENT_RECIPIENT_SOLANA',+ 'PAYMENT_RECIPIENT_EVM',+ 'PAYMENT_RECIPIENT_EVM_8453',+];+const PRIOR = Object.fromEntries(RECIPIENT_VARS.map((k) => [k, process.env[k]]));+afterEach(() => {delete process.env.THREE_PLAN_DISCOUNT_BPS;+ for (const k of RECIPIENT_VARS) {+ if (PRIOR[k] === undefined) delete process.env[k];+ else process.env[k] = PRIOR[k];+ }});describe('PLAN_ASSETS', () => {@@ -70,3 +85,43 @@ describe('intent TTLs', () => {expect(QUOTED_INTENT_TTL_MINUTES).toBeLessThan(INTENT_TTL_MINUTES);});});++describe('recipients', () => {+ // Both getters return null when unset, which is what turns checkout into a+ // 503 not_configured instead of quoting a payment nobody can collect.+ it('returns null when nothing is configured', () => {+ for (const k of RECIPIENT_VARS) delete process.env[k];+ expect(getSolanaRecipient()).toBeNull();+ expect(getEvmRecipient(8453)).toBeNull();+ });++ it('reads the configured Solana treasury', () => {+ process.env.PAYMENT_RECIPIENT_SOLANA = 'wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU';+ expect(getSolanaRecipient()).toBe('wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU');+ });++ it('prefers the per-chain EVM recipient over the shared default', () => {+ process.env.PAYMENT_RECIPIENT_EVM = '0x1111111111111111111111111111111111111111';+ process.env.PAYMENT_RECIPIENT_EVM_8453 = '0x2222222222222222222222222222222222222222';+ expect(getEvmRecipient(8453)).toBe('0x2222222222222222222222222222222222222222');+ expect(getEvmRecipient(137)).toBe('0x1111111111111111111111111111111111111111');+ });+});++describe('USDC atomics', () => {+ it('scales USD to 6-decimal atomics as a bigint', () => {+ expect(toUsdcAtomics(49)).toBe(49_000_000n);+ expect(toUsdcAtomics(0.01)).toBe(10_000n);+ });++ it('rounds sub-atomic fractions instead of throwing on a non-integer', () => {+ expect(toUsdcAtomics(1.0000004)).toBe(1_000_000n);+ });++ it('quotes a chain we accept for every EVM plan payment', () => {+ for (const [chainId, address] of Object.entries(EVM_USDC)) {+ expect(Number(chainId)).toBeGreaterThan(0);+ expect(address).toMatch(/^0x[a-fA-F0-9]{40}$/);+ }+ });+});diff --git a/tests/plan-payment-endpoints.test.js b/tests/plan-payment-endpoints.test.jsnew file mode 100644index 000000000..689432ea5--- /dev/null+++ b/tests/plan-payment-endpoints.test.js@@ -0,0 +1,249 @@+/**+ * Boundary behaviour for the plan-checkout payment lanes.+ *+ * POST /api/payments/solana/confirm+ * The checkout schema refuses devnet in production because devnet USDC is+ * free from a faucet. Confirm picks the RPC it queries AND the USDC mint it+ * accepts from its own `network` field, and the intent row stores no cluster,+ * so a devnet-tolerant confirm handed out free plans regardless of what+ * checkout allowed: create a mainnet intent, pay its nonce with faucet USDC+ * on devnet, confirm with network=devnet. Both schemas now share one enum.+ *+ * POST /api/payments/evm/confirm+ * Scoped to chain_type='evm': the Solana lane writes into the same table, so+ * an unscoped lookup let an EVM confirm read and expire a Solana intent.+ * And confirming needs 12 blocks of depth, so a transfer broadcast near the+ * end of the session could never be confirmed before it lapsed; a bounded+ * grace window keeps those already-on-chain funds claimable.+ *+ * POST /api/payments/intent+ * agent_id is a uuid column. An unvalidated value reached the driver as+ * SQLSTATE 22P02, which the wrapper turned into a 500 plus an ops alert.+ *+ * NODE_ENV is forced to production for the whole file (restored afterwards) so+ * the production-only network gate is what is under test. DB, session, rate+ * limit, RPC, price feeds, and email are mocked; the HTTP envelope helpers and+ * the zod schemas run for real, so status codes and JSON bodies are genuine.+ */++import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';++const envState = vi.hoisted(() => {+ const prior = process.env.NODE_ENV;+ process.env.NODE_ENV = 'production';+ return { prior };+});++const USER = { id: '28e98fb2-2a98-4500-b45a-5a9ad7b3f7a8', email: '[email protected]' };+const INTENT_ID = '2af3ee5e-8b10-40d5-bbf2-f375197dc39f';+const TX_SIG = '5Zx1uWnPZ8kkVYQ9mLXJx3nQ8Yb2c1D4eF5gH6jK7mN8pQ9rS1tU2vW3xY4zA5bC6dE7fG8hJ9kL1mN2pQ3r';+const TX_HASH = `0x${'a'.repeat(64)}`;+const AGENT_ID = '76bca598-103f-4e3a-8c95-b0d64993258a';++const db = vi.hoisted(() => ({ handlers: [], calls: [] }));++vi.mock('../api/_lib/db.js', () => ({+ sql: async (strings, ...values) => {+ const text = strings.join(' $ ').replace(/\s+/g, ' ').trim();+ db.calls.push({ text, values });+ for (const h of db.handlers) {+ if (h.match.test(text)) return h.result(values, text);+ }+ return [];+ },+ // http.js's wrap() classifies thrown errors through these on the 5xx path.+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));+vi.mock('../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => USER) }));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { authIp: vi.fn(async () => ({ success: true, reset: Date.now() + 60_000 })) },+ clientIp: () => '127.0.0.1',+}));+vi.mock('../api/_lib/email.js', () => ({ sendSubscriptionConfirmEmail: vi.fn(async () => {}) }));+vi.mock('../api/_lib/solana/connection.js', () => ({+ solanaConnection: vi.fn(() => ({ getParsedTransaction: vi.fn(async () => null) })),+}));+vi.mock('../api/_lib/balances.js', () => ({ solanaMintUsdPrice: vi.fn(async () => 150) }));+vi.mock('../api/_lib/token/price.js', () => ({ getTokenPriceUsd: vi.fn(async () => ({ priceUsd: 0.0023 })) }));+vi.mock('../api/_lib/evm/rpc.js', () => ({ evmTransport: vi.fn(() => () => {}) }));++const evm = vi.hoisted(() => ({ client: { getTransactionReceipt: vi.fn(), getBlockNumber: vi.fn() } }));+vi.mock('viem', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, createPublicClient: vi.fn(() => evm.client) };+});++const { default: solanaHandler } = await import('../api/payments/solana/[action].js');+const { default: evmHandler } = await import('../api/payments/evm/[action].js');+const { default: intentHandler } = await import('../api/payments/intent.js');++afterAll(() => {+ if (envState.prior === undefined) delete process.env.NODE_ENV;+ else process.env.NODE_ENV = envState.prior;+});++function makeReq(url, body, query) {+ return {+ method: 'POST',+ url,+ query,+ headers: { origin: 'https://three.ws', 'content-type': 'application/json' },+ body,+ socket: { remoteAddress: '127.0.0.1' },+ };+}+function makeRes() {+ const r = { statusCode: 200, _h: {}, _b: null };+ r.setHeader = (k, v) => { r._h[k] = v; };+ r.getHeader = (k) => r._h[k];+ r.end = (b) => { r._b = b; };+ Object.defineProperty(r, '_s', { get() { return this.statusCode; } });+ Object.defineProperty(r, 'json', { value: () => JSON.parse(r._b) });+ return r;+}+async function call(handler, url, body, query) {+ const res = makeRes();+ await handler(makeReq(url, body, query), res);+ return res;+}++/** A pending intent row, expired `minutesAgo` minutes ago (0 = still live). */+function intentRow({ chainType = 'evm', minutesAgo = -10, status = 'pending' } = {}) {+ return {+ id: INTENT_ID,+ user_id: USER.id,+ plan: 'pro',+ chain_type: chainType,+ chain_id: chainType === 'evm' ? 8453 : null,+ amount_usdc: '49',+ recipient: '0x4022de2d36c334e73c7a108805cea11c0564f402',+ nonce: 'JE_4V8pYCSRoNMMkHngHPA',+ status,+ expires_at: new Date(Date.now() - minutesAgo * 60 * 1000).toISOString(),+ };+}++beforeEach(() => {+ db.handlers = [];+ db.calls = [];+ evm.client.getTransactionReceipt.mockReset();+ evm.client.getBlockNumber.mockReset();+ vi.clearAllMocks();+});++describe('POST /api/payments/solana/confirm: cluster gate', () => {+ it('refuses a devnet confirm in production without touching the intent', async () => {+ const r = await call(solanaHandler, '/api/payments/solana/confirm', {+ intent_id: INTENT_ID, tx_signature: TX_SIG, network: 'devnet',+ }, { action: 'confirm' });+ expect(r._s).toBe(400);+ expect(r.json().error).toBe('validation_error');+ expect(db.calls.some((c) => /plan_payment_intents/.test(c.text))).toBe(false);+ });++ it('still accepts a mainnet confirm and looks the intent up in its own lane', async () => {+ const r = await call(solanaHandler, '/api/payments/solana/confirm', {+ intent_id: INTENT_ID, tx_signature: TX_SIG, network: 'mainnet',+ }, { action: 'confirm' });+ expect(r._s).toBe(404);+ expect(r.json().error).toBe('not_found');+ const lookup = db.calls.find((c) => /select \* from plan_payment_intents/.test(c.text));+ expect(lookup?.text).toMatch(/chain_type = 'solana'/);+ });++ it('refuses a devnet checkout in production too', async () => {+ const r = await call(solanaHandler, '/api/payments/solana/checkout', {+ plan: 'pro', asset: 'USDC', network: 'devnet',+ }, { action: 'checkout' });+ expect(r._s).toBe(400);+ expect(r.json().error).toBe('validation_error');+ });+});++describe('POST /api/payments/evm/confirm: lane scoping', () => {+ it('scopes the intent lookup to the EVM lane', async () => {+ const r = await call(evmHandler, '/api/payments/evm/confirm', {+ intent_id: INTENT_ID, tx_hash: TX_HASH,+ }, { action: 'confirm' });+ expect(r._s).toBe(404);+ const lookup = db.calls.find((c) => /select \* from plan_payment_intents/.test(c.text));+ expect(lookup?.text).toMatch(/chain_type = 'evm'/);+ });++ it('never writes to an intent it could not claim', async () => {+ await call(evmHandler, '/api/payments/evm/confirm', {+ intent_id: INTENT_ID, tx_hash: TX_HASH,+ }, { action: 'confirm' });+ expect(db.calls.some((c) => /update plan_payment_intents/.test(c.text))).toBe(false);+ });+});++describe('POST /api/payments/evm/confirm: expiry grace window', () => {+ it('still verifies a transfer confirmed minutes after the session lapsed', async () => {+ db.handlers = [{ match: /select \* from plan_payment_intents/, result: () => [intentRow({ minutesAgo: 5 })] }];+ evm.client.getTransactionReceipt.mockRejectedValue(new Error('not found'));+ const r = await call(evmHandler, '/api/payments/evm/confirm', {+ intent_id: INTENT_ID, tx_hash: TX_HASH,+ }, { action: 'confirm' });+ // Past the expiry gate: it reached the chain lookup rather than 410ing.+ expect(r._s).toBe(422);+ expect(r.json().error).toBe('tx_not_found');+ expect(db.calls.some((c) => /update plan_payment_intents/.test(c.text))).toBe(false);+ });++ it('expires an intent left unclaimed past the grace window', async () => {+ db.handlers = [{ match: /select \* from plan_payment_intents/, result: () => [intentRow({ minutesAgo: 180 })] }];+ const r = await call(evmHandler, '/api/payments/evm/confirm', {+ intent_id: INTENT_ID, tx_hash: TX_HASH,+ }, { action: 'confirm' });+ expect(r._s).toBe(410);+ expect(r.json().error).toBe('intent_expired');+ const write = db.calls.find((c) => /update plan_payment_intents/.test(c.text));+ expect(write?.text).toMatch(/status='expired'/);+ // Only a pending row may be marked expired, so this can never stomp a+ // confirmed or failed intent.+ expect(write?.text).toMatch(/status='pending'/);+ expect(evm.client.getTransactionReceipt).not.toHaveBeenCalled();+ });++ it('refuses a failed intent outright', async () => {+ db.handlers = [{ match: /select \* from plan_payment_intents/, result: () => [intentRow({ status: 'failed' })] }];+ const r = await call(evmHandler, '/api/payments/evm/confirm', {+ intent_id: INTENT_ID, tx_hash: TX_HASH,+ }, { action: 'confirm' });+ expect(r._s).toBe(410);+ expect(evm.client.getTransactionReceipt).not.toHaveBeenCalled();+ });+});++describe('POST /api/payments/intent: agent_id shape', () => {+ it('answers 400 on a non-uuid agent_id without querying the price table', async () => {+ const r = await call(intentHandler, '/api/payments/intent', { agent_id: 'not-a-uuid', skill: 'me' });+ expect(r._s).toBe(400);+ expect(r.json().error).toBe('validation_error');+ expect(db.calls.some((c) => /agent_skill_prices/.test(c.text))).toBe(false);+ });++ it('answers 400 on a non-string agent_id', async () => {+ const r = await call(intentHandler, '/api/payments/intent', { agent_id: { id: AGENT_ID }, skill: 'me' });+ expect(r._s).toBe(400);+ expect(db.calls.length).toBe(0);+ });++ it('answers 400 on a blank skill', async () => {+ const r = await call(intentHandler, '/api/payments/intent', { agent_id: AGENT_ID, skill: ' ' });+ expect(r._s).toBe(400);+ expect(db.calls.some((c) => /agent_skill_prices/.test(c.text))).toBe(false);+ });++ it('still reaches the price lookup for a well-formed body', async () => {+ const r = await call(intentHandler, '/api/payments/intent', { agent_id: AGENT_ID, skill: ' me ' });+ expect(r._s).toBe(404);+ expect(r.json().error).toBe('not_found');+ const lookup = db.calls.find((c) => /agent_skill_prices/.test(c.text));+ expect(lookup).toBeTruthy();+ // The skill is trimmed before it is matched against the price row.+ expect(lookup.values).toContain('me');+ });+});