Repository navigation
feat(x402): spec v2 402 challenge (PAYMENT-REQUIRED, amount, extra) + PAYMENT-SIGNATURE; v1 unchanged - #1569
Conversation
…ep X-PAYMENT and v1 fields The live 402 on POST /api/v1/x402/:uuid/trade-analysis was a hybrid: body x402Version 2 with v1 entries, no PAYMENT-REQUIRED header, no EIP-712 extra, and only X-PAYMENT read. The official @x402 client could not parse it. Adds the base64 PAYMENT-REQUIRED header (strict v2 PaymentRequired), amount and extra {name, version} on each entry, PAYMENT-SIGNATURE on the retry, and PAYMENT-RESPONSE. The v1 body fields and X-PAYMENT stay. Amount, payee and the facilitator request are unchanged; a conformance test drives the official client end to end. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…o not Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CodeQL js/missing-rate-limiting flags the handler (open on main as #93 since 2026-10-10; re-raised on this PR because the handler moved lines). It does not model src/middleware/rate-limit.ts. The test shows the 402 carries the limiter's ip bucket headers and a burst gets 429 rate_limited; with the global limiter removed it fails. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…er IP CodeQL js/missing-rate-limiting (alert #181 here, #93 on main) does not model the global token-bucket limiter. Adds an express-rate-limit limiter on POST /api/v1/x402/:uuid/trade-analysis, keyed on the trusted client IP. 120/min, not 60: the global 60-token bucket refilling 60/min passes at most 120 in any minute, so a 120 fixed window never refuses a request today's limiter allows. legacyHeaders off so it does not overwrite X-RateLimit-*. tests/x402-route-limiter.test.ts switches the global limiter off and gets 429 x402-route on request 121; removing the limiter turns it red. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Strix Security Review✅ No open security findings. PR summary: This PR makes the engine's paid x402 route POST /api/v1/x402/:uuid/trade-analysis emit a spec-conforming v2 402 challenge (a base64 PAYMENT-REQUIRED header plus v2 fields in the JSON body, including the EIP-712 extra domain) and accept the official v2 PAYMENT-SIGNATURE payload on the retry, while keeping the v1 body fields, X-PAYMENT, and the facilitator request unchanged. It also adds a per-route rate limiter, CORS entries for the new headers, and a conformance test suite driven by the official @x402 client. Review summaryReviewed the x402 v2 challenge change end to end: the PAYMENT-REQUIRED/PAYMENT-RESPONSE/PaymentPayload handling and header normalization in src/routes/x402-inbound.ts and src/services/x402-facilitator.ts, the new per-route limiter and its client-IP keying, the CORS header additions, and the new EIP-712 domain config in src/config/network.ts. No actionable security issue was found: every field that decides settlement (amount, payee, asset, network) is still taken from the server's own requirements and the client's Ruled out (4)
Review 1 on this PR · Reviewed by Strix |
There was a problem hiding this comment.
Reviewed the x402 v2 challenge change end to end: the PAYMENT-REQUIRED/PAYMENT-RESPONSE/PaymentPayload handling and header normalization in src/routes/x402-inbound.ts and src/services/x402-facilitator.ts, the new per-route limiter and its client-IP keying, the CORS header additions, and the new EIP-712 domain config in src/config/network.ts. No actionable security issue was found: every field that decides settlement (amount, payee, asset, network) is still taken from the server's own requirements and the client's accepted claim is discarded before the facilitator request, the new payload shape only relocates where the signature and authorization are read from, the settle-before-deliver ordering is intact on every branch, and the added limiter is additive rather than a new bypass path. The concerns that came up — a case-sensitive path gate in the pre-existing global limiter, an ineffective accepted pre-check that is not a value control, the absence of a local nonce replay guard, and per-IP key trust — were each independently validated and rejected as either inert or pre-existing conditions the PR does not make reachable.
Reviewed by Strix
Configure security review settings
Owner action: none from you unless a reviewer disagrees on the weight
Weight: MEDIUM (r31: a live API response change; no amount, payee, key or chain id moves). Draft. Before it can merge: Grok review (label
grok-review), Strix, and all CI green on one head SHA. Then a merging session may auto-merge under D-161. This session does not merge it, and you should not merge it by hand before Grok and Strix have run. Merging deploys the API to Railway (repid-engineservice); there is no flag, so the new 402 shape goes live on deploy. Rollback is a revert of this PR.One judgment call for the reviewers (not blocking): the paid route now accepts the official x402
PaymentPayloadshape on the retry. That is a new input shape on a route that settles real testnet USDC. It does not change what is paid: amount, payee, asset and network in the facilitator request still come from the server's own requirements, and a test pins the facilitator request byte for byte onmainand on this branch. If a reviewer reads "new payload shape on a settling route" as MAJOR, it becomes yours to approve.What was wrong
Gap 5 of the 2026-11-16 E2E eval (§5, §7): the live 402 on
POST /api/v1/x402/:uuid/trade-analysiswas a v1/v2 hybrid. The body saidx402Version: 2but carried v1 entries (maxAmountRequired, a per-entryresourcestring). There was noPAYMENT-REQUIREDheader and no EIP-712extra, and the retry read onlyX-PAYMENT.Read against production today, with no payment header (the route answers 402 before any write), by the official
@x402/fetch2.29.0 parser: header absent, and parsing failed withInvalid payment required response. The official v2 schema rejects the body for a missingresourceobject and a missingaccepts[0].amount. A second failure sat behind the first: the official EVM client will not sign an EIP-3009 authorization withoutextra.nameandextra.version.What changes
Spec: coinbase/x402
specs/x402-specification-v2.md(sha256cb66bdef…, the same file the eval cited),specs/transports-v2/http.mdandspecs/schemes/exact/scheme_exact_evm.md, read today frommain@0e6e8c55. The field names below are copied from those files.acceptson this route now sendsPAYMENT-REQUIRED: base64 of a strict v2PaymentRequiredwithx402Version,error, a top-levelresource {url, description, mimeType}, andaccepts[] {scheme, network, amount, asset, payTo, maxTimeoutSeconds, extra {name, version}}. It carries no v1 fields.maxAmountRequired, per-entryresource,mimeType,description) and gainsamount,extraand the top-levelresourceobject. It now also parses under the official v2 schema.PAYMENT-SIGNATURE, thenX-PAYMENT. If both are present and differ, the route answers 400conflicting_payment_headersrather than choosing one. An official payload (payload.signature/payload.authorization) is flattened into the shape the facilitator code already decodes. A flat header (what trustshell andx402-outbound-client.tssend) passes through unchanged.acceptednames terms it did not advertise. That covers scheme, network, amount, asset and payTo. It answers 402accepted_requirements_mismatchbefore any facilitator call, as the official server middleware does.PAYMENT-RESPONSE(base64SettlementResponse) is sent on success and on settlement failure, beside the unchangedX-PAYMENT-RESPONSE.src/config/network.ts, read on chain today withname()/version(). Base Sepolia USDC isUSDC/2; Base mainnet isUSD Coin/2. They differ, so this cannot be one shared constant.payment-signatureand exposespayment-requiredandpayment-response. A browser client that cannot readPAYMENT-REQUIREDcannot pay.docs/X402_SITE_GATE.mdsaid the route "verifies/settles anX-PAYMENTheader", which was the whole defect. It is corrected, and it names the two emitters that are still v1-shaped.Unchanged: the price (
10000), the payee (the agent'swallet_address, still fail-closed on unset),buildV2Envelopeand the facilitator/verifyand/settlecalls, and the escrow and tip routes' header handling.Evidence
tests/x402-v2-conformance.test.tsruns the official client:@x402/fetch+@x402/evm+@x402/core, pinned exactly to2.29.0as devDependencies. 2.29.0 was published 2026-10-28; 2.30 and 2.31 are under two weeks old. The test generates a throwaway buyer key, makes no network call outside localhost, and stubs the facilitator.wrapFetchWithPaymentreads the challenge, signs, retries withPAYMENT-SIGNATURE, and gets a 200. The official decoder readsPAYMENT-RESPONSE. The facilitator receives the client's own signature against our amount and payee. The signature recovers to the payer under the advertised domain.PaymentRequiredV2Schemaandx402HTTPClient.getPaymentRequiredResponse.mainand on this branch. One pins the v1 body fields. The other sends a flatX-PAYMENTfrom a deterministic signer and asserts the exact/verifyand/settlerequest bodies.X-PAYMENTand a v2PAYMENT-SIGNATUREcarrying one authorization produce identical facilitator requests.accepted(amount, payTo, network), and a failed settlement each answer as described, with no facilitator call where none should happen.main'ssrc/The headline failure on
mainis in the official client's own words:Failed to parse payment requirements: Invalid payment required response. Logs are inE:\dev\reports\2026-11-16\x402-v2\(fail-on-main.log,pass-on-branch.log,live-production-challenge.log,README.md). The main run wasgit checkout origin/main -- src/, run,git checkout HEAD -- src/, with no stash.Neighbouring suites:
tsc --noEmitis clean. 18 of 19 suites pass (alltests/*x402*, payee fail-closed, CORS, open-read CORS, join-kit, egress guard, lessons cap). The one red suite,tests/x402-gate-shadow-purity.test.ts, fails the same way withmain'ssrc/: abeforeAllexceeds 5 s on this machine. So it is ENV, not this diff; CI is the check.CodeQL
js/missing-rate-limiting(alert #181): a per-route limiter on top of the global oneThe handler is rate-limited. It is the same finding as alert #93, which has been open on
mainsince 2026-10-10 with the identical message and was last seen ataf0a7461. It shows as "new" here only because the handler moved from line 10 to line 43. CodeQL recognisesexpress-rate-limit-style middleware. It does not model the engine's own token-bucket limiter, which every/api/v1request passes through first.Mount order in
src/index.ts(line numbers on this branch):rateLimitMiddleware()gates every non-OPTIONS request whose path starts with/api/v1. An anonymous caller, which is every x402 buyer, is counted in theip:bucket atIP_DEFAULT= 60 per minute. A refused request gets429 {error: "rate_limited"}before the handler runs. There is no route override for/api/v1/x402.Measured, not asserted: a new test in
tests/x402-v2-conformance.test.ts, "the route is behind the global per-IP rate limiter", shows the 402 carriesX-RateLimit-Bucket: ipandX-RateLimit-Limit. A burst from one IP then gets429 rate_limitedwith noPAYMENT-REQUIRED, meaning it was refused before the handler ran. Withapp.use(globalRateLimit())commented out, the same test fails (Expected "ip", Received undefined). Logs:rate-limit-pass.logandrate-limit-mutation.login the report folder.Per-route limiter added (Sean's choice, 2026-11-16).
x402RouteLimiterinsrc/routes/x402-inbound.tsis anexpress-rate-limitlimiter, the package CodeQL recognises and the onesrc/index.tsalready uses. It is passed straight intorouter.post('/:uuid/trade-analysis', x402RouteLimiter, handler)and keyed onipKeyGenerator(trustedClientIp(req)), as the other limiters are.legacyHeaders: false, so it does not overwrite the global limiter'sX-RateLimit-*headers. It reports inRateLimit-*(draft-6) instead.429 {error: "rate_limited", bucket: "x402-route", limit: 120}.tests/x402-route-limiter.test.tsswitches the global limiter off, so a 429 can only come from the route limiter. Requests 1 to 120 get 402, and request 121 gets429 x402-route, refused before the handler. With the limiter removed from the route, that test fails (Expected: 120, Received: NaN). The conformance test also asserts the route limit is at least twice the global limit, so tightening either one turns it red.route-limiter-pass.logandroute-limiter-mutation.log.50ab38b8: theCodeQLcheck concludedsuccess("No new alerts in code changed by this pull request"). The newest analysis ofrefs/pull/1569/mergeis on merge commitaa40d588(parentsaf0a7461and50ab38b8) and has 0 results; the one before, on head83b29fee, had 1. Alert fix(leaderboard): narrative no longer self-contradicts when one model tops both lenses #181's instance on the PR ref is nowfixed. Alert fix(ci): make CI/test and crosscheck pass meaningfully (WARN_ONLY + dummy HF token) #93 onmainstays open until this merges.Also changed in passing, and why it is safe
buildPaymentRequirementsnow setsextra, andx402-resilient.tsverifyEip3009LocalreadsreqObj.extra?.name || 'USDC'. On Base Sepolia that gives the same domain as before. On mainnet it now gives the correctUSD Coinwhere it used to default to the wrongUSDC. Today no route sendsbuildPaymentRequirementsoutput to that function:resilientVerifyPaymenthas no caller, and the gasless path builds its own requirements. The escrow 402 body also gainsamountandextrathrough the same builder. Both are additive.Not done here (follow-ups)
POST /contracts/:id/escrow,src/services/x402-server.ts) still emit v1-shaped challenges and read onlyX-PAYMENT. They were left alone on purpose: advertising v2 there before acceptingPAYMENT-SIGNATUREwould send a v2 client into a 402 loop.descriptionreads "… verified by HyperDAG ZKP RepID". That is a public claim on a surface strangers hit, and the eval found the proofs are range checks. Out of scope here.tests/cors-headers.test.tsscans onlyx-header names, so it cannot see the v2 headers. The new test pins them instead.PAYMENT-SIGNATURE. That is another repo and was not touched.🤖 Generated with Claude Code