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: implement releaseIntent to revert consumed payment intents on handler failure

nirholas4b7a0dcdac31
diff --git a/api/_lib/x402.js b/api/_lib/x402.js
index 99a0795b4..855bd2c01 100644
--- a/api/_lib/x402.js
+++ b/api/_lib/x402.js
@@ -189,6 +189,25 @@ export async function consumeIntent(intentId) {
return rows.length > 0;
}
+/**
+ * Undo a consumeIntent() win when the paid work then fails. Atomically flips
+ * the intent back to 'paid' (only a row currently 'consumed' transitions) so
+ * the buyer can retry instead of losing a paid intent to a transient handler
+ * error. Pair with consume-first delivery flows: consume as the single-use
+ * lock, execute, and releaseIntent() on the error path.
+ *
+ * @returns {Promise<boolean>} true if this call performed the revert.
+ */
+export async function releaseIntent(intentId) {
+ const rows = await sql`
+ update agent_payment_intents
+ set status = 'paid'
+ where id = ${intentId} and status = 'consumed'
+ returning id
+ `;
+ return rows.length > 0;
+}
+
/**
* Helper: respond with the manifest only (no 402), for prefetch/discovery
* via `GET /api/agents/:id/x402/:skill/manifest`.
diff --git a/api/_lib/x402/payment-identifier-server.js b/api/_lib/x402/payment-identifier-server.js
index d01e09abc..aa6f9ada7 100644
--- a/api/_lib/x402/payment-identifier-server.js
+++ b/api/_lib/x402/payment-identifier-server.js
@@ -181,6 +181,41 @@ export async function releaseSlot({ route, paymentId }) {
await cache.release(route, paymentId);
}
+// Claim the in-flight slot for a payment, answering the request directly when
+// the slot is already taken. The hand-rolled paid endpoints (api/x402/*.js)
+// run check-then-act: cache lookup, verify, paid work, settle, THEN store.
+// Without this claim, N concurrent requests carrying the same X-PAYMENT all
+// miss the cache, all run the paid work, and all settle before the first
+// response is stored — one payment, N deliveries. paidEndpoint closes the
+// same window with reserveSlot at api/_lib/x402-paid-endpoint.js.
+//
+// Returns true when THIS request owns the slot and may proceed; false when a
+// response was already written (cached replay, payload conflict, or another
+// request in flight) and the caller must return immediately. Every failure
+// return after a successful claim must releaseSlot() so a transient error
+// never locks a legitimate payer out of retrying; the success path needs no
+// release because storeResponse() overwrites the slot with the cached entry.
+export async function claimSlotOrRespond({ res, route, paymentId, payloadHash, paymentHash, ttlSeconds }) {
+ const owns = await reserveSlot({ route, paymentId, ttlSeconds });
+ if (owns) return true;
+ const recheck = await checkCache({ route, paymentId, payloadHash, paymentHash });
+ if (recheck.kind === 'hit') {
+ writeCachedResponse(res, recheck.entry);
+ return false;
+ }
+ if (recheck.kind === 'conflict') {
+ writeConflict(res, {
+ route,
+ attemptedHash: recheck.attemptedHash,
+ existingHash: recheck.existingHash,
+ reason: recheck.reason,
+ });
+ return false;
+ }
+ writeInflight(res);
+ return false;
+}
+
// Always-on replay guard for endpoints that hand-roll the x402 dance (the MCP
// servers, launchpad/invoke) instead of using paidEndpoint(). paidEndpoint
// closes the verify→deliver→settle window with a proof-hash reservation; this is
diff --git a/api/agents/x402/[action].js b/api/agents/x402/[action].js
index aea36eed6..276870d9e 100644
--- a/api/agents/x402/[action].js
+++ b/api/agents/x402/[action].js
@@ -6,7 +6,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/au
import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { parse, isUuid } from '../../_lib/validate.js';
-import { emit402, verifyPaid, consumeIntent, manifestOnly } from '../../_lib/x402.js';
+import { emit402, verifyPaid, consumeIntent, releaseIntent, manifestOnly } from '../../_lib/x402.js';
import { resolvePayoutAddress } from '../../_lib/payout.js';
import { calculateFee } from '../../_lib/fee.js';
import { insertNotification } from '../../_lib/notify.js';
@@ -239,35 +239,48 @@ async function handleInvoke(req, res) {
}
}
- // Execute the skill BEFORE consuming the payment intent: if the handler
- // throws, wrap() returns the error with the intent untouched, so the buyer's
- // payment still covers a retry instead of being burned on a failed call.
- const result = await executeSkill(agent, body, auth, paid.payerAddress || null);
-
- // Credit revenue ONLY for the request that atomically wins paid→consumed.
- // Two concurrent requests can both pass verifyPaid (both see status='paid'),
- // but only one transitions the intent to 'consumed'; gating the insert here is
- // what prevents one on-chain payment from being credited twice. The unique
- // index on agent_revenue_events(intent_id) is the hard backstop.
+ // Consume the intent BEFORE executing the skill: the atomic paid→consumed
+ // transition is the single-use lock. Two concurrent requests used to both
+ // pass verifyPaid (both see status='paid') and BOTH execute, delivering
+ // the paid work twice for one on-chain payment; only the transition
+ // winner proceeds now. If the handler then throws, the intent flips back
+ // to 'paid' so the buyer's payment still covers a retry instead of being
+ // burned on a failed call.
const claimed = await consumeIntent(paid.intentId);
- if (claimed) {
- const gross = parseInt(paid.amount, 10);
- const { fee, net } = calculateFee(gross);
- await sql`
- insert into agent_revenue_events
- (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount, currency_mint, chain, payer_address)
- values
- (${agent.id}, ${paid.intentId}, ${body.skill}, ${gross}, ${fee}, ${net}, ${paid.currency}, ${price.chain ?? 'solana'}, ${paid.payerAddress})
- on conflict (intent_id) do nothing
- `;
- insertNotification(agent.user_id, 'payment_received', {
- agent_id: agent.id,
- agent_name: agent.name,
- skill: body.skill,
- net_amount: net,
- currency_mint: paid.currency,
- });
+ if (!claimed) {
+ return error(res, 409, 'payment_in_flight',
+ 'This payment intent was already used or is being processed. Retry shortly.');
+ }
+
+ let result;
+ try {
+ result = await executeSkill(agent, body, auth, paid.payerAddress || null);
+ } catch (err) {
+ // Handler failed after we won the transition: restore the intent so the
+ // buyer is not charged for a call that never delivered.
+ await releaseIntent(paid.intentId).catch(() => {});
+ throw err;
}
+
+ // Revenue is credited here, for the request that won the transition AND
+ // delivered. The unique index on agent_revenue_events(intent_id) is the
+ // hard backstop against double-crediting.
+ const gross = parseInt(paid.amount, 10);
+ const { fee, net } = calculateFee(gross);
+ await sql`
+ insert into agent_revenue_events
+ (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount, currency_mint, chain, payer_address)
+ values
+ (${agent.id}, ${paid.intentId}, ${body.skill}, ${gross}, ${fee}, ${net}, ${paid.currency}, ${price.chain ?? 'solana'}, ${paid.payerAddress})
+ on conflict (intent_id) do nothing
+ `;
+ insertNotification(agent.user_id, 'payment_received', {
+ agent_id: agent.id,
+ agent_name: agent.name,
+ skill: body.skill,
+ net_amount: net,
+ currency_mint: paid.currency,
+ });
return json(res, 200, {
ok: true,
intent_id: paid.intentId,
diff --git a/api/ibm-mcp.js b/api/ibm-mcp.js
index 9c7290a0f..42af0b727 100644
--- a/api/ibm-mcp.js
+++ b/api/ibm-mcp.js
@@ -90,7 +90,13 @@ export default wrap(async (req, res) => {
// replay thereafter. Fails open — see reservePaymentProof.
let releaseProof = async () => {};
if (x402Ctx) {
- const guard = await reservePaymentProof(RESOURCE_PATH, req.headers['x-payment']);
+ const guard = await reservePaymentProof(
+ RESOURCE_PATH,
+ // authenticateRequest accepts BOTH payment headers (v1 X-PAYMENT and
+ // the v2 payment-signature dialect); the guard must key on whichever
+ // one carried the proof or a v2 replay slips past it unclaimed.
+ req.headers['x-payment'] || req.headers['payment-signature'],
+ );
if (!guard.ok) {
return sendJsonRpcError(res, null, -32000, 'payment_in_flight', { retry_after: 1 });
}
diff --git a/api/mcp-agent.js b/api/mcp-agent.js
index bd03e5ea4..8f74ee0db 100644
--- a/api/mcp-agent.js
+++ b/api/mcp-agent.js
@@ -63,7 +63,13 @@ export default wrap(async (req, res) => {
// open — see reservePaymentProof.
let releaseProof = async () => {};
if (x402Ctx) {
- const guard = await reservePaymentProof('/api/mcp-agent', req.headers['x-payment']);
+ const guard = await reservePaymentProof(
+ '/api/mcp-agent',
+ // authenticateRequest accepts BOTH payment headers (v1 X-PAYMENT and
+ // the v2 payment-signature dialect); the guard must key on whichever
+ // one carried the proof or a v2 replay slips past it unclaimed.
+ req.headers['x-payment'] || req.headers['payment-signature'],
+ );
if (!guard.ok) {
return sendJsonRpcError(res, null, -32000, 'payment_in_flight', { retry_after: 1 });
}
diff --git a/api/mcp-bazaar.js b/api/mcp-bazaar.js
index 5234a24c7..702c2982c 100644
--- a/api/mcp-bazaar.js
+++ b/api/mcp-bazaar.js
@@ -65,7 +65,13 @@ export default wrap(async (req, res) => {
// open — see reservePaymentProof.
let releaseProof = async () => {};
if (x402Ctx) {
- const guard = await reservePaymentProof('/api/mcp-bazaar', req.headers['x-payment']);
+ const guard = await reservePaymentProof(
+ '/api/mcp-bazaar',
+ // authenticateRequest accepts BOTH payment headers (v1 X-PAYMENT and
+ // the v2 payment-signature dialect); the guard must key on whichever
+ // one carried the proof or a v2 replay slips past it unclaimed.
+ req.headers['x-payment'] || req.headers['payment-signature'],
+ );
if (!guard.ok) {
return sendJsonRpcError(res, null, -32000, 'payment_in_flight', { retry_after: 1 });
}
diff --git a/api/mcp.js b/api/mcp.js
index cee7e215d..e182aaca7 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -73,7 +73,13 @@ export default wrap(async (req, res) => {
// replay thereafter. Fails open — see reservePaymentProof.
let releaseProof = async () => {};
if (x402Ctx) {
- const guard = await reservePaymentProof('/api/mcp', req.headers['x-payment']);
+ const guard = await reservePaymentProof(
+ '/api/mcp',
+ // authenticateRequest accepts BOTH payment headers (v1 X-PAYMENT and
+ // the v2 payment-signature dialect); the guard must key on whichever
+ // one carried the proof or a v2 replay slips past it unclaimed.
+ req.headers['x-payment'] || req.headers['payment-signature'],
+ );
if (!guard.ok) {
return sendJsonRpcError(res, null, -32000, 'payment_in_flight', { retry_after: 1 });
}
diff --git a/api/x402/forge.js b/api/x402/forge.js
index 51ee9dbf4..d794f16e8 100644
--- a/api/x402/forge.js
+++ b/api/x402/forge.js
@@ -46,10 +46,12 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import {
PAYMENT_IDENTIFIER,
checkCache,
+ claimSlotOrRespond,
extractIdFromHeader,
hashPaymentProof,
hashRequestPayload,
paymentIdentifierExtension,
+ releaseSlot,
storeResponse,
writeCachedResponse,
writeConflict,
@@ -643,6 +645,11 @@ export default wrap(async (req, res) => {
// dedup key (reproducible only by the original payer), making replay
// protection unconditional. Same idiom as api/_lib/x402-paid-endpoint.js.
const paymentId = clientPaymentId || (paymentHash ? `proof:${paymentHash}` : null);
+ // Close the check-then-act window: N concurrent requests carrying the same
+ // payment could all miss the cache, all run the paid work, and all settle
+ // before the first response was stored. The NX claim admits exactly one;
+ // the rest are answered inside claimSlotOrRespond (replay/conflict/in-flight).
+ let ownsReservation = false;
if (paymentId) {
const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });
if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);
@@ -654,12 +661,15 @@ export default wrap(async (req, res) => {
reason: lookup.reason,
});
}
+ ownsReservation = await claimSlotOrRespond({ res, route: ROUTE, paymentId, payloadHash, paymentHash });
+ if (!ownsReservation) return;
}
let verified;
try {
verified = await verifyPayment({ paymentHeader, requirements });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
if (err.status === 402) return send402(res, { ...challenge, error: err.message });
return error(res, err.status || 502, err.code || 'verify_failed', err.message);
}
@@ -675,6 +685,7 @@ export default wrap(async (req, res) => {
try {
result = await submitGeneration(parsed);
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return respondGenerationError(res, err);
}
}
@@ -683,6 +694,7 @@ export default wrap(async (req, res) => {
try {
settled = await settlePayment({ verified });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
diff --git a/api/x402/mint-to-mesh.js b/api/x402/mint-to-mesh.js
index 3ceac5f52..b55b512c8 100644
--- a/api/x402/mint-to-mesh.js
+++ b/api/x402/mint-to-mesh.js
@@ -38,10 +38,12 @@ import { fetchTokenMeta } from '../_lib/solana-token-meta.js';
import {
PAYMENT_IDENTIFIER,
checkCache,
+ claimSlotOrRespond,
extractIdFromHeader,
hashPaymentProof,
hashRequestPayload,
paymentIdentifierExtension,
+ releaseSlot,
storeResponse,
writeCachedResponse,
writeConflict,
@@ -293,6 +295,11 @@ export default wrap(async (req, res) => {
// dedup key (reproducible only by the original payer), making replay
// protection unconditional. Same idiom as api/_lib/x402-paid-endpoint.js.
const paymentId = clientPaymentId || (paymentHash ? `proof:${paymentHash}` : null);
+ // Close the check-then-act window: N concurrent requests carrying the same
+ // payment could all miss the cache, all run the paid work, and all settle
+ // before the first response was stored. The NX claim admits exactly one;
+ // the rest are answered inside claimSlotOrRespond (replay/conflict/in-flight).
+ let ownsReservation = false;
if (paymentId) {
const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });
if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);
@@ -304,25 +311,34 @@ export default wrap(async (req, res) => {
reason: lookup.reason,
});
}
+ ownsReservation = await claimSlotOrRespond({ res, route: ROUTE, paymentId, payloadHash, paymentHash });
+ if (!ownsReservation) return;
}
let verified;
try {
verified = await verifyPayment({ paymentHeader, requirements });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
if (err.status === 402) return send402(res, { ...challenge, error: err.message });
return error(res, err.status || 502, err.code || 'verify_failed', err.message);
}
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))
+ if (!mint) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
+ return error(res, 400, 'missing_mint', 'query param "mint" is required');
+ }
+ if (!BASE58_RE.test(mint)) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(res, 400, 'invalid_mint', 'mint must be a base58 SPL address (32–44 chars)');
+ }
let result;
try {
result = await buildMesh(mint);
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(res, err.status || 500, err.code || 'internal_error', err.message);
}
@@ -330,6 +346,7 @@ export default wrap(async (req, res) => {
try {
settled = await settlePayment({ verified });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
diff --git a/api/x402/model-check.js b/api/x402/model-check.js
index 14911ab52..2901028f7 100644
--- a/api/x402/model-check.js
+++ b/api/x402/model-check.js
@@ -34,10 +34,12 @@ import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';
import {
PAYMENT_IDENTIFIER,
checkCache,
+ claimSlotOrRespond,
extractIdFromHeader,
hashPaymentProof,
hashRequestPayload,
paymentIdentifierExtension,
+ releaseSlot,
storeResponse,
writeCachedResponse,
writeConflict,
@@ -319,6 +321,11 @@ export default wrap(async (req, res) => {
// dedup key (reproducible only by the original payer), making replay
// protection unconditional. Same idiom as api/_lib/x402-paid-endpoint.js.
const paymentId = clientPaymentId || (paymentHash ? `proof:${paymentHash}` : null);
+ // Close the check-then-act window: N concurrent requests carrying the same
+ // payment could all miss the cache, all run the paid work, and all settle
+ // before the first response was stored. The NX claim admits exactly one;
+ // the rest are answered inside claimSlotOrRespond (replay/conflict/in-flight).
+ let ownsReservation = false;
if (paymentId) {
const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });
if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);
@@ -330,23 +337,30 @@ export default wrap(async (req, res) => {
reason: lookup.reason,
});
}
+ ownsReservation = await claimSlotOrRespond({ res, route: ROUTE, paymentId, payloadHash, paymentHash });
+ if (!ownsReservation) return;
}
let verified;
try {
verified = await verifyPayment({ paymentHeader, requirements });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
if (err.status === 402) return send402(res, { ...challenge, error: err.message });
return error(res, err.status || 502, err.code || 'verify_failed', err.message);
}
const target = String(req.query?.url || '').trim();
- if (!target) return error(res, 400, 'missing_url', 'query param "url" is required');
+ if (!target) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
+ return error(res, 400, 'missing_url', 'query param "url" is required');
+ }
let result;
try {
result = await fetchAndInspect(target);
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(res, err.status || 500, err.code || 'internal_error', err.message);
}
@@ -354,6 +368,7 @@ export default wrap(async (req, res) => {
try {
settled = await settlePayment({ verified });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
diff --git a/api/x402/pipeline.js b/api/x402/pipeline.js
index 1bc4ac4ed..ed8f169c4 100644
--- a/api/x402/pipeline.js
+++ b/api/x402/pipeline.js
@@ -42,10 +42,12 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import {
PAYMENT_IDENTIFIER,
checkCache,
+ claimSlotOrRespond,
extractIdFromHeader,
hashPaymentProof,
hashRequestPayload,
paymentIdentifierExtension,
+ releaseSlot,
storeResponse,
writeCachedResponse,
writeConflict,
@@ -329,6 +331,7 @@ export default wrap(async (req, res) => {
let paymentId = null;
let payloadHash = null;
let paymentHash = null;
+ let ownsReservation = false;
if (!bypass) {
const clientPaymentId = extractIdFromHeader(paymentHeader);
payloadHash = hashRequestPayload({ method: 'POST', url: ROUTE, body: rawBody });
@@ -345,6 +348,12 @@ export default wrap(async (req, res) => {
reason: lookup.reason,
});
}
+ // Close the check-then-act window: N concurrent requests carrying the
+ // same payment could all miss the cache, all launch a pipeline, and
+ // all settle before the first response was stored. The NX claim
+ // admits exactly one; the rest are answered inside claimSlotOrRespond.
+ ownsReservation = await claimSlotOrRespond({ res, route: ROUTE, paymentId, payloadHash, paymentHash });
+ if (!ownsReservation) return;
}
}
@@ -353,6 +362,7 @@ export default wrap(async (req, res) => {
try {
verified = await verifyPayment({ paymentHeader, requirements });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
if (err.status === 402) return send402(res, { ...challenge, error: err.message });
return error(res, err.status || 502, err.code || 'verify_failed', err.message);
}
@@ -369,6 +379,7 @@ export default wrap(async (req, res) => {
options: plan.options,
});
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return respondStageError(res, err);
}
@@ -377,6 +388,7 @@ export default wrap(async (req, res) => {
try {
settled = await settlePayment({ verified });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));
@@ -396,6 +408,7 @@ export default wrap(async (req, res) => {
network: env.X402_PAY_TO_SOLANA ? NETWORK_SOLANA_MAINNET : NETWORK_BASE_MAINNET,
});
if (!job) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(
res,
503,
diff --git a/api/x402/vanity-premium.js b/api/x402/vanity-premium.js
index 16473b0ed..b940ab0f6 100644
--- a/api/x402/vanity-premium.js
+++ b/api/x402/vanity-premium.js
@@ -39,10 +39,12 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import {
PAYMENT_IDENTIFIER,
checkCache,
+ claimSlotOrRespond,
extractIdFromHeader,
hashPaymentProof,
hashRequestPayload,
paymentIdentifierExtension,
+ releaseSlot,
storeResponse,
writeCachedResponse,
writeConflict,
@@ -293,11 +295,19 @@ async function handlePurchase(req, res, address) {
});
}
+ // Close the check-then-act window: N concurrent requests carrying the same
+ // payment could all miss the cache, all verify, and all race reserveForPurchase
+ // (the loser strands a reservation on a payment that never settles). The NX
+ // claim admits exactly one; the rest are answered inside claimSlotOrRespond.
+ const ownsReservation = await claimSlotOrRespond({ res, route: ROUTE, paymentId, payloadHash, paymentHash });
+ if (!ownsReservation) return;
+
// 1) verify the payment.
let verified;
try {
verified = await verifyPayment({ paymentHeader, requirements });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
if (err.status === 402) return send402(res, { ...challenge, error: err.message });
return error(res, err.status || 502, err.code || 'verify_failed', err.message);
}
@@ -309,9 +319,11 @@ async function handlePurchase(req, res, address) {
try {
reservation = await reserveForPurchase(address, { paymentId, purchaser });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(res, 502, 'reserve_failed', err.message);
}
if (!reservation.ok) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
const code = reservation.reason === 'not_found' ? 404 : 409;
return error(res, code, 'unavailable', `address ${address} could not be reserved (${reservation.reason}) — it may have just sold`);
}
@@ -322,11 +334,15 @@ async function handlePurchase(req, res, address) {
let bundle;
try {
const peek = await peekReservedSecret(address, { paymentId });
- if (!peek.ok) return error(res, 500, 'reveal_failed', `secret not retrievable (${peek.reason})`);
+ if (!peek.ok) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
+ return error(res, 500, 'reveal_failed', `secret not retrievable (${peek.reason})`);
+ }
bundle = JSON.parse(await openSecret(peek.ciphertext, peek.scheme));
} catch (err) {
// Decrypt/KMS failure BEFORE settle: don't charge. Reservation is left in
// place (buyer's payment can be retried against the same reserved row).
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(res, 502, 'decrypt_failed', 'could not decrypt the stored key — not charged, retry shortly');
}
@@ -335,6 +351,7 @@ async function handlePurchase(req, res, address) {
try {
settled = await settlePayment({ verified });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
diff --git a/api/x402/vanity-verifiable.js b/api/x402/vanity-verifiable.js
index db02e7267..7a18015b1 100644
--- a/api/x402/vanity-verifiable.js
+++ b/api/x402/vanity-verifiable.js
@@ -44,10 +44,12 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import {
PAYMENT_IDENTIFIER,
checkCache,
+ claimSlotOrRespond,
extractIdFromHeader,
hashPaymentProof,
hashRequestPayload,
paymentIdentifierExtension,
+ releaseSlot,
storeResponse,
writeCachedResponse,
writeConflict,
@@ -445,6 +447,11 @@ export default wrap(async (req, res) => {
const payloadHash = hashRequestPayload({ method: req.method, url: req.url, body: null });
const paymentHash = hashPaymentProof(paymentHeader);
const paymentId = clientPaymentId || (paymentHash ? `proof:${paymentHash}` : null);
+ // Close the check-then-act window: N concurrent requests carrying the same
+ // payment could all miss the cache, all run the paid work, and all settle
+ // before the first response was stored. The NX claim admits exactly one;
+ // the rest are answered inside claimSlotOrRespond (replay/conflict/in-flight).
+ let ownsReservation = false;
if (paymentId) {
const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });
if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);
@@ -456,12 +463,15 @@ export default wrap(async (req, res) => {
reason: lookup.reason,
});
}
+ ownsReservation = await claimSlotOrRespond({ res, route: ROUTE, paymentId, payloadHash, paymentHash });
+ if (!ownsReservation) return;
}
let verified;
try {
verified = await verifyPayment({ paymentHeader, requirements });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
if (err.status === 402) return send402(res, { ...challenge, error: err.message });
return error(res, err.status || 502, err.code || 'verify_failed', err.message);
}
@@ -472,6 +482,7 @@ export default wrap(async (req, res) => {
try {
result = await grindAndBuildReceipt(pattern);
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(res, err.status || 500, err.code || 'grind_failed', err.message);
}
@@ -479,6 +490,7 @@ export default wrap(async (req, res) => {
try {
settled = await settlePayment({ verified });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
diff --git a/api/x402/vanity.js b/api/x402/vanity.js
index 73a43fdba..ab1f4be50 100644
--- a/api/x402/vanity.js
+++ b/api/x402/vanity.js
@@ -37,10 +37,12 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import {
PAYMENT_IDENTIFIER,
checkCache,
+ claimSlotOrRespond,
extractIdFromHeader,
hashPaymentProof,
hashRequestPayload,
paymentIdentifierExtension,
+ releaseSlot,
storeResponse,
writeCachedResponse,
writeConflict,
@@ -760,6 +762,11 @@ export default wrap(async (req, res) => {
// dedup key (reproducible only by the original payer), making replay
// protection unconditional. Same idiom as api/_lib/x402-paid-endpoint.js.
const paymentId = clientPaymentId || (paymentHash ? `proof:${paymentHash}` : null);
+ // Close the check-then-act window: N concurrent requests carrying the same
+ // payment could all miss the cache, all run the paid work, and all settle
+ // before the first response was stored. The NX claim admits exactly one;
+ // the rest are answered inside claimSlotOrRespond (replay/conflict/in-flight).
+ let ownsReservation = false;
if (paymentId) {
const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });
if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);
@@ -771,12 +778,15 @@ export default wrap(async (req, res) => {
reason: lookup.reason,
});
}
+ ownsReservation = await claimSlotOrRespond({ res, route: ROUTE, paymentId, payloadHash, paymentHash });
+ if (!ownsReservation) return;
}
let verified;
try {
verified = await verifyPayment({ paymentHeader, requirements });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
if (err.status === 402) return send402(res, { ...challenge, error: err.message });
return error(res, err.status || 502, err.code || 'verify_failed', err.message);
}
@@ -814,6 +824,7 @@ export default wrap(async (req, res) => {
result = await grindAndShape(pattern);
}
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(res, err.status || 500, err.code || 'grind_failed', err.message);
}
@@ -827,6 +838,7 @@ export default wrap(async (req, res) => {
// payment failure never strands sellable stock.
await releaseReservation(inventoryClaim.address, { paymentId }).catch(() => {});
}
+ if (ownsReservation) await releaseSlot({ route: ROUTE, paymentId });
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
diff --git a/tests/agent-monetization.test.js b/tests/agent-monetization.test.js
index 0b1541eb8..e3bd2b157 100644
--- a/tests/agent-monetization.test.js
+++ b/tests/agent-monetization.test.js
@@ -47,6 +47,19 @@ vi.mock('../api/_lib/csrf.js', () => ({
generateToken: vi.fn(async () => 'test-csrf-token'),
}));
+// skill-runtime only runs for skills NOT in the handler's built-in HANDLERS
+// map (the tests all use the built-in 'echo' except the consume-first revert
+// case, which drives this mock to a throw).
+const runtimeState = { fail: false };
+vi.mock('../api/_lib/skill-runtime.js', () => ({
+ makeRuntime: vi.fn(() => ({
+ invoke: vi.fn(async () => {
+ if (runtimeState.fail) throw new Error('provider down');
+ return { ok: true };
+ }),
+ })),
+}));
+
// ── Handler imports (after mocks) ─────────────────────────────────────────────
const { default: pricingSkillHandler } = await import('../api/agents/_id/pricing/[skill].js');
@@ -406,6 +419,9 @@ describe('Revenue Attribution', () => {
payload: null,
end_time: null,
}]);
+ // consumeIntent UPDATE ... RETURNING id → this request wins the
+ // paid→consumed claim before the skill executes.
+ sqlState.queue.push([{ id: intentId }]);
const { status: first } = await invoke(x402Handler, {
method: 'POST',
@@ -429,6 +445,97 @@ describe('Revenue Attribution', () => {
});
expect(second).toBe(402);
});
+
+ // ── consume-first single-use lock (2026-07-23 audit) ─────────────────────
+ // The handler used to execute the skill BEFORE consuming the intent: two
+ // concurrent invokes both passed verifyPaid and BOTH delivered the paid
+ // work for one on-chain payment. The atomic paid→consumed transition now
+ // happens first; only the winner executes.
+
+ it('concurrent loser of the paid→consumed race gets 409 and the skill never executes', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+ const intentId = 'intent-race-001';
+
+ sqlState.queue.push([agent]);
+ sqlState.queue.push([]); // priceFor → meta fallback
+ sqlState.queue.push([]); // hasSkillAccess → x402 path
+ sqlState.queue.push([{
+ id: intentId,
+ agent_id: agent.id,
+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ amount: '1000000',
+ status: 'paid',
+ paid_at: new Date().toISOString(),
+ payload: null,
+ end_time: null,
+ }]);
+ // consumeIntent UPDATE ... RETURNING id → EMPTY: another in-flight
+ // request already won the transition.
+ sqlState.queue.push([]);
+
+ const { status, body } = await invoke(x402Handler, {
+ method: 'POST',
+ url: '/api/agents/x402/invoke',
+ headers: { 'x-payment-intent': intentId },
+ body: { agent_id: agent.id, skill: 'echo', args: {} },
+ });
+
+ expect(status).toBe(409);
+ expect(body.error).toBe('payment_in_flight');
+ // No revenue insert may happen for the loser.
+ expect(sqlState.calls.some((c) => String(c.query).includes('agent_revenue_events'))).toBe(false);
+ });
+
+ it('a handler failure after winning the claim restores the intent to paid', async () => {
+ // 'summarize' must be DECLARED on the agent or invoke 404s at the
+ // unknown-skill gate before ever reaching the payment path.
+ const { agent, session } = createTestAgent({ skills: ['summarize'] });
+ authState.session = session;
+ const intentId = 'intent-revert-001';
+ runtimeState.fail = true;
+
+ sqlState.queue.push([agent]);
+ sqlState.queue.push([]); // priceFor → meta fallback
+ sqlState.queue.push([]); // hasSkillAccess → x402 path
+ sqlState.queue.push([{
+ id: intentId,
+ agent_id: agent.id,
+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ amount: '1000000',
+ status: 'paid',
+ paid_at: new Date().toISOString(),
+ payload: null,
+ end_time: null,
+ }]);
+ sqlState.queue.push([{ id: intentId }]); // consumeIntent wins
+ sqlState.queue.push([{ id: intentId }]); // releaseIntent reverts consumed→paid
+
+ try {
+ await invoke(x402Handler, {
+ method: 'POST',
+ url: '/api/agents/x402/invoke',
+ headers: { 'x-payment-intent': intentId },
+ // 'summarize' is not a built-in handler → executeSkill goes through
+ // the mocked runtime, which throws.
+ body: { agent_id: agent.id, skill: 'summarize', args: {} },
+ });
+ } catch {
+ // invoke() may surface the 500 envelope as a thrown error depending on
+ // the wrap() mapping; the assertions below target the SQL trail.
+ } finally {
+ runtimeState.fail = false;
+ }
+
+ const updates = sqlState.calls
+ .map((c) => String(c.query))
+ .filter((q) => q.includes('update agent_payment_intents'));
+ expect(updates).toHaveLength(2);
+ expect(updates[0]).toContain("set status = 'consumed'");
+ expect(updates[1]).toContain("set status = 'paid'");
+ // No revenue for a call that never delivered.
+ expect(sqlState.calls.some((c) => String(c.query).includes('agent_revenue_events'))).toBe(false);
+ });
});
// ── 4. Revenue Dashboard ──────────────────────────────────────────────────────
diff --git a/tests/x402-claim-slot.test.js b/tests/x402-claim-slot.test.js
new file mode 100644
index 000000000..92df1a70c
--- /dev/null
+++ b/tests/x402-claim-slot.test.js
@@ -0,0 +1,97 @@
+// Regression guard for the 2026-07-23 audit finding (payment replay race):
+// the hand-rolled paid endpoints (api/x402/{model-check,mint-to-mesh,vanity,
+// vanity-verifiable,forge,pipeline,vanity-premium}.js) ran check-then-act —
+// cache lookup, verify, paid work, settle, THEN store — with no in-flight
+// reservation, so N concurrent requests carrying the same X-PAYMENT all
+// missed the cache, all ran the paid work, and all settled: one payment,
+// N deliveries. claimSlotOrRespond is the NX claim every one of those
+// endpoints now makes right after its cache lookup. These tests pin its
+// concurrency contract against the real in-process store.
+
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ claimSlotOrRespond,
+ storeResponse,
+ releaseSlot,
+} from '../api/_lib/x402/payment-identifier-server.js';
+import { _resetMemoryStore } from '../api/_lib/x402/idempotency-cache.js';
+
+const ROUTE = '/api/x402/test-slot';
+
+function makeRes() {
+ const r = { statusCode: 200, _h: {}, _b: null };
+ r.setHeader = (k, v) => { r._h[k.toLowerCase()] = v; };
+ r.getHeader = (k) => r._h[k.toLowerCase()];
+ r.end = (b) => { r._b = b; };
+ Object.defineProperty(r, 'body', { get: () => (r._b ? JSON.parse(r._b) : null) });
+ return r;
+}
+
+const claim = (res, paymentId = 'proof:abc123') =>
+ claimSlotOrRespond({
+ res,
+ route: ROUTE,
+ paymentId,
+ payloadHash: 'payload-hash-1',
+ paymentHash: 'proof-hash-1',
+ });
+
+beforeEach(() => {
+ _resetMemoryStore();
+});
+
+describe('claimSlotOrRespond', () => {
+ it('the first claim wins the slot', async () => {
+ const res = makeRes();
+ expect(await claim(res)).toBe(true);
+ // No response was written; the caller proceeds to verify+deliver+settle.
+ expect(res._b).toBeNull();
+ });
+
+ it('a concurrent claim for the same payment is answered in-flight, not admitted', async () => {
+ expect(await claim(makeRes())).toBe(true);
+ const res2 = makeRes();
+ expect(await claim(res2)).toBe(false);
+ expect(res2.statusCode).toBe(409);
+ expect(res2._h['x-x402-idempotent']).toBe('in-flight');
+ expect(res2.body.error).toBe('payment_in_flight');
+ });
+
+ it('a concurrent RACE admits exactly one winner', async () => {
+ const [a, b] = await Promise.all([claim(makeRes()), claim(makeRes()), claim(makeRes())]);
+ expect([a, b].filter(Boolean)).toHaveLength(1);
+ });
+
+ it('after the winner stores its response, later claims replay the cache', async () => {
+ expect(await claim(makeRes())).toBe(true);
+ await storeResponse({
+ route: ROUTE,
+ paymentId: 'proof:abc123',
+ payloadHash: 'payload-hash-1',
+ paymentHash: 'proof-hash-1',
+ status: 200,
+ body: JSON.stringify({ ok: true }),
+ contentType: 'application/json; charset=utf-8',
+ paymentResponseHeader: null,
+ });
+
+ const res = makeRes();
+ expect(await claim(res)).toBe(false);
+ expect(res.statusCode).toBe(200);
+ expect(res._h['x-x402-idempotent']).toBe('replay');
+ expect(res.body).toEqual({ ok: true });
+ });
+
+ it('a released slot (failure path) lets the payer retry instead of locking them out', async () => {
+ expect(await claim(makeRes())).toBe(true);
+ await releaseSlot({ route: ROUTE, paymentId: 'proof:abc123' });
+ // The retry wins the slot again — a transient verify/settle failure must
+ // never strand the payer on a stale in-flight marker.
+ expect(await claim(makeRes())).toBe(true);
+ });
+
+ it('different payments never block each other', async () => {
+ expect(await claim(makeRes(), 'proof:aaa')).toBe(true);
+ expect(await claim(makeRes(), 'proof:bbb')).toBe(true);
+ });
+});