Skip to content

feat(x402): spec v2 402 challenge (PAYMENT-REQUIRED, amount, extra) + PAYMENT-SIGNATURE; v1 unchanged - #1569

Merged
DealAppSeo merged 5 commits into
mainfrom
claude/x402-v2-challenge-aa091d
Nov 17, 2026
Merged

DealAppSeo merged 5 commits into
mainfrom
claude/x402-v2-challenge-aa091d

Conversation

@DealAppSeo

@DealAppSeo DealAppSeo commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner

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-engine service); 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 PaymentPayload shape 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 on main and 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-analysis was a v1/v2 hybrid. The body said x402Version: 2 but carried v1 entries (maxAmountRequired, a per-entry resource string). There was no PAYMENT-REQUIRED header and no EIP-712 extra, and the retry read only X-PAYMENT.

Read against production today, with no payment header (the route answers 402 before any write), by the official @x402/fetch 2.29.0 parser: header absent, and parsing failed with Invalid payment required response. The official v2 schema rejects the body for a missing resource object and a missing accepts[0].amount. A second failure sat behind the first: the official EVM client will not sign an EIP-3009 authorization without extra.name and extra.version.

What changes

Spec: coinbase/x402 specs/x402-specification-v2.md (sha256 cb66bdef…, the same file the eval cited), specs/transports-v2/http.md and specs/schemes/exact/scheme_exact_evm.md, read today from main @ 0e6e8c55. The field names below are copied from those files.

  • Every 402 that advertises accepts on this route now sends PAYMENT-REQUIRED: base64 of a strict v2 PaymentRequired with x402Version, error, a top-level resource {url, description, mimeType}, and accepts[] {scheme, network, amount, asset, payTo, maxTimeoutSeconds, extra {name, version}}. It carries no v1 fields.
  • The JSON body keeps every v1 field (maxAmountRequired, per-entry resource, mimeType, description) and gains amount, extra and the top-level resource object. It now also parses under the official v2 schema.
  • The retry reads PAYMENT-SIGNATURE, then X-PAYMENT. If both are present and differ, the route answers 400 conflicting_payment_headers rather 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 and x402-outbound-client.ts send) passes through unchanged.
  • The route refuses a v2 payload whose accepted names terms it did not advertise. That covers scheme, network, amount, asset and payTo. It answers 402 accepted_requirements_mismatch before any facilitator call, as the official server middleware does.
  • PAYMENT-RESPONSE (base64 SettlementResponse) is sent on success and on settlement failure, beside the unchanged X-PAYMENT-RESPONSE.
  • The EIP-712 domain is per network in src/config/network.ts, read on chain today with name() / version(). Base Sepolia USDC is USDC / 2; Base mainnet is USD Coin / 2. They differ, so this cannot be one shared constant.
  • CORS allows payment-signature and exposes payment-required and payment-response. A browser client that cannot read PAYMENT-REQUIRED cannot pay.
  • docs/X402_SITE_GATE.md said the route "verifies/settles an X-PAYMENT header", 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's wallet_address, still fail-closed on unset), buildV2Envelope and the facilitator /verify and /settle calls, and the escrow and tip routes' header handling.

Evidence

tests/x402-v2-conformance.test.ts runs the official client: @x402/fetch + @x402/evm + @x402/core, pinned exactly to 2.29.0 as 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.

  • End to end: wrapFetchWithPayment reads the challenge, signs, retries with PAYMENT-SIGNATURE, and gets a 200. The official decoder reads PAYMENT-RESPONSE. The facilitator receives the client's own signature against our amount and payee. The signature recovers to the payer under the advertised domain.
  • The header is strict: its key sets equal the spec's field tables exactly, and it parses under PaymentRequiredV2Schema and x402HTTPClient.getPaymentRequiredResponse.
  • v1 identical on both sides: two tests must be green on main and on this branch. One pins the v1 body fields. The other sends a flat X-PAYMENT from a deterministic signer and asserts the exact /verify and /settle request bodies.
  • Same settlement for both shapes: a flat X-PAYMENT and a v2 PAYMENT-SIGNATURE carrying one authorization produce identical facilitator requests.
  • Refusals: conflicting headers, mismatched accepted (amount, payTo, network), and a failed settlement each answer as described, with no facilitator call where none should happen.
run result
this test file + main's src/ 11 failed, 2 passed of 13; the 2 are the "identical on main and on this branch" pair
this test file + this branch 13 passed (14 with the rate-limit test added later; see below)

The headline failure on main is in the official client's own words: Failed to parse payment requirements: Invalid payment required response. Logs are in E:\dev\reports\2026-11-16\x402-v2\ (fail-on-main.log, pass-on-branch.log, live-production-challenge.log, README.md). The main run was git checkout origin/main -- src/, run, git checkout HEAD -- src/, with no stash.

Neighbouring suites: tsc --noEmit is clean. 18 of 19 suites pass (all tests/*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 with main's src/: a beforeAll exceeds 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 one

The handler is rate-limited. It is the same finding as alert #93, which has been open on main since 2026-10-10 with the identical message and was last seen at af0a7461. It shows as "new" here only because the handler moved from line 10 to line 43. CodeQL recognises express-rate-limit-style middleware. It does not model the engine's own token-bucket limiter, which every /api/v1 request passes through first.

Mount order in src/index.ts (line numbers on this branch):

304  app.use(express.json({ limit: "1mb" }));
312  app.use(attestationExtractorMiddleware);
313  app.use(globalRateLimit());                     // src/middleware/rate-limit.ts rateLimitMiddleware()
...
635  app.use('/api/v1/x402', x402InboundRouter);     // POST /api/v1/x402/:uuid/trade-analysis

rateLimitMiddleware() gates every non-OPTIONS request whose path starts with /api/v1. An anonymous caller, which is every x402 buyer, is counted in the ip: bucket at IP_DEFAULT = 60 per minute. A refused request gets 429 {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 carries X-RateLimit-Bucket: ip and X-RateLimit-Limit. A burst from one IP then gets 429 rate_limited with no PAYMENT-REQUIRED, meaning it was refused before the handler ran. With app.use(globalRateLimit()) commented out, the same test fails (Expected "ip", Received undefined). Logs: rate-limit-pass.log and rate-limit-mutation.log in the report folder.

Per-route limiter added (Sean's choice, 2026-11-16). x402RouteLimiter in src/routes/x402-inbound.ts is an express-rate-limit limiter, the package CodeQL recognises and the one src/index.ts already uses. It is passed straight into router.post('/:uuid/trade-analysis', x402RouteLimiter, handler) and keyed on ipKeyGenerator(trustedClientIp(req)), as the other limiters are.

  • The limit is 120 per minute, not 60. The global limiter is a 60-token bucket that refills at 60 per minute, so it can pass up to 120 requests in any 60 seconds. A fixed window of 60 would refuse some bursts that today's limiter allows; a fixed window of 120 never does. Paying clients are throttled no harder than before.
  • legacyHeaders: false, so it does not overwrite the global limiter's X-RateLimit-* headers. It reports in RateLimit-* (draft-6) instead.
  • Over the limit: 429 {error: "rate_limited", bucket: "x402-route", limit: 120}.
  • tests/x402-route-limiter.test.ts switches the global limiter off, so a 429 can only come from the route limiter. Requests 1 to 120 get 402, and request 121 gets 429 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.
  • Logs: route-limiter-pass.log and route-limiter-mutation.log.
  • CodeQL cleared it, read from GitHub on head 50ab38b8: the CodeQL check concluded success ("No new alerts in code changed by this pull request"). The newest analysis of refs/pull/1569/merge is on merge commit aa40d588 (parents af0a7461 and 50ab38b8) and has 0 results; the one before, on head 83b29fee, had 1. Alert fix(leaderboard): narrative no longer self-contradicts when one model tops both lenses #181's instance on the PR ref is now fixed. Alert fix(ci): make CI/test and crosscheck pass meaningfully (WARN_ONLY + dummy HF token) #93 on main stays open until this merges.

Also changed in passing, and why it is safe

buildPaymentRequirements now sets extra, and x402-resilient.ts verifyEip3009Local reads reqObj.extra?.name || 'USDC'. On Base Sepolia that gives the same domain as before. On mainnet it now gives the correct USD Coin where it used to default to the wrong USDC. Today no route sends buildPaymentRequirements output to that function: resilientVerifyPayment has no caller, and the gasless path builds its own requirements. The escrow 402 body also gains amount and extra through the same builder. Both are additive.

Not done here (follow-ups)

  • Escrow and tip (POST /contracts/:id/escrow, src/services/x402-server.ts) still emit v1-shaped challenges and read only X-PAYMENT. They were left alone on purpose: advertising v2 there before accepting PAYMENT-SIGNATURE would send a v2 client into a 402 loop.
  • Escrow's replay guard compares the raw header string. A re-encoded copy of the same authorization is a different string. The on-chain EIP-3009 nonce still stops a second transfer, but the guard should key on (payer, nonce). Moving escrow to v2 makes this more pressing, since two encodings become normal.
  • The challenge's description reads "… 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.ts scans only x- header names, so it cannot see the v2 headers. The new test pins them instead.
  • trustshell's client could move to PAYMENT-SIGNATURE. That is another repo and was not touched.

🤖 Generated with Claude Code

DealAppSeo and others added 3 commits November 16, 2026 12:32
…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>
@DealAppSeo DealAppSeo added the grok-review Ask the grok-review loop to review this PR (also drafts) label Nov 16, 2026
DealAppSeo and others added 2 commits November 16, 2026 13:24
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>
@DealAppSeo
DealAppSeo marked this pull request as ready for review November 17, 2026 01:09
@strix-security

strix-security Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

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 summary

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.

Ruled out (4)
  • Can a mixed-case request path skip the global /api/v1 rate limiter and reach the paid route unthrottled?
    The case-sensitive gate lives in unchanged middleware, the new route-level limiter matches the route under any casing and keys purely on IP, and the PR strictly reduces the ceiling on this route from unbounded (mixed case on main) to 120/min.
  • Can a caller bypass the accepted-requirements check and have the route settle or deliver against terms it never advertised?
    The client's `accepted` object has no consumer beyond the comparison itself, since the facilitator request builds both paymentRequirements and paymentAccepted from the server's own requirements, so skipping the check changes only which 402 reason the caller sees.
  • Can one authorization be replayed for multiple paid deliveries or settlements?
    Sequential replays are stopped by the EIP-3009 nonce, the verify/settle ordering is byte-identical to main, and the delivered resource is a not-implemented placeholder the same caller could obtain by paying again, so no attacker gains anything or harms another party.
  • Can a caller rotate the trusted client-IP header to evade the new per-route limiter?
    The new limiter keys on the same value as the pre-existing global limiter and only adds a cap, the self-host entrypoint does not mount these routes at all, and the requests it would free up are cheap 402 responses that affect no other user or shared state.

Review 1 on this PR · 50ab38b · requested Nov 17 01:09 UTC when the PR was opened


Reviewed by Strix
Re-run review · Configure security review settings · Try a deeper review with @strix-security /deep

@strix-security strix-security Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@DealAppSeo
DealAppSeo merged commit a15954c into main Nov 17, 2026
19 checks passed
@DealAppSeo
DealAppSeo deleted the claude/x402-v2-challenge-aa091d branch November 17, 2026 01:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

grok-review Ask the grok-review loop to review this PR (also drafts)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant