From 9bd8c1146eb780432fc0a69256de3fbc6bb5c23b Mon Sep 17 00:00:00 2001 From: Christopher Ferjo <270686917+hypeprinter007-stack@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:15:05 -0700 Subject: [PATCH] docs(skills): add seller replay guard to agent-payment-x402 x402 middleware verifies, runs the handler, then settles. Verification does not consume the authorization, so concurrent copies of one signed payment each run the handler; only one settles. Document a claim-once guard keyed on the EIP-3009 (from, nonce) or the SVM signed message, with an atomic insert before the payment middleware, failing open. Mirrored in ja-JP and zh-CN. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/ja-JP/skills/agent-payment-x402/SKILL.md | 60 +++++++++++++++++++ docs/zh-CN/skills/agent-payment-x402/SKILL.md | 60 +++++++++++++++++++ skills/agent-payment-x402/SKILL.md | 60 +++++++++++++++++++ 3 files changed, 180 insertions(+) diff --git a/docs/ja-JP/skills/agent-payment-x402/SKILL.md b/docs/ja-JP/skills/agent-payment-x402/SKILL.md index 84d762311..0cf7b1904 100644 --- a/docs/ja-JP/skills/agent-payment-x402/SKILL.md +++ b/docs/ja-JP/skills/agent-payment-x402/SKILL.md @@ -305,6 +305,66 @@ curl -s https://api.mainnet-beta.solana.com -X POST -H 'Content-Type: applicatio これは新規プロビジョニングされたウォレットやカストディアルウォレットへの支払いで最も問題になりやすい。そうしたウォレットは対象アセットの ATA をまだ持っていないことが多い。 +**セラー:1 つの支払い承認につきルートは 1 回だけ実行する。** ミドルウェアは支払いを検証し、ハンドラーを実行し、その後で決済する。検証は承認を消費しない(消費するのは決済)ため、同じ署名済み支払いを同時に複数回送ると、毎回検証を通り、毎回ハンドラーが実行される。ファシリテーターが決済するのは 1 つのコピーだけで、残りはレスポンスなしの 402 を受け取るので、誰も無料で出力を得ることはない。しかしハンドラー内の副作用(LLM 呼び出し、ジョブのキュー投入、オンチェーントランザクション)はコピーごとに発生する。本番のセラー(Python `x402` 2.9.0、FastAPI)では、1 つの承認を同時に 3 回送ると、ハンドラーが 3 回実行され、決済は 1 回だった。ハンドラー内の有料呼び出しカウンターも同じように売上を過大に数えるので、決済後に数えること。検証から決済までのより広い競合については [x402#1169](https://github.com/x402-foundation/x402/issues/1169) で議論されている。 + +各承認を、支払いミドルウェアが実行される前に、アトミックな挿入で 1 回だけ取得する: + +```typescript +import { createHash } from "node:crypto"; +import { getBase64Encoder, getTransactionDecoder } from "@solana/kit"; +import { createClient } from "redis"; + +const redis = await createClient({ url: process.env.REDIS_URL }).connect(); + +// One key per authorization, not per header: re-encoding the same signed +// payment must not make it look new. +function claimKey(header: string): string { + try { + const p = JSON.parse(Buffer.from(header, "base64").toString("utf8")); + const network = p.accepted?.network ?? ""; + const auth = p.payload?.authorization; + if (auth?.from && auth?.nonce) { + // EVM exact (EIP-3009): the token contract accepts each (from, nonce) once. + return `x402:${network}:${String(auth.from).toLowerCase()}:${String(auth.nonce).toLowerCase()}`; + } + if (typeof p.payload?.transaction === "string") { + // SVM exact: hash the message the payer signed, not the whole transaction. + // The fee payer's signature slot sits outside the payer's signature, so a + // copy with different bytes there is still the same payment. + const tx = getTransactionDecoder().decode(getBase64Encoder().encode(p.payload.transaction)); + return `x402:${network}:${createHash("sha256").update(tx.messageBytes).digest("hex")}`; + } + } catch { + // Unparseable: fall through to the raw header, which still catches exact copies. + } + return `x402:raw:${createHash("sha256").update(header).digest("hex")}`; +} + +// Register on paid routes, before the x402 payment middleware. +async function replayGuard(req, res, next) { + const header = req.get("payment-signature") ?? req.get("x-payment"); + if (!header) return next(); + let first = true; + try { + // NX is atomic: of two simultaneous copies exactly one wins. EX only has to + // outlive the route's maxTimeoutSeconds; after that the authorization is dead. + first = (await redis.set(claimKey(header), "1", { NX: true, EX: 900 })) === "OK"; + } catch { + // Fail open: the facilitator still refuses a second settlement, so a store + // outage degrades to the unguarded behaviour instead of blocking buyers. + } + if (!first) { + return res.status(402).json({ + error: "payment_replayed", + detail: "This payment authorization was already presented. Sign a fresh one for each request.", + }); + } + next(); +} +``` + +条件付き挿入ができるストアなら何でもよい:DynamoDB の `attribute_not_exists` 付き `PutItem`、または Postgres のユニークインデックス。クライアント側のコストは、同じ署名で再試行したリクエスト(たとえば 5xx の後、決済がスキップされた場合)が拒否されるようになることだ。アップストリームのクライアントは 402 ごとに新しい承認に署名する。これが防ぐのは 1 つの承認の重複コピーだけである。検証と決済の間に支払いを無効にする支払者(たとえば資金を移動する)は、依然としてハンドラーを 1 回実行させられる。高コストなルートでは、作業の前に資金を確保すること。 + **発見。** x402 バザール拡張を実装するファシリテーターは `/discovery/resources` エンドポイントを公開する — CDP カタログは `https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources`、PayAI カタログは `https://facilitator.payai.network/discovery/resources` で照会できる。Solana で支払い可能なサービスには、Solana Foundation のキュレーションカタログである [pay.sh](https://pay.sh) もある。 ## 例 diff --git a/docs/zh-CN/skills/agent-payment-x402/SKILL.md b/docs/zh-CN/skills/agent-payment-x402/SKILL.md index f79359dd8..abc89e102 100644 --- a/docs/zh-CN/skills/agent-payment-x402/SKILL.md +++ b/docs/zh-CN/skills/agent-payment-x402/SKILL.md @@ -305,6 +305,66 @@ curl -s https://api.mainnet-beta.solana.com -X POST -H 'Content-Type: applicatio 这个问题在向新开通的钱包或托管钱包付款时最容易出现,这类钱包往往还没有该资产的 ATA。 +**卖方:每个支付授权只运行一次路由。** 中间件先验证支付,再运行处理程序,然后结算。验证不会消耗授权(结算才会),因此同一笔已签名的支付同时发送多次,每次都能通过验证,每次都会运行处理程序。结算器只结算其中一份副本,其余副本收到不带响应的 402,所以没有人能免费获得输出。但处理程序中的每个副作用(LLM 调用、排队任务、链上交易)都会按副本数重复发生。在一个生产卖方(Python `x402` 2.9.0、FastAPI)上,同一授权并发发送三次,处理程序运行了三次,结算一次。放在处理程序内的付费调用计数器也会以同样方式高估收入;应在结算后计数。更广泛的验证到结算竞态在 [x402#1169](https://github.com/x402-foundation/x402/issues/1169) 中讨论。 + +在支付中间件运行之前,用原子插入将每个授权只认领一次: + +```typescript +import { createHash } from "node:crypto"; +import { getBase64Encoder, getTransactionDecoder } from "@solana/kit"; +import { createClient } from "redis"; + +const redis = await createClient({ url: process.env.REDIS_URL }).connect(); + +// One key per authorization, not per header: re-encoding the same signed +// payment must not make it look new. +function claimKey(header: string): string { + try { + const p = JSON.parse(Buffer.from(header, "base64").toString("utf8")); + const network = p.accepted?.network ?? ""; + const auth = p.payload?.authorization; + if (auth?.from && auth?.nonce) { + // EVM exact (EIP-3009): the token contract accepts each (from, nonce) once. + return `x402:${network}:${String(auth.from).toLowerCase()}:${String(auth.nonce).toLowerCase()}`; + } + if (typeof p.payload?.transaction === "string") { + // SVM exact: hash the message the payer signed, not the whole transaction. + // The fee payer's signature slot sits outside the payer's signature, so a + // copy with different bytes there is still the same payment. + const tx = getTransactionDecoder().decode(getBase64Encoder().encode(p.payload.transaction)); + return `x402:${network}:${createHash("sha256").update(tx.messageBytes).digest("hex")}`; + } + } catch { + // Unparseable: fall through to the raw header, which still catches exact copies. + } + return `x402:raw:${createHash("sha256").update(header).digest("hex")}`; +} + +// Register on paid routes, before the x402 payment middleware. +async function replayGuard(req, res, next) { + const header = req.get("payment-signature") ?? req.get("x-payment"); + if (!header) return next(); + let first = true; + try { + // NX is atomic: of two simultaneous copies exactly one wins. EX only has to + // outlive the route's maxTimeoutSeconds; after that the authorization is dead. + first = (await redis.set(claimKey(header), "1", { NX: true, EX: 900 })) === "OK"; + } catch { + // Fail open: the facilitator still refuses a second settlement, so a store + // outage degrades to the unguarded behaviour instead of blocking buyers. + } + if (!first) { + return res.status(402).json({ + error: "payment_replayed", + detail: "This payment authorization was already presented. Sign a fresh one for each request.", + }); + } + next(); +} +``` + +任何支持条件插入的存储都可以:DynamoDB 带 `attribute_not_exists` 的 `PutItem`,或 Postgres 的唯一索引。客户端的代价是,使用同一签名重试的请求(例如在 5xx 之后,结算被跳过时)现在会被拒绝;上游客户端本来就会为每个 402 签署新的授权。这只能阻止同一授权的重复副本。在验证和结算之间使支付失效的付款方(例如转走资金)仍能触发一次处理程序运行;对于高成本路由,应在执行工作前先锁定资金。 + **发现。** 实现 x402 集市扩展的结算器会公开 `/discovery/resources` 端点——可在 `https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources` 查询 CDP 目录,在 `https://facilitator.payai.network/discovery/resources` 查询 PayAI 目录。对于 Solana 可付费服务,还有 Solana 基金会的精选目录 [pay.sh](https://pay.sh)。 ## 示例 diff --git a/skills/agent-payment-x402/SKILL.md b/skills/agent-payment-x402/SKILL.md index 41608571d..1cd73f189 100644 --- a/skills/agent-payment-x402/SKILL.md +++ b/skills/agent-payment-x402/SKILL.md @@ -306,6 +306,66 @@ To provision it (whoever creates it pays the small rent, not the payer): This bites hardest when payouts go to freshly provisioned or custodial wallets, which often have no ATA for the asset yet. +**Sellers: run the route once per payment authorization.** The middleware verifies the payment, runs your handler, then settles. Verification does not consume the authorization (settlement does), so one signed payment sent several times at once passes verify every time and runs your handler every time. The facilitator settles only one copy, and the others get a 402 without the response, so nobody receives free output. But every side effect in the handler (an LLM call, a queued job, an on-chain transaction) happens once per copy. On a production seller (Python `x402` 2.9.0, FastAPI), one authorization sent three times concurrently produced three handler runs and one settlement. A paid-call counter inside the handler overstates revenue the same way; count after settlement instead. The wider verify-to-settle race is discussed in [x402#1169](https://github.com/x402-foundation/x402/issues/1169). + +Claim each authorization once, with an atomic insert, before the payment middleware runs: + +```typescript +import { createHash } from "node:crypto"; +import { getBase64Encoder, getTransactionDecoder } from "@solana/kit"; +import { createClient } from "redis"; + +const redis = await createClient({ url: process.env.REDIS_URL }).connect(); + +// One key per authorization, not per header: re-encoding the same signed +// payment must not make it look new. +function claimKey(header: string): string { + try { + const p = JSON.parse(Buffer.from(header, "base64").toString("utf8")); + const network = p.accepted?.network ?? ""; + const auth = p.payload?.authorization; + if (auth?.from && auth?.nonce) { + // EVM exact (EIP-3009): the token contract accepts each (from, nonce) once. + return `x402:${network}:${String(auth.from).toLowerCase()}:${String(auth.nonce).toLowerCase()}`; + } + if (typeof p.payload?.transaction === "string") { + // SVM exact: hash the message the payer signed, not the whole transaction. + // The fee payer's signature slot sits outside the payer's signature, so a + // copy with different bytes there is still the same payment. + const tx = getTransactionDecoder().decode(getBase64Encoder().encode(p.payload.transaction)); + return `x402:${network}:${createHash("sha256").update(tx.messageBytes).digest("hex")}`; + } + } catch { + // Unparseable: fall through to the raw header, which still catches exact copies. + } + return `x402:raw:${createHash("sha256").update(header).digest("hex")}`; +} + +// Register on paid routes, before the x402 payment middleware. +async function replayGuard(req, res, next) { + const header = req.get("payment-signature") ?? req.get("x-payment"); + if (!header) return next(); + let first = true; + try { + // NX is atomic: of two simultaneous copies exactly one wins. EX only has to + // outlive the route's maxTimeoutSeconds; after that the authorization is dead. + first = (await redis.set(claimKey(header), "1", { NX: true, EX: 900 })) === "OK"; + } catch { + // Fail open: the facilitator still refuses a second settlement, so a store + // outage degrades to the unguarded behaviour instead of blocking buyers. + } + if (!first) { + return res.status(402).json({ + error: "payment_replayed", + detail: "This payment authorization was already presented. Sign a fresh one for each request.", + }); + } + next(); +} +``` + +Any store with a conditional insert works: DynamoDB `PutItem` with `attribute_not_exists`, or a unique index in Postgres. The client-side cost is that a request retried with the same signature (for example after a 5xx, when settlement was skipped) is now refused; the upstream clients already sign a fresh authorization for each 402. This closes duplicate copies of one authorization only. A payer who invalidates the payment between verify and settle (for example by moving the funds) still gets one handler run; for expensive routes, hold funds before doing the work. + **Discovery.** Facilitators that implement the x402 bazaar extension expose a `/discovery/resources` endpoint — query the CDP catalog at `https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources` and the PayAI catalog at `https://facilitator.payai.network/discovery/resources`. For Solana-payable services there is also [pay.sh](https://pay.sh), the Solana Foundation's curated catalog. ## Examples