From 044f454fee662b755a1c014247ad74e049df1c99 Mon Sep 17 00:00:00 2001 From: RunTimeAdmin <248247024+RunTimeAdmin@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:13:36 -0600 Subject: [PATCH] Cancel the body of a 402 the x402 guard refuses sigvaraX402Fetch threw on a refused 402 without reading or cancelling the response it held, so a body cut off at the 64 KiB limit kept its connection open until the seller or a timeout closed it. Every refusal now cancels the body, a failed chain read included. A 402 that passes is left untouched. The evidence fetch in mcp.ts is unchanged: its 4 MiB read limit is what bounds the parse, and the same bytes beside an empty list cost as much to parse and pass any count of records. SDK tests, counted on 15 November: 383 pass and 9 skip of 392. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +-- docs/whitepaper.md | 2 +- packages/sdk/CHANGELOG.md | 10 +++++++ packages/sdk/src/x402.ts | 49 +++++++++++++++++++--------------- packages/sdk/test/x402.test.ts | 35 ++++++++++++++++++++++++ 5 files changed, 76 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index b049826..a443950 100644 --- a/README.md +++ b/README.md @@ -602,9 +602,9 @@ Everything below runs offline, with no deployed contracts, except three fork sui |---|---|---| | Contracts: unit, fuzz, E2E, upgrade, deploy-script, handover and 22 invariants | 799 | `forge test` | | Oracle | 1532 | `cd oracle && node --test` | -| SDK | 385 | `cd packages/sdk && npx vitest run` | +| SDK | 392 | `cd packages/sdk && npx vitest run` | -Counts are individual tests, so each of the 22 invariants counts once. The contracts were counted on 15 November 2026, the SDK on 15 November and the oracle on 15 November. Without a fork URL, 787 of the contract tests run and 12 skip. Run after `npm run build`, 376 of the SDK's 385 pass and 9 skip: the 8 integration tests, which need a live deployment, and one check that runs only in CI. Without a build, the 9 built-package tests skip too. Vitest strips types without checking them, so `npm run typecheck` in `packages/sdk` checks the tests against the SDK's types as well as the sources. [`scripts/mutation`](scripts/mutation/README.md) holds the harnesses that measure whether these tests would catch a deliberate break in the contracts or deploy scripts. +Counts are individual tests, so each of the 22 invariants counts once. The contracts were counted on 15 November 2026, the SDK on 15 November and the oracle on 15 November. Without a fork URL, 787 of the contract tests run and 12 skip. Run after `npm run build`, 383 of the SDK's 392 pass and 9 skip: the 8 integration tests, which need a live deployment, and one check that runs only in CI. Without a build, the 9 built-package tests skip too. Vitest strips types without checking them, so `npm run typecheck` in `packages/sdk` checks the tests against the SDK's types as well as the sources. [`scripts/mutation`](scripts/mutation/README.md) holds the harnesses that measure whether these tests would catch a deliberate break in the contracts or deploy scripts. Merges to `main` carry `[skip ci]`, to save CI minutes, so the push to `main` does not run the suites again. A change to code runs them on its pull request and merges only once every job there has passed; a docs-only change is checked locally with `node scripts/check-docs.mjs`. Each is checked against the `main` its branch started from, so two changes merged close together can still break `main`. That happened once, on 11 November 2026, and the next merge fixed it. The rule that every job must pass dates from 14 November 2026: before it, #281, #282 and #288 merged with their oracle job failing, and #283 and #297 fixed the tests that failed. On 13 November the oracle and SDK suites were run on `main` at `eaccb91` and passed. diff --git a/docs/whitepaper.md b/docs/whitepaper.md index 80d9bfc..eca3767 100644 --- a/docs/whitepaper.md +++ b/docs/whitepaper.md @@ -635,7 +635,7 @@ apply to a fresh deployment, not to the testnet. **Test coverage**, as of 15 November 2026: 799 contract tests across 36 Foundry test files including fuzz and invariant tests (the two slash drill suites fork Arc testnet themselves, and -the twelve in `SplitAuthorityFork` skip without `--fork-url`), 1532 oracle tests and 385 in the SDK (9 skip +the twelve in `SplitAuthorityFork` skip without `--fork-url`), 1532 oracle tests and 392 in the SDK (9 skip outside CI and without a live deployment; every test that runs passes). CI runs Foundry, the oracle and SDK suites, and Slither static analysis on every push, plus a documentation check that fails when the site states something the contracts do not. diff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.md index 5886d9f..a2709e8 100644 --- a/packages/sdk/CHANGELOG.md +++ b/packages/sdk/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## Unreleased + +### Fixed: a refused 402 kept its seller's connection open + +`sigvaraX402Fetch` reads a clone of a 402, and a 402 it refuses goes to nobody, so nothing read or cancelled the +body. A body cut off at the 64 KiB limit then held its connection until the seller or a timeout closed it: against a +local seller that kept sending, the socket was still open 3 seconds after the refusal. The guard now cancels the +body on every refusal, a failed chain read included, and that socket closed within a few milliseconds. A 402 that +passes is left for the client to read, as before. + ## 1.0.0-alpha.21 ### Fixed: `sigvara_verify_evidence` missed a finalized root a few payments behind a long list diff --git a/packages/sdk/src/x402.ts b/packages/sdk/src/x402.ts index 043b6f8..45cc457 100644 --- a/packages/sdk/src/x402.ts +++ b/packages/sdk/src/x402.ts @@ -115,27 +115,34 @@ export function sigvaraX402Fetch( return async (input, init) => { const res = await baseFetch(input, init); if (res.status !== 402) return res; - const offers = await x402OffersFrom(res); - if (!offers) throw new X402SellerRefused('This 402 names no offer that can be read, so its seller cannot be checked.', []); - if (offers.length > X402_MAX_OFFERS) { - throw new X402SellerRefused(`This 402 makes ${offers.length} offers, more than the ${X402_MAX_OFFERS} checked.`, []); - } - // Addresses compare without case, so one payee spelled two ways is checked once. - const byKey = new Map(); - for (const o of offers) { - const p = String(o.payTo ?? ''); - if (!byKey.has(p.toLowerCase())) byKey.set(p.toLowerCase(), p); - } - const payees = [...byKey.values()]; - const verdicts: TrustVerdict[] = []; - for (let i = 0; i < payees.length; i += CHECKS_AT_ONCE) { - verdicts.push(...await Promise.all(payees.slice(i, i + CHECKS_AT_ONCE).map((p) => trust.check(p)))); - } - const refused = verdicts.filter((v) => !v.ok); - if (refused.length > 0) { - const named = refused.map((v) => `${v.agent || '(no payTo)'}: ${v.reason}`).join('; '); - throw new X402SellerRefused(`Not paying this seller, which lacks standing. ${named}`, refused); + try { + const offers = await x402OffersFrom(res); + if (!offers) throw new X402SellerRefused('This 402 names no offer that can be read, so its seller cannot be checked.', []); + if (offers.length > X402_MAX_OFFERS) { + throw new X402SellerRefused(`This 402 makes ${offers.length} offers, more than the ${X402_MAX_OFFERS} checked.`, []); + } + // Addresses compare without case, so one payee spelled two ways is checked once. + const byKey = new Map(); + for (const o of offers) { + const p = String(o.payTo ?? ''); + if (!byKey.has(p.toLowerCase())) byKey.set(p.toLowerCase(), p); + } + const payees = [...byKey.values()]; + const verdicts: TrustVerdict[] = []; + for (let i = 0; i < payees.length; i += CHECKS_AT_ONCE) { + verdicts.push(...await Promise.all(payees.slice(i, i + CHECKS_AT_ONCE).map((p) => trust.check(p)))); + } + const refused = verdicts.filter((v) => !v.ok); + if (refused.length > 0) { + const named = refused.map((v) => `${v.agent || '(no payTo)'}: ${v.reason}`).join('; '); + throw new X402SellerRefused(`Not paying this seller, which lacks standing. ${named}`, refused); + } + return res; + } catch (err) { + // Nobody gets a refused 402, so nobody else will read or cancel its body. One cut off at the limit would hold + // its connection until the seller or a timeout closed it. A 402 that passes is left for the client to read. + await res.body?.cancel().catch(() => {}); + throw err; } - return res; }; } diff --git a/packages/sdk/test/x402.test.ts b/packages/sdk/test/x402.test.ts index 2904c49..2f84096 100644 --- a/packages/sdk/test/x402.test.ts +++ b/packages/sdk/test/x402.test.ts @@ -187,3 +187,38 @@ describe('x402 guard limits', () => { expect(most).toBeLessThanOrEqual(4); }); }); + +describe('x402 guard and the seller\'s connection', () => { + /** A 402 whose own body counts its cancels. The guard reads a clone, and the clone gets the real body. */ + function counted(parts: Parameters[0]) { + const real = required(parts); + const cancel = vi.fn(async () => {}); + const res = { status: 402, headers: real.headers, clone: () => real.clone(), body: { cancel } } as unknown as Response; + return { res, cancel }; + } + + const many = Array.from({ length: X402_MAX_OFFERS + 1 }, (_, i) => offer(`0x${(i + 1).toString(16).padStart(40, '0')}`)); + const down = { check: vi.fn(async (): Promise => { throw new Error('could not read the chain'); }) }; + const refusals: [string, Parameters[0], { check(agent: string): Promise }][] = [ + ['a 402 it cannot read', { rawBody: 'pay up' }, trustOnly(GOOD)], + ['a body over the limit', { rawBody: JSON.stringify({ accepts: [offer(GOOD)], pad: 'x'.repeat(X402_MAX_BYTES) }) }, trustOnly(GOOD)], + ['a header over the limit', { rawHeader: encode({ accepts: [offer(GOOD)], pad: 'x'.repeat(X402_MAX_BYTES) }) }, trustOnly(GOOD)], + ['too many offers', { body: { accepts: many } }, trustOnly()], + ['a seller without standing', { body: { accepts: [offer(BAD)] } }, trustOnly(GOOD)], + ['because the chain cannot be read', { body: { accepts: [offer(GOOD)] } }, down], + ]; + + // Nobody reads a refused 402, so the guard has to release its body: one cut off at the limit holds its connection + // until the seller or a timeout closes it. + it.each(refusals)('cancels the body once when it refuses %s', async (_why, parts, trust) => { + const { res, cancel } = counted(parts); + await expect(guarded(res, trust)).rejects.toThrow(); + expect(cancel).toHaveBeenCalledTimes(1); + }); + + it('leaves the body of a 402 it passes for the client to read', async () => { + const { res, cancel } = counted({ body: { accepts: [offer(GOOD)] } }); + expect(await guarded(res, trustOnly(GOOD))).toBe(res); + expect(cancel).not.toHaveBeenCalled(); + }); +});