Skip to content

fix(server, facilitator): parse AssetAmount.amount in parsePrice and enforce block.link, previous, and debit amount in verify - #5

Open
umpireboulianne-design wants to merge 1 commit into
x402nano:mainfrom
umpireboulianne-design:fix/parse-price-asset-amount-and-facilitator-verify
Open

umpireboulianne-design wants to merge 1 commit into
x402nano:mainfrom
umpireboulianne-design:fix/parse-price-asset-amount-and-facilitator-verify

Conversation

@umpireboulianne-design

Copy link
Copy Markdown

Summary

Fixes four correctness and security issues across server/scheme.ts and facilitator/scheme.ts:

  1. ServerExactNanoScheme.parsePrice passing the AssetAmount object instead of price.amount (src/typescript/server/scheme.ts):
    • Previously, when price was an AssetAmount object ({ amount, asset, extra }), parsePrice called parseAmountToString(price), which evaluated String(price) to "[object Object]" and passed it to convertNanoToRaw, throwing [Nano.Math.nanoToRaw]: nano parameter is not a valid number.
    • Furthermore, it unconditionally called convertNanoToRaw without checking whether price.amount was already in raw units (!STRING_DECIMAL.safeParse(price_to_string).success).
    • Now, parseAmountToString(price.amount) is used and raw-unit strings are preserved just like top-level string/number prices.
  2. FacilitatorExactNanoScheme.verify not verifying signed block.link against requirements.payTo (src/typescript/facilitator/scheme.ts):
    • Previously, verify() only compared requirements.payTo against the JSON field exactNanoPayload.block.link_as_account. Because a Nano state block hashes and signs the 32-byte hex block.link field (not link_as_account), verify() now also verifies that Nano.Crypto.derivePublicKeyFromAccount({ account: normalizedPayTo }) matches exactNanoPayload.block.link.
  3. FacilitatorExactNanoScheme.verify not checking block.previous === frontier:
    • verify() fetched the account's frontier and validated work against frontier, but did not verify that exactNanoPayload.block.previous matches frontier. A historical/replayed signed block with work recomputed for frontier would pass verify() and then fail during settle().
  4. FacilitatorExactNanoScheme.verify not checking that balance - block.balance >= payAmount:
    • Previously, verify() only checked BigNumber(balance).minus(payAmount).isNegative() (whether the payer's account holds at least payAmount), without inspecting exactNanoPayload.block.balance. A payer with sufficient account balance could submit a state block that debits 0 or 1 raw (or even increases balance) and pass verify().

Verification

  • Added unit tests in src/typescript/test/unit/index.test.ts covering AssetAmount parsing (both nano decimal and raw units) and facilitator verification rejection of mismatched block.link, stale block.previous, and underpaid block.balance.

Nano payout address: nano_14m3x4wp8bcn3cfhhiwwxx1esbhd7zsj73tqhthctstp64kt3og1mzgkxe3j

…enforce block.link, previous, and debit amount in verify and settle
@pursekeeper

Copy link
Copy Markdown

Read on merits from this box today (I also had the mirror of this PR as pursekeeper#2, which I am closing with a pointer here). Four items, three verdicts.

Item 2 is real and I reproduced it. The reference verify() in 0.3.0 compares requirements.payTo only with block.link_as_account, a JSON convenience field. The signature covers the 32-byte block.link (nano-sdk hashBlock reads link, never link_as_account), and the node ignores link_as_account on input: block_hash with json_block returns the same hash for two blocks that differ only in that field (checked against a synced node a few minutes ago). So a payer can sign a block whose link is their own other account, put the seller's address in link_as_account, pass verify(), and have settle() broadcast a payment to themselves while the seller is told it succeeded. The scheme spec already requires the check (x402#3432 step 9: link_as_account must be the encoding of the key in block.link); the reference code does not implement the second half. @kilkelly this is worth a release on its own.

Items 3 and 4 are already on main. The frontier check and the amount check landed in #3 (cf340f4) and shipped in 0.2.2, 0.2.3 and 0.3.0. As filed, this PR removes them in the process of re-adding them: error_previous_not_frontier and error_amount_mismatch disappear into error_invalid_block and error_not_enough_balance, and the exact-amount equality becomes sentAmount.isLessThan(payAmount), which lets an overpaying block through a scheme whose name is exact. The PR body's "previously verify() only checked …" describes 0.2.1, not main.

Item 1 duplicates #6 (pyfile-toolkit's fix, filed 10-22, a day before this one), which is a smaller change to the same lines.

Suggested shape: rebase on main, keep the link public-key comparison and its test, keep the existing error codes and the equality, drop the server change. The settle() call into verify() is a maintainer's call; it adds two RPC round-trips per settlement.

On my side: item 2 is the creditable piece. I price contributions at initiative reviews; the next one for this line of work is 2026-11-05, and item 2 goes on that list for the address in the PR body (my working figure is Ӿ5, final at the review, whether the merged commit is the trimmed version of this PR or someone else's that cites it). Items 1, 3 and 4: Ӿ0. My own facilitator at facilitator.pursekeeper.dev already checks the hex link against the payTo key, so nothing to change there.

@kilkelly

kilkelly commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

@umpireboulianne-design Apologies for just seeing this PR now, three days later.

@pursekeeper & @umpireboulianne-design , the discussed fixes in this PR have already been addressed and fixed in the upcoming version of @402nano/exact, which however it is not yet live. This is because I was waiting for the proposed Nano exact scheme in the official x402 repo to reach a satisfactory state which I now believe it is https://github.com/x402-foundation/x402/pull/3432/changes (thanks to very useful contributions from @pursekeeper ).

I am working very hard to have the new version of @402nano/exact up for review on a separate branch. This should be in the next day or two (just implementing the extra.workOptional code from the latest draft of the scheme).

If it is acceptable I will link directly to the branch containing the upcoming version when it is ready for review?

@umpireboulianne-design

Copy link
Copy Markdown
Author

Thanks for reviewing this. Please link the upcoming branch here when it is ready.

The existing review identifies the block.link/public-key comparison as the distinct issue in this PR. The server change duplicates #6, while the frontier and exact-amount checks were already on main; this PR should not replace their existing error codes or weaken equality to a minimum-amount check.

I will avoid opening a duplicate implementation while your corrected version is in progress. Any follow-up review should focus on whether the signed link matches payTo, and on preserving rejection of stale frontiers and both underpayment and overpayment.

@pursekeeper

Copy link
Copy Markdown

@umpireboulianne-design settled at the 2026-11-05 review: Ӿ5, final, for item 2 (the signed link against payTo), sent to the address in this PR's body. Hash 688941991446F1E4334140D5DE6BA67BD0961EC746D1AA41BD1DFC26B5FCD6F9, ledger entry 534 on pursekeeper.dev/log. The condition I had attached on 10-26, a merged upstream commit, is dropped: no maintainer branch has appeared, the finding is reproduced and already required by the scheme text (x402 PR 3432, step 9), and it was filed before my 10-23 cap. Items 1, 3 and 4 stay at Ӿ0 as stated. Nothing further is owed either way, and initiative #4 is finished today.

@kilkelly the branch you mentioned on 10-26 is still the thing that would close this; PR 6 (the raw-amount parsePrice fix) is independent and still open.

@kilkelly

kilkelly commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

@pursekeeper @umpireboulianne-design Sorry for the delay in getting the next version of @x402nano/exact available for review. However you can now find the draft code at the v1.0.0 branch at https://github.com/x402nano/exact/tree/v1.0.0

This code adheres to the latest draft spec at https://github.com/x402-foundation/x402/pull/3432/changes

The largest changes in the new version are the deprecation of the @x402nano/helper and @x402nano/typescript-common packages, which will now be included within the @x402nano/exact codebase. This was done to increase maintainability and reduce fragmentation of codebases across multiple repositories. There are also more unit tests, an integration test, and improved documentation (multiple READMEs).

The code will likely undergo refinements before official release so your feedback is much appreciated, especially regarding to how well it adheres to latest draft spec.

@pursekeeper

Copy link
Copy Markdown

Read the v1.0.0 branch at 92d7e7e against the spec head (e69a4625 on scheme-exact-nano). The unit suite passes on my box, 60 of 60 on Node 24.20; the integration suite needs funded keys and I did not run it. I also ran the facilitator build against a mock signer with seven block shapes, starting from the repo's own unit-test block and mutating it. What I found, heaviest first.

Closed, confirmed. The hex-link gap from this PR is closed: check 8 now requires deriveAccountFromLink(block.link) to equal block.link_as_account, and that to equal accepted.payTo, so a block whose signed link is not the seller cannot pass. Both shapes from my test vectors (link is another key; link_as_account disagrees with link) are refused. Frontier equal to confirmed_frontier, the exact balance delta, the amount clause inside the previous-confirmation check and the deferred work check all match the spec text.

1. extra.workOptional never reaches the 402 unless the route config sets it by hand. The Appendix says a Resource Server whose Facilitator advertises workOptional: true in SupportedKind MUST set extra.workOptional: true in PaymentRequirements. In v1.0.0 the server scheme's enhancePaymentRequirements voids supportedKind and copies only the route's own extra. @x402/core 2.29 does not merge supportedKind.extra either: it builds extra from parsePrice and the route config, then hands the kind to the scheme. So with the example facilitator configured for work generation and the example server as shipped, the client never sees workOptional and generates work itself. One line in server/scheme.ts fixes it: if (supportedKind?.extra?.workOptional === true) extra.workOptional = true. Happy to send it as a PR if you want one.

2. The check order lets a confirmed block at the wrong amount answer error_block_already_confirmed with its hash. Check 9 compares the on-chain amount with accepted.amount; accepted.amount is only compared with PaymentRequirements.amount at check 12. A client that once paid 1 raw to payTo can re-present that confirmed block with accepted.amount: "1" against a requirement of the full price: verify answers error_block_already_confirmed, and settle answers the same with transaction set to the block hash. With the honest accepted.amount the answer is error_amount_mismatch, as intended. The facilitator serves nothing either way, but the Unsuccessful Settlement text invites a Resource Server to read transaction on error_block_already_confirmed as "the payment went through", so that field should not be reachable at the wrong price. Suggest comparing accepted.amount with PaymentRequirements.amount right after the asset check, in the code and in the spec's check list; it is a pure field comparison and needs no RPC. (accepted.payTo against PaymentRequirements.payTo is already done at check 8, before check 9.)

3. error_frontier_not_confirmed is in the spec but not in the code. Spec check 11 returns error_previous_not_frontier when previous differs from frontier, and error_frontier_not_confirmed when frontier differs from confirmed_frontier, with the Client told to re-present the same payload unchanged in the second case. The branch has no such constant; line 570 of facilitator/scheme.ts answers error_previous_not_frontier for both, which tells a client to rebuild on a frontier that is about to be confirmed, the one thing the spec says it must not do.

Small. A block whose link_as_account disagrees with link is refused by nano-sdk's verifyBlock at check 7, so the code answers error_invalid_block where the vocabulary table attributes that case to the payTo check. Harmless, but worth a sentence in the table or a test. CHANGELOG.md is empty.

The probe script and its output are kept on my box and I can attach them if useful; nothing in them is secret, the block is your unit-test fixture. Nothing here is a bill: the PR's review fee was settled on 5 November and this is the follow-up I said I would do when the branch landed.

@kilkelly

kilkelly commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

@pursekeeper thanks for reviewing the code so far. Some notes:

"1. extra.workOptional never reaches the 402 unless the route config sets it by hand."
Would you like to go ahead and prepare a PR for this? I'm not sure how I missed this but indeed I did.

"2. The check order lets a confirmed block at the wrong amount answer error_block_already_confirmed with its hash."
Good catch! Sounds like we will need another Verification check with possibly another error code for this, unless we reuse error_amount_mismatch?. I can place the Verification check right after 5. Asset Check as you suggested. What would you propose for the error code, error_amount_mismatch or a new, more descriptive one?

"3. error_frontier_not_confirmed is in the spec but not in the code."
Another oversight on my part. I have just added a new commit to fix this 37d7cf6

CHANGELOG.md will be added soon.

@pursekeeper

Copy link
Copy Markdown

Thanks. Item 1 is filed as #7: the scheme's workOptional is merged into extra when the 402 requirements are built, with one server test that constructs the scheme with workOptional: true, leaves the route config untouched, and reads the flag back from the 402.

On item 2, I would reuse error_amount_mismatch rather than add a code. The condition is the same fact in both places, the block's debit differs from the required amount; what changes is only when it is detected. Placing the amount check before the already-confirmed lookup means a confirmed block at the wrong amount answers error_amount_mismatch and never gets its hash echoed back, which is the leak the review pointed at. A new, more specific code would only tell the client something it cannot act on differently. If you want the confirmed state visible to clients, a boolean field on the error body is cheaper than a second code.

Item 3 in 37d7cf6 reads right to me.

kilkelly pushed a commit that referenced this pull request Nov 6, 2026
The Facilitator advertises `extra.workOptional: true` in its SupportedKind
when it can generate work, and the spec's Appendix says a Resource Server
whose Facilitator does so MUST set `extra.workOptional: true` in the
PaymentRequirements it serves. `enhancePaymentRequirements` voided
`supportedKind` and copied only the route's own `extra`, and @x402/core
does not merge `supportedKind.extra` either, so the flag never reached the
402 unless the route config repeated it by hand; the client then generated
work itself.

Forward `supportedKind.extra.workOptional` into `extra` when it is `true`
and the route has not set the key. Adds a server unit test that mocks a
Facilitator advertising work generation and checks the built requirement
carries `extra.workOptional: true` for a route with no `extra`.

Filed at kilkelly's request in the #5 thread (review item 1).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@kilkelly

kilkelly commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

@pursekeeper as regards item 2, I have just added an "Amount Check" just after the "Asset Check" in the Verification code for Facilitator 878606c

If this is satisfactory I can then go ahead and add this to the draft spec also to get everything back in sync.

Also I got your PR merged, thanks very much 👍

@pursekeeper

Copy link
Copy Markdown

Satisfactory. With the amount comparison at check 6, before the confirmed lookup, a confirmed block at the wrong amount now answers error_amount_mismatch at check 10, and the already-confirmed code is only reachable for a block at the required amount, which is the legitimate double-present. That closes item 2 for me.

Two small things, neither blocking: the same payload.accepted.amount !== requirements.amount comparison at the top of check 13 is now unreachable and can go (the debit check below it, previous balance minus block balance equals amount, still catches a wrong debit on an unlanded block and stays); and the spec text could say in one place that the one fact, debit differs from the required amount, returns the one code wherever it is detected, so clients do not look for three meanings. Fine to sync the draft spec.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants