From e7a76662a38e59bbc575879bdb07450978360162 Mon Sep 17 00:00:00 2001 From: Revinand Date: Tue, 17 Nov 2026 14:37:12 +0100 Subject: [PATCH 01/14] test: capture 2.7.2 goldens for the x402 challenge, facilitator payload, well-known and doctor --- tests/integration/baseline-goldens.test.ts | 511 ++++++++++++++++++ .../goldens/2.7.2/doctor-multi.json | 119 ++++ .../goldens/2.7.2/doctor-single.json | 114 ++++ .../goldens/2.7.2/facilitator-settle.json | 43 ++ .../goldens/2.7.2/facilitator-verify.json | 43 ++ .../goldens/2.7.2/well-known-multi.json | 310 +++++++++++ .../goldens/2.7.2/well-known-single.json | 287 ++++++++++ .../goldens/2.7.2/x402-challenge-multi.json | 36 ++ .../goldens/2.7.2/x402-challenge-single.json | 23 + 9 files changed, 1486 insertions(+) create mode 100644 tests/integration/baseline-goldens.test.ts create mode 100644 tests/integration/goldens/2.7.2/doctor-multi.json create mode 100644 tests/integration/goldens/2.7.2/doctor-single.json create mode 100644 tests/integration/goldens/2.7.2/facilitator-settle.json create mode 100644 tests/integration/goldens/2.7.2/facilitator-verify.json create mode 100644 tests/integration/goldens/2.7.2/well-known-multi.json create mode 100644 tests/integration/goldens/2.7.2/well-known-single.json create mode 100644 tests/integration/goldens/2.7.2/x402-challenge-multi.json create mode 100644 tests/integration/goldens/2.7.2/x402-challenge-single.json diff --git a/tests/integration/baseline-goldens.test.ts b/tests/integration/baseline-goldens.test.ts new file mode 100644 index 0000000..3b1251a --- /dev/null +++ b/tests/integration/baseline-goldens.test.ts @@ -0,0 +1,511 @@ +/** + * 2.7.2 baseline for x402 challenges over HTTP, MCP and A2A, remote facilitator + * request bodies, the well-known document and a healthy `doctor --json` report. + * + * Keep challenge and facilitator request bytes unchanged when 2.8.0 options are + * disabled. If a change alters a golden, update its file in the same commit and + * explain why. + * + * The gateway uses the provider and adapter setup from `runGateway`. One loopback + * server fakes the JSON-RPC nodes, remote facilitator and merchant backend. + */ +import { createServer, type IncomingMessage, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'; +import { privateKeyToAccount } from 'viem/accounts'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { createAp2AuthorizationProvider } from '../../src/authorization/ap2'; +import { printDoctorReport, runDoctor } from '../../src/cli/commands/doctor'; +import { type GatewayConfig, parseConfig } from '../../src/config'; +import { NOOP_LOGGER, PAYMENT_HEADER, PAYMENT_REQUIRED_HEADER } from '../../src/core'; +import { createGateway } from '../../src/gateway'; +import { createConfiguredPaymentProviders } from '../../src/gateway/payment-providers'; +import { createPaymentProof } from '../../src/payments/x402/client'; +import { createA2aAdapter } from '../../src/protocols/a2a'; +import { A2A_X402_EXTENSION_URI } from '../../src/protocols/a2a/x402-extension'; +import { createAcpAdapter } from '../../src/protocols/acp'; +import { createMcpAdapter } from '../../src/protocols/mcp'; +import { createSqliteReceiptStore } from '../../src/storage/receipts'; +import { PACKAGE_VERSION } from '../../src/version'; +import { createParties } from '../unit/authorization-ap2/fixtures'; +import { createCapturingIo } from '../unit/cli/fixtures'; + +process.env['NODE_ENV'] = 'test'; + +const BASE_SEPOLIA = 'eip155:84532'; +const ARBITRUM_SEPOLIA = 'eip155:421614'; +const PAY_TO = '0x1111111111111111111111111111111111111111'; +// Anvil account 2. LOCAL DEVELOPMENT ONLY - DO NOT FUND +const BUYER_KEY = '0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a' as const; +const BUYER = privateKeyToAccount(BUYER_KEY).address; +// A fixed nonce and validity window keep the signature and payment payload deterministic +const NONCE = `0x${'42'.repeat(32)}` as const; +const VALID_BEFORE = 4_102_444_800; +const TX = `0x${'ab'.repeat(32)}`; +const GOLDEN = './goldens/2.7.2'; + +// Capture raw facilitator request bodies by route +const facilitatorBodies: Record = { verify: [], settle: [] }; +let upstream: Server; +let upstreamUrl = ''; + +async function readBody(req: IncomingMessage): Promise { + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(chunk as Buffer); + return Buffer.concat(chunks).toString('utf8'); +} + +// Use the chain ID from the RPC path and report code at any address. +// Return 6 for eth_call to satisfy the token decimals health check. +function rpcResult(chainId: number, method: string): unknown { + if (method === 'eth_chainId') return `0x${chainId.toString(16)}`; + if (method === 'eth_getCode') return '0x6080'; + if (method === 'eth_call') return `0x${'6'.padStart(64, '0')}`; + return undefined; +} + +function startUpstream(): Promise { + upstream = createServer(async (req, res) => { + const body = await readBody(req); + const path = req.url ?? ''; + const reply = (value: unknown) => { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify(value)); + }; + const rpc = /^\/rpc\/(\d+)$/.exec(path); + if (rpc) { + const { id, method } = JSON.parse(body) as { id: number; method: string }; + const result = rpcResult(Number(rpc[1]), method); + reply( + result === undefined + ? { jsonrpc: '2.0', id, error: { code: -32601, message: `no ${method}` } } + : { jsonrpc: '2.0', id, result }, + ); + return; + } + if (path === '/facilitator/supported') { + reply({ + kinds: [BASE_SEPOLIA, ARBITRUM_SEPOLIA].map((network) => ({ + x402Version: 2, + scheme: 'exact', + network, + })), + extensions: [], + signers: {}, + }); + return; + } + if (path === '/facilitator/verify') { + facilitatorBodies['verify']?.push(body); + reply({ isValid: true, payer: BUYER }); + return; + } + if (path === '/facilitator/settle') { + facilitatorBodies['settle']?.push(body); + reply({ success: true, transaction: TX, network: BASE_SEPOLIA, payer: BUYER }); + return; + } + if (path.startsWith('/backend/')) { + reply({ ok: true }); + return; + } + res.writeHead(404).end(); + }); + return new Promise((resolve) => + upstream.listen(0, '127.0.0.1', () => { + upstreamUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`; + resolve(); + }), + ); +} + +const pathInput = { + type: 'object', + properties: { checkout_session_id: { type: 'string' } }, + required: ['checkout_session_id'], + additionalProperties: false, +}; +const bodyInput = { type: 'object', additionalProperties: true }; + +// Define a free checkout operation exposed only through ACP +function acpResource(method: string, path: string, withPath: boolean, withBody: boolean) { + return { + name: `ACP ${method} ${path}`, + input: { + type: 'object', + properties: { + ...(withPath ? { path: pathInput } : {}), + ...(withBody ? { body: bodyInput } : {}), + }, + required: withPath ? ['path'] : ['body'], + additionalProperties: false, + }, + backend: { + type: 'http', + method, + url: `${upstreamUrl}/backend${path}`, + inputBindings: { + ...(withPath ? { path: 'path' } : {}), + ...(withBody ? { body: 'body' } : {}), + }, + }, + pricing: { type: 'free' }, + expose: ['acp'], + }; +} + +// Configure HTTP, MCP, A2A and ACP with x402, MPP and AP2 using the 2.7.2 config format +async function goldenConfig(x402: Record): Promise { + const parties = await createParties(); + const session = '/checkout_sessions/{checkout_session_id}'; + return parseConfig( + { + version: 1, + merchant: { + id: 'golden-store', + name: 'Golden Store', + publicBaseUrl: 'https://gateway.example', + }, + server: { port: 8080, host: '127.0.0.1' }, + storage: { receipts: { driver: 'sqlite', path: ':memory:' } }, + protocols: { + http: { enabled: true }, + mcp: { enabled: true, mountPath: '/mcp' }, + a2a: { enabled: true, mountPath: '/a2a' }, + acp: { + enabled: true, + mountPath: '/acp', + auth: { type: 'bearer', token: 'golden-acp-token' }, + idempotency: { retentionHours: 24 }, + checkout: { + operations: { + createCheckoutSession: 'acp_create', + updateCheckoutSession: 'acp_update', + getCheckoutSession: 'acp_get', + completeCheckoutSession: 'acp_complete', + cancelCheckoutSession: 'acp_cancel', + }, + }, + }, + }, + resources: { + market_report: { + name: 'Market Report', + description: 'Latest market analysis for a symbol.', + input: { + type: 'object', + properties: { symbol: { type: 'string' } }, + required: ['symbol'], + additionalProperties: false, + }, + backend: { type: 'http', method: 'GET', url: `${upstreamUrl}/backend/report` }, + pricing: { type: 'fixed', amount: '0.01', currency: 'USDC' }, + expose: ['http', 'mcp', 'a2a'], + payments: ['x402'], + }, + // Require AP2 on a resource so doctor doesn't warn that AP2 is unused + ap2_report: { + name: 'Mandated Report', + input: { type: 'object', properties: {}, additionalProperties: false }, + backend: { type: 'http', method: 'GET', url: `${upstreamUrl}/backend/ap2-report` }, + pricing: { type: 'fixed', amount: '0.02', currency: 'USDC' }, + expose: ['http'], + payments: ['x402'], + authorization: { required: ['ap2'] }, + }, + mpp_report: { + name: 'MPP Report', + input: { type: 'object', properties: {}, additionalProperties: false }, + backend: { type: 'http', method: 'GET', url: `${upstreamUrl}/backend/mpp-report` }, + pricing: { type: 'fixed', amount: '0.01', currency: 'USDC' }, + expose: ['http'], + payments: ['mpp'], + }, + acp_create: acpResource('POST', '/checkout_sessions', false, true), + acp_update: acpResource('POST', session, true, true), + acp_get: acpResource('GET', session, true, false), + acp_complete: acpResource('POST', `${session}/complete`, true, true), + acp_cancel: acpResource('POST', `${session}/cancel`, true, true), + }, + payments: { + x402: { + enabled: true, + facilitator: { mode: 'remote', url: `${upstreamUrl}/facilitator` }, + maxTimeoutSeconds: 120, + ...x402, + }, + mpp: { + enabled: true, + network: BASE_SEPOLIA, + rpcUrl: `${upstreamUrl}/rpc/84532`, + asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', + assetName: 'USDC', + assetVersion: '2', + recipient: PAY_TO, + realm: 'gateway.example', + challengeSecret: 'golden-mpp-challenge-secret-'.padEnd(32, 'x'), + facilitator: { mode: 'remote', url: `${upstreamUrl}/facilitator` }, + }, + }, + authorization: { + ap2: { + enabled: true, + specVersion: '0.2.0', + mode: 'direct', + trust: { + mandateIssuers: parties.mandateIssuers, + checkoutIssuers: parties.checkoutIssuers, + }, + }, + }, + }, + {}, + ); +} + +function singleOffer(): Record { + return { network: BASE_SEPOLIA, rpcUrl: `${upstreamUrl}/rpc/84532`, payTo: PAY_TO }; +} + +function multiOffer(): Record { + return { + options: [ + { network: BASE_SEPOLIA, payTo: PAY_TO }, + { network: ARBITRUM_SEPOLIA, payTo: PAY_TO, assetTransferMethod: 'permit2' }, + ], + networks: { + [BASE_SEPOLIA]: { rpcUrl: `${upstreamUrl}/rpc/84532` }, + [ARBITRUM_SEPOLIA]: { rpcUrl: `${upstreamUrl}/rpc/421614` }, + }, + }; +} + +interface Running { + readonly url: string; + readonly config: GatewayConfig; + close(): Promise; +} + +// Wire the store, providers and adapters as in `runGateway`, without signal handlers +async function startGateway(config: GatewayConfig): Promise { + const store = createSqliteReceiptStore({ path: ':memory:' }); + await store.init(); + const paymentProviders = await createConfiguredPaymentProviders(config.payments, NOOP_LOGGER); + const ap2 = config.authorization?.ap2; + const authorizationProviders = ap2?.enabled + ? [createAp2AuthorizationProvider({ config: ap2, logger: NOOP_LOGGER, store })] + : []; + const { mcp, a2a, acp } = config.protocols; + if (!acp.enabled) throw new Error('the golden config enables ACP'); + const gateway = await createGateway({ + config: { ...config, server: { ...config.server, port: 0 } }, + store, + paymentProviders, + authorizationProviders, + protocolAdapters: [ + createMcpAdapter({ mountPath: mcp.mountPath }), + createA2aAdapter({ mountPath: a2a.mountPath, agentName: config.merchant.name, store }), + createAcpAdapter({ + mountPath: acp.mountPath, + token: acp.auth.token, + operations: acp.checkout.operations, + idempotency: acp.idempotency, + store, + }), + ], + logger: NOOP_LOGGER, + }); + const { url } = await gateway.listen(); + return { + url, + config, + async close() { + await gateway.close(); + for (const provider of authorizationProviders) provider.close(); + await store.close(); + }, + }; +} + +// Require the captured bytes to match compact or two-space-indented JSON. +// Normalize loopback URLs, the package version and ISO timestamps for stable snapshots. +function golden(raw: string, gatewayUrl: string): string { + const parsed: unknown = JSON.parse(raw); + const pretty = JSON.stringify(parsed, null, 2); + expect([JSON.stringify(parsed), pretty]).toContain(raw); + return `${pretty}\n` + .replaceAll(upstreamUrl, 'http://upstream.invalid') + .replaceAll(gatewayUrl, 'http://gateway.invalid') + .replaceAll(PACKAGE_VERSION, '') + .replaceAll(/"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z"/g, '""'); +} + +// Snapshot discovery and require a healthy `doctor --json` report from the gateway +async function expectDiscoveryGoldens(running: Running, suffix: string): Promise { + const res = await fetch(`${running.url}/.well-known/agent-commerce`); + expect(res.status).toBe(200); + await expect(golden(await res.text(), running.url)).toMatchFileSnapshot( + `${GOLDEN}/well-known-${suffix}.json`, + ); + + const report = await runDoctor( + { gatewayUrl: running.url }, + { + loadConfig: async () => running.config, + fillEnvFromManifest: (env) => ({ env, filled: [], manifestFound: false }), + hasChainDeployScript: () => false, + }, + ); + expect(report.exitCode).toBe(0); + expect(report.score.passed).toBe(report.score.total); + const io = createCapturingIo(); + printDoctorReport(report, io, true); + await expect(golden(io.out.join('\n'), running.url)).toMatchFileSnapshot( + `${GOLDEN}/doctor-${suffix}.json`, + ); +} + +async function challengeHeader(url: string): Promise { + const res = await fetch(`${url}/api/resources/market_report/invoke`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ symbol: 'ETH' }), + }); + expect(res.status).toBe(402); + const header = res.headers.get(PAYMENT_REQUIRED_HEADER); + if (header === null) throw new Error('no PAYMENT-REQUIRED header'); + return Buffer.from(header, 'base64').toString('utf8'); +} + +beforeAll(startUpstream); +afterAll(() => new Promise((resolve) => upstream.close(() => resolve()))); + +describe('2.7.2 goldens: single x402 offer, every protocol, MPP and AP2', () => { + let running: Running; + + beforeAll(async () => { + running = await startGateway(await goldenConfig(singleOffer())); + }); + afterAll(() => running?.close()); + + it('the challenge in PAYMENT-REQUIRED, and the same document on MCP and A2A', async () => { + const raw = await challengeHeader(running.url); + await expect(golden(raw, running.url)).toMatchFileSnapshot( + `${GOLDEN}/x402-challenge-single.json`, + ); + const envelope = JSON.parse(raw) as Record; + + const client = new Client({ name: 'golden-client', version: '0.0.0-test' }); + await client.connect( + new StreamableHTTPClientTransport(new URL(`${running.url}/mcp`)) as Transport, + ); + const mcp = (await client.callTool({ + name: 'market_report', + arguments: { symbol: 'ETH' }, + })) as { isError?: boolean; structuredContent?: Record }; + await client.close(); + expect(mcp.isError).toBe(true); + for (const key of Object.keys(envelope)) { + expect(mcp.structuredContent?.[key]).toEqual(envelope[key]); + } + + const a2a = await fetch(`${running.url}/a2a`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'a2a-version': '1.0', + 'a2a-extensions': A2A_X402_EXTENSION_URI, + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 'golden', + method: 'SendMessage', + params: { + message: { + role: 'ROLE_USER', + messageId: 'msg-golden', + parts: [ + { + data: { resource: 'market_report', input: { symbol: 'ETH' } }, + mediaType: 'application/json', + }, + ], + }, + }, + }), + }); + const { task } = ( + (await a2a.json()) as { + result: { task: { status: { message: { metadata: Record } } } }; + } + ).result; + expect(task.status.message.metadata['x402.payment.required']).toEqual(envelope); + }); + + it('the verify and settle bodies a remote facilitator receives', async () => { + const envelope = JSON.parse(await challengeHeader(running.url)) as { + resource: unknown; + accepts: Record[]; + }; + const offer = envelope.accepts[0]; + if (offer === undefined) throw new Error('no offer'); + // Include the buyer's resource echo and extension to check that the gateway + // strips both before forwarding the payment payload to the facilitator + const signed = await createPaymentProof({ + buyerPrivateKey: BUYER_KEY, + accepts: offer, + extensions: { bazaar: { info: { input: { type: 'http', method: 'GET' } } } }, + overrides: { nonce: NONCE, validBefore: VALID_BEFORE }, + }); + const proof = Buffer.from( + JSON.stringify({ + resource: envelope.resource, + ...JSON.parse(Buffer.from(signed, 'base64').toString('utf8')), + }), + ).toString('base64'); + facilitatorBodies['verify'] = []; + facilitatorBodies['settle'] = []; + + const paid = await fetch(`${running.url}/api/resources/market_report/invoke`, { + method: 'POST', + headers: { 'content-type': 'application/json', [PAYMENT_HEADER]: proof }, + body: JSON.stringify({ symbol: 'ETH' }), + }); + expect(paid.status).toBe(200); + + const [verify] = facilitatorBodies['verify'] ?? []; + const [settle] = facilitatorBodies['settle'] ?? []; + expect(facilitatorBodies['verify']).toHaveLength(1); + expect(facilitatorBodies['settle']).toHaveLength(1); + await expect(golden(verify as string, running.url)).toMatchFileSnapshot( + `${GOLDEN}/facilitator-verify.json`, + ); + await expect(golden(settle as string, running.url)).toMatchFileSnapshot( + `${GOLDEN}/facilitator-settle.json`, + ); + }); + + it('the well-known document and a healthy doctor --json report', () => + expectDiscoveryGoldens(running, 'single')); +}); + +describe('2.7.2 goldens: two x402 offers', () => { + let running: Running; + + beforeAll(async () => { + running = await startGateway(await goldenConfig(multiOffer())); + }); + afterAll(() => running?.close()); + + it('the challenge in PAYMENT-REQUIRED', async () => { + const raw = await challengeHeader(running.url); + await expect(golden(raw, running.url)).toMatchFileSnapshot( + `${GOLDEN}/x402-challenge-multi.json`, + ); + }); + + it('the well-known document and a healthy doctor --json report', () => + expectDiscoveryGoldens(running, 'multi')); +}); diff --git a/tests/integration/goldens/2.7.2/doctor-multi.json b/tests/integration/goldens/2.7.2/doctor-multi.json new file mode 100644 index 0000000..564c6e7 --- /dev/null +++ b/tests/integration/goldens/2.7.2/doctor-multi.json @@ -0,0 +1,119 @@ +{ + "checks": [ + { + "name": "Config", + "status": "PASS", + "detail": "valid: 8 resource(s), merchant \"Golden Store\"" + }, + { + "name": "Gateway", + "status": "PASS", + "detail": "healthy and ready at http://gateway.invalid" + }, + { + "name": "Backend", + "status": "PASS", + "detail": "7/7 backend host(s) reachable" + }, + { + "name": "Protocols", + "status": "PASS", + "detail": "http=on mcp=on (/mcp) a2a=on (/a2a) acp=on (/acp)" + }, + { + "name": "A2A", + "status": "PASS", + "detail": "experimental · spec 1.0.1 · protocol 1.0 · binding JSONRPC · mount /a2a · card /.well-known/agent-card.json" + }, + { + "name": "A2A unsupported", + "status": "INFO", + "detail": "SendStreamingMessage, GetTask, ListTasks, CancelTask, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, long-running task persistence, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, x402 extension payments across gateway instances" + }, + { + "name": "ACP", + "status": "PASS", + "detail": "experimental · spec 2026-04-17 · API-Version 2026-04-17 · service checkout · mount /acp · discovery /.well-known/acp.json" + }, + { + "name": "ACP auth", + "status": "PASS", + "detail": "bearer token configured (16 characters, not shown)" + }, + { + "name": "ACP idempotency", + "status": "PASS", + "detail": "claims in the receipt database (retention 24h)" + }, + { + "name": "ACP checkout mapping", + "status": "PASS", + "detail": "5 operations mapped to free acp-exposed resources (acp_create, acp_update, acp_get, acp_complete, acp_cancel)" + }, + { + "name": "ACP unsupported", + "status": "INFO", + "detail": "carts service, feed service, standalone orders service, delegate_payment, delegate_authentication, ACP MCP transport binding, webhooks, outbound merchant-to-agent delivery, ACP client role, Signature header verification, Timestamp replay-window verification, discount extension, general ACP extension framework, multiple ACP API versions, seller-backed payment handler integration" + }, + { + "name": "AP2", + "status": "PASS", + "detail": "experimental · spec 0.2.0 · mode direct · mandate.checkout.1 · profile agent-commerce/ap2/checkout/v1 · clock skew 60s · mandate aud optional · mandate exp optional" + }, + { + "name": "AP2 trust", + "status": "PASS", + "detail": "mandate issuers: https://trusted-surface.example (1 key) · checkout issuers: https://merchant.example (1 key)" + }, + { + "name": "AP2 replay store", + "status": "PASS", + "detail": "mandate holds in the receipt database" + }, + { + "name": "AP2 resources", + "status": "PASS", + "detail": "ap2_report" + }, + { + "name": "AP2 unsupported", + "status": "INFO", + "detail": "autonomous mode, open checkout mandates (mandate.checkout.open.1), payment mandates (mandate.payment.1), spending constraint evaluation, cnf-bound agent keys, user credential delegation (OpenID4VP), delegation chains and key-binding JWTs, JWKS and any key discovery by URL (jku, x5u), issuer metadata fetching, key rotation without a config change, signature algorithms other than ES256, digest algorithms other than sha-256, mandate issuance, checkout receipts, AP2 over the ACP checkout adapter" + }, + { + "name": "Payments", + "status": "PASS", + "detail": "x402 v2 (scheme=exact) enabled - TESTNET, 2 options: Base Sepolia (eip155:84532) to 0x1111…1111; Arbitrum Sepolia (eip155:421614) to 0x1111…1111, facilitator=remote (auth=none), paymentFlow=authorization" + }, + { + "name": "Payments (offers)", + "status": "PASS", + "detail": "2 offer(s) pass their health checks" + }, + { + "name": "Payments (MPP)", + "status": "PASS", + "detail": "MPP charge/evm/authorization enabled - TESTNET on Base Sepolia (eip155:84532), asset=USDC 0x036C…CF7e, recipient=0x1111…1111, facilitator=remote (auth=none), paymentFlow=upfront, spec draft-httpauth-payment-01@806fdb8, mppx 0.13.1" + }, + { + "name": "Storage", + "status": "PASS", + "detail": "sqlite schema v5 writable; receipts=0" + }, + { + "name": "Transactions", + "status": "PASS", + "detail": "none unresolved" + }, + { + "name": "Protocol versions", + "status": "PASS", + "detail": "reported by gateway /.well-known/agent-commerce" + } + ], + "score": { + "passed": 19, + "total": 19 + }, + "exitCode": 0 +} diff --git a/tests/integration/goldens/2.7.2/doctor-single.json b/tests/integration/goldens/2.7.2/doctor-single.json new file mode 100644 index 0000000..2901a3d --- /dev/null +++ b/tests/integration/goldens/2.7.2/doctor-single.json @@ -0,0 +1,114 @@ +{ + "checks": [ + { + "name": "Config", + "status": "PASS", + "detail": "valid: 8 resource(s), merchant \"Golden Store\"" + }, + { + "name": "Gateway", + "status": "PASS", + "detail": "healthy and ready at http://gateway.invalid" + }, + { + "name": "Backend", + "status": "PASS", + "detail": "7/7 backend host(s) reachable" + }, + { + "name": "Protocols", + "status": "PASS", + "detail": "http=on mcp=on (/mcp) a2a=on (/a2a) acp=on (/acp)" + }, + { + "name": "A2A", + "status": "PASS", + "detail": "experimental · spec 1.0.1 · protocol 1.0 · binding JSONRPC · mount /a2a · card /.well-known/agent-card.json" + }, + { + "name": "A2A unsupported", + "status": "INFO", + "detail": "SendStreamingMessage, GetTask, ListTasks, CancelTask, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, long-running task persistence, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, x402 extension payments across gateway instances" + }, + { + "name": "ACP", + "status": "PASS", + "detail": "experimental · spec 2026-04-17 · API-Version 2026-04-17 · service checkout · mount /acp · discovery /.well-known/acp.json" + }, + { + "name": "ACP auth", + "status": "PASS", + "detail": "bearer token configured (16 characters, not shown)" + }, + { + "name": "ACP idempotency", + "status": "PASS", + "detail": "claims in the receipt database (retention 24h)" + }, + { + "name": "ACP checkout mapping", + "status": "PASS", + "detail": "5 operations mapped to free acp-exposed resources (acp_create, acp_update, acp_get, acp_complete, acp_cancel)" + }, + { + "name": "ACP unsupported", + "status": "INFO", + "detail": "carts service, feed service, standalone orders service, delegate_payment, delegate_authentication, ACP MCP transport binding, webhooks, outbound merchant-to-agent delivery, ACP client role, Signature header verification, Timestamp replay-window verification, discount extension, general ACP extension framework, multiple ACP API versions, seller-backed payment handler integration" + }, + { + "name": "AP2", + "status": "PASS", + "detail": "experimental · spec 0.2.0 · mode direct · mandate.checkout.1 · profile agent-commerce/ap2/checkout/v1 · clock skew 60s · mandate aud optional · mandate exp optional" + }, + { + "name": "AP2 trust", + "status": "PASS", + "detail": "mandate issuers: https://trusted-surface.example (1 key) · checkout issuers: https://merchant.example (1 key)" + }, + { + "name": "AP2 replay store", + "status": "PASS", + "detail": "mandate holds in the receipt database" + }, + { + "name": "AP2 resources", + "status": "PASS", + "detail": "ap2_report" + }, + { + "name": "AP2 unsupported", + "status": "INFO", + "detail": "autonomous mode, open checkout mandates (mandate.checkout.open.1), payment mandates (mandate.payment.1), spending constraint evaluation, cnf-bound agent keys, user credential delegation (OpenID4VP), delegation chains and key-binding JWTs, JWKS and any key discovery by URL (jku, x5u), issuer metadata fetching, key rotation without a config change, signature algorithms other than ES256, digest algorithms other than sha-256, mandate issuance, checkout receipts, AP2 over the ACP checkout adapter" + }, + { + "name": "Payments", + "status": "PASS", + "detail": "x402 v2 (scheme=exact) enabled - TESTNET on Base Sepolia (eip155:84532), destination=0x1111…1111, facilitator=remote (auth=none), paymentFlow=authorization" + }, + { + "name": "Payments (MPP)", + "status": "PASS", + "detail": "MPP charge/evm/authorization enabled - TESTNET on Base Sepolia (eip155:84532), asset=USDC 0x036C…CF7e, recipient=0x1111…1111, facilitator=remote (auth=none), paymentFlow=upfront, spec draft-httpauth-payment-01@806fdb8, mppx 0.13.1" + }, + { + "name": "Storage", + "status": "PASS", + "detail": "sqlite schema v5 writable; receipts=0" + }, + { + "name": "Transactions", + "status": "PASS", + "detail": "none unresolved" + }, + { + "name": "Protocol versions", + "status": "PASS", + "detail": "reported by gateway /.well-known/agent-commerce" + } + ], + "score": { + "passed": 18, + "total": 18 + }, + "exitCode": 0 +} diff --git a/tests/integration/goldens/2.7.2/facilitator-settle.json b/tests/integration/goldens/2.7.2/facilitator-settle.json new file mode 100644 index 0000000..110c5af --- /dev/null +++ b/tests/integration/goldens/2.7.2/facilitator-settle.json @@ -0,0 +1,43 @@ +{ + "x402Version": 2, + "paymentPayload": { + "x402Version": 2, + "accepted": { + "scheme": "exact", + "network": "eip155:84532", + "amount": "10000", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "payTo": "0x1111111111111111111111111111111111111111", + "maxTimeoutSeconds": 120, + "extra": { + "name": "USDC", + "version": "2", + "assetTransferMethod": "eip3009" + } + }, + "payload": { + "signature": "0x9e9124b0cb5f5b7037329a7cad609711ab9658f109b68d5854fb3486884ee5ad6eb4e4551632800337f21ef4d29752fe5016eda7d3376438a1c27b4da5a261091c", + "authorization": { + "from": "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC", + "to": "0x1111111111111111111111111111111111111111", + "value": "10000", + "validAfter": "0", + "validBefore": "4102444800", + "nonce": "0x4242424242424242424242424242424242424242424242424242424242424242" + } + } + }, + "paymentRequirements": { + "scheme": "exact", + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "amount": "10000", + "payTo": "0x1111111111111111111111111111111111111111", + "maxTimeoutSeconds": 120, + "extra": { + "name": "USDC", + "version": "2", + "assetTransferMethod": "eip3009" + } + } +} diff --git a/tests/integration/goldens/2.7.2/facilitator-verify.json b/tests/integration/goldens/2.7.2/facilitator-verify.json new file mode 100644 index 0000000..110c5af --- /dev/null +++ b/tests/integration/goldens/2.7.2/facilitator-verify.json @@ -0,0 +1,43 @@ +{ + "x402Version": 2, + "paymentPayload": { + "x402Version": 2, + "accepted": { + "scheme": "exact", + "network": "eip155:84532", + "amount": "10000", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "payTo": "0x1111111111111111111111111111111111111111", + "maxTimeoutSeconds": 120, + "extra": { + "name": "USDC", + "version": "2", + "assetTransferMethod": "eip3009" + } + }, + "payload": { + "signature": "0x9e9124b0cb5f5b7037329a7cad609711ab9658f109b68d5854fb3486884ee5ad6eb4e4551632800337f21ef4d29752fe5016eda7d3376438a1c27b4da5a261091c", + "authorization": { + "from": "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC", + "to": "0x1111111111111111111111111111111111111111", + "value": "10000", + "validAfter": "0", + "validBefore": "4102444800", + "nonce": "0x4242424242424242424242424242424242424242424242424242424242424242" + } + } + }, + "paymentRequirements": { + "scheme": "exact", + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "amount": "10000", + "payTo": "0x1111111111111111111111111111111111111111", + "maxTimeoutSeconds": 120, + "extra": { + "name": "USDC", + "version": "2", + "assetTransferMethod": "eip3009" + } + } +} diff --git a/tests/integration/goldens/2.7.2/well-known-multi.json b/tests/integration/goldens/2.7.2/well-known-multi.json new file mode 100644 index 0000000..9a3415e --- /dev/null +++ b/tests/integration/goldens/2.7.2/well-known-multi.json @@ -0,0 +1,310 @@ +{ + "gateway": { + "implementationVersion": "", + "supportedSpec": "agent-commerce/v1.0.0" + }, + "merchant": { + "id": "golden-store", + "name": "Golden Store", + "publicBaseUrl": "https://gateway.example" + }, + "protocols": { + "http": { + "enabled": true + }, + "mcp": { + "enabled": true, + "mountPath": "/mcp" + }, + "a2a": { + "enabled": true, + "mountPath": "/a2a" + }, + "acp": { + "enabled": true, + "mountPath": "/acp" + } + }, + "adapters": [ + { + "name": "mcp", + "kind": "protocol", + "implementationVersion": "", + "supportedSpec": "2026-07-28, 2025-11-25", + "capabilities": [ + "tools/list", + "tools/call" + ], + "status": "stable", + "unsupported": [ + "resources", + "prompts", + "sampling", + "completions", + "elicitation", + "roots", + "logging", + "notifications/tools/list_changed", + "tasks", + "dns-rebinding-protection", + "authorization", + "sessions", + "subscriptions", + "pagination", + "HTTP+SSE transport", + "MPP payment-required as JSON-RPC error -32042", + "MPP verification failure as JSON-RPC error -32043" + ], + "health": { + "status": "pass", + "checkedAt": "" + } + }, + { + "name": "a2a", + "kind": "protocol", + "implementationVersion": "", + "supportedSpec": "1.0.1", + "capabilities": [ + "agent-card", + "jsonrpc", + "SendMessage", + "x402-extension" + ], + "status": "experimental", + "unsupported": [ + "SendStreamingMessage", + "GetTask", + "ListTasks", + "CancelTask", + "SubscribeToTask", + "CreateTaskPushNotificationConfig", + "GetTaskPushNotificationConfig", + "ListTaskPushNotificationConfigs", + "DeleteTaskPushNotificationConfig", + "GetExtendedAgentCard", + "HTTP+JSON/REST binding", + "gRPC binding", + "SSE", + "long-running task persistence", + "task resumption other than an x402 extension payment", + "push notifications", + "multi-turn conversational continuation", + "authenticated extended agent cards", + "A2A authentication schemes", + "artifact types beyond Agent Commerce outcome data", + "x402 extension payments across gateway instances" + ], + "health": { + "status": "pass", + "checkedAt": "" + } + }, + { + "name": "acp", + "kind": "protocol", + "implementationVersion": "", + "supportedSpec": "2026-04-17", + "capabilities": [ + "rest transport", + "well-known discovery", + "bearer authentication", + "API-Version enforcement", + "request header forwarding to the merchant", + "checkout service", + "createCheckoutSession", + "updateCheckoutSession", + "getCheckoutSession", + "completeCheckoutSession", + "cancelCheckoutSession" + ], + "status": "experimental", + "unsupported": [ + "carts service", + "feed service", + "standalone orders service", + "delegate_payment", + "delegate_authentication", + "ACP MCP transport binding", + "webhooks", + "outbound merchant-to-agent delivery", + "ACP client role", + "Signature header verification", + "Timestamp replay-window verification", + "discount extension", + "general ACP extension framework", + "multiple ACP API versions", + "seller-backed payment handler integration" + ], + "health": { + "status": "pass", + "checkedAt": "" + } + } + ], + "paymentProviders": [ + { + "name": "x402", + "kind": "payment", + "implementationVersion": "", + "supportedSpec": "x402/v2 scheme=exact family=eip155", + "capabilities": [ + "exact-evm", + "remote-facilitator", + "eip-3009", + "permit2", + "caip-2", + "mode=testnet", + "authorization-flow", + "upfront-flow", + "multiple-offers" + ], + "status": "stable", + "unsupported": [ + "permit2 gas sponsoring extensions", + "upto scheme", + "batch-settlement scheme", + "auth-capture scheme" + ] + }, + { + "name": "mpp", + "kind": "payment", + "implementationVersion": "", + "supportedSpec": "mpp/draft-httpauth-payment-01 intent=charge method=evm", + "capabilities": [ + "intent=charge", + "method=evm", + "credential=authorization", + "eip-3009", + "network=eip155:31337", + "network=eip155:84532", + "network=eip155:8453", + "asset=USDC", + "verify-before-settle", + "authorization-flow", + "upfront-flow", + "payment-receipt", + "challenge-digest-binding" + ], + "status": "experimental", + "unsupported": [ + "methods other than evm", + "credential=permit2", + "credential=transaction", + "credential=hash", + "splits", + "intent=subscription", + "evm sessions", + "discovery extension" + ] + } + ], + "authorizationProviders": [ + { + "name": "ap2", + "kind": "authorization", + "implementationVersion": "", + "supportedSpec": "ap2/v0.2.0 mode=direct", + "capabilities": [ + "direct-mode", + "trusted-agent-provider", + "mandate.checkout.1", + "sd-jwt-presentation", + "ES256", + "sha-256", + "static-inline-trust", + "merchant-checkout-jwt-binding", + "agent-commerce/ap2/checkout/v1", + "purchase-binding", + "replay-defence" + ], + "status": "experimental", + "unsupported": [ + "autonomous mode", + "open checkout mandates (mandate.checkout.open.1)", + "payment mandates (mandate.payment.1)", + "spending constraint evaluation", + "cnf-bound agent keys", + "user credential delegation (OpenID4VP)", + "delegation chains and key-binding JWTs", + "JWKS and any key discovery by URL (jku, x5u)", + "issuer metadata fetching", + "key rotation without a config change", + "signature algorithms other than ES256", + "digest algorithms other than sha-256", + "mandate issuance", + "checkout receipts", + "AP2 over the ACP checkout adapter" + ] + } + ], + "store": { + "name": "sqlite-receipt-store", + "kind": "storage", + "implementationVersion": "", + "supportedSpec": "sqlite-schema-v5", + "capabilities": [ + "receipts", + "events", + "payment-attempts", + "transactions", + "idempotency-keys", + "authorization-holds", + "pending-tasks" + ], + "status": "stable" + }, + "payments": { + "x402": { + "enabled": true, + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "assetName": "USDC", + "assetVersion": "2", + "assetDecimals": 6, + "payTo": "0x1111111111111111111111111111111111111111", + "maxTimeoutSeconds": 120, + "facilitator": { + "mode": "remote" + }, + "mode": "testnet", + "paymentFlow": "authorization", + "options": [ + { + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "assetName": "USDC", + "assetVersion": "2", + "assetDecimals": 6, + "payTo": "0x1111111111111111111111111111111111111111", + "status": "pass" + }, + { + "network": "eip155:421614", + "asset": "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d", + "assetName": "USD Coin", + "assetVersion": "2", + "assetDecimals": 6, + "payTo": "0x1111111111111111111111111111111111111111", + "assetTransferMethod": "permit2", + "status": "pass" + } + ] + }, + "mpp": { + "enabled": true, + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "assetName": "USDC", + "assetVersion": "2", + "assetDecimals": 6, + "recipient": "0x1111111111111111111111111111111111111111", + "facilitator": { + "mode": "remote" + }, + "mode": "testnet", + "paymentFlow": "upfront" + } + } +} diff --git a/tests/integration/goldens/2.7.2/well-known-single.json b/tests/integration/goldens/2.7.2/well-known-single.json new file mode 100644 index 0000000..e64b53f --- /dev/null +++ b/tests/integration/goldens/2.7.2/well-known-single.json @@ -0,0 +1,287 @@ +{ + "gateway": { + "implementationVersion": "", + "supportedSpec": "agent-commerce/v1.0.0" + }, + "merchant": { + "id": "golden-store", + "name": "Golden Store", + "publicBaseUrl": "https://gateway.example" + }, + "protocols": { + "http": { + "enabled": true + }, + "mcp": { + "enabled": true, + "mountPath": "/mcp" + }, + "a2a": { + "enabled": true, + "mountPath": "/a2a" + }, + "acp": { + "enabled": true, + "mountPath": "/acp" + } + }, + "adapters": [ + { + "name": "mcp", + "kind": "protocol", + "implementationVersion": "", + "supportedSpec": "2026-07-28, 2025-11-25", + "capabilities": [ + "tools/list", + "tools/call" + ], + "status": "stable", + "unsupported": [ + "resources", + "prompts", + "sampling", + "completions", + "elicitation", + "roots", + "logging", + "notifications/tools/list_changed", + "tasks", + "dns-rebinding-protection", + "authorization", + "sessions", + "subscriptions", + "pagination", + "HTTP+SSE transport", + "MPP payment-required as JSON-RPC error -32042", + "MPP verification failure as JSON-RPC error -32043" + ], + "health": { + "status": "pass", + "checkedAt": "" + } + }, + { + "name": "a2a", + "kind": "protocol", + "implementationVersion": "", + "supportedSpec": "1.0.1", + "capabilities": [ + "agent-card", + "jsonrpc", + "SendMessage", + "x402-extension" + ], + "status": "experimental", + "unsupported": [ + "SendStreamingMessage", + "GetTask", + "ListTasks", + "CancelTask", + "SubscribeToTask", + "CreateTaskPushNotificationConfig", + "GetTaskPushNotificationConfig", + "ListTaskPushNotificationConfigs", + "DeleteTaskPushNotificationConfig", + "GetExtendedAgentCard", + "HTTP+JSON/REST binding", + "gRPC binding", + "SSE", + "long-running task persistence", + "task resumption other than an x402 extension payment", + "push notifications", + "multi-turn conversational continuation", + "authenticated extended agent cards", + "A2A authentication schemes", + "artifact types beyond Agent Commerce outcome data", + "x402 extension payments across gateway instances" + ], + "health": { + "status": "pass", + "checkedAt": "" + } + }, + { + "name": "acp", + "kind": "protocol", + "implementationVersion": "", + "supportedSpec": "2026-04-17", + "capabilities": [ + "rest transport", + "well-known discovery", + "bearer authentication", + "API-Version enforcement", + "request header forwarding to the merchant", + "checkout service", + "createCheckoutSession", + "updateCheckoutSession", + "getCheckoutSession", + "completeCheckoutSession", + "cancelCheckoutSession" + ], + "status": "experimental", + "unsupported": [ + "carts service", + "feed service", + "standalone orders service", + "delegate_payment", + "delegate_authentication", + "ACP MCP transport binding", + "webhooks", + "outbound merchant-to-agent delivery", + "ACP client role", + "Signature header verification", + "Timestamp replay-window verification", + "discount extension", + "general ACP extension framework", + "multiple ACP API versions", + "seller-backed payment handler integration" + ], + "health": { + "status": "pass", + "checkedAt": "" + } + } + ], + "paymentProviders": [ + { + "name": "x402", + "kind": "payment", + "implementationVersion": "", + "supportedSpec": "x402/v2 scheme=exact family=eip155", + "capabilities": [ + "exact-evm", + "remote-facilitator", + "eip-3009", + "caip-2", + "mode=testnet", + "authorization-flow", + "upfront-flow" + ], + "status": "stable", + "unsupported": [ + "permit2 gas sponsoring extensions", + "upto scheme", + "batch-settlement scheme", + "auth-capture scheme" + ] + }, + { + "name": "mpp", + "kind": "payment", + "implementationVersion": "", + "supportedSpec": "mpp/draft-httpauth-payment-01 intent=charge method=evm", + "capabilities": [ + "intent=charge", + "method=evm", + "credential=authorization", + "eip-3009", + "network=eip155:31337", + "network=eip155:84532", + "network=eip155:8453", + "asset=USDC", + "verify-before-settle", + "authorization-flow", + "upfront-flow", + "payment-receipt", + "challenge-digest-binding" + ], + "status": "experimental", + "unsupported": [ + "methods other than evm", + "credential=permit2", + "credential=transaction", + "credential=hash", + "splits", + "intent=subscription", + "evm sessions", + "discovery extension" + ] + } + ], + "authorizationProviders": [ + { + "name": "ap2", + "kind": "authorization", + "implementationVersion": "", + "supportedSpec": "ap2/v0.2.0 mode=direct", + "capabilities": [ + "direct-mode", + "trusted-agent-provider", + "mandate.checkout.1", + "sd-jwt-presentation", + "ES256", + "sha-256", + "static-inline-trust", + "merchant-checkout-jwt-binding", + "agent-commerce/ap2/checkout/v1", + "purchase-binding", + "replay-defence" + ], + "status": "experimental", + "unsupported": [ + "autonomous mode", + "open checkout mandates (mandate.checkout.open.1)", + "payment mandates (mandate.payment.1)", + "spending constraint evaluation", + "cnf-bound agent keys", + "user credential delegation (OpenID4VP)", + "delegation chains and key-binding JWTs", + "JWKS and any key discovery by URL (jku, x5u)", + "issuer metadata fetching", + "key rotation without a config change", + "signature algorithms other than ES256", + "digest algorithms other than sha-256", + "mandate issuance", + "checkout receipts", + "AP2 over the ACP checkout adapter" + ] + } + ], + "store": { + "name": "sqlite-receipt-store", + "kind": "storage", + "implementationVersion": "", + "supportedSpec": "sqlite-schema-v5", + "capabilities": [ + "receipts", + "events", + "payment-attempts", + "transactions", + "idempotency-keys", + "authorization-holds", + "pending-tasks" + ], + "status": "stable" + }, + "payments": { + "x402": { + "enabled": true, + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "assetName": "USDC", + "assetVersion": "2", + "assetDecimals": 6, + "payTo": "0x1111111111111111111111111111111111111111", + "maxTimeoutSeconds": 120, + "facilitator": { + "mode": "remote" + }, + "mode": "testnet", + "paymentFlow": "authorization" + }, + "mpp": { + "enabled": true, + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "assetName": "USDC", + "assetVersion": "2", + "assetDecimals": 6, + "recipient": "0x1111111111111111111111111111111111111111", + "facilitator": { + "mode": "remote" + }, + "mode": "testnet", + "paymentFlow": "upfront" + } + } +} diff --git a/tests/integration/goldens/2.7.2/x402-challenge-multi.json b/tests/integration/goldens/2.7.2/x402-challenge-multi.json new file mode 100644 index 0000000..d4d6a49 --- /dev/null +++ b/tests/integration/goldens/2.7.2/x402-challenge-multi.json @@ -0,0 +1,36 @@ +{ + "x402Version": 2, + "resource": { + "url": "resource://agent-commerce/resources/market_report", + "description": "Latest market analysis for a symbol.", + "mimeType": "application/json" + }, + "accepts": [ + { + "scheme": "exact", + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "amount": "10000", + "payTo": "0x1111111111111111111111111111111111111111", + "maxTimeoutSeconds": 120, + "extra": { + "name": "USDC", + "version": "2", + "assetTransferMethod": "eip3009" + } + }, + { + "scheme": "exact", + "network": "eip155:421614", + "asset": "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d", + "amount": "10000", + "payTo": "0x1111111111111111111111111111111111111111", + "maxTimeoutSeconds": 120, + "extra": { + "name": "USD Coin", + "version": "2", + "assetTransferMethod": "permit2" + } + } + ] +} diff --git a/tests/integration/goldens/2.7.2/x402-challenge-single.json b/tests/integration/goldens/2.7.2/x402-challenge-single.json new file mode 100644 index 0000000..a5ddbcd --- /dev/null +++ b/tests/integration/goldens/2.7.2/x402-challenge-single.json @@ -0,0 +1,23 @@ +{ + "x402Version": 2, + "resource": { + "url": "resource://agent-commerce/eip155%3A84532/0x1111111111111111111111111111111111111111/resources/market_report", + "description": "Latest market analysis for a symbol.", + "mimeType": "application/json" + }, + "accepts": [ + { + "scheme": "exact", + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "amount": "10000", + "payTo": "0x1111111111111111111111111111111111111111", + "maxTimeoutSeconds": 120, + "extra": { + "name": "USDC", + "version": "2", + "assetTransferMethod": "eip3009" + } + } + ] +} From d5bc013a399873526d3ec7155360454a34e5388f Mon Sep 17 00:00:00 2001 From: Revinand Date: Tue, 17 Nov 2026 15:07:28 +0100 Subject: [PATCH 02/14] feat(core): add the request surface and health reachability to the contract --- docs/contract-surface.txt | 2 + docs/contracts.md | 8 ++++ src/core/domain/common.ts | 5 +++ src/core/domain/payment.ts | 6 +++ src/core/execution/pipeline/admission.ts | 1 + tests/unit/core/execution/pipeline.test.ts | 49 +++++++++++++++++++++- 6 files changed, 70 insertions(+), 1 deletion(-) diff --git a/docs/contract-surface.txt b/docs/contract-surface.txt index b1d3943..dbc4685 100644 --- a/docs/contract-surface.txt +++ b/docs/contract-surface.txt @@ -23,6 +23,7 @@ interface AdapterHealth { interface AdapterHealthComponent { readonly name: string; readonly status: "pass" | "warn" | "fail"; + readonly undetermined?: "unreachable"; } interface AdapterHttpRoute { @@ -373,6 +374,7 @@ interface PaymentContext { readonly currency: string; readonly input?: unknown; readonly metadata?: Readonly>; + readonly protocol?: ProtocolName; readonly requestId: string; readonly requestedAt: string; readonly resource: CommerceResource; diff --git a/docs/contracts.md b/docs/contracts.md index 53edf38..9c2978c 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -299,6 +299,14 @@ persistence must not fail the commerce flow. Omitting the override keeps the code's default. - These fields and methods are experimental and may change in a minor release. The 3.0.0 migration plan makes `getIdempotencyKey` required. +- 2.8.0 adds two optional, experimental fields that may change in a minor + release. Existing 2.7 providers and adapters need no changes. + - `PaymentContext.protocol` identifies the request's protocol. On each + `createRequirement` call, the pipeline copies it from + `CanonicalRequest.protocol`. Providers can ignore it. + - `AdapterHealthComponent.undetermined` uses `'unreachable'` for a probe + that received no response. When set, `status` does not describe the + target's health. Without the field, `status` retains its 2.7 meaning. ### Protocols and gateway diff --git a/src/core/domain/common.ts b/src/core/domain/common.ts index 995feba..9f00aad 100644 --- a/src/core/domain/common.ts +++ b/src/core/domain/common.ts @@ -78,6 +78,11 @@ export interface AdapterHealth { export interface AdapterHealthComponent { readonly name: string; readonly status: 'pass' | 'warn' | 'fail'; + /** + * Marks a probe that received no response; `status` does not describe the + * target's health in this case. Experimental: may change in a minor release. + */ + readonly undetermined?: 'unreachable'; } /** Describes an adapter's supported surface for diagnostics */ diff --git a/src/core/domain/payment.ts b/src/core/domain/payment.ts index e94097e..12fe195 100644 --- a/src/core/domain/payment.ts +++ b/src/core/domain/payment.ts @@ -11,6 +11,7 @@ import type { DecimalAmount, IsoTimestamp, PaymentMethodName, + ProtocolName, } from './common'; import type { PaymentAttempt } from './receipt'; import type { CommerceResource } from './resource'; @@ -122,6 +123,11 @@ export interface PaymentContext { * challenge to the input but must not send it to a third party. */ readonly input?: unknown; + /** + * The request's protocol, set by the pipeline on each createRequirement call. + * Experimental: may change in a minor release. + */ + readonly protocol?: ProtocolName; readonly metadata?: Readonly>; } diff --git a/src/core/execution/pipeline/admission.ts b/src/core/execution/pipeline/admission.ts index cb4aea7..daf88d9 100644 --- a/src/core/execution/pipeline/admission.ts +++ b/src/core/execution/pipeline/admission.ts @@ -92,6 +92,7 @@ export function createPaymentAdmission( currency: pricing.currency, requestedAt: options.clock.nowIso(), input: validInput, + protocol: request.protocol, // Transport facts a rail may bind into its challenge, such as a body digest ...(request.metadata !== undefined ? { metadata: request.metadata } : {}), }); diff --git a/tests/unit/core/execution/pipeline.test.ts b/tests/unit/core/execution/pipeline.test.ts index e571351..3f81f7d 100644 --- a/tests/unit/core/execution/pipeline.test.ts +++ b/tests/unit/core/execution/pipeline.test.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from 'vitest'; -import type { EventSink, PaymentAttempt, ReceiptStore } from '../../../../src/core'; +import { + type EventSink, + type PaymentAttempt, + PROTOCOL_NAMES, + type ReceiptStore, +} from '../../../../src/core'; import type { CommerceEvent, CommerceEventType } from '../../../../src/core/domain/event'; import type { CanonicalRequest, @@ -240,6 +245,48 @@ describe('createExecutionPipeline', () => { expect(inputs).toEqual([{ city: 'Paris' }]); }); + it('passes the request surface to createRequirement on every protocol', async () => { + const resource = makeResource({ + id: 'res-1', + pricing: { type: 'fixed', amount: '0.01', currency: 'USDC' }, + paymentMethods: ['x402'], + exposedVia: PROTOCOL_NAMES, + }); + const seen: unknown[] = []; + const provider = createFakePaymentProvider({ + createRequirement: async (ctx) => { + seen.push(ctx.protocol); + return { + id: 'r', + requestId: ctx.requestId, + resourceId: ctx.resource.id, + provider: 'x402', + amount: ctx.amount, + currency: ctx.currency, + challenge: { provider: 'x402', version: '1', accepts: [] }, + }; + }, + }); + const store = createFakeStore(); + const pipeline = createExecutionPipeline({ + resources: createResourceRegistry([resource]), + paymentProviders: [provider], + store, + backend: createFakeBackendExecutor(), + events: store, + logger: createCapturingLogger(), + clock: createFakeClock(), + ids: createFakeIdGenerator(), + }); + + for (const protocol of PROTOCOL_NAMES) { + const outcome = await pipeline.execute(makeRequest({ protocol })); + expect(outcome.kind).toBe('payment-required'); + } + + expect(seen).toEqual(PROTOCOL_NAMES); + }); + it('throws INPUT_INVALID for input that fails the resource schema', async () => { const resource = makeResource({ id: 'res-1', From a261587fad5f02a0ab37be6cf3f22717a08bcf20 Mon Sep 17 00:00:00 2001 From: Revinand Date: Tue, 17 Nov 2026 15:52:51 +0100 Subject: [PATCH 03/14] feat: read support claims from one record per profile --- docs/contributing-adapters.md | 12 +- docs/protocols/ap2.md | 4 +- docs/protocols/mpp.md | 2 +- scripts/support-record.ts | 161 +++++++++++++ src/authorization/ap2/descriptor.ts | 40 +--- src/cli/commands/doctor/ap2.ts | 11 +- src/cli/commands/doctor/payments.ts | 8 +- src/cli/commands/doctor/protocols.ts | 16 +- src/gateway/well-known.ts | 8 +- src/payments/mpp/descriptor.ts | 25 +-- src/payments/x402/provider/index.ts | 11 +- src/protocols/a2a/descriptor.ts | 42 ++-- src/protocols/acp/descriptor.ts | 42 +--- src/protocols/mcp/descriptor.ts | 39 +--- src/support/a2a.json | 88 ++++++++ src/support/acp.json | 89 ++++++++ src/support/ap2.json | 88 ++++++++ src/support/claims.ts | 34 +++ src/support/http.json | 15 ++ src/support/mcp.json | 68 ++++++ src/support/mpp.json | 130 +++++++++++ src/support/x402.json | 127 +++++++++++ .../goldens/2.7.2/doctor-multi.json | 4 +- .../goldens/2.7.2/doctor-single.json | 4 +- .../goldens/2.7.2/well-known-multi.json | 18 +- .../goldens/2.7.2/well-known-single.json | 18 +- tests/integration/support-record.test.ts | 212 ++++++++++++++++++ tests/mainnet/x402.smoke.test.ts | 10 +- tests/unit/deploy/deploy.test.ts | 17 ++ tests/unit/payments-mpp/profile.test.ts | 11 + 30 files changed, 1170 insertions(+), 184 deletions(-) create mode 100644 scripts/support-record.ts create mode 100644 src/support/a2a.json create mode 100644 src/support/acp.json create mode 100644 src/support/ap2.json create mode 100644 src/support/claims.ts create mode 100644 src/support/http.json create mode 100644 src/support/mcp.json create mode 100644 src/support/mpp.json create mode 100644 src/support/x402.json create mode 100644 tests/integration/support-record.test.ts diff --git a/docs/contributing-adapters.md b/docs/contributing-adapters.md index ab4733e..c0a7cb0 100644 --- a/docs/contributing-adapters.md +++ b/docs/contributing-adapters.md @@ -31,9 +31,9 @@ A new name crosses the public contract and runtime wiring. After approval: 5. If it has distinct optional dependencies, add the narrow subpath, build entry, package export, optional peer and the real-package check in `tests/unit/cli/packaging.test.ts`. -6. Add its descriptor, discovery and `doctor` output. Update the frozen - contract and conformance coverage, and add a page under `docs/protocols/` - that [protocols.md](protocols.md) lists. +6. Add a support record under `src/support/`, a descriptor, and discovery and + `doctor` output. Update the frozen contract and conformance coverage. Add a + page under `docs/protocols/` and list it in [protocols.md](protocols.md). ## Protocol adapters @@ -95,9 +95,9 @@ validation, authorization, payment, backend execution and receipts. carriers from headers. - Keep handler failures inside the adapter and report health through `health()`. -- Pin `descriptor.supportedSpec`, list real `capabilities` and `unsupported` - features, and keep `status: experimental` until conformance coverage supports - promotion. +- Pin `descriptor.supportedSpec` and list implemented `capabilities`. Derive + `status` and `unsupported` from the adapter's record in `src/support/`. + Keep the adapter `experimental` until conformance coverage supports promotion. ### Adapter review checklist diff --git a/docs/protocols/ap2.md b/docs/protocols/ap2.md index c6490cb..d50b3ab 100644 --- a/docs/protocols/ap2.md +++ b/docs/protocols/ap2.md @@ -381,8 +381,8 @@ does not close authorization providers. ## Not implemented -`src/authorization/ap2/descriptor.ts` is authoritative for the unsupported list -published through discovery and `doctor`. The broader implementation limits are: +Discovery and `doctor` read the unsupported list from `src/support/ap2.json`. +The broader implementation limits are: - autonomous mode and open Checkout Mandates (`mandate.checkout.open.1`) - Payment Mandates (`mandate.payment.1`) diff --git a/docs/protocols/mpp.md b/docs/protocols/mpp.md index 1b06a19..af4e824 100644 --- a/docs/protocols/mpp.md +++ b/docs/protocols/mpp.md @@ -61,7 +61,7 @@ issuing challenges over plain HTTP. Base mainnet deployments must satisfy the [mainnet guardrails](../configuration.md#mainnet-guardrails). -Unsupported variants are listed in `src/payments/mpp/descriptor.ts`: non-EVM +Unsupported variants are listed in `src/support/mpp.json`: non-EVM methods, Permit2/transaction/hash credentials, splits, subscriptions, EVM sessions and the discovery extension. diff --git a/scripts/support-record.ts b/scripts/support-record.ts new file mode 100644 index 0000000..61ab54e --- /dev/null +++ b/scripts/support-record.ts @@ -0,0 +1,161 @@ +/** + * Validate the support records under `src/support/`, one per shipped profile. + * Each record states the revision, subset, exclusions, deviations and evidence + * its status covers. Descriptors and `doctor` trust these files at runtime. + * This schema runs in tests and tooling and is excluded from the published + * package. + */ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { z } from 'zod'; + +export const SUPPORT_RECORD_NAMES = ['http', 'mcp', 'a2a', 'acp', 'x402', 'mpp', 'ap2'] as const; + +export const REPO_ROOT = join(import.meta.dirname, '..'); + +const text = z.string().min(1); + +const SpecSchema = z.strictObject({ + // Revision identifiers for comparison with code + revisions: z.array(text).min(1), + // Display text for the pinned revision + display: text, + source: z.strictObject({ repo: text, commit: z.string().regex(/^[0-9a-f]{40}$/) }), + // Whether upstream calls the pinned revision stable; null when unspecified + stable: z.boolean().nullable(), + // Upstream's own words on the revision's status + statement: text, + // The date `statement` was read + checked: z.iso.date(), +}); + +const SupportRecordSchema = z + .strictObject({ + name: z.enum(SUPPORT_RECORD_NAMES), + kind: z.enum(['protocol', 'payment', 'authorization']), + title: text, + status: z.enum(['supported', 'experimental']), + // The profile's role as a transport, payment rail or authorization method + role: text, + subset: text, + spec: SpecSchema.optional(), + // Package names; version pins live in package.json + packages: z.array(z.strictObject({ name: text, use: z.enum(['runtime', 'test']) })), + // Vendored schemas and fixtures + artifacts: z.array(z.strictObject({ path: text, revision: text })), + // Descriptor capabilities, each with its own status + features: z.array( + z.strictObject({ + name: text, + status: z.enum(['supported', 'experimental', 'partial']), + spec: SpecSchema.optional(), + }), + ), + // `name` is the string the descriptor publishes in `unsupported` + exclusions: z.array( + z.strictObject({ name: text, note: text.optional(), feature: text.optional() }), + ), + deviations: z.array( + z.strictObject({ + summary: text, + // The specification and section the behavior departs from + spec: text, + upstream: text.optional(), + tests: z.array(text).min(1), + }), + ), + // Payment records: the surface, rail and authorization covered by the evidence + combinations: z + .array( + z.strictObject({ + surface: z.enum(['http', 'mcp', 'a2a']), + method: z.enum(['x402', 'mpp']), + authorization: z.literal('ap2').optional(), + level: z.enum(['e2e', 'integration', 'testnet', 'mainnet']), + evidence: text, + }), + ) + .optional(), + conformance: z + .strictObject({ + suite: text, + tests: z.array(text).min(1), + skipped: z.array( + z.strictObject({ + test: text, + reason: text, + spec: text.optional(), + upstream: text.optional(), + }), + ), + }) + .optional(), + // Known MUST-level gaps against the pinned revision + gaps: z.array( + z.strictObject({ requirement: text, state: z.enum(['open', 'closed', 'excluded']) }), + ), + docs: z.array(text).min(1), + }) + .superRefine((record, ctx) => { + const duplicates = (names: readonly string[]) => + names.filter((name, index) => names.indexOf(name) !== index); + const features = record.features.map((feature) => feature.name); + for (const name of duplicates(features)) { + ctx.addIssue({ code: 'custom', path: ['features'], message: `duplicate feature "${name}"` }); + } + for (const name of duplicates(record.exclusions.map((exclusion) => exclusion.name))) { + ctx.addIssue({ + code: 'custom', + path: ['exclusions'], + message: `duplicate exclusion "${name}"`, + }); + } + for (const exclusion of record.exclusions) { + if (exclusion.feature !== undefined && !features.includes(exclusion.feature)) { + ctx.addIssue({ + code: 'custom', + path: ['exclusions'], + message: `exclusion "${exclusion.name}" names unknown feature "${exclusion.feature}"`, + }); + } + } + if (record.combinations !== undefined && record.kind !== 'payment') { + ctx.addIssue({ + code: 'custom', + path: ['combinations'], + message: 'only a payment record lists tested combinations', + }); + } + }); + +export type SupportRecord = z.infer; +export type SupportRecordName = (typeof SUPPORT_RECORD_NAMES)[number]; + +export function supportRecordPath(name: SupportRecordName): string { + return join(REPO_ROOT, 'src/support', `${name}.json`); +} + +/** Read and validate a record; schema errors include the file path and validation details */ +export function readSupportRecord(name: SupportRecordName): SupportRecord { + const path = supportRecordPath(name); + const parsed = SupportRecordSchema.safeParse(JSON.parse(readFileSync(path, 'utf8'))); + if (!parsed.success) { + throw new Error(`src/support/${name}.json: ${z.prettifyError(parsed.error)}`); + } + if (parsed.data.name !== name) { + throw new Error(`src/support/${name}.json: name is "${parsed.data.name}", not "${name}"`); + } + return parsed.data; +} + +/** Evidence and documentation paths to check for existence */ +export function citedPaths(record: SupportRecord): string[] { + return [ + ...record.artifacts.map((artifact) => artifact.path), + ...(record.combinations ?? []).map((combination) => combination.evidence), + ...(record.conformance?.tests ?? []), + ...(record.conformance?.skipped ?? []).map((skipped) => skipped.test), + ...record.deviations.flatMap((deviation) => deviation.tests), + ...record.docs, + ]; +} diff --git a/src/authorization/ap2/descriptor.ts b/src/authorization/ap2/descriptor.ts index 31f78a9..414e0ef 100644 --- a/src/authorization/ap2/descriptor.ts +++ b/src/authorization/ap2/descriptor.ts @@ -1,10 +1,8 @@ -/** - * Adapter self-description. - * - * Imports nothing but core types and the pins, so `doctor` can report AP2 - * without pulling `jose` or `@sd-jwt/core` into the CLI bundle. - */ +// AP2 pins and support metadata for diagnostics, without loading the optional +// `jose` or `@sd-jwt/core` peers import type { AdapterDescriptor } from '../../core'; +import record from '../../support/ap2.json' with { type: 'json' }; +import { descriptorStatus, exclusionNames } from '../../support/claims'; import { AP2_CHECKOUT_MANDATE_VCT, AP2_CHECKOUT_PROFILE, @@ -29,32 +27,10 @@ export const AP2_CAPABILITIES: readonly string[] = [ ]; /** - * Major AP2 features this provider does not support, published in its - * descriptor and printed by `doctor`, so no client assumes full protocol - * support + * Unsupported AP2 features from the support record, published in the descriptor + * and printed by `doctor` to show the limits of protocol support */ -export const AP2_UNSUPPORTED: readonly string[] = [ - // Mandate kinds. Open mandates are refused: see AP2_CHECKOUT_MANDATE_VCT - 'autonomous mode', - 'open checkout mandates (mandate.checkout.open.1)', - 'payment mandates (mandate.payment.1)', - 'spending constraint evaluation', - 'cnf-bound agent keys', - // Delegation models other than a trusted agent provider - 'user credential delegation (OpenID4VP)', - 'delegation chains and key-binding JWTs', - // Key handling. Every key is written into config by an operator - 'JWKS and any key discovery by URL (jku, x5u)', - 'issuer metadata fetching', - 'key rotation without a config change', - // Algorithms - 'signature algorithms other than ES256', - 'digest algorithms other than sha-256', - // Roles this gateway does not play - 'mandate issuance', - 'checkout receipts', - 'AP2 over the ACP checkout adapter', -]; +export const AP2_UNSUPPORTED: readonly string[] = exclusionNames(record); export function buildAp2Descriptor(implementationVersion: string): AdapterDescriptor { return { @@ -63,7 +39,7 @@ export function buildAp2Descriptor(implementationVersion: string): AdapterDescri implementationVersion, supportedSpec: `ap2/v${AP2_SPEC_VERSION} mode=direct`, capabilities: AP2_CAPABILITIES, - status: 'experimental', + status: descriptorStatus(record), unsupported: AP2_UNSUPPORTED, }; } diff --git a/src/cli/commands/doctor/ap2.ts b/src/cli/commands/doctor/ap2.ts index edf3821..6336d15 100644 --- a/src/cli/commands/doctor/ap2.ts +++ b/src/cli/commands/doctor/ap2.ts @@ -1,13 +1,14 @@ // AP2 checks: settings, trust lists, the replay store and the gated resources -// Constants and a descriptor only: the AP2 provider would pull the optional -// peers `jose`, `@sd-jwt/core` and `canonicalize` into the CLI bundle +// Read AP2 constants and support metadata directly to keep the optional peers +// `jose`, `@sd-jwt/core` and `canonicalize` out of the static CLI imports import { AP2_CHECKOUT_MANDATE_VCT, AP2_CHECKOUT_PROFILE, AP2_SPEC_VERSION, } from '../../../authorization/ap2/constants'; -import { AP2_UNSUPPORTED } from '../../../authorization/ap2/descriptor'; +import ap2Record from '../../../support/ap2.json' with { type: 'json' }; +import { exclusionNames } from '../../../support/claims'; import type { GatewayConfig } from '../../lib/config-client'; import { type LegacyState, legacyStoreCheck } from './storage'; import type { DoctorCheck } from './types'; @@ -39,7 +40,7 @@ export function ap2Checks(config: GatewayConfig | undefined, legacy: LegacyState checks.push({ name: 'AP2', status: 'PASS', - detail: `experimental · spec ${AP2_SPEC_VERSION} · mode ${ap2.mode} · ${AP2_CHECKOUT_MANDATE_VCT} · profile ${AP2_CHECKOUT_PROFILE} · clock skew ${ap2.clockSkewSeconds}s · mandate aud ${ap2.requireMandateAudience === true ? 'required' : 'optional'} · mandate exp ${ap2.requireMandateExpiry === true ? 'required' : 'optional'}`, + detail: `${ap2Record.status} · spec ${AP2_SPEC_VERSION} · mode ${ap2.mode} · ${AP2_CHECKOUT_MANDATE_VCT} · profile ${AP2_CHECKOUT_PROFILE} · clock skew ${ap2.clockSkewSeconds}s · mandate aud ${ap2.requireMandateAudience === true ? 'required' : 'optional'} · mandate exp ${ap2.requireMandateExpiry === true ? 'required' : 'optional'}`, }); // Two lists, reported separately: signing the merchant's checkout @@ -77,7 +78,7 @@ export function ap2Checks(config: GatewayConfig | undefined, legacy: LegacyState checks.push({ name: 'AP2 unsupported', status: 'INFO', - detail: AP2_UNSUPPORTED.join(', '), + detail: exclusionNames(ap2Record).join(', '), }); } return checks; diff --git a/src/cli/commands/doctor/payments.ts b/src/cli/commands/doctor/payments.ts index 51ce656..c8f6515 100644 --- a/src/cli/commands/doctor/payments.ts +++ b/src/cli/commands/doctor/payments.ts @@ -18,11 +18,15 @@ import { resolveDeploymentMode, } from '../../../payments/x402/networks'; import { X402_DEFAULT_PAYMENT_FLOW } from '../../../payments/x402/payment-flow'; +import { featureStatus } from '../../../support/claims'; +import x402Record from '../../../support/x402.json' with { type: 'json' }; import type { GatewayConfig } from '../../lib/config-client'; import { PLACEHOLDER_ASSET_ADDRESS } from '../../lib/init-config'; import { maskMiddle } from '../../lib/mask'; import type { DoctorCheck, WellKnownResult } from './types'; +const QUOTE_STATUS = featureStatus(x402Record, 'erc-8409-quotes'); + // The rail's settlement order and how many resources override it function describePaymentFlow( rail: { @@ -399,7 +403,7 @@ function quoteCheck( ? { name, status: 'INFO', - detail: `ERC-8409 quotes enabled (experimental)${localIssuer !== undefined ? `, issuer=${localIssuer} from the local key` : ''}; the gateway's issuer could not be read`, + detail: `ERC-8409 quotes enabled (${QUOTE_STATUS})${localIssuer !== undefined ? `, issuer=${localIssuer} from the local key` : ''}; the gateway's issuer could not be read`, } : undefined; } @@ -431,7 +435,7 @@ function quoteCheck( return { name, status: 'PASS', - detail: `ERC-8409 quotes (experimental) - issuer=${issuer}${local === undefined ? ' as the gateway publishes it (viem could not be loaded to check it against the local key)' : ''}, requestScheme=${quote.requestScheme}, extension=${quote.extension}`, + detail: `ERC-8409 quotes (${QUOTE_STATUS}) - issuer=${issuer}${local === undefined ? ' as the gateway publishes it (viem could not be loaded to check it against the local key)' : ''}, requestScheme=${quote.requestScheme}, extension=${quote.extension}`, }; } diff --git a/src/cli/commands/doctor/protocols.ts b/src/cli/commands/doctor/protocols.ts index 790ba6d..dff2337 100644 --- a/src/cli/commands/doctor/protocols.ts +++ b/src/cli/commands/doctor/protocols.ts @@ -1,19 +1,21 @@ // Protocol checks: what is enabled, and the A2A and ACP specifics -// Narrow modules, not the protocol barrels: the CLI must pull in no protocol SDK +// Read protocol constants and support metadata directly to keep protocol SDKs +// out of the static CLI imports import { A2A_AGENT_CARD_PATH, A2A_PROTOCOL_BINDING, A2A_PROTOCOL_VERSION, A2A_SPEC_VERSION, } from '../../../protocols/a2a/constants'; -import { A2A_UNSUPPORTED } from '../../../protocols/a2a/descriptor'; import { ACP_API_VERSION, ACP_SPEC_VERSION, ACP_WELL_KNOWN_PATH, } from '../../../protocols/acp/constants'; -import { ACP_UNSUPPORTED } from '../../../protocols/acp/descriptor'; +import a2aRecord from '../../../support/a2a.json' with { type: 'json' }; +import acpRecord from '../../../support/acp.json' with { type: 'json' }; +import { exclusionNames } from '../../../support/claims'; import type { GatewayConfig } from '../../lib/config-client'; import { type LegacyState, legacyStoreCheck } from './storage'; import type { DoctorCheck, WellKnownResult } from './types'; @@ -89,14 +91,14 @@ export function protocolChecks( checks.push({ name: 'A2A', status: 'PASS', - detail: `experimental · spec ${A2A_SPEC_VERSION} · protocol ${A2A_PROTOCOL_VERSION} · binding ${A2A_PROTOCOL_BINDING} · mount ${config.protocols.a2a.mountPath} · card ${A2A_AGENT_CARD_PATH}`, + detail: `${a2aRecord.status} · spec ${A2A_SPEC_VERSION} · protocol ${A2A_PROTOCOL_VERSION} · binding ${A2A_PROTOCOL_BINDING} · mount ${config.protocols.a2a.mountPath} · card ${A2A_AGENT_CARD_PATH}`, }); // Listed in full, as are ACP's and AP2's below: a count does not tell an // operator whether the one feature their client needs is missing checks.push({ name: 'A2A unsupported', status: 'INFO', - detail: A2A_UNSUPPORTED.join(', '), + detail: exclusionNames(a2aRecord).join(', '), }); } @@ -112,7 +114,7 @@ export function protocolChecks( checks.push({ name: 'ACP', status: 'PASS', - detail: `experimental · spec ${ACP_SPEC_VERSION} · API-Version ${ACP_API_VERSION} · service checkout · mount ${acp.mountPath} · discovery ${ACP_WELL_KNOWN_PATH}`, + detail: `${acpRecord.status} · spec ${ACP_SPEC_VERSION} · API-Version ${ACP_API_VERSION} · service checkout · mount ${acp.mountPath} · discovery ${ACP_WELL_KNOWN_PATH}`, }); // Whether a token is configured and its length, never the token. Config @@ -138,7 +140,7 @@ export function protocolChecks( checks.push({ name: 'ACP unsupported', status: 'INFO', - detail: ACP_UNSUPPORTED.join(', '), + detail: exclusionNames(acpRecord).join(', '), }); } return checks; diff --git a/src/gateway/well-known.ts b/src/gateway/well-known.ts index 965c1e8..2eb14ea 100644 --- a/src/gateway/well-known.ts +++ b/src/gateway/well-known.ts @@ -29,6 +29,8 @@ import { import { x402OfferName } from '../payments/x402/options'; import { X402_DEFAULT_PAYMENT_FLOW, type X402PaymentFlow } from '../payments/x402/payment-flow'; import type { X402PaymentProvider } from '../payments/x402/provider/types'; +import { type FeatureStatus, featureStatus } from '../support/claims'; +import x402Record from '../support/x402.json' with { type: 'json' }; import { PACKAGE_VERSION } from '../version'; import type { ProbedAdapter, ProbedProvider } from './readiness'; @@ -36,6 +38,8 @@ import type { ProbedAdapter, ProbedProvider } from './readiness'; // negotiates against, which changes only when that contract does const GATEWAY_SUPPORTED_SPEC = 'agent-commerce/v1.0.0'; +const QUOTE_STATUS = featureStatus(x402Record, 'erc-8409-quotes'); + /** * The protocol block as published, not as configured. * @@ -133,7 +137,7 @@ export interface WellKnownX402Quote { readonly requestScheme: string; /** The key in `PaymentRequired.extensions` that carries the quotes */ readonly extension: string; - readonly status: 'experimental'; + readonly status: FeatureStatus; } export interface BuildWellKnownOptions { @@ -204,7 +208,7 @@ function publicQuote(providers: readonly PaymentProvider[]): WellKnownX402Quote | undefined; if (x402?.quote === undefined) return undefined; const { issuer, requestScheme, extension } = x402.quote; - return { issuer, requestScheme, extension, status: 'experimental' }; + return { issuer, requestScheme, extension, status: QUOTE_STATUS }; } export function buildWellKnownDocument(options: BuildWellKnownOptions): WellKnownDocument { diff --git a/src/payments/mpp/descriptor.ts b/src/payments/mpp/descriptor.ts index cb07d18..a701c11 100644 --- a/src/payments/mpp/descriptor.ts +++ b/src/payments/mpp/descriptor.ts @@ -1,12 +1,15 @@ /** * Describes the MPP profile and its unsupported variants. * - * The protocol name alone cannot identify a compatible intent, method and - * extension set, so the descriptor lists both the target and its gaps. + * The descriptor identifies the intent, method, extensions and unsupported + * variants needed to assess compatibility. Status and unsupported variants + * come from `src/support/mpp.json`. * * Importing the descriptor does not load `mppx`. */ import type { AdapterDescriptor } from '../../core/public-types'; +import { descriptorStatus, exclusionNames } from '../../support/claims'; +import record from '../../support/mpp.json' with { type: 'json' }; import { PACKAGE_VERSION } from '../../version'; import { MPP_NETWORKS, MPP_PROFILE, MPP_SUPPORTED_SPEC } from './constants'; @@ -29,20 +32,6 @@ export const MPP_DESCRIPTOR: AdapterDescriptor = { // HTTP request bodies only; MCP and A2A carry the proof in the body 'challenge-digest-binding', ], - // The pinned specs are drafts and mppx is pre-1.0; the wire format may change - status: 'experimental', - unsupported: [ - // Name other methods as a class instead of maintaining a second list - 'methods other than evm', - // This profile supports only the EIP-3009 `authorization` credential - 'credential=permit2', - 'credential=transaction', - 'credential=hash', - // The draft allows splits only with permit2 credentials - 'splits', - 'intent=subscription', - // A separate EVM draft, not an option of charge - 'evm sessions', - 'discovery extension', - ], + status: descriptorStatus(record), + unsupported: exclusionNames(record), }; diff --git a/src/payments/x402/provider/index.ts b/src/payments/x402/provider/index.ts index 2aacc1a..7fccb9a 100644 --- a/src/payments/x402/provider/index.ts +++ b/src/payments/x402/provider/index.ts @@ -12,6 +12,8 @@ */ import type { AdapterDescriptor } from '../../../core'; import { CommerceError, NOOP_LOGGER, systemClock } from '../../../core'; +import { descriptorStatus, exclusionNames } from '../../../support/claims'; +import record from '../../../support/x402.json' with { type: 'json' }; import { PACKAGE_VERSION } from '../../../version'; import { DEFAULT_IDS, DEFAULT_MAX_TIMEOUT_SECONDS, X402_VERSION } from './constants'; import { @@ -112,13 +114,8 @@ export function createX402PaymentProvider( ...(severalOffers ? ['multiple-offers'] : []), ...(quotes ? ['erc-8409-quotes'] : []), ], - status: 'stable', - unsupported: [ - 'permit2 gas sponsoring extensions', - 'upto scheme', - 'batch-settlement scheme', - 'auth-capture scheme', - ], + status: descriptorStatus(record), + unsupported: exclusionNames(record), }; // Loaded only with an offer of their family, so no deployment needs the diff --git a/src/protocols/a2a/descriptor.ts b/src/protocols/a2a/descriptor.ts index 47be8c7..c66b9f7 100644 --- a/src/protocols/a2a/descriptor.ts +++ b/src/protocols/a2a/descriptor.ts @@ -1,13 +1,13 @@ /** - * Adapter self-description. - * - * `supportedSpec` is the A2A specification revision (`1.0.1`), never the - * negotiation version (`1.0`) and never this package's version. Status is - * `experimental` while the adapter lacks the features in the unsupported list - * below; an entry leaves that list only when its feature is implemented. + * `supportedSpec` pins the A2A specification revision (`1.0.1`). Negotiation + * uses `1.0`; the package version is independent. Status and unsupported + * features come from `src/support/a2a.json`. Remove an unsupported entry only + * after implementing its feature. */ import type { AdapterDescriptor } from '../../core'; -import { A2A_SPEC_VERSION, A2A_UNSUPPORTED_METHODS } from './constants'; +import record from '../../support/a2a.json' with { type: 'json' }; +import { descriptorStatus, exclusionNames } from '../../support/claims'; +import { A2A_SPEC_VERSION } from './constants'; // What this adapter implements const A2A_CAPABILITIES: readonly string[] = [ @@ -19,28 +19,12 @@ const A2A_CAPABILITIES: readonly string[] = [ ]; /** - * Major A2A features this adapter does not implement, served on - * `/.well-known/agent-commerce` and printed by `doctor`, so no client assumes - * full protocol support + * Unsupported A2A features, published at `/.well-known/agent-commerce` and + * printed by `doctor` to show the limits of protocol support. + * The support record also lists the `A2A_UNSUPPORTED_METHODS` refused by the + * transport. */ -export const A2A_UNSUPPORTED: readonly string[] = [ - // Methods, as the protocol names them; the transport refuses the same list - ...A2A_UNSUPPORTED_METHODS, - // Transports other than the one binding served - 'HTTP+JSON/REST binding', - 'gRPC binding', - // Behaviors - 'SSE', - 'long-running task persistence', - 'task resumption other than an x402 extension payment', - 'push notifications', - 'multi-turn conversational continuation', - 'authenticated extended agent cards', - 'A2A authentication schemes', - 'artifact types beyond Agent Commerce outcome data', - // Instances with separate receipt stores cannot resume each other's tasks - 'x402 extension payments across gateway instances', -]; +export const A2A_UNSUPPORTED: readonly string[] = exclusionNames(record); export function buildDescriptor(implementationVersion: string): AdapterDescriptor { return { @@ -49,7 +33,7 @@ export function buildDescriptor(implementationVersion: string): AdapterDescripto implementationVersion, supportedSpec: A2A_SPEC_VERSION, capabilities: A2A_CAPABILITIES, - status: 'experimental', + status: descriptorStatus(record), unsupported: A2A_UNSUPPORTED, }; } diff --git a/src/protocols/acp/descriptor.ts b/src/protocols/acp/descriptor.ts index 02f43bc..ff3e05a 100644 --- a/src/protocols/acp/descriptor.ts +++ b/src/protocols/acp/descriptor.ts @@ -1,12 +1,11 @@ /** - * Adapter self-description. - * - * `supportedSpec` is the pinned ACP snapshot, never this package's version. - * Status is `experimental` while the adapter lacks the features in the - * unsupported list below; an entry leaves that list only when its feature is - * implemented. + * `supportedSpec` pins the ACP snapshot independently of the package version. + * Status and unsupported features come from `src/support/acp.json`. + * Remove an unsupported entry only after implementing its feature. */ import type { AdapterDescriptor } from '../../core'; +import record from '../../support/acp.json' with { type: 'json' }; +import { descriptorStatus, exclusionNames } from '../../support/claims'; import { ACP_CHECKOUT_OPERATIONS, ACP_SPEC_VERSION } from './constants'; // What this adapter implements @@ -22,32 +21,11 @@ const ACP_CAPABILITIES: readonly string[] = [ ]; /** - * Major ACP features this adapter does not implement, served on - * `/.well-known/agent-commerce` and printed by `doctor`, so no client assumes - * full protocol support + * Unsupported ACP features from the support record, published at + * `/.well-known/agent-commerce` and printed by `doctor` to show the limits of + * protocol support */ -export const ACP_UNSUPPORTED: readonly string[] = [ - // Services this seller does not implement, named as ACP names them. The - // discovery document advertises `checkout` alone, and these are the reason. - 'carts service', - 'feed service', - 'standalone orders service', - 'delegate_payment', - 'delegate_authentication', - // Bindings and delivery directions - 'ACP MCP transport binding', - 'webhooks', - 'outbound merchant-to-agent delivery', - 'ACP client role', - // Request authentication beyond the bearer token - 'Signature header verification', - 'Timestamp replay-window verification', - // Extensions, versioning and payment handlers - 'discount extension', - 'general ACP extension framework', - 'multiple ACP API versions', - 'seller-backed payment handler integration', -]; +export const ACP_UNSUPPORTED: readonly string[] = exclusionNames(record); export function buildDescriptor(implementationVersion: string): AdapterDescriptor { return { @@ -56,7 +34,7 @@ export function buildDescriptor(implementationVersion: string): AdapterDescripto implementationVersion, supportedSpec: ACP_SPEC_VERSION, capabilities: ACP_CAPABILITIES, - status: 'experimental', + status: descriptorStatus(record), unsupported: ACP_UNSUPPORTED, }; } diff --git a/src/protocols/mcp/descriptor.ts b/src/protocols/mcp/descriptor.ts index dd8e542..90d7ddd 100644 --- a/src/protocols/mcp/descriptor.ts +++ b/src/protocols/mcp/descriptor.ts @@ -1,10 +1,12 @@ /** - * Adapter self-description. `supportedSpec` lists the modern revision and - * the newest 2025-era revision. The SDK's legacy fallback also accepts older - * 2025-era revisions. + * `supportedSpec` lists the modern revision and the newest 2025-era revision. + * The SDK's legacy fallback also accepts older revisions, back to 2024-10-07. + * Tests do not negotiate that oldest revision. */ import { LATEST_PROTOCOL_VERSION } from '@modelcontextprotocol/server'; import type { AdapterDescriptor } from '../../core'; +import { descriptorStatus, exclusionNames } from '../../support/claims'; +import record from '../../support/mcp.json' with { type: 'json' }; import { MCP_MODERN_PROTOCOL_REVISION } from './constants'; // List the modern revision followed by the SDK's latest legacy revision @@ -14,33 +16,10 @@ const MCP_SUPPORTED_SPEC = `${MCP_MODERN_PROTOCOL_REVISION}, ${LATEST_PROTOCOL_V const MCP_CAPABILITIES: readonly string[] = ['tools/list', 'tools/call']; /** - * MCP surfaces this adapter does not implement, listed so its descriptor never - * implies blanket protocol compatibility. - * - * `dns-rebinding-protection` is delegated rather than missing: the gateway's - * `onRequest` hook validates Host and Origin for `/mcp` (see adapter.ts), and - * the adapter provides none on its own. + * Unsupported MCP surfaces from the support record, published in the descriptor + * to show the limits of protocol support */ -export const MCP_UNSUPPORTED: readonly string[] = [ - 'resources', - 'prompts', - 'sampling', - 'completions', - 'elicitation', - 'roots', - 'logging', - 'notifications/tools/list_changed', - 'tasks', - 'dns-rebinding-protection', - 'authorization', - 'sessions', - 'subscriptions', - 'pagination', - 'HTTP+SSE transport', - // mppx reads challenges and refusals from tool-result `_meta`. - 'MPP payment-required as JSON-RPC error -32042', - 'MPP verification failure as JSON-RPC error -32043', -]; +export const MCP_UNSUPPORTED: readonly string[] = exclusionNames(record); export function buildDescriptor(implementationVersion: string): AdapterDescriptor { return { @@ -49,7 +28,7 @@ export function buildDescriptor(implementationVersion: string): AdapterDescripto implementationVersion, supportedSpec: MCP_SUPPORTED_SPEC, capabilities: MCP_CAPABILITIES, - status: 'stable', + status: descriptorStatus(record), unsupported: MCP_UNSUPPORTED, }; } diff --git a/src/support/a2a.json b/src/support/a2a.json new file mode 100644 index 0000000..2694f53 --- /dev/null +++ b/src/support/a2a.json @@ -0,0 +1,88 @@ +{ + "name": "a2a", + "kind": "protocol", + "title": "A2A", + "status": "experimental", + "role": "Transport that carries x402 and MPP payments in SendMessage, including through the x402 extension.", + "subset": "Agent Card, `SendMessage`, paid flow and the x402 extension", + "spec": { + "revisions": ["1.0.1"], + "display": "v1.0.1; negotiation `1.0`; `JSONRPC` binding", + "source": { + "repo": "a2aproject/A2A", + "commit": "3303592588e388e62e0f69f701af531d2f4e3991" + }, + "stable": true, + "statement": "the first stable, production-ready version", + "checked": "2026-11-17" + }, + "packages": [{ "name": "@a2a-js/sdk", "use": "test" }], + "artifacts": [], + "features": [ + { "name": "agent-card", "status": "experimental" }, + { "name": "jsonrpc", "status": "experimental" }, + { "name": "SendMessage", "status": "experimental" }, + { "name": "x402-extension", "status": "experimental" } + ], + "exclusions": [ + { "name": "SendStreamingMessage" }, + { "name": "GetTask" }, + { "name": "ListTasks" }, + { "name": "CancelTask" }, + { "name": "SubscribeToTask" }, + { "name": "CreateTaskPushNotificationConfig" }, + { "name": "GetTaskPushNotificationConfig" }, + { "name": "ListTaskPushNotificationConfigs" }, + { "name": "DeleteTaskPushNotificationConfig" }, + { "name": "GetExtendedAgentCard" }, + { "name": "HTTP+JSON/REST binding" }, + { "name": "gRPC binding" }, + { "name": "SSE" }, + { "name": "long-running task persistence" }, + { "name": "task resumption other than an x402 extension payment" }, + { "name": "push notifications" }, + { "name": "multi-turn conversational continuation" }, + { "name": "text parts" }, + { "name": "file and URL parts (including inline bytes)" }, + { "name": "multi-part messages" }, + { "name": "message roles other than ROLE_USER" }, + { "name": "authenticated extended agent cards" }, + { "name": "A2A authentication schemes" }, + { "name": "artifact types beyond Agent Commerce outcome data" }, + { + "name": "x402 extension payments across gateway instances", + "note": "Instances with separate receipt stores cannot resume each other's tasks." + } + ], + "deviations": [], + "conformance": { + "suite": "Our tests against the A2A 1.0.1 specification; the A2A TCK has not been run.", + "tests": [ + "tests/conformance/a2a/agent-card.test.ts", + "tests/conformance/a2a/errors.test.ts", + "tests/conformance/a2a/free-resource.test.ts", + "tests/conformance/a2a/paid-resource.test.ts", + "tests/conformance/a2a/protocol-version.test.ts" + ], + "skipped": [] + }, + "gaps": [ + { + "requirement": "§3.1: GetTask, ListTasks and CancelTask, which every agent implements", + "state": "open" + }, + { + "requirement": "§3.2.2: returnImmediately as well as the blocking default", + "state": "open" + }, + { + "requirement": "§3.3.2: validate all input parameters, including tenant and configuration", + "state": "open" + }, + { + "requirement": "§7.1: encrypted communication in production; merchant.publicBaseUrl accepts http", + "state": "open" + } + ], + "docs": ["docs/protocols/a2a.md"] +} diff --git a/src/support/acp.json b/src/support/acp.json new file mode 100644 index 0000000..ec0cd0e --- /dev/null +++ b/src/support/acp.json @@ -0,0 +1,89 @@ +{ + "name": "acp", + "kind": "protocol", + "title": "ACP", + "status": "experimental", + "role": "Checkout API that forwards checkout operations to the merchant, whose payment handler receives payment_data. Gateway checkout routes are free and carry no x402 or MPP payment.", + "subset": "discovery and the five checkout operations", + "spec": { + "revisions": ["2026-04-17"], + "display": "stable snapshot `2026-04-17`; REST binding", + "source": { + "repo": "agentic-commerce-protocol/agentic-commerce-protocol", + "commit": "6b828681206f1f98a3faba978610ced66770d2ae" + }, + "stable": false, + "statement": "currently in `beta`", + "checked": "2026-11-17" + }, + "packages": [], + "artifacts": [ + { + "path": "src/protocols/acp/spec/2026-04-17/schema.agentic_checkout.json", + "revision": "6b828681206f1f98a3faba978610ced66770d2ae" + }, + { + "path": "tests/fixtures/acp/2026-04-17", + "revision": "6b828681206f1f98a3faba978610ced66770d2ae" + } + ], + "features": [ + { "name": "rest transport", "status": "experimental" }, + { "name": "well-known discovery", "status": "experimental" }, + { "name": "bearer authentication", "status": "experimental" }, + { "name": "API-Version enforcement", "status": "experimental" }, + { "name": "request header forwarding to the merchant", "status": "experimental" }, + { "name": "checkout service", "status": "experimental" }, + { "name": "createCheckoutSession", "status": "experimental" }, + { "name": "updateCheckoutSession", "status": "experimental" }, + { "name": "getCheckoutSession", "status": "experimental" }, + { "name": "completeCheckoutSession", "status": "experimental" }, + { "name": "cancelCheckoutSession", "status": "experimental" } + ], + "exclusions": [ + { + "name": "carts service", + "note": "The discovery document advertises only the checkout service." + }, + { "name": "feed service" }, + { "name": "standalone orders service" }, + { "name": "delegate_payment" }, + { "name": "delegate_authentication" }, + { "name": "ACP MCP transport binding" }, + { "name": "webhooks", "note": "The merchant backend sends ACP order webhooks itself." }, + { "name": "outbound merchant-to-agent delivery" }, + { "name": "ACP client role" }, + { + "name": "Signature header verification", + "note": "The adapter forwards the header to the merchant unverified." + }, + { + "name": "Timestamp replay-window verification", + "note": "The adapter forwards the header to the merchant unverified." + }, + { "name": "discount extension" }, + { "name": "general ACP extension framework" }, + { "name": "multiple ACP API versions" }, + { "name": "seller-backed payment handler integration" } + ], + "deviations": [ + { + "summary": "After a merchant 5xx, retrying the same Idempotency-Key returns 409 idempotency_unresolved unless protocols.acp.idempotency.merchantIdempotent is true. The merchant may have acted, so another execution could duplicate the order.", + "spec": "ACP RFC §6.5", + "tests": ["tests/conformance/acp/idempotency.test.ts", "tests/conformance/acp/errors.test.ts"] + } + ], + "conformance": { + "suite": "Our tests against the vendored schema and official examples; ACP publishes no conformance suite.", + "tests": [ + "tests/conformance/acp/checkout.test.ts", + "tests/conformance/acp/errors.test.ts", + "tests/conformance/acp/idempotency.test.ts", + "tests/conformance/acp/protocol.test.ts", + "tests/conformance/acp/snapshot.test.ts" + ], + "skipped": [] + }, + "gaps": [], + "docs": ["docs/protocols/acp.md"] +} diff --git a/src/support/ap2.json b/src/support/ap2.json new file mode 100644 index 0000000..cb00fc7 --- /dev/null +++ b/src/support/ap2.json @@ -0,0 +1,88 @@ +{ + "name": "ap2", + "kind": "authorization", + "title": "AP2", + "status": "experimental", + "role": "Authorization method, not a payment rail: a paid resource can require a verified mandate in addition to its x402 or MPP payment, never instead of it.", + "subset": "closed Checkout Mandate verification before settlement", + "spec": { + "revisions": ["v0.2.0"], + "display": "v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode", + "source": { + "repo": "google-agentic-commerce/AP2", + "commit": "b4587ac1d055888a73b4b21750973cffba961793" + }, + "stable": false, + "statement": "Standardization of the specification will continue within the Agentic Authentication Technical and Payments Technical Working Groups in FIDO", + "checked": "2026-11-17" + }, + "packages": [ + { "name": "jose", "use": "runtime" }, + { "name": "@sd-jwt/core", "use": "runtime" }, + { "name": "canonicalize", "use": "runtime" } + ], + "artifacts": [ + { + "path": "tests/fixtures/ap2/v0.2.0", + "revision": "b4587ac1d055888a73b4b21750973cffba961793" + } + ], + "features": [ + { "name": "direct-mode", "status": "experimental" }, + { "name": "trusted-agent-provider", "status": "experimental" }, + { "name": "mandate.checkout.1", "status": "experimental" }, + { "name": "sd-jwt-presentation", "status": "experimental" }, + { "name": "ES256", "status": "experimental" }, + { "name": "sha-256", "status": "experimental" }, + { "name": "static-inline-trust", "status": "experimental" }, + { "name": "merchant-checkout-jwt-binding", "status": "experimental" }, + { "name": "agent-commerce/ap2/checkout/v1", "status": "experimental" }, + { "name": "purchase-binding", "status": "experimental" }, + { "name": "replay-defence", "status": "experimental" } + ], + "exclusions": [ + { "name": "autonomous mode" }, + { + "name": "open checkout mandates (mandate.checkout.open.1)", + "note": "Rejected because the provider does not evaluate spending constraints." + }, + { "name": "payment mandates (mandate.payment.1)" }, + { "name": "spending constraint evaluation" }, + { "name": "cnf-bound agent keys" }, + { "name": "user credential delegation (OpenID4VP)" }, + { "name": "delegation chains and key-binding JWTs" }, + { + "name": "JWKS and any key discovery by URL (jku, x5u)", + "note": "Operators supply all keys in config." + }, + { "name": "issuer metadata fetching" }, + { "name": "remote revocation" }, + { "name": "key rotation without a config change" }, + { "name": "signature algorithms other than ES256" }, + { "name": "digest algorithms other than sha-256" }, + { "name": "mandate issuance" }, + { "name": "checkout receipts" }, + { + "name": "AP2 transport adapter or /.well-known/ap2", + "note": "HTTP, MCP and A2A carry the mandate in the gateway's own carriers; AP2 v0.2.0 defines none." + }, + { "name": "AP2 as a payment rail" }, + { "name": "AP2 over the ACP checkout adapter" } + ], + "deviations": [], + "conformance": { + "suite": "Tests using mandates minted by the AP2 v0.2.0 reference SDK, plus end-to-end refusal cases.", + "tests": [ + "tests/unit/authorization-ap2/sdk-vectors.test.ts", + "tests/integration/ap2-x402-conformance.test.ts" + ], + "skipped": [] + }, + "gaps": [ + { + "requirement": "Return a Checkout Receipt once the merchant has accepted or rejected a Checkout Mandate", + "state": "open" + } + ], + "docs": ["docs/protocols/ap2.md"] +} diff --git a/src/support/claims.ts b/src/support/claims.ts new file mode 100644 index 0000000..7589252 --- /dev/null +++ b/src/support/claims.ts @@ -0,0 +1,34 @@ +/** + * Read support status, feature status and exclusion names for descriptors, + * discovery and `doctor`, without loading external packages. + * `scripts/support-record.ts` validates records in tests and tooling; runtime + * readers trust them. + */ +import { CommerceError } from '../core/errors'; + +/** The fields of a support record that runtime code reads */ +export interface SupportClaims { + readonly status: string; + readonly features: readonly { readonly name: string; readonly status: string }[]; + readonly exclusions: readonly { readonly name: string }[]; +} + +export type FeatureStatus = 'supported' | 'experimental' | 'partial'; + +/** Maps `supported` to `stable` without changing the descriptor's status union */ +export function descriptorStatus(record: SupportClaims): 'stable' | 'experimental' { + return record.status === 'supported' ? 'stable' : 'experimental'; +} + +/** The strings a descriptor publishes in `unsupported` */ +export function exclusionNames(record: SupportClaims): readonly string[] { + return record.exclusions.map((exclusion) => exclusion.name); +} + +export function featureStatus(record: SupportClaims, name: string): FeatureStatus { + const feature = record.features.find((candidate) => candidate.name === name); + if (feature === undefined) { + throw new CommerceError('INTERNAL_ERROR', `support record has no feature "${name}"`); + } + return feature.status as FeatureStatus; +} diff --git a/src/support/http.json b/src/support/http.json new file mode 100644 index 0000000..f14cca7 --- /dev/null +++ b/src/support/http.json @@ -0,0 +1,15 @@ +{ + "name": "http", + "kind": "protocol", + "title": "HTTP", + "status": "supported", + "role": "Transport that carries x402 and MPP payments on each resource's invoke route.", + "subset": "resource routes and rail-specific payment headers", + "packages": [], + "artifacts": [], + "features": [], + "exclusions": [], + "deviations": [], + "gaps": [], + "docs": ["docs/protocols/http.md"] +} diff --git a/src/support/mcp.json b/src/support/mcp.json new file mode 100644 index 0000000..effa603 --- /dev/null +++ b/src/support/mcp.json @@ -0,0 +1,68 @@ +{ + "name": "mcp", + "kind": "protocol", + "title": "MCP", + "status": "supported", + "role": "Transport that carries x402 and MPP payments in tool calls.", + "subset": "tool discovery, invocation, payment-required and error mapping", + "spec": { + "revisions": ["2026-07-28", "2025-11-25"], + "display": "MCP `2026-07-28` and `2025-11-25`", + "source": { + "repo": "modelcontextprotocol/modelcontextprotocol", + "commit": "05aeb07b2db0c02adc4813a7c09f208ca8774152" + }, + "stable": true, + "statement": "Current: the current protocol version, which is ready for use and may continue to receive backwards compatible changes", + "checked": "2026-11-17" + }, + "packages": [ + { "name": "@modelcontextprotocol/server", "use": "runtime" }, + { "name": "@modelcontextprotocol/client", "use": "test" }, + { "name": "@modelcontextprotocol/sdk", "use": "test" } + ], + "artifacts": [], + "features": [ + { "name": "tools/list", "status": "supported" }, + { "name": "tools/call", "status": "supported" } + ], + "exclusions": [ + { "name": "resources" }, + { "name": "prompts" }, + { "name": "sampling" }, + { "name": "completions" }, + { "name": "elicitation" }, + { "name": "roots" }, + { "name": "logging" }, + { "name": "notifications/tools/list_changed" }, + { "name": "tasks" }, + { + "name": "dns-rebinding-protection", + "note": "The adapter relies on the gateway's onRequest hook to validate Host and Origin for the MCP mount." + }, + { "name": "authorization" }, + { "name": "sessions" }, + { "name": "subscriptions" }, + { "name": "pagination" }, + { "name": "HTTP+SSE transport" }, + { + "name": "MPP payment-required as JSON-RPC error -32042", + "note": "mppx reads challenges from the tool result's _meta." + }, + { + "name": "MPP verification failure as JSON-RPC error -32043", + "note": "mppx reads refusals from the tool result's _meta." + } + ], + "deviations": [], + "conformance": { + "suite": "Specification tests through the v1 and v2 SDK clients.", + "tests": [ + "tests/conformance/mcp/mcp-conformance.test.ts", + "tests/conformance/mcp/modern-era.test.ts" + ], + "skipped": [] + }, + "gaps": [], + "docs": ["docs/protocols/mcp.md"] +} diff --git a/src/support/mpp.json b/src/support/mpp.json new file mode 100644 index 0000000..ec0525c --- /dev/null +++ b/src/support/mpp.json @@ -0,0 +1,130 @@ +{ + "name": "mpp", + "kind": "payment", + "title": "MPP", + "status": "experimental", + "role": "Payment rail, carried by HTTP, MCP and A2A.", + "subset": "`charge`/`evm`/EIP-3009 over HTTP, MCP and A2A", + "spec": { + "revisions": [ + "draft-httpauth-payment-01", + "draft-payment-intent-charge-00", + "draft-evm-charge-00" + ], + "display": "drafts at `tempoxyz/mpp-specs@806fdb8`", + "source": { + "repo": "tempoxyz/mpp-specs", + "commit": "806fdb8b8c92cda5c84b8660558921b6bbeef7e0" + }, + "stable": false, + "statement": "Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time.", + "checked": "2026-11-17" + }, + "packages": [{ "name": "mppx", "use": "runtime" }], + "artifacts": [], + "features": [ + { "name": "intent=charge", "status": "experimental" }, + { "name": "method=evm", "status": "experimental" }, + { "name": "credential=authorization", "status": "experimental" }, + { "name": "eip-3009", "status": "experimental" }, + { "name": "network=eip155:31337", "status": "experimental" }, + { "name": "network=eip155:84532", "status": "experimental" }, + { "name": "network=eip155:8453", "status": "experimental" }, + { "name": "asset=USDC", "status": "experimental" }, + { "name": "verify-before-settle", "status": "experimental" }, + { "name": "authorization-flow", "status": "experimental" }, + { "name": "upfront-flow", "status": "experimental" }, + { "name": "payment-receipt", "status": "experimental" }, + { "name": "challenge-digest-binding", "status": "experimental" } + ], + "exclusions": [ + { "name": "methods other than evm" }, + { + "name": "credential=permit2", + "note": "The profile accepts only the EIP-3009 authorization credential." + }, + { "name": "credential=transaction" }, + { "name": "credential=hash" }, + { "name": "splits", "note": "The draft allows splits only with permit2 credentials." }, + { "name": "intent=subscription" }, + { "name": "evm sessions", "note": "A separate EVM draft, not an option of charge." }, + { "name": "discovery extension" } + ], + "deviations": [ + { + "summary": "The EIP-3009 nonce is keccak256 of JSON.stringify([id, realm]), as mppx 0.13 derives it, not of abi.encodePacked(id, realm); a credential using the draft's nonce fails with wrong_nonce.", + "spec": "draft-evm-charge-00", + "tests": ["tests/unit/payments-mpp/provider.test.ts"] + }, + { + "summary": "Over MCP, payment errors are tool results with isError and the challenges in _meta, not the JSON-RPC errors the draft maps them to (-32042, -32043, -32602 and -32603).", + "spec": "draft-payment-transport-mcp-00", + "tests": ["tests/integration/mcp-payment-bindings.test.ts"] + }, + { + "summary": "An unpaid request that gets a 402 also stores a resource.requested event beside the challenge.", + "spec": "draft-httpauth-payment-01 §11.4", + "tests": ["tests/unit/core/execution/pipeline.test.ts"] + }, + { + "summary": "A credential whose attempt is reserved or settlement-uncertain gets 409 without a fresh challenge, because a second challenge could lead to a second payment.", + "spec": "draft-httpauth-payment-01 §4.2; draft-evm-charge-00", + "tests": ["tests/integration/mpp-carriers.test.ts"] + }, + { + "summary": "With paymentFlow: authorization, the backend runs before the transfer, which the charge intent counts as partial access before payment. The default, upfront, settles first.", + "spec": "draft-payment-intent-charge-00", + "tests": ["tests/e2e/payment/mpp-settlement.e2e.test.ts"] + } + ], + "combinations": [ + { + "surface": "http", + "method": "mpp", + "level": "e2e", + "evidence": "tests/e2e/payment/mpp-settlement.e2e.test.ts" + }, + { + "surface": "http", + "method": "mpp", + "authorization": "ap2", + "level": "e2e", + "evidence": "tests/e2e/authorization/ap2-mpp.e2e.test.ts" + }, + { + "surface": "mcp", + "method": "mpp", + "level": "integration", + "evidence": "tests/integration/mcp-payment-bindings.test.ts" + }, + { + "surface": "a2a", + "method": "mpp", + "level": "integration", + "evidence": "tests/integration/mpp-carriers.test.ts" + }, + { + "surface": "http", + "method": "mpp", + "level": "testnet", + "evidence": "tests/testnet/mpp-base-sepolia.smoke.test.ts" + }, + { + "surface": "http", + "method": "mpp", + "level": "mainnet", + "evidence": "tests/mainnet/mpp-base.smoke.test.ts" + } + ], + "gaps": [ + { + "requirement": "Each challenge id is single-use (charge intent); two payers can each settle against one challenge", + "state": "open" + }, + { + "requirement": "Payment-Receipt only after an on-chain receipt with a matching Transfer log; the gateway trusts the facilitator's settle result", + "state": "open" + } + ], + "docs": ["docs/protocols/mpp.md"] +} diff --git a/src/support/x402.json b/src/support/x402.json new file mode 100644 index 0000000..5776fcd --- /dev/null +++ b/src/support/x402.json @@ -0,0 +1,127 @@ +{ + "name": "x402", + "kind": "payment", + "title": "x402", + "status": "supported", + "role": "Payment rail, carried by HTTP, MCP and A2A.", + "subset": "`exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding", + "spec": { + "revisions": ["v2"], + "display": "x402 v2", + "source": { + "repo": "x402-foundation/x402", + "commit": "51a0664c2b7826e3cb02595481eb6848a1b11815" + }, + "stable": null, + "statement": "Protocol Version: 2", + "checked": "2026-11-17" + }, + "packages": [ + { "name": "@x402/core", "use": "runtime" }, + { "name": "@x402/evm", "use": "runtime" }, + { "name": "@x402/svm", "use": "runtime" }, + { "name": "@x402/near", "use": "runtime" }, + { "name": "@x402/mcp", "use": "test" } + ], + "artifacts": [], + "features": [ + { "name": "exact-evm", "status": "supported" }, + { "name": "exact-svm", "status": "supported" }, + { "name": "exact-near", "status": "partial" }, + { "name": "local-facilitator", "status": "supported" }, + { "name": "remote-facilitator", "status": "supported" }, + { "name": "eip-3009", "status": "supported" }, + { "name": "permit2", "status": "supported" }, + { "name": "caip-2", "status": "supported" }, + { "name": "mode=local", "status": "supported" }, + { "name": "mode=testnet", "status": "supported" }, + { "name": "mode=mainnet", "status": "supported" }, + { "name": "authorization-flow", "status": "supported" }, + { "name": "upfront-flow", "status": "supported" }, + { "name": "multiple-offers", "status": "partial" }, + { + "name": "erc-8409-quotes", + "status": "experimental", + "spec": { + "revisions": ["0ee33230"], + "display": "draft `SergeevDmitry/ERCs@0ee33230`", + "source": { + "repo": "SergeevDmitry/ERCs", + "commit": "0ee33230ca9f9f41a714382552a47cd860465ca7" + }, + "stable": false, + "statement": "status: Draft", + "checked": "2026-11-17" + } + } + ], + "exclusions": [ + { "name": "permit2 gas sponsoring extensions" }, + { "name": "upto scheme" }, + { "name": "batch-settlement scheme" }, + { "name": "auth-capture scheme" }, + { + "name": "x402 v1", + "note": "A payload declaring an x402Version other than 2 is refused as invalid_x402_version on every carrier." + }, + { "name": "payer-bound quotes", "feature": "erc-8409-quotes" }, + { + "name": "contract quote issuers (ERC-1271, ERC-6492, EIP-7702 delegates)", + "feature": "erc-8409-quotes" + }, + { + "name": "quote consumption, single-use enforcement or revocation", + "feature": "erc-8409-quotes" + }, + { "name": "quote client nonces", "feature": "erc-8409-quotes" }, + { "name": "quotes for MPP, Solana or NEAR", "feature": "erc-8409-quotes" }, + { + "name": "signed receipts and the x402 offer-receipt extension", + "feature": "erc-8409-quotes" + }, + { "name": "remote quote signers and KMS", "feature": "erc-8409-quotes" }, + { "name": "per-resource quote toggles", "feature": "erc-8409-quotes" } + ], + "deviations": [], + "combinations": [ + { + "surface": "http", + "method": "x402", + "level": "e2e", + "evidence": "tests/e2e/payment/x402-settlement.e2e.test.ts" + }, + { + "surface": "a2a", + "method": "x402", + "level": "e2e", + "evidence": "tests/e2e/payment/x402-settlement.e2e.test.ts" + }, + { + "surface": "http", + "method": "x402", + "authorization": "ap2", + "level": "e2e", + "evidence": "tests/e2e/authorization/ap2-x402.e2e.test.ts" + }, + { + "surface": "mcp", + "method": "x402", + "level": "integration", + "evidence": "tests/integration/mcp-payment-bindings.test.ts" + }, + { + "surface": "http", + "method": "x402", + "level": "testnet", + "evidence": "tests/testnet/x402.smoke.test.ts" + }, + { + "surface": "http", + "method": "x402", + "level": "mainnet", + "evidence": "tests/mainnet/x402.smoke.test.ts" + } + ], + "gaps": [], + "docs": ["docs/protocols/x402.md"] +} diff --git a/tests/integration/goldens/2.7.2/doctor-multi.json b/tests/integration/goldens/2.7.2/doctor-multi.json index 564c6e7..0c1d718 100644 --- a/tests/integration/goldens/2.7.2/doctor-multi.json +++ b/tests/integration/goldens/2.7.2/doctor-multi.json @@ -28,7 +28,7 @@ { "name": "A2A unsupported", "status": "INFO", - "detail": "SendStreamingMessage, GetTask, ListTasks, CancelTask, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, long-running task persistence, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, x402 extension payments across gateway instances" + "detail": "SendStreamingMessage, GetTask, ListTasks, CancelTask, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, long-running task persistence, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, text parts, file and URL parts (including inline bytes), multi-part messages, message roles other than ROLE_USER, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, x402 extension payments across gateway instances" }, { "name": "ACP", @@ -78,7 +78,7 @@ { "name": "AP2 unsupported", "status": "INFO", - "detail": "autonomous mode, open checkout mandates (mandate.checkout.open.1), payment mandates (mandate.payment.1), spending constraint evaluation, cnf-bound agent keys, user credential delegation (OpenID4VP), delegation chains and key-binding JWTs, JWKS and any key discovery by URL (jku, x5u), issuer metadata fetching, key rotation without a config change, signature algorithms other than ES256, digest algorithms other than sha-256, mandate issuance, checkout receipts, AP2 over the ACP checkout adapter" + "detail": "autonomous mode, open checkout mandates (mandate.checkout.open.1), payment mandates (mandate.payment.1), spending constraint evaluation, cnf-bound agent keys, user credential delegation (OpenID4VP), delegation chains and key-binding JWTs, JWKS and any key discovery by URL (jku, x5u), issuer metadata fetching, remote revocation, key rotation without a config change, signature algorithms other than ES256, digest algorithms other than sha-256, mandate issuance, checkout receipts, AP2 transport adapter or /.well-known/ap2, AP2 as a payment rail, AP2 over the ACP checkout adapter" }, { "name": "Payments", diff --git a/tests/integration/goldens/2.7.2/doctor-single.json b/tests/integration/goldens/2.7.2/doctor-single.json index 2901a3d..d02f3e6 100644 --- a/tests/integration/goldens/2.7.2/doctor-single.json +++ b/tests/integration/goldens/2.7.2/doctor-single.json @@ -28,7 +28,7 @@ { "name": "A2A unsupported", "status": "INFO", - "detail": "SendStreamingMessage, GetTask, ListTasks, CancelTask, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, long-running task persistence, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, x402 extension payments across gateway instances" + "detail": "SendStreamingMessage, GetTask, ListTasks, CancelTask, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, long-running task persistence, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, text parts, file and URL parts (including inline bytes), multi-part messages, message roles other than ROLE_USER, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, x402 extension payments across gateway instances" }, { "name": "ACP", @@ -78,7 +78,7 @@ { "name": "AP2 unsupported", "status": "INFO", - "detail": "autonomous mode, open checkout mandates (mandate.checkout.open.1), payment mandates (mandate.payment.1), spending constraint evaluation, cnf-bound agent keys, user credential delegation (OpenID4VP), delegation chains and key-binding JWTs, JWKS and any key discovery by URL (jku, x5u), issuer metadata fetching, key rotation without a config change, signature algorithms other than ES256, digest algorithms other than sha-256, mandate issuance, checkout receipts, AP2 over the ACP checkout adapter" + "detail": "autonomous mode, open checkout mandates (mandate.checkout.open.1), payment mandates (mandate.payment.1), spending constraint evaluation, cnf-bound agent keys, user credential delegation (OpenID4VP), delegation chains and key-binding JWTs, JWKS and any key discovery by URL (jku, x5u), issuer metadata fetching, remote revocation, key rotation without a config change, signature algorithms other than ES256, digest algorithms other than sha-256, mandate issuance, checkout receipts, AP2 transport adapter or /.well-known/ap2, AP2 as a payment rail, AP2 over the ACP checkout adapter" }, { "name": "Payments", diff --git a/tests/integration/goldens/2.7.2/well-known-multi.json b/tests/integration/goldens/2.7.2/well-known-multi.json index 9a3415e..7462b21 100644 --- a/tests/integration/goldens/2.7.2/well-known-multi.json +++ b/tests/integration/goldens/2.7.2/well-known-multi.json @@ -90,6 +90,10 @@ "task resumption other than an x402 extension payment", "push notifications", "multi-turn conversational continuation", + "text parts", + "file and URL parts (including inline bytes)", + "multi-part messages", + "message roles other than ROLE_USER", "authenticated extended agent cards", "A2A authentication schemes", "artifact types beyond Agent Commerce outcome data", @@ -164,7 +168,16 @@ "permit2 gas sponsoring extensions", "upto scheme", "batch-settlement scheme", - "auth-capture scheme" + "auth-capture scheme", + "x402 v1", + "payer-bound quotes", + "contract quote issuers (ERC-1271, ERC-6492, EIP-7702 delegates)", + "quote consumption, single-use enforcement or revocation", + "quote client nonces", + "quotes for MPP, Solana or NEAR", + "signed receipts and the x402 offer-receipt extension", + "remote quote signers and KMS", + "per-resource quote toggles" ] }, { @@ -230,11 +243,14 @@ "delegation chains and key-binding JWTs", "JWKS and any key discovery by URL (jku, x5u)", "issuer metadata fetching", + "remote revocation", "key rotation without a config change", "signature algorithms other than ES256", "digest algorithms other than sha-256", "mandate issuance", "checkout receipts", + "AP2 transport adapter or /.well-known/ap2", + "AP2 as a payment rail", "AP2 over the ACP checkout adapter" ] } diff --git a/tests/integration/goldens/2.7.2/well-known-single.json b/tests/integration/goldens/2.7.2/well-known-single.json index e64b53f..277a502 100644 --- a/tests/integration/goldens/2.7.2/well-known-single.json +++ b/tests/integration/goldens/2.7.2/well-known-single.json @@ -90,6 +90,10 @@ "task resumption other than an x402 extension payment", "push notifications", "multi-turn conversational continuation", + "text parts", + "file and URL parts (including inline bytes)", + "multi-part messages", + "message roles other than ROLE_USER", "authenticated extended agent cards", "A2A authentication schemes", "artifact types beyond Agent Commerce outcome data", @@ -162,7 +166,16 @@ "permit2 gas sponsoring extensions", "upto scheme", "batch-settlement scheme", - "auth-capture scheme" + "auth-capture scheme", + "x402 v1", + "payer-bound quotes", + "contract quote issuers (ERC-1271, ERC-6492, EIP-7702 delegates)", + "quote consumption, single-use enforcement or revocation", + "quote client nonces", + "quotes for MPP, Solana or NEAR", + "signed receipts and the x402 offer-receipt extension", + "remote quote signers and KMS", + "per-resource quote toggles" ] }, { @@ -228,11 +241,14 @@ "delegation chains and key-binding JWTs", "JWKS and any key discovery by URL (jku, x5u)", "issuer metadata fetching", + "remote revocation", "key rotation without a config change", "signature algorithms other than ES256", "digest algorithms other than sha-256", "mandate issuance", "checkout receipts", + "AP2 transport adapter or /.well-known/ap2", + "AP2 as a payment rail", "AP2 over the ACP checkout adapter" ] } diff --git a/tests/integration/support-record.test.ts b/tests/integration/support-record.test.ts new file mode 100644 index 0000000..481fdf4 --- /dev/null +++ b/tests/integration/support-record.test.ts @@ -0,0 +1,212 @@ +/** + * Check support records against the descriptors that publish their claims. + * Descriptors derive status and unsupported features from the records; these + * tests also compare capabilities and revisions with their values in code. + */ +import { existsSync, readdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { LATEST_PROTOCOL_VERSION } from '@modelcontextprotocol/server'; +import { describe, expect, expectTypeOf, it } from 'vitest'; +import { + citedPaths, + REPO_ROOT, + readSupportRecord, + SUPPORT_RECORD_NAMES, + type SupportRecord, + type SupportRecordName, +} from '../../scripts/support-record'; +import { AP2_CAPABILITIES, AP2_UNSUPPORTED } from '../../src/ap2'; +import { AP2_SPEC_VERSION } from '../../src/authorization/ap2/constants'; +import { buildAp2Descriptor } from '../../src/authorization/ap2/descriptor'; +import { parseConfig } from '../../src/config'; +import { type AdapterDescriptor, NOOP_LOGGER } from '../../src/core'; +import { createConfiguredPaymentProviders } from '../../src/gateway/payment-providers'; +import { MPP_DESCRIPTOR } from '../../src/mpp'; +import { MPP_SPEC_COMMIT, MPP_SPEC_DRAFTS } from '../../src/payments/mpp/constants'; +import { X402_VERSION } from '../../src/payments/x402/provider/constants'; +import { A2A_SPEC_VERSION, A2A_UNSUPPORTED_METHODS } from '../../src/protocols/a2a/constants'; +import { buildDescriptor as buildA2aDescriptor } from '../../src/protocols/a2a/descriptor'; +import { ACP_SPEC_VERSION } from '../../src/protocols/acp/constants'; +import { buildDescriptor as buildAcpDescriptor } from '../../src/protocols/acp/descriptor'; +import { MCP_MODERN_PROTOCOL_REVISION } from '../../src/protocols/mcp/constants'; +import { buildDescriptor as buildMcpDescriptor } from '../../src/protocols/mcp/descriptor'; + +const records = Object.fromEntries( + SUPPORT_RECORD_NAMES.map((name) => [name, readSupportRecord(name)]), +) as Record; + +const featureNames = (record: SupportRecord) => record.features.map((feature) => feature.name); +const exclusionNames = (record: SupportRecord) => record.exclusions.map((entry) => entry.name); +const descriptorStatus = (record: SupportRecord) => + record.status === 'supported' ? 'stable' : 'experimental'; + +describe('support records', () => { + it('holds exactly one valid record per shipped profile, each named after its file', () => { + const files = readdirSync(join(REPO_ROOT, 'src/support')) + .filter((file) => file.endsWith('.json')) + .map((file) => file.slice(0, -'.json'.length)) + .sort(); + expect(files).toEqual([...SUPPORT_RECORD_NAMES].sort()); + for (const name of SUPPORT_RECORD_NAMES) expect(records[name].name).toBe(name); + }); + + it('cites only evidence and documentation files that exist', () => { + const missing = SUPPORT_RECORD_NAMES.flatMap((name) => + citedPaths(records[name]) + .filter((path) => !existsSync(join(REPO_ROOT, path))) + .map((path) => `src/support/${name}.json: ${path}`), + ); + expect(missing).toEqual([]); + }); + + it('lists tested combinations on the payment records only', () => { + expect(SUPPORT_RECORD_NAMES.filter((name) => records[name].combinations !== undefined)).toEqual( + ['x402', 'mpp'], + ); + }); +}); + +describe('descriptors publish their record', () => { + const cases: [SupportRecordName, AdapterDescriptor][] = [ + ['mcp', buildMcpDescriptor('test')], + ['a2a', buildA2aDescriptor('test')], + ['acp', buildAcpDescriptor('test')], + ['ap2', buildAp2Descriptor('test')], + ['mpp', MPP_DESCRIPTOR], + ]; + + it.each(cases)('%s: status, unsupported, capabilities and revision', (name, descriptor) => { + const record = records[name]; + expect(descriptor.status).toBe(descriptorStatus(record)); + expect(descriptor.unsupported).toEqual(exclusionNames(record)); + expect(descriptor.capabilities).toEqual(featureNames(record)); + expect(descriptor.supportedSpec).toContain(record.spec?.revisions[0]); + }); + + it('a2a: the record excludes every method the transport refuses', () => { + expect(exclusionNames(records.a2a)).toEqual( + expect.arrayContaining([...A2A_UNSUPPORTED_METHODS]), + ); + }); +}); + +// LOCAL DEVELOPMENT ONLY - DO NOT FUND: Anvil accounts 1 and 3 +const LOCAL_SIGNER = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d'; +const QUOTE_SIGNER = '0x7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6'; +const MERCHANT = '0x1111111111111111111111111111111111111111'; +const REMOTE = { mode: 'remote', url: 'https://facilitator.example', auth: { type: 'none' } }; + +// These configurations collectively enable every recorded x402 capability +const X402_MATRIX: Record> = { + 'local chain, in-process facilitator': { + network: 'eip155:31337', + rpcUrl: 'http://127.0.0.1:8545', + asset: '0x5FbDB2315678afecb367f032d93F642f64180aa3', + assetName: 'MockUSDC', + assetVersion: '2', + assetDecimals: 6, + payTo: MERCHANT, + facilitator: { mode: 'local', signerPrivateKey: LOCAL_SIGNER }, + }, + 'public testnets, several offers and families, quotes': { + networks: { + 'eip155:84532': { rpcUrl: 'https://base-sepolia.example' }, + 'eip155:421614': { rpcUrl: 'https://arbitrum-sepolia.example' }, + 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1': { rpcUrl: 'https://solana-devnet.example' }, + 'near:testnet': { rpcUrl: 'https://near-testnet.example' }, + }, + options: [ + { network: 'eip155:84532', payTo: MERCHANT }, + { network: 'eip155:421614', payTo: MERCHANT, assetTransferMethod: 'permit2' }, + { + network: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1', + payTo: '9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM', + }, + { network: 'near:testnet', payTo: 'merchant.testnet' }, + ], + facilitator: REMOTE, + quote: { enabled: true, signerPrivateKey: QUOTE_SIGNER }, + }, + 'Base mainnet': { + network: 'eip155:8453', + rpcUrl: 'https://base-mainnet.example', + payTo: MERCHANT, + facilitator: REMOTE, + allowMainnet: true, + allowUnauthenticatedFacilitator: true, + }, +}; + +async function x402Descriptor(x402: Record): Promise { + const config = parseConfig( + { + version: 1, + merchant: { id: 'shop', name: 'Shop', publicBaseUrl: 'https://shop.example' }, + server: { port: 8080, host: '127.0.0.1' }, + storage: { receipts: { driver: 'sqlite', path: ':memory:' } }, + protocols: { http: { enabled: true }, mcp: { enabled: false, mountPath: '/mcp' } }, + resources: { + report: { + name: 'Report', + backend: { type: 'http', method: 'GET', url: 'http://localhost:3000/report' }, + pricing: { type: 'fixed', amount: '0.01', currency: 'USDC' }, + expose: ['http'], + payments: ['x402'], + }, + }, + payments: { x402: { enabled: true, maxTimeoutSeconds: 120, ...x402 } }, + }, + {}, + ); + const [provider] = await createConfiguredPaymentProviders(config.payments, NOOP_LOGGER); + if (provider === undefined) throw new Error('no x402 provider was built'); + return provider.descriptor; +} + +describe('x402 descriptor across the configuration matrix', () => { + it('claims only recorded features, and the matrix reaches all of them', async () => { + const record = records.x402; + const seen = new Set(); + for (const [label, x402] of Object.entries(X402_MATRIX)) { + const descriptor = await x402Descriptor(x402); + expect(featureNames(record), label).toEqual( + expect.arrayContaining([...descriptor.capabilities]), + ); + expect(descriptor.status, label).toBe(descriptorStatus(record)); + expect(descriptor.unsupported, label).toEqual(exclusionNames(record)); + expect(descriptor.supportedSpec, label).toContain(record.spec?.revisions[0]); + for (const capability of descriptor.capabilities) seen.add(capability); + } + expect([...seen].sort()).toEqual(featureNames(record).sort()); + }); +}); + +describe('revisions the records restate from code', () => { + it('mcp: the modern revision and the SDK latest legacy one', () => { + expect(records.mcp.spec?.revisions).toEqual([ + MCP_MODERN_PROTOCOL_REVISION, + LATEST_PROTOCOL_VERSION, + ]); + }); + + it('a2a, acp, ap2 and x402: the pinned revision', () => { + expect(records.a2a.spec?.revisions).toEqual([A2A_SPEC_VERSION]); + expect(records.acp.spec?.revisions).toEqual([ACP_SPEC_VERSION]); + expect(records.ap2.spec?.revisions).toEqual([`v${AP2_SPEC_VERSION}`]); + expect(records.x402.spec?.revisions).toEqual([`v${X402_VERSION}`]); + }); + + it('mpp: the three pinned drafts and their commit', () => { + expect(records.mpp.spec?.revisions).toEqual(Object.values(MPP_SPEC_DRAFTS)); + expect(records.mpp.spec?.source.commit).toBe(MPP_SPEC_COMMIT); + }); +}); + +describe('published exports derived from a record keep their 2.7 types', () => { + it('AP2_UNSUPPORTED, AP2_CAPABILITIES and MPP_DESCRIPTOR', () => { + // Checked by tsc: a JSON import would otherwise widen or narrow these + expectTypeOf(AP2_UNSUPPORTED).toEqualTypeOf(); + expectTypeOf(AP2_CAPABILITIES).toEqualTypeOf(); + expectTypeOf(MPP_DESCRIPTOR).toEqualTypeOf(); + }); +}); diff --git a/tests/mainnet/x402.smoke.test.ts b/tests/mainnet/x402.smoke.test.ts index 7f6d816..a3da695 100644 --- a/tests/mainnet/x402.smoke.test.ts +++ b/tests/mainnet/x402.smoke.test.ts @@ -2,11 +2,11 @@ * x402 settlement on mainnets. **This spends real money.** * * Only `npm run test:mainnet` runs it, never CI. Nothing runs unless - * `X402_SMOKE_TARGETS` names allowlisted targets (`base`, `base-permit2`, `solana`) and - * `ALLOW_X402_MAINNET=true` is set; each target also needs a funded buyer, a - * merchant address and an explicit facilitator. The run stops before signing - * anything when it would exceed its spend cap. The harness lives in - * tests/fixtures/x402/smoke. + * `X402_SMOKE_TARGETS` names allowlisted targets (`base`, `base-permit2`, + * `solana`, `near`) and `ALLOW_X402_MAINNET=true` is set. Each target needs a + * funded buyer, a merchant address and an explicit facilitator; NEAR can use a + * relayer instead. The run stops before signing anything that would exceed + * its spend cap. The harness lives in tests/fixtures/x402/smoke. */ import { defineSmokeSuite } from '../fixtures/x402/smoke/suite'; diff --git a/tests/unit/deploy/deploy.test.ts b/tests/unit/deploy/deploy.test.ts index 8d78b0e..12f3f20 100644 --- a/tests/unit/deploy/deploy.test.ts +++ b/tests/unit/deploy/deploy.test.ts @@ -122,4 +122,21 @@ describe('deploy/', () => { expect(version, name).toBe(pkg.peerDependencies[name as string]); } }); + + it("CI's clean consumer install pins the optional peers package.json declares", () => { + const workflow = readFileSync(join(REPO_ROOT, '.github/workflows/ci.yml'), 'utf8'); + const installs = [...workflow.matchAll(/^\s+npm install ((?:@?[\w./-]+@\d\S* ?)+)$/gm)]; + expect(installs).toHaveLength(1); + const pins = (installs[0]?.[1] ?? '').split(' ').map((spec) => { + const at = spec.lastIndexOf('@'); + return [spec.slice(0, at), spec.slice(at + 1)] as const; + }); + expect(pins.map(([name]) => name)).toEqual([ + '@modelcontextprotocol/server', + '@x402/core', + '@x402/evm', + 'viem', + ]); + for (const [name, version] of pins) expect(version, name).toBe(pkg.peerDependencies[name]); + }); }); diff --git a/tests/unit/payments-mpp/profile.test.ts b/tests/unit/payments-mpp/profile.test.ts index 5b09640..ec3cb7a 100644 --- a/tests/unit/payments-mpp/profile.test.ts +++ b/tests/unit/payments-mpp/profile.test.ts @@ -29,6 +29,17 @@ describe('pinned MPP profile', () => { expect(installed.version).toBe(MPPX_VERSION); }); + it('pins the mppx version package.json declares, as a peer and for development', () => { + // The installed copy can lag package.json until the next install + const pkg = JSON.parse( + readFileSync(new URL('../../../package.json', import.meta.url), 'utf8'), + ) as Record<'peerDependencies' | 'devDependencies', Record>; + expect([pkg.peerDependencies['mppx'], pkg.devDependencies['mppx']]).toEqual([ + MPPX_VERSION, + MPPX_VERSION, + ]); + }); + it('records a full upstream commit, not a branch or a short sha', () => { expect(MPP_SPEC_COMMIT).toMatch(/^[0-9a-f]{40}$/); }); From 1a6d1a0760b96994f61676c9b97aa370b32134ed Mon Sep 17 00:00:00 2001 From: Revinand Date: Wed, 18 Nov 2026 14:17:17 +0100 Subject: [PATCH 04/14] feat: generate support tables and fail on drift --- README.md | 32 +- docs/contributing-adapters.md | 10 +- docs/protocols.md | 75 +++- docs/protocols/a2a.md | 52 ++- docs/protocols/acp.md | 53 ++- docs/protocols/ap2.md | 59 ++- docs/protocols/mcp.md | 44 +- docs/protocols/mpp.md | 61 ++- docs/protocols/x402.md | 57 ++- package.json | 1 + scripts/support-record.ts | 519 ++++++++++++++++++++++- src/support/a2a.json | 2 +- src/support/acp.json | 4 +- src/support/mcp.json | 6 +- src/support/mpp.json | 12 +- src/support/x402.json | 7 +- tests/integration/support-record.test.ts | 197 ++++++++- 17 files changed, 1079 insertions(+), 112 deletions(-) diff --git a/README.md b/README.md index ad9f36d..fc75434 100644 --- a/README.md +++ b/README.md @@ -8,12 +8,14 @@ Quickstart License TypeScript + MCP x402 MPP A2A ACP AP2 +

## What it is, in ten seconds @@ -303,17 +305,22 @@ See [docs/configuration.md](docs/configuration.md). ## Protocol support -| Protocol | Status | Pinned revision | -| ------------ | ------------ | ------------------------------------------------------------------------------------------------------------ | -| **HTTP** | Supported | native routes | -| **MCP** | Supported | `2026-07-28` and `2025-11-25`, `@modelcontextprotocol/server@2.3.0` | -| **x402** | Supported | x402 v2 (`@x402/core`, `@x402/evm`, `@x402/svm`, `@x402/near`), scheme `exact`, EVM and Solana; NEAR partial | -| **MPP** | Experimental | `mppx@0.13.1`, `charge` + `evm` + EIP-3009, USDC on Base Sepolia and Base | -| **A2A** | Experimental | A2A v1.0.1, binding `JSONRPC`, method `SendMessage`, x402 extension | -| **ACP** | Experimental | ACP `2026-04-17`, REST checkout + discovery | -| **AP2** | Experimental | AP2 `v0.2.0`, Direct Checkout Mandate verification | -| **ERC-8409** | Experimental | draft `SergeevDmitry/ERCs@0ee33230`: signed quotes on x402 EVM offers | -| UCP | Planned | no implementation | + + +| Protocol | Status | Pinned revision | Implemented subset | +| ------------ | ------------ | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| **HTTP** | Supported | native | resource routes and rail-specific payment headers | +| **MCP** | Supported | MCP `2026-07-28` and `2025-11-25`; `@modelcontextprotocol/server@2.3.0` | tool discovery, invocation, payment-required and error mapping | +| **x402** | Supported | x402 v2; `@x402/core@2.30.0`, `@x402/evm@2.30.0`, `@x402/svm@2.30.0`, `@x402/near@2.30.0` | `exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding | +| **MPP** | Experimental | drafts at `tempoxyz/mpp-specs@806fdb8`; `mppx@0.13.1` | `charge`/`evm`/EIP-3009 with USDC on Base Sepolia and Base, over HTTP, MCP and A2A | +| **A2A** | Experimental | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage`, paid flow and the x402 extension | +| **ACP** | Experimental | stable snapshot `2026-04-17`; REST binding | discovery and the five checkout operations | +| **AP2** | Experimental | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode; `jose@6.2.12`, `@sd-jwt/core@0.20.1`, `canonicalize@5.0.0` | closed Checkout Mandate verification before settlement | +| **ERC-8409** | Experimental | draft `SergeevDmitry/ERCs@0ee33230` | signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce` | + + + +UCP is planned and has no implementation. [AP2](docs/protocols/ap2.md) is an authorization method, not a transport. It verifies a mandate before a paid resource settles; the gateway does not issue the mandate @@ -339,6 +346,9 @@ MPP, A2A, ACP, AP2, ERC-8409 quotes, `agent-commerce import openapi`, 2.6.0, the `idempotency` resource settings with the store and provider methods added in 2.7.0, and the `./testing` entry. +A profile moves from experimental to supported only when it meets the +[promotion criteria](docs/protocols.md#promotion-criteria). + The journal's `Transaction` type, `ReceiptStore` journal methods and `/api/transactions` response shape are supported. The `transactionId` fields, `receiptCommitted` and flags accepted by `reconcile` and `resolve` are also diff --git a/docs/contributing-adapters.md b/docs/contributing-adapters.md index c0a7cb0..fa309ca 100644 --- a/docs/contributing-adapters.md +++ b/docs/contributing-adapters.md @@ -31,9 +31,13 @@ A new name crosses the public contract and runtime wiring. After approval: 5. If it has distinct optional dependencies, add the narrow subpath, build entry, package export, optional peer and the real-package check in `tests/unit/cli/packaging.test.ts`. -6. Add a support record under `src/support/`, a descriptor, and discovery and - `doctor` output. Update the frozen contract and conformance coverage. Add a - page under `docs/protocols/` and list it in [protocols.md](protocols.md). +6. Add a support record under `src/support/` and its name to + `SUPPORT_RECORD_NAMES` in `scripts/support-record.ts`. Add a descriptor, + and discovery and `doctor` output. Update the frozen contract and + conformance coverage. Add a page under `docs/protocols/` with the region + markers its record needs, list it in [protocols.md](protocols.md), and run + `npm run support:write`. `tests/integration/support-record.test.ts` names + any region that is missing or out of date. ## Protocol adapters diff --git a/docs/protocols.md b/docs/protocols.md index e64e7a9..d75f726 100644 --- a/docs/protocols.md +++ b/docs/protocols.md @@ -5,20 +5,23 @@ subset. Each protocol's page describes that subset in detail. ## Support matrix -| Protocol | Status | Revision | Implemented subset | -| ------------ | ------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | -| **HTTP** | Supported | native | resource routes and rail-specific payment headers | -| **MCP** | Supported | MCP `2026-07-28` and `2025-11-25` through `@modelcontextprotocol/server@2.3.0` | tool discovery, invocation, payment-required and error mapping | -| **x402** | Supported | x402 v2, `@x402/core@2.30.0`, `@x402/evm@2.30.0`, `@x402/svm@2.30.0`, `@x402/near@2.30.0` | `exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding | -| **A2A** | Experimental | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage`, paid flow and the x402 extension | -| **ACP** | Experimental | stable snapshot `2026-04-17`; REST binding | discovery and the five checkout operations | -| **AP2** | Experimental | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode | closed Checkout Mandate verification before settlement | -| **MPP** | Experimental | drafts at `tempoxyz/mpp-specs@806fdb8`; `mppx@0.13.1` | `charge`/`evm`/EIP-3009 over HTTP, MCP and A2A | -| **ERC-8409** | Experimental | draft `SergeevDmitry/ERCs@0ee33230` | signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce` | -| UCP | Planned | - | no implementation | + + +| Protocol | Status | Role | Revision | Implemented subset | +| ------------ | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| **HTTP** | Supported | Transport that carries x402 and MPP payments on each resource's invoke route. | native | resource routes and rail-specific payment headers | +| **MCP** | Supported | Transport that carries x402 and MPP payments in tool calls. | MCP `2026-07-28` and `2025-11-25`; `@modelcontextprotocol/server@2.3.0` | tool discovery, invocation, payment-required and error mapping | +| **x402** | Supported | Payment rail, carried by HTTP, MCP and A2A. | x402 v2; `@x402/core@2.30.0`, `@x402/evm@2.30.0`, `@x402/svm@2.30.0`, `@x402/near@2.30.0` | `exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding | +| **MPP** | Experimental | Payment rail, carried by HTTP, MCP and A2A. | drafts at `tempoxyz/mpp-specs@806fdb8`; `mppx@0.13.1` | `charge`/`evm`/EIP-3009 with USDC on Base Sepolia and Base, over HTTP, MCP and A2A | +| **A2A** | Experimental | Transport that carries x402 and MPP payments in `SendMessage`, including through the x402 extension. | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage`, paid flow and the x402 extension | +| **ACP** | Experimental | Checkout API that forwards checkout operations to the merchant, whose payment handler receives `payment_data`. Gateway checkout routes are free and carry no x402 or MPP payment. | stable snapshot `2026-04-17`; REST binding | discovery and the five checkout operations | +| **AP2** | Experimental | Authorization method, not a payment rail: a paid resource can require a verified mandate in addition to its x402 or MPP payment, never instead of it. | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode; `jose@6.2.12`, `@sd-jwt/core@0.20.1`, `canonicalize@5.0.0` | closed Checkout Mandate verification before settlement | +| **ERC-8409** | Experimental | x402 feature: EIP-712 signed quotes on the EVM offers of a challenge. | draft `SergeevDmitry/ERCs@0ee33230` | signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce` | + + Experimental components are disabled unless configured and support only the -subsets their pages describe. Planned means there is no adapter or endpoint. +subsets their pages describe. UCP is planned and has no implementation. AP2 is an authorization method, not a transport or payment rail. It appears in `authorizationProviders` in gateway discovery and has no AP2-specific mount or @@ -32,6 +35,54 @@ and providers, including `supportedSpec`, `capabilities`, `unsupported` and `status`. When enabled, A2A, ACP and AP2 also print their detailed unsupported lists in `agent-commerce doctor`. +## Tested combinations + +Each row names the test that covers a rail over a surface. E2E rows settle on +a local Anvil chain. Integration rows mock the facilitator and run no chain. +Public testnet and mainnet rows are smoke tests that spend funds and run only +on the wallet holder's machine, never in CI. + + + +| Rail | Surface | Authorization | Tested at | Test | +| ---- | ------- | ------------- | --------------------- | ------------------------------------------------ | +| x402 | HTTP | - | E2E, local chain | `tests/e2e/payment/x402-settlement.e2e.test.ts` | +| x402 | A2A | - | E2E, local chain | `tests/e2e/payment/x402-settlement.e2e.test.ts` | +| x402 | HTTP | AP2 | E2E, local chain | `tests/e2e/authorization/ap2-x402.e2e.test.ts` | +| x402 | MCP | - | integration, no chain | `tests/integration/mcp-payment-bindings.test.ts` | +| x402 | HTTP | - | public testnet | `tests/testnet/x402.smoke.test.ts` | +| x402 | HTTP | - | mainnet | `tests/mainnet/x402.smoke.test.ts` | +| MPP | HTTP | - | E2E, local chain | `tests/e2e/payment/mpp-settlement.e2e.test.ts` | +| MPP | HTTP | AP2 | E2E, local chain | `tests/e2e/authorization/ap2-mpp.e2e.test.ts` | +| MPP | MCP | - | integration, no chain | `tests/integration/mcp-payment-bindings.test.ts` | +| MPP | A2A | - | integration, no chain | `tests/integration/mpp-carriers.test.ts` | +| MPP | HTTP | - | public testnet | `tests/testnet/mpp-base-sepolia.smoke.test.ts` | +| MPP | HTTP | - | mainnet | `tests/mainnet/mpp-base.smoke.test.ts` | + + + +## Promotion criteria + +A profile moves from experimental to supported when all four criteria hold. +Each reads fields of the profile's record in `src/support/`: + +1. Upstream declares the pinned revision stable (`spec.stable`). +2. Every MUST-level gap against that revision is closed, or the profile + excludes the feature and lists it (`gaps`, `exclusions`). +3. Conformance evidence exists: the upstream suite where there is one, + otherwise our tests against the specification's requirements and examples + (`conformance`). Every MUST test that runs passes, and each skipped test is + named with its reason. A test that fails only because it contradicts the + specification, or assumes an input mode the profile does not declare, is + recorded the same way, with the specification section and the upstream + report. +4. Operational docs exist, with crash and replay coverage (`docs`, + `combinations`). + +"Supported" covers the recorded subset, never the whole specification. HTTP, +MCP and x402 were supported before 2.8.0 introduced these criteria, and keep +that status. Upstream does not label x402 v2 stable, and its record says so. + ## Protocol pages - [HTTP surface](protocols/http.md): routes, and the payment headers each rail diff --git a/docs/protocols/a2a.md b/docs/protocols/a2a.md index 2462668..4d31f54 100644 --- a/docs/protocols/a2a.md +++ b/docs/protocols/a2a.md @@ -184,13 +184,55 @@ without an `id` returns `-32600` without running. Each A2A error carries a `google.rpc.ErrorInfo` in `error.data`, with a reason such as `VERSION_NOT_SUPPORTED` and the domain `a2a-protocol.org`. +## Pins + + + +| Pin | Value | +| ------------------------ | ------------------------------------------------------------------------------------------------------------ | +| Pinned revision | v1.0.1; negotiation `1.0`; `JSONRPC` binding | +| Upstream source | [`a2aproject/A2A@33035925`](https://github.com/a2aproject/A2A/tree/3303592588e388e62e0f69f701af531d2f4e3991) | +| Declared stable upstream | yes | +| Upstream wording | "the first stable, production-ready version" (read 2026-11-17) | +| `@a2a-js/sdk` | `1.3.0`, tests only | + + + ## A2A exclusions -Unsupported methods are `SendStreamingMessage`, `GetTask`, `ListTasks`, -`CancelTask`, `SubscribeToTask`, the four task-push-notification-config -methods and `GetExtendedAgentCard`. The adapter also excludes REST and gRPC -bindings, SSE, long-running tasks, push delivery, multi-turn continuation, -authenticated extended cards, A2A authentication and other artifact types. +The A2A descriptor in `GET /.well-known/agent-commerce` lists these names in +`unsupported`, and `agent-commerce doctor` prints them when A2A is enabled: + + + +- `SendStreamingMessage` +- `GetTask` +- `ListTasks` +- `CancelTask` +- `SubscribeToTask` +- `CreateTaskPushNotificationConfig` +- `GetTaskPushNotificationConfig` +- `ListTaskPushNotificationConfigs` +- `DeleteTaskPushNotificationConfig` +- `GetExtendedAgentCard` +- `HTTP+JSON/REST binding` +- `gRPC binding` +- `SSE` +- `long-running task persistence` +- `task resumption other than an x402 extension payment` +- `push notifications` +- `multi-turn conversational continuation` +- `text parts` +- `file and URL parts (including inline bytes)` +- `multi-part messages` +- `message roles other than ROLE_USER` +- `authenticated extended agent cards` +- `A2A authentication schemes` +- `artifact types beyond Agent Commerce outcome data` +- `x402 extension payments across gateway instances`: Instances with separate receipt stores cannot resume each other's tasks. + + + Only pending x402 payment tasks can be stored and resumed. The A2A adapter accepts `_payment` but does not verify or settle payments diff --git a/docs/protocols/acp.md b/docs/protocols/acp.md index 264e35b..a618ec2 100644 --- a/docs/protocols/acp.md +++ b/docs/protocols/acp.md @@ -222,12 +222,57 @@ Discovery is public while ACP is enabled and uses locale and intervention metadata appears only when configured. Tokens, backend URLs, resource ids and database paths are excluded. +## Pins + + + +| Pin | Value | +| ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Pinned revision | stable snapshot `2026-04-17`; REST binding | +| Upstream source | [`agentic-commerce-protocol/agentic-commerce-protocol@6b828681`](https://github.com/agentic-commerce-protocol/agentic-commerce-protocol/tree/6b828681206f1f98a3faba978610ced66770d2ae) | +| Declared stable upstream | no | +| Upstream wording | "currently in `beta`" (read 2026-11-17) | +| `src/protocols/acp/spec/2026-04-17/schema.agentic_checkout.json` | vendored from `6b828681` | +| `tests/fixtures/acp/2026-04-17` | vendored from `6b828681` | + + + +## Deviations + +Each entry names the section of the pinned revision the gateway departs from +and the tests that hold the behavior. + + + +- **ACP RFC §6.5**: After a merchant 5xx, retrying the same `Idempotency-Key` returns 409 `idempotency_unresolved` unless `protocols.acp.idempotency.merchantIdempotent` is true. The merchant may have acted, so another execution could duplicate the order. Tests: `tests/conformance/acp/idempotency.test.ts`, `tests/conformance/acp/errors.test.ts`. + + + ## ACP exclusions -The adapter excludes carts, feed and standalone orders; delegated payment and -authentication; the ACP MCP binding; webhooks and outbound delivery; the client -role; `Signature` and `Timestamp` verification; discounts and the general -extension framework; seller-backed payment handlers; and other ACP versions. +The ACP descriptor in `GET /.well-known/agent-commerce` lists these names in +`unsupported`, and `agent-commerce doctor` prints them when ACP is enabled: + + + +- `carts service`: The discovery document advertises only the checkout service. +- `feed service` +- `standalone orders service` +- `delegate_payment` +- `delegate_authentication` +- `ACP MCP transport binding` +- `webhooks`: The merchant backend sends ACP order webhooks itself. +- `outbound merchant-to-agent delivery` +- `ACP client role` +- `Signature header verification`: The adapter forwards the header to the merchant unverified. +- `Timestamp replay-window verification`: The adapter forwards the header to the merchant unverified. +- `discount extension` +- `general ACP extension framework` +- `multiple ACP API versions` +- `seller-backed payment handler integration` + + + A `Signature` header does not replace bearer authentication. No ACP SDK ships. Conformance tests use the vendored official schema and examples. diff --git a/docs/protocols/ap2.md b/docs/protocols/ap2.md index d50b3ab..22f294d 100644 --- a/docs/protocols/ap2.md +++ b/docs/protocols/ap2.md @@ -379,25 +379,50 @@ Whoever creates an AP2 provider must call `close()`. The application composition root does so after `gateway.close()`; `createGateway()` itself does not close authorization providers. +## Pins + + + +| Pin | Value | +| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Pinned revision | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode | +| Upstream source | [`google-agentic-commerce/AP2@b4587ac1`](https://github.com/google-agentic-commerce/AP2/tree/b4587ac1d055888a73b4b21750973cffba961793) | +| Declared stable upstream | no | +| Upstream wording | "Standardization of the specification will continue within the Agentic Authentication Technical and Payments Technical Working Groups in FIDO" (read 2026-11-17) | +| `jose` | `6.2.12`, optional peer | +| `@sd-jwt/core` | `0.20.1`, optional peer | +| `canonicalize` | `5.0.0`, optional peer | +| `tests/fixtures/ap2/v0.2.0` | vendored from `b4587ac1` | + + + ## Not implemented -Discovery and `doctor` read the unsupported list from `src/support/ap2.json`. -The broader implementation limits are: - -- autonomous mode and open Checkout Mandates (`mandate.checkout.open.1`) -- Payment Mandates (`mandate.payment.1`) -- spending-constraint evaluation -- `cnf`-bound agent keys, delegation chains and key-binding JWTs -- User Credential delegation through OpenID4VP -- JWKS, issuer metadata, remote key discovery or remote revocation -- key rotation without a config change -- signatures other than ES256 or digests other than SHA-256 -- mandate issuance or signed AP2 Checkout Receipts -- an AP2 transport adapter or `/.well-known/ap2` -- AP2 as a payment rail -- AP2 over ACP - -Open mandates are refused because their spending constraints are not evaluated. +The AP2 descriptor in `GET /.well-known/agent-commerce` lists these names in +`unsupported`, and `agent-commerce doctor` prints them when AP2 is enabled: + + + +- `autonomous mode` +- `open checkout mandates (mandate.checkout.open.1)`: Rejected because the provider does not evaluate spending constraints. +- `payment mandates (mandate.payment.1)` +- `spending constraint evaluation` +- `cnf-bound agent keys` +- `user credential delegation (OpenID4VP)` +- `delegation chains and key-binding JWTs` +- `JWKS and any key discovery by URL (jku, x5u)`: Operators supply all keys in config. +- `issuer metadata fetching` +- `remote revocation` +- `key rotation without a config change` +- `signature algorithms other than ES256` +- `digest algorithms other than sha-256` +- `mandate issuance` +- `checkout receipts` +- `AP2 transport adapter or /.well-known/ap2`: HTTP, MCP and A2A carry the mandate in the gateway's own carriers; AP2 v0.2.0 defines none. +- `AP2 as a payment rail` +- `AP2 over the ACP checkout adapter` + + ## Code map diff --git a/docs/protocols/mcp.md b/docs/protocols/mcp.md index 5f031b4..2f30030 100644 --- a/docs/protocols/mcp.md +++ b/docs/protocols/mcp.md @@ -115,12 +115,48 @@ For payment-required and error results, `content[0].text` is a JSON copy of `structuredContent`; `content[1].text` is a sentence for readers. Unexpected exception messages and stack traces are omitted. +## Pins + + + +| Pin | Value | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Pinned revision | MCP `2026-07-28` and `2025-11-25` | +| Upstream source | [`modelcontextprotocol/modelcontextprotocol@05aeb07b`](https://github.com/modelcontextprotocol/modelcontextprotocol/tree/05aeb07b2db0c02adc4813a7c09f208ca8774152) | +| Declared stable upstream | yes | +| Upstream wording | "Current: the current protocol version, which is ready for use and may continue to receive backwards compatible changes" (read 2026-11-17) | +| `@modelcontextprotocol/server` | `2.3.0`, optional peer | +| `@modelcontextprotocol/client` | `2.3.0`, tests only | +| `@modelcontextprotocol/sdk` | `1.32.0`, tests only | + + + ## MCP exclusions -The adapter does not implement MCP resources, prompts, sampling, completions, -elicitation, roots, logging, tasks or tool-list-change notifications. It has -no MCP authorization, sessions, subscriptions, pagination or HTTP+SSE transport. -The gateway, rather than the MCP adapter, enforces Host and Origin checks. +The MCP descriptor in `GET /.well-known/agent-commerce` lists these names in +`unsupported`: + + + +- `resources` +- `prompts` +- `sampling` +- `completions` +- `elicitation` +- `roots` +- `logging` +- `notifications/tools/list_changed` +- `tasks` +- `dns-rebinding-protection`: The adapter relies on the gateway's `onRequest` hook to validate Host and Origin for the MCP mount. +- `authorization` +- `sessions` +- `subscriptions` +- `pagination` +- `HTTP+SSE transport` +- `MPP payment-required as JSON-RPC error -32042`: mppx reads challenges from the tool result's `_meta`. +- `MPP verification failure as JSON-RPC error -32043`: mppx reads refusals from the tool result's `_meta`. + + The MCP adapter maps payment carriers and results. It does not verify or settle payments or call merchant backends. diff --git a/docs/protocols/mpp.md b/docs/protocols/mpp.md index af4e824..283d1d4 100644 --- a/docs/protocols/mpp.md +++ b/docs/protocols/mpp.md @@ -4,11 +4,11 @@ The gateway targets `draft-httpauth-payment-01`, `draft-payment-intent-charge-00`, and `draft-evm-charge-00` at -`tempoxyz/mpp-specs@806fdb8`. It pins the pre-1.0 `mppx@0.13.1` as an -optional peer. For EIP-3009, the gateway follows `mppx`: it hashes -`JSON.stringify([id, realm])` with keccak256 to derive the nonce. The EVM -draft instead hashes `abi.encodePacked(id, realm)`. Credentials using the -draft nonce, including those produced by `mppx` 0.12 or earlier, fail +`tempoxyz/mpp-specs@806fdb8`. It uses the pre-1.0 `mppx`, an optional peer +pinned to the version under [Pins](#pins). For EIP-3009, the gateway follows +`mppx`: it hashes `JSON.stringify([id, realm])` with keccak256 to derive the +nonce. The EVM draft instead hashes `abi.encodePacked(id, realm)`. Credentials +using the draft nonce, including those produced by `mppx` 0.12 or earlier, fail verification with `wrong_nonce`. Later drafts or `mppx` releases may change the wire format again, so MPP @@ -61,10 +61,6 @@ issuing challenges over plain HTTP. Base mainnet deployments must satisfy the [mainnet guardrails](../configuration.md#mainnet-guardrails). -Unsupported variants are listed in `src/support/mpp.json`: non-EVM -methods, Permit2/transaction/hash credentials, splits, subscriptions, EVM -sessions and the discovery extension. - ## Idempotency-Key Experimental and disabled by default. On a resource with @@ -102,3 +98,50 @@ another payer returns 422 `Unprocessable Content`, following section 2.7 of usable stored response. [http.md](http.md) lists the redelivery headers. + +## Pins + + + +| Pin | Value | +| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Pinned revision | drafts at `tempoxyz/mpp-specs@806fdb8` | +| Upstream source | [`tempoxyz/mpp-specs@806fdb8b`](https://github.com/tempoxyz/mpp-specs/tree/806fdb8b8c92cda5c84b8660558921b6bbeef7e0) | +| Declared stable upstream | no | +| Upstream wording | "Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time." (read 2026-11-17) | +| `mppx` | `0.13.1`, optional peer | + + + +## Deviations + +Each entry names the section of the pinned revision the gateway departs from +and the tests that hold the behavior. + + + +- **draft-evm-charge-00**: The EIP-3009 nonce is keccak256 of `JSON.stringify([id, realm])`, as `mppx` 0.13 derives it, not of `abi.encodePacked(id, realm)`; a credential using the draft's nonce fails with `wrong_nonce`. Tests: `tests/unit/payments-mpp/provider.test.ts`. +- **draft-payment-transport-mcp-00**: Over MCP, payment errors are tool results with `isError` and the challenges in `_meta`, not the JSON-RPC errors the draft maps them to (-32042, -32043, -32602 and -32603). Tests: `tests/integration/mcp-payment-bindings.test.ts`. +- **draft-httpauth-payment-01 §11.4**: An unpaid request that gets a 402 also stores a `resource.requested` event beside the challenge. Tests: `tests/unit/core/execution/pipeline.test.ts`. +- **draft-httpauth-payment-01 §4.2; draft-evm-charge-00**: A credential whose attempt is reserved or settlement-uncertain gets 409 without a fresh challenge, because a second challenge could lead to a second payment. Tests: `tests/integration/mpp-carriers.test.ts`. +- **draft-payment-intent-charge-00**: With `paymentFlow: authorization`, the backend runs before the transfer, which the charge intent counts as partial access before payment. The default, `upfront`, settles first. Tests: `tests/e2e/payment/mpp-settlement.e2e.test.ts`. + + + +## MPP exclusions + +The MPP descriptor in `GET /.well-known/agent-commerce` lists these names in +`unsupported`: + + + +- `methods other than evm` +- `credential=permit2`: The profile accepts only the EIP-3009 authorization credential. +- `credential=transaction` +- `credential=hash` +- `splits`: The draft allows splits only with `permit2` credentials. +- `intent=subscription` +- `evm sessions`: A separate EVM draft, not an option of charge. +- `discovery extension` + + diff --git a/docs/protocols/x402.md b/docs/protocols/x402.md index 16f7aee..2acc1f5 100644 --- a/docs/protocols/x402.md +++ b/docs/protocols/x402.md @@ -268,10 +268,21 @@ ERC-8409 requires transport bindings to define the following: the payment deadline with `validUntil`. Quote expiry does not cancel a submitted payment. -Not implemented: payer-bound quotes; contract issuers (ERC-1271, ERC-6492, -EIP-7702 delegates); quote consumption, single-use enforcement or revocation; -client nonces; quotes for MPP, Solana or NEAR; signed receipts and x402's -`offer-receipt` extension; remote signers and KMS; per-resource toggles. +The x402 descriptor lists these quote exclusions in `unsupported` whether or +not quotes are enabled: + + + +- `payer-bound quotes` +- `contract quote issuers (ERC-1271, ERC-6492, EIP-7702 delegates)` +- `quote consumption, single-use enforcement or revocation` +- `quote client nonces` +- `quotes for MPP, Solana or NEAR` +- `signed receipts and the x402 offer-receipt extension` +- `remote quote signers and KMS` +- `per-resource quote toggles` + + ## Support matrix @@ -291,3 +302,41 @@ README lists their transactions. Every public-network x402 payment was signed by the x402 SDK's own client for its family. Other wallets and clients have not been tested. + +## Pins + + + +| Pin | Value | +| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | +| Pinned revision | x402 v2 | +| Upstream source | [`x402-foundation/x402@51a0664c`](https://github.com/x402-foundation/x402/tree/51a0664c2b7826e3cb02595481eb6848a1b11815) | +| Declared stable upstream | not stated | +| Upstream wording | "Protocol Version: 2" (read 2026-11-17) | +| ERC-8409 pinned revision | draft `SergeevDmitry/ERCs@0ee33230` | +| ERC-8409 upstream source | [`SergeevDmitry/ERCs@0ee33230`](https://github.com/SergeevDmitry/ERCs/tree/0ee33230ca9f9f41a714382552a47cd860465ca7) | +| ERC-8409 declared stable upstream | no | +| ERC-8409 upstream wording | "status: Draft" (read 2026-11-17) | +| `@x402/core` | `2.30.0`, optional peer | +| `@x402/evm` | `2.30.0`, optional peer | +| `@x402/svm` | `2.30.0`, optional peer | +| `@x402/near` | `2.30.0`, optional peer | +| `@x402/mcp` | `2.30.0`, tests only | + + + +## x402 exclusions + +The x402 descriptor in `GET /.well-known/agent-commerce` lists these names in +`unsupported`, followed by the +[ERC-8409 quote exclusions](#erc-8409-signed-quotes): + + + +- `permit2 gas sponsoring extensions` +- `upto scheme` +- `batch-settlement scheme` +- `auth-capture scheme` +- `x402 v1`: A payload declaring an `x402Version` other than 2 is refused as `invalid_x402_version` on every carrier. + + diff --git a/package.json b/package.json index 1752aae..966f8bf 100644 --- a/package.json +++ b/package.json @@ -90,6 +90,7 @@ "test:mainnet": "vitest run --config vitest.mainnet.config.ts", "check:contract": "node scripts/contract-surface.mjs", "check:metadata": "node scripts/check-package-metadata.mjs", + "support:write": "tsx scripts/support-record.ts --write", "verify": "npm run check:contract && npm run lint && npm run typecheck && npm test", "agent-commerce": "tsx src/cli/index.ts", "doctor": "tsx src/cli/index.ts doctor", diff --git a/scripts/support-record.ts b/scripts/support-record.ts index 61ab54e..8947888 100644 --- a/scripts/support-record.ts +++ b/scripts/support-record.ts @@ -1,15 +1,22 @@ /** - * Validate the support records under `src/support/`, one per shipped profile. - * Each record states the revision, subset, exclusions, deviations and evidence - * its status covers. Descriptors and `doctor` trust these files at runtime. - * This schema runs in tests and tooling and is excluded from the published - * package. + * Validate the support records under `src/support/`, one per shipped profile, + * and render the docs regions generated from them. Each record states the + * revision, subset, exclusions, deviations and evidence its status covers. + * Descriptors and `doctor` trust these files at runtime. This schema runs in + * tests and tooling and is excluded from the published package. + * + * npm run support:write rewrite every generated region from the records + * + * `tests/integration/support-record.test.ts` fails on any drift and names the + * file, the region and the record. */ -import { readFileSync } from 'node:fs'; -import { join } from 'node:path'; +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { z } from 'zod'; -export const SUPPORT_RECORD_NAMES = ['http', 'mcp', 'a2a', 'acp', 'x402', 'mpp', 'ap2'] as const; +// Also the order every generated table lists the profiles in +export const SUPPORT_RECORD_NAMES = ['http', 'mcp', 'x402', 'mpp', 'a2a', 'acp', 'ap2'] as const; export const REPO_ROOT = join(import.meta.dirname, '..'); @@ -48,7 +55,11 @@ const SupportRecordSchema = z z.strictObject({ name: text, status: z.enum(['supported', 'experimental', 'partial']), + // A feature with its own spec gets its own matrix row, under `title` spec: SpecSchema.optional(), + title: text.optional(), + role: text.optional(), + subset: text.optional(), }), ), // `name` is the string the descriptor publishes in `unsupported` @@ -119,6 +130,16 @@ const SupportRecordSchema = z }); } } + for (const feature of record.features) { + const row = [feature.title, feature.role, feature.subset]; + if ((feature.spec !== undefined) !== row.every((field) => field !== undefined)) { + ctx.addIssue({ + code: 'custom', + path: ['features'], + message: `feature "${feature.name}" needs title, role and subset exactly when it has a spec`, + }); + } + } if (record.combinations !== undefined && record.kind !== 'payment') { ctx.addIssue({ code: 'custom', @@ -148,14 +169,482 @@ export function readSupportRecord(name: SupportRecordName): SupportRecord { return parsed.data; } -/** Evidence and documentation paths to check for existence */ +/** Evidence and documentation paths to check for existence, each once */ export function citedPaths(record: SupportRecord): string[] { return [ - ...record.artifacts.map((artifact) => artifact.path), - ...(record.combinations ?? []).map((combination) => combination.evidence), - ...(record.conformance?.tests ?? []), - ...(record.conformance?.skipped ?? []).map((skipped) => skipped.test), - ...record.deviations.flatMap((deviation) => deviation.tests), - ...record.docs, + ...new Set([ + ...record.artifacts.map((artifact) => artifact.path), + ...(record.combinations ?? []).map((combination) => combination.evidence), + ...(record.conformance?.tests ?? []), + ...(record.conformance?.skipped ?? []).map((skipped) => skipped.test), + ...record.deviations.flatMap((deviation) => deviation.tests), + ...record.docs, + ]), + ]; +} + +export interface PackageManifest { + readonly dependencies?: Readonly>; + readonly devDependencies?: Readonly>; + readonly peerDependencies?: Readonly>; +} + +/** Everything the drift check reads, injectable so tests can mutate a copy */ +export interface SupportTree { + readonly records: readonly SupportRecord[]; + readonly manifest: PackageManifest; + /** Undefined when the file does not exist */ + readonly read: (path: string) => string | undefined; + readonly exists: (path: string) => boolean; +} + +export function readSupportTree(): SupportTree { + return { + records: SUPPORT_RECORD_NAMES.map(readSupportRecord), + manifest: JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf8')) as PackageManifest, + read: (path) => { + const full = join(REPO_ROOT, path); + return existsSync(full) ? readFileSync(full, 'utf8') : undefined; + }, + exists: (path) => existsSync(join(REPO_ROOT, path)), + }; +} + +// Rendering + +const STATUS_WORD = { supported: 'Supported', experimental: 'Experimental', partial: 'Partial' }; + +// Supported badges keep each project's color; experimental ones share one +const BADGE_COLOR: Readonly> = { mcp: '6b4fbb', x402: '0052ff' }; +const SUPPORTED_BADGE = '2ea44f'; +const EXPERIMENTAL_BADGE = 'f0a30a'; + +const SURFACE_TITLE = { http: 'HTTP', mcp: 'MCP', a2a: 'A2A' }; +const LEVEL_TITLE = { + e2e: 'E2E, local chain', + integration: 'integration, no chain', + testnet: 'public testnet', + mainnet: 'mainnet', +}; + +// A Markdown table with every column padded to its widest cell +function table(header: readonly string[], body: readonly (readonly string[])[]): string { + const rows = body.map((row) => row.map((cell) => cell.replaceAll('|', '\\|'))); + const widths = header.map((cell, column) => + Math.max(3, cell.length, ...rows.map((row) => (row[column] ?? '').length)), + ); + const line = (cells: readonly string[]) => + `| ${cells.map((cell, column) => cell.padEnd(widths[column] ?? 0)).join(' | ')} |`; + return [line(header), line(widths.map((width) => '-'.repeat(width))), ...rows.map(line)].join( + '\n', + ); +} + +// A Markdown block between region markers, set off by blank lines +const block = (text: string) => `\n${text}\n\n`; + +type Spec = NonNullable; +type Package = SupportRecord['packages'][number]; + +function packageVersion(manifest: PackageManifest, pkg: Package): string | undefined { + return pkg.use === 'test' + ? manifest.devDependencies?.[pkg.name] + : (manifest.peerDependencies?.[pkg.name] ?? manifest.dependencies?.[pkg.name]); +} + +const pinned = (manifest: PackageManifest, pkg: Package) => + `\`${pkg.name}@${packageVersion(manifest, pkg) ?? 'missing'}\``; + +function revisionCell(record: SupportRecord, manifest: PackageManifest): string { + const runtime = record.packages.filter((pkg) => pkg.use === 'runtime'); + const packages = runtime.map((pkg) => pinned(manifest, pkg)).join(', '); + const display = record.spec?.display ?? 'native'; + return packages === '' ? display : `${display}; ${packages}`; +} + +interface MatrixRow { + readonly title: string; + readonly status: string; + readonly role: string; + readonly revision: string; + readonly subset: string; +} + +// One row per record, then one per feature that has its own spec +function matrixRows(records: readonly SupportRecord[], manifest: PackageManifest): MatrixRow[] { + return [ + ...records.map((record) => ({ + title: record.title, + status: STATUS_WORD[record.status], + role: record.role, + revision: revisionCell(record, manifest), + subset: record.subset, + })), + ...records.flatMap((record) => + record.features.flatMap((feature) => + feature.spec === undefined + ? [] + : [ + { + title: feature.title ?? feature.name, + status: STATUS_WORD[feature.status], + role: feature.role ?? '', + revision: feature.spec.display, + subset: feature.subset ?? '', + }, + ], + ), + ), ]; } + +function badges(records: readonly SupportRecord[]): string { + return records + .filter((record) => record.spec !== undefined) + .map((record) => { + const color = + record.status === 'experimental' + ? EXPERIMENTAL_BADGE + : (BADGE_COLOR[record.name] ?? SUPPORTED_BADGE); + const label = record.title.replaceAll('-', '--'); + return ` ${record.title}\n`; + }) + .join(''); +} + +function specRows(spec: Spec, prefix: string): string[][] { + const commit = spec.source.commit; + const stable = spec.stable === null ? 'not stated' : spec.stable ? 'yes' : 'no'; + return [ + [`${prefix}pinned revision`, spec.display], + [ + `${prefix}upstream source`, + `[\`${spec.source.repo}@${commit.slice(0, 8)}\`](https://github.com/${spec.source.repo}/tree/${commit})`, + ], + [`${prefix}declared stable upstream`, stable], + [`${prefix}upstream wording`, `"${spec.statement}" (read ${spec.checked})`], + ]; +} + +function pins(record: SupportRecord, manifest: PackageManifest): string { + const use = (pkg: Package) => { + if (pkg.use === 'test') return 'tests only'; + return manifest.peerDependencies?.[pkg.name] !== undefined ? 'optional peer' : 'dependency'; + }; + const rows = [ + ...(record.spec === undefined ? [] : specRows(record.spec, '')), + ...record.features.flatMap((feature) => + feature.spec === undefined ? [] : specRows(feature.spec, `${feature.title} `), + ), + ...record.packages.map((pkg) => [ + `\`${pkg.name}\``, + `\`${packageVersion(manifest, pkg) ?? 'missing'}\`, ${use(pkg)}`, + ]), + ...record.artifacts.map((artifact) => [ + `\`${artifact.path}\``, + `vendored from \`${artifact.revision.slice(0, 8)}\``, + ]), + ]; + // Capitalize the first word of each label that is not a package or a path + const label = (cell: string) => + cell.startsWith('`') ? cell : `${cell.charAt(0).toUpperCase()}${cell.slice(1)}`; + return table( + ['Pin', 'Value'], + rows.map(([name = '', value = '']) => [label(name), value]), + ); +} + +function exclusionList(exclusions: SupportRecord['exclusions']): string { + return exclusions + .map( + (exclusion) => + `- \`${exclusion.name}\`${exclusion.note === undefined ? '' : `: ${exclusion.note}`}`, + ) + .join('\n'); +} + +function deviationList(record: SupportRecord): string { + return record.deviations + .map((deviation) => { + const tests = deviation.tests.map((test) => `\`${test}\``).join(', '); + const upstream = + deviation.upstream === undefined ? '' : ` Reported upstream: ${deviation.upstream}.`; + return `- **${deviation.spec}**: ${deviation.summary}${upstream} Tests: ${tests}.`; + }) + .join('\n'); +} + +function combinations(records: readonly SupportRecord[]): string { + const rows = records.flatMap((record) => + (record.combinations ?? []).map((combination) => [ + record.title, + SURFACE_TITLE[combination.surface], + combination.authorization === undefined ? '-' : 'AP2', + LEVEL_TITLE[combination.level], + `\`${combination.evidence}\``, + ]), + ); + return table(['Rail', 'Surface', 'Authorization', 'Tested at', 'Test'], rows); +} + +export interface RenderedRegion { + readonly body: string; + /** What the region is generated from, named in a drift report */ + readonly source: string; +} + +/** Every generated region, by repository path and region id */ +export function renderRegions( + records: readonly SupportRecord[], + manifest: PackageManifest, +): Map> { + const all = 'src/support/*.json and package.json'; + const matrix = matrixRows(records, manifest); + const regions = new Map>([ + [ + 'README.md', + new Map([ + ['badges', { body: badges(records), source: 'src/support/*.json' }], + [ + 'matrix', + { + body: block( + table( + ['Protocol', 'Status', 'Pinned revision', 'Implemented subset'], + matrix.map((row) => [`**${row.title}**`, row.status, row.revision, row.subset]), + ), + ), + source: all, + }, + ], + ]), + ], + [ + 'docs/protocols.md', + new Map([ + [ + 'matrix', + { + body: block( + table( + ['Protocol', 'Status', 'Role', 'Revision', 'Implemented subset'], + matrix.map((row) => [ + `**${row.title}**`, + row.status, + row.role, + row.revision, + row.subset, + ]), + ), + ), + source: all, + }, + ], + ['combinations', { body: block(combinations(records)), source: 'src/support/*.json' }], + ]), + ], + ]); + for (const record of records) { + const source = `src/support/${record.name}.json`; + const page = new Map(); + if (record.spec !== undefined || record.packages.length > 0 || record.artifacts.length > 0) { + page.set('pins', { + body: block(pins(record, manifest)), + source: `${source} and package.json`, + }); + } + const untagged = record.exclusions.filter((exclusion) => exclusion.feature === undefined); + if (untagged.length > 0) { + page.set('exclusions', { body: block(exclusionList(untagged)), source }); + } + for (const feature of new Set(record.exclusions.flatMap((e) => e.feature ?? []))) { + const tagged = record.exclusions.filter((exclusion) => exclusion.feature === feature); + page.set(`exclusions:${feature}`, { body: block(exclusionList(tagged)), source }); + } + if (record.deviations.length > 0) { + page.set('deviations', { body: block(deviationList(record)), source }); + } + if (page.size > 0) regions.set(`docs/protocols/${record.name}.md`, page); + } + return regions; +} + +// Regions in a file + +const REGION = + /^([ \t]*)\n([\s\S]*?)^[ \t]*/gm; + +interface FoundRegion { + readonly id: string; + readonly body: string; +} + +function findRegions(content: string): FoundRegion[] { + return [...content.matchAll(REGION)].map((match) => ({ + id: match[2] ?? '', + body: match[3] ?? '', + })); +} + +function replaceRegions(content: string, rendered: ReadonlyMap): string { + return content.replace(REGION, (whole, indent: string, id: string) => { + const region = rendered.get(id); + if (region === undefined) return whole; + return `${indent}\n${region.body}${indent}`; + }); +} + +// The drift check + +const titleNamed = (text: string, title: string) => + new RegExp(`(^|[^\\w-])${title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\w-])`).test(text); + +// Hand-written sentences that name the experimental profiles +const STATUS_SENTENCES = [ + { + path: 'README.md', + place: 'Versioning sentence', + find: (content: string) => /### Versioning\n\n([\s\S]*?)\n\n/.exec(content)?.[1], + }, + { + path: 'plugins/agent-commerce-gateway/skills/agent-commerce/SKILL.md', + place: '"exist but are experimental" sentence', + find: (content: string) => /[^.]*exist but are experimental[^.]*\./.exec(content)?.[0], + }, +]; + +// x402 route table rows, by the start of the route, and the feature each row states +const X402_ROUTES: readonly [string, string][] = [ + ['EIP-3009 ', 'eip-3009'], + ['Permit2 ', 'permit2'], + ['Solana', 'exact-svm'], + ['NEAR', 'exact-near'], +]; + +function handWrittenProblems(tree: SupportTree): string[] { + const problems: string[] = []; + const experimental = tree.records.filter((record) => record.status === 'experimental'); + for (const sentence of STATUS_SENTENCES) { + const text = sentence.find(tree.read(sentence.path) ?? ''); + if (text === undefined) { + problems.push(`${sentence.path}: ${sentence.place} not found`); + continue; + } + for (const record of tree.records) { + const named = titleNamed(text, record.title); + if (named !== experimental.includes(record)) { + problems.push( + `${sentence.path}: the ${sentence.place} ${named ? 'names' : 'omits'} ${record.title}, which src/support/${record.name}.json records as ${record.status}`, + ); + } + } + } + for (const record of tree.records) { + const path = `docs/protocols/${record.name}.md`; + const marked = (tree.read(path) ?? '').includes('**Experimental.**'); + if (marked !== (record.status === 'experimental')) { + problems.push( + `${path}: ${marked ? 'says' : 'does not say'} **Experimental.**, but src/support/${record.name}.json records ${record.status}`, + ); + } + } + const x402 = tree.records.find((record) => record.name === 'x402'); + const routes = /## Support matrix\n[\s\S]*?\n(\|[\s\S]*?)\n\n/.exec( + tree.read('docs/protocols/x402.md') ?? '', + )?.[1]; + for (const [prefix, featureName] of X402_ROUTES) { + const feature = x402?.features.find((candidate) => candidate.name === featureName); + const rows = (routes ?? '') + .split('\n') + .map((line) => line.split('|').map((cell) => cell.trim())) + .filter((cells) => cells[1]?.startsWith(prefix)); + if (rows.length === 0) { + problems.push(`docs/protocols/x402.md: no support matrix row starts with "${prefix.trim()}"`); + } + for (const cells of rows) { + if (cells[2] !== feature?.status) { + problems.push( + `docs/protocols/x402.md: the "${cells[1]}" row says ${cells[2]}, but src/support/x402.json records ${featureName} as ${feature?.status}`, + ); + } + } + } + return problems; +} + +/** Every disagreement between the records, package.json and the docs, each naming its place */ +export function supportProblems(tree: SupportTree): string[] { + const problems: string[] = []; + const { manifest } = tree; + for (const record of tree.records) { + const source = `src/support/${record.name}.json`; + for (const pkg of record.packages) { + const runtime = manifest.peerDependencies?.[pkg.name] ?? manifest.dependencies?.[pkg.name]; + const declared = + pkg.use === 'runtime' + ? runtime !== undefined + : manifest.devDependencies?.[pkg.name] !== undefined && runtime === undefined; + if (!declared) { + problems.push( + `${source}: package ${pkg.name} (${pkg.use}) is not in package.json ${pkg.use === 'runtime' ? 'dependencies or peerDependencies' : 'devDependencies alone'}`, + ); + } + } + for (const path of citedPaths(record)) { + if (!tree.exists(path)) problems.push(`${source}: cites ${path}, which does not exist`); + } + } + for (const [path, regions] of renderRegions(tree.records, manifest)) { + const content = tree.read(path); + if (content === undefined) { + problems.push(`${path}: missing, but support regions are generated into it`); + continue; + } + const found = findRegions(content); + for (const [id, region] of regions) { + const matches = found.filter((candidate) => candidate.id === id); + if (matches.length !== 1) { + problems.push(`${path}: region "${id}" appears ${matches.length} times, not once`); + } else if (matches[0]?.body !== region.body) { + problems.push( + `${path}: region "${id}" differs from ${region.source}; run npm run support:write`, + ); + } + } + for (const region of found) { + if (!regions.has(region.id)) problems.push(`${path}: unknown region "${region.id}"`); + } + } + return [...problems, ...handWrittenProblems(tree)]; +} + +/** The new content of each file whose generated regions are out of date */ +export function regionUpdates(tree: SupportTree): Map { + const updates = new Map(); + for (const [path, regions] of renderRegions(tree.records, tree.manifest)) { + const content = tree.read(path); + if (content === undefined) throw new Error(`${path}: missing`); + const ids = new Set(findRegions(content).map((region) => region.id)); + const absent = [...regions.keys()].filter((id) => !ids.has(id)); + if (absent.length > 0) { + throw new Error(`${path}: add the markers for region(s) ${absent.join(', ')} first`); + } + const next = replaceRegions(content, regions); + if (next !== content) updates.set(path, next); + } + return updates; +} + +if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + if (!process.argv.includes('--write')) { + console.error('usage: tsx scripts/support-record.ts --write'); + process.exit(2); + } + const updates = regionUpdates(readSupportTree()); + for (const [path, content] of updates) writeFileSync(join(REPO_ROOT, path), content); + console.log( + updates.size === 0 + ? 'support regions: unchanged' + : `support regions: rewrote ${[...updates.keys()].join(', ')}`, + ); +} diff --git a/src/support/a2a.json b/src/support/a2a.json index 2694f53..db12234 100644 --- a/src/support/a2a.json +++ b/src/support/a2a.json @@ -3,7 +3,7 @@ "kind": "protocol", "title": "A2A", "status": "experimental", - "role": "Transport that carries x402 and MPP payments in SendMessage, including through the x402 extension.", + "role": "Transport that carries x402 and MPP payments in `SendMessage`, including through the x402 extension.", "subset": "Agent Card, `SendMessage`, paid flow and the x402 extension", "spec": { "revisions": ["1.0.1"], diff --git a/src/support/acp.json b/src/support/acp.json index ec0cd0e..299dcdb 100644 --- a/src/support/acp.json +++ b/src/support/acp.json @@ -3,7 +3,7 @@ "kind": "protocol", "title": "ACP", "status": "experimental", - "role": "Checkout API that forwards checkout operations to the merchant, whose payment handler receives payment_data. Gateway checkout routes are free and carry no x402 or MPP payment.", + "role": "Checkout API that forwards checkout operations to the merchant, whose payment handler receives `payment_data`. Gateway checkout routes are free and carry no x402 or MPP payment.", "subset": "discovery and the five checkout operations", "spec": { "revisions": ["2026-04-17"], @@ -68,7 +68,7 @@ ], "deviations": [ { - "summary": "After a merchant 5xx, retrying the same Idempotency-Key returns 409 idempotency_unresolved unless protocols.acp.idempotency.merchantIdempotent is true. The merchant may have acted, so another execution could duplicate the order.", + "summary": "After a merchant 5xx, retrying the same `Idempotency-Key` returns 409 `idempotency_unresolved` unless `protocols.acp.idempotency.merchantIdempotent` is true. The merchant may have acted, so another execution could duplicate the order.", "spec": "ACP RFC §6.5", "tests": ["tests/conformance/acp/idempotency.test.ts", "tests/conformance/acp/errors.test.ts"] } diff --git a/src/support/mcp.json b/src/support/mcp.json index effa603..f436fdb 100644 --- a/src/support/mcp.json +++ b/src/support/mcp.json @@ -38,7 +38,7 @@ { "name": "tasks" }, { "name": "dns-rebinding-protection", - "note": "The adapter relies on the gateway's onRequest hook to validate Host and Origin for the MCP mount." + "note": "The adapter relies on the gateway's `onRequest` hook to validate Host and Origin for the MCP mount." }, { "name": "authorization" }, { "name": "sessions" }, @@ -47,11 +47,11 @@ { "name": "HTTP+SSE transport" }, { "name": "MPP payment-required as JSON-RPC error -32042", - "note": "mppx reads challenges from the tool result's _meta." + "note": "mppx reads challenges from the tool result's `_meta`." }, { "name": "MPP verification failure as JSON-RPC error -32043", - "note": "mppx reads refusals from the tool result's _meta." + "note": "mppx reads refusals from the tool result's `_meta`." } ], "deviations": [], diff --git a/src/support/mpp.json b/src/support/mpp.json index ec0525c..e97ed9f 100644 --- a/src/support/mpp.json +++ b/src/support/mpp.json @@ -4,7 +4,7 @@ "title": "MPP", "status": "experimental", "role": "Payment rail, carried by HTTP, MCP and A2A.", - "subset": "`charge`/`evm`/EIP-3009 over HTTP, MCP and A2A", + "subset": "`charge`/`evm`/EIP-3009 with USDC on Base Sepolia and Base, over HTTP, MCP and A2A", "spec": { "revisions": [ "draft-httpauth-payment-01", @@ -45,24 +45,24 @@ }, { "name": "credential=transaction" }, { "name": "credential=hash" }, - { "name": "splits", "note": "The draft allows splits only with permit2 credentials." }, + { "name": "splits", "note": "The draft allows splits only with `permit2` credentials." }, { "name": "intent=subscription" }, { "name": "evm sessions", "note": "A separate EVM draft, not an option of charge." }, { "name": "discovery extension" } ], "deviations": [ { - "summary": "The EIP-3009 nonce is keccak256 of JSON.stringify([id, realm]), as mppx 0.13 derives it, not of abi.encodePacked(id, realm); a credential using the draft's nonce fails with wrong_nonce.", + "summary": "The EIP-3009 nonce is keccak256 of `JSON.stringify([id, realm])`, as `mppx` 0.13 derives it, not of `abi.encodePacked(id, realm)`; a credential using the draft's nonce fails with `wrong_nonce`.", "spec": "draft-evm-charge-00", "tests": ["tests/unit/payments-mpp/provider.test.ts"] }, { - "summary": "Over MCP, payment errors are tool results with isError and the challenges in _meta, not the JSON-RPC errors the draft maps them to (-32042, -32043, -32602 and -32603).", + "summary": "Over MCP, payment errors are tool results with `isError` and the challenges in `_meta`, not the JSON-RPC errors the draft maps them to (-32042, -32043, -32602 and -32603).", "spec": "draft-payment-transport-mcp-00", "tests": ["tests/integration/mcp-payment-bindings.test.ts"] }, { - "summary": "An unpaid request that gets a 402 also stores a resource.requested event beside the challenge.", + "summary": "An unpaid request that gets a 402 also stores a `resource.requested` event beside the challenge.", "spec": "draft-httpauth-payment-01 §11.4", "tests": ["tests/unit/core/execution/pipeline.test.ts"] }, @@ -72,7 +72,7 @@ "tests": ["tests/integration/mpp-carriers.test.ts"] }, { - "summary": "With paymentFlow: authorization, the backend runs before the transfer, which the charge intent counts as partial access before payment. The default, upfront, settles first.", + "summary": "With `paymentFlow: authorization`, the backend runs before the transfer, which the charge intent counts as partial access before payment. The default, `upfront`, settles first.", "spec": "draft-payment-intent-charge-00", "tests": ["tests/e2e/payment/mpp-settlement.e2e.test.ts"] } diff --git a/src/support/x402.json b/src/support/x402.json index 5776fcd..46c3433 100644 --- a/src/support/x402.json +++ b/src/support/x402.json @@ -52,7 +52,10 @@ "stable": false, "statement": "status: Draft", "checked": "2026-11-17" - } + }, + "title": "ERC-8409", + "role": "x402 feature: EIP-712 signed quotes on the EVM offers of a challenge.", + "subset": "signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce`" } ], "exclusions": [ @@ -62,7 +65,7 @@ { "name": "auth-capture scheme" }, { "name": "x402 v1", - "note": "A payload declaring an x402Version other than 2 is refused as invalid_x402_version on every carrier." + "note": "A payload declaring an `x402Version` other than 2 is refused as `invalid_x402_version` on every carrier." }, { "name": "payer-bound quotes", "feature": "erc-8409-quotes" }, { diff --git a/tests/integration/support-record.test.ts b/tests/integration/support-record.test.ts index 481fdf4..eece327 100644 --- a/tests/integration/support-record.test.ts +++ b/tests/integration/support-record.test.ts @@ -1,19 +1,24 @@ /** - * Check support records against the descriptors that publish their claims. - * Descriptors derive status and unsupported features from the records; these - * tests also compare capabilities and revisions with their values in code. + * Check support records against the descriptors that publish their claims and + * the docs generated from them. Descriptors derive status and unsupported + * features from the records; these tests also compare capabilities and + * revisions with their values in code. */ -import { existsSync, readdirSync } from 'node:fs'; +import { readdirSync } from 'node:fs'; import { join } from 'node:path'; import { LATEST_PROTOCOL_VERSION } from '@modelcontextprotocol/server'; import { describe, expect, expectTypeOf, it } from 'vitest'; import { - citedPaths, + type PackageManifest, REPO_ROOT, readSupportRecord, + readSupportTree, + regionUpdates, SUPPORT_RECORD_NAMES, type SupportRecord, type SupportRecordName, + type SupportTree, + supportProblems, } from '../../scripts/support-record'; import { AP2_CAPABILITIES, AP2_UNSUPPORTED } from '../../src/ap2'; import { AP2_SPEC_VERSION } from '../../src/authorization/ap2/constants'; @@ -50,15 +55,6 @@ describe('support records', () => { for (const name of SUPPORT_RECORD_NAMES) expect(records[name].name).toBe(name); }); - it('cites only evidence and documentation files that exist', () => { - const missing = SUPPORT_RECORD_NAMES.flatMap((name) => - citedPaths(records[name]) - .filter((path) => !existsSync(join(REPO_ROOT, path))) - .map((path) => `src/support/${name}.json: ${path}`), - ); - expect(missing).toEqual([]); - }); - it('lists tested combinations on the payment records only', () => { expect(SUPPORT_RECORD_NAMES.filter((name) => records[name].combinations !== undefined)).toEqual( ['x402', 'mpp'], @@ -210,3 +206,176 @@ describe('published exports derived from a record keep their 2.7 types', () => { expectTypeOf(MPP_DESCRIPTOR).toEqualTypeOf(); }); }); + +describe('drift between the records, package.json and the docs', () => { + const tree = readSupportTree(); + + // A writable copy of package.json's dependency sections + type Manifest = { -readonly [K in keyof PackageManifest]-?: Record }; + + interface Change { + readonly records?: (records: SupportRecord[]) => void; + readonly manifest?: (manifest: Manifest) => void; + readonly edit?: Readonly string>>; + readonly deleted?: string; + } + + // The real tree with one change, made on copies + function changed(change: Change): SupportTree { + const mutated = structuredClone(tree.records) as SupportRecord[]; + const manifest = structuredClone(tree.manifest) as Manifest; + change.records?.(mutated); + change.manifest?.(manifest); + return { + records: mutated, + manifest, + read: (path) => { + const content = tree.read(path); + const edit = change.edit?.[path]; + return content === undefined || edit === undefined ? content : edit(content); + }, + exists: (path) => path !== change.deleted && tree.exists(path), + }; + } + + const record = (records: SupportRecord[], name: SupportRecordName) => { + const found = records.find((candidate) => candidate.name === name); + if (found === undefined) throw new Error(`no ${name} record`); + return found; + }; + + const stale = (path: string, region: string, source: string) => + `${path}: region "${region}" differs from ${source}; run npm run support:write`; + const ALL = 'src/support/*.json and package.json'; + + it('finds none on the real tree, and --write would change no file', () => { + expect(supportProblems(tree)).toEqual([]); + expect([...regionUpdates(tree).keys()]).toEqual([]); + }); + + const HAND_EDIT: Change = { + edit: { + 'README.md': (content) => + content.replace('| **MPP** | Experimental', '| **MPP** | Supported '), + }, + }; + const MARKERS_REMOVED: Change = { + edit: { + 'docs/protocols/mcp.md': (content) => + content.replace( + /[\s\S]*?/, + '', + ), + }, + }; + + const cases: [string, Change, string[]][] = [ + [ + 'a package version bumped in package.json', + { + manifest: (manifest) => { + manifest.peerDependencies.mppx = '0.13.2'; + }, + }, + [ + stale('README.md', 'matrix', ALL), + stale('docs/protocols.md', 'matrix', ALL), + stale('docs/protocols/mpp.md', 'pins', 'src/support/mpp.json and package.json'), + ], + ], + [ + 'a recorded package missing from package.json', + { + manifest: (manifest) => { + delete manifest.peerDependencies['@sd-jwt/core']; + delete manifest.devDependencies['@sd-jwt/core']; + }, + }, + [ + 'src/support/ap2.json: package @sd-jwt/core (runtime) is not in package.json dependencies or peerDependencies', + stale('README.md', 'matrix', ALL), + stale('docs/protocols.md', 'matrix', ALL), + stale('docs/protocols/ap2.md', 'pins', 'src/support/ap2.json and package.json'), + ], + ], + [ + 'an exclusion added to a record', + { records: (records) => void record(records, 'acp').exclusions.push({ name: 'carts' }) }, + [stale('docs/protocols/acp.md', 'exclusions', 'src/support/acp.json')], + ], + [ + 'an experimental profile recorded as supported', + { + records: (records) => { + record(records, 'a2a').status = 'supported'; + }, + }, + [ + stale('README.md', 'badges', 'src/support/*.json'), + stale('README.md', 'matrix', ALL), + stale('docs/protocols.md', 'matrix', ALL), + 'README.md: the Versioning sentence names A2A, which src/support/a2a.json records as supported', + 'plugins/agent-commerce-gateway/skills/agent-commerce/SKILL.md: the "exist but are experimental" sentence names A2A, which src/support/a2a.json records as supported', + 'docs/protocols/a2a.md: says **Experimental.**, but src/support/a2a.json records supported', + ], + ], + ['a hand edit inside a generated region', HAND_EDIT, [stale('README.md', 'matrix', ALL)]], + [ + 'a deleted evidence file', + { deleted: 'tests/e2e/payment/x402-settlement.e2e.test.ts' }, + [ + 'src/support/x402.json: cites tests/e2e/payment/x402-settlement.e2e.test.ts, which does not exist', + ], + ], + [ + 'an experimental profile missing from the Versioning sentence', + { + edit: { + 'README.md': (content) => content.replace('MPP, A2A, ACP, AP2,', 'A2A, ACP, AP2,'), + }, + }, + [ + 'README.md: the Versioning sentence omits MPP, which src/support/mpp.json records as experimental', + ], + ], + [ + 'an x402 route row whose status differs from its feature', + { + edit: { + 'docs/protocols/x402.md': (content) => + content.replace(/(\| NEAR +\| )partial/, '$1supported'), + }, + }, + [ + 'docs/protocols/x402.md: the "NEAR" row says supported, but src/support/x402.json records exact-near as partial', + ], + ], + [ + 'a region whose markers were removed', + MARKERS_REMOVED, + ['docs/protocols/mcp.md: region "pins" appears 0 times, not once'], + ], + ]; + + it.each(cases)('names the place of %s', (_, change, expected) => { + expect(supportProblems(changed(change))).toEqual(expected); + }); + + it('escapes a pipe inside a generated table cell', () => { + const piped = changed({ + records: (records) => { + record(records, 'acp').subset = 'checkout | discovery'; + }, + }); + expect(regionUpdates(piped).get('docs/protocols.md')).toContain('checkout \\| discovery'); + }); + + it('--write restores a hand-edited region and refuses a file with missing markers', () => { + expect(regionUpdates(changed(HAND_EDIT))).toEqual( + new Map([['README.md', tree.read('README.md')]]), + ); + expect(() => regionUpdates(changed(MARKERS_REMOVED))).toThrow( + 'docs/protocols/mcp.md: add the markers for region(s) pins first', + ); + }); +}); From 9f51e8d4913752a3d50df6315a44e7f452121422 Mon Sep 17 00:00:00 2001 From: Revinand Date: Wed, 18 Nov 2026 16:04:57 +0100 Subject: [PATCH 05/14] feat(cli): mark doctor results that could not be determined --- README.md | 16 +- docs/contracts.md | 11 + docs/security.md | 3 + .../references/troubleshooting.md | 27 +- src/cli/commands/doctor/ap2.ts | 4 +- src/cli/commands/doctor/index.ts | 75 ++- src/cli/commands/doctor/payments.ts | 44 +- src/cli/commands/doctor/protocols.ts | 26 +- src/cli/commands/doctor/report.ts | 3 +- src/cli/commands/doctor/secrets.ts | 42 ++ src/cli/commands/doctor/storage.ts | 9 +- src/cli/commands/doctor/types.ts | 30 +- src/cli/lib/config-client.ts | 7 + src/cli/lib/http.ts | 16 +- src/config/env.ts | 44 ++ src/config/index.ts | 5 +- src/config/load.ts | 13 +- src/core/no-answer.ts | 34 ++ src/gateway/well-known.ts | 58 +- src/payments/x402/facilitator.ts | 19 +- src/payments/x402/provider/health.ts | 38 +- tests/integration/doctor-certainty.test.ts | 317 +++++++++++ .../goldens/2.7.2/doctor-multi.json | 9 +- .../goldens/2.7.2/doctor-single.json | 14 +- .../goldens/2.7.2/well-known-multi.json | 3 +- .../goldens/2.7.2/well-known-single.json | 6 +- tests/integration/mpp-config.test.ts | 19 +- tests/unit/cli/doctor-certainty.test.ts | 496 ++++++++++++++++++ tests/unit/cli/doctor.test.ts | 13 +- tests/unit/cli/fixtures.ts | 11 +- tests/unit/cli/lib.test.ts | 29 +- tests/unit/config/env.test.ts | 52 +- tests/unit/config/load.test.ts | 23 +- tests/unit/core/no-answer.test.ts | 66 +++ tests/unit/gateway/helpers.ts | 14 +- tests/unit/gateway/server.test.ts | 82 +++ .../facilitator-isolation.test.ts | 2 + .../provider-health-mocked.test.ts | 112 +++- 38 files changed, 1678 insertions(+), 114 deletions(-) create mode 100644 src/cli/commands/doctor/secrets.ts create mode 100644 src/core/no-answer.ts create mode 100644 tests/integration/doctor-certainty.test.ts create mode 100644 tests/unit/cli/doctor-certainty.test.ts create mode 100644 tests/unit/core/no-answer.test.ts diff --git a/README.md b/README.md index fc75434..5e0e576 100644 --- a/README.md +++ b/README.md @@ -504,6 +504,7 @@ spend real USDC when their opt-ins and credentials are present. $ npm run agent-commerce -- doctor --config config-demo.yaml PASS Config valid: 2 resource(s), merchant "Demo Data Store" (using local chain manifest .deploy/local.json for X402_ASSET, X402_ASSET_NAME, X402_ASSET_VERSION, X402_ASSET_DECIMALS, MERCHANT_WALLET, X402_FACILITATOR_PRIVATE_KEY) +PASS Secrets 6 set (MERCHANT_WALLET, X402_ASSET, X402_ASSET_DECIMALS, X402_ASSET_NAME, X402_ASSET_VERSION, X402_FACILITATOR_PRIVATE_KEY); 8 defaulted (ADMIN_TOKEN, DASHBOARD_ORIGIN, GATEWAY_PORT, GATEWAY_PUBLIC_BASE_URL, MERCHANT_API_BASE_URL, RECEIPT_STORE_PATH, X402_NETWORK, X402_RPC_URL) PASS Gateway healthy and ready at http://127.0.0.1:8080 PASS Backend 2/2 backend host(s) reachable PASS Protocols http=on mcp=on (/mcp) a2a=off acp=off @@ -511,12 +512,13 @@ INFO A2A disabled INFO ACP disabled INFO AP2 disabled PASS Payments x402 v2 (scheme=exact) enabled - LOCAL dev chain (eip155:31337), destination=0x7099…79C8, facilitator=local (in-process), paymentFlow=authorization +PASS Payments (offers) 1 offer(s) pass their health checks INFO Payments (MPP) MPP not configured PASS Storage sqlite schema v5 writable; receipts=2 PASS Transactions none unresolved PASS Protocol versions reported by gateway /.well-known/agent-commerce -Score: 8/8 checks passed +Score: 10/10 checks passed ``` `doctor` compares live settlement terms with local config for each rail and @@ -524,6 +526,18 @@ resource: offer order, network, token, payee and transfer method, plus decimals and payment flows when published. Mismatches fail the check. It also names failing offers when health is published; reasons appear in gateway debug logs. +`Secrets` lists each config placeholder (`${VAR}`) as missing, set or +defaulted. Config loading stops at the first missing variable; this check +reports them all. It fails if any are missing and prints names only, never +values or defaults. + +A check that cannot reach a verdict carries `undetermined`: `unreachable` +for known transport failures, such as refused or reset connections, timeouts +or temporary DNS failures; `skipped` when a prerequisite fails. Unresolvable +hostnames and TLS errors leave the check unmarked. +Text output appends `[not determined: ]`. The marker does not affect +status, score or exit code; an unreachable gateway still fails its check. + Exits non-zero if anything fails. `--json` for machines. ### `agent-commerce reconcile` diff --git a/docs/contracts.md b/docs/contracts.md index 9c2978c..a286c33 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -457,6 +457,17 @@ persistence must not fail the commerce flow. as they become idle and resolves after requests and adapters have finished. In 2.5, adapters stopped first and could close a store still in use by a request. +- 2.8.0: x402 health marks an offer's component with `undetermined: 'unreachable'` + for recognized transport failures, including refused, reset or timed-out + connections, temporary DNS failures and request timeouts. Unresolvable + hostnames, TLS or certificate errors, JSON-RPC errors, non-2xx responses and + reverts leave the component unmarked. MPP uses the same provider to report its + offer's health. + - `/.well-known` adds `status` and `undetermined` to a single-offer + `payments.x402` block and to `payments.mpp`, and `undetermined` to each + offer in `options` and `resourceOptions`. + - `doctor` reads them for `Payments (offers)` and the new + `Payments (MPP offers)` check. ### Authorization and AP2 diff --git a/docs/security.md b/docs/security.md index c8f65e5..6f6e369 100644 --- a/docs/security.md +++ b/docs/security.md @@ -573,6 +573,9 @@ real funds. | **the payment proof header as a bearer credential** | with matching input and any required mandate, `PAYMENT-SIGNATURE` retrieves the stored response until retention ends. Keep it out of proxy, APM and access logs; the gateway's logger redacts it | `tests/integration/payment-retries.test.ts` ("redelivers an exact resend, marked as a replay, without a second charge"), `tests/unit/gateway/logger.test.ts` ("redacts every wire header that carries a credential or a proof") | | **a retention window outside 1 to 8760 hours** | config load refuses it, and a pipeline built without config throws `CONFIG_INVALID` before any payment work | `tests/unit/config/schema.test.ts` ("refuses a retention of %s hours as too long", "refuses a retention of %s", "accepts the longest retention, one year"), `tests/unit/core/execution/pipeline-retry.test.ts` ("refuses a retention of %s hours before any provider call", "accepts a retention of one year") | | **an A2A in-flight refusal that tells the client to resend on the consumed task** | the failed task reports `retryable: false` with no `retryAfterSeconds`; the client starts a new task with the same payment `id` | `tests/unit/protocols-a2a/payment-resume.test.ts` ("does not tell the client to retry an in-flight payment id on the consumed task") | +| **`doctor` reporting a misconfigured RPC or facilitator as unreachable** | marks an offer `unreachable` for recognized transport failures, including refused or reset connections, temporary DNS failures and timeouts. Unresolvable hostnames, TLS and certificate errors, JSON-RPC errors, non-2xx responses, reverts, unparseable bodies, missing peers and unrecognized errors fail without this marker | `tests/unit/core/no-answer.test.ts` ("is false for %s"), `tests/unit/payments-x402/provider-health-mocked.test.ts` ("leaves the %s unmarked after %s"), `tests/integration/doctor-certainty.test.ts` ("%s: %s FAILs unmarked when %s") | +| **`doctor` reporting a gateway that answered as unreachable** | marks `Gateway` `unreachable` for recognized transport failures, including refused or reset connections and timeouts. Unresolvable hostnames, ports rejected by fetch, non-2xx `/health` responses and Host refusals fail unmarked; checks that need the discovery document are `skipped`. Responses with unusable document content leave those checks unmarked | `tests/unit/cli/doctor-certainty.test.ts` ("when %s", "says a gateway that answered non-2xx is unhealthy, not unreachable"), `tests/integration/doctor-certainty.test.ts` ("leaves Gateway unmarked, and says why, when fetch refuses the port") | +| **the `doctor` Secrets check printing a value or a default** | reports placeholder names in text and JSON, never variable values or defaults | `tests/unit/cli/doctor-certainty.test.ts` ("FAILs naming every missing variable, and prints no value or default"), `tests/unit/config/env.test.ts` ("returns names only: no value and no default") | A facilitator verdict is a returned result. The SDK throws when a remote `/verify` answers with a non-2xx status; the binding turns that throw back into diff --git a/plugins/agent-commerce-gateway/skills/agent-commerce/references/troubleshooting.md b/plugins/agent-commerce-gateway/skills/agent-commerce/references/troubleshooting.md index 80e0d51..061fb01 100644 --- a/plugins/agent-commerce-gateway/skills/agent-commerce/references/troubleshooting.md +++ b/plugins/agent-commerce-gateway/skills/agent-commerce/references/troubleshooting.md @@ -77,12 +77,21 @@ before retrying; the gateway does not refund the payment automatically. otherwise it is 0, even with warnings. For L2, also require a passing `Gateway` check and report warnings. -| Check | Not passing means | -| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `Config` | `validate` would fail; fix that first | -| `Gateway` | `FAIL`: `/health` is unreachable or returns a non-2xx status. Check the URL derived from `server.host` and `server.port`, or pass `--gateway `. `WARN`: `/health` passed but `/ready` did not; inspect `/ready` for store, adapter or provider failures | -| `Backend` | No HTTP response from some or all distinct configured URLs. Probes use GET without backend headers or a body, substitute `demo-check` for path parameters and accept any HTTP status as reachable. Check the API and `MERCHANT_API_BASE_URL`; a PASS does not verify the configured operation | -| `Protocols` | The gateway's `/.well-known/agent-commerce` is unreachable | -| `Payments`, `Payments (MPP)` | The running gateway's live offers or MPP setting differ from the config, usually because it runs an older config. Restart it | -| `Payments (offers)` | `FAIL`: an offer's health check fails; `WARN`: one is degraded. Causes include an unreachable RPC or facilitator, or a missing Solana, NEAR or CDP peer. Inspect `/ready`; the gateway logs each reason at debug level | -| `Storage` | `WARN`: no receipts file at `storage.receipts.path` yet, or the running gateway uses another path. `FAIL`: the file cannot be opened | +A check that cannot reach a verdict carries `undetermined`: `unreachable` +for a recognized transport failure, or `skipped` when a prerequisite fails. +For an `unreachable` `Gateway` or `Backend`, check the service, its address and +network access. An unmarked failure naming `ENOTFOUND`, a certificate or +`bad port` calls for checking DNS, TLS configuration and the URL. For a +`skipped` check, fix the failing `Config` or `Gateway` first. Text output +appends `[not determined: ]`. + +| Check | Not passing means | +| -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Config` | `validate` would fail; fix that first | +| `Secrets` | `FAIL`: a `${VAR}` placeholder in the config is unset; the detail lists all missing names, never values. Set them in the environment or in a file passed with `--env-file` | +| `Gateway` | `FAIL`: `/health` could not be checked or returned a non-2xx status. The `unreachable` marker identifies recognized transport failures. Check the URL derived from `server.host` and `server.port`, or pass `--gateway `. `WARN`: `/health` passed but `/ready` did not; inspect `/ready` for store, adapter or provider failures | +| `Backend` | No HTTP response from some or all distinct configured URLs. Probes use GET without backend headers or a body, substitute `demo-check` for path parameters and accept any HTTP status as reachable. Check the API and `MERCHANT_API_BASE_URL`; a PASS does not verify the configured operation | +| `Protocols` | The gateway's `/.well-known/agent-commerce` gave no answer or a non-2xx status | +| `Payments`, `Payments (MPP)` | The running gateway's live offers or MPP setting differ from the config, usually because it runs an older config. Restart it | +| `Payments (offers)`, `Payments (MPP offers)` | `FAIL`: an offer's health check fails; `WARN`: one is degraded. `unreachable` means every failing or degraded offer has a recognized RPC or facilitator transport failure. Unmarked failures can indicate a bad response, a hostname that does not resolve, a TLS error, or a missing Solana, NEAR or CDP peer. Inspect `/ready`; the gateway logs each reason at debug level | +| `Storage` | `WARN`: no receipts file at `storage.receipts.path` yet, or the running gateway uses another path. `FAIL`: the file cannot be opened | diff --git a/src/cli/commands/doctor/ap2.ts b/src/cli/commands/doctor/ap2.ts index 6336d15..810c1b2 100644 --- a/src/cli/commands/doctor/ap2.ts +++ b/src/cli/commands/doctor/ap2.ts @@ -11,7 +11,7 @@ import ap2Record from '../../../support/ap2.json' with { type: 'json' }; import { exclusionNames } from '../../../support/claims'; import type { GatewayConfig } from '../../lib/config-client'; import { type LegacyState, legacyStoreCheck } from './storage'; -import type { DoctorCheck } from './types'; +import { type DoctorCheck, SKIPPED_CONFIG_INVALID } from './types'; // Issuer ids and how many keys each carries. Never a key function describeIssuers( @@ -33,7 +33,7 @@ export function ap2Checks(config: GatewayConfig | undefined, legacy: LegacyState // issuer ids and key counts appear. const ap2 = config?.authorization?.ap2; if (config === undefined) { - checks.push({ name: 'AP2', status: 'WARN', detail: 'skipped: config invalid' }); + checks.push({ name: 'AP2', status: 'WARN', ...SKIPPED_CONFIG_INVALID }); } else if (ap2 === undefined || !ap2.enabled) { checks.push({ name: 'AP2', status: 'INFO', detail: 'disabled' }); } else { diff --git a/src/cli/commands/doctor/index.ts b/src/cli/commands/doctor/index.ts index bf1a479..ae978f9 100644 --- a/src/cli/commands/doctor/index.ts +++ b/src/cli/commands/doctor/index.ts @@ -5,7 +5,11 @@ import { createSqliteReceiptStore, openSqliteReceiptStoreReadOnly, } from '../../../storage/receipts'; -import { type GatewayConfig, loadConfigDynamic } from '../../lib/config-client'; +import { + type GatewayConfig, + loadConfigDynamic, + readConfigFileDynamic, +} from '../../lib/config-client'; import { fetchJson } from '../../lib/http'; import { fillEnvFromLocalChainManifest, @@ -17,8 +21,18 @@ import { readVersionReport } from '../../lib/versions'; import { ap2Checks } from './ap2'; import { paymentChecks } from './payments'; import { protocolChecks } from './protocols'; +import { secretsCheck } from './secrets'; import { storageChecks } from './storage'; -import type { CheckStatus, DoctorCheck, DoctorDeps, DoctorOptions, DoctorReport } from './types'; +import { + type CheckStatus, + type DoctorCheck, + type DoctorDeps, + type DoctorOptions, + type DoctorReport, + SKIPPED_CONFIG_INVALID, + type Undetermined, + undeterminedField, +} from './types'; const CHECK_TIMEOUT_MS = 1500; @@ -101,22 +115,39 @@ export async function runDoctor( }); } + // Skip Secrets when an injected loader has no reader; the default could read + // a different config + const readConfigFile = + deps.readConfigFile ?? (deps.loadConfig === undefined ? readConfigFileDynamic : undefined); + if (readConfigFile !== undefined) { + checks.push(await secretsCheck(readConfigFile, options.configPath, env)); + } + const gatewayUrl = deriveGatewayUrl(options.gatewayUrl, config); - // 2. Gateway + // 2. Gateway. Status 0 means the request threw; `noAnswer` identifies a known + // transport failure. Hostname and TLS errors remain unmarked. const health = await fetchJson(fetchImpl, `${gatewayUrl}/health`, CHECK_TIMEOUT_MS); let gatewayUp = false; + // Why the checks that read the well-known document have no live data + let liveCause: Undetermined | undefined; if (!health.ok) { + liveCause = health.noAnswer ? 'unreachable' : 'skipped'; checks.push({ name: 'Gateway', status: 'FAIL', - detail: `unreachable at ${gatewayUrl} (${health.error ?? `HTTP ${health.status}`})`, + detail: + health.status === 0 + ? `unreachable at ${gatewayUrl} (${health.error ?? 'no answer'})` + : `unhealthy at ${gatewayUrl} (HTTP ${health.status})`, + ...undeterminedField(health.noAnswer ? 'unreachable' : undefined), }); } else { const ready = await fetchJson(fetchImpl, `${gatewayUrl}/ready`, CHECK_TIMEOUT_MS); // Doctor sends no Origin header, so a 403 from /ready means the Host was // rejected. GET /health skips the Host check used by other routes. if (ready.status === 403) { + liveCause = 'skipped'; checks.push({ name: 'Gateway', status: 'FAIL', @@ -131,6 +162,7 @@ export async function runDoctor( name: 'Gateway', status: 'WARN', detail: `healthy but not ready at ${gatewayUrl} (${ready.error ?? `HTTP ${ready.status}`})`, + ...undeterminedField(ready.noAnswer ? 'unreachable' : undefined), }, ); } @@ -138,7 +170,7 @@ export async function runDoctor( // 3. Backend(s) if (config === undefined) { - checks.push({ name: 'Backend', status: 'WARN', detail: 'skipped: config invalid' }); + checks.push({ name: 'Backend', status: 'WARN', ...SKIPPED_CONFIG_INVALID }); } else if (config.resources.length === 0) { checks.push({ name: 'Backend', status: 'INFO', detail: 'no resources configured' }); } else { @@ -147,13 +179,19 @@ export async function runDoctor( const results = await Promise.all( urls.map((url) => fetchJson(fetchImpl, url, CHECK_TIMEOUT_MS)), ); - const reachable = results.filter((r) => r.status !== 0).length; + // Any HTTP response establishes reachability. Mark unreachable only when all + // requests that threw have recognized transport failures. + const unreached = results.filter((r) => r.status === 0); + const reachable = urls.length - unreached.length; const status: CheckStatus = reachable === urls.length ? 'PASS' : reachable === 0 ? 'FAIL' : 'WARN'; checks.push({ name: 'Backend', status, detail: `${reachable}/${urls.length} backend host(s) reachable`, + ...undeterminedField( + unreached.length > 0 && unreached.every((r) => r.noAnswer) ? 'unreachable' : undefined, + ), }); } @@ -165,14 +203,23 @@ export async function runDoctor( CHECK_TIMEOUT_MS, ) : undefined; + // Clear the marker after any document response, even if its content is unusable + if (wellKnown !== undefined) liveCause = wellKnown.noAnswer ? 'unreachable' : undefined; // 5-7. Protocols, AP2, payments and storage. Read import records first so // protocol and AP2 checks can report the status of deprecated store keys. const storage = await storageChecks(config, createStore); - checks.push(...protocolChecks(config, wellKnown, storage.legacy)); + checks.push(...protocolChecks(config, wellKnown, storage.legacy, liveCause)); checks.push(...ap2Checks(config, storage.legacy)); checks.push( - ...(await paymentChecks(config, wellKnown, gatewayUrl, chainDeploy, deps.loadViemAccounts)), + ...(await paymentChecks( + config, + wellKnown, + gatewayUrl, + chainDeploy, + deps.loadViemAccounts, + liveCause, + )), ); checks.push(...storage.checks); @@ -188,7 +235,8 @@ export async function runDoctor( checks.push({ name: 'Protocol versions', status: 'INFO', - detail: `gateway unreachable; local pins: ${local.pinned.map((p) => `${p.name}@${p.version}`).join(', ')}`, + detail: `${liveCause === 'unreachable' ? 'gateway unreachable' : 'gateway versions unavailable'}; local pins: ${local.pinned.map((p) => `${p.name}@${p.version}`).join(', ')}`, + ...undeterminedField(liveCause), }); } @@ -200,4 +248,11 @@ export async function runDoctor( } export { printDoctorReport } from './report'; -export type { CheckStatus, DoctorCheck, DoctorDeps, DoctorOptions, DoctorReport } from './types'; +export type { + CheckStatus, + DoctorCheck, + DoctorDeps, + DoctorOptions, + DoctorReport, + Undetermined, +} from './types'; diff --git a/src/cli/commands/doctor/payments.ts b/src/cli/commands/doctor/payments.ts index c8f6515..e452d29 100644 --- a/src/cli/commands/doctor/payments.ts +++ b/src/cli/commands/doctor/payments.ts @@ -23,7 +23,13 @@ import x402Record from '../../../support/x402.json' with { type: 'json' }; import type { GatewayConfig } from '../../lib/config-client'; import { PLACEHOLDER_ASSET_ADDRESS } from '../../lib/init-config'; import { maskMiddle } from '../../lib/mask'; -import type { DoctorCheck, WellKnownResult } from './types'; +import { + type DoctorCheck, + SKIPPED_CONFIG_INVALID, + type Undetermined, + undeterminedField, + type WellKnownResult, +} from './types'; const QUOTE_STATUS = featureStatus(x402Record, 'erc-8409-quotes'); @@ -51,6 +57,8 @@ interface RailOffer { readonly assetTransferMethod?: string; /** The live offer's health status, when the gateway publishes it */ readonly status?: string; + // Set when the gateway reports the offer's probe as unreachable + readonly undetermined?: 'unreachable'; } // A rail's terms, as configured or as the running gateway publishes them @@ -67,7 +75,7 @@ interface RailTerms { type LiveRailResult = RailTerms | 'disabled' | undefined; function readOffer(rec: Record, rail: 'x402' | 'mpp'): RailOffer | undefined { - const { asset, network, assetDecimals, assetTransferMethod, status } = rec; + const { asset, network, assetDecimals, assetTransferMethod, status, undetermined } = rec; const payTo = rec[rail === 'mpp' ? 'recipient' : 'payTo']; if (typeof asset !== 'string' || typeof network !== 'string' || typeof payTo !== 'string') { return undefined; @@ -79,6 +87,7 @@ function readOffer(rec: Record, rail: 'x402' | 'mpp'): RailOffe ...(typeof assetDecimals === 'number' ? { assetDecimals } : {}), ...(typeof assetTransferMethod === 'string' ? { assetTransferMethod } : {}), ...(typeof status === 'string' ? { status } : {}), + ...(undetermined === 'unreachable' ? { undetermined } : {}), }; } @@ -292,6 +301,7 @@ function railOffer(option: { function offerHealthCheck( live: RailTerms, named: (network: string) => string, + name: string, ): DoctorCheck | undefined { const all = [...live.offers, ...Object.values(live.resourceOffers ?? {}).flat()]; const offers = [ @@ -312,7 +322,7 @@ function offerHealthCheck( .join('; '); if (failing.length === 0 && degraded.length === 0) { return { - name: 'Payments (offers)', + name, status: 'PASS', detail: `${reported.length} offer(s) pass their health checks`, }; @@ -321,10 +331,13 @@ function offerHealthCheck( ...(failing.length > 0 ? [`failing: ${describe(failing)}`] : []), ...(degraded.length > 0 ? [`degraded: ${describe(degraded)}`] : []), ]; + // Keep the aggregate unmarked if any failing or degraded offer is unmarked + const unanswered = [...failing, ...degraded].every((offer) => offer.undetermined !== undefined); return { - name: 'Payments (offers)', + name, status: failing.length > 0 ? 'FAIL' : 'WARN', detail: `${problems.join('; ')}. The gateway logs each reason at debug level`, + ...undeterminedField(unanswered ? 'unreachable' : undefined), }; } @@ -384,6 +397,7 @@ function quoteCheck( body: Record | undefined, gatewayUrl: string, stale: string, + liveCause: Undetermined | undefined, ): DoctorCheck | undefined { const name = 'Payments (quotes)'; if (enabled && local === 'invalid') { @@ -404,6 +418,7 @@ function quoteCheck( name, status: 'INFO', detail: `ERC-8409 quotes enabled (${QUOTE_STATUS})${localIssuer !== undefined ? `, issuer=${localIssuer} from the local key` : ''}; the gateway's issuer could not be read`, + ...undeterminedField(liveCause), } : undefined; } @@ -447,13 +462,17 @@ export async function paymentChecks( chainDeploy = false, // Load this optional peer only when local x402 quote signing is enabled loadAccounts: LoadViemAccounts = () => import('viem/accounts'), + // Why the well-known document was not obtained; absent after a response + liveCause?: Undetermined, ): Promise { const checks: DoctorCheck[] = []; // Suggest the repository deployment script only when the caller found it const stale = `; the gateway may be running against an older deployment - restart it${chainDeploy ? ' or re-run chain:deploy' : ''}`; // 6. Payments const x402 = config?.payments.x402; - if (x402 === undefined || !x402.enabled) { + if (config === undefined) { + checks.push({ name: 'Payments', status: 'INFO', ...SKIPPED_CONFIG_INVALID }); + } else if (x402 === undefined || !x402.enabled) { checks.push({ name: 'Payments', status: 'INFO', detail: 'x402 not configured' }); } else { const options = x402.options ?? [x402]; @@ -501,6 +520,7 @@ export async function paymentChecks( name: 'Payments', status: 'INFO', detail: `${summary} (gateway's live settlement config could not be verified)`, + ...undeterminedField(liveCause), }); } else { const configured: RailTerms = { @@ -523,7 +543,7 @@ export async function paymentChecks( ? { name: 'Payments', status: 'PASS', detail: summary } : { name: 'Payments', status: 'FAIL', detail: `${mismatch}${stale}` }, ); - const offerHealth = offerHealthCheck(live, named); + const offerHealth = offerHealthCheck(live, named, 'Payments (offers)'); if (offerHealth !== undefined) checks.push(offerHealth); } const quotes = quoteCheck( @@ -535,6 +555,7 @@ export async function paymentChecks( wellKnown?.ok ? wellKnown.body : undefined, gatewayUrl, stale, + liveCause, ); if (quotes !== undefined) checks.push(quotes); if (mode === 'mainnet') { @@ -550,7 +571,9 @@ export async function paymentChecks( } } const mpp = config?.payments.mpp; - if (mpp === undefined || !mpp.enabled) { + if (config === undefined) { + checks.push({ name: 'Payments (MPP)', status: 'INFO', ...SKIPPED_CONFIG_INVALID }); + } else if (mpp === undefined || !mpp.enabled) { checks.push({ name: 'Payments (MPP)', status: 'INFO', detail: 'MPP not configured' }); } else { const { mode, where, via } = describeSettlement(mpp.network, mpp.facilitator); @@ -586,6 +609,7 @@ export async function paymentChecks( name: 'Payments (MPP)', status: 'INFO', detail: `${summary} (live MPP settlement config unavailable for comparison)`, + ...undeterminedField(liveCause), }); } else { const mismatch = findRailMismatch(configured, live, 'recipient'); @@ -594,6 +618,12 @@ export async function paymentChecks( ? { name: 'Payments (MPP)', status: 'PASS', detail: summary } : { name: 'Payments (MPP)', status: 'FAIL', detail: `${mismatch}${stale}` }, ); + const offerHealth = offerHealthCheck( + live, + (network) => `${findX402Network(network)?.displayName ?? 'unknown network'} (${network})`, + 'Payments (MPP offers)', + ); + if (offerHealth !== undefined) checks.push(offerHealth); } if (mode === 'mainnet') { checks.push( diff --git a/src/cli/commands/doctor/protocols.ts b/src/cli/commands/doctor/protocols.ts index dff2337..6f533e0 100644 --- a/src/cli/commands/doctor/protocols.ts +++ b/src/cli/commands/doctor/protocols.ts @@ -18,7 +18,13 @@ import acpRecord from '../../../support/acp.json' with { type: 'json' }; import { exclusionNames } from '../../../support/claims'; import type { GatewayConfig } from '../../lib/config-client'; import { type LegacyState, legacyStoreCheck } from './storage'; -import type { DoctorCheck, WellKnownResult } from './types'; +import { + type DoctorCheck, + SKIPPED_CONFIG_INVALID, + type Undetermined, + undeterminedField, + type WellKnownResult, +} from './types'; /** * The resource mapped to each checkout operation, re-checked against the rules @@ -64,13 +70,23 @@ export function protocolChecks( config: GatewayConfig | undefined, wellKnown: WellKnownResult | undefined, legacy: LegacyState, + // Why the well-known document was not obtained; absent after a response + liveCause?: Undetermined, ): DoctorCheck[] { const checks: DoctorCheck[] = []; // 5. Protocols if (config === undefined) { - checks.push({ name: 'Protocols', status: 'WARN', detail: 'skipped: config invalid' }); + checks.push({ name: 'Protocols', status: 'WARN', ...SKIPPED_CONFIG_INVALID }); } else if (wellKnown === undefined || !wellKnown.ok) { - checks.push({ name: 'Protocols', status: 'FAIL', detail: 'well-known document unreachable' }); + checks.push({ + name: 'Protocols', + status: 'FAIL', + detail: + wellKnown === undefined || wellKnown.status === 0 + ? 'well-known document unreachable' + : `well-known document unavailable (HTTP ${wellKnown.status})`, + ...undeterminedField(liveCause), + }); } else { const mcpMountPath = config.protocols.mcp.enabled ? config.protocols.mcp.mountPath : undefined; const a2aMountPath = config.protocols.a2a.enabled ? config.protocols.a2a.mountPath : undefined; @@ -84,7 +100,7 @@ export function protocolChecks( // 5b. A2A specifics, from the pins rather than the live gateway. The spec // revision and the negotiation version look alike, so each is named. if (config === undefined) { - checks.push({ name: 'A2A', status: 'WARN', detail: 'skipped: config invalid' }); + checks.push({ name: 'A2A', status: 'WARN', ...SKIPPED_CONFIG_INVALID }); } else if (!config.protocols.a2a.enabled) { checks.push({ name: 'A2A', status: 'INFO', detail: 'disabled' }); } else { @@ -106,7 +122,7 @@ export function protocolChecks( // the bearer token, the idempotency path and the operation mapping. This // report prints the path and the mapping, never the token. if (config === undefined) { - checks.push({ name: 'ACP', status: 'WARN', detail: 'skipped: config invalid' }); + checks.push({ name: 'ACP', status: 'WARN', ...SKIPPED_CONFIG_INVALID }); } else if (!config.protocols.acp.enabled) { checks.push({ name: 'ACP', status: 'INFO', detail: 'disabled' }); } else { diff --git a/src/cli/commands/doctor/report.ts b/src/cli/commands/doctor/report.ts index f192026..879878c 100644 --- a/src/cli/commands/doctor/report.ts +++ b/src/cli/commands/doctor/report.ts @@ -23,7 +23,8 @@ export function printDoctorReport(report: DoctorReport, io: Io, json: boolean): } for (const check of report.checks) { const label = statusColor(check.status, check.status.padEnd(5)); - io.stdout(`${label} ${check.name.padEnd(20)} ${check.detail}`); + const mark = check.undetermined !== undefined ? ` [not determined: ${check.undetermined}]` : ''; + io.stdout(`${label} ${check.name.padEnd(20)} ${check.detail}${mark}`); } io.stdout(''); io.stdout(`Score: ${report.score.passed}/${report.score.total} checks passed`); diff --git a/src/cli/commands/doctor/secrets.ts b/src/cli/commands/doctor/secrets.ts new file mode 100644 index 0000000..d2e9c3b --- /dev/null +++ b/src/cli/commands/doctor/secrets.ts @@ -0,0 +1,42 @@ +// Secrets: every `${VAR}` placeholder in the raw config, by name and never by value + +import { listEnvPlaceholders } from '../../../config/env'; +import type { ConfigFileReader } from '../../lib/config-client'; +import type { DoctorCheck } from './types'; + +/** + * List all missing config variables; config loading stops at the first. + * Return names only, since values and defaults may contain credentials. + */ +export async function secretsCheck( + read: ConfigFileReader, + path: string | undefined, + env: NodeJS.ProcessEnv, +): Promise { + let raw: unknown; + try { + raw = await read({ ...(path !== undefined ? { path } : {}), env }); + } catch { + // The Config check reports why + return { + name: 'Secrets', + status: 'WARN', + detail: 'skipped: config file unreadable', + undetermined: 'skipped', + }; + } + const { missing, set, defaulted } = listEnvPlaceholders(raw, env); + const groups = [ + ...(missing.length > 0 ? [`${missing.length} missing (${missing.join(', ')})`] : []), + ...(set.length > 0 ? [`${set.length} set (${set.join(', ')})`] : []), + ...(defaulted.length > 0 ? [`${defaulted.length} defaulted (${defaulted.join(', ')})`] : []), + ]; + if (groups.length === 0) { + return { name: 'Secrets', status: 'INFO', detail: 'config reads no environment variable' }; + } + return { + name: 'Secrets', + status: missing.length > 0 ? 'FAIL' : 'PASS', + detail: groups.join('; '), + }; +} diff --git a/src/cli/commands/doctor/storage.ts b/src/cli/commands/doctor/storage.ts index 65f5855..2a4bde3 100644 --- a/src/cli/commands/doctor/storage.ts +++ b/src/cli/commands/doctor/storage.ts @@ -10,7 +10,12 @@ import { type SqliteReceiptStoreSummary, } from '../../../storage/receipts'; import type { GatewayConfig } from '../../lib/config-client'; -import type { CheckStatus, DoctorCheck, DoctorStore } from './types'; +import { + type CheckStatus, + type DoctorCheck, + type DoctorStore, + SKIPPED_CONFIG_INVALID, +} from './types'; // Whether an existing file is writable, without creating one function isWritableFile(path: string): boolean { @@ -141,7 +146,7 @@ export async function storageChecks( // 7. Storage if (config === undefined) { return { - checks: [{ name: 'Storage', status: 'WARN', detail: 'skipped: config invalid' }], + checks: [{ name: 'Storage', status: 'WARN', ...SKIPPED_CONFIG_INVALID }], legacy: undefined, }; } diff --git a/src/cli/commands/doctor/types.ts b/src/cli/commands/doctor/types.ts index dee5636..6824522 100644 --- a/src/cli/commands/doctor/types.ts +++ b/src/cli/commands/doctor/types.ts @@ -1,17 +1,26 @@ // The report doctor builds, and what a caller can inject import type { ReceiptStore } from '../../../core'; import type { SqliteReceiptStore } from '../../../storage/receipts'; -import type { ConfigLoader } from '../../lib/config-client'; +import type { ConfigFileReader, ConfigLoader } from '../../lib/config-client'; import type { FetchJsonResult, FetchLike } from '../../lib/http'; import type { ManifestEnvFill } from '../../lib/manifest-env'; import type { LoadViemAccounts } from './payments'; export type CheckStatus = 'PASS' | 'WARN' | 'FAIL' | 'INFO'; +/** + * Why a check could not reach a verdict: `unreachable` for a recognized + * transport failure, or `skipped` for a failed prerequisite. The marker does + * not affect the check's status, the score or the exit code. + */ +export type Undetermined = 'unreachable' | 'skipped'; + export interface DoctorCheck { readonly name: string; readonly status: CheckStatus; readonly detail: string; + /** Absent on a result that is a verdict */ + readonly undetermined?: Undetermined; } export interface DoctorReport { @@ -31,6 +40,12 @@ export type DoctorStore = ReceiptStore & { readonly summary?: SqliteReceiptStore export interface DoctorDeps { readonly fetchImpl?: FetchLike; readonly loadConfig?: ConfigLoader; + /** + * Reads raw config for the Secrets check. The default reader is used only + * when neither this reader nor `loadConfig` is injected; an injected loader + * without a reader skips the check. + */ + readonly readConfigFile?: ConfigFileReader; readonly createStore?: (path: string) => DoctorStore; readonly fillEnvFromManifest?: (env: NodeJS.ProcessEnv) => ManifestEnvFill; readonly hasChainDeployScript?: () => boolean; @@ -38,3 +53,16 @@ export interface DoctorDeps { } export type WellKnownResult = FetchJsonResult>; + +/** Returns `{ undetermined }` when a reason is given, otherwise an empty object */ +export function undeterminedField(reason: Undetermined | undefined): { + readonly undetermined?: Undetermined; +} { + return reason !== undefined ? { undetermined: reason } : {}; +} + +/** The fields of a check that did not run because config failed to load */ +export const SKIPPED_CONFIG_INVALID = { + detail: 'skipped: config invalid', + undetermined: 'skipped', +} as const; diff --git a/src/cli/lib/config-client.ts b/src/cli/lib/config-client.ts index 9030882..aa2ff9e 100644 --- a/src/cli/lib/config-client.ts +++ b/src/cli/lib/config-client.ts @@ -16,6 +16,9 @@ export interface LoadConfigOptions { export type ConfigLoader = (options?: LoadConfigOptions) => Promise; +/** Reads the loader's raw config before environment substitution and validation */ +export type ConfigFileReader = (options?: LoadConfigOptions) => Promise; + /** Validates an already-built raw config object, without touching the disk */ export type ConfigParser = (raw: unknown, env?: NodeJS.ProcessEnv) => Promise; @@ -34,6 +37,10 @@ export async function loadConfigDynamic(options: LoadConfigOptions = {}): Promis return (await importConfig()).loadConfig(options); } +export async function readConfigFileDynamic(options: LoadConfigOptions = {}): Promise { + return (await importConfig()).readConfigFile(options); +} + /** Validates a raw config object in memory; `init` uses it to validate before writing */ export async function parseConfigDynamic( raw: unknown, diff --git a/src/cli/lib/http.ts b/src/cli/lib/http.ts index 6b23ff5..584f6bb 100644 --- a/src/cli/lib/http.ts +++ b/src/cli/lib/http.ts @@ -1,3 +1,5 @@ +import { gotNoAnswer } from '../../core/no-answer'; + /** * Fetch with a timeout, for `doctor`. `fetchImpl` is injected so tests can * pass a fake `fetch` and never touch the network. @@ -6,9 +8,12 @@ export type FetchLike = typeof fetch; export interface FetchJsonResult { readonly ok: boolean; + /** The HTTP status, or 0 when the request threw */ readonly status: number; readonly body?: T; readonly error?: string; + /** Present when `gotNoAnswer` recognizes a transport failure */ + readonly noAnswer?: true; } export async function fetchJson( @@ -30,7 +35,16 @@ export async function fetchJson( return { ok: false, status: 0, - error: err instanceof Error ? err.message : 'unknown fetch error', + error: errorText(err), + ...(gotNoAnswer(err) ? { noAnswer: true as const } : {}), }; } } + +// Include a nested cause's message to explain undici's generic "fetch failed" +function errorText(err: unknown): string { + if (!(err instanceof Error)) return 'unknown fetch error'; + let root = err; + for (let depth = 0; depth < 10 && root.cause instanceof Error; depth++) root = root.cause; + return root === err ? err.message : `${err.message}: ${root.message}`; +} diff --git a/src/config/env.ts b/src/config/env.ts index ed6cde7..9728a49 100644 --- a/src/config/env.ts +++ b/src/config/env.ts @@ -47,6 +47,50 @@ export function substituteEnv(value: unknown, env: NodeJS.ProcessEnv, path = '$' return value; } +/** Sorted placeholder names from raw config, grouped by how they resolve in the environment */ +export interface EnvPlaceholders { + /** `${VAR}` with `VAR` unset; config loading stops at the first missing variable */ + readonly missing: readonly string[]; + /** `${VAR:-default}` with `VAR` unset or empty */ + readonly defaulted: readonly string[]; + readonly set: readonly string[]; +} + +/** + * Collect recognized placeholder names without validating template syntax; + * config loading reports unsupported templates. Each name appears once, using + * the most severe state: missing, then defaulted, then set. Return names only, + * never values or defaults. + */ +export function listEnvPlaceholders(raw: unknown, env: NodeJS.ProcessEnv): EnvPlaceholders { + // 0 set, 1 defaulted, 2 missing: a higher number is worse + const worst = new Map(); + const visit = (value: unknown): void => { + if (typeof value === 'string') { + for (const [, name = '', hasDefault] of value.matchAll(PLACEHOLDER_PATTERN)) { + const envValue = env[name]; + const state = + hasDefault !== undefined + ? envValue === undefined || envValue === '' + ? 1 + : 0 + : envValue === undefined + ? 2 + : 0; + worst.set(name, Math.max(state, worst.get(name) ?? 0)); + } + } else if (Array.isArray(value)) { + value.forEach(visit); + } else if (isRecord(value)) { + Object.values(value).forEach(visit); + } + }; + visit(raw); + const names = [...worst.keys()].sort(); + const named = (state: number) => names.filter((name) => worst.get(name) === state); + return { missing: named(2), defaulted: named(1), set: named(0) }; +} + function substituteString(value: string, env: NodeJS.ProcessEnv, path: string): string { assertTemplateIsSupported(value, path); return substituteOnce(value, env, path); diff --git a/src/config/index.ts b/src/config/index.ts index da4bf04..622595a 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -1,7 +1,8 @@ // `config.yaml` schema, loader and environment substitution -export { substituteEnv } from './env'; +export type { EnvPlaceholders } from './env'; +export { listEnvPlaceholders, substituteEnv } from './env'; export type { LoadConfigOptions } from './load'; -export { loadConfig } from './load'; +export { loadConfig, readConfigFile } from './load'; export type { GatewayConfig } from './schema'; export { parseConfig } from './schema'; diff --git a/src/config/load.ts b/src/config/load.ts index fc773b1..90019df 100644 --- a/src/config/load.ts +++ b/src/config/load.ts @@ -18,6 +18,14 @@ export interface LoadConfigOptions { } export async function loadConfig(options: LoadConfigOptions = {}): Promise { + return parseConfig(await readConfigFile(options), options.env ?? process.env); +} + +/** + * Read the same file as `loadConfig`, returning parsed YAML before environment + * substitution and config validation. File and YAML errors match `loadConfig`. + */ +export async function readConfigFile(options: LoadConfigOptions = {}): Promise { const env = options.env ?? process.env; const cwd = options.cwd ?? process.cwd(); const configPath = resolveConfigPath(options.path, env, cwd); @@ -32,9 +40,8 @@ export async function loadConfig(options: LoadConfigOptions = {}): Promise>; /** Absent unless the x402 provider signs ERC-8409 quotes */ readonly quote?: WellKnownX402Quote; - }; + } & OfferHealth; /** Public settlement fields; excludes the challenge secret and facilitator credentials */ readonly mpp?: { readonly enabled: boolean; @@ -111,12 +111,23 @@ export interface WellKnownDocument { readonly paymentFlow: X402PaymentFlow; /** Resources that set their own flow, by id; absent when none does */ readonly resourcePaymentFlows?: Readonly>; - }; + } & OfferHealth; }; } +/** + * Public probe results for one offer, without diagnostic detail. On a rail + * block, these fields describe its own offer and appear only when `options` + * is absent. + */ +export interface OfferHealth { + readonly status?: AdapterHealth['status']; + /** Marks an unreachable probe; `status` does not describe the offer's health */ + readonly undetermined?: 'unreachable'; +} + /** One x402 offer's public terms */ -export interface WellKnownX402Offer { +export interface WellKnownX402Offer extends OfferHealth { readonly network: string; readonly asset: string; readonly assetName?: string; @@ -124,8 +135,6 @@ export interface WellKnownX402Offer { readonly assetDecimals: number; readonly payTo: string; readonly assetTransferMethod?: 'permit2'; - /** Last reported health status, excluding diagnostic detail */ - readonly status?: AdapterHealth['status']; } /** @@ -172,14 +181,25 @@ function publicProtocols(protocols: GatewayConfig['protocols']): WellKnownProtoc }; } +// Find the offer's probe by its x402 component name; return no fields if absent +function offerHealth( + health: AdapterHealth | undefined, + offer: { readonly network: string; readonly asset: string; readonly payTo: string }, +): OfferHealth { + const name = x402OfferName(offer); + const component = health?.components?.find((candidate) => candidate.name === name); + if (component === undefined) return {}; + const { status, undetermined } = component; + return { status, ...(undetermined !== undefined ? { undetermined } : {}) }; +} + // Allowlist public offer fields: RPC URLs can contain API keys function publicOffer( option: X402OptionConfig, - statuses: ReadonlyMap, + health: AdapterHealth | undefined, ): WellKnownX402Offer { const { network, asset, assetName, assetVersion, assetDecimals, payTo, assetTransferMethod } = option; - const status = statuses.get(x402OfferName(option)); return { network, asset, @@ -188,7 +208,7 @@ function publicOffer( assetDecimals, payTo, ...(assetTransferMethod !== undefined ? { assetTransferMethod } : {}), - ...(status !== undefined ? { status } : {}), + ...offerHealth(health, option), }; } @@ -218,10 +238,10 @@ export function buildWellKnownDocument(options: BuildWellKnownOptions): WellKnow })); const { x402, mpp } = options.config.payments; - const x402Health = options.paymentHealth?.find((probed) => probed.name === 'x402')?.health; - const offerStatuses = new Map( - (x402Health?.components ?? []).map((component) => [component.name, component.status]), - ); + const probed = (name: string) => + options.paymentHealth?.find((provider) => provider.name === name)?.health; + const x402Health = probed('x402'); + const x402Options = x402?.options !== undefined && x402.options.length > 1 ? x402.options : []; const quote = publicQuote(options.paymentProviders); return { @@ -258,15 +278,15 @@ export function buildWellKnownDocument(options: BuildWellKnownOptions): WellKnow ), paymentFlow: x402.paymentFlow ?? X402_DEFAULT_PAYMENT_FLOW, ...flowOverrides(x402.resourcePaymentFlows), - ...(x402.options !== undefined && x402.options.length > 1 - ? { options: x402.options.map((option) => publicOffer(option, offerStatuses)) } - : {}), + ...(x402Options.length > 0 + ? { options: x402Options.map((option) => publicOffer(option, x402Health)) } + : offerHealth(x402Health, x402)), ...(x402.resourceOptions !== undefined ? { resourceOptions: Object.fromEntries( Object.entries(x402.resourceOptions).map(([id, list]) => [ id, - list.map((option) => publicOffer(option, offerStatuses)), + list.map((option) => publicOffer(option, x402Health)), ]), ), } @@ -289,6 +309,12 @@ export function buildWellKnownDocument(options: BuildWellKnownOptions): WellKnow mode: resolveDeploymentMode(requireX402Network(mpp.network, 'payments.mpp.network')), paymentFlow: mpp.paymentFlow ?? MPP_DEFAULT_PAYMENT_FLOW, ...flowOverrides(mpp.resourcePaymentFlows), + // MPP settles through an x402 provider, which names the offer + ...offerHealth(probed('mpp'), { + network: mpp.network, + asset: mpp.asset, + payTo: mpp.recipient, + }), }, } : {}), diff --git a/src/payments/x402/facilitator.ts b/src/payments/x402/facilitator.ts index 8cc1ea5..e9dfcaa 100644 --- a/src/payments/x402/facilitator.ts +++ b/src/payments/x402/facilitator.ts @@ -185,19 +185,18 @@ export function createRemoteFacilitatorBinding( // The SDK bounds each attempt but not its retry waits. `Promise.race` keeps // a handler on the abandoned call, so its later rejection is not unhandled. +// The `TimeoutError` cause lets health() classify the deadline as unreachable. function withDeadline(call: Promise, ms: number): Promise { let timer: NodeJS.Timeout | undefined; const deadline = new Promise((_, reject) => { - timer = setTimeout( - () => - reject( - new CommerceError( - 'PAYMENT_PROVIDER_UNAVAILABLE', - `x402 provider: facilitator /supported did not answer within ${ms / 1000} s`, - ), - ), - ms, - ); + timer = setTimeout(() => { + const message = `x402 provider: facilitator /supported did not answer within ${ms / 1000} s`; + reject( + new CommerceError('PAYMENT_PROVIDER_UNAVAILABLE', message, { + cause: new DOMException(message, 'TimeoutError'), + }), + ); + }, ms); timer.unref(); }); return Promise.race([call, deadline]).finally(() => clearTimeout(timer)); diff --git a/src/payments/x402/provider/health.ts b/src/payments/x402/provider/health.ts index 4803d83..19791d7 100644 --- a/src/payments/x402/provider/health.ts +++ b/src/payments/x402/provider/health.ts @@ -6,6 +6,7 @@ import { erc20Abi } from 'viem'; import { type AdapterHealth, CommerceError } from '../../../core'; import { redactedErrorText } from '../../../core/errors'; import { isRecord } from '../../../core/is-record'; +import { gotNoAnswer } from '../../../core/no-answer'; import { normalizeAddress } from '../addresses'; import type { createLocalPublicClient } from '../chain'; import type { FacilitatorBinding } from '../facilitator'; @@ -281,27 +282,37 @@ export function createHealthCheck(ctx: ProviderContext): () => Promise - offerHealth(offer, kinds).catch((err: unknown) => ({ - status: 'fail' as const, - detail: `x402 health check failed: ${redactedErrorText(err)}`, - })), + offerHealth(offer, kinds).catch( + (err: unknown): OfferResult => ({ + status: 'fail', + detail: `x402 health check failed: ${redactedErrorText(err)}`, + // The SDK throws its own timeout error from `/supported` + ...(gotNoAnswer(err, ['FacilitatorTimeoutError']) + ? { undetermined: 'unreachable' } + : {}), + }), + ), ), ); const failed = results.some((result) => result.status === 'fail'); const details = offers.flatMap((offer, index) => { - const result = results[index] as (typeof results)[number]; + const result = results[index] as OfferResult; if (failed && result.status !== 'fail') return []; return [offers.length === 1 ? result.detail : `${x402OfferName(offer)}: ${result.detail}`]; }); return { status: failed ? 'fail' : 'pass', detail: details.join('; '), - components: offers.map((offer, index) => ({ - name: x402OfferName(offer), - status: (results[index] as (typeof results)[number]).status, - })), + components: offers.map((offer, index) => { + const { status, undetermined } = results[index] as OfferResult; + return { + name: x402OfferName(offer), + status, + ...(undetermined !== undefined ? { undetermined } : {}), + }; + }), checkedAt, durationMs: clock.monotonicMs() - startedAt, }; @@ -338,6 +349,13 @@ export function createHealthCheck(ctx: ProviderContext): () => Promise { + upstream = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (chunk: Buffer) => chunks.push(chunk)); + req.on('end', () => { + const path = req.url ?? ''; + const reply = (value: unknown, status = 200) => { + res.writeHead(status, { 'content-type': 'application/json' }); + res.end(JSON.stringify(value)); + }; + const rpc = /^\/rpc\/(\w+)$/.exec(path); + if (rpc) { + const { id, method } = JSON.parse(Buffer.concat(chunks).toString('utf8')) as { + id: number; + method: string; + }; + const chainId = Number(rpc[1]); + const result = + method === 'eth_chainId' + ? `0x${chainId.toString(16)}` + : method === 'eth_getCode' + ? '0x6080' + : method === 'eth_call' + ? `0x${'6'.padStart(64, '0')}` + : undefined; + reply( + Number.isNaN(chainId) || result === undefined + ? { jsonrpc: '2.0', id, error: { code: -32601, message: `no ${method}` } } + : { jsonrpc: '2.0', id, result }, + ); + return; + } + if (path === '/facilitator/supported') { + reply({ + kinds: [BASE_SEPOLIA, ARBITRUM_SEPOLIA].map((network) => ({ + x402Version: 2, + scheme: 'exact', + network, + })), + extensions: [], + signers: {}, + }); + return; + } + if (path === '/denied/supported') { + reply({ error: 'unauthorized' }, 401); + return; + } + if (path.startsWith('/backend/')) { + reply({ ok: true }); + return; + } + res.writeHead(404).end(); + }); + }); + return new Promise((resolve) => + upstream.listen(0, '127.0.0.1', () => { + upstreamUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`; + resolve(); + }), + ); +} + +interface Targets { + readonly rpc?: string; + readonly facilitator?: string; + readonly backend?: string; +} + +// One paid resource on the given rail; every target defaults to the healthy upstream +function config(rail: 'x402' | 'x402-multi' | 'mpp', targets: Targets = {}): GatewayConfig { + const rpc = targets.rpc ?? `${upstreamUrl}/rpc/84532`; + const facilitator = { mode: 'remote', url: targets.facilitator ?? `${upstreamUrl}/facilitator` }; + const x402 = + rail === 'x402' + ? { network: BASE_SEPOLIA, rpcUrl: rpc, payTo: PAY_TO } + : { + options: [ + { network: BASE_SEPOLIA, payTo: PAY_TO }, + { network: ARBITRUM_SEPOLIA, payTo: PAY_TO }, + ], + networks: { + [BASE_SEPOLIA]: { rpcUrl: rpc }, + [ARBITRUM_SEPOLIA]: { rpcUrl: `${upstreamUrl}/rpc/421614` }, + }, + }; + return parseConfig( + { + version: 1, + merchant: { id: 'certainty', name: 'Certainty', publicBaseUrl: 'https://gateway.example' }, + server: { port: 8080, host: '127.0.0.1' }, + storage: { receipts: { driver: 'sqlite', path: ':memory:' } }, + protocols: { http: { enabled: true }, mcp: { enabled: false, mountPath: '/mcp' } }, + resources: { + report: { + name: 'Report', + input: { type: 'object', properties: {}, additionalProperties: false }, + backend: { + type: 'http', + method: 'GET', + url: `${targets.backend ?? upstreamUrl}/backend/r`, + }, + pricing: { type: 'fixed', amount: '0.01', currency: 'USDC' }, + expose: ['http'], + payments: [rail === 'mpp' ? 'mpp' : 'x402'], + }, + }, + payments: + rail === 'mpp' + ? { + mpp: { + enabled: true, + network: BASE_SEPOLIA, + rpcUrl: rpc, + asset: USDC, + assetName: 'USDC', + assetVersion: '2', + recipient: PAY_TO, + realm: 'gateway.example', + challengeSecret: 'certainty-mpp-challenge-secret-'.padEnd(32, 'x'), + facilitator, + }, + } + : { x402: { enabled: true, facilitator, maxTimeoutSeconds: 120, ...x402 } }, + }, + {}, + ); +} + +let gateway: GatewayInstance | undefined; + +// Start a gateway with configured payment providers, then run doctor against it +async function doctor(gatewayConfig: GatewayConfig): Promise> { + const store = createSqliteReceiptStore({ path: ':memory:' }); + await store.init(); + gateway = await createGateway({ + config: { ...gatewayConfig, server: { ...gatewayConfig.server, port: 0 } }, + store, + paymentProviders: await createConfiguredPaymentProviders(gatewayConfig.payments, NOOP_LOGGER), + protocolAdapters: [], + logger: NOOP_LOGGER, + }); + const { url } = await gateway.listen(); + const report = await runDoctor( + { gatewayUrl: url }, + { + loadConfig: async () => gatewayConfig, + fillEnvFromManifest: (env) => ({ env, filled: [], manifestFound: false }), + hasChainDeployScript: () => false, + }, + ); + return new Map(report.checks.map((check) => [check.name, check])); +} + +beforeAll(async () => { + await startUpstream(); + silentUrl = await releasedPort(); +}); +afterAll(() => new Promise((resolve) => upstream.close(() => resolve()))); +afterEach(async () => { + await gateway?.close(); + gateway = undefined; +}); + +describe('doctor through a running gateway: a target that gives no answer', () => { + // In the two-offer config, `rpc` is the first offer's RPC only + it.each([ + ['x402', 'Payments (offers)', 'rpc'], + ['x402', 'Payments (offers)', 'facilitator'], + ['x402-multi', 'Payments (offers)', 'rpc'], + ['x402-multi', 'Payments (offers)', 'facilitator'], + ['mpp', 'Payments (MPP offers)', 'rpc'], + ['mpp', 'Payments (MPP offers)', 'facilitator'], + ] as const)( + '%s: %s FAILs, marked unreachable, when the %s is silent', + async (rail, name, target) => { + const checks = await doctor(config(rail, { [target]: silentUrl })); + expect(checks.get(name)).toMatchObject({ status: 'FAIL', undetermined: 'unreachable' }); + // The gateway answered: it is not ready, and that is a verdict + expect(checks.get('Gateway')).toMatchObject({ status: 'WARN' }); + expect(checks.get('Gateway')).not.toHaveProperty('undetermined'); + }, + ); + + it('FAILs Backend, marked unreachable, when the backend host is silent', async () => { + const checks = await doctor(config('x402', { backend: silentUrl })); + expect(checks.get('Backend')).toEqual({ + name: 'Backend', + status: 'FAIL', + detail: '0/1 backend host(s) reachable', + undetermined: 'unreachable', + }); + expect(checks.get('Payments (offers)')).toMatchObject({ status: 'PASS' }); + }); + + it('marks nothing when every target answers', async () => { + for (const rail of ['x402', 'x402-multi', 'mpp'] as const) { + const checks = await doctor(config(rail)); + expect([...checks.values()].filter((check) => 'undetermined' in check)).toEqual([]); + await gateway?.close(); + gateway = undefined; + } + }); +}); + +describe('doctor through a running gateway: a target that answers wrongly', () => { + // Thunks: the upstream URL is known only once it listens. `https://` against + // the plain-HTTP upstream fails the TLS handshake. + const tls = () => upstreamUrl.replace('http:', 'https:'); + const WRONG: Record Targets> = { + 'the RPC returns a JSON-RPC error': () => ({ rpc: `${upstreamUrl}/rpc/error` }), + 'the facilitator answers 401': () => ({ facilitator: `${upstreamUrl}/denied` }), + 'the RPC fails the TLS handshake': () => ({ rpc: `${tls()}/rpc/84532` }), + 'the facilitator fails the TLS handshake': () => ({ facilitator: `${tls()}/facilitator` }), + }; + + it.each( + (['x402', 'mpp'] as const).flatMap((rail) => + Object.keys(WRONG).map( + (wrong) => + [rail, rail === 'mpp' ? 'Payments (MPP offers)' : 'Payments (offers)', wrong] as const, + ), + ), + )('%s: %s FAILs unmarked when %s', async (rail, name, wrong) => { + const checks = await doctor(config(rail, (WRONG[wrong] as () => Targets)())); + expect(checks.get(name)?.status).toBe('FAIL'); + expect(checks.get(name)).not.toHaveProperty('undetermined'); + }); + + it('FAILs Backend unmarked when its URL uses a port fetch refuses', async () => { + const checks = await doctor(config('x402', { backend: 'http://127.0.0.1:1' })); + expect(checks.get('Backend')).toEqual({ + name: 'Backend', + status: 'FAIL', + detail: '0/1 backend host(s) reachable', + }); + }); + + it("does not mark two offers when one is silent and the other's RPC answers wrongly", async () => { + const gatewayConfig = config('x402-multi', { rpc: silentUrl }); + const x402 = gatewayConfig.payments.x402 as NonNullable; + // The second offer's RPC reports Base Sepolia's chain id instead of Arbitrum Sepolia's + const options = (x402.options ?? []).map((option, index) => + index === 1 ? { ...option, rpcUrl: `${upstreamUrl}/rpc/84532` } : option, + ); + const checks = await doctor({ + ...gatewayConfig, + payments: { x402: { ...x402, options } }, + }); + expect(checks.get('Payments (offers)')?.status).toBe('FAIL'); + expect(checks.get('Payments (offers)')).not.toHaveProperty('undetermined'); + }); +}); + +describe('doctor without a gateway', () => { + const run = (gatewayUrl: string) => + runDoctor( + { gatewayUrl }, + { + loadConfig: async () => config('x402'), + fillEnvFromManifest: (env) => ({ env, filled: [], manifestFound: false }), + hasChainDeployScript: () => false, + }, + ); + + it('marks Gateway unreachable when the connection is refused', async () => { + const gateway = (await run(silentUrl)).checks.find((c) => c.name === 'Gateway'); + expect(gateway).toMatchObject({ status: 'FAIL', undetermined: 'unreachable' }); + expect(gateway?.detail).toMatch(/\(fetch failed: connect ECONNREFUSED 127\.0\.0\.1:\d+\)$/); + }); + + it('leaves Gateway unmarked, and says why, when fetch refuses the port', async () => { + const report = await run('http://127.0.0.1:1'); + expect(report.checks.find((c) => c.name === 'Gateway')).toEqual({ + name: 'Gateway', + status: 'FAIL', + detail: 'unreachable at http://127.0.0.1:1 (fetch failed: bad port)', + }); + expect(report.checks.find((c) => c.name === 'Protocols')).toMatchObject({ + status: 'FAIL', + undetermined: 'skipped', + }); + }); +}); diff --git a/tests/integration/goldens/2.7.2/doctor-multi.json b/tests/integration/goldens/2.7.2/doctor-multi.json index 0c1d718..24b6a3e 100644 --- a/tests/integration/goldens/2.7.2/doctor-multi.json +++ b/tests/integration/goldens/2.7.2/doctor-multi.json @@ -95,6 +95,11 @@ "status": "PASS", "detail": "MPP charge/evm/authorization enabled - TESTNET on Base Sepolia (eip155:84532), asset=USDC 0x036C…CF7e, recipient=0x1111…1111, facilitator=remote (auth=none), paymentFlow=upfront, spec draft-httpauth-payment-01@806fdb8, mppx 0.13.1" }, + { + "name": "Payments (MPP offers)", + "status": "PASS", + "detail": "1 offer(s) pass their health checks" + }, { "name": "Storage", "status": "PASS", @@ -112,8 +117,8 @@ } ], "score": { - "passed": 19, - "total": 19 + "passed": 20, + "total": 20 }, "exitCode": 0 } diff --git a/tests/integration/goldens/2.7.2/doctor-single.json b/tests/integration/goldens/2.7.2/doctor-single.json index d02f3e6..6228ecd 100644 --- a/tests/integration/goldens/2.7.2/doctor-single.json +++ b/tests/integration/goldens/2.7.2/doctor-single.json @@ -85,11 +85,21 @@ "status": "PASS", "detail": "x402 v2 (scheme=exact) enabled - TESTNET on Base Sepolia (eip155:84532), destination=0x1111…1111, facilitator=remote (auth=none), paymentFlow=authorization" }, + { + "name": "Payments (offers)", + "status": "PASS", + "detail": "1 offer(s) pass their health checks" + }, { "name": "Payments (MPP)", "status": "PASS", "detail": "MPP charge/evm/authorization enabled - TESTNET on Base Sepolia (eip155:84532), asset=USDC 0x036C…CF7e, recipient=0x1111…1111, facilitator=remote (auth=none), paymentFlow=upfront, spec draft-httpauth-payment-01@806fdb8, mppx 0.13.1" }, + { + "name": "Payments (MPP offers)", + "status": "PASS", + "detail": "1 offer(s) pass their health checks" + }, { "name": "Storage", "status": "PASS", @@ -107,8 +117,8 @@ } ], "score": { - "passed": 18, - "total": 18 + "passed": 20, + "total": 20 }, "exitCode": 0 } diff --git a/tests/integration/goldens/2.7.2/well-known-multi.json b/tests/integration/goldens/2.7.2/well-known-multi.json index 7462b21..7396c9a 100644 --- a/tests/integration/goldens/2.7.2/well-known-multi.json +++ b/tests/integration/goldens/2.7.2/well-known-multi.json @@ -320,7 +320,8 @@ "mode": "remote" }, "mode": "testnet", - "paymentFlow": "upfront" + "paymentFlow": "upfront", + "status": "pass" } } } diff --git a/tests/integration/goldens/2.7.2/well-known-single.json b/tests/integration/goldens/2.7.2/well-known-single.json index 277a502..2d3b4cb 100644 --- a/tests/integration/goldens/2.7.2/well-known-single.json +++ b/tests/integration/goldens/2.7.2/well-known-single.json @@ -283,7 +283,8 @@ "mode": "remote" }, "mode": "testnet", - "paymentFlow": "authorization" + "paymentFlow": "authorization", + "status": "pass" }, "mpp": { "enabled": true, @@ -297,7 +298,8 @@ "mode": "remote" }, "mode": "testnet", - "paymentFlow": "upfront" + "paymentFlow": "upfront", + "status": "pass" } } } diff --git a/tests/integration/mpp-config.test.ts b/tests/integration/mpp-config.test.ts index f1be6c3..a79b5ce 100644 --- a/tests/integration/mpp-config.test.ts +++ b/tests/integration/mpp-config.test.ts @@ -1,13 +1,13 @@ // An MPP-only config through `createConfiguredPaymentProviders`, from parsing to a running gateway import { Challenge } from 'mppx'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeAll, describe, expect, it } from 'vitest'; import { parseConfig } from '../../src/config/schema'; import type { BackendExecutor } from '../../src/core'; import { createGateway, type GatewayInstance } from '../../src/gateway'; import { createConfiguredPaymentProviders } from '../../src/gateway/payment-providers'; import { validRawConfig } from '../unit/config/fixtures'; import { NOOP_TEST_LOGGER } from '../unit/core/execution/helpers'; -import { createFakeStore } from '../unit/gateway/helpers'; +import { createFakeStore, releasedPort } from '../unit/gateway/helpers'; process.env['NODE_ENV'] = 'test'; @@ -15,9 +15,14 @@ const SECRET = 'mpp-challenge-secret-'.padEnd(32, 'x'); const RPC_KEY = 'RPC-KEY-IN-PATH'; const FACILITATOR_TENANT = 'tenant-in-path'; +// Use a released loopback port to simulate an RPC connection refusal +let rpcUrl = ''; +beforeAll(async () => { + rpcUrl = `${await releasedPort()}/v2/${RPC_KEY}`; +}); + const MPP = { enabled: true, - rpcUrl: `https://sepolia.example/v2/${RPC_KEY}`, asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', assetName: 'USDC', assetVersion: '2', @@ -34,7 +39,8 @@ function mppOnlyConfig(withX402 = false) { payTo: '0x2222222222222222222222222222222222222222', facilitator: { mode: 'remote', url: 'https://x402-facilitator.example' }, }; - raw['payments'] = withX402 ? { x402, mpp: MPP } : { mpp: MPP }; + const mpp = { ...MPP, rpcUrl }; + raw['payments'] = withX402 ? { x402, mpp } : { mpp }; (raw['resources'] as { market_report: { payments: string[] } }).market_report.payments = ['mpp']; return parseConfig(raw, {}); } @@ -86,7 +92,8 @@ describe('payments.mpp wiring', () => { method: 'GET', url: '/.well-known/agent-commerce', }); - // No network configured, so MPP takes its default, Base Sepolia + // With no configured network, MPP defaults to Base Sepolia. The probe marks + // the refused RPC connection as unreachable. expect(wellKnown.json().payments.mpp).toEqual({ enabled: true, network: 'eip155:84532', @@ -98,6 +105,8 @@ describe('payments.mpp wiring', () => { facilitator: { mode: 'remote' }, mode: 'testnet', paymentFlow: 'upfront', + status: 'fail', + undetermined: 'unreachable', }); for (const secret of [SECRET, RPC_KEY, FACILITATOR_TENANT]) { expect(wellKnown.body).not.toContain(secret); diff --git a/tests/unit/cli/doctor-certainty.test.ts b/tests/unit/cli/doctor-certainty.test.ts new file mode 100644 index 0000000..28bccbf --- /dev/null +++ b/tests/unit/cli/doctor-certainty.test.ts @@ -0,0 +1,496 @@ +// Which `doctor` results carry `undetermined`, the printed mark, and the Secrets check +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { stripVTControlCharacters } from 'node:util'; +import { describe, expect, it } from 'vitest'; +import { printDoctorReport, runDoctor } from '../../../src/cli/commands/doctor'; +import type { DoctorDeps } from '../../../src/cli/commands/doctor/types'; +import { + createCapturingIo, + createFakeFetch, + fetchFailed, + jsonResponse, + makeFakeReceiptStore, + makeGatewayConfig, +} from './fixtures'; + +const GATEWAY = 'http://127.0.0.1:8080'; +const BACKEND = 'http://localhost:3000/api/weather/demo-check'; + +const X402 = { + enabled: true, + network: 'eip155:31337', + rpcUrl: 'http://127.0.0.1:8545', + asset: '0x5FbDB2315678afecb367f032d93F642f64180aa3', + assetName: 'MockUSDC', + assetVersion: '2', + assetDecimals: 6, + payTo: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + maxTimeoutSeconds: 60, + facilitator: { mode: 'local' as const, signerPrivateKey: '0xdeadbeef' }, +}; +const SECOND_ASSET = '0x2222222222222222222222222222222222222222'; + +const MPP = { + enabled: true, + network: 'eip155:84532' as const, + rpcUrl: 'https://sepolia.example/v2/RPC-KEY', + asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', + assetName: 'USDC', + assetVersion: '2', + recipient: '0x1111111111111111111111111111111111111111', + realm: 'api.example.com', + challengeSecret: 'CHALLENGE-SECRET-'.padEnd(32, 'x'), + facilitator: { + mode: 'remote' as const, + url: 'https://facilitator.example', + auth: { type: 'bearer' as const, token: 'FACILITATOR-TOKEN' }, + }, +}; + +const BOTH_RAILS = makeGatewayConfig({ payments: { x402: X402, mpp: MPP } }); + +type Handlers = Record Response | Promise>; + +// A request that fails with an answer: the name does not resolve +const doesNotResolve = (): Response => { + throw fetchFailed('ENOTFOUND', 'getaddrinfo ENOTFOUND gateway.test'); +}; + +// Healthy responses by default. An undefined handler removes a URL, causing the +// fake fetch to reject that request. +function gatewayFetch(overrides: Record Response) | undefined> = {}) { + const handlers: Record Response) | undefined> = { + [`${GATEWAY}/health`]: () => jsonResponse({ status: 'ok' }), + [`${GATEWAY}/ready`]: () => jsonResponse({ status: 'ready' }), + [`${GATEWAY}/.well-known/agent-commerce`]: () => jsonResponse({ merchant: { id: 'm' } }), + [BACKEND]: () => jsonResponse({}), + ...overrides, + }; + return createFakeFetch( + Object.fromEntries(Object.entries(handlers).filter(([, h]) => h !== undefined)) as Handlers, + ); +} + +async function doctor(deps: DoctorDeps) { + const report = await runDoctor( + { gatewayUrl: GATEWAY }, + { + createStore: () => makeFakeReceiptStore(), + fillEnvFromManifest: (env) => ({ env, filled: [], manifestFound: false }), + hasChainDeployScript: () => false, + ...deps, + }, + ); + return { report, check: (name: string) => report.checks.find((c) => c.name === name) }; +} + +// Compare a check's status and optional undetermined marker +const verdict = (check: { status: string; undetermined?: string } | undefined) => + check === undefined + ? undefined + : { status: check.status, ...(check.undetermined ? { mark: check.undetermined } : {}) }; + +describe('doctor: the gateway and what depends on its document', () => { + const DEPENDENT = [ + 'Gateway', + 'Protocols', + 'Payments', + 'Payments (MPP)', + 'Protocol versions', + ] as const; + + // `unreachable` when nothing answered, `skipped` when the document was never + // fetched, nothing when it answered without usable content + it.each([ + [ + '/health gives no answer', + { [`${GATEWAY}/health`]: undefined }, + ['FAIL', 'unreachable'], + 'unreachable', + ], + ['/health does not resolve', { [`${GATEWAY}/health`]: doesNotResolve }, ['FAIL'], 'skipped'], + [ + '/health answers 500', + { [`${GATEWAY}/health`]: () => jsonResponse({}, 500) }, + ['FAIL'], + 'skipped', + ], + [ + '/ready rejects the Host', + { [`${GATEWAY}/ready`]: () => jsonResponse({}, 403) }, + ['FAIL'], + 'skipped', + ], + [ + 'the document gives no answer', + { [`${GATEWAY}/.well-known/agent-commerce`]: undefined }, + ['PASS'], + 'unreachable', + ], + [ + 'the document does not resolve', + { [`${GATEWAY}/.well-known/agent-commerce`]: doesNotResolve }, + ['PASS'], + undefined, + ], + [ + 'the document answers 500', + { [`${GATEWAY}/.well-known/agent-commerce`]: () => jsonResponse({}, 500) }, + ['PASS'], + undefined, + ], + ] as const)('when %s', async (_label, overrides, [gatewayStatus, gatewayMark], cause) => { + const { check } = await doctor({ + fetchImpl: gatewayFetch(overrides), + loadConfig: async () => BOTH_RAILS, + }); + const mark = cause !== undefined ? { mark: cause } : {}; + expect(Object.fromEntries(DEPENDENT.map((name) => [name, verdict(check(name))]))).toEqual({ + Gateway: { status: gatewayStatus, ...(gatewayMark ? { mark: gatewayMark } : {}) }, + Protocols: { status: 'FAIL', ...mark }, + Payments: { status: 'INFO', ...mark }, + 'Payments (MPP)': { status: 'INFO', ...mark }, + 'Protocol versions': { status: 'INFO', ...mark }, + }); + }); + + it('says a gateway that answered non-2xx is unhealthy, not unreachable', async () => { + const { check } = await doctor({ + fetchImpl: gatewayFetch({ [`${GATEWAY}/health`]: () => jsonResponse({}, 500) }), + loadConfig: async () => BOTH_RAILS, + }); + expect(check('Gateway')?.detail).toBe(`unhealthy at ${GATEWAY} (HTTP 500)`); + expect(check('Protocol versions')?.detail).toMatch(/^gateway versions unavailable; local pins/); + }); + + it('leaves Payments unmarked when the document answers without a payments block', async () => { + const { check } = await doctor({ + fetchImpl: gatewayFetch(), + loadConfig: async () => BOTH_RAILS, + }); + expect(verdict(check('Payments'))).toEqual({ status: 'INFO' }); + expect(verdict(check('Payments (MPP)'))).toEqual({ status: 'INFO' }); + }); + + it.each([ + ['gives no answer', undefined, { status: 'WARN', mark: 'unreachable' }], + ['does not resolve', doesNotResolve, { status: 'WARN' }], + ['answers 503', () => jsonResponse({}, 503), { status: 'WARN' }], + ] as const)('WARNs a gateway whose /ready %s', async (_label, ready, expected) => { + const { check } = await doctor({ + fetchImpl: gatewayFetch({ [`${GATEWAY}/ready`]: ready }), + loadConfig: async () => makeGatewayConfig(), + }); + expect(verdict(check('Gateway'))).toEqual(expected); + }); +}); + +describe('doctor: backends', () => { + // The config has a second resource on another host + const twoHosts = () => { + const config = makeGatewayConfig(); + const [first] = config.resources; + if (first === undefined) throw new Error('the fixture config has a resource'); + const second = { + ...first, + id: 'other', + handler: { ...first.handler, url: 'http://other.test/api' }, + }; + return { ...config, resources: [first, second] }; + }; + + it.each([ + [ + 'one of two hosts gives no answer', + { 'http://other.test/api': undefined }, + { status: 'WARN', mark: 'unreachable' }, + ], + [ + 'both give no answer', + { [BACKEND]: undefined, 'http://other.test/api': undefined }, + { status: 'FAIL', mark: 'unreachable' }, + ], + [ + 'one of two hosts does not resolve', + { 'http://other.test/api': doesNotResolve }, + { status: 'WARN' }, + ], + [ + 'one host gives no answer and the other does not resolve', + { [BACKEND]: undefined, 'http://other.test/api': doesNotResolve }, + { status: 'FAIL' }, + ], + [ + 'a host answers 500', + { 'http://other.test/api': () => jsonResponse({}, 500) }, + { status: 'PASS' }, + ], + ] as const)('reports Backend, and its mark, when %s', async (_label, overrides, expected) => { + const { check } = await doctor({ + // Object.assign: every override names the other host, which a spread would flag + fetchImpl: gatewayFetch( + Object.assign({ 'http://other.test/api': () => jsonResponse({}) }, overrides), + ), + loadConfig: async () => twoHosts(), + }); + expect(verdict(check('Backend'))).toEqual(expected); + }); +}); + +describe('doctor: invalid config', () => { + it('marks every check it skipped, and keeps each status', async () => { + const { report } = await doctor({ + fetchImpl: gatewayFetch(), + loadConfig: async () => { + throw new Error('bad config'); + }, + }); + const marked = report.checks + .filter((c) => c.undetermined !== undefined) + .map((c) => [c.name, c.status, c.detail, c.undetermined]); + expect(marked).toEqual([ + ['Backend', 'WARN', 'skipped: config invalid', 'skipped'], + ['Protocols', 'WARN', 'skipped: config invalid', 'skipped'], + ['A2A', 'WARN', 'skipped: config invalid', 'skipped'], + ['ACP', 'WARN', 'skipped: config invalid', 'skipped'], + ['AP2', 'WARN', 'skipped: config invalid', 'skipped'], + ['Payments', 'INFO', 'skipped: config invalid', 'skipped'], + ['Payments (MPP)', 'INFO', 'skipped: config invalid', 'skipped'], + ['Storage', 'WARN', 'skipped: config invalid', 'skipped'], + ]); + // The failure itself is a verdict + expect(report.checks.find((c) => c.name === 'Config')).not.toHaveProperty('undetermined'); + }); +}); + +describe('doctor: offer health from the document', () => { + const offer = (asset: string, status: string, unreachable: boolean) => ({ + network: X402.network, + asset, + payTo: X402.payTo, + status, + ...(unreachable ? { undetermined: 'unreachable' } : {}), + }); + const x402Document = (offers: readonly ReturnType[]) => ({ + merchant: { id: 'm' }, + payments: { + x402: { + enabled: true, + ...(offers[0] as object), + options: offers, + paymentFlow: 'authorization', + }, + }, + }); + const twoOffers = makeGatewayConfig({ + payments: { x402: { ...X402, options: [X402, { ...X402, asset: SECOND_ASSET }] } }, + }); + + it.each([ + [ + 'every failing offer got no answer', + [offer(X402.asset, 'fail', true), offer(SECOND_ASSET, 'pass', false)], + { status: 'FAIL', mark: 'unreachable' }, + ], + [ + 'one failing offer answered', + [offer(X402.asset, 'fail', true), offer(SECOND_ASSET, 'fail', false)], + { status: 'FAIL' }, + ], + [ + 'a degraded offer answered', + [offer(X402.asset, 'fail', true), offer(SECOND_ASSET, 'warn', false)], + { status: 'FAIL' }, + ], + [ + 'only a degraded offer got no answer', + [offer(X402.asset, 'pass', false), offer(SECOND_ASSET, 'warn', true)], + { status: 'WARN', mark: 'unreachable' }, + ], + ] as const)('Payments (offers) when %s', async (_label, offers, expected) => { + const { check } = await doctor({ + fetchImpl: gatewayFetch({ + [`${GATEWAY}/.well-known/agent-commerce`]: () => jsonResponse(x402Document(offers)), + }), + loadConfig: async () => twoOffers, + }); + expect(verdict(check('Payments (offers)'))).toEqual(expected); + }); + + it.each([ + ['fail', true, { status: 'FAIL', mark: 'unreachable' }], + ['fail', false, { status: 'FAIL' }], + ['pass', false, { status: 'PASS' }], + ] as const)( + 'Payments (MPP offers) for a %s block (no answer: %s)', + async (status, unreachable, expected) => { + const mppDocument = { + merchant: { id: 'm' }, + payments: { + mpp: { + enabled: true, + network: MPP.network, + asset: MPP.asset, + recipient: MPP.recipient, + paymentFlow: 'upfront', + status, + ...(unreachable ? { undetermined: 'unreachable' } : {}), + }, + }, + }; + const { check } = await doctor({ + fetchImpl: gatewayFetch({ + [`${GATEWAY}/.well-known/agent-commerce`]: () => jsonResponse(mppDocument), + }), + loadConfig: async () => makeGatewayConfig({ payments: { mpp: MPP } }), + }); + expect(verdict(check('Payments (MPP)'))).toEqual({ status: 'PASS' }); + expect(verdict(check('Payments (MPP offers)'))).toEqual(expected); + }, + ); +}); + +describe('doctor: a healthy run', () => { + it('marks no result', async () => { + const { report } = await doctor({ + fetchImpl: gatewayFetch(), + loadConfig: async () => makeGatewayConfig(), + }); + expect(report.exitCode).toBe(0); + expect(report.checks.filter((c) => 'undetermined' in c)).toEqual([]); + }); +}); + +describe('printDoctorReport: the mark', () => { + it('appends the mark to a text row, and keeps the field in JSON', () => { + const report = { + checks: [ + { + name: 'Gateway', + status: 'FAIL' as const, + detail: 'down', + undetermined: 'unreachable' as const, + }, + { name: 'Storage', status: 'PASS' as const, detail: 'ok' }, + ], + score: { passed: 1, total: 2 }, + exitCode: 1, + }; + const text = createCapturingIo(); + printDoctorReport(report, text, false); + expect(text.out.slice(0, 2).map((line) => stripVTControlCharacters(line))).toEqual([ + `FAIL ${'Gateway'.padEnd(20)} down [not determined: unreachable]`, + `PASS ${'Storage'.padEnd(20)} ok`, + ]); + const json = createCapturingIo(); + printDoctorReport(report, json, true); + expect(JSON.parse(json.out[0] ?? '{}').checks).toEqual(report.checks); + }); +}); + +describe('doctor: Secrets', () => { + const RAW = { + server: { adminToken: '${ADMIN_TOKEN}' }, + payments: { + x402: { + payTo: '${MERCHANT_WALLET}', + rpcUrl: '${RPC_URL:-https://default-rpc.example/DEFAULT-KEY}', + facilitator: { token: '${FACILITATOR_TOKEN}' }, + }, + }, + }; + // The environment arrives the way the Config check reads it, through the + // manifest fill, which leaves process.env untouched + const secrets = (env: Record, deps: Partial = {}) => + doctor({ + fetchImpl: gatewayFetch(), + loadConfig: async () => makeGatewayConfig(), + readConfigFile: async () => RAW, + fillEnvFromManifest: () => ({ env, filled: [], manifestFound: false }), + ...deps, + }); + + it('FAILs naming every missing variable, and prints no value or default', async () => { + const { report, check } = await secrets({ ADMIN_TOKEN: 'ADMIN-SECRET-VALUE' }); + expect(check('Secrets')).toEqual({ + name: 'Secrets', + status: 'FAIL', + detail: + '2 missing (FACILITATOR_TOKEN, MERCHANT_WALLET); 1 set (ADMIN_TOKEN); 1 defaulted (RPC_URL)', + }); + expect(report.exitCode).toBe(1); + const text = createCapturingIo(); + printDoctorReport(report, text, false); + const json = createCapturingIo(); + printDoctorReport(report, json, true); + for (const output of [text.out.join('\n'), json.out.join('\n')]) { + expect(output).not.toContain('ADMIN-SECRET-VALUE'); + expect(output).not.toContain('DEFAULT-KEY'); + } + }); + + it("passes when every variable resolves in the Config check's environment, a default included", async () => { + const { check } = await secrets({ + ADMIN_TOKEN: 'a', + MERCHANT_WALLET: 'b', + FACILITATOR_TOKEN: '', + }); + expect(check('Secrets')).toMatchObject({ + status: 'PASS', + detail: '3 set (ADMIN_TOKEN, FACILITATOR_TOKEN, MERCHANT_WALLET); 1 defaulted (RPC_URL)', + }); + }); + + it('is INFO for a config that reads no variable', async () => { + const { check } = await secrets( + {}, + { readConfigFile: async () => ({ server: { port: 8080 } }) }, + ); + expect(check('Secrets')).toMatchObject({ status: 'INFO' }); + }); + + it('WARNs, marked skipped, when the file cannot be read', async () => { + const { check } = await secrets( + {}, + { + readConfigFile: async () => { + throw new Error('ENOENT'); + }, + }, + ); + expect(check('Secrets')).toEqual({ + name: 'Secrets', + status: 'WARN', + detail: 'skipped: config file unreadable', + undetermined: 'skipped', + }); + }); + + it('is left out when a loader is injected without a reader', async () => { + const { check } = await doctor({ + fetchImpl: gatewayFetch(), + loadConfig: async () => makeGatewayConfig(), + }); + expect(check('Secrets')).toBeUndefined(); + }); + + it('reads the --config file by default', async () => { + const file = join(mkdtempSync(join(tmpdir(), 'doctor-secrets-')), 'config.yaml'); + writeFileSync(file, 'server:\n adminToken: ${DOCTOR_SECRETS_ONLY_VAR}\n'); + const report = await runDoctor( + { gatewayUrl: GATEWAY, configPath: file }, + { + fetchImpl: gatewayFetch(), + createStore: () => makeFakeReceiptStore(), + fillEnvFromManifest: (env) => ({ env, filled: [], manifestFound: false }), + hasChainDeployScript: () => false, + }, + ); + expect(report.checks.find((c) => c.name === 'Secrets')).toMatchObject({ + status: 'FAIL', + detail: '1 missing (DOCTOR_SECRETS_ONLY_VAR)', + }); + }); +}); diff --git a/tests/unit/cli/doctor.test.ts b/tests/unit/cli/doctor.test.ts index e815ba9..d2b7b1c 100644 --- a/tests/unit/cli/doctor.test.ts +++ b/tests/unit/cli/doctor.test.ts @@ -1095,17 +1095,20 @@ describe('runDoctor: ERC-8409 quotes', () => { expect(await quoteCheck(undefined)).toBeUndefined(); }); + // Only a gateway that gave no answer marks the result; a document that + // answered without a readable issuer is a finding it.each([ - ['the gateway is unreachable', undefined], - ['the gateway reports x402 disabled', wellKnownBody({ enabled: false })], - ['the quote block is not an object', withQuote('erc-8409')], - ['the issuer is missing', withQuote({ ...QUOTE, issuer: undefined })], - ])("reports INFO with the local key's issuer when %s", async (_label, body) => { + ['the gateway is unreachable', undefined, { undetermined: 'unreachable' }], + ['the gateway reports x402 disabled', wellKnownBody({ enabled: false }), {}], + ['the quote block is not an object', withQuote('erc-8409'), {}], + ['the issuer is missing', withQuote({ ...QUOTE, issuer: undefined }), {}], + ])("reports INFO with the local key's issuer when %s", async (_label, body, mark) => { expect(await quoteCheck(QUOTE_KEY, body)).toEqual({ name: 'Payments (quotes)', status: 'INFO', detail: "ERC-8409 quotes enabled (experimental), issuer=0x5CbD…07FB from the local key; the gateway's issuer could not be read", + ...mark, }); }); }); diff --git a/tests/unit/cli/fixtures.ts b/tests/unit/cli/fixtures.ts index d681bbf..4f1e82c 100644 --- a/tests/unit/cli/fixtures.ts +++ b/tests/unit/cli/fixtures.ts @@ -43,7 +43,12 @@ export function makeGatewayConfig(overrides: Partial = {}): Gatew }; } -/** A fake `fetch` from an exact-URL -> Response map. Unmatched URLs reject, as if unreachable */ +/** An undici fetch error with the Node error code on its cause */ +export function fetchFailed(code: string | undefined, message: string): TypeError { + return new TypeError('fetch failed', { cause: Object.assign(new Error(message), { code }) }); +} + +/** A fake `fetch` with exact URL handlers; unmatched URLs reject as unreachable */ export function createFakeFetch( handlers: Record Response | Promise>, ): FetchLike { @@ -51,9 +56,7 @@ export function createFakeFetch( const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url; const handler = handlers[url]; - if (handler === undefined) { - throw new TypeError(`fake fetch: connection refused for ${url}`); - } + if (handler === undefined) throw fetchFailed('ECONNREFUSED', `connect ECONNREFUSED ${url}`); return handler(); }; return fake as unknown as FetchLike; diff --git a/tests/unit/cli/lib.test.ts b/tests/unit/cli/lib.test.ts index ebc0ef7..204da91 100644 --- a/tests/unit/cli/lib.test.ts +++ b/tests/unit/cli/lib.test.ts @@ -3,7 +3,7 @@ import { type FetchLike, fetchJson } from '../../../src/cli/lib/http'; import { processIo } from '../../../src/cli/lib/io'; import { maskMiddle } from '../../../src/cli/lib/mask'; import { readVersionReport } from '../../../src/cli/lib/versions'; -import { createFakeFetch, jsonResponse } from './fixtures'; +import { createFakeFetch, fetchFailed, jsonResponse } from './fixtures'; describe('maskMiddle', () => { it('masks the middle of a long value, keeping a prefix and suffix', () => { @@ -38,12 +38,25 @@ describe('fetchJson', () => { expect(result.status).toBe(404); }); - it('returns status 0 and an error message when the fetch itself throws (unreachable)', async () => { - const fetchImpl = createFakeFetch({}); - const result = await fetchJson(fetchImpl, 'http://x/unreachable'); - expect(result.ok).toBe(false); - expect(result.status).toBe(0); - expect(result.error).toBeTruthy(); + it('returns status 0, the root cause and noAnswer when the connection is refused', async () => { + const result = await fetchJson(createFakeFetch({}), 'http://x/unreachable'); + expect(result).toEqual({ + ok: false, + status: 0, + error: 'fetch failed: connect ECONNREFUSED http://x/unreachable', + noAnswer: true, + }); + }); + + it('returns status 0 without noAnswer when the hostname does not resolve', async () => { + const fetchImpl = (async () => { + throw fetchFailed('ENOTFOUND', 'getaddrinfo ENOTFOUND x'); + }) as unknown as FetchLike; + expect(await fetchJson(fetchImpl, 'http://x/')).toEqual({ + ok: false, + status: 0, + error: 'fetch failed: getaddrinfo ENOTFOUND x', + }); }); it('falls back to a generic error message when a non-Error value is thrown', async () => { @@ -61,7 +74,7 @@ describe('fetchJson', () => { init?.signal?.addEventListener('abort', () => reject(init.signal?.reason)); })) as FetchLike; const result = await fetchJson(fetchImpl, 'http://x/slow', 10); - expect(result).toMatchObject({ ok: false, status: 0 }); + expect(result).toMatchObject({ ok: false, status: 0, noAnswer: true }); expect(result.error).toMatch(/timeout/i); }); diff --git a/tests/unit/config/env.test.ts b/tests/unit/config/env.test.ts index 6c97721..df07a31 100644 --- a/tests/unit/config/env.test.ts +++ b/tests/unit/config/env.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { substituteEnv } from '../../../src/config/env'; +import { listEnvPlaceholders, substituteEnv } from '../../../src/config/env'; import { isCommerceError } from '../../../src/core'; describe('substituteEnv', () => { @@ -126,3 +126,53 @@ describe('nested placeholders and the unresolved-placeholder promise', () => { expect(substituteEnv({ x: 'cost is ${5' }, {})).toEqual({ x: 'cost is ${5' }); }); }); + +describe('listEnvPlaceholders', () => { + it('names each placeholder by state, sorted, from nested objects and arrays', () => { + const raw = { + server: { adminToken: '${ADMIN_TOKEN}', port: '${PORT:-8080}' }, + payments: [{ url: 'https://rpc.example/${RPC_KEY}?x=${ZONE:-eu}', other: 7 }], + merchant: { name: '${MISSING_NAME}' }, + }; + expect( + listEnvPlaceholders(raw, { ADMIN_TOKEN: 'secret-value', RPC_KEY: 'k', ZONE: 'us' }), + ).toEqual({ + missing: ['MISSING_NAME'], + defaulted: ['PORT'], + set: ['ADMIN_TOKEN', 'RPC_KEY', 'ZONE'], + }); + }); + + // An empty value is set for ${VAR} and defaulted for ${VAR:-d} + it('counts an empty value as set for ${VAR} and as defaulted for ${VAR:-default}', () => { + expect(listEnvPlaceholders({ a: '${A}', b: '${B:-x}' }, { A: '', B: '' })).toEqual({ + missing: [], + defaulted: ['B'], + set: ['A'], + }); + }); + + // Put the worse state first to catch code that keeps the last use instead + it('lists a name used several ways once, under its worst state', () => { + const raw = { a: '${TOKEN}', b: '${TOKEN:-dev}', c: '${PORT:-1}', d: '${PORT}' }; + expect(listEnvPlaceholders(raw, { PORT: '' })).toEqual({ + missing: ['TOKEN'], + defaulted: ['PORT'], + set: [], + }); + }); + + it('returns names only: no value and no default', () => { + const listed = listEnvPlaceholders( + { a: '${SET_VAR}', b: '${DEFAULTED:-default-secret}' }, + { SET_VAR: 'value-secret' }, + ); + expect(JSON.stringify(listed)).not.toMatch(/secret/); + }); + + it('does not throw on templates config load refuses, and ignores keys', () => { + const raw = { '${KEY_NAME}': 'x', a: '${A:-${B}}', b: '${C-x}', c: '$PLAIN' }; + expect(() => substituteEnv(raw, {})).toThrow(); + expect(listEnvPlaceholders(raw, {})).toEqual({ missing: [], defaulted: ['A'], set: [] }); + }); +}); diff --git a/tests/unit/config/load.test.ts b/tests/unit/config/load.test.ts index f77e5ce..eb2c4a7 100644 --- a/tests/unit/config/load.test.ts +++ b/tests/unit/config/load.test.ts @@ -2,7 +2,7 @@ import { promises as fs } from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; -import { loadConfig } from '../../../src/config/load'; +import { loadConfig, readConfigFile } from '../../../src/config/load'; import { isCommerceError } from '../../../src/core'; const VALID_YAML = ` @@ -232,3 +232,24 @@ describe('loadConfig', () => { } }); }); + +describe('readConfigFile', () => { + it('returns the parsed file before substitution and validation', async () => { + const dir = await makeTmpDir(); + const file = path.join(dir, 'raw.yaml'); + await fs.writeFile(file, 'server:\n adminToken: ${ADMIN_TOKEN}\nunknownKey: 1\n', 'utf8'); + expect(await readConfigFile({ path: file, env: {} })).toEqual({ + server: { adminToken: '${ADMIN_TOKEN}' }, + unknownKey: 1, + }); + }); + + it('refuses a missing file as loadConfig does', async () => { + const dir = await makeTmpDir(); + const file = path.join(dir, 'absent.yaml'); + await expect(readConfigFile({ path: file })).rejects.toMatchObject({ + code: 'CONFIG_INVALID', + message: `Could not read configuration file "${file}"`, + }); + }); +}); diff --git a/tests/unit/core/no-answer.test.ts b/tests/unit/core/no-answer.test.ts new file mode 100644 index 0000000..eb5830e --- /dev/null +++ b/tests/unit/core/no-answer.test.ts @@ -0,0 +1,66 @@ +// Request errors classified as unreachable +import { describe, expect, it } from 'vitest'; +import { gotNoAnswer } from '../../../src/core/no-answer'; + +// undici's fetch error, with the Node error code on its cause +const fetchFailed = (code: string | undefined, message = 'x') => + new TypeError('fetch failed', { cause: Object.assign(new Error(message), { code }) }); + +describe('gotNoAnswer', () => { + it.each([ + 'ECONNREFUSED', + 'ECONNRESET', + 'ETIMEDOUT', + 'EHOSTUNREACH', + 'ENETUNREACH', + 'EAI_AGAIN', + 'UND_ERR_CONNECT_TIMEOUT', + 'UND_ERR_HEADERS_TIMEOUT', + 'UND_ERR_BODY_TIMEOUT', + ])('is true for a fetch that failed with %s', (code) => { + expect(gotNoAnswer(fetchFailed(code))).toBe(true); + }); + + it.each([ + ['a hostname that does not resolve', fetchFailed('ENOTFOUND')], + ['a certificate for another host', fetchFailed('ERR_TLS_CERT_ALTNAME_INVALID')], + ['an expired certificate', fetchFailed('CERT_HAS_EXPIRED')], + ['a server that does not speak TLS', fetchFailed('ERR_SSL_PACKET_LENGTH_TOO_LONG')], + ['a port fetch refuses to use', fetchFailed(undefined, 'bad port')], + ['a fetch error without a cause', new TypeError('fetch failed')], + ['a JSON-RPC error code', Object.assign(new Error('no method'), { code: -32601 })], + ['an unrecognized error', new Error('boom')], + ['a thrown string', 'ECONNREFUSED'], + ['nothing', undefined], + ])('is false for %s', (_label, err) => { + expect(gotNoAnswer(err)).toBe(false); + }); + + it('is true for a timeout named TimeoutError, at any depth', () => { + const timeout = new DOMException('The operation was aborted due to timeout', 'TimeoutError'); + expect(gotNoAnswer(timeout)).toBe(true); + expect( + gotNoAnswer(new Error('wrapped', { cause: new Error('twice', { cause: timeout }) })), + ).toBe(true); + }); + + it('reads the code on an AggregateError from a connection to several addresses', () => { + const both = Object.assign(new AggregateError([new Error('a'), new Error('b')]), { + code: 'ECONNREFUSED', + }); + expect(gotNoAnswer(new TypeError('fetch failed', { cause: both }))).toBe(true); + }); + + it("treats a caller's timeout names as no answer, and only for that caller", () => { + const sdkTimeout = Object.assign(new Error('timed out'), { name: 'FacilitatorTimeoutError' }); + expect(gotNoAnswer(sdkTimeout, ['FacilitatorTimeoutError'])).toBe(true); + expect(gotNoAnswer(sdkTimeout)).toBe(false); + }); + + it('returns false for a cause cycle instead of looping', () => { + const a = new Error('a'); + const b = new Error('b', { cause: a }); + Object.assign(a, { cause: b }); + expect(gotNoAnswer(a)).toBe(false); + }); +}); diff --git a/tests/unit/gateway/helpers.ts b/tests/unit/gateway/helpers.ts index 4b9061f..3e3d823 100644 --- a/tests/unit/gateway/helpers.ts +++ b/tests/unit/gateway/helpers.ts @@ -1,6 +1,7 @@ // Shared fakes for gateway tests, implementing the core interfaces directly // rather than importing another area's implementation -import type { IncomingMessage, ServerResponse } from 'node:http'; +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; import type { GatewayConfig } from '../../../src/config'; import type { AdapterDescriptor, @@ -272,3 +273,14 @@ export function makeGatewayConfig(overrides: Partial = {}): Gatew ...overrides, }; } + +/** A loopback URL with a released port, used to simulate a refused connection */ +export function releasedPort(): Promise { + const server = createServer(); + return new Promise((resolve) => + server.listen(0, '127.0.0.1', () => { + const { port } = server.address() as AddressInfo; + server.close(() => resolve(`http://127.0.0.1:${port}`)); + }), + ); +} diff --git a/tests/unit/gateway/server.test.ts b/tests/unit/gateway/server.test.ts index 4b82be3..d5411ce 100644 --- a/tests/unit/gateway/server.test.ts +++ b/tests/unit/gateway/server.test.ts @@ -7,6 +7,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; process.env['NODE_ENV'] = 'test'; import type { + AdapterHealthComponent, BackendExecutor, CanonicalRequest, Clock, @@ -474,6 +475,87 @@ describe('createGateway HTTP surface', () => { expect(res.payload).not.toContain('SECRET-DETAIL'); }); + // A single offer's probe appears on the rail block; with `options`, each + // listed offer carries its own result + it('publishes the probe result of a single-offer x402 block and the MPP block, with the no-answer mark', async () => { + const base = makeGatewayConfig(); + const x402 = base.payments.x402 as NonNullable; + const mpp = { + enabled: true, + network: 'eip155:84532' as const, + rpcUrl: 'https://sepolia.example/v2/RPC-KEY', + asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', + assetName: 'USDC', + assetVersion: '2', + recipient: '0x1111111111111111111111111111111111111111', + realm: 'api.example.com', + challengeSecret: 'CHALLENGE-SECRET-'.padEnd(32, 'x'), + facilitator: { + mode: 'remote' as const, + url: 'https://facilitator.example', + auth: { type: 'none' as const }, + }, + }; + const config = makeGatewayConfig({ payments: { x402, mpp } }); + const offerName = (network: string, asset: string, payTo: string) => + `${network} ${asset.toLowerCase()} ${payTo.toLowerCase()}`; + const withHealth = (name: 'x402' | 'mpp', components: AdapterHealthComponent[]) => ({ + ...createFakePaymentProvider({ name }), + health: async () => ({ status: 'fail' as const, checkedAt: 'x', components }), + }); + const gateway = await buildGateway({ + config, + paymentProviders: [ + withHealth('x402', [ + { + name: offerName(x402.network, x402.asset, x402.payTo), + status: 'fail', + undetermined: 'unreachable', + }, + ]), + withHealth('mpp', [ + { name: offerName(mpp.network, mpp.asset, mpp.recipient), status: 'fail' }, + ]), + ], + }); + const res = await gateway.server.inject({ method: 'GET', url: '/.well-known/agent-commerce' }); + const { payments } = res.json(); + expect(payments.x402).toMatchObject({ status: 'fail', undetermined: 'unreachable' }); + expect(payments.x402).not.toHaveProperty('options'); + // A wrong answer is a verdict, and carries no mark + expect(payments.mpp.status).toBe('fail'); + expect(payments.mpp).not.toHaveProperty('undetermined'); + }); + + it('marks each listed x402 offer, and leaves the multi-offer block and an unprobed offer bare', async () => { + const base = makeGatewayConfig(); + const x402 = base.payments.x402 as NonNullable; + const second = { ...x402, asset: '0x2222222222222222222222222222222222222222' }; + const config = makeGatewayConfig({ payments: { x402: { ...x402, options: [x402, second] } } }); + const provider = { + ...createFakePaymentProvider(), + health: async () => ({ + status: 'fail' as const, + checkedAt: 'x', + // No component for the first offer + components: [ + { + name: `${second.network} ${second.asset} ${second.payTo.toLowerCase()}`, + status: 'fail' as const, + undetermined: 'unreachable' as const, + }, + ], + }), + }; + const gateway = await buildGateway({ config, paymentProviders: [provider] }); + const res = await gateway.server.inject({ method: 'GET', url: '/.well-known/agent-commerce' }); + const block = res.json().payments.x402; + expect(block).not.toHaveProperty('status'); + expect(block).not.toHaveProperty('undetermined'); + expect(block.options[0]).not.toHaveProperty('status'); + expect(block.options[1]).toMatchObject({ status: 'fail', undetermined: 'unreachable' }); + }); + it('GET /api/resources lists resources without leaking backend header secrets', async () => { const config = makeGatewayConfig(); const withSecretHeader = { diff --git a/tests/unit/payments-x402/facilitator-isolation.test.ts b/tests/unit/payments-x402/facilitator-isolation.test.ts index 7b7fb4d..ee7b3d7 100644 --- a/tests/unit/payments-x402/facilitator-isolation.test.ts +++ b/tests/unit/payments-x402/facilitator-isolation.test.ts @@ -88,9 +88,11 @@ describe('remote facilitator binding', () => { if (binding.kind !== 'remote') throw new Error('expected a remote binding'); const read = binding.supported(); + // health() reads the TimeoutError cause as "no answer" const outcome = expect(read).rejects.toMatchObject({ code: 'PAYMENT_PROVIDER_UNAVAILABLE', message: expect.stringContaining('did not answer within 10 s'), + cause: expect.objectContaining({ name: 'TimeoutError' }), }); await vi.advanceTimersByTimeAsync(SUPPORTED_TIMEOUT_MS); await outcome; diff --git a/tests/unit/payments-x402/provider-health-mocked.test.ts b/tests/unit/payments-x402/provider-health-mocked.test.ts index 9d732ab..409a960 100644 --- a/tests/unit/payments-x402/provider-health-mocked.test.ts +++ b/tests/unit/payments-x402/provider-health-mocked.test.ts @@ -4,8 +4,10 @@ * throw, and every RPC or chain-state outcome is cheap to force this way. */ +import { FacilitatorTimeoutError } from '@x402/core/http'; +import { HttpRequestError, RpcRequestError, TimeoutError } from 'viem'; import { beforeEach, describe, expect, it, vi } from 'vitest'; -import type { Clock } from '../../../src/core'; +import { type Clock, CommerceError } from '../../../src/core'; const getChainIdMock = vi.fn(); const getCodeMock = vi.fn(); @@ -235,6 +237,114 @@ describe('health() - mocked RPC client', () => { }); }); +// Exercise error classification with the libraries' own error classes. +// tests/integration/doctor-certainty.test.ts covers refused connections, +// JSON-RPC errors and HTTP 401 responses through real clients. +describe('health() - a throw that got no answer marks the offer', () => { + const url = 'http://127.0.0.1:19322'; + // undici's fetch error, with the Node error code on its cause + const fetchFailed = (code: string) => + new TypeError('fetch failed', { cause: Object.assign(new Error(code), { code }) }); + + beforeEach(() => { + vi.clearAllMocks(); + readContractMock.mockResolvedValue(6); + getCodeMock.mockResolvedValue('0x6080604052'); + }); + + // `where` says which call throws: the RPC, or the facilitator's `/supported` + async function componentAfter(where: 'rpc' | 'facilitator', err: unknown) { + if (where === 'rpc') { + getChainIdMock.mockRejectedValueOnce(err); + } else { + getChainIdMock.mockResolvedValueOnce(84532); + supportedMock.mockRejectedValueOnce(err); + } + const health = await (await makeProvider('remote')).health(); + expect(health.status).toBe('fail'); + return health.components?.[0]; + } + + it.each([ + [ + 'rpc', + 'a refused connection, as viem wraps it', + () => new HttpRequestError({ url, cause: fetchFailed('ECONNREFUSED') }), + ], + ['rpc', "viem's request timeout", () => new TimeoutError({ body: {}, url })], + [ + 'rpc', + 'an aborted fetch on a Solana or NEAR call', + () => new DOMException('The operation was aborted due to timeout', 'TimeoutError'), + ], + ['facilitator', 'a refused connection', () => fetchFailed('ECONNREFUSED')], + [ + 'facilitator', + "the SDK's request timeout", + () => new FacilitatorTimeoutError('supported', 10_000), + ], + [ + 'facilitator', + 'the /supported deadline', + () => + new CommerceError('PAYMENT_PROVIDER_UNAVAILABLE', 'did not answer within 10 s', { + cause: new DOMException('did not answer within 10 s', 'TimeoutError'), + }), + ], + ] as const)('marks the %s unreachable after %s', async (where, _label, error) => { + expect(await componentAfter(where, error())).toMatchObject({ + status: 'fail', + undetermined: 'unreachable', + }); + }); + + it.each([ + [ + 'rpc', + 'a JSON-RPC error', + () => new RpcRequestError({ body: {}, url, error: { code: -32601, message: 'no method' } }), + ], + [ + 'rpc', + 'a non-2xx from the RPC', + () => new HttpRequestError({ url, status: 502, details: 'Bad Gateway' }), + ], + [ + 'rpc', + 'a 2xx whose body is not JSON', + () => new HttpRequestError({ url, cause: new SyntaxError('Unexpected token <') }), + ], + [ + 'rpc', + 'a Solana or NEAR JSON-RPC error', + () => + new CommerceError('PAYMENT_PROVIDER_UNAVAILABLE', 'RPC status failed', { + details: { rpcError: { code: -32000 } }, + }), + ], + [ + 'rpc', + 'a hostname that does not resolve', + () => new HttpRequestError({ url, cause: fetchFailed('ENOTFOUND') }), + ], + [ + 'facilitator', + 'a certificate for another host', + () => fetchFailed('ERR_TLS_CERT_ALTNAME_INVALID'), + ], + ['rpc', 'an unrecognized error', () => new Error('boom')], + [ + 'facilitator', + 'a 401 from /supported', + () => new Error('Facilitator getSupported failed (401): unauthorized'), + ], + ] as const)('leaves the %s unmarked after %s', async (where, _label, error) => { + const component = await componentAfter(where, error()); + expect(component?.status).toBe('fail'); + expect(component).not.toHaveProperty('undetermined'); + }); +}); + describe('health() - several offers', () => { const OTHER_ASSET = '0x2222222222222222222222222222222222222222' as const; From 80628bcf5ed63d34b75bdfebed82c8ea570074b4 Mon Sep 17 00:00:00 2001 From: Revinand Date: Wed, 18 Nov 2026 17:18:58 +0100 Subject: [PATCH 06/14] feat(x402): add an opt-in public resource URL --- docs/configuration.md | 34 ++- docs/contracts.md | 9 + docs/protocols/x402.md | 37 ++- docs/security.md | 2 + src/config/schema/normalize.ts | 40 +++ src/config/schema/raw.ts | 2 + src/config/schema/types.ts | 7 + src/gateway/payment-providers.ts | 1 + src/payments/x402/provider/requirement.ts | 25 +- src/payments/x402/provider/types.ts | 8 + tests/integration/a2a-x402-extension.test.ts | 113 +++++++- tests/integration/mpp-config.test.ts | 34 ++- tests/integration/x402-public-url.test.ts | 212 +++++++++++++++ tests/unit/config/schema.test.ts | 71 +++++ .../payments-x402/public-resource-url.test.ts | 247 ++++++++++++++++++ 15 files changed, 810 insertions(+), 32 deletions(-) create mode 100644 tests/integration/x402-public-url.test.ts create mode 100644 tests/unit/payments-x402/public-resource-url.test.ts diff --git a/docs/configuration.md b/docs/configuration.md index bbe2c63..af9ea12 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -631,12 +631,42 @@ to fit the response headers. Its default is one 4 or 8 KB memory page; oversized headers cause nginx to reject the response. SDK clients echo quotes in `PAYMENT-SIGNATURE`, which can reach about 7.4 KB with six quoted offers. This approaches nginx's default 8 KB limit for a single request header field, -set by -[`large_client_header_buffers`](https://nginx.org/en/docs/http/ngx_http_core_module.html#large_client_header_buffers). +set by [`large_client_header_buffers`](https://nginx.org/en/docs/http/ngx_http_core_module.html#large_client_header_buffers). Each cache miss requires a signature per EVM offer. Rate-limit unpaid requests at the edge; see [Denial of service](security.md#denial-of-service). +### Public resource URL + +Experimental and disabled by default. `publicResourceUrl: true` sets an x402 +challenge's `resource.url` to the configured public endpoint for the request's +surface. This gives indexers a URL they can request in place of the gateway's +`resource://agent-commerce/...` identifier. + +```yaml +merchant: + publicBaseUrl: https://shop.example +payments: + x402: + publicResourceUrl: true +``` + +| Request arrives on | `resource.url` | +| ------------------ | ------------------------------------------- | +| HTTP | `/api/resources//invoke` | +| MCP | `` | +| A2A | `` | + +Requests without a URL mapping keep the `resource://` form. MPP challenges +are unchanged. Enabling the option requires `merchant.publicBaseUrl` to be an +http:// or https:// URL; otherwise config loading fails with `CONFIG_INVALID`. + +After the option changes, proofs that echo the previous URL are rejected, +including proofs for A2A tasks still awaiting payment after a restart. Proofs +that echo another surface's URL are also rejected. Both cases return +`invalid_payment_requirements` without settlement; the buyer can request and +pay a new challenge. See [x402](protocols/x402.md#the-resource-url). + ### `payments.mpp` MPP accepts the `USDC` currency label on the local chain `eip155:31337`, Base diff --git a/docs/contracts.md b/docs/contracts.md index a286c33..6f132bf 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -468,6 +468,15 @@ persistence must not fail the commerce flow. offer in `options` and `resourceOptions`. - `doctor` reads them for `Payments (offers)` and the new `Payments (MPP offers)` check. +- 2.8.0: experimental `X402ProviderOptions.resourceUrls` maps resource ids and + request surfaces (`http`, `mcp` or `a2a`) to each challenge's `resource.url`. + - `createRequirement` reads the surface from `PaymentContext.protocol`. A + context without one, an ACP request, or a surface without an entry keeps + the `resource://` form. + - With `payments.x402.publicResourceUrl: true`, config normalization fills + `GatewayConfig.payments.x402.resourceUrls`. MPP's internal x402 provider + does not receive this map. + - Without the option, challenges are unchanged. ### Authorization and AP2 diff --git a/docs/protocols/x402.md b/docs/protocols/x402.md index 2acc1f5..345e8c9 100644 --- a/docs/protocols/x402.md +++ b/docs/protocols/x402.md @@ -66,16 +66,16 @@ sent. An absent `extra.paymentFlow` means `authorization`. A proof's `resource.u must equal the challenge's when present. A mismatch is `invalid_payment_requirements`, refused before the facilitator is called. `maxTimeoutSeconds` and `extra` keys added by the client are not compared. The facilitator receives the payload -without `resource`, since its `resource://` URL is the gateway's own identifier, -and without `extensions`: verification and settlement do not use echoed -[quotes](#erc-8409-signed-quotes), and a Permit2 gas-sponsoring extension would -activate unsupported SDK facilitator behavior. +without `resource` and `extensions`, after the gateway has checked the URL +in any echoed `resource` against the challenge. Verification and settlement +do not use echoed [quotes](#erc-8409-signed-quotes), and a Permit2 +gas-sponsoring extension would activate unsupported SDK facilitator behavior. -With [several options](../configuration.md#several-options), the challenge uses -`resource://agent-commerce/resources/`. The comparison above selects the -proof's offer; zero or multiple matches yield `invalid_payment_requirements`. -A resource with [its own offers](../configuration.md#a-resources-own-offers) -accepts only proofs matching that list; resources may share offers. +With [several options](../configuration.md#several-options), the comparison +above selects the proof's offer; zero or multiple matches yield +`invalid_payment_requirements`. A resource with +[its own offers](../configuration.md#a-resources-own-offers) accepts only +proofs matching that list; resources may share offers. x402 v1 is not accepted. A payload declaring an `x402Version` other than 2 is refused as `invalid_x402_version` on every carrier. A request carrying only the @@ -119,6 +119,25 @@ other types. Local mode requires Anvil on `eip155:31337`; all public networks require remote mode. Mainnet also requires the guardrails in [configuration.md](../configuration.md#mainnet-guardrails). +## The resource URL + +By default, `resource.url` is a gateway identifier. A single offer uses +`resource://agent-commerce///resources/`; multiple offers +share `resource://agent-commerce/resources/`. The `` and `` +segments are percent-encoded. + +With [`publicResourceUrl`](../configuration.md#public-resource-url), the URL +names the configured HTTP invoke route, MCP mount or A2A mount for the +request's surface. Every offer of that resource shares the URL on that surface; +`accepted` still selects the offer. The echo comparison above rejects these +proofs before calling the facilitator, so neither reaches settlement: + +- a proof that echoes the previous URL after the option changes; +- a proof that echoes another surface's URL. + +The buyer can request and pay a new challenge. These checks provide no security +boundary: `resource.url` is unsigned, and a client may omit it. + ## Payment identifier Experimental and disabled by default. A resource with diff --git a/docs/security.md b/docs/security.md index 6f6e369..419363b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -333,6 +333,8 @@ real funds. | amount differs from the price in either direction | `invalid_exact_evm_payload_authorization_value_mismatch` before settlement | `tests/e2e/payment/x402-settlement.e2e.test.ts` | | **an x402 proof whose `accepted` differs from the offer, or whose `resource.url` differs from the challenge's** | `invalid_payment_requirements` before the facilitator is called | `tests/unit/payments-x402/provider-remote-facilitator.test.ts` | | **multi-offer x402 proof whose `accepted` matches zero or multiple offers** | `invalid_payment_requirements`; no offer is selected and the facilitator is not called | `tests/unit/payments-x402/provider-remote-facilitator.test.ts` | +| **an x402 proof under `publicResourceUrl`, whose offers share one `resource.url`** | offer selection still uses `accepted`, as with `resource://`; the URL form does not change the replay key | `tests/unit/payments-x402/public-resource-url.test.ts` | +| **an x402 proof echoing a challenge issued before `publicResourceUrl` changed, or another surface's challenge** | `invalid_payment_requirements` before calling the facilitator; no settlement, including for an A2A task awaiting payment across a restart | `tests/unit/payments-x402/public-resource-url.test.ts`, `tests/integration/x402-public-url.test.ts`, `tests/integration/a2a-x402-extension.test.ts` | | **an AP2 mandate approved for one x402 offer, presented with a proof for another** | selected destination, network or asset fails mandate binding; no settlement | `tests/unit/core/execution/pipeline-authorization.test.ts` | | **an EIP-3009 authorization signed for one EVM chain, presented as another chain's offer** | `invalid_exact_evm_signature`: signature fails against the other chain's EIP-712 domain; neither chain's balances change | `tests/e2e/payment/x402-multichain.e2e.test.ts` | | **the same payer, token address and nonce on two EVM chains** | both settle: the replay key includes the chain id | same | diff --git a/src/config/schema/normalize.ts b/src/config/schema/normalize.ts index 87a89bd..966381d 100644 --- a/src/config/schema/normalize.ts +++ b/src/config/schema/normalize.ts @@ -1,5 +1,7 @@ // The business-rule pass: coerces leaves and checks cross-references across sections +import type { CommerceResource } from '../../core'; import { CommerceError } from '../../core'; +import { joinUrl } from '../../protocols/http'; import { normalizeAcp, validateAcpCheckoutMapping } from './acp'; import { normalizeAp2, validateLegacyStoresIsolated } from './ap2'; import { normalizeMpp } from './mpp'; @@ -59,12 +61,18 @@ export function normalize(raw: RawConfig): GatewayConfig { return mimeType !== undefined ? [[resource.id, mimeType]] : []; }), ); + const publicUrl = raw.payments.x402?.publicResourceUrl; + const resourceUrls = + publicUrl !== undefined && toBoolean(publicUrl, 'payments.x402.publicResourceUrl') + ? publicResourceUrls(raw.merchant.publicBaseUrl, protocols, resources) + : undefined; const x402WithFlows = x402 !== undefined ? { ...x402, ...flowOverrides('x402'), ...(Object.keys(mimeTypes).length > 0 ? { resourceMimeTypes: mimeTypes } : {}), + ...(resourceUrls !== undefined ? { resourceUrls } : {}), } : x402; const mppWithFlows = mpp !== undefined ? { ...mpp, ...flowOverrides('mpp') } : mpp; @@ -110,6 +118,38 @@ export function normalize(raw: RawConfig): GatewayConfig { }; } +// Build URLs for the surfaces exposing each x402 resource, using the public +// base URL so indexers can request endpoints instead of `resource://` identifiers +function publicResourceUrls( + publicBaseUrl: string, + protocols: NormalizedProtocols, + resources: readonly CommerceResource[], +): Record>> { + if (!isHttpUrl(publicBaseUrl)) { + throw new CommerceError( + 'CONFIG_INVALID', + `payments.x402.publicResourceUrl needs merchant.publicBaseUrl to be an http:// or https:// URL, not ${JSON.stringify(publicBaseUrl)}`, + { details: { path: 'merchant.publicBaseUrl' } }, + ); + } + const path = (surface: 'http' | 'mcp' | 'a2a', id: string) => + surface === 'http' + ? `/api/resources/${encodeURIComponent(id)}/invoke` + : protocols[surface].mountPath; + return Object.fromEntries( + resources + .filter((resource) => resource.paymentMethods.includes('x402')) + .map((resource) => [ + resource.id, + Object.fromEntries( + (['http', 'mcp', 'a2a'] as const) + .filter((surface) => resource.exposedVia.includes(surface)) + .map((surface) => [surface, joinUrl(publicBaseUrl, path(surface, resource.id))]), + ), + ]), + ); +} + // Two enabled mounts may not overlap: each registers a `${mountPath}/*` // wildcard, so a shared prefix lets one adapter answer for the other. Disabled // protocols mount nothing and are not compared. diff --git a/src/config/schema/raw.ts b/src/config/schema/raw.ts index 9a5a918..ee3e812 100644 --- a/src/config/schema/raw.ts +++ b/src/config/schema/raw.ts @@ -353,6 +353,8 @@ const X402Schema = z allowMainnet: BooleanOrString.optional(), // Accepts credential-free facilitator access on mainnet. Never defaulted allowUnauthenticatedFacilitator: BooleanOrString.optional(), + // Experimental: use the configured public endpoint in x402 challenges + publicResourceUrl: BooleanOrString.optional(), // Experimental ERC-8409 quotes; signing a quote transfers no funds quote: z .object({ diff --git a/src/config/schema/types.ts b/src/config/schema/types.ts index 92c00a3..f32208a 100644 --- a/src/config/schema/types.ts +++ b/src/config/schema/types.ts @@ -5,6 +5,7 @@ import type { MppNetwork } from '../../payments/mpp/constants'; import type { X402FacilitatorConfig } from '../../payments/x402/guardrails'; import type { CustomNetworks } from '../../payments/x402/networks'; import type { X402PaymentFlow } from '../../payments/x402/payment-flow'; +import type { X402ProviderOptions } from '../../payments/x402/provider/types'; import type { AcpCheckoutOperation } from '../../protocols/acp/constants'; /** Optional ACP discovery metadata. Absent fields are omitted from the document */ @@ -93,6 +94,12 @@ export interface GatewayConfig { readonly resourcePaymentFlows?: Readonly>; /** Resources that set `mimeType`, by resource id; others declare `application/json` */ readonly resourceMimeTypes?: Readonly>; + /** + * Experimental. With `publicResourceUrl: true`, config normalization maps + * each x402 resource's exposed HTTP, MCP and A2A surfaces to its invoke + * route or protocol mount under `merchant.publicBaseUrl`. + */ + readonly resourceUrls?: NonNullable; readonly facilitator: X402FacilitatorConfig; readonly allowMainnet?: boolean; readonly allowUnauthenticatedFacilitator?: boolean; diff --git a/src/gateway/payment-providers.ts b/src/gateway/payment-providers.ts index afcc1d7..222e786 100644 --- a/src/gateway/payment-providers.ts +++ b/src/gateway/payment-providers.ts @@ -59,6 +59,7 @@ export async function createConfiguredPaymentProviders( ...(x402.resourceMimeTypes !== undefined ? { resourceMimeTypes: x402.resourceMimeTypes } : {}), + ...(x402.resourceUrls !== undefined ? { resourceUrls: x402.resourceUrls } : {}), facilitator: x402.facilitator, ...(x402.allowMainnet !== undefined ? { allowMainnet: x402.allowMainnet } : {}), ...(x402.allowUnauthenticatedFacilitator !== undefined diff --git a/src/payments/x402/provider/requirement.ts b/src/payments/x402/provider/requirement.ts index a08f545..80ccbe1 100644 --- a/src/payments/x402/provider/requirement.ts +++ b/src/payments/x402/provider/requirement.ts @@ -112,20 +112,27 @@ export function createRequirementBuilders( const extensions = identifier === undefined ? quoteExtensions : { ...quoteExtensions, ...identifier }; - // The v2 challenge document as sent on the wire. The HTTP adapter - // base64-encodes it into `PAYMENT-REQUIRED` and MCP passes it through, so - // both surfaces offer the same challenge. + // Build the v2 challenge document. HTTP base64-encodes it into + // `PAYMENT-REQUIRED`; MCP passes the document through directly. // - // `resource.url` is outside the EIP-3009 signature. A single offer puts its - // network and payee in it, so the buyer's echo identifies the offer. With - // several, the URL stays the same whichever one the buyer pays. + // `accepted` identifies the offer paid by a proof. With a matching + // `resourceUrls` entry, `resource.url` uses the configured URL for this + // resource and request surface. Otherwise a single offer's `resource://` + // URL includes its network and payee; multiple offers share one URL. + // The URL is outside the EIP-3009 signature; verification rejects a + // mismatched URL only when the proof echoes it. const resourceId = encodeURIComponent(context.resource.id); + const surface = context.protocol === 'acp' ? undefined : context.protocol; + const publicUrl = + surface !== undefined ? options.resourceUrls?.[context.resource.id]?.[surface] : undefined; const envelope: PaymentRequired = { x402Version: X402_VERSION, resource: { - url: single - ? `resource://agent-commerce/${encodeURIComponent(single.network)}/${single.payTo}/resources/${resourceId}` - : `resource://agent-commerce/resources/${resourceId}`, + url: + publicUrl ?? + (single + ? `resource://agent-commerce/${encodeURIComponent(single.network)}/${single.payTo}/resources/${resourceId}` + : `resource://agent-commerce/resources/${resourceId}`), description: context.resource.description ?? context.resource.name, // The media type the merchant declares, else `application/json`; an HTTP // delivery carries the backend's own type when it is text and fits the body diff --git a/src/payments/x402/provider/types.ts b/src/payments/x402/provider/types.ts index 02bf5ef..1bf52aa 100644 --- a/src/payments/x402/provider/types.ts +++ b/src/payments/x402/provider/types.ts @@ -25,6 +25,14 @@ export interface X402ProviderOptions extends X402OfferOptions { * keyed by resource id. Defaults to `application/json`. */ readonly resourceMimeTypes?: Readonly>; + /** + * Experimental. Maps resource ids and request surfaces to the public + * `resource.url` used in their challenges. Requests without a surface, + * ACP requests and missing entries use `resource://agent-commerce/...`. + */ + readonly resourceUrls?: Readonly< + Record>>> + >; /** * Which facilitator verifies and broadcasts. `local` runs one in this process * against a dev chain, and its `signerPrivateKey` pays gas there, usually diff --git a/tests/integration/a2a-x402-extension.test.ts b/tests/integration/a2a-x402-extension.test.ts index c81cff2..67d9bdb 100644 --- a/tests/integration/a2a-x402-extension.test.ts +++ b/tests/integration/a2a-x402-extension.test.ts @@ -3,19 +3,29 @@ * providers, the real A2A adapter, and an `@x402/core` client building the * `PaymentPayload`. Only the facilitator HTTP client is mocked. */ + +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { x402Client } from '@x402/core/client'; import type { PaymentRequired } from '@x402/core/types'; import { registerExactEvmScheme } from '@x402/evm/exact/client'; import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { GatewayConfig } from '../../src/config'; -import type { CanonicalRequest, CommerceResource, PaymentMethodName } from '../../src/core'; +import type { + CanonicalRequest, + CommerceResource, + PaymentMethodName, + ReceiptStore, +} from '../../src/core'; import { createGateway, type GatewayInstance } from '../../src/gateway'; import { createMppPaymentProvider } from '../../src/payments/mpp/provider'; import { createX402PaymentProvider } from '../../src/payments/x402/provider'; import { createA2aAdapter } from '../../src/protocols/a2a'; import type { A2aAgentCard, A2aTask } from '../../src/protocols/a2a/types'; import { A2A_X402_EXTENSION_URI } from '../../src/protocols/a2a/x402-extension'; +import { createSqliteReceiptStore } from '../../src/storage/receipts'; import { createFakeStore } from '../unit/gateway/helpers'; process.env['NODE_ENV'] = 'test'; @@ -44,6 +54,16 @@ const REMOTE = { auth: { type: 'none' }, } as const; const buyer = privateKeyToAccount(generatePrivateKey()); +const X402_OPTIONS = { + network: 'eip155:31337', + rpcUrl: RPC_URL, + asset: ASSET, + assetName: AUTHORIZATION.name, + assetVersion: AUTHORIZATION.version, + assetDecimals: 6, + payTo: PAY_TO, + facilitator: REMOTE, +} as const; let gateway: GatewayInstance; let backendCalls = 0; @@ -90,16 +110,7 @@ beforeEach(async () => { config: config(), store: createFakeStore(), paymentProviders: [ - createX402PaymentProvider({ - network: 'eip155:31337', - rpcUrl: RPC_URL, - asset: ASSET, - assetName: AUTHORIZATION.name, - assetVersion: AUTHORIZATION.version, - assetDecimals: 6, - payTo: PAY_TO, - facilitator: REMOTE, - }), + createX402PaymentProvider(X402_OPTIONS), createMppPaymentProvider({ network: 'eip155:31337', recipient: PAY_TO, @@ -567,3 +578,83 @@ describe('an AP2 mandate sent with the x402 extension payment', () => { expect(body.result?.task.status.state).toBe('TASK_STATE_COMPLETED'); }); }); + +describe('x402 A2A extension with the public resource URL, across a restart', () => { + const A2A_URL = 'http://localhost:8080/a2a'; + let dir = ''; + let store: ReceiptStore | undefined; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'a2a-public-url-')); + }); + + afterEach(async () => { + await gateway.close().catch(() => {}); + await store?.close(); + store = undefined; + rmSync(dir, { recursive: true, force: true }); + }); + + // Use the shared receipt file to preserve tasks awaiting payment across boots + async function boot(publicUrl: boolean): Promise { + await gateway.close().catch(() => {}); + await store?.close(); + store = createSqliteReceiptStore({ path: join(dir, 'receipts.db') }); + await store.init(); + gateway = await createGateway({ + config: config(), + store, + paymentProviders: [ + createX402PaymentProvider({ + ...X402_OPTIONS, + ...(publicUrl ? { resourceUrls: { x402_report: { a2a: A2A_URL } } } : {}), + }), + ], + protocolAdapters: [createA2aAdapter({ store })], + backend: { + async call() { + backendCalls++; + return { status: 200, body: { report: 'paid' }, headers: {}, durationMs: 1 }; + }, + }, + }); + } + + const submitted = async (task: A2aTask) => ({ + 'x402.payment.status': 'payment-submitted', + 'x402.payment.payload': await paymentPayload(task), + }); + + it('pays a task after a restart, its proof echoing the A2A URL, and settles once', async () => { + await boot(true); + const task = await challenged(); + const required = task.status.message?.metadata?.['x402.payment.required'] as PaymentRequired; + expect(required.resource.url).toBe(A2A_URL); + const metadata = await submitted(task); + + await boot(true); + const { body } = await rpc(pay(task, metadata)); + + expect(body.result?.task.status.state).toBe('TASK_STATE_COMPLETED'); + expect(backendCalls).toBe(1); + expect(facilitator.settle).toHaveBeenCalledTimes(1); + }); + + it('refuses a task challenged before the URL was turned on, and settles nothing', async () => { + await boot(false); + const task = await challenged(); + const metadata = await submitted(task); + + await boot(true); + const { body } = await rpc(pay(task, metadata)); + + expect(body.result?.task.status.state).toBe('TASK_STATE_FAILED'); + expect(body.result?.task.status.message?.metadata).toMatchObject({ + 'x402.payment.status': 'payment-failed', + 'x402.payment.error': 'invalid_payment_requirements', + }); + expect(backendCalls).toBe(0); + expect(facilitator.verify).not.toHaveBeenCalled(); + expect(facilitator.settle).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/integration/mpp-config.test.ts b/tests/integration/mpp-config.test.ts index a79b5ce..beac533 100644 --- a/tests/integration/mpp-config.test.ts +++ b/tests/integration/mpp-config.test.ts @@ -32,12 +32,13 @@ const MPP = { facilitator: { mode: 'remote', url: `https://facilitator.example/${FACILITATOR_TENANT}` }, }; -function mppOnlyConfig(withX402 = false) { +function mppOnlyConfig(withX402 = false, publicResourceUrl = false) { const raw = validRawConfig(); const x402 = { ...((raw['payments'] as Record>)['x402'] ?? {}), payTo: '0x2222222222222222222222222222222222222222', facilitator: { mode: 'remote', url: 'https://x402-facilitator.example' }, + ...(publicResourceUrl ? { publicResourceUrl } : {}), }; const mpp = { ...MPP, rpcUrl }; raw['payments'] = withX402 ? { x402, mpp } : { mpp }; @@ -112,4 +113,35 @@ describe('payments.mpp wiring', () => { expect(wellKnown.body).not.toContain(secret); } }); + + it("keeps MPP's challenge when x402 names public resource URLs", async () => { + const challenge = async (publicResourceUrl: boolean) => { + const config = mppOnlyConfig(true, publicResourceUrl); + const node = await createGateway({ + config, + store: createFakeStore(), + paymentProviders: await createConfiguredPaymentProviders(config.payments, NOOP_TEST_LOGGER), + protocolAdapters: [], + backend, + }); + try { + const res = await node.server.inject({ + method: 'POST', + url: '/api/resources/market_report/invoke', + headers: { 'content-type': 'application/json' }, + payload: {}, + }); + expect(res.statusCode).toBe(402); + const { realm, method, intent, request } = Challenge.deserialize( + String(res.headers['www-authenticate']), + ); + return { realm, method, intent, request }; + } finally { + await node.close(); + } + }; + expect(await challenge(true)).toEqual(await challenge(false)); + // The MPP-paid resource gets no x402 URL + expect(mppOnlyConfig(true, true).payments.x402?.resourceUrls).toEqual({}); + }); }); diff --git a/tests/integration/x402-public-url.test.ts b/tests/integration/x402-public-url.test.ts new file mode 100644 index 0000000..01c2c6a --- /dev/null +++ b/tests/integration/x402-public-url.test.ts @@ -0,0 +1,212 @@ +/** + * Exercise `payments.x402.publicResourceUrl` from config normalization to SDK + * buyer clients, using the gateway, configured providers and MCP adapter. + * The facilitator HTTP client is mocked. + */ +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'; +import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; +import { x402Client } from '@x402/core/client'; +import type { PaymentPayload, PaymentRequired } from '@x402/core/types'; +import { registerExactEvmScheme } from '@x402/evm/exact/client'; +import { wrapMCPClientWithPayment } from '@x402/mcp'; +import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { parseConfig } from '../../src/config'; +import { NOOP_LOGGER } from '../../src/core'; +import { createGateway, type GatewayInstance } from '../../src/gateway'; +import { createConfiguredPaymentProviders } from '../../src/gateway/payment-providers'; +import { createMcpAdapter } from '../../src/protocols/mcp'; +import { createFakeStore } from '../unit/gateway/helpers'; + +const facilitator = vi.hoisted(() => ({ verify: vi.fn(), settle: vi.fn() })); +vi.mock('@x402/core/http', () => ({ + FacilitatorResponseError: class extends Error {}, + HTTPFacilitatorClient: class { + verify(...args: unknown[]) { + return facilitator.verify(...args); + } + settle(...args: unknown[]) { + return facilitator.settle(...args); + } + }, +})); + +const BASE = 'https://shop.example'; +const NETWORK = 'eip155:84532'; +const INVOKE = `${BASE}/api/resources/report/invoke`; +const TX = `0x${'ab'.repeat(32)}`; +const buyer = privateKeyToAccount(generatePrivateKey()); + +let gateway: GatewayInstance; +let url = ''; +let mcp: Client | undefined; + +beforeEach(async () => { + facilitator.verify.mockReset().mockResolvedValue({ isValid: true, payer: buyer.address }); + facilitator.settle.mockReset().mockResolvedValue({ + success: true, + transaction: TX, + network: NETWORK, + payer: buyer.address, + }); + const config = parseConfig( + { + version: 1, + merchant: { id: 'shop', name: 'Shop', publicBaseUrl: BASE }, + server: { port: 0, host: '127.0.0.1' }, + storage: { receipts: { driver: 'sqlite', path: ':memory:' } }, + protocols: { http: { enabled: true }, mcp: { enabled: true, mountPath: '/mcp' } }, + resources: { + report: { + name: 'Report', + input: { type: 'object', properties: {}, additionalProperties: false }, + backend: { type: 'http', method: 'GET', url: 'http://backend.local/report' }, + pricing: { type: 'fixed', amount: '0.01', currency: 'USDC' }, + expose: ['http', 'mcp'], + payments: ['x402'], + }, + // A path separator and a space in an id the HTTP route still finds + 'eu/q3 report': { + name: 'EU Q3 report', + input: { type: 'object', properties: {}, additionalProperties: false }, + backend: { type: 'http', method: 'GET', url: 'http://backend.local/report' }, + pricing: { type: 'fixed', amount: '0.01', currency: 'USDC' }, + expose: ['http'], + payments: ['x402'], + }, + }, + payments: { + x402: { + enabled: true, + network: NETWORK, + rpcUrl: 'http://127.0.0.1:19321', // never contacted + payTo: '0x1111111111111111111111111111111111111111', + maxTimeoutSeconds: 120, + facilitator: { mode: 'remote', url: 'https://facilitator.example' }, + publicResourceUrl: true, + }, + }, + }, + {}, + ); + gateway = await createGateway({ + config, + store: createFakeStore(), + paymentProviders: await createConfiguredPaymentProviders(config.payments, NOOP_LOGGER), + protocolAdapters: [createMcpAdapter()], + logger: NOOP_LOGGER, + backend: { + async call() { + return { status: 200, body: { report: 'paid' }, headers: {}, durationMs: 1 }; + }, + }, + }); + ({ url } = await gateway.listen()); +}); + +afterEach(async () => { + await mcp?.close().catch(() => {}); + mcp = undefined; + await gateway.close().catch(() => {}); +}); + +function payments(): x402Client { + const client = new x402Client(); + registerExactEvmScheme(client, { signer: buyer, networks: [NETWORK] }); + return client; +} + +// Send a request with the configured public Host header +function invoke(path: string, proof?: PaymentPayload) { + return gateway.server.inject({ + method: 'POST', + url: path, + headers: { + host: new URL(BASE).host, + 'content-type': 'application/json', + ...(proof !== undefined + ? { 'payment-signature': Buffer.from(JSON.stringify(proof)).toString('base64') } + : {}), + }, + payload: {}, + }); +} + +async function httpChallenge(path = '/api/resources/report/invoke'): Promise { + const res = await invoke(path); + expect(res.statusCode).toBe(402); + return JSON.parse( + Buffer.from(String(res.headers['payment-required']), 'base64').toString('utf8'), + ) as PaymentRequired; +} + +async function connect(): Promise { + mcp = new Client({ name: 'public-url-buyer', version: '0.0.0-test' }); + await mcp.connect(new StreamableHTTPClientTransport(new URL(`${url}/mcp`)) as Transport); + return mcp; +} + +describe('x402 public resource URL through the gateway', () => { + it('names the HTTP invoke route, and that URL answers 402', async () => { + const required = await httpChallenge(); + expect(required.resource.url).toBe(INVOKE); + + const again = await invoke(new URL(required.resource.url).pathname); + expect(again.statusCode).toBe(402); + }); + + it('encodes an id the URL could not carry, and that URL reaches the same resource', async () => { + const path = '/api/resources/eu%2Fq3%20report/invoke'; + const required = await httpChallenge(path); + expect(required.resource.url).toBe(`${BASE}${path}`); + + const again = await httpChallenge(new URL(required.resource.url).pathname); + expect(again.resource.url).toBe(required.resource.url); + }); + + it('delivers to an SDK proof that echoes the HTTP URL, and settles once', async () => { + const paid = await invoke( + '/api/resources/report/invoke', + await payments().createPaymentPayload(await httpChallenge()), + ); + expect(paid.statusCode).toBe(200); + expect(paid.json()).toEqual({ report: 'paid' }); + expect(facilitator.settle).toHaveBeenCalledTimes(1); + }); + + it('names the MCP mount, and an @x402/mcp client pays it', async () => { + const client = await connect(); + const challenged = (await client.callTool({ name: 'report', arguments: {} })) as CallToolResult; + expect((challenged.structuredContent as unknown as PaymentRequired).resource.url).toBe( + `${BASE}/mcp`, + ); + + const result = await wrapMCPClientWithPayment(client, payments(), { + autoPayment: true, + }).callTool('report', {}); + expect(result.paymentMade).toBe(true); + expect(result.isError).not.toBe(true); + expect(facilitator.settle).toHaveBeenCalledTimes(1); + }); + + it('refuses on MCP a proof made for the HTTP challenge, before the facilitator', async () => { + const proof = await payments().createPaymentPayload(await httpChallenge()); + const refused = (await ( + await connect() + ).callTool({ + name: 'report', + arguments: {}, + _meta: { 'x402/payment': proof }, + })) as CallToolResult; + + expect(refused.isError).toBe(true); + expect(refused.structuredContent).toMatchObject({ + code: 'PAYMENT_INVALID', + error: 'invalid_payment_requirements', + }); + expect(facilitator.verify).not.toHaveBeenCalled(); + expect(facilitator.settle).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/config/schema.test.ts b/tests/unit/config/schema.test.ts index 838c7a5..963363b 100644 --- a/tests/unit/config/schema.test.ts +++ b/tests/unit/config/schema.test.ts @@ -2557,6 +2557,77 @@ describe('resource mimeType', () => { }); }); +describe('payments.x402.publicResourceUrl', () => { + function withPublicUrl(value: unknown, edit: (raw: Record) => void = () => {}) { + const raw = validRawConfig(); + (raw['payments'] as { x402: Record }).x402['publicResourceUrl'] = value; + edit(raw); + return raw; + } + + it.each([ + ['absent', validRawConfig()], + ['false', withPublicUrl(false)], + ])('gives the x402 rail no resource URLs when %s', (_label, raw) => { + expect(parseConfig(raw, {}).payments.x402?.resourceUrls).toBeUndefined(); + }); + + it.each([true, 'true'])( + 'names the invoke route and MCP mount of each paid resource with %j', + (value) => { + // weather_basic is free and gets no URL + expect(parseConfig(withPublicUrl(value), {}).payments.x402?.resourceUrls).toEqual({ + market_report: { + http: 'http://localhost:8080/api/resources/market_report/invoke', + mcp: 'http://localhost:8080/mcp', + }, + }); + }, + ); + + it('joins a base URL with a path and a trailing slash, and adds the A2A mount', () => { + const raw = withPublicUrl(true, (r) => { + (r['merchant'] as Record)['publicBaseUrl'] = 'https://shop.example/gw/'; + (r['protocols'] as Record)['a2a'] = { enabled: true, mountPath: '/agents' }; + (r['resources'] as { market_report: Record }).market_report['expose'] = [ + 'http', + 'a2a', + ]; + }); + expect(parseConfig(raw, {}).payments.x402?.resourceUrls).toEqual({ + market_report: { + http: 'https://shop.example/gw/api/resources/market_report/invoke', + a2a: 'https://shop.example/gw/agents', + }, + }); + }); + + it('refuses the opt-in when merchant.publicBaseUrl is not an http(s) URL', () => { + const raw = withPublicUrl(true, (r) => { + (r['merchant'] as Record)['publicBaseUrl'] = 'localhost:8080'; + }); + expectConfigInvalid( + () => parseConfig(raw, {}), + 'merchant.publicBaseUrl', + 'payments.x402.publicResourceUrl needs merchant.publicBaseUrl to be an http:// or https:// URL', + ); + }); + + it('still only warns about that base URL without the opt-in', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const raw = validRawConfig(); + (raw['merchant'] as Record)['publicBaseUrl'] = 'localhost:8080'; + try { + expect(parseConfig(raw, {}).merchant.publicBaseUrl).toBe('localhost:8080'); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('is not an http:// or https:// URL'), + ); + } finally { + warn.mockRestore(); + } + }); +}); + describe('resource idempotency', () => { function withIdempotency(id: string, idempotency: unknown): Record { const raw = validRawConfig(); diff --git a/tests/unit/payments-x402/public-resource-url.test.ts b/tests/unit/payments-x402/public-resource-url.test.ts new file mode 100644 index 0000000..c108500 --- /dev/null +++ b/tests/unit/payments-x402/public-resource-url.test.ts @@ -0,0 +1,247 @@ +// Public `resource.url` selection, offer matching and URL mismatch refusals +import { x402Client } from '@x402/core/client'; +import type { PaymentPayload, PaymentRequired } from '@x402/core/types'; +import { registerExactEvmScheme } from '@x402/evm/exact/client'; +import { privateKeyToAccount } from 'viem/accounts'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { + CommerceResource, + PaymentContext, + PaymentRequirement, + ProtocolName, +} from '../../../src/core'; +import { + createX402PaymentProvider, + type X402ProviderOptions, +} from '../../../src/payments/x402/provider'; + +const verifyMock = vi.fn(); + +// Local proof validation runs before the mocked facilitator HTTP client +vi.mock('@x402/core/http', () => ({ + FacilitatorResponseError: class extends Error {}, + HTTPFacilitatorClient: class { + verify(...args: unknown[]) { + return verifyMock(...args); + } + }, +})); + +const ASSET = '0x5FbDB2315678afecb367f032d93F642f64180aa3'; +const PAY_TO = '0x1111111111111111111111111111111111111111'; +const OTHER_ASSET = '0x2222222222222222222222222222222222222222'; +const OTHER_PAY_TO = '0x3333333333333333333333333333333333333333'; +const BUYER = privateKeyToAccount( + '0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a', +); +const BASE = 'https://shop.example'; +const URLS = { + 'demo.report': { + http: `${BASE}/api/resources/demo.report/invoke`, + mcp: `${BASE}/mcp`, + a2a: `${BASE}/a2a`, + }, +}; +const SINGLE_RESOURCE_URL = `resource://agent-commerce/eip155%3A31337/${PAY_TO}/resources/demo.report`; +const SHARED_RESOURCE_URL = 'resource://agent-commerce/resources/demo.report'; + +const RESOURCE: CommerceResource = { + id: 'demo.report', + name: 'Demo report', + handler: { type: 'http', method: 'GET', url: 'http://merchant.invalid/api/report' }, + pricing: { type: 'fixed', amount: '0.01', currency: 'USD' }, + exposedVia: ['http', 'mcp', 'a2a'], + paymentMethods: ['x402'], +}; + +const offer = (asset: string, payTo: string) => ({ + network: 'eip155:31337', + rpcUrl: 'http://127.0.0.1:19321', // never contacted + asset, + assetName: 'MockUSDC', + assetVersion: '2', + assetDecimals: 6, + payTo, +}); + +function provider(offers: 1 | 2, resourceUrls?: X402ProviderOptions['resourceUrls']) { + return createX402PaymentProvider({ + offers: + offers === 1 + ? [offer(ASSET, PAY_TO)] + : [offer(ASSET, PAY_TO), offer(OTHER_ASSET, OTHER_PAY_TO)], + facilitator: { mode: 'remote', url: 'https://facilitator.example', auth: { type: 'none' } }, + ...(resourceUrls !== undefined ? { resourceUrls } : {}), + }); +} + +function context(protocol?: ProtocolName): PaymentContext { + return { + requestId: 'req-1', + resource: RESOURCE, + amount: '0.01', + currency: 'USD', + requestedAt: '2026-11-18T00:00:00.000Z', + ...(protocol !== undefined ? { protocol } : {}), + }; +} + +const urlOf = (requirement: PaymentRequirement) => + (requirement.challenge.envelope as unknown as PaymentRequired).resource.url; + +// The SDK client signs the offer at `pick` and echoes the challenge's resource +async function sdkProof(challenge: PaymentRequirement, pick = 0): Promise { + const client = new x402Client((_version, accepts) => accepts[pick] as never); + registerExactEvmScheme(client, { signer: BUYER, networks: ['eip155:31337'] }); + client.setSpendControls(false); // the test token is not in the SDK's list + return client.createPaymentPayload(challenge.challenge.envelope as unknown as PaymentRequired); +} + +// Selects the offer as the pipeline does, then verifies against it +async function verify( + by: ReturnType, + requirement: PaymentRequirement, + payload: PaymentPayload, +) { + const ctx = { + requestId: 'req-1', + resource: RESOURCE, + requirement, + submission: { + method: 'x402' as const, + payload: Buffer.from(JSON.stringify(payload)).toString('base64'), + }, + }; + const selected = (await by.selectRequirement?.(ctx)) ?? requirement; + return { selected, result: await by.verify({ ...ctx, requirement: selected }) }; +} + +beforeEach(() => { + verifyMock.mockReset().mockResolvedValue({ isValid: true, payer: BUYER.address }); +}); + +describe('x402 public resource URL: the challenge', () => { + it.each([ + ['http', 1], + ['mcp', 1], + ['a2a', 1], + ['http', 2], + ['mcp', 2], + ['a2a', 2], + ] as const)('names the %s endpoint with %i offer(s)', async (protocol, offers) => { + const requirement = await provider(offers, URLS).createRequirement(context(protocol)); + expect(urlOf(requirement)).toBe(URLS['demo.report'][protocol]); + }); + + it.each([ + ['no surface', 1, undefined, SINGLE_RESOURCE_URL], + ['an ACP request', 1, 'acp', SINGLE_RESOURCE_URL], + ['no surface', 2, undefined, SHARED_RESOURCE_URL], + ['an ACP request', 2, 'acp', SHARED_RESOURCE_URL], + ] as const)( + 'keeps the resource:// form for %s with %i offer(s)', + async (_label, offers, protocol, url) => { + const requirement = await provider(offers, URLS).createRequirement(context(protocol)); + expect(urlOf(requirement)).toBe(url); + }, + ); + + it('keeps the resource:// form for a surface the map gives no URL', async () => { + const only = { 'demo.report': { http: URLS['demo.report'].http } }; + expect(urlOf(await provider(1, only).createRequirement(context('mcp')))).toBe( + SINGLE_RESOURCE_URL, + ); + }); + + it.each(['http', 'mcp', 'a2a'] as const)( + 'is unchanged without the option on the %s surface', + async (protocol) => { + expect(urlOf(await provider(1).createRequirement(context(protocol)))).toBe( + SINGLE_RESOURCE_URL, + ); + expect(urlOf(await provider(2).createRequirement(context(protocol)))).toBe( + SHARED_RESOURCE_URL, + ); + }, + ); +}); + +describe('x402 public resource URL: proofs', () => { + it.each([ + [1, 0, PAY_TO], + [2, 0, PAY_TO], + [2, 1, OTHER_PAY_TO], + ] as const)( + 'verifies an SDK proof echoing the URL, with %i offer(s), for the offer at %i', + async (offers, pick, payTo) => { + const by = provider(offers, URLS); + const challenge = await by.createRequirement(context('http')); + const payload = await sdkProof(challenge, pick); + expect(payload.resource?.url).toBe(URLS['demo.report'].http); + + const { selected, result } = await verify(by, challenge, payload); + expect(selected.destination).toBe(payTo); + expect(result.status).toBe('verified'); + expect(verifyMock).toHaveBeenCalledTimes(1); + }, + ); + + // Verify each proof against the requirement for the request carrying it + const REFUSED: ReadonlyArray< + readonly [string, (offers: 1 | 2) => Promise<[PaymentRequirement, PaymentPayload]>] + > = [ + [ + 'an echoed URL the challenge did not name', + async (offers) => { + const challenge = await provider(offers, URLS).createRequirement(context('http')); + const payload = await sdkProof(challenge); + return [challenge, { ...payload, resource: { ...payload.resource, url: `${BASE}/other` } }]; + }, + ], + [ + 'a proof for the HTTP challenge paid on MCP', + async (offers) => { + const by = provider(offers, URLS); + const payload = await sdkProof(await by.createRequirement(context('http'))); + return [await by.createRequirement(context('mcp')), payload]; + }, + ], + [ + 'a proof for a challenge issued before the switch', + async (offers) => { + const payload = await sdkProof(await provider(offers).createRequirement(context('http'))); + return [await provider(offers, URLS).createRequirement(context('http')), payload]; + }, + ], + ]; + + it.each( + REFUSED.flatMap(([label, build]) => [1, 2].map((offers) => [label, offers, build] as const)), + )('refuses %s, with %i offer(s), before the facilitator', async (_label, offers, build) => { + const [requirement, payload] = await build(offers as 1 | 2); + const { result } = await verify(provider(offers as 1 | 2, URLS), requirement, payload); + expect(result).toMatchObject({ + status: 'rejected', + rejectionReason: 'invalid_payment_requirements', + }); + expect(verifyMock).not.toHaveBeenCalled(); + }); + + it('derives one replay key from one authorization under either URL form', async () => { + const before = await provider(1).createRequirement(context('http')); + const after = await provider(1, URLS).createRequirement(context('http')); + const signed = await sdkProof(before); + // The same signed authorization, echoing the public URL instead + const echoed = { + ...signed, + resource: (after.challenge.envelope as unknown as PaymentRequired).resource, + }; + + const old = await verify(provider(1), before, signed); + const opted = await verify(provider(1, URLS), after, echoed); + expect(old.result.status).toBe('verified'); + expect(opted.result.status).toBe('verified'); + expect(opted.result.replayKey).toBeDefined(); + expect(opted.result.replayKey).toBe(old.result.replayKey); + }); +}); From 4f4c88eb7a2444272077ab5b104fbbf11b65c5f0 Mon Sep 17 00:00:00 2001 From: Revinand Date: Wed, 18 Nov 2026 19:18:04 +0100 Subject: [PATCH 07/14] feat(x402): publish Bazaar discovery metadata --- docs/configuration.md | 24 ++ docs/contracts.md | 10 + docs/protocols/x402.md | 55 ++- docs/security.md | 14 +- package-lock.json | 76 ++++ package.json | 1 + src/config/schema/normalize.ts | 36 ++ src/config/schema/raw.ts | 2 + src/config/schema/types.ts | 6 + src/core/execution/schema-example.ts | 89 ++++ src/core/execution/validation.ts | 49 +++ src/gateway/payment-providers.ts | 1 + src/payments/x402/payload.ts | 26 +- src/payments/x402/provider/bazaar.ts | 199 +++++++++ src/payments/x402/provider/requirement.ts | 42 +- src/payments/x402/provider/settle.ts | 7 +- src/payments/x402/provider/types.ts | 10 + src/payments/x402/provider/verify.ts | 5 +- src/protocols/a2a/agent-card.ts | 48 +-- src/protocols/mcp/tool-mapping.ts | 35 +- tests/integration/x402-bazaar.test.ts | 250 ++++++++++++ tests/unit/config/schema.test.ts | 92 +++++ tests/unit/core/execution/validation.test.ts | 90 +++- .../payments-x402/bazaar-challenge.test.ts | 384 ++++++++++++++++++ tests/unit/payments-x402/bazaar.test.ts | 310 ++++++++++++++ 25 files changed, 1761 insertions(+), 100 deletions(-) create mode 100644 src/core/execution/schema-example.ts create mode 100644 src/payments/x402/provider/bazaar.ts create mode 100644 tests/integration/x402-bazaar.test.ts create mode 100644 tests/unit/payments-x402/bazaar-challenge.test.ts create mode 100644 tests/unit/payments-x402/bazaar.test.ts diff --git a/docs/configuration.md b/docs/configuration.md index af9ea12..f47637a 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -667,6 +667,30 @@ that echo another surface's URL are also rejected. Both cases return `invalid_payment_requirements` without settlement; the buyer can request and pay a new challenge. See [x402](protocols/x402.md#the-resource-url). +### Bazaar metadata + +Experimental and disabled by default. `bazaar.enabled: true` adds Bazaar +discovery metadata to x402 challenges on HTTP and MCP for resources whose +`payments` include `x402`. Enabling it requires `publicResourceUrl: true`; +otherwise config loading fails with `CONFIG_INVALID`. + +```yaml +payments: + x402: + publicResourceUrl: true + bazaar: + enabled: true +``` + +During config loading, omissions from HTTP/MCP metadata produce warnings with +the resource id, affected surfaces and reason. Omitting metadata leaves payment +behavior unchanged. +[x402](protocols/x402.md#bazaar-discovery-metadata) lists the rules. + +Choose a facilitator that accepts Bazaar metadata. When a challenge carries +it, verify and settle forward that metadata. On HTTP, a Bazaar validation +rejection can cause repeated 402 challenges. + ### `payments.mpp` MPP accepts the `USDC` currency label on the local chain `eip155:31337`, Base diff --git a/docs/contracts.md b/docs/contracts.md index 6f132bf..3101bf5 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -477,6 +477,16 @@ persistence must not fail the commerce flow. `GatewayConfig.payments.x402.resourceUrls`. MPP's internal x402 provider does not receive this map. - Without the option, challenges are unchanged. +- 2.8.0: experimental `X402ProviderOptions.resourceBazaar` maps resource ids + and request surfaces (`http` or `mcp`) to each challenge's `extensions.bazaar` + value. + - With `payments.x402.bazaar.enabled: true`, config normalization fills + `GatewayConfig.payments.x402.resourceBazaar` with metadata that passes + the omission rules. MPP's internal x402 provider does not receive it. + - For a challenge carrying Bazaar metadata, verify and settle send its + `resource` and `extensions.bazaar` to the facilitator, replacing those + fields from the proof. + - Without the option, challenges and facilitator bodies are unchanged. ### Authorization and AP2 diff --git a/docs/protocols/x402.md b/docs/protocols/x402.md index 345e8c9..6815d20 100644 --- a/docs/protocols/x402.md +++ b/docs/protocols/x402.md @@ -66,10 +66,12 @@ sent. An absent `extra.paymentFlow` means `authorization`. A proof's `resource.u must equal the challenge's when present. A mismatch is `invalid_payment_requirements`, refused before the facilitator is called. `maxTimeoutSeconds` and `extra` keys added by the client are not compared. The facilitator receives the payload -without `resource` and `extensions`, after the gateway has checked the URL -in any echoed `resource` against the challenge. Verification and settlement -do not use echoed [quotes](#erc-8409-signed-quotes), and a Permit2 -gas-sponsoring extension would activate unsupported SDK facilitator behavior. +without the proof's `resource` and `extensions`, after the gateway has checked +the URL in any echoed `resource` against the challenge. A challenge with +[Bazaar metadata](#bazaar-discovery-metadata) supplies the forwarded discovery +fields. Verification and settlement do not use echoed +[quotes](#erc-8409-signed-quotes), and a Permit2 gas-sponsoring extension would +activate unsupported SDK facilitator behavior. With [several options](../configuration.md#several-options), the comparison above selects the proof's offer; zero or multiple matches yield @@ -138,6 +140,51 @@ proofs before calling the facilitator, so neither reaches settlement: The buyer can request and pay a new challenge. These checks provide no security boundary: `resource.url` is unsigned, and a client may omit it. +## Bazaar discovery metadata + +Experimental and disabled by default. With +[`bazaar.enabled`](../configuration.md#bazaar-metadata), x402 challenges on HTTP +and MCP carry `extensions.bazaar` metadata for a facilitator's catalog. +Other surfaces carry no Bazaar metadata. A resource whose first enabled rail +is MPP receives an MPP challenge. + +| Surface | `info.input` | `info.output` | +| ------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | +| HTTP | `{ type: 'http', method: 'POST', bodyType: 'json', body: }` | `{ type: 'json' }`, with an `example` only when both schema and value pass local checks | +| MCP | `{ type: 'mcp', toolName: , description, inputSchema, example }` | none | + +`schema` describes `info` using JSON Schema 2020-12; the HTTP form puts the +resource's input schema at `body`. The MCP `inputSchema` matches the one +`tools/list` returns before adding `_payment` and `_authorization`. Each +required property's example uses its first `examples` entry, then its `default` +or first `enum` value, otherwise a value for its type. + +The builder does not copy backend URLs or headers. Descriptions, schemas and +example values are public metadata; credentials embedded in them are not +redacted. + +The gateway validates input before pricing. On HTTP, an example that fails the +input schema returns 400 instead of a payment challenge. To keep discovery +probes usable, config loading omits metadata and warns when: + +- its description (or name when no description is set) exceeds the gateway's + limit of 500 UTF-16 code units; +- its input schema uses a keyword the gateway does not enforce. Enforced are + `type`, `properties`, `required`, `additionalProperties`, `enum` and a + single-schema `items`, each where the node's type admits it, plus the + annotations `title`, `description`, `examples`, `default`, `$comment`, + `deprecated`, `readOnly` and `writeOnly`; +- the example fails the input schema or the backend request shape; +- a surface's extension exceeds 4096 bytes; only that surface is omitted. + +If adding Bazaar would push the base64 `PAYMENT-REQUIRED` value over 8192 bytes, +the HTTP challenge omits it. A `warn` log names the resource once per provider +instance. Omitting metadata leaves payment behavior unchanged. + +On verify and settle, the facilitator receives the challenge's `resource` and +`extensions.bazaar`, replacing the proof's values. No other extension is +forwarded. + ## Payment identifier Experimental and disabled by default. A resource with diff --git a/docs/security.md b/docs/security.md index 419363b..ed6efbe 100644 --- a/docs/security.md +++ b/docs/security.md @@ -333,8 +333,14 @@ real funds. | amount differs from the price in either direction | `invalid_exact_evm_payload_authorization_value_mismatch` before settlement | `tests/e2e/payment/x402-settlement.e2e.test.ts` | | **an x402 proof whose `accepted` differs from the offer, or whose `resource.url` differs from the challenge's** | `invalid_payment_requirements` before the facilitator is called | `tests/unit/payments-x402/provider-remote-facilitator.test.ts` | | **multi-offer x402 proof whose `accepted` matches zero or multiple offers** | `invalid_payment_requirements`; no offer is selected and the facilitator is not called | `tests/unit/payments-x402/provider-remote-facilitator.test.ts` | -| **an x402 proof under `publicResourceUrl`, whose offers share one `resource.url`** | offer selection still uses `accepted`, as with `resource://`; the URL form does not change the replay key | `tests/unit/payments-x402/public-resource-url.test.ts` | -| **an x402 proof echoing a challenge issued before `publicResourceUrl` changed, or another surface's challenge** | `invalid_payment_requirements` before calling the facilitator; no settlement, including for an A2A task awaiting payment across a restart | `tests/unit/payments-x402/public-resource-url.test.ts`, `tests/integration/x402-public-url.test.ts`, `tests/integration/a2a-x402-extension.test.ts` | +| **an x402 proof under `publicResourceUrl`, whose offers share one `resource.url`** | offer selection still uses `accepted`, as with `resource://`; the URL form does not change the replay key | `tests/unit/payments-x402/public-resource-url.test.ts` | +| **an x402 proof echoing a challenge issued before `publicResourceUrl` changed, or another surface's challenge** | `invalid_payment_requirements` before calling the facilitator; no settlement, including for an A2A task awaiting payment across a restart | `tests/unit/payments-x402/public-resource-url.test.ts`, `tests/integration/x402-public-url.test.ts`, `tests/integration/a2a-x402-extension.test.ts` | +| **a buyer echoing altered Bazaar metadata or `resource` fields to poison a facilitator's catalog** | replaces the proof's values with the issued challenge's `resource` and `extensions.bazaar` before forwarding | `tests/unit/payments-x402/bazaar-challenge.test.ts`, `tests/integration/x402-bazaar.test.ts` | +| **a proof's `payment-identifier`, ERC-8409 quote or gas-sponsoring extension, under Bazaar** | none of the proof's extensions are forwarded; the facilitator receives only the challenge's `extensions.bazaar` | `tests/unit/payments-x402/bazaar-challenge.test.ts` | +| **Bazaar metadata echoed from another surface, with several offers** | offer selection still uses `accepted`; the facilitator receives the challenge's own metadata | `tests/unit/payments-x402/bazaar-challenge.test.ts` | +| **Bazaar metadata exposing a backend URL, header, credential, reserved field or unexposed surface** | backend connection settings are not copied; resource ids, descriptions, schemas and generated examples are public metadata. Schema and example contents are not redacted. Bazaar adds no `_payment` or `_authorization` carriers; unexposed surfaces receive no metadata | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/config/schema.test.ts` | +| **a Bazaar extension large enough to break the `PAYMENT-REQUIRED` header, and payment with it** | config loading omits extensions over 4096 bytes and warns; an HTTP challenge omits Bazaar if it would push the encoded header value over 8192 bytes. Payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/payments-x402/bazaar-challenge.test.ts` | +| **a generated Bazaar example the gateway would refuse, silently dropping the listing** | config loading omits the resource's metadata and warns with its id, affected surfaces and reason; payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/config/schema.test.ts`, `tests/integration/x402-bazaar.test.ts` | | **an AP2 mandate approved for one x402 offer, presented with a proof for another** | selected destination, network or asset fails mandate binding; no settlement | `tests/unit/core/execution/pipeline-authorization.test.ts` | | **an EIP-3009 authorization signed for one EVM chain, presented as another chain's offer** | `invalid_exact_evm_signature`: signature fails against the other chain's EIP-712 domain; neither chain's balances change | `tests/e2e/payment/x402-multichain.e2e.test.ts` | | **the same payer, token address and nonce on two EVM chains** | both settle: the replay key includes the chain id | same | @@ -343,9 +349,9 @@ real funds. | **a Permit2 payment from a buyer without a Permit2 allowance** | 412 with `error: permit2_allowance_required` in a fresh `PAYMENT-REQUIRED`; `permit2_simulation_failed` and 402 on a chain without Multicall3; balances unchanged | `tests/e2e/payment/x402-permit2.e2e.test.ts` | | **a proof of the other transfer method, or one carrying both an EIP-3009 and a Permit2 authorization** | `unsupported_scheme` before the facilitator is called, which would settle the Permit2 one | `tests/unit/payments-x402/provider-remote-facilitator.test.ts`, `tests/unit/payments-x402/provider.test.ts` | | **an EIP-3009 authorization whose value, time bounds or nonce are not in canonical form** | `invalid_payload` before the facilitator is called: amounts and times must be decimal, the nonce 32 bytes of hex | `tests/unit/payments-x402/provider.test.ts` | -| **a gas-sponsoring extension in a Permit2 payload** | not forwarded: the facilitator receives no `extensions` | `tests/unit/payments-x402/provider-remote-facilitator.test.ts` | +| **a gas-sponsoring extension in a Permit2 payload** | not forwarded: the facilitator receives none of the proof's `extensions` | `tests/unit/payments-x402/provider-remote-facilitator.test.ts` | | **an ERC-8409 quote altered after signing, or signed by another key** | a buyer that verifies the signature against the published issuer rejects it | `tests/unit/payments-x402/quote.test.ts`, `tests/integration/x402-quotes.test.ts` | -| **an altered ERC-8409 quote echoed in a payment** | ignored: verification and settlement use the offer and payer authorization; the facilitator receives no `extensions` | `tests/integration/x402-quotes.test.ts` | +| **an altered ERC-8409 quote echoed in a payment** | ignored: verification and settlement use the offer and payer authorization; the facilitator receives none of the proof's `extensions` | `tests/integration/x402-quotes.test.ts` | | **a leaked quote signing key** | its holder can sign quotes as the merchant. Keep the key unfunded. Rotation changes the published issuer after a restart; `doctor` detects a gateway still using the old key | `tests/integration/x402-quotes.test.ts`, `tests/unit/cli/doctor.test.ts` | | **unpaid requests that vary the input to force quote signing** | each cache miss requires a signature per EVM offer; repeated input reuses a cached quote while a full payment window remains | `tests/unit/payments-x402/quote.test.ts` | | **a quote signing key that controls an EVM `payTo`, or a well-known Anvil key outside the local chain** | `CONFIG_INVALID` during provider construction; the message omits the key | `tests/unit/payments-x402/quote.test.ts` | diff --git a/package-lock.json b/package-lock.json index ca0c2e1..c00b7d2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -45,6 +45,7 @@ "@vitest/coverage-v8": "4.1.12", "@x402/core": "2.30.0", "@x402/evm": "2.30.0", + "@x402/extensions": "2.30.0", "@x402/mcp": "2.30.0", "@x402/near": "2.30.0", "@x402/svm": "2.30.0", @@ -2211,6 +2212,39 @@ "node": ">=20" } }, + "node_modules/@signinwithethereum/siwe": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@signinwithethereum/siwe/-/siwe-4.2.1.tgz", + "integrity": "sha512-CQEQhCIgN9blil1YpaGR+wvGPdsBVK6zed5DBu03s1IdbSO3kA/n7Zp+SAkZGiHy3HY6OJm1Su0/Bd33vKK6nQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@signinwithethereum/siwe-parser": "^4.2.1" + }, + "peerDependencies": { + "ethers": "^5.7.0 || ^6.13.0", + "viem": "^2.7.0" + }, + "peerDependenciesMeta": { + "ethers": { + "optional": true + }, + "viem": { + "optional": true + } + } + }, + "node_modules/@signinwithethereum/siwe-parser": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@signinwithethereum/siwe-parser/-/siwe-parser-4.2.1.tgz", + "integrity": "sha512-GAdwNiBaRpUMTiFfPrbQ3e/RBhPbEhRRN1sZmDMLgLEZuKqKwO7V0ksVzCerE9l8HFKTNw5R/q3kPDCWJRz4zA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@noble/hashes": "^1.7.0", + "apg-js": "^4.4.0" + } + }, "node_modules/@solana-program/compute-budget": { "version": "0.18.1", "resolved": "https://registry.npmjs.org/@solana-program/compute-budget/-/compute-budget-0.18.1.tgz", @@ -3703,6 +3737,34 @@ "zod": "^4.6.6" } }, + "node_modules/@x402/extensions": { + "version": "2.30.0", + "resolved": "https://registry.npmjs.org/@x402/extensions/-/extensions-2.30.0.tgz", + "integrity": "sha512-Lqu8hYkFAIhzarWa8V1272tyolFAW7WjHrxQ7we5P0fEZ8oMXOq1hna2X0FXQetZoOFzBDwSWBBMsrqE8ZzvcQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@noble/curves": "^1.9.0", + "@scure/base": "^1.2.6", + "@signinwithethereum/siwe": "^4.1.0", + "@x402/core": "~2.30.0", + "ajv": "^8.18.0", + "jose": "^5.9.6", + "tweetnacl": "^1.0.3", + "viem": "^2.48.11", + "zod": "^4.6.6" + } + }, + "node_modules/@x402/extensions/node_modules/jose": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz", + "integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/@x402/mcp": { "version": "2.30.0", "resolved": "https://registry.npmjs.org/@x402/mcp/-/mcp-2.30.0.tgz", @@ -3859,6 +3921,13 @@ "dev": true, "license": "MIT" }, + "node_modules/apg-js": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/apg-js/-/apg-js-4.4.0.tgz", + "integrity": "sha512-fefmXFknJmtgtNEXfPwZKYkMFX4Fyeyz+fNF6JWp87biGOPslJbCBVU158zvKRZfHBKnJDy8CMM40oLFGkXT8Q==", + "dev": true, + "license": "BSD-2-Clause" + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -7129,6 +7198,13 @@ "fsevents": "~2.3.3" } }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", + "dev": true, + "license": "Unlicense" + }, "node_modules/type-fest": { "version": "5.9.0", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.9.0.tgz", diff --git a/package.json b/package.json index 966f8bf..c303aba 100644 --- a/package.json +++ b/package.json @@ -190,6 +190,7 @@ "@vitest/coverage-v8": "4.1.12", "@x402/core": "2.30.0", "@x402/evm": "2.30.0", + "@x402/extensions": "2.30.0", "@x402/mcp": "2.30.0", "@x402/near": "2.30.0", "@x402/svm": "2.30.0", diff --git a/src/config/schema/normalize.ts b/src/config/schema/normalize.ts index 966381d..28d0dda 100644 --- a/src/config/schema/normalize.ts +++ b/src/config/schema/normalize.ts @@ -1,6 +1,7 @@ // The business-rule pass: coerces leaves and checks cross-references across sections import type { CommerceResource } from '../../core'; import { CommerceError } from '../../core'; +import { bazaarMetadata } from '../../payments/x402/provider/bazaar'; import { joinUrl } from '../../protocols/http'; import { normalizeAcp, validateAcpCheckoutMapping } from './acp'; import { normalizeAp2, validateLegacyStoresIsolated } from './ap2'; @@ -66,6 +67,11 @@ export function normalize(raw: RawConfig): GatewayConfig { publicUrl !== undefined && toBoolean(publicUrl, 'payments.x402.publicResourceUrl') ? publicResourceUrls(raw.merchant.publicBaseUrl, protocols, resources) : undefined; + const bazaarRaw = raw.payments.x402?.bazaar; + const resourceBazaar = + bazaarRaw !== undefined && toBoolean(bazaarRaw.enabled, 'payments.x402.bazaar.enabled') + ? bazaarExtensions(resourceUrls, resources) + : undefined; const x402WithFlows = x402 !== undefined ? { @@ -73,6 +79,7 @@ export function normalize(raw: RawConfig): GatewayConfig { ...flowOverrides('x402'), ...(Object.keys(mimeTypes).length > 0 ? { resourceMimeTypes: mimeTypes } : {}), ...(resourceUrls !== undefined ? { resourceUrls } : {}), + ...(resourceBazaar !== undefined ? { resourceBazaar } : {}), } : x402; const mppWithFlows = mpp !== undefined ? { ...mpp, ...flowOverrides('mpp') } : mpp; @@ -118,6 +125,35 @@ export function normalize(raw: RawConfig): GatewayConfig { }; } +// Build Bazaar metadata for public URLs and report omitted resources or surfaces +// during config loading. Omitting metadata leaves payment behavior unchanged. +function bazaarExtensions( + resourceUrls: Record>> | undefined, + resources: readonly CommerceResource[], +): NonNullable['resourceBazaar'] { + if (resourceUrls === undefined) { + throw new CommerceError( + 'CONFIG_INVALID', + 'payments.x402.bazaar.enabled requires payments.x402.publicResourceUrl: true', + { details: { path: 'payments.x402.bazaar.enabled' } }, + ); + } + return Object.fromEntries( + resources.flatMap((resource) => { + const urls = resourceUrls[resource.id]; + if (urls === undefined) return []; + const surfaces = (['http', 'mcp'] as const).filter((surface) => urls[surface] !== undefined); + const { extensions, omitted } = bazaarMetadata(resource, surfaces); + for (const { surfaces: left, reason } of omitted) { + console.warn( + `[agent-commerce] resource "${resource.id}" gets no Bazaar metadata on ${left.join(' and ')}: ${reason}. Payment is unaffected.`, + ); + } + return Object.keys(extensions).length > 0 ? [[resource.id, extensions]] : []; + }), + ); +} + // Build URLs for the surfaces exposing each x402 resource, using the public // base URL so indexers can request endpoints instead of `resource://` identifiers function publicResourceUrls( diff --git a/src/config/schema/raw.ts b/src/config/schema/raw.ts index ee3e812..fd06f9c 100644 --- a/src/config/schema/raw.ts +++ b/src/config/schema/raw.ts @@ -355,6 +355,8 @@ const X402Schema = z allowUnauthenticatedFacilitator: BooleanOrString.optional(), // Experimental: use the configured public endpoint in x402 challenges publicResourceUrl: BooleanOrString.optional(), + // Experimental Bazaar discovery metadata; enabling it requires publicResourceUrl + bazaar: z.object({ enabled: BooleanOrString }).strict().optional(), // Experimental ERC-8409 quotes; signing a quote transfers no funds quote: z .object({ diff --git a/src/config/schema/types.ts b/src/config/schema/types.ts index f32208a..1b3e374 100644 --- a/src/config/schema/types.ts +++ b/src/config/schema/types.ts @@ -100,6 +100,12 @@ export interface GatewayConfig { * route or protocol mount under `merchant.publicBaseUrl`. */ readonly resourceUrls?: NonNullable; + /** + * Experimental. With `bazaar.enabled: true`, config normalization fills + * this map for HTTP and MCP entries in `resourceUrls` that pass the + * metadata checks + */ + readonly resourceBazaar?: NonNullable; readonly facilitator: X402FacilitatorConfig; readonly allowMainnet?: boolean; readonly allowUnauthenticatedFacilitator?: boolean; diff --git a/src/core/execution/schema-example.ts b/src/core/execution/schema-example.ts new file mode 100644 index 0000000..3ad08e7 --- /dev/null +++ b/src/core/execution/schema-example.ts @@ -0,0 +1,89 @@ +// Example values and the published object form of a resource's input schema, +// shared by the A2A Agent Card, MCP tools and x402 Bazaar metadata +import type { JsonSchema } from '../domain/common'; +import { AUTHORIZATION_INPUT_FIELD, PAYMENT_INPUT_FIELD } from '../domain/wire'; +import { isRecord } from '../is-record'; + +/** + * Build a sample using the first schema example, then its default or first + * enum value, otherwise a value for the declared type. Generated objects use + * required properties only; explicit examples, defaults and enum values are + * returned unchanged. Other constraints may require different input. + */ +export function exampleValue(schema: unknown, name: string): unknown { + if (!isRecord(schema)) return `<${name}>`; + const examples = schema['examples']; + if (Array.isArray(examples) && examples.length > 0) return examples[0]; + if (schema['default'] !== undefined) return schema['default']; + const allowed = schema['enum']; + if (Array.isArray(allowed) && allowed.length > 0) return allowed[0]; + const declared = schema['type']; + const type: unknown = Array.isArray(declared) ? declared[0] : declared; + switch (type) { + case 'object': + return exampleObject(schema); + case 'array': + return schema['items'] !== undefined ? [exampleValue(schema['items'], name)] : []; + case 'number': + case 'integer': + return 0; + case 'boolean': + return false; + case 'null': + return null; + default: + return `<${name}>`; + } +} + +/** An object holding an example of each required property, without the reserved fields */ +export function exampleObject(schema: Record): Record { + const properties = isRecord(schema['properties']) ? schema['properties'] : {}; + const required = Array.isArray(schema['required']) ? schema['required'] : []; + const example: Record = {}; + for (const key of required) { + // The reserved fields carry proofs, which no example can hold + if (typeof key !== 'string' || key === PAYMENT_INPUT_FIELD || key === AUTHORIZATION_INPUT_FIELD) + continue; + example[key] = exampleValue(properties[key], key); + } + return example; +} + +/** An object input schema before adding reserved payment and authorization fields */ +export interface ObjectInputSchema { + readonly [keyword: string]: unknown; + readonly type: 'object'; + readonly properties: Readonly>>; + readonly required?: readonly string[]; +} + +/** + * Normalize a resource input schema for MCP, before adding reserved fields. + * Preserve other keywords while setting `type` to `'object'`, retaining only + * object-valued `properties` and string entries in `required`. + */ +export function objectInputSchema(schema: JsonSchema | undefined): ObjectInputSchema { + const base = isRecord(schema) ? schema : {}; + const properties = isRecord(base['properties']) + ? Object.fromEntries( + Object.entries(base['properties']).filter( + (entry): entry is [string, Record] => isRecord(entry[1]), + ), + ) + : {}; + const required = Array.isArray(base['required']) + ? base['required'].filter((v): v is string => typeof v === 'string') + : []; + const extra = Object.fromEntries( + Object.entries(base).filter( + ([key]) => key !== 'type' && key !== 'properties' && key !== 'required', + ), + ); + return { + ...extra, + type: 'object', + properties, + ...(required.length > 0 ? { required } : {}), + }; +} diff --git a/src/core/execution/validation.ts b/src/core/execution/validation.ts index 0185ac8..097e35d 100644 --- a/src/core/execution/validation.ts +++ b/src/core/execution/validation.ts @@ -43,6 +43,55 @@ const SUPPORTED_TYPES = new Set([ 'null', ]); +// The keywords `validateNode` enforces, plus annotations that constrain nothing +const FULLY_ENFORCED_KEYWORDS = new Set([ + 'type', + 'properties', + 'required', + 'additionalProperties', + 'enum', + 'items', + 'title', + 'description', + 'examples', + 'default', + '$comment', + 'deprecated', + 'readOnly', + 'writeOnly', +]); + +/** + * Check whether a schema and its subschemas stay within this validator's + * supported keyword subset. Bazaar also validates the generated example + * before publishing it. + */ +export function isFullyEnforced(schema: unknown): boolean { + if (!isRecord(schema)) return false; + if (!Object.keys(schema).every((key) => FULLY_ENFORCED_KEYWORDS.has(key))) return false; + const { type, properties, required, additionalProperties, items } = schema; + const types = Array.isArray(type) ? type : type === undefined ? [] : [type]; + if (Array.isArray(type) && type.length === 0) return false; + if (!types.every((t) => typeof t === 'string' && SUPPORTED_TYPES.has(t))) return false; + if (properties !== undefined) { + if (!isRecord(properties) || !Object.values(properties).every(isFullyEnforced)) return false; + } + if (required !== undefined) { + if (!Array.isArray(required) || !required.every((name) => typeof name === 'string')) + return false; + } + if (schema['enum'] !== undefined && !Array.isArray(schema['enum'])) return false; + // `validateNode` applies these two only when the node's type admits them + if (additionalProperties !== undefined) { + if (!isObjectSchemaNode(schema)) return false; + if (typeof additionalProperties !== 'boolean' && !isFullyEnforced(additionalProperties)) + return false; + } + if (items === undefined) return true; + // A tuple `items` (an array of schemas) is not enforced + return types.includes('array') && isFullyEnforced(items); +} + /** Wrap a resource `inputSchema` in a reusable validator function */ export function compileJsonSchema(schema: JsonSchema | undefined): Validator { return (input: unknown): ValidationResult => { diff --git a/src/gateway/payment-providers.ts b/src/gateway/payment-providers.ts index 222e786..90df703 100644 --- a/src/gateway/payment-providers.ts +++ b/src/gateway/payment-providers.ts @@ -60,6 +60,7 @@ export async function createConfiguredPaymentProviders( ? { resourceMimeTypes: x402.resourceMimeTypes } : {}), ...(x402.resourceUrls !== undefined ? { resourceUrls: x402.resourceUrls } : {}), + ...(x402.resourceBazaar !== undefined ? { resourceBazaar: x402.resourceBazaar } : {}), facilitator: x402.facilitator, ...(x402.allowMainnet !== undefined ? { allowMainnet: x402.allowMainnet } : {}), ...(x402.allowUnauthenticatedFacilitator !== undefined diff --git a/src/payments/x402/payload.ts b/src/payments/x402/payload.ts index eda7373..72e4ff9 100644 --- a/src/payments/x402/payload.ts +++ b/src/payments/x402/payload.ts @@ -7,10 +7,11 @@ * which throws. */ import { PaymentPayloadV2Schema } from '@x402/core/schemas'; -import type { PaymentPayload } from '@x402/core/types'; +import type { PaymentPayload, PaymentRequired } from '@x402/core/types'; import type { ExactEIP3009Payload, ExactPermit2Payload } from '@x402/evm'; import { isRecord } from '../../core/is-record'; import { isEvmAddress } from './addresses'; +import { BAZAAR_EXTENSION_KEY } from './provider/bazaar'; export function decodePaymentSubmission(payloadBase64: string): PaymentPayload | undefined { const json = decodeJson(payloadBase64); @@ -28,18 +29,25 @@ export function declaredX402Version(payloadBase64: string): unknown { } /** - * The payload as sent to a facilitator. `resource` is optional in v2 and - * verify() has already matched it against the offer; hosted facilitators have - * settled payloads without it, and none has been shown to accept this - * gateway's `resource://` URL. `extensions` is dropped because quote echoes - * are not used to verify payment, and a gas-sponsoring extension in a Permit2 - * payload would activate unsupported SDK facilitator behavior. + * Build the facilitator payload, dropping the buyer's `resource` and + * `extensions`. `resource` is optional in v2; verify() checks its URL against + * the challenge when present. Quote echoes are not used to verify payment, + * and a gas-sponsoring extension in a Permit2 payload would activate + * unsupported SDK facilitator behavior. + * + * When the `issued` challenge carries Bazaar metadata, attach its `resource` + * and `extensions.bazaar` for cataloging. Use the issued values so a buyer's + * altered echo cannot replace the listing metadata. */ export function forFacilitator( payload: T, -): Omit { + issued: PaymentRequired | undefined, +): Omit & Pick, 'resource' | 'extensions'> { const { resource: _resource, extensions: _extensions, ...rest } = payload; - return rest; + const bazaar = issued?.extensions?.[BAZAAR_EXTENSION_KEY]; + return issued !== undefined && bazaar !== undefined + ? { ...rest, resource: issued.resource, extensions: { [BAZAAR_EXTENSION_KEY]: bazaar } } + : rest; } function decodeJson(payloadBase64: string): unknown { diff --git a/src/payments/x402/provider/bazaar.ts b/src/payments/x402/provider/bazaar.ts new file mode 100644 index 0000000..cd293db --- /dev/null +++ b/src/payments/x402/provider/bazaar.ts @@ -0,0 +1,199 @@ +// Build HTTP and MCP Bazaar metadata without loading an SDK. Config loading +// can use these helpers to report omitted resources and surfaces before startup. +import type { CommerceResource } from '../../../core'; +import { validateBackendRequestShape } from '../../../core/execution/backend-request'; +import { + exampleObject, + exampleValue, + objectInputSchema, +} from '../../../core/execution/schema-example'; +import { compileJsonSchema, isFullyEnforced } from '../../../core/execution/validation'; + +/** The extension's key in a challenge's `extensions` */ +export const BAZAAR_EXTENSION_KEY = 'bazaar'; + +/** Maximum serialized extension size accepted by `bazaarMetadata`, in bytes */ +export const MAX_BAZAAR_EXTENSION_BYTES = 4096; + +/** Maximum description length accepted by `bazaarMetadata` */ +export const MAX_BAZAAR_DESCRIPTION_LENGTH = 500; + +/** Experimental. One surface's `extensions.bazaar` value */ +export interface BazaarExtension { + readonly info: Readonly>; + readonly schema: Readonly>; +} + +/** Supported Bazaar metadata surfaces */ +export type BazaarSurface = 'http' | 'mcp'; + +export interface BazaarMetadata { + readonly extensions: Partial>; + /** Omission reasons and affected surfaces, for config-load warnings */ + readonly omitted: readonly { + readonly surfaces: readonly BazaarSurface[]; + readonly reason: string; + }[]; +} + +const JSON_SCHEMA_2020_12 = 'https://json-schema.org/draft/2020-12/schema'; + +/** + * Build Bazaar extensions for the requested surfaces. Metadata is omitted + * unless the generated example passes the input schema and backend request + * shape checks, and the schema uses the validator's supported subset. This + * avoids publishing examples that fail gateway validation before pricing. + */ +export function bazaarMetadata( + resource: CommerceResource, + surfaces: readonly BazaarSurface[], +): BazaarMetadata { + if (surfaces.length === 0) return { extensions: {}, omitted: [] }; + const all = (reason: string): BazaarMetadata => ({ + extensions: {}, + omitted: [{ surfaces, reason }], + }); + + const description = resource.description ?? resource.name; + if (description.length > MAX_BAZAAR_DESCRIPTION_LENGTH) { + return all( + `its description is longer than ${MAX_BAZAAR_DESCRIPTION_LENGTH} characters, which the CDP facilitator refuses`, + ); + } + const schema = resource.inputSchema ?? {}; + if (!isFullyEnforced(schema)) { + return all( + 'its input schema uses a keyword the gateway does not enforce, which leaves the example unproven', + ); + } + const example = exampleObject(schema); + if (!compileJsonSchema(schema)(example).valid || !shapeAccepts(resource, example)) { + return all('the example generated from its input schema fails the gateway input checks'); + } + + const built = { + http: () => httpForm(resource, schema, example), + mcp: () => mcpForm(resource, description, example), + }; + const extensions: Partial> = {}; + const oversized: BazaarSurface[] = []; + for (const surface of surfaces) { + const extension = built[surface](); + if (Buffer.byteLength(JSON.stringify(extension)) > MAX_BAZAAR_EXTENSION_BYTES) { + oversized.push(surface); + } else { + extensions[surface] = extension; + } + } + return { + extensions, + omitted: + oversized.length > 0 + ? [ + { + surfaces: oversized, + reason: `the extension exceeds ${MAX_BAZAAR_EXTENSION_BYTES} bytes`, + }, + ] + : [], + }; +} + +function shapeAccepts(resource: CommerceResource, example: unknown): boolean { + try { + validateBackendRequestShape(resource.handler, example, { + requestId: 'bazaar-example', + resourceId: resource.id, + }); + return true; + } catch { + return false; + } +} + +// The invoke route takes the input as a JSON body +function httpForm( + resource: CommerceResource, + schema: Record, + example: Record, +): BazaarExtension { + const output = outputExample(resource.outputSchema); + return { + info: { + input: { type: 'http', method: 'POST', bodyType: 'json', body: example }, + output: { type: 'json', ...(output !== undefined ? { example: output } : {}) }, + }, + schema: { + $schema: JSON_SCHEMA_2020_12, + type: 'object', + properties: { + input: { + type: 'object', + properties: { + type: { type: 'string', const: 'http' }, + method: { type: 'string', enum: ['POST'] }, + bodyType: { type: 'string', enum: ['json'] }, + body: schema, + }, + required: ['type', 'method', 'bodyType', 'body'], + additionalProperties: false, + }, + output: { + type: 'object', + properties: { + type: { type: 'string' }, + ...(output !== undefined ? { example: resource.outputSchema } : {}), + }, + required: ['type'], + }, + }, + required: ['input'], + }, + }; +} + +// A tool is keyed by its endpoint URL and `toolName`, the resource id +function mcpForm( + resource: CommerceResource, + description: string, + example: Record, +): BazaarExtension { + return { + info: { + input: { + type: 'mcp', + toolName: resource.id, + description, + inputSchema: objectInputSchema(resource.inputSchema), + example, + }, + }, + schema: { + $schema: JSON_SCHEMA_2020_12, + type: 'object', + properties: { + input: { + type: 'object', + properties: { + type: { type: 'string', const: 'mcp' }, + toolName: { type: 'string' }, + description: { type: 'string' }, + inputSchema: { type: 'object' }, + example: { type: 'object' }, + }, + required: ['type', 'toolName', 'inputSchema'], + additionalProperties: false, + }, + }, + required: ['input'], + }, + }; +} + +// Publish an output example only when its schema uses the supported subset +// and local validation accepts it; runtime delivery does not validate output schemas +function outputExample(schema: Record | undefined): unknown { + if (schema === undefined || !isFullyEnforced(schema)) return undefined; + const example = exampleValue(schema, 'output'); + return compileJsonSchema(schema)(example).valid ? example : undefined; +} diff --git a/src/payments/x402/provider/requirement.ts b/src/payments/x402/provider/requirement.ts index 80ccbe1..b7c5676 100644 --- a/src/payments/x402/provider/requirement.ts +++ b/src/payments/x402/provider/requirement.ts @@ -10,10 +10,15 @@ import { parseCanonicalAmount } from '../amount'; import type { X402Network } from '../networks'; import { decodePaymentSubmission } from '../payload'; import { X402_DEFAULT_PAYMENT_FLOW } from '../payment-flow'; +import { BAZAAR_EXTENSION_KEY } from './bazaar'; import { DEFAULT_MIME_TYPE, X402_PROTOCOL_VERSION, X402_VERSION } from './constants'; import { paymentIdentifierExtensions } from './payment-id'; import type { ProviderContext, SvmOffer } from './types'; +// Budget for the encoded PAYMENT-REQUIRED value when adding Bazaar metadata; +// large headers may be rejected by proxies +const MAX_HTTP_CHALLENGE_HEADER_BYTES = 8192; + // Requirement metadata naming the offer `selectRequirement` chose, by index export const SELECTED_OFFER_KEY = 'x402.offer'; @@ -61,7 +66,9 @@ export function createRequirementBuilders( readonly createRequirement: (context: PaymentContext) => Promise; readonly selectRequirement: (context: PaymentVerificationContext) => Promise; } { - const { options, offersFor, clock, ids, maxTimeoutSeconds } = ctx; + const { options, offersFor, clock, ids, maxTimeoutSeconds, logger } = ctx; + // Resources whose HTTP challenge has already been logged as too large + const oversizedLogged = new Set(); async function createRequirement(context: PaymentContext): Promise { const offers = offersFor(context.resource.id); @@ -111,6 +118,10 @@ export function createRequirementBuilders( const identifier = paymentIdentifierExtensions(context.resource); const extensions = identifier === undefined ? quoteExtensions : { ...quoteExtensions, ...identifier }; + const bazaar = + context.protocol === 'http' || context.protocol === 'mcp' + ? options.resourceBazaar?.[context.resource.id]?.[context.protocol] + : undefined; // Build the v2 challenge document. HTTP base64-encodes it into // `PAYMENT-REQUIRED`; MCP passes the document through directly. @@ -141,6 +152,10 @@ export function createRequirementBuilders( accepts, ...(extensions !== undefined ? { extensions } : {}), }; + const challenge = + bazaar === undefined + ? envelope + : withBazaar(envelope, bazaar, context.protocol === 'http', context.resource.id); const expiresAt = new Date(clock.now().getTime() + maxTimeoutSeconds * 1000).toISOString(); @@ -160,7 +175,7 @@ export function createRequirementBuilders( provider: 'x402', version: X402_PROTOCOL_VERSION, accepts: accepts as unknown as Record[], - envelope: envelope as unknown as Record, + envelope: challenge as unknown as Record, }, metadata: { [SETTLE_AFTER_BACKEND_METADATA_KEY]: paymentFlow === 'authorization', @@ -171,6 +186,29 @@ export function createRequirementBuilders( }; } + // Omit Bazaar from oversized HTTP challenges to reduce proxy header failures + function withBazaar( + envelope: PaymentRequired, + bazaar: unknown, + http: boolean, + resourceId: string, + ): PaymentRequired { + const extended = { + ...envelope, + extensions: { ...envelope.extensions, [BAZAAR_EXTENSION_KEY]: bazaar }, + }; + const encoded = 4 * Math.ceil(Buffer.byteLength(JSON.stringify(extended)) / 3); + if (!http || encoded <= MAX_HTTP_CHALLENGE_HEADER_BYTES) return extended; + if (!oversizedLogged.has(resourceId)) { + oversizedLogged.add(resourceId); + logger.warn( + { resourceId, bytes: encoded }, + 'x402: Bazaar metadata left out of an HTTP challenge whose PAYMENT-REQUIRED header would exceed 8 KiB', + ); + } + return envelope; + } + /** * Selects the unique offer matching `accepted`, leaving zero or multiple * matches unchanged for `verify()` to reject. Selection identifies the diff --git a/src/payments/x402/provider/settle.ts b/src/payments/x402/provider/settle.ts index ed474c0..e0224bb 100644 --- a/src/payments/x402/provider/settle.ts +++ b/src/payments/x402/provider/settle.ts @@ -1,5 +1,5 @@ // Settles a verified proof and classifies the facilitator's answer -import type { PaymentRequirements, SettleResponse } from '@x402/core/types'; +import type { PaymentRequired, PaymentRequirements, SettleResponse } from '@x402/core/types'; import type { PaymentResult, PaymentSettlementContext } from '../../../core'; import { CommerceError } from '../../../core'; import { redactedErrorText } from '../../../core/errors'; @@ -73,7 +73,10 @@ export function createSettle( const scope = offer.binding.open(); let sdkResult: SettleResponse; try { - sdkResult = await scope.settle(forFacilitator(payload), requirements); + sdkResult = await scope.settle( + forFacilitator(payload, requirement.challenge.envelope as PaymentRequired | undefined), + requirements, + ); } catch (err) { if (isProviderUnavailableError(err) || scope.transportFailed()) { throw new CommerceError( diff --git a/src/payments/x402/provider/types.ts b/src/payments/x402/provider/types.ts index 1bf52aa..eeccf26 100644 --- a/src/payments/x402/provider/types.ts +++ b/src/payments/x402/provider/types.ts @@ -7,6 +7,7 @@ import type { X402FacilitatorConfig } from '../guardrails'; import type { CustomNetworks, DeploymentMode, X402Network } from '../networks'; import type { X402AssetTransferMethod } from '../options'; import type { X402PaymentFlow } from '../payment-flow'; +import type { BazaarExtension, BazaarSurface } from './bazaar'; import type { QuoteIssuer } from './quote'; /** A single offer and the settings every offer shares */ @@ -25,6 +26,15 @@ export interface X402ProviderOptions extends X402OfferOptions { * keyed by resource id. Defaults to `application/json`. */ readonly resourceMimeTypes?: Readonly>; + /** + * Experimental. Maps resource ids and HTTP/MCP surfaces to the challenge's + * `extensions.bazaar` value. Omitted from HTTP challenges when it would make + * the encoded `PAYMENT-REQUIRED` value exceed 8 KiB. When present, verify and + * settle send it and the challenge's `resource` to the facilitator. + */ + readonly resourceBazaar?: Readonly< + Record>>> + >; /** * Experimental. Maps resource ids and request surfaces to the public * `resource.url` used in their challenges. Requests without a surface, diff --git a/src/payments/x402/provider/verify.ts b/src/payments/x402/provider/verify.ts index 174c779..b0e4689 100644 --- a/src/payments/x402/provider/verify.ts +++ b/src/payments/x402/provider/verify.ts @@ -170,7 +170,10 @@ export function createVerify( const scope = offer.binding.open(); let sdkResult: VerifyResponse; try { - sdkResult = await scope.verify(forFacilitator(payload), requirements); + sdkResult = await scope.verify( + forFacilitator(payload, requirement.challenge.envelope as PaymentRequired | undefined), + requirements, + ); } catch (err) { // A throw means no verdict was obtained, so it is never held against the // buyer. Only an unclassified one is logged, as it may be an SDK fault. diff --git a/src/protocols/a2a/agent-card.ts b/src/protocols/a2a/agent-card.ts index 0399378..3c12917 100644 --- a/src/protocols/a2a/agent-card.ts +++ b/src/protocols/a2a/agent-card.ts @@ -6,8 +6,8 @@ * shape through fields it does define: a sentence in the agent description, * which also says where the schemas are published, and one example per skill. */ -import { AUTHORIZATION_INPUT_FIELD, type CommerceResource, PAYMENT_INPUT_FIELD } from '../../core'; -import { isRecord } from '../../core/is-record'; +import { type CommerceResource, PAYMENT_INPUT_FIELD } from '../../core'; +import { exampleObject } from '../../core/execution/schema-example'; import { joinUrl } from '../http'; import { A2A_JSON_MEDIA_TYPE, A2A_PROTOCOL_BINDING, A2A_PROTOCOL_VERSION } from './constants'; import { A2A_CALL_SHAPE } from './message-mapping'; @@ -49,50 +49,6 @@ function skillDescription(resource: CommerceResource): string { return base; } -/** - * Build a sample from schema examples, defaults, enum values or the declared - * type. Objects include required properties only. Other constraints may need - * different input. - */ -function exampleValue(schema: unknown, name: string): unknown { - if (!isRecord(schema)) return `<${name}>`; - const examples = schema['examples']; - if (Array.isArray(examples) && examples.length > 0) return examples[0]; - if (schema['default'] !== undefined) return schema['default']; - const allowed = schema['enum']; - if (Array.isArray(allowed) && allowed.length > 0) return allowed[0]; - const declared = schema['type']; - const type: unknown = Array.isArray(declared) ? declared[0] : declared; - switch (type) { - case 'object': - return exampleObject(schema); - case 'array': - return schema['items'] !== undefined ? [exampleValue(schema['items'], name)] : []; - case 'number': - case 'integer': - return 0; - case 'boolean': - return false; - case 'null': - return null; - default: - return `<${name}>`; - } -} - -function exampleObject(schema: Record): Record { - const properties = isRecord(schema['properties']) ? schema['properties'] : {}; - const required = Array.isArray(schema['required']) ? schema['required'] : []; - const example: Record = {}; - for (const key of required) { - // The reserved fields carry proofs, which no example can hold - if (typeof key !== 'string' || key === PAYMENT_INPUT_FIELD || key === AUTHORIZATION_INPUT_FIELD) - continue; - example[key] = exampleValue(properties[key], key); - } - return example; -} - /** The `data` value of a data part that calls the skill, as JSON */ function skillExample(resource: CommerceResource): string { return JSON.stringify({ diff --git a/src/protocols/mcp/tool-mapping.ts b/src/protocols/mcp/tool-mapping.ts index 46b6e4b..96c43ab 100644 --- a/src/protocols/mcp/tool-mapping.ts +++ b/src/protocols/mcp/tool-mapping.ts @@ -12,7 +12,7 @@ import { PAYMENT_INPUT_FIELD, type PaymentMethodName, } from '../../core'; -import { isRecord } from '../../core/is-record'; +import { objectInputSchema } from '../../core/execution/schema-example'; import { MPP_MCP_CREDENTIAL_META_KEY } from '../../payments/mpp/transport'; import { X402_MCP_PAYMENT_META_KEY } from '../../payments/x402/transport'; import { MCP_TOOL_NAME_PATTERN } from './constants'; @@ -109,17 +109,8 @@ export function buildToolDescription(resource: CommerceResource): string { * would otherwise refuse to send them. */ export function buildInputSchema(resource: CommerceResource): Tool['inputSchema'] { - const base = resource.inputSchema; - const baseIsObject = isRecord(base); - - // Keep object-valued property schemas from the resource's config JSON - const basePropertyEntries: readonly [string, JSONObject][] = - baseIsObject && isRecord(base.properties) - ? Object.entries(base.properties).filter((entry): entry is [string, JSONObject] => - isRecord(entry[1]), - ) - : []; - const properties: Record = Object.fromEntries(basePropertyEntries); + const schema = objectInputSchema(resource.inputSchema); + const properties = { ...schema.properties } as Record; // Both overwrite a resource-declared property of the same name; config // rejects that collision at load time @@ -143,23 +134,5 @@ export function buildInputSchema(resource: CommerceResource): Tool['inputSchema' }; } - const required = - baseIsObject && Array.isArray(base.required) - ? base.required.filter((v): v is string => typeof v === 'string') - : []; - - const extra = baseIsObject - ? Object.fromEntries( - Object.entries(base).filter( - ([key]) => key !== 'type' && key !== 'properties' && key !== 'required', - ), - ) - : {}; - - return { - ...extra, - type: 'object', - properties, - ...(required.length > 0 ? { required } : {}), - }; + return { ...schema, properties } as Tool['inputSchema']; } diff --git a/tests/integration/x402-bazaar.test.ts b/tests/integration/x402-bazaar.test.ts new file mode 100644 index 0000000..50818b4 --- /dev/null +++ b/tests/integration/x402-bazaar.test.ts @@ -0,0 +1,250 @@ +/** + * Exercise `payments.x402.bazaar` through config normalization, the gateway, + * configured providers, MCP, SDK buyer clients and upstream validation. + * Mock the facilitator HTTP client and inspect its forwarded payloads. + */ +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'; +import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; +import { x402Client } from '@x402/core/client'; +import type { PaymentPayload, PaymentRequired } from '@x402/core/types'; +import { registerExactEvmScheme } from '@x402/evm/exact/client'; +import { validateDiscoveryExtension } from '@x402/extensions/bazaar'; +import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { type GatewayConfig, parseConfig } from '../../src/config'; +import { NOOP_LOGGER } from '../../src/core'; +import { createGateway, type GatewayInstance } from '../../src/gateway'; +import { createConfiguredPaymentProviders } from '../../src/gateway/payment-providers'; +import { createMcpAdapter } from '../../src/protocols/mcp'; +import { createFakeStore } from '../unit/gateway/helpers'; + +const facilitator = vi.hoisted(() => ({ verify: vi.fn(), settle: vi.fn() })); +vi.mock('@x402/core/http', () => ({ + FacilitatorResponseError: class extends Error {}, + HTTPFacilitatorClient: class { + verify(...args: unknown[]) { + return facilitator.verify(...args); + } + settle(...args: unknown[]) { + return facilitator.settle(...args); + } + }, +})); + +const BASE = 'https://shop.example'; +const NETWORK = 'eip155:84532'; +const buyer = privateKeyToAccount(generatePrivateKey()); +const backendResource = (expose: string[], payments: string[], input: Record) => ({ + name: 'Forecast', + description: 'Forecast for a city', + input, + backend: { type: 'http', method: 'POST', url: 'http://backend.local/forecast' }, + pricing: { type: 'fixed', amount: '0.01', currency: 'USDC' }, + expose, + payments, +}); +const CITY = { + type: 'object', + properties: { city: { type: 'string' }, days: { type: 'integer', default: 3 } }, + required: ['city', 'days'], + additionalProperties: false, +}; + +let config: GatewayConfig; +let gateway: GatewayInstance; +let url = ''; +let mcp: Client | undefined; +let warn: ReturnType; + +beforeEach(async () => { + facilitator.verify.mockReset().mockResolvedValue({ isValid: true, payer: buyer.address }); + facilitator.settle.mockReset().mockResolvedValue({ + success: true, + transaction: `0x${'ab'.repeat(32)}`, + network: NETWORK, + payer: buyer.address, + }); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + config = parseConfig( + { + version: 1, + merchant: { id: 'shop', name: 'Shop', publicBaseUrl: BASE }, + server: { port: 0, host: '127.0.0.1' }, + storage: { receipts: { driver: 'sqlite', path: ':memory:' } }, + protocols: { http: { enabled: true }, mcp: { enabled: true, mountPath: '/mcp' } }, + resources: { + forecast: backendResource(['http', 'mcp'], ['x402'], CITY), + // `pattern` is not enforced, so the resource is omitted from Bazaar metadata + strict: backendResource(['http'], ['x402'], { + type: 'object', + properties: { city: { type: 'string', pattern: '^[A-Z]' } }, + required: ['city'], + additionalProperties: false, + }), + mpp_first: backendResource(['http'], ['mpp', 'x402'], CITY), + }, + payments: { + x402: { + enabled: true, + network: NETWORK, + rpcUrl: 'http://127.0.0.1:19321', // never contacted + payTo: '0x1111111111111111111111111111111111111111', + maxTimeoutSeconds: 120, + facilitator: { mode: 'remote', url: 'https://facilitator.example' }, + publicResourceUrl: true, + bazaar: { enabled: true }, + }, + mpp: { + enabled: true, + rpcUrl: 'http://127.0.0.1:19321', + asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', + assetName: 'USDC', + assetVersion: '2', + recipient: '0x1111111111111111111111111111111111111111', + realm: 'shop.example', + challengeSecret: 'mpp-challenge-secret-'.padEnd(32, 'x'), + facilitator: { mode: 'remote', url: 'https://facilitator.example' }, + }, + }, + }, + {}, + ); + gateway = await createGateway({ + config, + store: createFakeStore(), + paymentProviders: await createConfiguredPaymentProviders(config.payments, NOOP_LOGGER), + protocolAdapters: [createMcpAdapter()], + logger: NOOP_LOGGER, + backend: { + async call() { + return { status: 200, body: { forecast: 'sun' }, headers: {}, durationMs: 1 }; + }, + }, + }); + ({ url } = await gateway.listen()); +}); + +afterEach(async () => { + warn.mockRestore(); + await mcp?.close().catch(() => {}); + mcp = undefined; + await gateway.close().catch(() => {}); +}); + +const issued = (id: string, surface: 'http' | 'mcp') => + config.payments.x402?.resourceBazaar?.[id]?.[surface]; + +function payments(): x402Client { + const client = new x402Client(); + registerExactEvmScheme(client, { signer: buyer, networks: [NETWORK] }); + return client; +} + +function invoke(id: string, body: unknown, proof?: PaymentPayload) { + return gateway.server.inject({ + method: 'POST', + url: `/api/resources/${id}/invoke`, + headers: { + host: new URL(BASE).host, + 'content-type': 'application/json', + ...(proof !== undefined + ? { 'payment-signature': Buffer.from(JSON.stringify(proof)).toString('base64') } + : {}), + }, + payload: body as Record, + }); +} + +function challengeOf(res: Awaited>): PaymentRequired { + expect(res.statusCode).toBe(402); + return JSON.parse( + Buffer.from(String(res.headers['payment-required']), 'base64').toString('utf8'), + ) as PaymentRequired; +} + +describe('x402 Bazaar metadata through the gateway', () => { + it('answers the HTTP example, posted as a facilitator probes, with 402 and the metadata', async () => { + const http = issued('forecast', 'http'); + const probe = (http?.info['input'] as { body?: unknown } | undefined)?.body; + expect(probe).toEqual({ city: '', days: 3 }); + + const required = challengeOf(await invoke('forecast', probe)); + + expect(required.resource.url).toBe(`${BASE}/api/resources/forecast/invoke`); + expect(required.extensions).toEqual({ bazaar: http }); + expect(validateDiscoveryExtension(required.extensions?.['bazaar'] as never)).toEqual({ + valid: true, + }); + }); + + it('answers the MCP example, sent as tool arguments, with a payment-required result and the metadata', async () => { + const tool = issued('forecast', 'mcp')?.info['input'] as { + toolName: string; + example: Record; + }; + mcp = new Client({ name: 'bazaar-probe', version: '0.0.0-test' }); + await mcp.connect(new StreamableHTTPClientTransport(new URL(`${url}/mcp`)) as Transport); + + const result = (await mcp.callTool({ + name: tool.toolName, + arguments: tool.example, + })) as CallToolResult; + + expect(result.isError).toBe(true); + expect(result.structuredContent).toMatchObject({ + code: 'PAYMENT_REQUIRED', + resource: { url: `${BASE}/mcp` }, + extensions: { bazaar: issued('forecast', 'mcp') }, + }); + }); + + it('sends the facilitator the issued metadata when the buyer echoes altered metadata', async () => { + const proof = await payments().createPaymentPayload( + challengeOf(await invoke('forecast', { city: 'Oslo', days: 1 })), + ); + const altered = { ...proof, extensions: { bazaar: { info: { input: { type: 'http' } } } } }; + + const paid = await invoke('forecast', { city: 'Oslo', days: 1 }, altered); + + expect(paid.statusCode).toBe(200); + for (const mock of [facilitator.verify, facilitator.settle]) { + expect(mock).toHaveBeenCalledTimes(1); + expect(mock.mock.calls[0]?.[0]).toMatchObject({ + resource: { url: `${BASE}/api/resources/forecast/invoke` }, + extensions: { bazaar: issued('forecast', 'http') }, + }); + } + }); + + it('warns about a resource left out at load, and still sells it', async () => { + expect(issued('strict', 'http')).toBeUndefined(); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('resource "strict" gets no Bazaar metadata on http'), + ); + const required = challengeOf(await invoke('strict', { city: 'Oslo' })); + expect(required).not.toHaveProperty('extensions'); + + const paid = await invoke( + 'strict', + { city: 'Oslo' }, + await payments().createPaymentPayload(required), + ); + + expect(paid.statusCode).toBe(200); + expect(Object.keys(facilitator.verify.mock.calls[0]?.[0] as object)).toEqual([ + 'x402Version', + 'accepted', + 'payload', + ]); + }); + + it('answers a resource whose first rail is MPP with an MPP challenge and no metadata', async () => { + const res = await invoke('mpp_first', { city: 'Oslo', days: 1 }); + + expect(res.statusCode).toBe(402); + expect(res.headers['www-authenticate']).toMatch(/^Payment /); + expect(res.headers['payment-required']).toBeUndefined(); + }); +}); diff --git a/tests/unit/config/schema.test.ts b/tests/unit/config/schema.test.ts index 963363b..0f08762 100644 --- a/tests/unit/config/schema.test.ts +++ b/tests/unit/config/schema.test.ts @@ -2628,6 +2628,98 @@ describe('payments.x402.publicResourceUrl', () => { }); }); +describe('payments.x402.bazaar', () => { + // `null` leaves publicResourceUrl out + function withBazaar(enabled: unknown, publicResourceUrl: boolean | null = true) { + const raw = validRawConfig(); + const x402 = (raw['payments'] as { x402: Record }).x402; + x402['bazaar'] = { enabled }; + if (publicResourceUrl !== null) x402['publicResourceUrl'] = publicResourceUrl; + return raw; + } + function marketReport(raw: Record): Record { + return (raw['resources'] as { market_report: Record }).market_report; + } + let warn: ReturnType; + beforeEach(() => { + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + afterEach(() => { + warn.mockRestore(); + }); + + it.each([ + ['absent', validRawConfig()], + ['false', withBazaar(false)], + ])('gives the x402 rail no Bazaar metadata when %s', (_label, raw) => { + expect(parseConfig(raw, {}).payments.x402?.resourceBazaar).toBeUndefined(); + }); + + it.each([true, 'true'])( + 'builds the HTTP and MCP forms for each paid resource with %j', + (enabled) => { + const bazaar = parseConfig(withBazaar(enabled), {}).payments.x402?.resourceBazaar; + // weather_basic is free; market_report is paid and exposed on both + expect(Object.keys(bazaar ?? {})).toEqual(['market_report']); + expect(bazaar?.['market_report']?.http?.info).toEqual({ + input: { type: 'http', method: 'POST', bodyType: 'json', body: {} }, + output: { type: 'json' }, + }); + expect(bazaar?.['market_report']?.mcp?.info['input']).toMatchObject({ + type: 'mcp', + toolName: 'market_report', + }); + expect(warn).not.toHaveBeenCalled(); + }, + ); + + it.each([ + ['publicResourceUrl is absent', null], + ['publicResourceUrl is false', false], + ])('refuses the key when %s', (_label, publicResourceUrl) => { + expectConfigInvalid( + () => parseConfig(withBazaar(true, publicResourceUrl), {}), + 'payments.x402.bazaar.enabled', + 'payments.x402.bazaar.enabled requires payments.x402.publicResourceUrl: true', + ); + }); + + it('builds no form for a surface the resource is not exposed on', () => { + const raw = withBazaar(true); + marketReport(raw)['expose'] = ['http']; + const bazaar = parseConfig(raw, {}).payments.x402?.resourceBazaar; + expect(Object.keys(bazaar?.['market_report'] ?? {})).toEqual(['http']); + }); + + it('refuses a key it does not know', () => { + const raw = validRawConfig(); + (raw['payments'] as { x402: Record }).x402['bazaar'] = { + enabled: true, + routeTemplate: '/x', + }; + expect(() => parseConfig(raw, {})).toThrow(/routeTemplate/); + }); + + it('leaves out a resource it cannot prove valid, names it in a warning, and keeps its payment', () => { + const raw = withBazaar(true); + marketReport(raw)['input'] = { + type: 'object', + properties: { ticker: { type: 'string', pattern: '^[A-Z]+$' } }, + required: ['ticker'], + additionalProperties: false, + }; + const config = parseConfig(raw, {}); + + expect(config.payments.x402?.resourceBazaar).toEqual({}); + expect(config.resources.find((r) => r.id === 'market_report')?.paymentMethods).toEqual([ + 'x402', + ]); + expect(warn).toHaveBeenCalledWith( + '[agent-commerce] resource "market_report" gets no Bazaar metadata on http and mcp: its input schema uses a keyword the gateway does not enforce, which leaves the example unproven. Payment is unaffected.', + ); + }); +}); + describe('resource idempotency', () => { function withIdempotency(id: string, idempotency: unknown): Record { const raw = validRawConfig(); diff --git a/tests/unit/core/execution/validation.test.ts b/tests/unit/core/execution/validation.test.ts index 45681d5..095baf6 100644 --- a/tests/unit/core/execution/validation.test.ts +++ b/tests/unit/core/execution/validation.test.ts @@ -1,5 +1,6 @@ +import Ajv2020 from 'ajv/dist/2020.js'; import { describe, expect, it } from 'vitest'; -import { compileJsonSchema } from '../../../../src/core/execution/validation'; +import { compileJsonSchema, isFullyEnforced } from '../../../../src/core/execution/validation'; describe('compileJsonSchema', () => { it('accepts anything when no schema is given', () => { @@ -296,3 +297,90 @@ describe('compileJsonSchema', () => { expect(validate({ city: 'Berlin', evil: true }).valid).toBe(false); // still closed }); }); + +describe('isFullyEnforced', () => { + const ENFORCED: readonly [string, Record][] = [ + ['an empty schema', {}], + [ + 'a closed object with every supported keyword and the annotations', + { + type: 'object', + title: 'Query', + description: 'A query', + $comment: 'internal', + properties: { + city: { type: 'string', examples: ['Oslo'], deprecated: false }, + days: { type: ['integer', 'null'], default: 3, readOnly: true }, + units: { enum: ['metric', 'imperial'], writeOnly: false }, + tags: { type: 'array', items: { type: 'string' } }, + extra: { type: 'object', additionalProperties: { type: 'number' } }, + }, + required: ['city'], + additionalProperties: false, + }, + ], + [ + 'properties without a type', + { properties: { a: { type: 'boolean' } }, additionalProperties: false }, + ], + ]; + + it.each(ENFORCED)('is true for %s', (_label, schema) => { + expect(isFullyEnforced(schema)).toBe(true); + }); + + it.each([ + ['a non-object schema', true], + ['an unenforced keyword', { type: 'string', minLength: 1 }], + ['a keyword the config warning list lacks', { type: 'object', minProperties: 1 }], + [ + 'an unenforced keyword in a property', + { properties: { a: { type: 'string', format: 'email' } } }, + ], + [ + 'an unenforced keyword in additionalProperties', + { type: 'object', additionalProperties: { const: 1 } }, + ], + ['an unenforced keyword in items', { type: 'array', items: { type: 'string', pattern: 'x' } }], + ['a boolean property schema', { properties: { a: true } }], + ['a tuple items', { type: 'array', items: [{ type: 'string' }] }], + ['items without an array type', { items: { type: 'string' } }], + ['additionalProperties without an object node', { additionalProperties: false }], + ['an unknown type', { type: 'date' }], + ['an empty type list', { type: [] }], + ['a non-string type', { type: [1] }], + ['a non-array enum', { enum: 'a' }], + ['non-string required entries', { type: 'object', required: [1] }], + ['a non-object properties', { properties: [] }], + ['$ref', { $ref: '#/$defs/a' }], + ['$schema', { $schema: 'https://json-schema.org/draft/2020-12/schema' }], + ])('is false for %s', (_label, schema) => { + expect(isFullyEnforced(schema)).toBe(false); + }); + + // Compare gateway and Ajv 2020-12 verdicts for these schemas and sample values + const ajv = new Ajv2020({ strict: false }); + const VALUES: readonly unknown[] = [ + {}, + { city: 'Oslo' }, + { city: 'Oslo', days: null, units: 'metric', tags: ['a'], extra: { n: 1 } }, + { city: 'Oslo', units: 'kelvin' }, + { city: 1 }, + { city: 'Oslo', tags: [1] }, + { city: 'Oslo', extra: { n: 'x' } }, + { city: 'Oslo', unknown: true }, + { a: true }, + { a: 'yes' }, + [], + 'text', + null, + ]; + + it.each(ENFORCED)('agrees with Ajv 2020-12 on every sample value for %s', (_label, schema) => { + const gateway = compileJsonSchema(schema); + const reference = ajv.compile(schema); + expect(VALUES.map((value) => gateway(value).valid)).toEqual( + VALUES.map((value) => reference(value)), + ); + }); +}); diff --git a/tests/unit/payments-x402/bazaar-challenge.test.ts b/tests/unit/payments-x402/bazaar-challenge.test.ts new file mode 100644 index 0000000..bc33481 --- /dev/null +++ b/tests/unit/payments-x402/bazaar-challenge.test.ts @@ -0,0 +1,384 @@ +// Bazaar challenge metadata, HTTP header limits and facilitator payloads +import { x402Client } from '@x402/core/client'; +import type { PaymentPayload, PaymentRequired } from '@x402/core/types'; +import { registerExactEvmScheme } from '@x402/evm/exact/client'; +import { privateKeyToAccount } from 'viem/accounts'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { + type CommerceResource, + NOOP_LOGGER, + type PaymentContext, + type PaymentRequirement, + type ProtocolName, +} from '../../../src/core'; +import { + createX402PaymentProvider, + type X402ProviderOptions, +} from '../../../src/payments/x402/provider'; + +const facilitator = vi.hoisted(() => ({ verify: vi.fn(), settle: vi.fn() })); + +// Mock the facilitator HTTP client to inspect the payment payloads passed to it +vi.mock('@x402/core/http', () => ({ + FacilitatorResponseError: class extends Error {}, + HTTPFacilitatorClient: class { + verify(...args: unknown[]) { + return facilitator.verify(...args); + } + settle(...args: unknown[]) { + return facilitator.settle(...args); + } + }, +})); + +const PAY_TO = '0x1111111111111111111111111111111111111111'; +const BUYER = privateKeyToAccount( + '0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a', +); +const BASE = 'https://shop.example'; +const URLS = { + report: { http: `${BASE}/api/resources/report/invoke`, mcp: `${BASE}/mcp`, a2a: `${BASE}/a2a` }, +}; +const bazaarFor = (surface: string, pad = '') => ({ + info: { input: { type: surface, pad } }, + schema: { type: 'object' }, +}); +const BAZAAR = { report: { http: bazaarFor('http'), mcp: bazaarFor('mcp') } }; + +const RESOURCE: CommerceResource = { + id: 'report', + name: 'Report', + handler: { type: 'http', method: 'GET', url: 'http://merchant.invalid/report' }, + pricing: { type: 'fixed', amount: '0.01', currency: 'USD' }, + exposedVia: ['http', 'mcp', 'a2a'], + paymentMethods: ['x402'], +}; + +function provider(overrides: Partial = {}) { + return createX402PaymentProvider({ + network: 'eip155:31337', + rpcUrl: 'http://127.0.0.1:19321', // never contacted + asset: '0x5FbDB2315678afecb367f032d93F642f64180aa3', + assetName: 'MockUSDC', + assetVersion: '2', + assetDecimals: 6, + payTo: PAY_TO, + facilitator: { mode: 'remote', url: 'https://facilitator.example', auth: { type: 'none' } }, + resourceUrls: URLS, + ...overrides, + }); +} + +function context(protocol?: ProtocolName): PaymentContext { + return { + requestId: 'req-1', + resource: RESOURCE, + amount: '0.01', + currency: 'USD', + requestedAt: '2026-11-18T00:00:00.000Z', + ...(protocol !== undefined ? { protocol } : {}), + }; +} + +const envelopeOf = (requirement: PaymentRequirement) => + requirement.challenge.envelope as unknown as PaymentRequired; + +async function sdkProof(requirement: PaymentRequirement): Promise { + const client = new x402Client(); + registerExactEvmScheme(client, { signer: BUYER, networks: ['eip155:31337'] }); + client.setSpendControls(false); // the test token is not in the SDK's list + return client.createPaymentPayload(envelopeOf(requirement)); +} + +// Verify and settle a proof, returning the payloads passed to the facilitator client +async function pay( + by: ReturnType, + requirement: PaymentRequirement, + proof: PaymentPayload, +) { + const ctx = { + requestId: 'req-1', + resource: RESOURCE, + requirement, + submission: { + method: 'x402' as const, + payload: Buffer.from(JSON.stringify(proof)).toString('base64'), + }, + }; + const verification = await by.verify(ctx); + expect(verification.status).toBe('verified'); + const settlement = await by.settle({ ...ctx, verification }); + expect(settlement.status).toBe('settled'); + return { + verified: facilitator.verify.mock.calls[0]?.[0] as Record, + settled: facilitator.settle.mock.calls[0]?.[0] as Record, + }; +} + +beforeEach(() => { + facilitator.verify.mockReset().mockResolvedValue({ isValid: true, payer: BUYER.address }); + facilitator.settle.mockReset().mockResolvedValue({ + success: true, + transaction: `0x${'ab'.repeat(32)}`, + network: 'eip155:31337', + payer: BUYER.address, + }); +}); + +describe('Bazaar metadata in the challenge', () => { + it.each(['http', 'mcp'] as const)('carries the %s extension on that surface', async (surface) => { + const envelope = envelopeOf( + await provider({ resourceBazaar: BAZAAR }).createRequirement(context(surface)), + ); + expect(envelope.extensions).toEqual({ bazaar: BAZAAR.report[surface] }); + }); + + it.each([ + ['A2A', 'a2a'], + ['ACP', 'acp'], + ['no surface', undefined], + ] as const)('carries none on %s', async (_label, surface) => { + const envelope = envelopeOf( + await provider({ resourceBazaar: BAZAAR }).createRequirement(context(surface)), + ); + expect(envelope).not.toHaveProperty('extensions'); + }); + + // Measure the HTTP envelope overhead before padding it to the target size + async function sizedHttpChallenge(encodedBytes: number) { + const base = envelopeOf( + await provider({ resourceBazaar: { report: { http: bazaarFor('http') } } }).createRequirement( + context('http'), + ), + ); + const jsonBytes = Buffer.byteLength(JSON.stringify(base)); + const pad = 'p'.repeat((encodedBytes / 4) * 3 - jsonBytes); + return { pad, extension: bazaarFor('http', pad) }; + } + + it('keeps it when the encoded HTTP challenge is exactly 8192 bytes', async () => { + const { pad, extension } = await sizedHttpChallenge(8192); + const envelope = envelopeOf( + await provider({ resourceBazaar: { report: { http: extension } } }).createRequirement( + context('http'), + ), + ); + expect(Buffer.from(JSON.stringify(envelope)).toString('base64')).toHaveLength(8192); + expect(envelope.extensions).toEqual({ bazaar: bazaarFor('http', pad) }); + }); + + it('leaves it out of an HTTP challenge one byte over, and logs that once per resource', async () => { + const { extension } = await sizedHttpChallenge(8192); + const big = { + ...extension, + info: { input: { ...extension.info.input, pad: `${extension.info.input.pad}p` } }, + }; + // Exceed the HTTP budget even with MCP's shorter URL + const bigger = bazaarFor('mcp', 'p'.repeat(extension.info.input.pad.length + 1024)); + const warn = vi.fn(); + const by = provider({ + resourceBazaar: { report: { http: big, mcp: bigger } }, + logger: { ...NOOP_LOGGER, warn }, + }); + + const first = envelopeOf(await by.createRequirement(context('http'))); + const second = envelopeOf(await by.createRequirement(context('http'))); + // MCP carries the challenge in the result body, not a header + const mcp = envelopeOf(await by.createRequirement(context('mcp'))); + + expect(first).not.toHaveProperty('extensions'); + expect(second).not.toHaveProperty('extensions'); + expect(mcp.extensions).toEqual({ bazaar: bigger }); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith( + { resourceId: 'report', bytes: 8196 }, + 'x402: Bazaar metadata left out of an HTTP challenge whose PAYMENT-REQUIRED header would exceed 8 KiB', + ); + }); +}); + +describe('Bazaar metadata and AP2', () => { + // The requirement fields an AP2 mandate binds (src/authorization/ap2/profile.ts) + const bound = ({ + resourceId, + provider, + amount, + currency, + destination, + network, + asset, + }: PaymentRequirement) => ({ + resourceId, + provider, + amount, + currency, + destination, + network, + asset, + }); + + it('leaves every field a mandate binds unchanged', async () => { + const on = await provider({ resourceBazaar: BAZAAR }).createRequirement(context('http')); + const off = await provider({ resourceUrls: {} }).createRequirement(context('http')); + expect(envelopeOf(on).extensions).toEqual({ bazaar: BAZAAR.report.http }); + expect(bound(on)).toEqual({ + resourceId: 'report', + provider: 'x402', + amount: '0.01', + currency: 'USD', + destination: PAY_TO, + network: 'eip155:31337', + asset: '0x5FbDB2315678afecb367f032d93F642f64180aa3', + }); + expect(bound(on)).toEqual(bound(off)); + }); +}); + +describe('Bazaar metadata and offer selection', () => { + it('selects the offer the proof pays, whatever metadata it echoes, and still forwards the issued metadata', async () => { + const OTHER_ASSET = '0x2222222222222222222222222222222222222222'; + const OTHER_PAY_TO = '0x3333333333333333333333333333333333333333'; + const offer = (asset: string, payTo: string) => ({ + network: 'eip155:31337', + rpcUrl: 'http://127.0.0.1:19321', // never contacted + asset, + assetName: 'MockUSDC', + assetVersion: '2', + assetDecimals: 6, + payTo, + }); + const by = createX402PaymentProvider({ + offers: [ + offer('0x5FbDB2315678afecb367f032d93F642f64180aa3', PAY_TO), + offer(OTHER_ASSET, OTHER_PAY_TO), + ], + facilitator: { mode: 'remote', url: 'https://facilitator.example', auth: { type: 'none' } }, + resourceUrls: URLS, + resourceBazaar: BAZAAR, + }); + const requirement = await by.createRequirement(context('http')); + const client = new x402Client((_version, accepts) => accepts[1] as never); + registerExactEvmScheme(client, { signer: BUYER, networks: ['eip155:31337'] }); + client.setSpendControls(false); // the test token is not in the SDK's list + const proof = await client.createPaymentPayload(envelopeOf(requirement)); + // The other surface's metadata, echoed as if it were this challenge's + const echoed = { ...proof, extensions: { bazaar: BAZAAR.report.mcp } }; + + const selected = await by.selectRequirement?.({ + requestId: 'req-1', + resource: RESOURCE, + requirement, + submission: { + method: 'x402', + payload: Buffer.from(JSON.stringify(echoed)).toString('base64'), + }, + }); + if (selected === undefined) return expect.unreachable('no selectRequirement'); + const { verified } = await pay(by, selected, echoed); + + expect({ destination: selected.destination, asset: selected.asset }).toEqual({ + destination: OTHER_PAY_TO, + asset: OTHER_ASSET, + }); + expect(verified['accepted']).toEqual(proof.accepted); + expect(verified['extensions']).toEqual({ bazaar: BAZAAR.report.http }); + }); +}); + +describe('Bazaar metadata on the way to the facilitator', () => { + it('sends only x402Version, accepted and payload when the challenge has none', async () => { + const by = provider(); + const requirement = await by.createRequirement(context('http')); + const { verified, settled } = await pay(by, requirement, await sdkProof(requirement)); + expect(Object.keys(verified)).toEqual(['x402Version', 'accepted', 'payload']); + expect(Object.keys(settled)).toEqual(['x402Version', 'accepted', 'payload']); + }); + + it('forwards Bazaar alone from a challenge that also declares payment-identifier', async () => { + const by = provider({ resourceBazaar: BAZAAR }); + const resource: CommerceResource = { + ...RESOURCE, + idempotency: { redelivery: { retentionHours: 24, required: false } }, + }; + const requirement = await by.createRequirement({ ...context('http'), resource }); + expect(Object.keys(envelopeOf(requirement).extensions ?? {})).toEqual([ + 'payment-identifier', + 'bazaar', + ]); + + const { verified, settled } = await pay(by, requirement, await sdkProof(requirement)); + + expect(verified['extensions']).toEqual({ bazaar: BAZAAR.report.http }); + expect(settled['extensions']).toEqual({ bazaar: BAZAAR.report.http }); + }); + + // Each echo is the SDK client's proof after the buyer changes its extensions + const ECHOES: readonly [string, (proof: PaymentPayload) => PaymentPayload][] = [ + ['the echo unchanged', (proof) => proof], + [ + 'altered Bazaar metadata', + (proof) => ({ + ...proof, + extensions: { bazaar: { info: { input: { type: 'http', body: { poisoned: true } } } } }, + }), + ], + [ + 'an altered description and added service metadata', + (proof) => ({ + ...proof, + resource: { + ...(proof.resource as PaymentRequired['resource']), + description: 'Free money', + serviceName: 'Hostile', + tags: ['spam'], + } as PaymentRequired['resource'], + }), + ], + [ + 'a payment-identifier extension', + (proof) => ({ + ...proof, + extensions: { + ...proof.extensions, + 'payment-identifier': { info: { id: 'pay_1234567890abcdef' } }, + }, + }), + ], + [ + 'an ERC-8409 quote extension', + (proof) => ({ + ...proof, + extensions: { ...proof.extensions, 'erc-8409': { quotes: [{ signature: '0x00' }] } }, + }), + ], + [ + 'a gas-sponsoring extension', + (proof) => ({ + ...proof, + extensions: { ...proof.extensions, eip2612GasSponsoring: { info: { signature: '0x00' } } }, + }), + ], + ]; + + it.each(ECHOES)( + 'forwards the issued resource and Bazaar metadata, given %s', + async (_label, edit) => { + const by = provider({ resourceBazaar: BAZAAR }); + const requirement = await by.createRequirement(context('http')); + const issued = envelopeOf(requirement); + const proof = await sdkProof(requirement); + + const { verified, settled } = await pay(by, requirement, edit(proof)); + + const expected = { + x402Version: 2, + accepted: proof.accepted, + payload: proof.payload, + resource: issued.resource, + extensions: { bazaar: BAZAAR.report.http }, + }; + expect(verified).toEqual(expected); + expect(settled).toEqual(expected); + }, + ); +}); diff --git a/tests/unit/payments-x402/bazaar.test.ts b/tests/unit/payments-x402/bazaar.test.ts new file mode 100644 index 0000000..cf4cfd5 --- /dev/null +++ b/tests/unit/payments-x402/bazaar.test.ts @@ -0,0 +1,310 @@ +// HTTP and MCP Bazaar metadata forms, upstream validation and omission rules +import type { PaymentPayload, PaymentRequirements } from '@x402/core/types'; +import { + extractDiscoveryInfo, + validateDiscoveryExtension, + validateDiscoveryExtensionSpec, +} from '@x402/extensions/bazaar'; +import { describe, expect, it } from 'vitest'; +import type { CommerceResource, JsonSchema } from '../../../src/core'; +import { + type BazaarExtension, + type BazaarSurface, + bazaarMetadata, +} from '../../../src/payments/x402/provider/bazaar'; +import { buildInputSchema } from '../../../src/protocols/mcp/tool-mapping'; + +const INPUT: JsonSchema = { + type: 'object', + properties: { + city: { type: 'string', description: 'City name' }, + days: { type: 'integer', default: 3 }, + units: { type: 'string', enum: ['metric', 'imperial'] }, + filters: { + type: 'object', + properties: { tags: { type: 'array', items: { type: 'string' } } }, + required: ['tags'], + additionalProperties: false, + }, + verbose: { type: 'boolean' }, + }, + required: ['city', 'days', 'units', 'filters'], + additionalProperties: false, +}; +const EXAMPLE = { city: '', days: 3, units: 'metric', filters: { tags: [''] } }; + +function resource(overrides: Partial = {}): CommerceResource { + return { + id: 'weather', + name: 'Weather', + description: 'Forecast for a city', + inputSchema: INPUT, + handler: { type: 'http', method: 'POST', url: 'http://backend.local/forecast' }, + pricing: { type: 'fixed', amount: '0.01', currency: 'USDC' }, + exposedVia: ['http', 'mcp'], + paymentMethods: ['x402'], + ...overrides, + }; +} + +const BOTH: readonly BazaarSurface[] = ['http', 'mcp']; + +function extensionOf(surface: BazaarSurface, of = resource()): BazaarExtension { + const extension = bazaarMetadata(of, [surface]).extensions[surface]; + if (extension === undefined) return expect.unreachable(`no ${surface} extension`); + return extension; +} + +// A forwarded payload, as a facilitator receives it with the metadata +function forwarded(url: string, extension: BazaarExtension): PaymentPayload { + return { + x402Version: 2, + resource: { url, description: 'Forecast for a city', mimeType: 'application/json' }, + accepted: {} as PaymentRequirements, + payload: {}, + extensions: { bazaar: extension }, + }; +} + +describe('Bazaar metadata forms', () => { + it('describes the invoke route as a POST of the example JSON body', () => { + expect(extensionOf('http').info).toEqual({ + input: { type: 'http', method: 'POST', bodyType: 'json', body: EXAMPLE }, + output: { type: 'json' }, + }); + }); + + it('describes the MCP tool by its id, schema and example', () => { + expect(extensionOf('mcp').info).toEqual({ + input: { + type: 'mcp', + toolName: 'weather', + description: 'Forecast for a city', + inputSchema: INPUT, + example: EXAMPLE, + }, + }); + }); + + it.each(BOTH)('passes upstream validation of the %s form', (surface) => { + const extension = extensionOf(surface); + expect(validateDiscoveryExtension(extension as never)).toEqual({ valid: true }); + expect(validateDiscoveryExtensionSpec(extension as never)).toEqual({ valid: true }); + }); + + it('is extracted by upstream as an HTTP listing keyed by the invoke URL', () => { + const url = 'https://shop.example/api/resources/weather/invoke'; + const extension = extensionOf('http'); + expect(extractDiscoveryInfo(forwarded(url, extension), {} as PaymentRequirements)).toEqual({ + resourceUrl: url, + description: 'Forecast for a city', + mimeType: 'application/json', + x402Version: 2, + discoveryInfo: extension.info, + extensions: { bazaar: extension }, + routeTemplate: undefined, + method: 'POST', + }); + }); + + it('is extracted by upstream as an MCP listing keyed by the mount URL and tool name', () => { + const url = 'https://shop.example/mcp'; + const extension = extensionOf('mcp'); + expect( + extractDiscoveryInfo(forwarded(url, extension), {} as PaymentRequirements), + ).toMatchObject({ resourceUrl: url, toolName: 'weather', discoveryInfo: extension.info }); + }); + + it('declares the same MCP input schema as tools/list, less the reserved fields', () => { + // No `type`: tools/list adds `type: 'object'`, which the declared schema must match + const { type: _, ...untyped } = INPUT; + const paid = resource({ inputSchema: untyped, authorization: { required: ['ap2'] } }); + const listed = buildInputSchema(paid) as { properties: Record }; + // Confirm that MCP added both reserved carrier fields + expect(Object.keys(listed.properties)).toEqual( + expect.arrayContaining(['_payment', '_authorization']), + ); + const { _payment, _authorization, ...properties } = listed.properties; + + expect(extensionOf('mcp', paid).info['input']).toMatchObject({ + inputSchema: { ...listed, properties }, + }); + }); + + it('keeps the backend URL, its headers and the reserved fields out of the metadata', () => { + const secret = resource({ + handler: { + type: 'http', + method: 'POST', + url: 'https://internal.backend.example/secret-path/forecast', + headers: { 'x-api-key': 'sk_live_backend_credential' }, + }, + authorization: { required: ['ap2'] }, + }); + const text = JSON.stringify(bazaarMetadata(secret, BOTH).extensions); + for (const leaked of [ + 'internal.backend', + 'secret-path', + 'x-api-key', + 'sk_live', + '_payment', + '_authorization', + ]) { + expect(text).not.toContain(leaked); + } + }); + + it('adds an output example the output schema provably accepts', () => { + const outputSchema = { + type: 'object', + properties: { forecast: { type: 'string' } }, + required: ['forecast'], + }; + const extension = extensionOf('http', resource({ outputSchema })); + expect(extension.info['output']).toEqual({ type: 'json', example: { forecast: '' } }); + expect(validateDiscoveryExtension(extension as never)).toEqual({ valid: true }); + }); + + it.each([ + [ + 'uses a keyword the gateway does not enforce', + { type: 'object', properties: { at: { type: 'string', format: 'date' } } }, + ], + ['rejects its own generated example', { type: 'string', enum: [1] }], + ])('leaves out the output example when the output schema %s', (_label, outputSchema) => { + expect(extensionOf('http', resource({ outputSchema })).info['output']).toEqual({ + type: 'json', + }); + }); + + it('describes a resource without an input schema as taking an empty object', () => { + const { inputSchema: _, ...open } = resource(); + expect(extensionOf('http', open).info['input']).toEqual({ + type: 'http', + method: 'POST', + bodyType: 'json', + body: {}, + }); + expect(extensionOf('mcp', open).info['input']).toMatchObject({ + inputSchema: { type: 'object', properties: {} }, + example: {}, + }); + }); + + it('builds nothing for no surface', () => { + expect(bazaarMetadata(resource(), [])).toEqual({ extensions: {}, omitted: [] }); + }); +}); + +describe('Bazaar metadata omission', () => { + const nested = (property: Record) => + resource({ + inputSchema: { + type: 'object', + properties: { city: property }, + required: ['city'], + additionalProperties: false, + }, + }); + + it.each([ + ['pattern', nested({ type: 'string', pattern: '^[A-Z]' })], + [ + 'a nested format', + nested({ type: 'object', properties: { d: { type: 'string', format: 'date' } } }), + ], + ['$ref', nested({ $ref: '#/$defs/city' })], + [ + 'minProperties, which config does not warn about', + resource({ inputSchema: { type: 'object', minProperties: 1 } }), + ], + ['a tuple items', nested({ type: 'array', items: [{ type: 'string' }] })], + ['additionalProperties without an object type', nested({ additionalProperties: false })], + ['items without an array type', nested({ items: { type: 'string' } })], + ['an empty type list', nested({ type: [] })], + ['an unknown type', nested({ type: 'date' })], + ])('leaves out a resource whose input schema uses %s', (_label, of) => { + expect(bazaarMetadata(of, BOTH)).toEqual({ + extensions: {}, + omitted: [ + { + surfaces: BOTH, + reason: + 'its input schema uses a keyword the gateway does not enforce, which leaves the example unproven', + }, + ], + }); + }); + + it.each([ + ['fails the input schema', nested({ type: 'string', enum: [1] })], + [ + 'fails the backend request shape', + resource({ + inputSchema: { + type: 'object', + properties: { where: { type: 'string' } }, + required: ['where'], + }, + handler: { + type: 'http', + method: 'GET', + url: 'http://backend.local/{city}', + inputBindings: { path: 'where' }, + }, + }), + ], + ])('leaves out a resource whose generated example %s', (_label, of) => { + expect(bazaarMetadata(of, BOTH).omitted).toEqual([ + { + surfaces: BOTH, + reason: 'the example generated from its input schema fails the gateway input checks', + }, + ]); + }); + + const TOO_LONG = [ + { + surfaces: BOTH, + reason: 'its description is longer than 500 characters, which the CDP facilitator refuses', + }, + ]; + + it('keeps a resource whose description is exactly 500 characters', () => { + const { extensions, omitted } = bazaarMetadata( + resource({ description: 'd'.repeat(500) }), + BOTH, + ); + expect(Object.keys(extensions)).toEqual(['http', 'mcp']); + expect(omitted).toEqual([]); + }); + + it('leaves out a resource whose description is 501 characters', () => { + expect(bazaarMetadata(resource({ description: 'd'.repeat(501) }), BOTH)).toEqual({ + extensions: {}, + omitted: TOO_LONG, + }); + }); + + it('applies the limit to the name when there is no description', () => { + const { description: _, ...rest } = resource({ name: 'n'.repeat(501) }); + expect(bazaarMetadata(rest, BOTH)).toEqual({ extensions: {}, omitted: TOO_LONG }); + }); + + it('leaves out each surface whose extension exceeds 4 KiB, and keeps the others', () => { + // The MCP form also carries the description. With it at 480 characters + // and 44 properties, MCP is over 4096 bytes and HTTP under. + const properties = Object.fromEntries( + Array.from({ length: 44 }, (_, i) => [`property_${i}`, { type: 'string' }]), + ); + const of = resource({ + description: 'd'.repeat(480), + inputSchema: { type: 'object', properties, required: Object.keys(properties) }, + }); + const { extensions, omitted } = bazaarMetadata(of, BOTH); + + expect(Object.keys(extensions)).toEqual(['http']); + expect(Buffer.byteLength(JSON.stringify(extensions.http))).toBeGreaterThan(3800); + expect(omitted).toEqual([{ surfaces: ['mcp'], reason: 'the extension exceeds 4096 bytes' }]); + }); +}); From 791899d7dc3bd3caaed1999f0d1faa9bdc907acc Mon Sep 17 00:00:00 2001 From: Revinand Date: Wed, 18 Nov 2026 20:11:04 +0100 Subject: [PATCH 08/14] feat(cli): generate MCP Registry metadata --- README.md | 21 +- docs/configuration.md | 38 +- docs/contracts.md | 20 +- docs/protocols/mcp.md | 36 ++ docs/security.md | 13 +- src/cli/commands/doctor/index.ts | 6 +- src/cli/commands/doctor/registry.ts | 103 ++++ src/cli/commands/doctor/types.ts | 2 + src/cli/commands/export-mcp-registry.ts | 58 ++ src/cli/commands/import-openapi.ts | 30 +- src/cli/lib/mcp-registry.ts | 78 +++ src/cli/lib/write-file.ts | 20 + src/cli/program.ts | 52 +- src/config/schema/mcp-registry.ts | 59 ++ src/config/schema/normalize.ts | 1 + src/config/schema/raw.ts | 4 + src/config/schema/types.ts | 19 +- .../2025-12-11/server.schema.json | 574 ++++++++++++++++++ tests/unit/cli/doctor-registry.test.ts | 308 ++++++++++ tests/unit/cli/export-mcp-registry.test.ts | 136 +++++ tests/unit/cli/import-openapi.test.ts | 16 + tests/unit/cli/mcp-registry.test.ts | 153 +++++ tests/unit/cli/program.test.ts | 115 +++- tests/unit/config/schema.test.ts | 95 +++ 24 files changed, 1894 insertions(+), 63 deletions(-) create mode 100644 src/cli/commands/doctor/registry.ts create mode 100644 src/cli/commands/export-mcp-registry.ts create mode 100644 src/cli/lib/mcp-registry.ts create mode 100644 src/cli/lib/write-file.ts create mode 100644 src/config/schema/mcp-registry.ts create mode 100644 tests/fixtures/mcp-registry/2025-12-11/server.schema.json create mode 100644 tests/unit/cli/doctor-registry.test.ts create mode 100644 tests/unit/cli/export-mcp-registry.test.ts create mode 100644 tests/unit/cli/mcp-registry.test.ts diff --git a/README.md b/README.md index 5e0e576..cb6e729 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,8 @@ agent-commerce doctor Requires **Node >= 22**. The package includes the `agent-commerce` CLI (`init`, `validate`, `start`, `doctor`, `reconcile`, `resolve`, `demo`, -`import openapi`, `version`) and a library for embedding the gateway. +`import openapi`, `export mcp-registry`, `version`) and a library for embedding +the gateway. The default install excludes optional protocol, payment and authorization peers. The OpenAPI parser is a regular dependency because import is part of the CLI. @@ -86,10 +87,10 @@ agent-commerce start --config config.yaml --env-file .env Install the optional peers for the features you enable, listed below. Missing startup imports stop the gateway with an error naming the package; missing Solana, NEAR or CDP peers fail provider health checks or payment requests. -`start`, `validate`, `doctor`, `reconcile` and `resolve` accept `--env-file ` to -load environment variables before reading the config. Variables already set in -the environment take precedence. To embed the gateway in your own process, use -the library: +`start`, `validate`, `doctor`, `reconcile`, `resolve` and `export mcp-registry` +accept `--env-file ` to load environment variables before reading the +config. Variables already set in the environment take precedence. To embed the +gateway in your own process, use the library: ```ts import { createGateway, loadConfig, receipts } from '@devlab.group/agent-commerce'; @@ -538,6 +539,16 @@ hostnames and TLS errors leave the check unmarked. Text output appends `[not determined: ]`. The marker does not affect status, score or exit code; an unreachable gateway still fails its check. +`--registry` (experimental) adds an `MCP Registry` check. It fetches the +latest listing for `protocols.mcp.registry.name` from +`registry.modelcontextprotocol.io`, sending only that name, and compares it +with what `export mcp-registry` would write. Differences, deprecated or deleted +listings, missing listings and request failures produce WARN rather than FAIL. +Recognized transport failures also get the `unreachable` marker. The check +names differing fields and uses fixed messages for known lifecycle statuses, +without echoing arbitrary registry values or request error messages. See +[MCP Registry listing](docs/protocols/mcp.md#mcp-registry-listing). + Exits non-zero if anything fails. `--json` for machines. ### `agent-commerce reconcile` diff --git a/docs/configuration.md b/docs/configuration.md index f47637a..203d83d 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -214,6 +214,41 @@ literal prefix (see Generated by [`agent-commerce import openapi`](openapi-import.md); nothing about the field is OpenAPI-specific. +## `protocols.mcp.registry` + +Experimental and optional. This block supplies the listing fields that +[`agent-commerce export mcp-registry`](protocols/mcp.md#mcp-registry-listing) +writes to `server.json` and `doctor --registry` compares with the live +listing. Config loading validates these fields; the MCP adapter does not use +them. + +```yaml +protocols: + mcp: + enabled: true + mountPath: /mcp + registry: + name: io.github.acme/weather + version: 1.4.0 # the listing's version, not the package's + description: Weather forecasts, paid per call +``` + +Config loading checks the following MCP Registry field rules and names invalid +keys: + +- `name`: at most 200 characters, a namespace and a name joined by one `/`. + Each side has at least two characters and starts and ends with an ASCII + letter or digit. The namespace may also contain `.` and `-`; the name may + contain `.`, `_` and `-`. +- `version`: 1 to 255 characters. Not `latest`, and not a range such as + `^1.2.3`, `>= 1.2.3`, `1.x`, `1.*`, `1.2.3 - 2.0.0` or `1.2 || 1.3`. The + range check also treats dotted versions containing `x`, `X` or `*` as ranges, + including in the prerelease part, so it rejects `1.0.0-next.1`. Quote versions + that YAML would read as numbers, such as `"1.4"`. +- `description`: 1 to 100 characters. + +Lengths count Unicode code points. + ## `protocols.acp` Experimental, off by default, and absent from a config that predates it. The @@ -881,7 +916,8 @@ none of whose listed rails is enabled · `expose` values outside `protocols.mcp.enabled` is false (likewise `a2a` and `acp`) · enabled A2A with no resource exposed through `a2a` · two enabled protocol mounts that overlap · a mount that claims a route the gateway already -serves, including the A2A Agent Card and ACP discovery paths · an ACP checkout +serves, including the A2A Agent Card and ACP discovery paths · a +`protocols.mcp.registry` value that breaks the field rules above · an ACP checkout mapping that is incomplete, names a missing or non-`acp` resource, reuses one resource for two operations, or maps a paid one · an ACP idempotency retention below 24 hours · an invalid or zero `payTo`/`asset`/`recipient` · an diff --git a/docs/contracts.md b/docs/contracts.md index 3101bf5..d637bcc 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -487,6 +487,12 @@ persistence must not fail the commerce flow. `resource` and `extensions.bazaar` to the facilitator, replacing those fields from the proof. - Without the option, challenges and facilitator bodies are unchanged. +- 2.8.0: experimental `GatewayConfig.protocols.mcp.registry` holds the + `name`, `version` and `description` from `protocols.mcp.registry` and is + absent when that block is omitted. Config loading validates these fields + against the MCP Registry's name, length and version rules. + `agent-commerce export mcp-registry` and `doctor --registry` use the metadata; + the MCP adapter does not. ### Authorization and AP2 @@ -1039,7 +1045,16 @@ export interface GatewayConfig { }; readonly protocols: { readonly http: { readonly enabled: boolean }; - readonly mcp: { readonly enabled: boolean; readonly mountPath: string }; + readonly mcp: { + readonly enabled: boolean; + readonly mountPath: string; + // Experimental; present only when `protocols.mcp.registry` is set + readonly registry?: { + readonly name: string; + readonly version: string; + readonly description: string; + }; + }; readonly a2a: { readonly enabled: boolean; readonly mountPath: string }; readonly acp: AcpProtocolConfig; }; @@ -1059,6 +1074,9 @@ export interface GatewayConfig { readonly paymentFlow?: X402PaymentFlow; // default 'authorization' readonly resourcePaymentFlows?: Readonly>; readonly resourceMimeTypes?: Readonly>; // resources that set `mimeType` + // Experimental; filled by `publicResourceUrl` and `bazaar.enabled` + readonly resourceUrls?: X402ProviderOptions['resourceUrls']; + readonly resourceBazaar?: X402ProviderOptions['resourceBazaar']; readonly facilitator: X402FacilitatorConfig; readonly allowMainnet?: boolean; readonly allowUnauthenticatedFacilitator?: boolean; diff --git a/docs/protocols/mcp.md b/docs/protocols/mcp.md index 2f30030..5af20a0 100644 --- a/docs/protocols/mcp.md +++ b/docs/protocols/mcp.md @@ -115,6 +115,42 @@ For payment-required and error results, `content[0].text` is a JSON copy of `structuredContent`; `content[1].text` is a sentence for readers. Unexpected exception messages and stack traces are omitted. +## MCP Registry listing + +Experimental. The [MCP Registry](https://registry.modelcontextprotocol.io) +is a public catalog of MCP servers in preview. Use the CLI to export a listing, +then publish it: + +1. Set [`protocols.mcp.registry`](../configuration.md#protocolsmcpregistry) + and an HTTPS `merchant.publicBaseUrl`. +2. Run `agent-commerce export mcp-registry`. It loads and validates the full + config as `start` does, so required `${VAR}` placeholders must resolve. It + writes `server.json` with the 2025-12-11 `$schema`, your `name`, `description` + and `version`, and one `streamable-http` remote at + ``. + Use `--output` to choose another path and `--force` to replace an existing + file. The command writes nothing and names the key to change when MCP is + disabled, the registry block is missing, or the URL uses a scheme other than + HTTPS or names `localhost`, `127.0.0.1` or a `.localhost` host. +3. Log in and publish with the registry's `mcp-publisher` CLI. The namespace + determines the required ownership proof: `io.github./` needs GitHub + authentication; a reverse-DNS namespace such as `com.example/` needs a DNS + TXT record or a `/.well-known/mcp-registry-auth` file on `example.com`. + The gateway does not serve that file. See the registry's + [authentication guide](https://github.com/modelcontextprotocol/registry/blob/115f85225c9fac5281d8a2dc8551cf49b004d2f9/docs/modelcontextprotocol-io/authentication.mdx). +4. Run `agent-commerce doctor --registry` to compare the published listing + with your config. + +The listing's version comes from `protocols.mcp.registry.version`, independently +of the package version. The registry recommends semantic versions and uses +their ordering to choose the latest. Publishing a prerelease such as `1.2.3-1` +after its release, `1.2.3`, does not make it the latest. If your config names +that prerelease, `doctor --registry` reports a version difference. + +Several server names may list the same remote URL, so the URL alone does not +prove who runs the server. `doctor --registry` looks up the configured name +only and reports a response with another name as a difference in `name`. + ## Pins diff --git a/docs/security.md b/docs/security.md index ed6efbe..5270ec6 100644 --- a/docs/security.md +++ b/docs/security.md @@ -335,12 +335,12 @@ real funds. | **multi-offer x402 proof whose `accepted` matches zero or multiple offers** | `invalid_payment_requirements`; no offer is selected and the facilitator is not called | `tests/unit/payments-x402/provider-remote-facilitator.test.ts` | | **an x402 proof under `publicResourceUrl`, whose offers share one `resource.url`** | offer selection still uses `accepted`, as with `resource://`; the URL form does not change the replay key | `tests/unit/payments-x402/public-resource-url.test.ts` | | **an x402 proof echoing a challenge issued before `publicResourceUrl` changed, or another surface's challenge** | `invalid_payment_requirements` before calling the facilitator; no settlement, including for an A2A task awaiting payment across a restart | `tests/unit/payments-x402/public-resource-url.test.ts`, `tests/integration/x402-public-url.test.ts`, `tests/integration/a2a-x402-extension.test.ts` | -| **a buyer echoing altered Bazaar metadata or `resource` fields to poison a facilitator's catalog** | replaces the proof's values with the issued challenge's `resource` and `extensions.bazaar` before forwarding | `tests/unit/payments-x402/bazaar-challenge.test.ts`, `tests/integration/x402-bazaar.test.ts` | -| **a proof's `payment-identifier`, ERC-8409 quote or gas-sponsoring extension, under Bazaar** | none of the proof's extensions are forwarded; the facilitator receives only the challenge's `extensions.bazaar` | `tests/unit/payments-x402/bazaar-challenge.test.ts` | +| **a buyer echoing altered Bazaar metadata or `resource` fields to poison a facilitator's catalog** | replaces the proof's values with the issued challenge's `resource` and `extensions.bazaar` before forwarding | `tests/unit/payments-x402/bazaar-challenge.test.ts`, `tests/integration/x402-bazaar.test.ts` | +| **a proof's `payment-identifier`, ERC-8409 quote or gas-sponsoring extension, under Bazaar** | none of the proof's extensions are forwarded; the facilitator receives only the challenge's `extensions.bazaar` | `tests/unit/payments-x402/bazaar-challenge.test.ts` | | **Bazaar metadata echoed from another surface, with several offers** | offer selection still uses `accepted`; the facilitator receives the challenge's own metadata | `tests/unit/payments-x402/bazaar-challenge.test.ts` | -| **Bazaar metadata exposing a backend URL, header, credential, reserved field or unexposed surface** | backend connection settings are not copied; resource ids, descriptions, schemas and generated examples are public metadata. Schema and example contents are not redacted. Bazaar adds no `_payment` or `_authorization` carriers; unexposed surfaces receive no metadata | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/config/schema.test.ts` | -| **a Bazaar extension large enough to break the `PAYMENT-REQUIRED` header, and payment with it** | config loading omits extensions over 4096 bytes and warns; an HTTP challenge omits Bazaar if it would push the encoded header value over 8192 bytes. Payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/payments-x402/bazaar-challenge.test.ts` | -| **a generated Bazaar example the gateway would refuse, silently dropping the listing** | config loading omits the resource's metadata and warns with its id, affected surfaces and reason; payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/config/schema.test.ts`, `tests/integration/x402-bazaar.test.ts` | +| **Bazaar metadata exposing a backend URL, header, credential, reserved field or unexposed surface** | backend connection settings are not copied; resource ids, descriptions, schemas and generated examples are public metadata. Schema and example contents are not redacted. Bazaar adds no `_payment` or `_authorization` carriers; unexposed surfaces receive no metadata | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/config/schema.test.ts` | +| **a Bazaar extension large enough to break the `PAYMENT-REQUIRED` header, and payment with it** | config loading omits extensions over 4096 bytes and warns; an HTTP challenge omits Bazaar if it would push the encoded header value over 8192 bytes. Payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/payments-x402/bazaar-challenge.test.ts` | +| **a generated Bazaar example the gateway would refuse, silently dropping the listing** | config loading omits the resource's metadata and warns with its id, affected surfaces and reason; payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/config/schema.test.ts`, `tests/integration/x402-bazaar.test.ts` | | **an AP2 mandate approved for one x402 offer, presented with a proof for another** | selected destination, network or asset fails mandate binding; no settlement | `tests/unit/core/execution/pipeline-authorization.test.ts` | | **an EIP-3009 authorization signed for one EVM chain, presented as another chain's offer** | `invalid_exact_evm_signature`: signature fails against the other chain's EIP-712 domain; neither chain's balances change | `tests/e2e/payment/x402-multichain.e2e.test.ts` | | **the same payer, token address and nonce on two EVM chains** | both settle: the replay key includes the chain id | same | @@ -584,6 +584,9 @@ real funds. | **`doctor` reporting a misconfigured RPC or facilitator as unreachable** | marks an offer `unreachable` for recognized transport failures, including refused or reset connections, temporary DNS failures and timeouts. Unresolvable hostnames, TLS and certificate errors, JSON-RPC errors, non-2xx responses, reverts, unparseable bodies, missing peers and unrecognized errors fail without this marker | `tests/unit/core/no-answer.test.ts` ("is false for %s"), `tests/unit/payments-x402/provider-health-mocked.test.ts` ("leaves the %s unmarked after %s"), `tests/integration/doctor-certainty.test.ts` ("%s: %s FAILs unmarked when %s") | | **`doctor` reporting a gateway that answered as unreachable** | marks `Gateway` `unreachable` for recognized transport failures, including refused or reset connections and timeouts. Unresolvable hostnames, ports rejected by fetch, non-2xx `/health` responses and Host refusals fail unmarked; checks that need the discovery document are `skipped`. Responses with unusable document content leave those checks unmarked | `tests/unit/cli/doctor-certainty.test.ts` ("when %s", "says a gateway that answered non-2xx is unhealthy, not unreachable"), `tests/integration/doctor-certainty.test.ts` ("leaves Gateway unmarked, and says why, when fetch refuses the port") | | **the `doctor` Secrets check printing a value or a default** | reports placeholder names in text and JSON, never variable values or defaults | `tests/unit/cli/doctor-certainty.test.ts` ("FAILs naming every missing variable, and prints no value or default"), `tests/unit/config/env.test.ts` ("returns names only: no value and no default") | +| **an MCP Registry answer injecting text into `doctor` output** | `doctor --registry` names differing fields and uses fixed messages for known lifecycle statuses, without echoing arbitrary answer values or request error messages in text or JSON | `tests/unit/cli/doctor-registry.test.ts` ("prints no value from a hostile answer, in text or JSON", "leaves a TLS failure unmarked and does not print its message") | +| **`doctor --registry` sending more than the server name** | sends a GET to `/v0.1/servers//versions/latest` with no custom headers or body, only when the flag is set and config yields a listing | `tests/unit/cli/doctor-registry.test.ts` ("asks for the configured name only, with no header or body", "adds no check and sends nothing to the registry without the flag", "sends nothing for an http public URL") | +| **another server name listing the gateway's URL, taken for the merchant's listing** | `doctor --registry` looks up the configured name only and reports a response with another name as a difference in `name` | `tests/unit/cli/doctor-registry.test.ts` ("asks for the configured name only, with no header or body", "reports a listing under another name") | A facilitator verdict is a returned result. The SDK throws when a remote `/verify` answers with a non-2xx status; the binding turns that throw back into diff --git a/src/cli/commands/doctor/index.ts b/src/cli/commands/doctor/index.ts index ae978f9..166d08f 100644 --- a/src/cli/commands/doctor/index.ts +++ b/src/cli/commands/doctor/index.ts @@ -21,6 +21,7 @@ import { readVersionReport } from '../../lib/versions'; import { ap2Checks } from './ap2'; import { paymentChecks } from './payments'; import { protocolChecks } from './protocols'; +import { registryCheck } from './registry'; import { secretsCheck } from './secrets'; import { storageChecks } from './storage'; import { @@ -65,7 +66,7 @@ function substitutePathParams(url: string): string { return filled; } -/** `agent-commerce doctor [--config] [--gateway] [--json]` */ +/** `agent-commerce doctor [--config] [--gateway] [--json] [--registry]` */ export async function runDoctor( options: DoctorOptions, deps: DoctorDeps = {}, @@ -240,6 +241,9 @@ export async function runDoctor( }); } + // 9. MCP Registry, only on request: it calls a third party + if (options.registry === true) checks.push(await registryCheck(config, fetchImpl)); + const scored = checks.filter((c) => c.status !== 'INFO'); const passed = scored.filter((c) => c.status === 'PASS').length; const exitCode = checks.some((c) => c.status === 'FAIL') ? 1 : 0; diff --git a/src/cli/commands/doctor/registry.ts b/src/cli/commands/doctor/registry.ts new file mode 100644 index 0000000..27f0fb0 --- /dev/null +++ b/src/cli/commands/doctor/registry.ts @@ -0,0 +1,103 @@ +// MCP Registry: the live listing of `protocols.mcp.registry.name`, checked with --registry +import { isRecord } from '../../../core/is-record'; +import type { GatewayConfig } from '../../lib/config-client'; +import { type FetchLike, fetchJson } from '../../lib/http'; +import { type ServerJson, serverJson } from '../../lib/mcp-registry'; +import { type DoctorCheck, SKIPPED_CONFIG_INVALID } from './types'; + +/** The registry `doctor --registry` reads */ +export const MCP_REGISTRY_URL = 'https://registry.modelcontextprotocol.io'; + +const NAME = 'MCP Registry'; +// Allow more time for the public registry than for gateway checks +const REGISTRY_TIMEOUT_MS = 5000; +const OFFICIAL_META = 'io.modelcontextprotocol.registry/official'; + +/** + * Compares the configured name's latest listing with `export mcp-registry` + * output. The request sends only the name. Listing and request problems produce + * WARN because they do not establish deployment health. Treat the answer as + * untrusted: report differing field names and known lifecycle statuses without + * echoing arbitrary registry values or request error messages. + */ +export async function registryCheck( + config: GatewayConfig | undefined, + fetchImpl: FetchLike, +): Promise { + if (config === undefined) return { name: NAME, status: 'WARN', ...SKIPPED_CONFIG_INVALID }; + if (config.protocols.mcp.registry === undefined) { + return { name: NAME, status: 'INFO', detail: 'protocols.mcp.registry not configured' }; + } + const built = serverJson(config); + if ('problems' in built) { + return { + name: NAME, + status: 'WARN', + detail: built.problems.map((problem) => `${problem.key} ${problem.message}`).join('; '), + }; + } + const local = built.document; + const answer = await fetchJson( + fetchImpl, + `${MCP_REGISTRY_URL}/v0.1/servers/${encodeURIComponent(local.name)}/versions/latest`, + REGISTRY_TIMEOUT_MS, + ); + // An error message can carry text from the far end, such as certificate names + if (answer.status === 0) { + return answer.noAnswer === true + ? { + name: NAME, + status: 'WARN', + detail: 'no answer from the registry', + undetermined: 'unreachable', + } + : { name: NAME, status: 'WARN', detail: 'the registry request failed' }; + } + if (answer.status === 404) { + return { name: NAME, status: 'WARN', detail: `${local.name} is not listed` }; + } + if (!answer.ok || !isRecord(answer.body) || !isRecord(answer.body['server'])) { + return { + name: NAME, + status: 'WARN', + detail: answer.ok + ? 'the registry answer is not a server listing' + : `the registry answered HTTP ${answer.status}`, + }; + } + + const problems = [ + ...lifecycle(answer.body['_meta']), + ...differences(answer.body['server'], local), + ]; + return problems.length === 0 + ? { + name: NAME, + status: 'PASS', + detail: `${local.name} ${local.version} is listed as configured`, + } + : { name: NAME, status: 'WARN', detail: `${local.name}: ${problems.join('; ')}` }; +} + +// Only the registry's known status words reach the output +function lifecycle(meta: unknown): string[] { + const official = isRecord(meta) ? meta[OFFICIAL_META] : undefined; + const status = isRecord(official) ? official['status'] : undefined; + if (status === 'active') return []; + if (status === 'deprecated' || status === 'deleted') return [`listing is ${status}`]; + return ['listing has no known status']; +} + +function differences(listed: Record, local: ServerJson): string[] { + const fields = (['name', 'version', 'description'] as const).filter( + (field) => listed[field] !== local[field], + ); + const remotes = listed['remotes']; + const remote = Array.isArray(remotes) && remotes.length === 1 ? remotes[0] : undefined; + const sameRemote = + isRecord(remote) && + remote['type'] === local.remotes[0].type && + remote['url'] === local.remotes[0].url; + const differing = sameRemote ? fields : [...fields, 'remotes']; + return differing.length > 0 ? [`listing differs from config in ${differing.join(', ')}`] : []; +} diff --git a/src/cli/commands/doctor/types.ts b/src/cli/commands/doctor/types.ts index 6824522..e609604 100644 --- a/src/cli/commands/doctor/types.ts +++ b/src/cli/commands/doctor/types.ts @@ -32,6 +32,8 @@ export interface DoctorReport { export interface DoctorOptions { readonly configPath?: string; readonly gatewayUrl?: string; + /** Experimental. Adds a Registry check; queries the public registry when config yields a listing */ + readonly registry?: boolean; } /** A receipt store for doctor to read; `summary` adds the journal and import checks */ diff --git a/src/cli/commands/export-mcp-registry.ts b/src/cli/commands/export-mcp-registry.ts new file mode 100644 index 0000000..e2190f4 --- /dev/null +++ b/src/cli/commands/export-mcp-registry.ts @@ -0,0 +1,58 @@ +// `agent-commerce export mcp-registry`: write `server.json` for the MCP Registry from config +import { existsSync } from 'node:fs'; +import { type ConfigLoader, type GatewayConfig, loadConfigDynamic } from '../lib/config-client'; +import type { Io } from '../lib/io'; +import { serverJson } from '../lib/mcp-registry'; +import { writeAtomically } from '../lib/write-file'; +import { formatConfigError } from './validate'; + +export interface ExportMcpRegistryOptions { + readonly configPath?: string; + readonly output: string; + readonly force?: boolean; +} + +export interface ExportMcpRegistryDeps { + readonly loadConfig?: ConfigLoader; +} + +/** Exports a listing after config loading and listing checks succeed */ +export async function runExportMcpRegistry( + options: ExportMcpRegistryOptions, + io: Io, + deps: ExportMcpRegistryDeps = {}, +): Promise { + const { output } = options; + if (existsSync(output) && options.force !== true) { + io.stderr(`FAIL ${output} already exists. Re-run with --force to overwrite.`); + return 1; + } + + let config: GatewayConfig; + try { + config = await (deps.loadConfig ?? loadConfigDynamic)( + options.configPath !== undefined ? { path: options.configPath } : {}, + ); + } catch (error) { + io.stderr(formatConfigError(error, false, false)); + return 1; + } + + const result = serverJson(config); + if ('problems' in result) { + for (const problem of result.problems) io.stderr(`FAIL ${problem.key} ${problem.message}`); + return 1; + } + + try { + await writeAtomically(output, `${JSON.stringify(result.document, null, 2)}\n`); + } catch (error) { + io.stderr( + `FAIL ${output} could not be written: ${error instanceof Error ? error.message : String(error)}`, + ); + return 1; + } + io.stdout(`Wrote ${output} for ${result.document.name} ${result.document.version}.`); + io.stdout('Publish it with mcp-publisher after verifying the namespace.'); + return 0; +} diff --git a/src/cli/commands/import-openapi.ts b/src/cli/commands/import-openapi.ts index 93d2f43..cbde7eb 100644 --- a/src/cli/commands/import-openapi.ts +++ b/src/cli/commands/import-openapi.ts @@ -6,8 +6,7 @@ * `--output config.yaml --force` replaces that file rather than merging. */ import { existsSync } from 'node:fs'; -import { mkdir, rename, rm, writeFile } from 'node:fs/promises'; -import { basename, dirname, extname, resolve } from 'node:path'; +import { basename, extname } from 'node:path'; import { PROTOCOL_NAMES } from '../../core'; import { buildResourceDrafts, @@ -17,6 +16,7 @@ import { renderResourcesYaml, } from '../../openapi'; import type { Io } from '../lib/io'; +import { writeAtomically } from '../lib/write-file'; export interface ImportOpenApiOptions { readonly source: string; @@ -103,7 +103,7 @@ export async function runImportOpenApi( const wrote = failures.length === 0; if (wrote) { try { - await writeAtomically(outputPath, renderResourcesYaml(result), deps); + await (deps.writeFile ?? writeAtomically)(outputPath, renderResourcesYaml(result)); } catch (error) { io.stderr(`FAIL ${outputPath} could not be written: ${describe(error)}`); return 1; @@ -164,30 +164,6 @@ function buildPolicy(options: ImportOpenApiOptions): ImportPolicy | string { return policy; } -async function writeAtomically( - outputPath: string, - content: string, - deps: ImportOpenApiDeps, -): Promise { - if (deps.writeFile !== undefined) { - await deps.writeFile(outputPath, content); - return; - } - // Temp sibling then rename: a crash or a full disk must not leave a - // half-written file where a complete one used to be - const target = resolve(outputPath); - const temporary = `${target}.${process.pid}.tmp`; - try { - // Like `init --output`: a missing output directory is created, not an error - await mkdir(dirname(target), { recursive: true }); - await writeFile(temporary, content, 'utf8'); - await rename(temporary, target); - } catch (error) { - await rm(temporary, { force: true }); - throw error; - } -} - function printSummary( result: ImportResult, context: { outputPath: string; wrote: boolean; policy: ImportPolicy }, diff --git a/src/cli/lib/mcp-registry.ts b/src/cli/lib/mcp-registry.ts new file mode 100644 index 0000000..53ace55 --- /dev/null +++ b/src/cli/lib/mcp-registry.ts @@ -0,0 +1,78 @@ +// The MCP Registry listing (`server.json`) for a gateway, built from config alone +import { joinUrl } from '../../protocols/http'; +import type { GatewayConfig } from './config-client'; + +/** The `server.json` schema revision the listing follows */ +export const SERVER_JSON_SCHEMA = + 'https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json'; + +export interface ServerJson { + readonly $schema: typeof SERVER_JSON_SCHEMA; + readonly name: string; + readonly description: string; + readonly version: string; + readonly remotes: readonly [{ readonly type: 'streamable-http'; readonly url: string }]; +} + +/** Why a listing cannot be written, naming the config key to change */ +export interface RegistryProblem { + readonly key: string; + readonly message: string; +} + +/** + * Builds a listing from validated `config`, or returns the problems found. + * Requires MCP to be enabled and registry metadata to be present. The remote + * URL joins `merchant.publicBaseUrl` and the MCP mount; it must use HTTPS and + * must not name `localhost`, `127.0.0.1` or `*.localhost`. The version comes + * from `protocols.mcp.registry`, independently of the package version. + */ +export function serverJson( + config: GatewayConfig, +): { readonly document: ServerJson } | { readonly problems: readonly RegistryProblem[] } { + const { mcp } = config.protocols; + const problems: RegistryProblem[] = []; + if (!mcp.enabled) { + problems.push({ + key: 'protocols.mcp.enabled', + message: 'is false: the listing would name a server that does not run', + }); + } + if (mcp.registry === undefined) { + problems.push({ + key: 'protocols.mcp.registry', + message: 'is not set: it holds the listing name, version and description', + }); + } + const url = remoteUrl(config.merchant.publicBaseUrl, mcp.mountPath); + if (typeof url === 'string') problems.push({ key: 'merchant.publicBaseUrl', message: url }); + + if (mcp.registry === undefined || typeof url === 'string' || problems.length > 0) { + return { problems }; + } + return { + document: { + $schema: SERVER_JSON_SCHEMA, + name: mcp.registry.name, + description: mcp.registry.description, + version: mcp.registry.version, + remotes: [{ type: 'streamable-http', url: url.href }], + }, + }; +} + +// Check the remote URL against the registry's `IsValidRemoteURL` rules +function remoteUrl(publicBaseUrl: string, mountPath: string): URL | string { + let url: URL; + try { + url = new URL(joinUrl(publicBaseUrl, mountPath)); + } catch { + return 'is not a URL'; + } + if (url.protocol !== 'https:') return 'must be an https:// URL: the MCP Registry refuses others'; + const host = url.hostname; + if (host === 'localhost' || host === '127.0.0.1' || host.endsWith('.localhost')) { + return `names ${host}, which the MCP Registry refuses`; + } + return url; +} diff --git a/src/cli/lib/write-file.ts b/src/cli/lib/write-file.ts new file mode 100644 index 0000000..31d2227 --- /dev/null +++ b/src/cli/lib/write-file.ts @@ -0,0 +1,20 @@ +import { mkdir, rename, rm, writeFile } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; + +/** + * Writes `content` to a temporary sibling, then renames it over `outputPath`. + * The destination is replaced after the write succeeds, so a failed write + * leaves an existing file intact. Creates missing output directories. + */ +export async function writeAtomically(outputPath: string, content: string): Promise { + const target = resolve(outputPath); + const temporary = `${target}.${process.pid}.tmp`; + try { + await mkdir(dirname(target), { recursive: true }); + await writeFile(temporary, content, 'utf8'); + await rename(temporary, target); + } catch (error) { + await rm(temporary, { force: true }); + throw error; + } +} diff --git a/src/cli/program.ts b/src/cli/program.ts index b15f201..c06326b 100644 --- a/src/cli/program.ts +++ b/src/cli/program.ts @@ -4,6 +4,7 @@ import { PROTOCOL_NAMES } from '../core'; import { runBackupCommand } from './commands/backup'; import { runDemo } from './commands/demo'; import { printDoctorReport, runDoctor } from './commands/doctor'; +import { runExportMcpRegistry } from './commands/export-mcp-registry'; import { runImportOpenApi } from './commands/import-openapi'; import { runInit } from './commands/init'; import { runReconcileCommand } from './commands/reconcile'; @@ -28,7 +29,7 @@ export function buildProgram(io: Io = processIo): Command { program .name('agent-commerce') .description( - 'CLI for the Agent Commerce Gateway: init, import, validate, start, doctor, reconcile, backup, demo.', + 'CLI for the Agent Commerce Gateway: init, import, export, validate, start, doctor, reconcile, backup, demo.', ) // `--version` prints the CLI version only; the `version` subcommand also // lists the pinned protocol/SDK versions. Both read `readVersionReport()`, @@ -106,14 +107,22 @@ export function buildProgram(io: Io = processIo): Command { 'gateway base URL (default: derived from config, else http://localhost:8080)', ) .option('--json', 'emit machine-readable JSON instead of a formatted report', false) - .action(async (opts: { config?: string; gateway?: string; json?: boolean }) => { - const report = await runDoctor({ - ...(opts.config !== undefined ? { configPath: opts.config } : {}), - ...(opts.gateway !== undefined ? { gatewayUrl: opts.gateway } : {}), - }); - printDoctorReport(report, io, opts.json === true); - process.exitCode = report.exitCode; - }); + .option( + '--registry', + 'also compare the MCP Registry listing named in protocols.mcp.registry with config (calls registry.modelcontextprotocol.io)', + false, + ) + .action( + async (opts: { config?: string; gateway?: string; json?: boolean; registry: boolean }) => { + const report = await runDoctor({ + ...(opts.config !== undefined ? { configPath: opts.config } : {}), + ...(opts.gateway !== undefined ? { gatewayUrl: opts.gateway } : {}), + registry: opts.registry, + }); + printDoctorReport(report, io, opts.json === true); + process.exitCode = report.exitCode; + }, + ); program .command('reconcile') @@ -287,6 +296,31 @@ export function buildProgram(io: Io = processIo): Command { }, ); + // Group catalog exports under `export`, mirroring `import` + const exportCommand = program + .command('export') + .description('Generate catalog listings for the gateway from config.'); + + exportCommand + .command('mcp-registry') + .description( + 'Write server.json for the MCP Registry from protocols.mcp.registry (experimental).', + ) + .option('--config ', `path to ${DEFAULT_CONFIG_FILENAME}`) + .option('--env-file ', ENV_FILE_HELP) + .option('--output ', 'output path', 'server.json') + .option('--force', 'overwrite an existing output file', false) + .action(async (opts: { config?: string; output: string; force: boolean }) => { + process.exitCode = await runExportMcpRegistry( + { + ...(opts.config !== undefined ? { configPath: opts.config } : {}), + output: opts.output, + force: opts.force, + }, + io, + ); + }); + program .command('demo') .description( diff --git a/src/config/schema/mcp-registry.ts b/src/config/schema/mcp-registry.ts new file mode 100644 index 0000000..4522ddc --- /dev/null +++ b/src/config/schema/mcp-registry.ts @@ -0,0 +1,59 @@ +// MCP Registry field rules for `protocols.mcp.registry`, based on +// `modelcontextprotocol/registry@115f8522`, `internal/validators/validators.go` +import { z } from 'zod'; + +// `serverNameRegex`: one slash, and at least two characters on each side +const SERVER_NAME = /^[a-zA-Z0-9][a-zA-Z0-9.-]*[a-zA-Z0-9]\/[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$/; + +// Preserve the upstream range patterns. RE2's `\s` matches [\t\n\f\r ], +// a narrower set than JavaScript's. +const re2 = (source: string) => + new RegExp(source.replaceAll(String.raw`\s`, String.raw`[\t\n\f\r ]`)); +const RANGES = [ + // `comparatorRangeRe`, `hyphenRangeRe`, `orRangeRe` + String.raw`^\s*(?:\^|~|>=|<=|>|<|=)\s*v?\d+(?:\.\d+){0,3}(?:-[0-9A-Za-z.-]+)?\s*$`, + String.raw`^\s*v?\d+(?:\.\d+){0,3}(?:-[0-9A-Za-z.-]+)?\s-\s*v?\d+(?:\.\d+){0,3}(?:-[0-9A-Za-z.-]+)?\s*$`, + String.raw`^\s*(?:v?\d+(?:\.\d+){0,3}(?:-[0-9A-Za-z.-]+)?\s*)(?:\|\|\s*v?\d+(?:\.\d+){0,3}(?:-[0-9A-Za-z.-]+)?\s*)+$`, +].map(re2); +// `dottedVersionLikeRe` +const DOTTED_VERSION_LIKE = re2( + String.raw`^\s*(?:v?\d+|x|X|\*)(?:\.(?:\d+|x|X|\*)){1,2}(?:-[0-9A-Za-z.-]+)?\s*$`, +); + +// Match `looksLikeVersionRange`: a dotted version containing `x`, `X` or `*` +// counts as a range, even in the prerelease part of `1.0.0-next.1` +function looksLikeVersionRange(version: string): boolean { + // Go's strings.TrimSpace trims Unicode White_Space + const trimmed = version.replace(/^\p{White_Space}+|\p{White_Space}+$/gu, ''); + if (trimmed === '') return false; + if (RANGES.some((range) => range.test(trimmed))) return true; + return DOTTED_VERSION_LIKE.test(trimmed) && /[xX*]/.test(trimmed); +} + +// Lengths in code points, as JSON Schema and the registry count them +const codePoints = (min: number, max: number) => + z.string().refine( + (value) => { + const length = [...value].length; + return length >= min && length <= max; + }, + { message: `must be ${min} to ${max} characters` }, + ); + +export const McpRegistrySchema = z + .object({ + name: z.string().max(200).regex(SERVER_NAME, { + message: + 'must be a namespace and a name joined by one "/", such as io.github.acme/weather. Each side has at least 2 characters and starts and ends with a letter or digit; the namespace may also hold "." and "-", the name ".", "_" and "-".', + }), + version: codePoints(1, 255) + .refine((value) => value !== 'latest', { + message: 'must not be "latest", which the MCP Registry reserves', + }) + .refine((value) => !looksLikeVersionRange(value), { + message: + 'must name one version, not a range such as ^1.2.3, 1.x or 1.0 - 2.0. The MCP Registry also reads a dotted version holding x, X or * anywhere, such as 1.0.0-next.1, as a range.', + }), + description: codePoints(1, 100), + }) + .strict(); diff --git a/src/config/schema/normalize.ts b/src/config/schema/normalize.ts index 28d0dda..fc2caa4 100644 --- a/src/config/schema/normalize.ts +++ b/src/config/schema/normalize.ts @@ -21,6 +21,7 @@ export function normalize(raw: RawConfig): GatewayConfig { mcp: { enabled: toBoolean(raw.protocols.mcp.enabled, 'protocols.mcp.enabled'), mountPath: raw.protocols.mcp.mountPath, + ...(raw.protocols.mcp.registry !== undefined ? { registry: raw.protocols.mcp.registry } : {}), }, a2a: { enabled: toBoolean(raw.protocols.a2a?.enabled ?? false, 'protocols.a2a.enabled'), diff --git a/src/config/schema/raw.ts b/src/config/schema/raw.ts index fd06f9c..090e93c 100644 --- a/src/config/schema/raw.ts +++ b/src/config/schema/raw.ts @@ -2,6 +2,7 @@ import { z } from 'zod'; import { X402_PAYMENT_FLOWS } from '../../payments/x402/payment-flow'; import { ACP_WELL_KNOWN_PATH } from '../../protocols/acp/constants'; +import { McpRegistrySchema } from './mcp-registry'; export const SUPPORTED_CONFIG_VERSION = 1; @@ -163,6 +164,9 @@ const ProtocolsSchema = z .object({ enabled: BooleanOrString, mountPath: MountPathSchema, + // Experimental metadata for `export mcp-registry` and `doctor --registry`. + // Validated at config load; unused by the MCP adapter. + registry: McpRegistrySchema.optional(), }) .strict(), // Optional; A2A is off unless configured diff --git a/src/config/schema/types.ts b/src/config/schema/types.ts index 1b3e374..7eb36ae 100644 --- a/src/config/schema/types.ts +++ b/src/config/schema/types.ts @@ -68,7 +68,7 @@ export interface GatewayConfig { readonly storage: { readonly receipts: { readonly driver: 'sqlite'; readonly path: string } }; readonly protocols: { readonly http: { readonly enabled: boolean }; - readonly mcp: { readonly enabled: boolean; readonly mountPath: string }; + readonly mcp: McpProtocolConfig; readonly a2a: { readonly enabled: boolean; readonly mountPath: string }; readonly acp: AcpProtocolConfig; }; @@ -151,9 +151,24 @@ export interface GatewayConfig { readonly authorization?: { readonly ap2: Ap2AuthorizationConfig }; } +/** `protocols.mcp` after normalization */ +export interface McpProtocolConfig { + readonly enabled: boolean; + readonly mountPath: string; + /** + * Experimental listing fields for `agent-commerce export mcp-registry` and + * `doctor --registry`; the MCP adapter does not use them + */ + readonly registry?: { + readonly name: string; + readonly version: string; + readonly description: string; + }; +} + export interface NormalizedProtocols { readonly http: { readonly enabled: boolean }; - readonly mcp: { readonly enabled: boolean; readonly mountPath: string }; + readonly mcp: McpProtocolConfig; readonly a2a: { readonly enabled: boolean; readonly mountPath: string }; readonly acp: AcpProtocolConfig; } diff --git a/tests/fixtures/mcp-registry/2025-12-11/server.schema.json b/tests/fixtures/mcp-registry/2025-12-11/server.schema.json new file mode 100644 index 0000000..9f6469b --- /dev/null +++ b/tests/fixtures/mcp-registry/2025-12-11/server.schema.json @@ -0,0 +1,574 @@ +{ + "$comment": "This file is auto-generated from docs/reference/api/openapi.yaml. Do not edit manually. Run 'make generate-schema' to update.", + "$id": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", + "$ref": "#/definitions/ServerDetail", + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "Argument": { + "anyOf": [ + { + "$ref": "#/definitions/PositionalArgument" + }, + { + "$ref": "#/definitions/NamedArgument" + } + ], + "description": "Warning: Arguments construct command-line parameters that may contain user-provided input. This creates potential command injection risks if clients execute commands in a shell environment. For example, a malicious argument value like ';rm -rf ~/Development' could execute dangerous commands. Clients should prefer non-shell execution methods (e.g., posix_spawn) when possible to eliminate injection risks entirely. Where not possible, clients should obtain consent from users or agents to run the resolved command before execution." + }, + "Icon": { + "description": "An optionally-sized icon that can be displayed in a user interface.", + "properties": { + "mimeType": { + "description": "Optional MIME type override if the source MIME type is missing or generic. Must be one of: image/png, image/jpeg, image/jpg, image/svg+xml, image/webp.", + "enum": [ + "image/png", + "image/jpeg", + "image/jpg", + "image/svg+xml", + "image/webp" + ], + "example": "image/png", + "type": "string" + }, + "sizes": { + "description": "Optional array of strings that specify sizes at which the icon can be used. Each string should be in WxH format (e.g., '48x48', '96x96') or 'any' for scalable formats like SVG. If not provided, the client should assume that the icon can be used at any size.", + "examples": [ + [ + "48x48", + "96x96" + ], + [ + "any" + ] + ], + "items": { + "pattern": "^(\\d+x\\d+|any)$", + "type": "string" + }, + "type": "array" + }, + "src": { + "description": "A standard URI pointing to an icon resource. Must be an HTTPS URL. Consumers SHOULD take steps to ensure URLs serving icons are from the same domain as the server or a trusted domain. Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain executable JavaScript.", + "example": "https://example.com/icon.png", + "format": "uri", + "maxLength": 255, + "type": "string" + }, + "theme": { + "description": "Optional specifier for the theme this icon is designed for. 'light' indicates the icon is designed to be used with a light background, and 'dark' indicates the icon is designed to be used with a dark background. If not provided, the client should assume the icon can be used with any theme.", + "enum": [ + "light", + "dark" + ], + "type": "string" + } + }, + "required": [ + "src" + ], + "type": "object" + }, + "Input": { + "properties": { + "choices": { + "description": "A list of possible values for the input. If provided, the user must select one of these values.", + "example": [], + "items": { + "type": "string" + }, + "type": "array" + }, + "default": { + "description": "The default value for the input. This should be a valid value for the input. If you want to provide input examples or guidance, use the `placeholder` field instead.", + "type": "string" + }, + "description": { + "description": "A description of the input, which clients can use to provide context to the user.", + "type": "string" + }, + "format": { + "default": "string", + "description": "Specifies the input format. Supported values include `filepath`, which should be interpreted as a file on the user's filesystem.\n\nWhen the input is converted to a string, booleans should be represented by the strings \"true\" and \"false\", and numbers should be represented as decimal values.", + "enum": [ + "string", + "number", + "boolean", + "filepath" + ], + "type": "string" + }, + "isRequired": { + "default": false, + "type": "boolean" + }, + "isSecret": { + "default": false, + "description": "Indicates whether the input is a secret value (e.g., password, token). If true, clients should handle the value securely.", + "type": "boolean" + }, + "placeholder": { + "description": "A placeholder for the input to be displaying during configuration. This is used to provide examples or guidance about the expected form or content of the input.", + "type": "string" + }, + "value": { + "description": "The value for the input. If this is not set, the user may be prompted to provide a value. If a value is set, it should not be configurable by end users.\n\nIdentifiers wrapped in `{curly_braces}` will be replaced with the corresponding properties from the input `variables` map. If an identifier in braces is not found in `variables`, or if `variables` is not provided, the `{curly_braces}` substring should remain unchanged.\n", + "type": "string" + } + }, + "type": "object" + }, + "InputWithVariables": { + "allOf": [ + { + "$ref": "#/definitions/Input" + }, + { + "properties": { + "variables": { + "additionalProperties": { + "$ref": "#/definitions/Input" + }, + "description": "A map of variable names to their values. Keys in the input `value` that are wrapped in `{curly_braces}` will be replaced with the corresponding variable values.", + "type": "object" + } + }, + "type": "object" + } + ] + }, + "KeyValueInput": { + "allOf": [ + { + "$ref": "#/definitions/InputWithVariables" + }, + { + "properties": { + "name": { + "description": "Name of the header or environment variable.", + "example": "SOME_VARIABLE", + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + } + ] + }, + "LocalTransport": { + "anyOf": [ + { + "$ref": "#/definitions/StdioTransport" + }, + { + "$ref": "#/definitions/StreamableHttpTransport" + }, + { + "$ref": "#/definitions/SseTransport" + } + ], + "description": "Transport protocol configuration for local/package context" + }, + "NamedArgument": { + "allOf": [ + { + "$ref": "#/definitions/InputWithVariables" + }, + { + "properties": { + "isRepeated": { + "default": false, + "description": "Whether the argument can be repeated multiple times.", + "type": "boolean" + }, + "name": { + "description": "The flag name, including any leading dashes.", + "example": "--port", + "type": "string" + }, + "type": { + "enum": [ + "named" + ], + "example": "named", + "type": "string" + } + }, + "required": [ + "type", + "name" + ], + "type": "object" + } + ], + "description": "A command-line `--flag={value}`." + }, + "Package": { + "properties": { + "environmentVariables": { + "description": "A mapping of environment variables to be set when running the package.", + "items": { + "$ref": "#/definitions/KeyValueInput" + }, + "type": "array" + }, + "fileSha256": { + "description": "SHA-256 hash of the package file for integrity verification. Required for MCPB packages and optional for other package types. Authors are responsible for generating correct SHA-256 hashes when creating server.json. If present, MCP clients must validate the downloaded file matches the hash before running packages to ensure file integrity.", + "example": "fe333e598595000ae021bd27117db32ec69af6987f507ba7a63c90638ff633ce", + "pattern": "^[a-f0-9]{64}$", + "type": "string" + }, + "identifier": { + "description": "Package identifier - either a package name (for registries) or URL (for direct downloads)", + "examples": [ + "@modelcontextprotocol/server-brave-search", + "https://github.com/example/releases/download/v1.0.0/package.mcpb" + ], + "type": "string" + }, + "packageArguments": { + "description": "A list of arguments to be passed to the package's binary.", + "items": { + "$ref": "#/definitions/Argument" + }, + "type": "array" + }, + "registryBaseUrl": { + "description": "Base URL of the package registry", + "examples": [ + "https://registry.npmjs.org", + "https://pypi.org", + "https://docker.io", + "https://api.nuget.org/v3/index.json", + "https://github.com", + "https://gitlab.com" + ], + "format": "uri", + "type": "string" + }, + "registryType": { + "description": "Registry type indicating how to download packages (e.g., 'npm', 'pypi', 'oci', 'nuget', 'mcpb')", + "examples": [ + "npm", + "pypi", + "oci", + "nuget", + "mcpb" + ], + "type": "string" + }, + "runtimeArguments": { + "description": "A list of arguments to be passed to the package's runtime command (such as docker or npx). The `runtimeHint` field should be provided when `runtimeArguments` are present.", + "items": { + "$ref": "#/definitions/Argument" + }, + "type": "array" + }, + "runtimeHint": { + "description": "A hint to help clients determine the appropriate runtime for the package. This field should be provided when `runtimeArguments` are present.", + "examples": [ + "npx", + "uvx", + "docker", + "dnx" + ], + "type": "string" + }, + "transport": { + "$ref": "#/definitions/LocalTransport", + "description": "Transport protocol configuration for the package" + }, + "version": { + "description": "Package version. Must be a specific version. Version ranges are rejected (e.g., '^1.2.3', '~1.2.3', '\u003e=1.2.3', '1.x', '1.*').", + "example": "1.0.2", + "minLength": 1, + "not": { + "const": "latest" + }, + "type": "string" + } + }, + "required": [ + "registryType", + "identifier", + "transport" + ], + "type": "object" + }, + "PositionalArgument": { + "allOf": [ + { + "$ref": "#/definitions/InputWithVariables" + }, + { + "anyOf": [ + { + "required": [ + "valueHint" + ] + }, + { + "required": [ + "value" + ] + } + ], + "properties": { + "isRepeated": { + "default": false, + "description": "Whether the argument can be repeated multiple times in the command line.", + "type": "boolean" + }, + "type": { + "enum": [ + "positional" + ], + "example": "positional", + "type": "string" + }, + "valueHint": { + "description": "An identifier for the positional argument. It is not part of the command line. It may be used by client configuration as a label identifying the argument. It is also used to identify the value in transport URL variable substitution.", + "example": "file_path", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + } + ], + "description": "A positional input is a value inserted verbatim into the command line." + }, + "RemoteTransport": { + "allOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/StreamableHttpTransport" + }, + { + "$ref": "#/definitions/SseTransport" + } + ] + }, + { + "properties": { + "variables": { + "additionalProperties": { + "$ref": "#/definitions/Input" + }, + "description": "Configuration variables that can be referenced in URL template {curly_braces}. The key is the variable name, and the value defines the variable properties.", + "type": "object" + } + }, + "type": "object" + } + ], + "description": "Transport protocol configuration for remote context - extends StreamableHttpTransport or SseTransport with variables" + }, + "Repository": { + "description": "Repository metadata for the MCP server source code. Enables users and security experts to inspect the code, improving transparency.", + "properties": { + "id": { + "description": "Repository identifier from the hosting service (e.g., GitHub repo ID). Owned and determined by the source forge. Should remain stable across repository renames and may be used to detect repository resurrection attacks - if a repository is deleted and recreated, the ID should change. For GitHub, use: gh api repos/\u003cowner\u003e/\u003crepo\u003e --jq '.id'", + "example": "b94b5f7e-c7c6-d760-2c78-a5e9b8a5b8c9", + "type": "string" + }, + "source": { + "description": "Repository hosting service identifier. Used by registries to determine validation and API access methods.", + "example": "github", + "type": "string" + }, + "subfolder": { + "description": "Optional relative path from repository root to the server location within a monorepo or nested package structure. Must be a clean relative path.", + "example": "src/everything", + "type": "string" + }, + "url": { + "description": "Repository URL for browsing source code. Should support both web browsing and git clone operations.", + "example": "https://github.com/modelcontextprotocol/servers", + "format": "uri", + "type": "string" + } + }, + "required": [ + "url", + "source" + ], + "type": "object" + }, + "ServerDetail": { + "description": "Schema for a static representation of an MCP server. Used in various contexts related to discovery, installation, and configuration.", + "properties": { + "$schema": { + "description": "JSON Schema URI for this server.json format", + "example": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", + "format": "uri", + "type": "string" + }, + "_meta": { + "description": "Extension metadata using reverse DNS namespacing for vendor-specific data", + "properties": { + "io.modelcontextprotocol.registry/publisher-provided": { + "additionalProperties": true, + "description": "Publisher-provided metadata for downstream registries", + "example": { + "buildInfo": { + "commit": "abc123def456", + "pipelineId": "build-789", + "timestamp": "2023-12-01T10:30:00Z" + }, + "tool": "publisher-cli", + "version": "1.2.3" + }, + "type": "object" + } + }, + "type": "object" + }, + "description": { + "description": "Clear human-readable explanation of server functionality. Should focus on capabilities, not implementation details.", + "example": "MCP server providing weather data and forecasts via OpenWeatherMap API", + "maxLength": 100, + "minLength": 1, + "type": "string" + }, + "icons": { + "description": "Optional set of sized icons that the client can display in a user interface. Clients that support rendering icons MUST support at least the following MIME types: image/png and image/jpeg (safe, universal compatibility). Clients SHOULD also support: image/svg+xml (scalable but requires security precautions) and image/webp (modern, efficient format).", + "items": { + "$ref": "#/definitions/Icon" + }, + "type": "array" + }, + "name": { + "description": "Server name in reverse-DNS format. Must contain exactly one forward slash separating namespace from server name.", + "example": "io.github.user/weather", + "maxLength": 200, + "minLength": 3, + "pattern": "^[a-zA-Z0-9.-]+/[a-zA-Z0-9._-]+$", + "type": "string" + }, + "packages": { + "items": { + "$ref": "#/definitions/Package" + }, + "type": "array" + }, + "remotes": { + "items": { + "$ref": "#/definitions/RemoteTransport" + }, + "type": "array" + }, + "repository": { + "$ref": "#/definitions/Repository", + "description": "Optional repository metadata for the MCP server source code. Recommended for transparency and security inspection." + }, + "title": { + "description": "Optional human-readable title or display name for the MCP server. MCP subregistries or clients MAY choose to use this for display purposes.", + "example": "Weather API", + "maxLength": 100, + "minLength": 1, + "type": "string" + }, + "version": { + "description": "Version string for this server. SHOULD follow semantic versioning (e.g., '1.0.2', '2.1.0-alpha'). Equivalent of Implementation.version in MCP specification. Non-semantic versions are allowed but may not sort predictably. Version ranges are rejected (e.g., '^1.2.3', '~1.2.3', '\u003e=1.2.3', '1.x', '1.*').", + "example": "1.0.2", + "maxLength": 255, + "type": "string" + }, + "websiteUrl": { + "description": "Optional URL to the server's homepage, documentation, or project website. This provides a central link for users to learn more about the server. Particularly useful when the server has custom installation instructions or setup requirements.", + "example": "https://modelcontextprotocol.io/examples", + "format": "uri", + "type": "string" + } + }, + "required": [ + "name", + "description", + "version" + ], + "type": "object" + }, + "SseTransport": { + "properties": { + "headers": { + "description": "HTTP headers to include", + "items": { + "$ref": "#/definitions/KeyValueInput" + }, + "type": "array" + }, + "type": { + "description": "Transport type", + "enum": [ + "sse" + ], + "example": "sse", + "type": "string" + }, + "url": { + "description": "Server-Sent Events endpoint URL template. Variables in {curly_braces} are resolved based on context: In Package context, they reference argument valueHints, argument names, or environment variable names from the parent Package. In Remote context, they reference variables from the transport's 'variables' object. After variable substitution, this should produce a valid URI.", + "example": "https://mcp-fs.example.com/sse", + "pattern": "^https?://[^\\s]+$", + "type": "string" + } + }, + "required": [ + "type", + "url" + ], + "type": "object" + }, + "StdioTransport": { + "properties": { + "type": { + "description": "Transport type", + "enum": [ + "stdio" + ], + "example": "stdio", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + "StreamableHttpTransport": { + "properties": { + "headers": { + "description": "HTTP headers to include", + "items": { + "$ref": "#/definitions/KeyValueInput" + }, + "type": "array" + }, + "type": { + "description": "Transport type", + "enum": [ + "streamable-http" + ], + "example": "streamable-http", + "type": "string" + }, + "url": { + "description": "URL template for the streamable-http transport. Variables in {curly_braces} are resolved based on context: In Package context, they reference argument valueHints, argument names, or environment variable names from the parent Package. In Remote context, they reference variables from the transport's 'variables' object. After variable substitution, this should produce a valid URI.", + "example": "https://api.example.com/mcp", + "pattern": "^https?://[^\\s]+$", + "type": "string" + } + }, + "required": [ + "type", + "url" + ], + "type": "object" + } + }, + "title": "server.json defining a Model Context Protocol (MCP) server" +} diff --git a/tests/unit/cli/doctor-registry.test.ts b/tests/unit/cli/doctor-registry.test.ts new file mode 100644 index 0000000..2e83313 --- /dev/null +++ b/tests/unit/cli/doctor-registry.test.ts @@ -0,0 +1,308 @@ +// `doctor --registry`: the live MCP Registry listing compared with config, through a fake fetch +import { describe, expect, it } from 'vitest'; +import { printDoctorReport, runDoctor } from '../../../src/cli/commands/doctor'; +import type { GatewayConfig } from '../../../src/cli/lib/config-client'; +import type { FetchLike } from '../../../src/cli/lib/http'; +import { CommerceError } from '../../../src/core'; +import { + createCapturingIo, + createFakeFetch, + fetchFailed, + jsonResponse, + makeFakeReceiptStore, + makeGatewayConfig, +} from './fixtures'; + +const GATEWAY = 'http://127.0.0.1:8080'; +const LISTING_URL = + 'https://registry.modelcontextprotocol.io/v0.1/servers/io.github.acme%2Fweather/versions/latest'; +const REGISTRY = { + name: 'io.github.acme/weather', + version: '1.0.0', + description: 'Weather forecasts, paid per call', +}; + +function config( + options: { publicBaseUrl?: string; mcp?: GatewayConfig['protocols']['mcp'] } = {}, +): GatewayConfig { + const base = makeGatewayConfig(); + return makeGatewayConfig({ + merchant: { + ...base.merchant, + publicBaseUrl: options.publicBaseUrl ?? 'https://api.example.com', + }, + protocols: { + ...base.protocols, + mcp: options.mcp ?? { enabled: true, mountPath: '/mcp', registry: REGISTRY }, + }, + }); +} + +// A registry response for an exported and published listing +function listing( + server: Record = {}, + official: Record = { status: 'active' }, +): Record { + return { + server: { + $schema: 'https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json', + ...REGISTRY, + remotes: [{ type: 'streamable-http', url: 'https://api.example.com/mcp' }], + ...server, + }, + _meta: { + 'io.modelcontextprotocol.registry/official': { + publishedAt: '2026-11-01T00:00:00Z', + updatedAt: '2026-11-01T00:00:00Z', + isLatest: true, + ...official, + }, + }, + }; +} + +// Record requests to a healthy gateway and backend. The optional `registry` +// handler answers the listing URL; without it, that request rejects as unreachable. +function fakeFetch(registry?: () => Response) { + const requests: { url: string; init: RequestInit | undefined }[] = []; + const inner = createFakeFetch({ + [`${GATEWAY}/health`]: () => jsonResponse({ status: 'ok' }), + [`${GATEWAY}/ready`]: () => jsonResponse({ status: 'ready' }), + [`${GATEWAY}/.well-known/agent-commerce`]: () => jsonResponse({ merchant: { id: 'm' } }), + 'http://localhost:3000/api/weather/demo-check': () => jsonResponse({}), + ...(registry !== undefined ? { [LISTING_URL]: registry } : {}), + }); + const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => { + requests.push({ url: String(input), init }); + return inner(input, init); + }) as FetchLike; + return { fetchImpl, requests }; +} + +async function doctor(options: { + registry?: boolean; + config?: GatewayConfig | Error; + answer?: (() => Response) | undefined; +}) { + const { fetchImpl, requests } = fakeFetch(options.answer); + const loaded = options.config ?? config(); + const report = await runDoctor( + { + gatewayUrl: GATEWAY, + ...(options.registry !== undefined ? { registry: options.registry } : {}), + }, + { + fetchImpl, + loadConfig: async () => { + if (loaded instanceof Error) throw loaded; + return loaded; + }, + createStore: () => makeFakeReceiptStore(), + fillEnvFromManifest: (env) => ({ env, filled: [], manifestFound: false }), + hasChainDeployScript: () => false, + }, + ); + return { + report, + check: report.checks.find((c) => c.name === 'MCP Registry'), + registryRequests: requests.filter((r) => r.url.startsWith('https://registry.')), + }; +} + +describe('doctor --registry', () => { + it('adds no check and sends nothing to the registry without the flag', async () => { + const { check, registryRequests } = await doctor({ answer: () => jsonResponse(listing()) }); + expect(check).toBeUndefined(); + expect(registryRequests).toEqual([]); + }); + + it('asks for the configured name only, with no header or body', async () => { + const { registryRequests } = await doctor({ + registry: true, + answer: () => jsonResponse(listing()), + }); + expect(registryRequests).toHaveLength(1); + expect(registryRequests[0]?.url).toBe(LISTING_URL); + expect(Object.keys(registryRequests[0]?.init ?? {})).toEqual(['signal']); + }); + + it.each([ + [ + 'a listing that matches', + () => jsonResponse(listing()), + 'PASS', + 'io.github.acme/weather 1.0.0 is listed as configured', + ], + [ + 'another latest version', + () => jsonResponse(listing({ version: '0.9.0' })), + 'WARN', + 'io.github.acme/weather: listing differs from config in version', + ], + [ + 'another description and remote URL', + () => + jsonResponse( + listing({ + description: 'Old text', + remotes: [{ type: 'streamable-http', url: 'https://old.example.com/mcp' }], + }), + ), + 'WARN', + 'io.github.acme/weather: listing differs from config in description, remotes', + ], + [ + 'a second remote', + () => + jsonResponse( + listing({ + remotes: [ + { type: 'streamable-http', url: 'https://api.example.com/mcp' }, + { type: 'sse', url: 'https://api.example.com/sse' }, + ], + }), + ), + 'WARN', + 'io.github.acme/weather: listing differs from config in remotes', + ], + // The gateway URL under another server's name is not the merchant's listing + [ + 'a listing under another name', + () => jsonResponse(listing({ name: 'io.github.other/weather' })), + 'WARN', + 'io.github.acme/weather: listing differs from config in name', + ], + [ + 'a deprecated listing', + () => jsonResponse(listing({}, { status: 'deprecated' })), + 'WARN', + 'io.github.acme/weather: listing is deprecated', + ], + [ + 'a deleted listing', + () => jsonResponse(listing({}, { status: 'deleted' })), + 'WARN', + 'io.github.acme/weather: listing is deleted', + ], + [ + 'a listing with no status', + () => jsonResponse({ server: listing()['server'] }), + 'WARN', + 'io.github.acme/weather: listing has no known status', + ], + [ + 'a name it does not list', + () => jsonResponse({ title: 'Not Found' }, 404), + 'WARN', + 'io.github.acme/weather is not listed', + ], + ['a server error', () => jsonResponse({}, 503), 'WARN', 'the registry answered HTTP 503'], + [ + 'an answer that is not a listing', + () => jsonResponse(['io.github.acme/weather']), + 'WARN', + 'the registry answer is not a server listing', + ], + ])('reports %s', async (_label, answer, status, detail) => { + const { check } = await doctor({ registry: true, answer }); + expect(check).toEqual({ name: 'MCP Registry', status, detail }); + }); + + it('marks no answer as unreachable', async () => { + const { check } = await doctor({ registry: true }); + expect(check).toEqual({ + name: 'MCP Registry', + status: 'WARN', + detail: 'no answer from the registry', + undetermined: 'unreachable', + }); + }); + + it('leaves a TLS failure unmarked and does not print its message', async () => { + const { report, check } = await doctor({ + registry: true, + answer: () => { + throw fetchFailed( + 'ERR_TLS_CERT_ALTNAME_INVALID', + "Host is not in the cert's altnames: DNS:EVIL-CERT-NAME", + ); + }, + }); + expect(check).toEqual({ + name: 'MCP Registry', + status: 'WARN', + detail: 'the registry request failed', + }); + expect(JSON.stringify(report)).not.toContain('EVIL-CERT-NAME'); + }); + + it('prints no value from a hostile answer, in text or JSON', async () => { + const HOSTILE = '\u001b[31mHOSTILE\nPASS Config'; + const { report } = await doctor({ + registry: true, + answer: () => + jsonResponse({ + server: { + name: HOSTILE, + version: HOSTILE, + description: HOSTILE, + remotes: [{ type: HOSTILE, url: HOSTILE }], + [HOSTILE]: HOSTILE, + }, + _meta: { 'io.modelcontextprotocol.registry/official': { status: HOSTILE } }, + }), + }); + const text = createCapturingIo(); + printDoctorReport(report, text, false); + const json = createCapturingIo(); + printDoctorReport(report, json, true); + + expect(report.checks.find((c) => c.name === 'MCP Registry')?.detail).toBe( + 'io.github.acme/weather: listing has no known status; listing differs from config in name, version, description, remotes', + ); + for (const output of [text.out.join('\n'), json.out.join('\n')]) { + expect(output).not.toContain('HOSTILE'); + expect(output).not.toContain('\u001b[31m'); + } + }); + + it.each([ + ['a listing that matches', () => jsonResponse(listing())], + ['a deleted listing', () => jsonResponse(listing({}, { status: 'deleted' }))], + ['no answer', undefined], + ])('keeps the exit code of a run without the flag for %s', async (_label, answer) => { + const without = await doctor({ answer }); + const withFlag = await doctor({ registry: true, answer }); + expect(withFlag.check?.status).not.toBe('FAIL'); + expect(withFlag.report.exitCode).toBe(without.report.exitCode); + }); + + it.each([ + [ + 'config that does not load', + new CommerceError('CONFIG_INVALID', 'bad config'), + { status: 'WARN', detail: 'skipped: config invalid', undetermined: 'skipped' }, + ], + [ + 'no registry block', + config({ mcp: { enabled: true, mountPath: '/mcp' } }), + { status: 'INFO', detail: 'protocols.mcp.registry not configured' }, + ], + [ + 'an http public URL', + config({ publicBaseUrl: 'http://api.example.com' }), + { + status: 'WARN', + detail: 'merchant.publicBaseUrl must be an https:// URL: the MCP Registry refuses others', + }, + ], + ])('sends nothing for %s', async (_label, loaded, expected) => { + const { check, registryRequests } = await doctor({ + registry: true, + config: loaded, + answer: () => jsonResponse(listing()), + }); + expect(check).toEqual({ name: 'MCP Registry', ...expected }); + expect(registryRequests).toEqual([]); + }); +}); diff --git a/tests/unit/cli/export-mcp-registry.test.ts b/tests/unit/cli/export-mcp-registry.test.ts new file mode 100644 index 0000000..d97e0ed --- /dev/null +++ b/tests/unit/cli/export-mcp-registry.test.ts @@ -0,0 +1,136 @@ +// `agent-commerce export mcp-registry`: what it writes, and when it writes nothing +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { runExportMcpRegistry } from '../../../src/cli/commands/export-mcp-registry'; +import type { GatewayConfig } from '../../../src/cli/lib/config-client'; +import { CommerceError } from '../../../src/core'; +import { createCapturingIo, makeGatewayConfig } from './fixtures'; + +const dirs: string[] = []; +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); +function outputPath(): string { + const dir = mkdtempSync(join(tmpdir(), 'agent-commerce-export-')); + dirs.push(dir); + return join(dir, 'server.json'); +} + +const REGISTRY = { + name: 'io.github.acme/weather', + version: '2.0.1', + description: 'Weather forecasts, paid per call', +}; + +function config(mcp: GatewayConfig['protocols']['mcp']): GatewayConfig { + const base = makeGatewayConfig(); + return makeGatewayConfig({ + merchant: { ...base.merchant, publicBaseUrl: 'https://api.example.com' }, + protocols: { ...base.protocols, mcp }, + }); +} +const LISTABLE = config({ enabled: true, mountPath: '/mcp', registry: REGISTRY }); + +async function run( + options: { output: string; force?: boolean }, + loadConfig: () => Promise = async () => LISTABLE, +) { + const io = createCapturingIo(); + const load = vi.fn(loadConfig); + const code = await runExportMcpRegistry(options, io, { loadConfig: load }); + return { code, io, load }; +} + +describe('export mcp-registry', () => { + it('writes server.json with $schema first and reports the listing', async () => { + const output = outputPath(); + + const { code, io } = await run({ output }); + + expect(code).toBe(0); + const content = readFileSync(output, 'utf8'); + expect(JSON.parse(content)).toEqual({ + $schema: 'https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json', + name: 'io.github.acme/weather', + description: 'Weather forecasts, paid per call', + version: '2.0.1', + remotes: [{ type: 'streamable-http', url: 'https://api.example.com/mcp' }], + }); + expect(content.startsWith('{\n "$schema": ')).toBe(true); + expect(content.endsWith('}\n')).toBe(true); + expect(io.out).toEqual([ + `Wrote ${output} for io.github.acme/weather 2.0.1.`, + 'Publish it with mcp-publisher after verifying the namespace.', + ]); + expect(io.err).toEqual([]); + }); + + it('refuses an existing file without --force, before reading config', async () => { + const output = outputPath(); + writeFileSync(output, 'keep me\n', 'utf8'); + + const { code, io, load } = await run({ output }); + + expect(code).toBe(1); + expect(io.err).toEqual([`FAIL ${output} already exists. Re-run with --force to overwrite.`]); + expect(readFileSync(output, 'utf8')).toBe('keep me\n'); + expect(load).not.toHaveBeenCalled(); + }); + + it('replaces an existing file with --force', async () => { + const output = outputPath(); + writeFileSync(output, 'replace me\n', 'utf8'); + + const { code } = await run({ output, force: true }); + + expect(code).toBe(0); + expect(JSON.parse(readFileSync(output, 'utf8'))).toMatchObject({ version: '2.0.1' }); + }); + + it('writes nothing when a registry rule fails, naming each key', async () => { + const output = outputPath(); + + const { code, io } = await run({ output }, async () => + config({ enabled: false, mountPath: '/mcp' }), + ); + + expect(code).toBe(1); + expect(io.err).toEqual([ + 'FAIL protocols.mcp.enabled is false: the listing would name a server that does not run', + 'FAIL protocols.mcp.registry is not set: it holds the listing name, version and description', + ]); + expect(existsSync(output)).toBe(false); + }); + + it('fails naming the path when the file cannot be written', async () => { + // A regular file where the output directory should be + const blocker = outputPath(); + writeFileSync(blocker, 'not a directory\n', 'utf8'); + const output = join(blocker, 'server.json'); + + const { code, io } = await run({ output }); + + expect(code).toBe(1); + expect(io.err).toHaveLength(1); + expect(io.err[0]).toMatch(new RegExp(`^FAIL ${output} could not be written: `)); + expect(io.out).toEqual([]); + }); + + it('writes nothing when config fails to load', async () => { + const output = outputPath(); + + const { code, io } = await run({ output }, async () => { + throw new CommerceError('CONFIG_INVALID', 'Configuration invalid at "protocols.mcp"', { + details: { path: 'protocols.mcp' }, + }); + }); + + expect(code).toBe(1); + expect(io.err.join('\n')).toContain( + 'FAIL CONFIG_INVALID: Configuration invalid at "protocols.mcp"', + ); + expect(existsSync(output)).toBe(false); + }); +}); diff --git a/tests/unit/cli/import-openapi.test.ts b/tests/unit/cli/import-openapi.test.ts index 6651536..930cb45 100644 --- a/tests/unit/cli/import-openapi.test.ts +++ b/tests/unit/cli/import-openapi.test.ts @@ -94,6 +94,22 @@ describe('agent-commerce import openapi', () => { expect(readFileSync(output, 'utf8')).toContain('resources:'); }); + it('hands the fragment to an injected writer and writes nothing itself', async () => { + const output = tmpOutput(); + const writes: { path: string; content: string }[] = []; + + const code = await runImportOpenApi( + { source: fixture('responses-3.1.yaml'), output }, + createCapturingIo(), + { writeFile: async (path, content) => void writes.push({ path, content }) }, + ); + + expect(code).toBe(0); + expect(writes.map((write) => write.path)).toEqual([output]); + expect(writes[0]?.content).toContain('# Generated by agent-commerce import openapi'); + expect(existsSync(output)).toBe(false); + }); + it('leaves no temporary file behind', async () => { const output = tmpOutput(); await run({ source: fixture('responses-3.1.yaml'), output }); diff --git a/tests/unit/cli/mcp-registry.test.ts b/tests/unit/cli/mcp-registry.test.ts new file mode 100644 index 0000000..12a1a81 --- /dev/null +++ b/tests/unit/cli/mcp-registry.test.ts @@ -0,0 +1,153 @@ +// `server.json` from config: the pinned schema, where the version comes from, and the registry's URL rules +import { readFileSync } from 'node:fs'; +import Ajv from 'ajv'; +import addFormats from 'ajv-formats'; +import { describe, expect, it } from 'vitest'; +import type { GatewayConfig } from '../../../src/cli/lib/config-client'; +import { type ServerJson, serverJson } from '../../../src/cli/lib/mcp-registry'; +import { PACKAGE_VERSION } from '../../../src/version'; +import { makeGatewayConfig } from './fixtures'; + +const SCHEMA_URL = 'https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json'; +// Byte-identical to modelcontextprotocol/static@a9ba437d +const schema = JSON.parse( + readFileSync( + new URL('../../fixtures/mcp-registry/2025-12-11/server.schema.json', import.meta.url), + 'utf8', + ), +) as { $id: string }; +// Disable strict mode to allow the upstream schema's `example` keyword +const ajv = new Ajv({ strict: false, allErrors: true }); +addFormats(ajv); +const validateServerJson = ajv.compile(schema); + +const REGISTRY = { + name: 'io.github.acme/weather', + version: '1.0.0', + description: 'Weather forecasts, paid per call', +}; +// One code point, two UTF-16 units +const ASTRAL = '\u{1D538}'; + +function config( + options: { publicBaseUrl?: string; mcp?: GatewayConfig['protocols']['mcp'] } = {}, +): GatewayConfig { + const base = makeGatewayConfig(); + return makeGatewayConfig({ + merchant: { + ...base.merchant, + publicBaseUrl: options.publicBaseUrl ?? 'https://api.example.com', + }, + protocols: { + ...base.protocols, + mcp: options.mcp ?? { enabled: true, mountPath: '/mcp', registry: REGISTRY }, + }, + }); +} + +function listed(registry: typeof REGISTRY): ServerJson { + const result = serverJson(config({ mcp: { enabled: true, mountPath: '/mcp', registry } })); + expect(result).toHaveProperty('document'); + return (result as { readonly document: ServerJson }).document; +} + +describe('serverJson', () => { + it('lists the MCP mount under merchant.publicBaseUrl with the configured values', () => { + expect(serverJson(config())).toEqual({ + document: { + $schema: SCHEMA_URL, + name: 'io.github.acme/weather', + description: 'Weather forecasts, paid per call', + version: '1.0.0', + remotes: [{ type: 'streamable-http', url: 'https://api.example.com/mcp' }], + }, + }); + }); + + it('names the schema file the tests validate against', () => { + expect(schema.$id).toBe(SCHEMA_URL); + }); + + it('joins a base path and the mount with one slash, in the URL parser form', () => { + const result = serverJson( + config({ + publicBaseUrl: 'https://API.example.com/shop/', + mcp: { enabled: true, mountPath: '/tools/mcp/', registry: REGISTRY }, + }), + ); + expect(result).toMatchObject({ + document: { remotes: [{ url: 'https://api.example.com/shop/tools/mcp' }] }, + }); + }); + + it('takes the version from config, not from the package', () => { + expect(PACKAGE_VERSION).not.toBe('0.3.1'); + expect(listed({ ...REGISTRY, version: '0.3.1' })['version']).toBe('0.3.1'); + }); + + it.each([ + ['the values above', REGISTRY], + ['a 200-character name', { ...REGISTRY, name: `ab/${'c'.repeat(197)}` }], + ['a 255-character version', { ...REGISTRY, version: `1.0.0-${'a'.repeat(249)}` }], + ['a 100-character description', { ...REGISTRY, description: 'd'.repeat(100) }], + ['100 code points outside the BMP', { ...REGISTRY, description: ASTRAL.repeat(100) }], + ])('validates against the pinned schema with %s', (_label, registry) => { + const document = listed(registry); + expect(validateServerJson(document), JSON.stringify(validateServerJson.errors)).toBe(true); + }); + + // The schema refuses one past each limit config enforces + it.each([ + ['name', `ab/${'c'.repeat(198)}`], + ['version', `1.0.0-${'a'.repeat(250)}`], + ['description', 'd'.repeat(101)], + ['description', ASTRAL.repeat(101)], + ])('the pinned schema refuses %s %#', (field, value) => { + expect(validateServerJson({ ...listed(REGISTRY), [field]: value })).toBe(false); + }); + + it.each([ + [ + 'MCP is disabled', + config({ mcp: { enabled: false, mountPath: '/mcp', registry: REGISTRY } }), + ['protocols.mcp.enabled'], + ], + [ + 'the block is absent', + config({ mcp: { enabled: true, mountPath: '/mcp' } }), + ['protocols.mcp.registry'], + ], + [ + 'an http URL', + config({ publicBaseUrl: 'http://api.example.com' }), + ['merchant.publicBaseUrl'], + ], + ['localhost', config({ publicBaseUrl: 'https://localhost:8443' }), ['merchant.publicBaseUrl']], + ['127.0.0.1', config({ publicBaseUrl: 'https://127.0.0.1' }), ['merchant.publicBaseUrl']], + [ + 'a .localhost name', + config({ publicBaseUrl: 'https://shop.localhost' }), + ['merchant.publicBaseUrl'], + ], + [ + 'a value that is not a URL', + config({ publicBaseUrl: 'api.example.com' }), + ['merchant.publicBaseUrl'], + ], + [ + 'every problem at once', + config({ publicBaseUrl: 'http://localhost', mcp: { enabled: false, mountPath: '/mcp' } }), + ['protocols.mcp.enabled', 'protocols.mcp.registry', 'merchant.publicBaseUrl'], + ], + ])('refuses %s, naming the key', (_label, input, keys) => { + expect(serverJson(input)).toEqual({ + problems: keys.map((key) => ({ key, message: expect.any(String) })), + }); + }); + + it('accepts a private address, as the registry does', () => { + expect(serverJson(config({ publicBaseUrl: 'https://10.0.0.5:8443' }))).toMatchObject({ + document: { remotes: [{ url: 'https://10.0.0.5:8443/mcp' }] }, + }); + }); +}); diff --git a/tests/unit/cli/program.test.ts b/tests/unit/cli/program.test.ts index 406e929..07952a7 100644 --- a/tests/unit/cli/program.test.ts +++ b/tests/unit/cli/program.test.ts @@ -61,6 +61,7 @@ describe('agent-commerce --help', () => { 'backup', 'init', 'import', + 'export', 'demo', ]) { expect(text).toMatch(new RegExp(`^ ${command}\\b`, 'm')); @@ -169,10 +170,10 @@ payments: {} }); // In a real process Node refuses an unreadable path first; see packaging.test.ts - it.each(['validate', 'doctor', 'start', 'reconcile'])( + it.each([['validate'], ['doctor'], ['start'], ['reconcile'], ['export', 'mcp-registry']])( '%s exits 1 naming an env file that cannot be read, before doing anything else', - async (command) => { - const { exitCode, io } = await run([command, '--env-file', '/does/not/exist.env']); + async (...command) => { + const { exitCode, io } = await run([...command, '--env-file', '/does/not/exist.env']); expect(exitCode).toBe(1); expect(io.err.join('\n')).toContain('cannot read --env-file "/does/not/exist.env"'); expect(io.out).toEqual([]); @@ -181,7 +182,7 @@ payments: {} }); describe('agent-commerce doctor', () => { - it('exits 1 and emits JSON when the gateway is unreachable', async () => { + function configFile(): string { const dir = tempDir('agent-commerce-program-'); const configPath = join(dir, 'config.yaml'); const dbPath = join(dir, 'receipts.db').replace(/\\/g, '/'); @@ -198,15 +199,35 @@ payments: {} `, 'utf8', ); + return configPath; + } + const doctorArgs = (configPath: string) => [ + 'doctor', + '--config', + configPath, + '--gateway', + 'http://127.0.0.1:1', + '--json', + ]; + + // Without a registry block, the check reports INFO without a registry request + it('adds the MCP Registry check with --registry', async () => { + const configPath = configFile(); + const without = await run(doctorArgs(configPath)); + const withFlag = await run([...doctorArgs(configPath), '--registry']); + + const registryCheck = (io: { out: string[] }) => + (JSON.parse(io.out.join('')) as DoctorReport).checks.find((c) => c.name === 'MCP Registry'); + expect(registryCheck(without.io)).toBeUndefined(); + expect(registryCheck(withFlag.io)).toEqual({ + name: 'MCP Registry', + status: 'INFO', + detail: 'protocols.mcp.registry not configured', + }); + }); - const { exitCode, io } = await run([ - 'doctor', - '--config', - configPath, - '--gateway', - 'http://127.0.0.1:1', - '--json', - ]); + it('exits 1 and emits JSON when the gateway is unreachable', async () => { + const { exitCode, io } = await run(doctorArgs(configFile())); expect(exitCode).toBe(1); const parsed = JSON.parse(io.out.join('')) as DoctorReport; expect(parsed.exitCode).toBe(1); @@ -219,6 +240,76 @@ payments: {} }); }); +describe('agent-commerce export mcp-registry', () => { + function configFile(dir: string): string { + const configPath = join(dir, 'config.yaml'); + writeFileSync( + configPath, + ` +version: 1 +merchant: { id: demo, name: Demo, publicBaseUrl: https://api.example.com } +server: { port: 8080, host: 0.0.0.0 } +storage: { receipts: { driver: sqlite, path: ./data/receipts.db } } +protocols: + http: { enabled: true } + mcp: + enabled: true + mountPath: /mcp + registry: { name: io.github.acme/weather, version: 1.4.0, description: Weather forecasts } +resources: {} +payments: {} +`, + 'utf8', + ); + return configPath; + } + + it('writes the listing from a config file through the real program wiring', async () => { + const dir = tempDir('agent-commerce-program-export-'); + const output = join(dir, 'listing', 'server.json'); + + const { exitCode } = await run([ + 'export', + 'mcp-registry', + '--config', + configFile(dir), + '--output', + output, + ]); + + expect(exitCode).toBe(0); + expect(JSON.parse(readFileSync(output, 'utf8'))).toMatchObject({ + name: 'io.github.acme/weather', + version: '1.4.0', + description: 'Weather forecasts', + remotes: [{ type: 'streamable-http', url: 'https://api.example.com/mcp' }], + }); + }); + + it('overwrites an existing file only with --force', async () => { + const dir = tempDir('agent-commerce-program-export-'); + const output = join(dir, 'server.json'); + writeFileSync(output, 'keep me\n', 'utf8'); + const argv = ['export', 'mcp-registry', '--config', configFile(dir), '--output', output]; + + const refused = await run(argv); + expect(refused.exitCode).toBe(1); + expect(readFileSync(output, 'utf8')).toBe('keep me\n'); + + const forced = await run([...argv, '--force']); + expect(forced.exitCode).toBe(0); + expect(JSON.parse(readFileSync(output, 'utf8'))).toMatchObject({ version: '1.4.0' }); + }); + + it('prints its usage with server.json as the default output', async () => { + const { exitCode, io } = await run(['export', 'mcp-registry', '--help']); + expect(exitCode).toBe(0); + const text = io.out.join('\n'); + expect(text).toContain('Usage: agent-commerce export mcp-registry'); + expect(text).toContain('(default: "server.json")'); + }); +}); + describe('agent-commerce init', () => { const tmpConfigPath = () => join(tempDir('agent-commerce-program-init-'), 'config.yaml'); diff --git a/tests/unit/config/schema.test.ts b/tests/unit/config/schema.test.ts index 0f08762..4d866b9 100644 --- a/tests/unit/config/schema.test.ts +++ b/tests/unit/config/schema.test.ts @@ -2720,6 +2720,101 @@ describe('payments.x402.bazaar', () => { }); }); +describe('protocols.mcp.registry', () => { + const REGISTRY = { + name: 'io.github.acme/weather', + version: '1.0.0', + description: 'Weather forecasts, paid per call', + }; + // One code point, two UTF-16 units + const ASTRAL = '\u{1D538}'; + + function withRegistry(registry: unknown): Record { + const raw = validRawConfig(); + (raw['protocols'] as { mcp: Record }).mcp['registry'] = registry; + return raw; + } + + it('leaves protocols.mcp as before when the block is absent', () => { + expect(parseConfig(validRawConfig(), {}).protocols.mcp).toStrictEqual({ + enabled: true, + mountPath: '/mcp', + }); + }); + + it('keeps the block as written', () => { + expect(parseConfig(withRegistry(REGISTRY), {}).protocols.mcp.registry).toEqual(REGISTRY); + }); + + // The first rows are upstream's own cases in validators_test.go + it.each([ + ['a dotted namespace', 'name', 'com.microsoft.azure.service/webapp-server'], + ['".", "_" and "-" in the name', 'name', 'io.github.acme/my_server.v-2'], + ['200 characters', 'name', `ab/${'c'.repeat(197)}`], + ['a semver version', 'version', '1.2.3'], + ['a prerelease', 'version', '1.2.3-alpha.1'], + ['a date', 'version', '2021.03.15'], + ['a word', 'version', 'snapshot'], + ['a hyphen that joins no versions', 'version', 'snapshot - 2025.09'], + ['a hyphen between no-break spaces, not a range in RE2', 'version', '1.0 - 2.0'], + ['255 characters', 'version', `1.0.0-${'a'.repeat(249)}`], + ['100 characters', 'description', 'd'.repeat(100)], + ['100 code points outside the BMP', 'description', ASTRAL.repeat(100)], + ])('accepts %s as %s', (_label, key, value) => { + const registry = parseConfig(withRegistry({ ...REGISTRY, [key]: value }), {}).protocols.mcp + .registry; + expect(registry).toEqual({ ...REGISTRY, [key]: value }); + }); + + it.each([ + ['no slash', 'name', 'io.github.acme'], + ['two slashes', 'name', 'com.example/server/path'], + ['a double slash', 'name', 'com.example//server'], + ['an empty namespace', 'name', '/server-name'], + ['an empty name', 'name', 'com.example/'], + ['"_" in the namespace', 'name', 'io_github.acme/weather'], + ['a one-character namespace', 'name', 'a/weather'], + ['a one-character name', 'name', 'io.github.acme/w'], + ['a name ending in "-"', 'name', 'io.github.acme/weather-'], + ['201 characters', 'name', `ab/${'c'.repeat(198)}`], + ['a number', 'name', 42], + ['an empty version', 'version', ''], + ['"latest"', 'version', 'latest'], + ['a caret range', 'version', '^1.2.3'], + ['a comparator and a space', 'version', '>= 1.2.3'], + ['an x-range', 'version', '1.x'], + ['a wildcard', 'version', '1.*'], + ['a hyphen range', 'version', '1.2.3 - 2.0.0'], + ['an OR range', 'version', '1.2 || 1.3'], + ['a prerelease holding "x"', 'version', '1.0.0-next.1'], + ['a range ending in U+0085, which Go trims', 'version', '1.x\u0085'], + ['256 characters', 'version', `1.0.0-${'a'.repeat(250)}`], + ['an empty description', 'description', ''], + ['101 characters', 'description', 'd'.repeat(101)], + ['101 code points outside the BMP', 'description', ASTRAL.repeat(101)], + ])('refuses %s, naming protocols.mcp.registry.%s', (_label, key, value) => { + expectConfigInvalid( + () => parseConfig(withRegistry({ ...REGISTRY, [key]: value }), {}), + `protocols.mcp.registry.${key}`, + ); + }); + + it.each(['name', 'version', 'description'])('requires %s', (key) => { + const partial = Object.fromEntries(Object.entries(REGISTRY).filter(([k]) => k !== key)); + expectConfigInvalid( + () => parseConfig(withRegistry(partial), {}), + `protocols.mcp.registry.${key}`, + ); + }); + + it('refuses a key the block does not define', () => { + expectConfigInvalid( + () => parseConfig(withRegistry({ ...REGISTRY, title: 'Weather' }), {}), + 'protocols.mcp.registry', + ); + }); +}); + describe('resource idempotency', () => { function withIdempotency(id: string, idempotency: unknown): Record { const raw = validRawConfig(); From d2334c374e20d5fe7ff74157be0d3d87d7882d42 Mon Sep 17 00:00:00 2001 From: Revinand Date: Wed, 18 Nov 2026 20:32:07 +0100 Subject: [PATCH 09/14] test: settle with forwarded Bazaar metadata on Anvil --- docs/security.md | 4 +- tests/e2e/payment/x402-bazaar.e2e.test.ts | 374 ++++++++++++++++++++ tests/fixtures/x402/loopback-facilitator.ts | 10 + 3 files changed, 386 insertions(+), 2 deletions(-) create mode 100644 tests/e2e/payment/x402-bazaar.e2e.test.ts diff --git a/docs/security.md b/docs/security.md index 5270ec6..f983623 100644 --- a/docs/security.md +++ b/docs/security.md @@ -335,8 +335,8 @@ real funds. | **multi-offer x402 proof whose `accepted` matches zero or multiple offers** | `invalid_payment_requirements`; no offer is selected and the facilitator is not called | `tests/unit/payments-x402/provider-remote-facilitator.test.ts` | | **an x402 proof under `publicResourceUrl`, whose offers share one `resource.url`** | offer selection still uses `accepted`, as with `resource://`; the URL form does not change the replay key | `tests/unit/payments-x402/public-resource-url.test.ts` | | **an x402 proof echoing a challenge issued before `publicResourceUrl` changed, or another surface's challenge** | `invalid_payment_requirements` before calling the facilitator; no settlement, including for an A2A task awaiting payment across a restart | `tests/unit/payments-x402/public-resource-url.test.ts`, `tests/integration/x402-public-url.test.ts`, `tests/integration/a2a-x402-extension.test.ts` | -| **a buyer echoing altered Bazaar metadata or `resource` fields to poison a facilitator's catalog** | replaces the proof's values with the issued challenge's `resource` and `extensions.bazaar` before forwarding | `tests/unit/payments-x402/bazaar-challenge.test.ts`, `tests/integration/x402-bazaar.test.ts` | -| **a proof's `payment-identifier`, ERC-8409 quote or gas-sponsoring extension, under Bazaar** | none of the proof's extensions are forwarded; the facilitator receives only the challenge's `extensions.bazaar` | `tests/unit/payments-x402/bazaar-challenge.test.ts` | +| **a buyer echoing altered Bazaar metadata or `resource` fields to poison a facilitator's catalog** | replaces the proof's values with the issued challenge's `resource` and `extensions.bazaar` before forwarding | `tests/unit/payments-x402/bazaar-challenge.test.ts`, `tests/integration/x402-bazaar.test.ts`, `tests/e2e/payment/x402-bazaar.e2e.test.ts` | +| **a proof's `payment-identifier`, ERC-8409 quote or gas-sponsoring extension, under Bazaar** | none of the proof's extensions are forwarded; the facilitator receives only the challenge's `extensions.bazaar` | `tests/unit/payments-x402/bazaar-challenge.test.ts`, `tests/e2e/payment/x402-bazaar.e2e.test.ts` | | **Bazaar metadata echoed from another surface, with several offers** | offer selection still uses `accepted`; the facilitator receives the challenge's own metadata | `tests/unit/payments-x402/bazaar-challenge.test.ts` | | **Bazaar metadata exposing a backend URL, header, credential, reserved field or unexposed surface** | backend connection settings are not copied; resource ids, descriptions, schemas and generated examples are public metadata. Schema and example contents are not redacted. Bazaar adds no `_payment` or `_authorization` carriers; unexposed surfaces receive no metadata | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/config/schema.test.ts` | | **a Bazaar extension large enough to break the `PAYMENT-REQUIRED` header, and payment with it** | config loading omits extensions over 4096 bytes and warns; an HTTP challenge omits Bazaar if it would push the encoded header value over 8192 bytes. Payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/payments-x402/bazaar-challenge.test.ts` | diff --git a/tests/e2e/payment/x402-bazaar.e2e.test.ts b/tests/e2e/payment/x402-bazaar.e2e.test.ts new file mode 100644 index 0000000..fa5918a --- /dev/null +++ b/tests/e2e/payment/x402-bazaar.e2e.test.ts @@ -0,0 +1,374 @@ +/** + * Bazaar metadata during settlement on Anvil through a loopback facilitator. + * Its recorded `/verify` and `/settle` bodies must use the challenge's + * `resource` and `extensions.bazaar` when `payments.x402.bazaar` is enabled, + * including when the buyer alters the echoed metadata. Each purchase must + * move funds. With Bazaar disabled, or for MPP alongside Bazaar, the facilitator + * payload contains only `x402Version`, `accepted` and `payload`. + */ +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'; +import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; +import { x402Client } from '@x402/core/client'; +import type { PaymentPayload, PaymentRequired } from '@x402/core/types'; +import { registerExactEvmScheme } from '@x402/evm/exact/client'; +import { wrapMCPClientWithPayment } from '@x402/mcp'; +import { Challenge } from 'mppx'; +import { charge as clientCharge } from 'mppx/evm/client'; +import { privateKeyToAccount } from 'viem/accounts'; +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; +import { type GatewayConfig, parseConfig } from '../../../src/config'; +import { + NOOP_LOGGER, + PAYMENT_HEADER, + PAYMENT_REQUIRED_HEADER, + PAYMENT_RESPONSE_HEADER, +} from '../../../src/core'; +import { createGateway, type GatewayInstance } from '../../../src/gateway'; +import { createConfiguredPaymentProviders } from '../../../src/gateway/payment-providers'; +import { type AnvilHandle, deployLocalChain, startAnvil } from '../../../src/payments/x402/testing'; +import { createMcpAdapter } from '../../../src/protocols/mcp'; +import { createSqliteReceiptStore, type SqliteReceiptStore } from '../../../src/storage/receipts'; +import { + type LoopbackBody, + type LoopbackFacilitator, + startLoopbackFacilitator, +} from '../../fixtures/x402/loopback-facilitator'; +import { expectRealSettlement, readBalances } from '../../fixtures/x402/settlement'; + +const PORT = 18801; +const NETWORK = 'eip155:31337'; +const BASE = 'https://shop.example'; +const INPUT = { city: 'Oslo' }; +const ONE_USDC = 1_000_000n; +const THREE_KEYS = ['x402Version', 'accepted', 'payload']; + +type EvmChallenge = Parameters['createCredential']>[0]['challenge']; + +interface Stack { + readonly gateway: GatewayInstance; + readonly store: SqliteReceiptStore; + readonly facilitator: LoopbackFacilitator; + readonly url: string; + readonly config: GatewayConfig; +} + +let anvil: AnvilHandle; +let deployment: Awaited>; +let withBazaar: Stack; +let withoutBazaar: Stack; +let mcp: Client | undefined; + +function rawConfig(facilitatorUrl: string, bazaar: boolean): Record { + const facilitator = { mode: 'remote', url: facilitatorUrl, auth: { type: 'none' } }; + const resource = (expose: string[], payments: string[]) => ({ + name: 'Forecast', + description: 'Forecast for a city', + input: { + type: 'object', + properties: { city: { type: 'string' } }, + required: ['city'], + additionalProperties: false, + }, + backend: { type: 'http', method: 'POST', url: 'http://merchant.invalid/forecast' }, + pricing: { type: 'fixed', amount: '1.00', currency: 'USDC' }, + expose, + payments, + }); + const domain = { assetName: deployment.assetName, assetVersion: deployment.assetVersion }; + return { + version: 1, + merchant: { id: 'bazaar-e2e', name: 'Bazaar E2E', publicBaseUrl: BASE }, + server: { port: 0, host: '127.0.0.1', allowedOrigins: [] }, + storage: { receipts: { driver: 'sqlite', path: ':memory:' } }, + protocols: { http: { enabled: true }, mcp: { enabled: true, mountPath: '/mcp' } }, + resources: { + forecast: resource(['http', 'mcp'], ['x402']), + // Put MPP first to serve this resource; including x402 also generates Bazaar metadata + forecast_mpp: resource(['http'], ['mpp', 'x402']), + }, + payments: { + x402: { + enabled: true, + network: NETWORK, + rpcUrl: anvil.rpcUrl, + asset: deployment.asset, + ...domain, + assetDecimals: deployment.assetDecimals, + payTo: deployment.merchant.address, + maxTimeoutSeconds: 120, + facilitator, + ...(bazaar ? { publicResourceUrl: true, bazaar: { enabled: true } } : {}), + }, + mpp: { + enabled: true, + network: NETWORK, + rpcUrl: anvil.rpcUrl, + asset: deployment.asset, + ...domain, + recipient: deployment.merchant.address, + realm: 'shop.example', + challengeSecret: 'bazaar-e2e-challenge-secret'.padEnd(32, 'x'), + facilitator, + }, + }, + }; +} + +async function startStack(bazaar: boolean): Promise { + const facilitator = await startLoopbackFacilitator({ + evm: { + chains: [{ network: NETWORK, rpcUrl: anvil.rpcUrl }], + signerPrivateKey: deployment.facilitator.privateKey, + }, + }); + const config = parseConfig(rawConfig(facilitator.url, bazaar), {}); + const store = createSqliteReceiptStore({ path: ':memory:', logger: NOOP_LOGGER }); + await store.init(); + const gateway = await createGateway({ + config, + store, + paymentProviders: await createConfiguredPaymentProviders(config.payments, NOOP_LOGGER), + protocolAdapters: [createMcpAdapter()], + logger: NOOP_LOGGER, + backend: { + async call() { + return { status: 200, body: { forecast: 'sun' }, headers: {}, durationMs: 1 }; + }, + }, + }); + const { url } = await gateway.listen(); + return { gateway, store, facilitator, url, config }; +} + +function invoke(stack: Stack, id: string, headers: Record = {}) { + return stack.gateway.server.inject({ + method: 'POST', + url: `/api/resources/${id}/invoke`, + headers: { host: new URL(BASE).host, 'content-type': 'application/json', ...headers }, + payload: INPUT, + }); +} + +const decode = (value: unknown): Record => + JSON.parse(Buffer.from(String(value), 'base64').toString('utf8')); + +const encode = (proof: PaymentPayload) => Buffer.from(JSON.stringify(proof)).toString('base64'); + +function buyer(): x402Client { + const client = new x402Client(); + registerExactEvmScheme(client, { + signer: privateKeyToAccount(deployment.buyer.privateKey), + networks: [NETWORK], + }); + client.setSpendControls(false); + return client; +} + +async function httpChallenge(stack: Stack): Promise { + const unpaid = await invoke(stack, 'forecast'); + expect(unpaid.statusCode).toBe(402); + return decode(unpaid.headers[PAYMENT_REQUIRED_HEADER]) as unknown as PaymentRequired; +} + +function balances() { + return readBalances({ + rpcUrl: anvil.rpcUrl, + asset: deployment.asset, + buyer: deployment.buyer.address, + merchant: deployment.merchant.address, + }); +} + +// Run a purchase, verify its balance changes and receipt transaction, then +// return the facilitator request bodies it produced +async function purchase( + stack: Stack, + pay: () => Promise, + provider: 'x402' | 'mpp' = 'x402', +): Promise { + const from = stack.facilitator.bodies.length; + const before = await balances(); + + await pay(); + + const [receipt] = await stack.store.listReceipts({ limit: 1 }); + expect(receipt?.payment).toMatchObject({ provider, status: 'settled' }); + await expectRealSettlement({ + rpcUrl: anvil.rpcUrl, + asset: deployment.asset, + buyer: deployment.buyer.address, + merchant: deployment.merchant.address, + before, + after: await balances(), + amountBaseUnits: ONE_USDC, + txHash: receipt?.payment?.externalReference as string, + }); + return stack.facilitator.bodies.slice(from); +} + +async function payHttp(stack: Stack, proof: PaymentPayload): Promise { + const paid = await invoke(stack, 'forecast', { [PAYMENT_HEADER]: encode(proof) }); + expect(paid.statusCode).toBe(200); + expect(paid.json()).toEqual({ forecast: 'sun' }); + return String(decode(paid.headers[PAYMENT_RESPONSE_HEADER])['transaction']); +} + +const payloads = (bodies: LoopbackBody[]) => bodies.map(({ body }) => body['paymentPayload']); + +beforeAll(async () => { + anvil = await startAnvil({ port: PORT, silent: true }); + deployment = await deployLocalChain({ rpcUrl: anvil.rpcUrl, buyerInitialBalance: '10.00' }); + withBazaar = await startStack(true); + withoutBazaar = await startStack(false); +}, 180_000); + +afterEach(async () => { + await mcp?.close().catch(() => {}); + mcp = undefined; +}); + +afterAll(async () => { + for (const stack of [withBazaar, withoutBazaar]) { + await stack?.gateway.close().catch(() => {}); + await stack?.store.close().catch(() => {}); + await stack?.facilitator.close(); + } + await anvil?.stop(); +}); + +describe('x402 Bazaar metadata - real local chain', () => { + it('HTTP: settles, and the facilitator verifies and settles with the 402 resource and metadata', async () => { + const required = await httpChallenge(withBazaar); + expect(required.resource.url).toBe(`${BASE}/api/resources/forecast/invoke`); + expect(Object.keys(required.extensions ?? {})).toEqual(['bazaar']); + const proof = await buyer().createPaymentPayload(required); + let transaction = ''; + + const bodies = await purchase(withBazaar, async () => { + transaction = await payHttp(withBazaar, proof); + }); + + expect(bodies.map(({ operation }) => operation)).toEqual(['verify', 'settle']); + for (const payload of payloads(bodies)) { + expect(payload).toEqual({ + x402Version: 2, + accepted: required.accepts[0], + payload: proof.payload, + resource: required.resource, + extensions: { bazaar: required.extensions?.['bazaar'] }, + }); + } + const [receipt] = await withBazaar.store.listReceipts({ limit: 1 }); + expect(receipt?.payment?.externalReference).toBe(transaction); + }); + + it('HTTP: an altered echo changes nothing the facilitator receives', async () => { + const required = await httpChallenge(withBazaar); + const proof = await buyer().createPaymentPayload(required); + const altered: PaymentPayload = { + ...proof, + resource: { + ...(proof.resource as PaymentRequired['resource']), + description: 'Free money', + }, + extensions: { + bazaar: { info: { input: { type: 'http', body: { poisoned: true } } } }, + 'payment-identifier': { info: { id: 'pay_1234567890abcdef' } }, + eip2612GasSponsoring: { info: { signature: '0x00' } }, + }, + }; + + const bodies = await purchase(withBazaar, async () => { + await payHttp(withBazaar, altered); + }); + + expect(bodies.map(({ operation }) => operation)).toEqual(['verify', 'settle']); + for (const payload of payloads(bodies)) { + expect(payload).toEqual({ + x402Version: 2, + accepted: required.accepts[0], + payload: proof.payload, + resource: required.resource, + extensions: { bazaar: required.extensions?.['bazaar'] }, + }); + } + }); + + it('MCP: an @x402/mcp client settles, and the facilitator gets the MCP challenge metadata', async () => { + mcp = new Client({ name: 'bazaar-e2e-buyer', version: '0.0.0-test' }); + await mcp.connect( + new StreamableHTTPClientTransport(new URL(`${withBazaar.url}/mcp`)) as Transport, + ); + const challenged = (await mcp.callTool({ + name: 'forecast', + arguments: INPUT, + })) as CallToolResult; + const required = challenged.structuredContent as unknown as PaymentRequired; + expect(required.resource.url).toBe(`${BASE}/mcp`); + expect(Object.keys(required.extensions ?? {})).toEqual(['bazaar']); + + const bodies = await purchase(withBazaar, async () => { + const result = await wrapMCPClientWithPayment(mcp as Client, buyer(), { + autoPayment: true, + }).callTool('forecast', INPUT); + expect(result.paymentMade).toBe(true); + expect(result.isError).not.toBe(true); + }); + + expect(bodies.map(({ operation }) => operation)).toEqual(['verify', 'settle']); + for (const payload of payloads(bodies) as Record[]) { + expect(Object.keys(payload)).toEqual([...THREE_KEYS, 'resource', 'extensions']); + expect(payload['resource']).toEqual(required.resource); + expect(payload['extensions']).toEqual({ bazaar: required.extensions?.['bazaar'] }); + } + }); + + it('feature off: settles with only x402Version, accepted and payload sent', async () => { + const required = await httpChallenge(withoutBazaar); + expect(required).not.toHaveProperty('extensions'); + const proof = await buyer().createPaymentPayload(required); + + const bodies = await purchase(withoutBazaar, async () => { + await payHttp(withoutBazaar, proof); + }); + + expect(bodies.map(({ operation }) => operation)).toEqual(['verify', 'settle']); + for (const payload of payloads(bodies) as Record[]) { + expect(Object.keys(payload)).toEqual(THREE_KEYS); + } + }); + + it('MPP beside Bazaar: settles with only x402Version, accepted and payload sent', async () => { + // Config has Bazaar metadata for this resource; MPP must omit it from settlement + expect(withBazaar.config.payments.x402?.resourceBazaar?.['forecast_mpp']).toHaveProperty( + 'http', + ); + const bodies = await purchase( + withBazaar, + async () => { + const unpaid = await invoke(withBazaar, 'forecast_mpp'); + expect(unpaid.statusCode).toBe(402); + expect(unpaid.headers[PAYMENT_REQUIRED_HEADER]).toBeUndefined(); + const challenge = Challenge.deserialize(String(unpaid.headers['www-authenticate'])); + const credential = await clientCharge({ + account: privateKeyToAccount(deployment.buyer.privateKey), + authorization: { name: deployment.assetName, version: deployment.assetVersion }, + }).createCredential({ challenge: challenge as unknown as EvmChallenge, context: {} }); + + const paid = await invoke(withBazaar, 'forecast_mpp', { + authorization: String(credential), + }); + + expect(paid.statusCode).toBe(200); + }, + 'mpp', + ); + + expect(bodies.map(({ operation }) => operation)).toEqual(['verify', 'settle']); + for (const payload of payloads(bodies) as Record[]) { + expect(Object.keys(payload)).toEqual(THREE_KEYS); + } + }); +}); diff --git a/tests/fixtures/x402/loopback-facilitator.ts b/tests/fixtures/x402/loopback-facilitator.ts index 801d927..5af00e8 100644 --- a/tests/fixtures/x402/loopback-facilitator.ts +++ b/tests/fixtures/x402/loopback-facilitator.ts @@ -30,9 +30,16 @@ export interface LoopbackFacilitator { readonly url: string; /** Requests received as `METHOD URL`, including any query string */ readonly requests: readonly string[]; + /** Parsed POST bodies received at `/verify` and `/settle` */ + readonly bodies: readonly LoopbackBody[]; close(): Promise; } +export interface LoopbackBody { + readonly operation: 'verify' | 'settle'; + readonly body: Record; +} + async function readJson(req: IncomingMessage): Promise> { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(chunk as Buffer); @@ -99,6 +106,7 @@ export async function startLoopbackFacilitator(options: { } const requests: string[] = []; + const bodies: LoopbackBody[] = []; const handle = (req: IncomingMessage, res: ServerResponse) => { requests.push(`${req.method} ${req.url}`); const reply = (status: number, body: unknown) => { @@ -127,6 +135,7 @@ export async function startLoopbackFacilitator(options: { } readJson(req) .then(async (body) => { + bodies.push({ operation, body }); const requirements = body['paymentRequirements'] as { network: string }; const payload = body['paymentPayload'] as never; const sdkFacilitator = sdkFacilitators.get(requirements.network); @@ -160,6 +169,7 @@ export async function startLoopbackFacilitator(options: { return { url: `${options.tls ? 'https' : 'http'}://127.0.0.1:${(server.address() as AddressInfo).port}`, requests, + bodies, close: () => new Promise((resolve) => server.close(() => resolve())), }; } From 54043d7feb515e1598cdbc99f01b3ae51a2e9a45 Mon Sep 17 00:00:00 2001 From: Revinand Date: Wed, 18 Nov 2026 22:59:29 +0100 Subject: [PATCH 10/14] fix(x402): check input schemas and output before publishing Bazaar metadata --- biome.json | 6 +- docs/protocols.md | 2 +- docs/protocols/acp.md | 2 +- docs/protocols/mcp.md | 2 +- docs/protocols/x402.md | 15 ++- docs/security.md | 1 + scripts/support-record.ts | 2 +- src/cli/lib/write-file.ts | 2 +- src/config/schema/normalize.ts | 5 +- src/config/schema/resource-schema.ts | 32 +---- src/core/execution/schema-example.ts | 14 +-- src/core/execution/validation.ts | 108 +++++++++++----- src/core/no-answer.ts | 3 +- src/payments/x402/provider/bazaar.ts | 57 +++++---- src/protocols/mcp/tool-mapping.ts | 4 +- src/support/acp.json | 2 +- tests/integration/baseline-goldens.test.ts | 2 +- tests/integration/x402-bazaar.test.ts | 4 +- tests/unit/config/schema.test.ts | 69 ++++++++++- tests/unit/core/execution/validation.test.ts | 123 +++++++++++++++---- tests/unit/payments-x402/bazaar.test.ts | 122 ++++++++++++++---- 21 files changed, 427 insertions(+), 150 deletions(-) diff --git a/biome.json b/biome.json index c1d906a..e3e01c0 100644 --- a/biome.json +++ b/biome.json @@ -18,7 +18,9 @@ "!contracts/lib", "!package-lock.json", "!src/protocols/acp/spec", - "!tests/fixtures/acp" + "!tests/fixtures/acp", + "!tests/fixtures/mcp-registry", + "!tests/integration/goldens" ] }, "formatter": { @@ -54,4 +56,4 @@ "arrowParentheses": "always" } } -} +} \ No newline at end of file diff --git a/docs/protocols.md b/docs/protocols.md index d75f726..679e2e3 100644 --- a/docs/protocols.md +++ b/docs/protocols.md @@ -81,7 +81,7 @@ Each reads fields of the profile's record in `src/support/`: "Supported" covers the recorded subset, never the whole specification. HTTP, MCP and x402 were supported before 2.8.0 introduced these criteria, and keep -that status. Upstream does not label x402 v2 stable, and its record says so. +that status. Upstream does not label x402 v2 stable, and its record states that. ## Protocol pages diff --git a/docs/protocols/acp.md b/docs/protocols/acp.md index a618ec2..629411c 100644 --- a/docs/protocols/acp.md +++ b/docs/protocols/acp.md @@ -244,7 +244,7 @@ and the tests that hold the behavior. -- **ACP RFC §6.5**: After a merchant 5xx, retrying the same `Idempotency-Key` returns 409 `idempotency_unresolved` unless `protocols.acp.idempotency.merchantIdempotent` is true. The merchant may have acted, so another execution could duplicate the order. Tests: `tests/conformance/acp/idempotency.test.ts`, `tests/conformance/acp/errors.test.ts`. +- **ACP RFC §6.5**: After a merchant 5xx, retrying the same `Idempotency-Key` returns 409 `idempotency_unresolved` unless `protocols.acp.idempotency.merchantIdempotent` is true. The merchant may have acted, and another execution could duplicate the order. Tests: `tests/conformance/acp/idempotency.test.ts`, `tests/conformance/acp/errors.test.ts`. diff --git a/docs/protocols/mcp.md b/docs/protocols/mcp.md index 5af20a0..2861dcc 100644 --- a/docs/protocols/mcp.md +++ b/docs/protocols/mcp.md @@ -147,7 +147,7 @@ their ordering to choose the latest. Publishing a prerelease such as `1.2.3-1` after its release, `1.2.3`, does not make it the latest. If your config names that prerelease, `doctor --registry` reports a version difference. -Several server names may list the same remote URL, so the URL alone does not +Several server names may list the same remote URL; the URL alone does not prove who runs the server. `doctor --registry` looks up the configured name only and reports a response with another name as a difference in `name`. diff --git a/docs/protocols/x402.md b/docs/protocols/x402.md index 6815d20..4baee6f 100644 --- a/docs/protocols/x402.md +++ b/docs/protocols/x402.md @@ -132,7 +132,7 @@ With [`publicResourceUrl`](../configuration.md#public-resource-url), the URL names the configured HTTP invoke route, MCP mount or A2A mount for the request's surface. Every offer of that resource shares the URL on that surface; `accepted` still selects the offer. The echo comparison above rejects these -proofs before calling the facilitator, so neither reaches settlement: +proofs before calling the facilitator, and neither reaches settlement: - a proof that echoes the previous URL after the option changes; - a proof that echoes another surface's URL. @@ -150,7 +150,7 @@ is MPP receives an MPP challenge. | Surface | `info.input` | `info.output` | | ------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | -| HTTP | `{ type: 'http', method: 'POST', bodyType: 'json', body: }` | `{ type: 'json' }`, with an `example` only when both schema and value pass local checks | +| HTTP | `{ type: 'http', method: 'POST', bodyType: 'json', body: }` | `{ type: 'json', example }` when the resource's `mimeType` is JSON or unset and both output schema and example pass local checks; otherwise none | | MCP | `{ type: 'mcp', toolName: , description, inputSchema, example }` | none | `schema` describes `info` using JSON Schema 2020-12; the HTTP form puts the @@ -172,11 +172,18 @@ probes usable, config loading omits metadata and warns when: - its input schema uses a keyword the gateway does not enforce. Enforced are `type`, `properties`, `required`, `additionalProperties`, `enum` and a single-schema `items`, each where the node's type admits it, plus the - annotations `title`, `description`, `examples`, `default`, `$comment`, - `deprecated`, `readOnly` and `writeOnly`; + annotations `title`, `description`, `example`, `examples`, `default`, + `$comment`, `deprecated`, `readOnly` and `writeOnly`; +- its input schema has an empty `enum` or gives a keyword a value JSON Schema + 2020-12 does not allow, such as a repeated `required` name, a repeated `type` + or a `description` that is not a string. The x402 SDK's validator rejects + extensions with these schema values; - the example fails the input schema or the backend request shape; - a surface's extension exceeds 4096 bytes; only that surface is omitted. +A schema warning names the keyword and its path, such as +`input.properties.city uses "pattern"`. + If adding Bazaar would push the base64 `PAYMENT-REQUIRED` value over 8192 bytes, the HTTP challenge omits it. A `warn` log names the resource once per provider instance. Omitting metadata leaves payment behavior unchanged. diff --git a/docs/security.md b/docs/security.md index f983623..9ec7567 100644 --- a/docs/security.md +++ b/docs/security.md @@ -341,6 +341,7 @@ real funds. | **Bazaar metadata exposing a backend URL, header, credential, reserved field or unexposed surface** | backend connection settings are not copied; resource ids, descriptions, schemas and generated examples are public metadata. Schema and example contents are not redacted. Bazaar adds no `_payment` or `_authorization` carriers; unexposed surfaces receive no metadata | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/config/schema.test.ts` | | **a Bazaar extension large enough to break the `PAYMENT-REQUIRED` header, and payment with it** | config loading omits extensions over 4096 bytes and warns; an HTTP challenge omits Bazaar if it would push the encoded header value over 8192 bytes. Payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/payments-x402/bazaar-challenge.test.ts` | | **a generated Bazaar example the gateway would refuse, silently dropping the listing** | config loading omits the resource's metadata and warns with its id, affected surfaces and reason; payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/config/schema.test.ts`, `tests/integration/x402-bazaar.test.ts` | +| **an input schema the gateway accepts and a facilitator cannot compile, silently dropping the listing** | config loading omits metadata for malformed keyword values detected by the JSON Schema 2020-12 checks or an empty `enum`; warnings name the keyword and its path | `tests/unit/core/execution/validation.test.ts`, `tests/unit/payments-x402/bazaar.test.ts` ("leaves out a resource whose input schema has ..., which upstream validation refuses") | | **an AP2 mandate approved for one x402 offer, presented with a proof for another** | selected destination, network or asset fails mandate binding; no settlement | `tests/unit/core/execution/pipeline-authorization.test.ts` | | **an EIP-3009 authorization signed for one EVM chain, presented as another chain's offer** | `invalid_exact_evm_signature`: signature fails against the other chain's EIP-712 domain; neither chain's balances change | `tests/e2e/payment/x402-multichain.e2e.test.ts` | | **the same payer, token address and nonce on two EVM chains** | both settle: the replay key includes the chain id | same | diff --git a/scripts/support-record.ts b/scripts/support-record.ts index 8947888..23fee4d 100644 --- a/scripts/support-record.ts +++ b/scripts/support-record.ts @@ -189,7 +189,7 @@ export interface PackageManifest { readonly peerDependencies?: Readonly>; } -/** Everything the drift check reads, injectable so tests can mutate a copy */ +/** Everything the drift check reads, injectable for tests that mutate a copy */ export interface SupportTree { readonly records: readonly SupportRecord[]; readonly manifest: PackageManifest; diff --git a/src/cli/lib/write-file.ts b/src/cli/lib/write-file.ts index 31d2227..e66b716 100644 --- a/src/cli/lib/write-file.ts +++ b/src/cli/lib/write-file.ts @@ -3,7 +3,7 @@ import { dirname, resolve } from 'node:path'; /** * Writes `content` to a temporary sibling, then renames it over `outputPath`. - * The destination is replaced after the write succeeds, so a failed write + * The destination is replaced only after the write succeeds; a failed write * leaves an existing file intact. Creates missing output directories. */ export async function writeAtomically(outputPath: string, content: string): Promise { diff --git a/src/config/schema/normalize.ts b/src/config/schema/normalize.ts index fc2caa4..d91038f 100644 --- a/src/config/schema/normalize.ts +++ b/src/config/schema/normalize.ts @@ -71,7 +71,7 @@ export function normalize(raw: RawConfig): GatewayConfig { const bazaarRaw = raw.payments.x402?.bazaar; const resourceBazaar = bazaarRaw !== undefined && toBoolean(bazaarRaw.enabled, 'payments.x402.bazaar.enabled') - ? bazaarExtensions(resourceUrls, resources) + ? bazaarExtensions(resourceUrls, resources, mimeTypes) : undefined; const x402WithFlows = x402 !== undefined @@ -131,6 +131,7 @@ export function normalize(raw: RawConfig): GatewayConfig { function bazaarExtensions( resourceUrls: Record>> | undefined, resources: readonly CommerceResource[], + mimeTypes: Readonly>, ): NonNullable['resourceBazaar'] { if (resourceUrls === undefined) { throw new CommerceError( @@ -144,7 +145,7 @@ function bazaarExtensions( const urls = resourceUrls[resource.id]; if (urls === undefined) return []; const surfaces = (['http', 'mcp'] as const).filter((surface) => urls[surface] !== undefined); - const { extensions, omitted } = bazaarMetadata(resource, surfaces); + const { extensions, omitted } = bazaarMetadata(resource, surfaces, mimeTypes[resource.id]); for (const { surfaces: left, reason } of omitted) { console.warn( `[agent-commerce] resource "${resource.id}" gets no Bazaar metadata on ${left.join(' and ')}: ${reason}. Payment is unaffected.`, diff --git a/src/config/schema/resource-schema.ts b/src/config/schema/resource-schema.ts index 9fb5701..3c12387 100644 --- a/src/config/schema/resource-schema.ts +++ b/src/config/schema/resource-schema.ts @@ -1,6 +1,7 @@ // A resource's input schema: the default closed object and the keywords the validator supports import { CommerceError } from '../../core'; import { isObjectSchemaNode } from '../../core/execution'; +import { ENFORCED_SCHEMA_KEYWORDS } from '../../core/execution/validation'; import { isRecord } from '../../core/is-record'; /** @@ -61,31 +62,6 @@ export const EMPTY_CLOSED_OBJECT_SCHEMA: Record = { additionalProperties: false, }; -// Keywords core's validator ignores (see `execution/validation.ts` for the -// enforced subset). Config warns at load, since an operator who writes -// `pattern` cannot otherwise tell that it is not enforced. -const UNSUPPORTED_SCHEMA_KEYWORDS = [ - 'pattern', - 'minLength', - 'maxLength', - 'format', - 'minimum', - 'maximum', - 'exclusiveMinimum', - 'exclusiveMaximum', - 'multipleOf', - 'oneOf', - 'anyOf', - 'allOf', - 'not', - '$ref', - 'const', - 'patternProperties', - 'minItems', - 'maxItems', - 'uniqueItems', -]; - // `type` set to something that rules out "object". No `type` at all does not // exclude it: the validator treats `properties`/`required` alone as an object // schema. @@ -108,8 +84,10 @@ export function validateResourceSchemaKeywords( path: string, schema: Record, ): void { - for (const keyword of UNSUPPORTED_SCHEMA_KEYWORDS) { - if (Object.hasOwn(schema, keyword)) { + // Warn about keywords outside core's supported list to tell operators that + // constraints such as `pattern` are not enforced + for (const keyword of Object.keys(schema)) { + if (!ENFORCED_SCHEMA_KEYWORDS.has(keyword)) { console.warn( `[agent-commerce] resource "${id}" ${path} uses JSON Schema keyword "${keyword}", which this gateway does not enforce (see src/core/execution/validation.ts for the supported subset). Remove it or treat it as documentation only.`, ); diff --git a/src/core/execution/schema-example.ts b/src/core/execution/schema-example.ts index 3ad08e7..e5128ce 100644 --- a/src/core/execution/schema-example.ts +++ b/src/core/execution/schema-example.ts @@ -1,5 +1,5 @@ // Example values and the published object form of a resource's input schema, -// shared by the A2A Agent Card, MCP tools and x402 Bazaar metadata +// shared by the adapters and payment metadata that describe a resource import type { JsonSchema } from '../domain/common'; import { AUTHORIZATION_INPUT_FIELD, PAYMENT_INPUT_FIELD } from '../domain/wire'; import { isRecord } from '../is-record'; @@ -50,8 +50,8 @@ export function exampleObject(schema: Record): Record>>; @@ -59,11 +59,11 @@ export interface ObjectInputSchema { } /** - * Normalize a resource input schema for MCP, before adding reserved fields. - * Preserve other keywords while setting `type` to `'object'`, retaining only - * object-valued `properties` and string entries in `required`. + * Normalize a resource input schema for publication before a surface adds + * reserved fields. Set `type` to `'object'`, keep object-valued `properties` + * and string entries in `required`, and preserve other keywords. */ -export function objectInputSchema(schema: JsonSchema | undefined): ObjectInputSchema { +export function publishedInputSchema(schema: JsonSchema | undefined): PublishedInputSchema { const base = isRecord(schema) ? schema : {}; const properties = isRecord(base['properties']) ? Object.fromEntries( diff --git a/src/core/execution/validation.ts b/src/core/execution/validation.ts index 097e35d..b6926b8 100644 --- a/src/core/execution/validation.ts +++ b/src/core/execution/validation.ts @@ -11,12 +11,12 @@ * order) * - `items` (one schema applied to every array element, no tuple form) * - * Not enforced: `minLength`, `maxLength`, `pattern`, `format`, `minimum`, - * `maximum`, `exclusiveMinimum/Maximum`, `multipleOf`, `oneOf`, `anyOf`, - * `allOf`, `not`, `$ref`, `const`, `patternProperties`, `minItems`, - * `maxItems`, `uniqueItems`, tuple-form `items`, and a `type` naming anything - * outside the list above. Config warns at load when a schema uses one of these - * keywords or a tuple `items`. + * Not enforced: every other constraint, among them `minLength`, `maxLength`, + * `pattern`, `format`, `minimum`, `maximum`, `multipleOf`, `oneOf`, `anyOf`, + * `allOf`, `not`, `$ref`, `const`, `patternProperties`, `minItems`, `maxItems` + * and `uniqueItems`, tuple-form `items`, and a `type` naming anything outside + * the list above. Config warns at load when a schema uses a keyword outside + * `ENFORCED_SCHEMA_KEYWORDS` or a tuple `items`. */ import { isDeepStrictEqual } from 'node:util'; import type { JsonSchema } from '../domain/common'; @@ -43,8 +43,12 @@ const SUPPORTED_TYPES = new Set([ 'null', ]); -// The keywords `validateNode` enforces, plus annotations that constrain nothing -const FULLY_ENFORCED_KEYWORDS = new Set([ +/** + * Keywords enforced by `validateNode`, plus annotations that do not constrain + * input. Includes the singular OpenAPI `example` carried by `import openapi`. + * Config warns about input schema keywords outside this set. + */ +export const ENFORCED_SCHEMA_KEYWORDS: ReadonlySet = new Set([ 'type', 'properties', 'required', @@ -53,6 +57,7 @@ const FULLY_ENFORCED_KEYWORDS = new Set([ 'items', 'title', 'description', + 'example', 'examples', 'default', '$comment', @@ -61,35 +66,82 @@ const FULLY_ENFORCED_KEYWORDS = new Set([ 'writeOnly', ]); +// The value forms JSON Schema 2020-12 allows for the annotations above +const ANNOTATION_FORMS: readonly (readonly [string, string, (value: unknown) => boolean])[] = [ + ['title', 'a string', (value) => typeof value === 'string'], + ['description', 'a string', (value) => typeof value === 'string'], + ['$comment', 'a string', (value) => typeof value === 'string'], + ['examples', 'a list', Array.isArray], + ['deprecated', 'a boolean', (value) => typeof value === 'boolean'], + ['readOnly', 'a boolean', (value) => typeof value === 'boolean'], + ['writeOnly', 'a boolean', (value) => typeof value === 'boolean'], +]; + +const isDistinctStrings = (value: unknown): value is string[] => + Array.isArray(value) && + value.every((entry) => typeof entry === 'string') && + new Set(value).size === value.length; + /** - * Check whether a schema and its subschemas stay within this validator's - * supported keyword subset. Bazaar also validates the generated example - * before publishing it. + * Find the first unsupported or malformed part of a schema: a keyword outside + * `ENFORCED_SCHEMA_KEYWORDS`, a subschema that is not an object, `items` or + * `additionalProperties` that this validator would not apply under the node's + * type, or an invalid keyword value. Check keyword forms against JSON Schema + * 2020-12 and reject empty `enum` arrays, which Ajv also refuses to compile. + * Return `undefined` when these checks pass. */ -export function isFullyEnforced(schema: unknown): boolean { - if (!isRecord(schema)) return false; - if (!Object.keys(schema).every((key) => FULLY_ENFORCED_KEYWORDS.has(key))) return false; +export function unenforcedSchemaPart(schema: unknown, path = '$'): FieldError | undefined { + if (!isRecord(schema)) return { path, message: 'is not a schema object' }; + const unknown = Object.keys(schema).find((key) => !ENFORCED_SCHEMA_KEYWORDS.has(key)); + if (unknown !== undefined) { + return { path, message: `uses "${unknown}", which the gateway does not enforce` }; + } + const malformed = (keyword: string, form: string): FieldError => ({ + path, + message: `has a "${keyword}" that is not ${form}`, + }); const { type, properties, required, additionalProperties, items } = schema; - const types = Array.isArray(type) ? type : type === undefined ? [] : [type]; - if (Array.isArray(type) && type.length === 0) return false; - if (!types.every((t) => typeof t === 'string' && SUPPORTED_TYPES.has(t))) return false; - if (properties !== undefined) { - if (!isRecord(properties) || !Object.values(properties).every(isFullyEnforced)) return false; + const types = typeof type === 'string' ? [type] : type === undefined ? [] : type; + if ( + !isDistinctStrings(types) || + (Array.isArray(type) && type.length === 0) || + !types.every((entry) => SUPPORTED_TYPES.has(entry)) + ) { + return malformed('type', 'a supported type or a list of distinct ones'); } - if (required !== undefined) { - if (!Array.isArray(required) || !required.every((name) => typeof name === 'string')) - return false; + if (required !== undefined && !isDistinctStrings(required)) { + return malformed('required', 'a list of distinct strings'); + } + const allowed = schema['enum']; + if (allowed !== undefined && (!Array.isArray(allowed) || allowed.length === 0)) { + return malformed('enum', 'a list with at least one value'); + } + for (const [keyword, form, accepts] of ANNOTATION_FORMS) { + if (schema[keyword] !== undefined && !accepts(schema[keyword])) return malformed(keyword, form); + } + if (properties !== undefined) { + if (!isRecord(properties)) return malformed('properties', 'an object'); + for (const [key, sub] of Object.entries(properties)) { + const part = unenforcedSchemaPart(sub, `${path}.properties.${key}`); + if (part !== undefined) return part; + } } - if (schema['enum'] !== undefined && !Array.isArray(schema['enum'])) return false; // `validateNode` applies these two only when the node's type admits them if (additionalProperties !== undefined) { - if (!isObjectSchemaNode(schema)) return false; - if (typeof additionalProperties !== 'boolean' && !isFullyEnforced(additionalProperties)) - return false; + if (!isObjectSchemaNode(schema)) { + return { path, message: 'declares "additionalProperties" but is not an object schema' }; + } + if (typeof additionalProperties !== 'boolean') { + const part = unenforcedSchemaPart(additionalProperties, `${path}.additionalProperties`); + if (part !== undefined) return part; + } + } + if (items === undefined) return undefined; + if (!types.includes('array')) { + return { path, message: 'declares "items" but its type does not include "array"' }; } - if (items === undefined) return true; // A tuple `items` (an array of schemas) is not enforced - return types.includes('array') && isFullyEnforced(items); + return unenforcedSchemaPart(items, `${path}.items`); } /** Wrap a resource `inputSchema` in a reusable validator function */ diff --git a/src/core/no-answer.ts b/src/core/no-answer.ts index 8006cb7..9752cf8 100644 --- a/src/core/no-answer.ts +++ b/src/core/no-answer.ts @@ -19,7 +19,8 @@ const NO_ANSWER_CODES = new Set([ * Identify known transport failures for health checks and `doctor`. Search a * bounded cause chain for the codes above, `TimeoutError` (used by * `AbortSignal.timeout` and viem), or a name in `timeoutNames`. Return false - * for unrecognized errors so configuration failures are not treated as outages. + * for unrecognized errors, which keeps configuration failures from counting + * as outages. */ export function gotNoAnswer(err: unknown, timeoutNames: readonly string[] = []): boolean { let cause = err; diff --git a/src/payments/x402/provider/bazaar.ts b/src/payments/x402/provider/bazaar.ts index cd293db..72dcec9 100644 --- a/src/payments/x402/provider/bazaar.ts +++ b/src/payments/x402/provider/bazaar.ts @@ -5,9 +5,9 @@ import { validateBackendRequestShape } from '../../../core/execution/backend-req import { exampleObject, exampleValue, - objectInputSchema, + publishedInputSchema, } from '../../../core/execution/schema-example'; -import { compileJsonSchema, isFullyEnforced } from '../../../core/execution/validation'; +import { compileJsonSchema, unenforcedSchemaPart } from '../../../core/execution/validation'; /** The extension's key in a challenge's `extensions` */ export const BAZAAR_EXTENSION_KEY = 'bazaar'; @@ -40,13 +40,16 @@ const JSON_SCHEMA_2020_12 = 'https://json-schema.org/draft/2020-12/schema'; /** * Build Bazaar extensions for the requested surfaces. Metadata is omitted - * unless the generated example passes the input schema and backend request - * shape checks, and the schema uses the validator's supported subset. This - * avoids publishing examples that fail gateway validation before pricing. + * unless the generated example passes input schema and backend request shape + * checks, and the schema passes checks for supported keywords and valid values. + * These checks avoid publishing examples the gateway rejects before pricing + * or malformed schemas a facilitator cannot compile. `mimeType` is the + * resource's declared media type; an omitted value is treated as JSON. */ export function bazaarMetadata( resource: CommerceResource, surfaces: readonly BazaarSurface[], + mimeType?: string, ): BazaarMetadata { if (surfaces.length === 0) return { extensions: {}, omitted: [] }; const all = (reason: string): BazaarMetadata => ({ @@ -61,10 +64,9 @@ export function bazaarMetadata( ); } const schema = resource.inputSchema ?? {}; - if (!isFullyEnforced(schema)) { - return all( - 'its input schema uses a keyword the gateway does not enforce, which leaves the example unproven', - ); + const part = unenforcedSchemaPart(schema, 'input'); + if (part !== undefined) { + return all(`its input schema cannot be published as is: ${part.path} ${part.message}`); } const example = exampleObject(schema); if (!compileJsonSchema(schema)(example).valid || !shapeAccepts(resource, example)) { @@ -72,7 +74,7 @@ export function bazaarMetadata( } const built = { - http: () => httpForm(resource, schema, example), + http: () => httpForm(resource, schema, example, mimeType), mcp: () => mcpForm(resource, description, example), }; const extensions: Partial> = {}; @@ -111,17 +113,25 @@ function shapeAccepts(resource: CommerceResource, example: unknown): boolean { } } -// The invoke route takes the input as a JSON body +// Recognize JSON media types, including those with a `+json` syntax suffix +const JSON_MEDIA_TYPE = /^[^/;\s]+\/(?:[^;\s]+\+)?json\s*(?:;|$)/i; + +// The invoke route takes a JSON body. Match the x402 SDK builder by publishing +// `output` only when a JSON response example is available. function httpForm( resource: CommerceResource, schema: Record, example: Record, + mimeType: string | undefined, ): BazaarExtension { - const output = outputExample(resource.outputSchema); + const output = + mimeType === undefined || JSON_MEDIA_TYPE.test(mimeType) + ? outputExample(resource.outputSchema) + : undefined; return { info: { input: { type: 'http', method: 'POST', bodyType: 'json', body: example }, - output: { type: 'json', ...(output !== undefined ? { example: output } : {}) }, + ...(output !== undefined ? { output: { type: 'json', example: output } } : {}), }, schema: { $schema: JSON_SCHEMA_2020_12, @@ -138,14 +148,15 @@ function httpForm( required: ['type', 'method', 'bodyType', 'body'], additionalProperties: false, }, - output: { - type: 'object', - properties: { - type: { type: 'string' }, - ...(output !== undefined ? { example: resource.outputSchema } : {}), - }, - required: ['type'], - }, + ...(output !== undefined + ? { + output: { + type: 'object', + properties: { type: { type: 'string' }, example: resource.outputSchema }, + required: ['type'], + }, + } + : {}), }, required: ['input'], }, @@ -164,7 +175,7 @@ function mcpForm( type: 'mcp', toolName: resource.id, description, - inputSchema: objectInputSchema(resource.inputSchema), + inputSchema: publishedInputSchema(resource.inputSchema), example, }, }, @@ -193,7 +204,7 @@ function mcpForm( // Publish an output example only when its schema uses the supported subset // and local validation accepts it; runtime delivery does not validate output schemas function outputExample(schema: Record | undefined): unknown { - if (schema === undefined || !isFullyEnforced(schema)) return undefined; + if (schema === undefined || unenforcedSchemaPart(schema) !== undefined) return undefined; const example = exampleValue(schema, 'output'); return compileJsonSchema(schema)(example).valid ? example : undefined; } diff --git a/src/protocols/mcp/tool-mapping.ts b/src/protocols/mcp/tool-mapping.ts index 96c43ab..8f9bb5e 100644 --- a/src/protocols/mcp/tool-mapping.ts +++ b/src/protocols/mcp/tool-mapping.ts @@ -12,7 +12,7 @@ import { PAYMENT_INPUT_FIELD, type PaymentMethodName, } from '../../core'; -import { objectInputSchema } from '../../core/execution/schema-example'; +import { publishedInputSchema } from '../../core/execution/schema-example'; import { MPP_MCP_CREDENTIAL_META_KEY } from '../../payments/mpp/transport'; import { X402_MCP_PAYMENT_META_KEY } from '../../payments/x402/transport'; import { MCP_TOOL_NAME_PATTERN } from './constants'; @@ -109,7 +109,7 @@ export function buildToolDescription(resource: CommerceResource): string { * would otherwise refuse to send them. */ export function buildInputSchema(resource: CommerceResource): Tool['inputSchema'] { - const schema = objectInputSchema(resource.inputSchema); + const schema = publishedInputSchema(resource.inputSchema); const properties = { ...schema.properties } as Record; // Both overwrite a resource-declared property of the same name; config diff --git a/src/support/acp.json b/src/support/acp.json index 299dcdb..3df678c 100644 --- a/src/support/acp.json +++ b/src/support/acp.json @@ -68,7 +68,7 @@ ], "deviations": [ { - "summary": "After a merchant 5xx, retrying the same `Idempotency-Key` returns 409 `idempotency_unresolved` unless `protocols.acp.idempotency.merchantIdempotent` is true. The merchant may have acted, so another execution could duplicate the order.", + "summary": "After a merchant 5xx, retrying the same `Idempotency-Key` returns 409 `idempotency_unresolved` unless `protocols.acp.idempotency.merchantIdempotent` is true. The merchant may have acted, and another execution could duplicate the order.", "spec": "ACP RFC §6.5", "tests": ["tests/conformance/acp/idempotency.test.ts", "tests/conformance/acp/errors.test.ts"] } diff --git a/tests/integration/baseline-goldens.test.ts b/tests/integration/baseline-goldens.test.ts index 3b1251a..453fdc8 100644 --- a/tests/integration/baseline-goldens.test.ts +++ b/tests/integration/baseline-goldens.test.ts @@ -205,7 +205,7 @@ async function goldenConfig(x402: Record): Promise { protocols: { http: { enabled: true }, mcp: { enabled: true, mountPath: '/mcp' } }, resources: { forecast: backendResource(['http', 'mcp'], ['x402'], CITY), - // `pattern` is not enforced, so the resource is omitted from Bazaar metadata + // Omit Bazaar metadata for this resource because `pattern` is not enforced strict: backendResource(['http'], ['x402'], { type: 'object', properties: { city: { type: 'string', pattern: '^[A-Z]' } }, @@ -221,7 +221,7 @@ describe('x402 Bazaar metadata through the gateway', () => { it('warns about a resource left out at load, and still sells it', async () => { expect(issued('strict', 'http')).toBeUndefined(); expect(warn).toHaveBeenCalledWith( - expect.stringContaining('resource "strict" gets no Bazaar metadata on http'), + '[agent-commerce] resource "strict" gets no Bazaar metadata on http: its input schema cannot be published as is: input.properties.city uses "pattern", which the gateway does not enforce. Payment is unaffected.', ); const required = challengeOf(await invoke('strict', { city: 'Oslo' })); expect(required).not.toHaveProperty('extensions'); diff --git a/tests/unit/config/schema.test.ts b/tests/unit/config/schema.test.ts index 4d866b9..862f217 100644 --- a/tests/unit/config/schema.test.ts +++ b/tests/unit/config/schema.test.ts @@ -1206,6 +1206,45 @@ describe('parseConfig', () => { parseConfig(validRawConfig(), {}); expect(warnSpy).not.toHaveBeenCalled(); }); + + it.each(['minProperties', 'prefixItems', 'nullable', '$schema'])( + 'warns about %s, which the validator does not read', + (keyword) => { + const raw = validRawConfig(); + ( + raw['resources'] as { market_report: { input: Record } } + ).market_report.input = { + type: 'object', + properties: {}, + additionalProperties: false, + [keyword]: 1, + }; + parseConfig(raw, {}); + expect(warnSpy).toHaveBeenCalledTimes(1); + expect(warnSpy.mock.calls[0]?.[0]).toContain( + `resource "market_report" input uses JSON Schema keyword "${keyword}"`, + ); + }, + ); + + it('does not warn about annotations, the singular example of an imported schema included', () => { + const raw = validRawConfig(); + ( + raw['resources'] as { market_report: { input: Record } } + ).market_report.input = { + type: 'object', + title: 'Query', + description: 'A query', + properties: { + city: { type: 'string', example: 'Oslo', examples: ['Oslo'], default: 'Oslo' }, + old: { type: 'string', deprecated: true, readOnly: false, writeOnly: false }, + }, + $comment: 'internal', + additionalProperties: false, + }; + parseConfig(raw, {}); + expect(warnSpy).not.toHaveBeenCalled(); + }); }); it('rejects a schema declaring properties/required whose type excludes "object" - the validator would never enforce either', () => { @@ -2663,7 +2702,6 @@ describe('payments.x402.bazaar', () => { expect(Object.keys(bazaar ?? {})).toEqual(['market_report']); expect(bazaar?.['market_report']?.http?.info).toEqual({ input: { type: 'http', method: 'POST', bodyType: 'json', body: {} }, - output: { type: 'json' }, }); expect(bazaar?.['market_report']?.mcp?.info['input']).toMatchObject({ type: 'mcp', @@ -2715,9 +2753,36 @@ describe('payments.x402.bazaar', () => { 'x402', ]); expect(warn).toHaveBeenCalledWith( - '[agent-commerce] resource "market_report" gets no Bazaar metadata on http and mcp: its input schema uses a keyword the gateway does not enforce, which leaves the example unproven. Payment is unaffected.', + '[agent-commerce] resource "market_report" gets no Bazaar metadata on http and mcp: its input schema cannot be published as is: input.properties.ticker uses "pattern", which the gateway does not enforce. Payment is unaffected.', ); }); + + const OUTPUT = { + type: 'object', + properties: { ok: { type: 'boolean' } }, + required: ['ok'], + }; + + it('declares the JSON output example of a resource that names no media type', () => { + const raw = withBazaar(true); + marketReport(raw)['output'] = OUTPUT; + const bazaar = parseConfig(raw, {}).payments.x402?.resourceBazaar; + expect(bazaar?.['market_report']?.http?.info['output']).toEqual({ + type: 'json', + example: { ok: false }, + }); + }); + + it('declares no JSON output for a resource whose mimeType is text/html', () => { + const raw = withBazaar(true); + marketReport(raw)['output'] = OUTPUT; + marketReport(raw)['mimeType'] = 'text/html'; + const config = parseConfig(raw, {}); + expect(config.payments.x402?.resourceMimeTypes).toEqual({ market_report: 'text/html' }); + expect(config.payments.x402?.resourceBazaar?.['market_report']?.http?.info).toEqual({ + input: { type: 'http', method: 'POST', bodyType: 'json', body: {} }, + }); + }); }); describe('protocols.mcp.registry', () => { diff --git a/tests/unit/core/execution/validation.test.ts b/tests/unit/core/execution/validation.test.ts index 095baf6..34f6825 100644 --- a/tests/unit/core/execution/validation.test.ts +++ b/tests/unit/core/execution/validation.test.ts @@ -1,6 +1,6 @@ import Ajv2020 from 'ajv/dist/2020.js'; import { describe, expect, it } from 'vitest'; -import { compileJsonSchema, isFullyEnforced } from '../../../../src/core/execution/validation'; +import { compileJsonSchema, unenforcedSchemaPart } from '../../../../src/core/execution/validation'; describe('compileJsonSchema', () => { it('accepts anything when no schema is given', () => { @@ -298,7 +298,7 @@ describe('compileJsonSchema', () => { }); }); -describe('isFullyEnforced', () => { +describe('unenforcedSchemaPart', () => { const ENFORCED: readonly [string, Record][] = [ ['an empty schema', {}], [ @@ -325,39 +325,118 @@ describe('isFullyEnforced', () => { ], ]; - it.each(ENFORCED)('is true for %s', (_label, schema) => { - expect(isFullyEnforced(schema)).toBe(true); + it.each(ENFORCED)('finds no such part in %s', (_label, schema) => { + expect(unenforcedSchemaPart(schema)).toBeUndefined(); + }); + + it('accepts the singular example annotation that import openapi carries', () => { + expect(unenforcedSchemaPart({ type: 'string', example: 'Oslo' })).toBeUndefined(); }); it.each([ - ['a non-object schema', true], - ['an unenforced keyword', { type: 'string', minLength: 1 }], - ['a keyword the config warning list lacks', { type: 'object', minProperties: 1 }], + ['a non-object schema', true, '$', 'is not a schema object'], + ['an unenforced keyword', { type: 'string', minLength: 1 }, '$', 'uses "minLength"'], + [ + 'a keyword the former config warning list lacked', + { type: 'object', minProperties: 1 }, + '$', + 'uses "minProperties"', + ], [ 'an unenforced keyword in a property', { properties: { a: { type: 'string', format: 'email' } } }, + '$.properties.a', + 'uses "format"', ], [ 'an unenforced keyword in additionalProperties', { type: 'object', additionalProperties: { const: 1 } }, + '$.additionalProperties', + 'uses "const"', + ], + [ + 'an unenforced keyword in items', + { type: 'array', items: { type: 'string', pattern: 'x' } }, + '$.items', + 'uses "pattern"', + ], + [ + 'a boolean property schema', + { properties: { a: true } }, + '$.properties.a', + 'is not a schema object', + ], + [ + 'a tuple items', + { type: 'array', items: [{ type: 'string' }] }, + '$.items', + 'is not a schema object', + ], + ['items without an array type', { items: { type: 'string' } }, '$', 'declares "items"'], + [ + 'additionalProperties without an object node', + { additionalProperties: false }, + '$', + 'declares "additionalProperties"', ], - ['an unenforced keyword in items', { type: 'array', items: { type: 'string', pattern: 'x' } }], - ['a boolean property schema', { properties: { a: true } }], - ['a tuple items', { type: 'array', items: [{ type: 'string' }] }], - ['items without an array type', { items: { type: 'string' } }], - ['additionalProperties without an object node', { additionalProperties: false }], - ['an unknown type', { type: 'date' }], - ['an empty type list', { type: [] }], - ['a non-string type', { type: [1] }], - ['a non-array enum', { enum: 'a' }], - ['non-string required entries', { type: 'object', required: [1] }], - ['a non-object properties', { properties: [] }], - ['$ref', { $ref: '#/$defs/a' }], - ['$schema', { $schema: 'https://json-schema.org/draft/2020-12/schema' }], - ])('is false for %s', (_label, schema) => { - expect(isFullyEnforced(schema)).toBe(false); + ['an unknown type', { type: 'date' }, '$', 'has a "type"'], + ['an empty type list', { type: [] }, '$', 'has a "type"'], + ['a non-string type', { type: [1] }, '$', 'has a "type"'], + ['a non-array enum', { enum: 'a' }, '$', 'has a "enum"'], + ['non-string required entries', { type: 'object', required: [1] }, '$', 'has a "required"'], + ['a non-object properties', { properties: [] }, '$', 'has a "properties"'], + ['$ref', { $ref: '#/$defs/a' }, '$', 'uses "$ref"'], + ['$schema', { $schema: 'https://json-schema.org/draft/2020-12/schema' }, '$', 'uses "$schema"'], + ])('names the place of %s', (_label, schema, path, fragment) => { + const part = unenforcedSchemaPart(schema); + expect(part?.path).toBe(path); + expect(part?.message).toContain(fragment); + }); + + it('starts the path at the name it is given', () => { + expect( + unenforcedSchemaPart({ properties: { q: { type: 'string', pattern: 'x' } } }, 'input'), + ).toEqual({ + path: 'input.properties.q', + message: 'uses "pattern", which the gateway does not enforce', + }); }); + // Ajv rejects these malformed schemas during compilation + const MALFORMED: readonly [string, Record, string, string][] = [ + ['a repeated required name', { type: 'object', required: ['a', 'a'] }, '$', 'required'], + ['a repeated type', { type: ['object', 'object'] }, '$', 'type'], + ['an empty enum', { enum: [] }, '$', 'enum'], + ['examples that are not a list', { type: 'string', examples: 'x' }, '$', 'examples'], + ['a numeric description', { type: 'string', description: 5 }, '$', 'description'], + ['a numeric title', { type: 'string', title: 7 }, '$', 'title'], + ['a numeric $comment', { type: 'string', $comment: 1 }, '$', '$comment'], + [ + 'a deprecated that is not a boolean', + { type: 'string', deprecated: 'yes' }, + '$', + 'deprecated', + ], + ['a readOnly that is not a boolean', { type: 'string', readOnly: 1 }, '$', 'readOnly'], + ['a writeOnly that is not a boolean', { type: 'string', writeOnly: 'no' }, '$', 'writeOnly'], + [ + 'a malformed value in a nested property', + { type: 'object', properties: { a: { type: 'object', required: ['b', 'b'] } } }, + '$.properties.a', + 'required', + ], + ]; + + it.each(MALFORMED)( + 'names %s, which Ajv 2020-12 refuses to compile', + (_label, schema, path, keyword) => { + expect(() => new Ajv2020({ strict: false }).compile(schema)).toThrow(); + const part = unenforcedSchemaPart(schema); + expect(part?.path).toBe(path); + expect(part?.message).toContain(`has a "${keyword}"`); + }, + ); + // Compare gateway and Ajv 2020-12 verdicts for these schemas and sample values const ajv = new Ajv2020({ strict: false }); const VALUES: readonly unknown[] = [ diff --git a/tests/unit/payments-x402/bazaar.test.ts b/tests/unit/payments-x402/bazaar.test.ts index cf4cfd5..bc86f6a 100644 --- a/tests/unit/payments-x402/bazaar.test.ts +++ b/tests/unit/payments-x402/bazaar.test.ts @@ -70,7 +70,6 @@ describe('Bazaar metadata forms', () => { it('describes the invoke route as a POST of the example JSON body', () => { expect(extensionOf('http').info).toEqual({ input: { type: 'http', method: 'POST', bodyType: 'json', body: EXAMPLE }, - output: { type: 'json' }, }); }); @@ -171,9 +170,42 @@ describe('Bazaar metadata forms', () => { { type: 'object', properties: { at: { type: 'string', format: 'date' } } }, ], ['rejects its own generated example', { type: 'string', enum: [1] }], - ])('leaves out the output example when the output schema %s', (_label, outputSchema) => { - expect(extensionOf('http', resource({ outputSchema })).info['output']).toEqual({ + ['gives a keyword a malformed value', { type: 'object', required: ['a', 'a'] }], + ])('declares no output when the output schema %s', (_label, outputSchema) => { + const extension = extensionOf('http', resource({ outputSchema })); + expect(extension.info).not.toHaveProperty('output'); + expect(extension.schema['properties']).not.toHaveProperty('output'); + expect(validateDiscoveryExtension(extension as never)).toEqual({ valid: true }); + }); + + const OUTPUT = { + type: 'object', + properties: { forecast: { type: 'string' } }, + required: ['forecast'], + }; + const httpWith = (mimeType: string) => + bazaarMetadata(resource({ outputSchema: OUTPUT }), ['http'], mimeType).extensions.http; + + it.each(['text/html', 'text/plain; charset=utf-8', 'application/xml', 'application/jsonl'])( + 'declares no JSON output for a resource whose media type is %s', + (mimeType) => { + const extension = httpWith(mimeType); + expect(extension?.info).toEqual({ + input: { type: 'http', method: 'POST', bodyType: 'json', body: EXAMPLE }, + }); + expect(validateDiscoveryExtension(extension as never)).toEqual({ valid: true }); + }, + ); + + it.each([ + 'application/json', + 'application/json; charset=utf-8', + 'application/problem+json', + 'Application/JSON', + ])('declares the JSON output example for a resource whose media type is %s', (mimeType) => { + expect(httpWith(mimeType)?.info['output']).toEqual({ type: 'json', + example: { forecast: '' }, }); }); @@ -207,35 +239,83 @@ describe('Bazaar metadata omission', () => { }, }); + const NOT_ENFORCED = 'which the gateway does not enforce'; + const BAD_TYPE = 'has a "type" that is not a supported type or a list of distinct ones'; + it.each([ - ['pattern', nested({ type: 'string', pattern: '^[A-Z]' })], + [ + 'pattern', + nested({ type: 'string', pattern: '^[A-Z]' }), + `input.properties.city uses "pattern", ${NOT_ENFORCED}`, + ], [ 'a nested format', nested({ type: 'object', properties: { d: { type: 'string', format: 'date' } } }), + `input.properties.city.properties.d uses "format", ${NOT_ENFORCED}`, ], - ['$ref', nested({ $ref: '#/$defs/city' })], [ - 'minProperties, which config does not warn about', + '$ref', + nested({ $ref: '#/$defs/city' }), + `input.properties.city uses "$ref", ${NOT_ENFORCED}`, + ], + [ + 'minProperties', resource({ inputSchema: { type: 'object', minProperties: 1 } }), + `input uses "minProperties", ${NOT_ENFORCED}`, + ], + [ + 'a tuple items', + nested({ type: 'array', items: [{ type: 'string' }] }), + 'input.properties.city.items is not a schema object', + ], + [ + 'additionalProperties without an object type', + nested({ additionalProperties: false }), + 'input.properties.city declares "additionalProperties" but is not an object schema', + ], + [ + 'items without an array type', + nested({ items: { type: 'string' } }), + 'input.properties.city declares "items" but its type does not include "array"', ], - ['a tuple items', nested({ type: 'array', items: [{ type: 'string' }] })], - ['additionalProperties without an object type', nested({ additionalProperties: false })], - ['items without an array type', nested({ items: { type: 'string' } })], - ['an empty type list', nested({ type: [] })], - ['an unknown type', nested({ type: 'date' })], - ])('leaves out a resource whose input schema uses %s', (_label, of) => { + ['an empty type list', nested({ type: [] }), `input.properties.city ${BAD_TYPE}`], + ['an unknown type', nested({ type: 'date' }), `input.properties.city ${BAD_TYPE}`], + ])('leaves out a resource whose input schema uses %s, naming the place', (_label, of, place) => { expect(bazaarMetadata(of, BOTH)).toEqual({ extensions: {}, - omitted: [ - { - surfaces: BOTH, - reason: - 'its input schema uses a keyword the gateway does not enforce, which leaves the example unproven', - }, - ], + omitted: [{ surfaces: BOTH, reason: `its input schema cannot be published as is: ${place}` }], }); }); + // Gateway validation tolerates these malformed keyword values, but the + // facilitator's schema compiler rejects them + it.each([ + ['a repeated required name', { type: 'object', required: ['a', 'a'] }, 'required'], + ['a repeated type', { type: ['string', 'string'] }, 'type'], + ['examples that are not a list', { type: 'string', examples: 'x' }, 'examples'], + ['a numeric description', { type: 'string', description: 5 }, 'description'], + ['a numeric title', { type: 'string', title: 7 }, 'title'], + ['a deprecated that is not a boolean', { type: 'string', deprecated: 'yes' }, 'deprecated'], + ['an empty enum', { enum: [] }, 'enum'], + ])( + 'leaves out a resource whose input schema has %s, which upstream validation refuses', + (_label, property, keyword) => { + // Replace a valid property schema in the published HTTP form with this one + const published = extensionOf('http'); + const withProperty = structuredClone(published) as unknown as { + schema: { properties: { input: { properties: { body: JsonSchema } } } }; + }; + withProperty.schema.properties.input.properties.body = nested(property) + .inputSchema as JsonSchema; + expect(validateDiscoveryExtension(withProperty as never).valid).toBe(false); + + const { extensions, omitted } = bazaarMetadata(nested(property), BOTH); + expect(extensions).toEqual({}); + expect(omitted).toHaveLength(1); + expect(omitted[0]?.reason).toContain(`input.properties.city has a "${keyword}"`); + }, + ); + it.each([ ['fails the input schema', nested({ type: 'string', enum: [1] })], [ @@ -293,9 +373,9 @@ describe('Bazaar metadata omission', () => { it('leaves out each surface whose extension exceeds 4 KiB, and keeps the others', () => { // The MCP form also carries the description. With it at 480 characters - // and 44 properties, MCP is over 4096 bytes and HTTP under. + // and 45 properties, MCP is over 4096 bytes and HTTP under. const properties = Object.fromEntries( - Array.from({ length: 44 }, (_, i) => [`property_${i}`, { type: 'string' }]), + Array.from({ length: 45 }, (_, i) => [`property_${i}`, { type: 'string' }]), ); const of = resource({ description: 'd'.repeat(480), From 0519df75a1716885548a67fa5ec179f6dd6bf863 Mon Sep 17 00:00:00 2001 From: Revinand Date: Wed, 18 Nov 2026 23:04:44 +0100 Subject: [PATCH 11/14] fix(x402): reserve proof header room and gate Bazaar forwarding on /supported --- docs/configuration.md | 8 +- docs/contracts.md | 10 +- docs/protocols/x402.md | 35 ++- docs/security.md | 4 +- src/payments/x402/payload.ts | 5 +- .../x402/provider/bazaar-forwarding.ts | 85 +++++++ src/payments/x402/provider/index.ts | 6 +- src/payments/x402/provider/requirement.ts | 45 +++- src/payments/x402/provider/settle.ts | 12 +- src/payments/x402/provider/types.ts | 7 +- src/payments/x402/provider/verify.ts | 12 +- tests/e2e/payment/x402-bazaar.e2e.test.ts | 24 +- tests/fixtures/x402/loopback-facilitator.ts | 4 +- tests/integration/x402-bazaar.test.ts | 56 ++++- .../payments-x402/bazaar-challenge.test.ts | 209 +++++++++++++++++- .../unit/payments-x402/provider-near.test.ts | 25 +++ tests/unit/payments-x402/provider-svm.test.ts | 42 ++++ 17 files changed, 538 insertions(+), 51 deletions(-) create mode 100644 src/payments/x402/provider/bazaar-forwarding.ts diff --git a/docs/configuration.md b/docs/configuration.md index 203d83d..ccfe1bb 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -722,9 +722,11 @@ the resource id, affected surfaces and reason. Omitting metadata leaves payment behavior unchanged. [x402](protocols/x402.md#bazaar-discovery-metadata) lists the rules. -Choose a facilitator that accepts Bazaar metadata. When a challenge carries -it, verify and settle forward that metadata. On HTTP, a Bazaar validation -rejection can cause repeated 402 challenges. +Choose a facilitator whose `/supported` response lists `bazaar` among its +extensions. Verify and settle forward metadata only to these remote +facilitators. Other facilitators receive the proof without metadata. If a +facilitator lists the extension but rejects payment because of the metadata, +HTTP buyers can receive repeated 402 challenges. ### `payments.mpp` diff --git a/docs/contracts.md b/docs/contracts.md index d637bcc..41e8d38 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -483,9 +483,13 @@ persistence must not fail the commerce flow. - With `payments.x402.bazaar.enabled: true`, config normalization fills `GatewayConfig.payments.x402.resourceBazaar` with metadata that passes the omission rules. MPP's internal x402 provider does not receive it. - - For a challenge carrying Bazaar metadata, verify and settle send its - `resource` and `extensions.bazaar` to the facilitator, replacing those - fields from the proof. + - When a challenge carries Bazaar metadata, verify and settle send its + `resource` and `extensions.bazaar` to a remote facilitator that lists + `bazaar` in `/supported`, replacing those fields from the proof. Any other + facilitator receives neither. + - An HTTP challenge omits the metadata unless its encoded + `PAYMENT-REQUIRED` value plus the largest proof reserve among its offer + families fits within 8192 bytes. - Without the option, challenges and facilitator bodies are unchanged. - 2.8.0: experimental `GatewayConfig.protocols.mcp.registry` holds the `name`, `version` and `description` from `protocols.mcp.registry` and is diff --git a/docs/protocols/x402.md b/docs/protocols/x402.md index 4baee6f..6fc6cad 100644 --- a/docs/protocols/x402.md +++ b/docs/protocols/x402.md @@ -184,13 +184,34 @@ probes usable, config loading omits metadata and warns when: A schema warning names the keyword and its path, such as `input.properties.city uses "pattern"`. -If adding Bazaar would push the base64 `PAYMENT-REQUIRED` value over 8192 bytes, -the HTTP challenge omits it. A `warn` log names the resource once per provider -instance. Omitting metadata leaves payment behavior unchanged. - -On verify and settle, the facilitator receives the challenge's `resource` and -`extensions.bazaar`, replacing the proof's values. No other extension is -forwarded. +An HTTP challenge omits Bazaar unless its base64 `PAYMENT-REQUIRED` value plus +a proof reserve fits within 8192 bytes. SDK clients repeat `extensions` beside +the signed payload in `PAYMENT-SIGNATURE`; nginx's default request header field +limit is 8 KiB. The reserve is 1024 bytes for EVM offers, 1280 for NEAR and 2304 +for Solana. A resource with several offers uses the largest reserve. It also +leaves room for the `error` field added to a challenge after a refused proof. +Contract wallet signatures may exceed the EVM allowance. A `warn` log names +each resource that exceeds the budget, once per provider instance. MCP carries +the challenge in the result body, where this header budget does not apply. +Omitting metadata leaves payment behavior unchanged. + +On verify and settle, a remote facilitator that lists `bazaar` in the +`extensions` of its `/supported` response (x402 v2, section 7.3) receives the +challenge's `resource` and `extensions.bazaar`, replacing the proof's values. +No other extension is forwarded. A facilitator whose response does not list +`bazaar` receives neither field. This avoids sending unsupported fields that +could cause it to reject the buyer's payment. The challenge still carries the +metadata, and a `warn` log names the facilitator once per provider instance. +The `/supported` response is cached for a minute. If the read fails or takes +longer than one second, that verify or settle call proceeds without metadata. +The in-process facilitator keeps no catalog and receives no metadata. + +A facilitator can report metadata processing outcomes in the +`EXTENSION-RESPONSES` header of a verify or settle response. For +`bazaar.status: "rejected"`, the gateway logs a `warn` with the resource id and +up to 200 characters of the reason, once per resource and provider instance. +This metadata outcome does not change the payment result. The pinned x402 SDK +also prints selected status, reason and code fields from each outcome to stdout. ## Payment identifier diff --git a/docs/security.md b/docs/security.md index 9ec7567..4c8bed1 100644 --- a/docs/security.md +++ b/docs/security.md @@ -339,9 +339,11 @@ real funds. | **a proof's `payment-identifier`, ERC-8409 quote or gas-sponsoring extension, under Bazaar** | none of the proof's extensions are forwarded; the facilitator receives only the challenge's `extensions.bazaar` | `tests/unit/payments-x402/bazaar-challenge.test.ts`, `tests/e2e/payment/x402-bazaar.e2e.test.ts` | | **Bazaar metadata echoed from another surface, with several offers** | offer selection still uses `accepted`; the facilitator receives the challenge's own metadata | `tests/unit/payments-x402/bazaar-challenge.test.ts` | | **Bazaar metadata exposing a backend URL, header, credential, reserved field or unexposed surface** | backend connection settings are not copied; resource ids, descriptions, schemas and generated examples are public metadata. Schema and example contents are not redacted. Bazaar adds no `_payment` or `_authorization` carriers; unexposed surfaces receive no metadata | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/config/schema.test.ts` | -| **a Bazaar extension large enough to break the `PAYMENT-REQUIRED` header, and payment with it** | config loading omits extensions over 4096 bytes and warns; an HTTP challenge omits Bazaar if it would push the encoded header value over 8192 bytes. Payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/payments-x402/bazaar-challenge.test.ts` | +| **a Bazaar extension large enough to break the `PAYMENT-REQUIRED` header or the buyer's `PAYMENT-SIGNATURE` echo, and payment with it** | config loading omits extensions over 4096 bytes and warns; an HTTP challenge omits Bazaar if its encoded value plus the proof reserve exceeds 8192 bytes (1024 for EVM offers, 1280 for NEAR, 2304 for Solana; the largest applies). The reserve also allows for the `error` field after a refused proof. Payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/payments-x402/bazaar-challenge.test.ts` ("fits the SDK client echo of the largest kept challenge in an 8192-byte header", "leaves it out of an HTTP challenge one byte over, and logs that once per resource") | | **a generated Bazaar example the gateway would refuse, silently dropping the listing** | config loading omits the resource's metadata and warns with its id, affected surfaces and reason; payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/config/schema.test.ts`, `tests/integration/x402-bazaar.test.ts` | | **an input schema the gateway accepts and a facilitator cannot compile, silently dropping the listing** | config loading omits metadata for malformed keyword values detected by the JSON Schema 2020-12 checks or an empty `enum`; warnings name the keyword and its path | `tests/unit/core/execution/validation.test.ts`, `tests/unit/payments-x402/bazaar.test.ts` ("leaves out a resource whose input schema has ..., which upstream validation refuses") | +| **a facilitator that does not implement Bazaar refusing a payment over the forwarded fields, and the buyer blamed for it** | verify and settle forward `resource` and `extensions.bazaar` only to a remote facilitator that lists `bazaar` in `/supported`; when that read fails or takes over one second, the call sends neither | `tests/unit/payments-x402/bazaar-challenge.test.ts` ("Bazaar metadata and the facilitator /supported list"), `tests/integration/x402-bazaar.test.ts`, `tests/e2e/payment/x402-bazaar.e2e.test.ts` | +| **a facilitator rejecting a Bazaar listing unnoticed, or adding unbounded reason text to the gateway log** | the gateway logs a `rejected` outcome in `EXTENSION-RESPONSES` at `warn` once per resource and provider instance; it redacts URLs in the reason to scheme and host before truncating it to 200 characters. This metadata outcome does not change the payment result | `tests/unit/payments-x402/bazaar-challenge.test.ts` ("Bazaar outcome from the facilitator") | | **an AP2 mandate approved for one x402 offer, presented with a proof for another** | selected destination, network or asset fails mandate binding; no settlement | `tests/unit/core/execution/pipeline-authorization.test.ts` | | **an EIP-3009 authorization signed for one EVM chain, presented as another chain's offer** | `invalid_exact_evm_signature`: signature fails against the other chain's EIP-712 domain; neither chain's balances change | `tests/e2e/payment/x402-multichain.e2e.test.ts` | | **the same payer, token address and nonce on two EVM chains** | both settle: the replay key includes the chain id | same | diff --git a/src/payments/x402/payload.ts b/src/payments/x402/payload.ts index 72e4ff9..814acbb 100644 --- a/src/payments/x402/payload.ts +++ b/src/payments/x402/payload.ts @@ -36,8 +36,9 @@ export function declaredX402Version(payloadBase64: string): unknown { * unsupported SDK facilitator behavior. * * When the `issued` challenge carries Bazaar metadata, attach its `resource` - * and `extensions.bazaar` for cataloging. Use the issued values so a buyer's - * altered echo cannot replace the listing metadata. + * and `extensions.bazaar` for cataloging. The provider passes `issued` only + * for a facilitator that lists the extension. Use the issued values to keep + * an altered buyer echo from replacing the listing metadata. */ export function forFacilitator( payload: T, diff --git a/src/payments/x402/provider/bazaar-forwarding.ts b/src/payments/x402/provider/bazaar-forwarding.ts new file mode 100644 index 0000000..da8daab --- /dev/null +++ b/src/payments/x402/provider/bazaar-forwarding.ts @@ -0,0 +1,85 @@ +// Forward Bazaar metadata to supporting facilitators and log cataloging outcomes +import type { PaymentRequired } from '@x402/core/types'; +import { redactedErrorText } from '../../../core/errors'; +import { isRecord } from '../../../core/is-record'; +import { BAZAAR_EXTENSION_KEY } from './bazaar'; +import type { SupportedSource } from './fee-payer'; +import type { ProviderContext } from './types'; + +// Maximum wait for `/supported` before forwarding a proof without metadata +const SUPPORTED_GRACE_MS = 1_000; +// Bound the amount of facilitator-controlled reason text written to the log +const MAX_LOGGED_REASON_LENGTH = 200; + +export interface BazaarForwarding { + /** + * Return `issued` when it carries Bazaar metadata and the remote facilitator + * lists `bazaar` in `/supported`. Otherwise return `undefined`, which omits + * its `resource` and metadata. Failed or slow reads omit them too. + */ + issuedFor(issued: PaymentRequired | undefined): Promise; + /** Log a cataloging refusal from a verify or settle result, once per resource */ + report(resourceId: string, extensionResponses: Record | undefined): void; +} + +/** + * Forward metadata only to remote facilitators that list `bazaar` in + * `/supported`, as specified in x402 v2 section 7.3. Unsupported fields could + * otherwise cause a facilitator to reject the buyer's payment. The in-process + * facilitator keeps no catalog and receives no metadata. Wait up to one second + * for `/supported`, then proceed without metadata if the read is slow or fails. + */ +export function createBazaarForwarding( + ctx: ProviderContext, + currentSupported: SupportedSource, +): BazaarForwarding { + const { remoteBinding, logger } = ctx; + let unlistedLogged = false; + const rejectedLogged = new Set(); + + async function listed(): Promise { + if (remoteBinding?.kind !== 'remote') return false; + let timer: NodeJS.Timeout | undefined; + const late = new Promise((resolve) => { + timer = setTimeout(() => resolve(undefined), SUPPORTED_GRACE_MS); + timer.unref(); + }); + const supported = await Promise.race([currentSupported(), late]) + .catch(() => undefined) + .finally(() => clearTimeout(timer)); + if (supported === undefined) return false; + const lists = + Array.isArray(supported.extensions) && supported.extensions.includes(BAZAAR_EXTENSION_KEY); + if (!lists && !unlistedLogged) { + unlistedLogged = true; + logger.warn( + { facilitator: remoteBinding.describe }, + 'x402: the facilitator does not list the bazaar extension in /supported; Bazaar metadata stays in challenges but is not sent to it', + ); + } + return lists; + } + + return { + async issuedFor(issued) { + if (issued?.extensions?.[BAZAAR_EXTENSION_KEY] === undefined) return undefined; + return (await listed()) ? issued : undefined; + }, + report(resourceId, extensionResponses) { + const outcome = extensionResponses?.[BAZAAR_EXTENSION_KEY]; + if (!isRecord(outcome) || outcome['status'] !== 'rejected') return; + if (rejectedLogged.has(resourceId)) return; + rejectedLogged.add(resourceId); + const reason = outcome['rejectedReason']; + logger.warn( + { + resourceId, + ...(typeof reason === 'string' + ? { reportedReason: redactedErrorText(reason).slice(0, MAX_LOGGED_REASON_LENGTH) } + : {}), + }, + 'x402: the facilitator rejected the Bazaar metadata of a resource and will not catalog it. Payment is unaffected', + ); + }, + }; +} diff --git a/src/payments/x402/provider/index.ts b/src/payments/x402/provider/index.ts index 7fccb9a..816f67d 100644 --- a/src/payments/x402/provider/index.ts +++ b/src/payments/x402/provider/index.ts @@ -15,6 +15,7 @@ import { CommerceError, NOOP_LOGGER, systemClock } from '../../../core'; import { descriptorStatus, exclusionNames } from '../../../support/claims'; import record from '../../../support/x402.json' with { type: 'json' }; import { PACKAGE_VERSION } from '../../../version'; +import { createBazaarForwarding } from './bazaar-forwarding'; import { DEFAULT_IDS, DEFAULT_MAX_TIMEOUT_SECONDS, X402_VERSION } from './constants'; import { createNearRelayerSource, @@ -156,8 +157,9 @@ export function createX402PaymentProvider( ctx, createSvmFeePayerSource(supported), ); - const verify = createVerify(ctx, createNearRelayerSource(supported, logger)); - const settle = createSettle(ctx); + const bazaar = createBazaarForwarding(ctx, supported); + const verify = createVerify(ctx, createNearRelayerSource(supported, logger), bazaar); + const settle = createSettle(ctx, bazaar); const health = createHealthCheck(ctx); return { diff --git a/src/payments/x402/provider/requirement.ts b/src/payments/x402/provider/requirement.ts index b7c5676..76b43bc 100644 --- a/src/payments/x402/provider/requirement.ts +++ b/src/payments/x402/provider/requirement.ts @@ -13,11 +13,26 @@ import { X402_DEFAULT_PAYMENT_FLOW } from '../payment-flow'; import { BAZAAR_EXTENSION_KEY } from './bazaar'; import { DEFAULT_MIME_TYPE, X402_PROTOCOL_VERSION, X402_VERSION } from './constants'; import { paymentIdentifierExtensions } from './payment-id'; -import type { ProviderContext, SvmOffer } from './types'; +import type { Offer, ProviderContext, SvmOffer } from './types'; -// Budget for the encoded PAYMENT-REQUIRED value when adding Bazaar metadata; -// large headers may be rejected by proxies -const MAX_HTTP_CHALLENGE_HEADER_BYTES = 8192; +// Budget for a header value with Bazaar metadata, based on nginx's default +// 8 KiB request header field limit. Proxies may reject larger headers. +const MAX_HTTP_HEADER_BYTES = 8192; + +/** + * Reserve space below the header budget for the proof. The buyer's + * `PAYMENT-SIGNATURE` repeats `resource`, `extensions` and one offer + * beside its signed payload, which after base64 takes about 0.6 KB for + * EIP-3009 and 0.8 KB for Permit2 with an EOA signature, under 1 KB for a + * NEAR delegate action and 2.2 KB for a full-size Solana transaction. A + * contract wallet's signature can exceed the EVM figure. The reserve also + * covers `error`, which the HTTP adapter adds to a refused proof's challenge. + */ +const PROOF_RESERVE_BYTES: Readonly> = { + evm: 1024, + svm: 2304, + near: 1280, +}; // Requirement metadata naming the offer `selectRequirement` chose, by index export const SELECTED_OFFER_KEY = 'x402.offer'; @@ -155,7 +170,15 @@ export function createRequirementBuilders( const challenge = bazaar === undefined ? envelope - : withBazaar(envelope, bazaar, context.protocol === 'http', context.resource.id); + : withBazaar( + envelope, + bazaar, + // MCP carries the challenge in the result body, not a header + context.protocol === 'http' + ? Math.max(...offers.map((offer) => PROOF_RESERVE_BYTES[offer.family])) + : undefined, + context.resource.id, + ); const expiresAt = new Date(clock.now().getTime() + maxTimeoutSeconds * 1000).toISOString(); @@ -186,24 +209,26 @@ export function createRequirementBuilders( }; } - // Omit Bazaar from oversized HTTP challenges to reduce proxy header failures + // Omit Bazaar if the HTTP challenge plus its proof reserve exceeds 8 KiB. + // `headerReserve` is undefined for other surfaces. function withBazaar( envelope: PaymentRequired, bazaar: unknown, - http: boolean, + headerReserve: number | undefined, resourceId: string, ): PaymentRequired { const extended = { ...envelope, extensions: { ...envelope.extensions, [BAZAAR_EXTENSION_KEY]: bazaar }, }; + if (headerReserve === undefined) return extended; const encoded = 4 * Math.ceil(Buffer.byteLength(JSON.stringify(extended)) / 3); - if (!http || encoded <= MAX_HTTP_CHALLENGE_HEADER_BYTES) return extended; + if (encoded + headerReserve <= MAX_HTTP_HEADER_BYTES) return extended; if (!oversizedLogged.has(resourceId)) { oversizedLogged.add(resourceId); logger.warn( - { resourceId, bytes: encoded }, - 'x402: Bazaar metadata left out of an HTTP challenge whose PAYMENT-REQUIRED header would exceed 8 KiB', + { resourceId, bytes: encoded, reservedBytes: headerReserve }, + 'x402: Bazaar metadata left out of an HTTP challenge too large to leave room for the signed proof in an 8 KiB header', ); } return envelope; diff --git a/src/payments/x402/provider/settle.ts b/src/payments/x402/provider/settle.ts index e0224bb..70eb9e5 100644 --- a/src/payments/x402/provider/settle.ts +++ b/src/payments/x402/provider/settle.ts @@ -5,6 +5,7 @@ import { CommerceError } from '../../../core'; import { redactedErrorText } from '../../../core/errors'; import { isTransactionReference } from '../addresses'; import { decodePaymentSubmission, forFacilitator } from '../payload'; +import type { BazaarForwarding } from './bazaar-forwarding'; import { isNearVerdict, isOnChainRevertError, @@ -23,6 +24,7 @@ import type { ProviderContext } from './types'; /** Builds the provider's `settle`, which throws unless handed a successful verification */ export function createSettle( ctx: ProviderContext, + bazaar: BazaarForwarding, ): (context: PaymentSettlementContext) => Promise { const { offersFor, clock, logger } = ctx; @@ -70,13 +72,13 @@ export function createSettle( rejectionReason, }); + const issued = await bazaar.issuedFor( + requirement.challenge.envelope as PaymentRequired | undefined, + ); const scope = offer.binding.open(); let sdkResult: SettleResponse; try { - sdkResult = await scope.settle( - forFacilitator(payload, requirement.challenge.envelope as PaymentRequired | undefined), - requirements, - ); + sdkResult = await scope.settle(forFacilitator(payload, issued), requirements); } catch (err) { if (isProviderUnavailableError(err) || scope.transportFailed()) { throw new CommerceError( @@ -109,6 +111,8 @@ export function createSettle( return rejectedSettlement('transaction_reverted'); } + bazaar.report(requirement.resourceId, sdkResult.extensionResponses); + // verify() established the payer. The Solana scheme's settlement example // names the fee payer there, while x402 v2 defines the payer's wallet. const payer = verification.payer ?? sdkResult.payer; diff --git a/src/payments/x402/provider/types.ts b/src/payments/x402/provider/types.ts index eeccf26..2d27042 100644 --- a/src/payments/x402/provider/types.ts +++ b/src/payments/x402/provider/types.ts @@ -28,9 +28,10 @@ export interface X402ProviderOptions extends X402OfferOptions { readonly resourceMimeTypes?: Readonly>; /** * Experimental. Maps resource ids and HTTP/MCP surfaces to the challenge's - * `extensions.bazaar` value. Omitted from HTTP challenges when it would make - * the encoded `PAYMENT-REQUIRED` value exceed 8 KiB. When present, verify and - * settle send it and the challenge's `resource` to the facilitator. + * `extensions.bazaar` value. Omitted when the encoded HTTP challenge's + * `PAYMENT-REQUIRED` value plus its proof reserve exceeds 8 KiB. + * Verify and settle send it and the challenge's `resource` to a remote + * facilitator that lists `bazaar` in `/supported`. */ readonly resourceBazaar?: Readonly< Record>>> diff --git a/src/payments/x402/provider/verify.ts b/src/payments/x402/provider/verify.ts index b0e4689..697543f 100644 --- a/src/payments/x402/provider/verify.ts +++ b/src/payments/x402/provider/verify.ts @@ -6,6 +6,7 @@ import { CommerceError, RECONCILIATION_METADATA_KEY } from '../../../core'; import { redactedErrorText } from '../../../core/errors'; import { normalizeAddress, sameAddress } from '../addresses'; import { declaredX402Version, decodePaymentSubmission, forFacilitator } from '../payload'; +import type { BazaarForwarding } from './bazaar-forwarding'; import { X402_VERSION } from './constants'; import { offerCurrency } from './offers'; import { paymentIdentifierEchoed } from './payment-id'; @@ -22,6 +23,7 @@ const RELAYER_GRACE_MS = 1_000; export function createVerify( ctx: ProviderContext, nearRelayers: (offer: NearOffer) => Promise, + bazaar: BazaarForwarding, ): (context: PaymentVerificationContext) => Promise { const { offersFor, clock, logger, svm, near } = ctx; @@ -167,13 +169,13 @@ export function createVerify( // Fetch NEAR relayers alongside verification; failed `/supported` reads yield none const relayers = offer.family === 'near' ? nearRelayers(offer) : undefined; + const issued = await bazaar.issuedFor( + requirement.challenge.envelope as PaymentRequired | undefined, + ); const scope = offer.binding.open(); let sdkResult: VerifyResponse; try { - sdkResult = await scope.verify( - forFacilitator(payload, requirement.challenge.envelope as PaymentRequired | undefined), - requirements, - ); + sdkResult = await scope.verify(forFacilitator(payload, issued), requirements); } catch (err) { // A throw means no verdict was obtained, so it is never held against the // buyer. Only an unclassified one is logged, as it may be an SDK fault. @@ -187,6 +189,8 @@ export function createVerify( ); } + bazaar.report(requirement.resourceId, sdkResult.extensionResponses); + if (!sdkResult.isValid) { // An RPC that never answered is not a payment that failed a check if (scope.transportFailed() || NO_VERDICT_REASONS.has(sdkResult.invalidReason ?? '')) { diff --git a/tests/e2e/payment/x402-bazaar.e2e.test.ts b/tests/e2e/payment/x402-bazaar.e2e.test.ts index fa5918a..9d5cc9a 100644 --- a/tests/e2e/payment/x402-bazaar.e2e.test.ts +++ b/tests/e2e/payment/x402-bazaar.e2e.test.ts @@ -58,6 +58,8 @@ let anvil: AnvilHandle; let deployment: Awaited>; let withBazaar: Stack; let withoutBazaar: Stack; +// Bazaar is enabled, but the facilitator does not advertise the extension +let unlisted: Stack; let mcp: Client | undefined; function rawConfig(facilitatorUrl: string, bazaar: boolean): Record { @@ -116,12 +118,13 @@ function rawConfig(facilitatorUrl: string, bazaar: boolean): Record { +async function startStack(bazaar: boolean, extensions: string[] = ['bazaar']): Promise { const facilitator = await startLoopbackFacilitator({ evm: { chains: [{ network: NETWORK, rpcUrl: anvil.rpcUrl }], signerPrivateKey: deployment.facilitator.privateKey, }, + extensions, }); const config = parseConfig(rawConfig(facilitator.url, bazaar), {}); const store = createSqliteReceiptStore({ path: ':memory:', logger: NOOP_LOGGER }); @@ -222,6 +225,7 @@ beforeAll(async () => { deployment = await deployLocalChain({ rpcUrl: anvil.rpcUrl, buyerInitialBalance: '10.00' }); withBazaar = await startStack(true); withoutBazaar = await startStack(false); + unlisted = await startStack(true, []); }, 180_000); afterEach(async () => { @@ -230,7 +234,7 @@ afterEach(async () => { }); afterAll(async () => { - for (const stack of [withBazaar, withoutBazaar]) { + for (const stack of [withBazaar, withoutBazaar, unlisted]) { await stack?.gateway.close().catch(() => {}); await stack?.store.close().catch(() => {}); await stack?.facilitator.close(); @@ -340,6 +344,22 @@ describe('x402 Bazaar metadata - real local chain', () => { } }); + it('facilitator without the extension: settles with the metadata in the 402 and none sent', async () => { + const required = await httpChallenge(unlisted); + expect(Object.keys(required.extensions ?? {})).toEqual(['bazaar']); + const proof = await buyer().createPaymentPayload(required); + + const bodies = await purchase(unlisted, async () => { + await payHttp(unlisted, proof); + }); + + expect(unlisted.facilitator.requests).toContain('GET /supported'); + expect(bodies.map(({ operation }) => operation)).toEqual(['verify', 'settle']); + for (const payload of payloads(bodies) as Record[]) { + expect(Object.keys(payload)).toEqual(THREE_KEYS); + } + }); + it('MPP beside Bazaar: settles with only x402Version, accepted and payload sent', async () => { // Config has Bazaar metadata for this resource; MPP must omit it from settlement expect(withBazaar.config.payments.x402?.resourceBazaar?.['forecast_mpp']).toHaveProperty( diff --git a/tests/fixtures/x402/loopback-facilitator.ts b/tests/fixtures/x402/loopback-facilitator.ts index 5af00e8..4984544 100644 --- a/tests/fixtures/x402/loopback-facilitator.ts +++ b/tests/fixtures/x402/loopback-facilitator.ts @@ -69,6 +69,8 @@ export async function startLoopbackFacilitator(options: { readonly near?: LoopbackNear; /** Serves https with this certificate, since a mainnet gateway refuses a plain-HTTP facilitator */ readonly tls?: { readonly key: string; readonly cert: string }; + /** Extension identifiers advertised by `/supported`; empty by default */ + readonly extensions?: readonly string[]; }): Promise { const chains = options.evm?.chains ?? []; const bindings = new Map( @@ -122,7 +124,7 @@ export async function startLoopbackFacilitator(options: { ...chains.map(({ network }) => ({ x402Version: 2, scheme: 'exact', network })), ...sdk.flatMap((supported) => supported.kinds.filter((kind) => kind.x402Version === 2)), ], - extensions: [], + extensions: options.extensions ?? [], signers: Object.assign({}, ...sdk.map((supported) => supported.signers)), }); return; diff --git a/tests/integration/x402-bazaar.test.ts b/tests/integration/x402-bazaar.test.ts index ded4c0d..32a676c 100644 --- a/tests/integration/x402-bazaar.test.ts +++ b/tests/integration/x402-bazaar.test.ts @@ -20,7 +20,7 @@ import { createConfiguredPaymentProviders } from '../../src/gateway/payment-prov import { createMcpAdapter } from '../../src/protocols/mcp'; import { createFakeStore } from '../unit/gateway/helpers'; -const facilitator = vi.hoisted(() => ({ verify: vi.fn(), settle: vi.fn() })); +const facilitator = vi.hoisted(() => ({ verify: vi.fn(), settle: vi.fn(), supported: vi.fn() })); vi.mock('@x402/core/http', () => ({ FacilitatorResponseError: class extends Error {}, HTTPFacilitatorClient: class { @@ -30,6 +30,9 @@ vi.mock('@x402/core/http', () => ({ settle(...args: unknown[]) { return facilitator.settle(...args); } + getSupported() { + return facilitator.supported(); + } }, })); @@ -58,7 +61,14 @@ let url = ''; let mcp: Client | undefined; let warn: ReturnType; +const supported = (extensions: string[]) => ({ + kinds: [{ x402Version: 2, scheme: 'exact', network: NETWORK }], + extensions, + signers: {}, +}); + beforeEach(async () => { + facilitator.supported.mockReset().mockResolvedValue(supported(['bazaar'])); facilitator.verify.mockReset().mockResolvedValue({ isValid: true, payer: buyer.address }); facilitator.settle.mockReset().mockResolvedValue({ success: true, @@ -218,6 +228,50 @@ describe('x402 Bazaar metadata through the gateway', () => { } }); + it('sells through a facilitator that does not list the extension, sending it no metadata', async () => { + facilitator.supported.mockResolvedValue(supported([])); + const required = challengeOf(await invoke('forecast', { city: 'Oslo', days: 1 })); + expect(required.extensions).toEqual({ bazaar: issued('forecast', 'http') }); + + const paid = await invoke( + 'forecast', + { city: 'Oslo', days: 1 }, + await payments().createPaymentPayload(required), + ); + + expect(paid.statusCode).toBe(200); + expect(paid.json()).toEqual({ forecast: 'sun' }); + for (const mock of [facilitator.verify, facilitator.settle]) { + expect(mock).toHaveBeenCalledTimes(1); + expect(Object.keys(mock.mock.calls[0]?.[0] as object)).toEqual([ + 'x402Version', + 'accepted', + 'payload', + ]); + } + }); + + it('answers a refused proof with a challenge that keeps the metadata and names the reason', async () => { + facilitator.verify.mockResolvedValue({ + isValid: false, + invalidReason: 'invalid_exact_evm_signature', + }); + const required = challengeOf(await invoke('forecast', { city: 'Oslo', days: 1 })); + + const refused = await invoke( + 'forecast', + { city: 'Oslo', days: 1 }, + await payments().createPaymentPayload(required), + ); + + expect(challengeOf(refused)).toMatchObject({ + error: 'invalid_exact_evm_signature', + extensions: { bazaar: issued('forecast', 'http') }, + }); + expect(String(refused.headers['payment-required']).length).toBeLessThanOrEqual(8192); + expect(facilitator.settle).not.toHaveBeenCalled(); + }); + it('warns about a resource left out at load, and still sells it', async () => { expect(issued('strict', 'http')).toBeUndefined(); expect(warn).toHaveBeenCalledWith( diff --git a/tests/unit/payments-x402/bazaar-challenge.test.ts b/tests/unit/payments-x402/bazaar-challenge.test.ts index bc33481..d7a1ef4 100644 --- a/tests/unit/payments-x402/bazaar-challenge.test.ts +++ b/tests/unit/payments-x402/bazaar-challenge.test.ts @@ -3,7 +3,7 @@ import { x402Client } from '@x402/core/client'; import type { PaymentPayload, PaymentRequired } from '@x402/core/types'; import { registerExactEvmScheme } from '@x402/evm/exact/client'; import { privateKeyToAccount } from 'viem/accounts'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { type CommerceResource, NOOP_LOGGER, @@ -15,8 +15,10 @@ import { createX402PaymentProvider, type X402ProviderOptions, } from '../../../src/payments/x402/provider'; +import { createBazaarForwarding } from '../../../src/payments/x402/provider/bazaar-forwarding'; +import type { ProviderContext } from '../../../src/payments/x402/provider/types'; -const facilitator = vi.hoisted(() => ({ verify: vi.fn(), settle: vi.fn() })); +const facilitator = vi.hoisted(() => ({ verify: vi.fn(), settle: vi.fn(), supported: vi.fn() })); // Mock the facilitator HTTP client to inspect the payment payloads passed to it vi.mock('@x402/core/http', () => ({ @@ -28,6 +30,9 @@ vi.mock('@x402/core/http', () => ({ settle(...args: unknown[]) { return facilitator.settle(...args); } + getSupported() { + return facilitator.supported(); + } }, })); @@ -115,7 +120,18 @@ async function pay( }; } +const supported = (extensions: string[]) => ({ + kinds: [{ x402Version: 2, scheme: 'exact', network: 'eip155:31337' }], + extensions, + signers: {}, +}); + +afterEach(() => { + vi.useRealTimers(); +}); + beforeEach(() => { + facilitator.supported.mockReset().mockResolvedValue(supported(['bazaar'])); facilitator.verify.mockReset().mockResolvedValue({ isValid: true, payer: BUYER.address }); facilitator.settle.mockReset().mockResolvedValue({ success: true, @@ -156,19 +172,49 @@ describe('Bazaar metadata in the challenge', () => { return { pad, extension: bazaarFor('http', pad) }; } - it('keeps it when the encoded HTTP challenge is exactly 8192 bytes', async () => { - const { pad, extension } = await sizedHttpChallenge(8192); + // 8192 less the 1024 bytes kept for an EVM proof + const EVM_LIMIT = 7168; + const encodedLength = (document: unknown) => + Buffer.from(JSON.stringify(document)).toString('base64').length; + + it('keeps it when the encoded HTTP challenge leaves exactly 1024 bytes of an 8192-byte header', async () => { + const { pad, extension } = await sizedHttpChallenge(EVM_LIMIT); const envelope = envelopeOf( await provider({ resourceBazaar: { report: { http: extension } } }).createRequirement( context('http'), ), ); - expect(Buffer.from(JSON.stringify(envelope)).toString('base64')).toHaveLength(8192); + expect(encodedLength(envelope)).toBe(EVM_LIMIT); expect(envelope.extensions).toEqual({ bazaar: bazaarFor('http', pad) }); }); + it('fits the SDK client echo of the largest kept challenge in an 8192-byte header', async () => { + const { extension } = await sizedHttpChallenge(EVM_LIMIT); + const requirement = await provider({ + resourceBazaar: { report: { http: extension } }, + }).createRequirement(context('http')); + + const proof = await sdkProof(requirement); + + // The echo repeats the metadata and adds the signed payload + expect(proof.extensions).toEqual({ bazaar: extension }); + expect(encodedLength(proof)).toBeGreaterThan(EVM_LIMIT); + expect(encodedLength(proof)).toBeLessThanOrEqual(8192); + }); + + it("fits a refused proof's challenge with the longest error code in an 8192-byte header", async () => { + const { extension } = await sizedHttpChallenge(EVM_LIMIT); + const envelope = envelopeOf( + await provider({ resourceBazaar: { report: { http: extension } } }).createRequirement( + context('http'), + ), + ); + // A provider reason is at most 128 characters + expect(encodedLength({ ...envelope, error: 'r'.repeat(128) })).toBeLessThanOrEqual(8192); + }); + it('leaves it out of an HTTP challenge one byte over, and logs that once per resource', async () => { - const { extension } = await sizedHttpChallenge(8192); + const { extension } = await sizedHttpChallenge(EVM_LIMIT); const big = { ...extension, info: { input: { ...extension.info.input, pad: `${extension.info.input.pad}p` } }, @@ -191,8 +237,8 @@ describe('Bazaar metadata in the challenge', () => { expect(mcp.extensions).toEqual({ bazaar: bigger }); expect(warn).toHaveBeenCalledTimes(1); expect(warn).toHaveBeenCalledWith( - { resourceId: 'report', bytes: 8196 }, - 'x402: Bazaar metadata left out of an HTTP challenge whose PAYMENT-REQUIRED header would exceed 8 KiB', + { resourceId: 'report', bytes: EVM_LIMIT + 4, reservedBytes: 1024 }, + 'x402: Bazaar metadata left out of an HTTP challenge too large to leave room for the signed proof in an 8 KiB header', ); }); }); @@ -382,3 +428,150 @@ describe('Bazaar metadata on the way to the facilitator', () => { }, ); }); + +describe('Bazaar metadata and the facilitator /supported list', () => { + const THREE_KEYS = ['x402Version', 'accepted', 'payload']; + + it('sends none to a facilitator that does not list the extension, and warns once', async () => { + facilitator.supported.mockResolvedValue(supported(['eip2612GasSponsoring'])); + const warn = vi.fn(); + const by = provider({ resourceBazaar: BAZAAR, logger: { ...NOOP_LOGGER, warn } }); + const requirement = await by.createRequirement(context('http')); + expect(envelopeOf(requirement).extensions).toEqual({ bazaar: BAZAAR.report.http }); + + const { verified, settled } = await pay(by, requirement, await sdkProof(requirement)); + await pay(by, requirement, await sdkProof(requirement)); + + expect(Object.keys(verified)).toEqual(THREE_KEYS); + expect(Object.keys(settled)).toEqual(THREE_KEYS); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith( + { facilitator: 'remote https://facilitator.example (auth=none)' }, + 'x402: the facilitator does not list the bazaar extension in /supported; Bazaar metadata stays in challenges but is not sent to it', + ); + }); + + it('sends none, and still verifies and settles, when /supported fails', async () => { + facilitator.supported.mockRejectedValue(new Error('facilitator down')); + const by = provider({ resourceBazaar: BAZAAR }); + const requirement = await by.createRequirement(context('http')); + + const { verified, settled } = await pay(by, requirement, await sdkProof(requirement)); + + expect(Object.keys(verified)).toEqual(THREE_KEYS); + expect(Object.keys(settled)).toEqual(THREE_KEYS); + }); + + it('sends none, and waits one second per call, when /supported does not answer', async () => { + const by = provider({ resourceBazaar: BAZAAR }); + const requirement = await by.createRequirement(context('http')); + const proof = await sdkProof(requirement); + facilitator.supported.mockReturnValue(new Promise(() => {})); + vi.useFakeTimers(); + + const paying = pay(by, requirement, proof); + await vi.advanceTimersByTimeAsync(999); + expect(facilitator.verify).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(facilitator.verify).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1_000); + const { verified, settled } = await paying; + + expect(Object.keys(verified)).toEqual(THREE_KEYS); + expect(Object.keys(settled)).toEqual(THREE_KEYS); + }); + + it('does not read /supported for a challenge without the metadata', async () => { + const by = provider(); + const requirement = await by.createRequirement(context('http')); + + await pay(by, requirement, await sdkProof(requirement)); + + expect(facilitator.supported).not.toHaveBeenCalled(); + }); +}); + +describe('Bazaar metadata and the in-process facilitator', () => { + it('gets none, and /supported is not read, since it keeps no catalog', async () => { + const currentSupported = vi.fn(); + const forwarding = createBazaarForwarding( + { remoteBinding: undefined, logger: NOOP_LOGGER } as unknown as ProviderContext, + currentSupported, + ); + const issued = envelopeOf( + await provider({ resourceBazaar: BAZAAR }).createRequirement(context('http')), + ); + expect(issued.extensions).toEqual({ bazaar: BAZAAR.report.http }); + + expect(await forwarding.issuedFor(issued)).toBeUndefined(); + expect(currentSupported).not.toHaveBeenCalled(); + }); +}); + +describe('Bazaar outcome from the facilitator', () => { + const REJECTED = { + bazaar: { + status: 'rejected', + rejectedReason: `info failed schema validation at https://user:secret@catalog.example/v1?key=abc ${'x'.repeat(400)}`, + }, + }; + const REJECTION_MESSAGE = + 'x402: the facilitator rejected the Bazaar metadata of a resource and will not catalog it. Payment is unaffected'; + + async function payWith(by: ReturnType) { + const requirement = await by.createRequirement(context('http')); + return pay(by, requirement, await sdkProof(requirement)); + } + + it('logs a rejection on verify once per resource, with the reason redacted and cut to 200 characters', async () => { + facilitator.verify.mockResolvedValue({ + isValid: true, + payer: BUYER.address, + extensionResponses: REJECTED, + }); + const warn = vi.fn(); + const by = provider({ resourceBazaar: BAZAAR, logger: { ...NOOP_LOGGER, warn } }); + + await payWith(by); + await payWith(by); + + expect(warn).toHaveBeenCalledTimes(1); + const [fields, message] = warn.mock.calls[0] as [Record, string]; + expect(message).toBe(REJECTION_MESSAGE); + expect(fields).toEqual({ + resourceId: 'report', + reportedReason: + `info failed schema validation at https://catalog.example ${'x'.repeat(400)}`.slice(0, 200), + }); + }); + + it('logs a rejection that arrives on settle', async () => { + facilitator.settle.mockResolvedValue({ + success: true, + transaction: `0x${'ab'.repeat(32)}`, + network: 'eip155:31337', + payer: BUYER.address, + extensionResponses: { bazaar: { status: 'rejected' } }, + }); + const warn = vi.fn(); + const by = provider({ resourceBazaar: BAZAAR, logger: { ...NOOP_LOGGER, warn } }); + + await payWith(by); + + expect(warn.mock.calls).toEqual([[{ resourceId: 'report' }, REJECTION_MESSAGE]]); + }); + + it.each(['success', 'processing'])('logs nothing for a %s outcome', async (status) => { + facilitator.verify.mockResolvedValue({ + isValid: true, + payer: BUYER.address, + extensionResponses: { bazaar: { status } }, + }); + const warn = vi.fn(); + const by = provider({ resourceBazaar: BAZAAR, logger: { ...NOOP_LOGGER, warn } }); + + await payWith(by); + + expect(warn).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/payments-x402/provider-near.test.ts b/tests/unit/payments-x402/provider-near.test.ts index cfeaf0f..fa0dbae 100644 --- a/tests/unit/payments-x402/provider-near.test.ts +++ b/tests/unit/payments-x402/provider-near.test.ts @@ -600,3 +600,28 @@ describe('payment-identifier on a NEAR offer', () => { expect(verifyMock).not.toHaveBeenCalled(); }); }); + +describe('Bazaar metadata on an HTTP challenge with a NEAR offer', () => { + // Subtract the 1280-byte NEAR proof reserve from 8192, then undo base64 sizing + const LIMIT = 6912; + const LIMIT_JSON_BYTES = (LIMIT / 4) * 3; + + async function challenge(pad: string): Promise<{ extensions?: unknown }> { + const requirement = await makeProvider({ + resourceBazaar: { [RESOURCE.id]: { http: { info: { pad }, schema: {} } } }, + }).createRequirement({ ...paymentContext(), protocol: 'http' }); + return requirement.challenge.envelope as { extensions?: unknown }; + } + + it('keeps it only while 1280 bytes of an 8192-byte header stay free', async () => { + const unpadded = Buffer.byteLength(JSON.stringify(await challenge(''))); + const pad = 'p'.repeat(LIMIT_JSON_BYTES - unpadded); + + const atLimit = await challenge(pad); + const over = await challenge(`${pad}p`); + + expect(Buffer.from(JSON.stringify(atLimit)).toString('base64')).toHaveLength(LIMIT); + expect(atLimit.extensions).toEqual({ bazaar: { info: { pad }, schema: {} } }); + expect(over).not.toHaveProperty('extensions'); + }); +}); diff --git a/tests/unit/payments-x402/provider-svm.test.ts b/tests/unit/payments-x402/provider-svm.test.ts index 892d028..634e239 100644 --- a/tests/unit/payments-x402/provider-svm.test.ts +++ b/tests/unit/payments-x402/provider-svm.test.ts @@ -640,3 +640,45 @@ describe('payment-identifier on a Solana offer', () => { expect(verifyMock).not.toHaveBeenCalled(); }); }); + +describe('Bazaar metadata on an HTTP challenge with a Solana offer', () => { + const EVM_OFFER = { + network: 'eip155:84532', + rpcUrl: RPC_URL, + asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', + assetName: 'USDC', + assetVersion: '2', + assetDecimals: 6, + payTo: '0x1111111111111111111111111111111111111111', + }; + // Subtract the 2304-byte Solana proof reserve from 8192, then undo base64 sizing + const LIMIT = 5888; + const LIMIT_JSON_BYTES = (LIMIT / 4) * 3; + + async function challenge(pad: string, besideEvm: boolean): Promise { + const svmOffer = { network: DEVNET, rpcUrl: RPC_URL, asset: USDC, assetDecimals: 6, payTo }; + const requirement = await makeProvider({ + offers: besideEvm ? [EVM_OFFER, svmOffer] : [svmOffer], + resourceBazaar: { [RESOURCE.id]: { http: { info: { pad }, schema: {} } } }, + }).createRequirement({ ...paymentContext(), protocol: 'http' }); + return requirement.challenge.envelope as unknown as PaymentRequired; + } + + it.each([ + ['alone', false], + ['beside an EVM offer, whose smaller reserve does not apply', true], + ])( + 'keeps it only while 2304 bytes of an 8192-byte header stay free, %s', + async (_label, besideEvm) => { + const unpadded = Buffer.byteLength(JSON.stringify(await challenge('', besideEvm))); + const pad = 'p'.repeat(LIMIT_JSON_BYTES - unpadded); + + const atLimit = await challenge(pad, besideEvm); + const over = await challenge(`${pad}p`, besideEvm); + + expect(Buffer.from(JSON.stringify(atLimit)).toString('base64')).toHaveLength(LIMIT); + expect(atLimit.extensions).toEqual({ bazaar: { info: { pad }, schema: {} } }); + expect(over).not.toHaveProperty('extensions'); + }, + ); +}); From 98be9a5be7f46839d549f3a73d421bdd6dfae63f Mon Sep 17 00:00:00 2001 From: Revinand Date: Wed, 18 Nov 2026 23:09:25 +0100 Subject: [PATCH 12/14] fix(mcp): align serverInfo, endpoint URLs and doctor with the Registry listing --- README.md | 7 +++-- docs/configuration.md | 11 +++++-- docs/contracts.md | 9 +++--- docs/protocols/mcp.md | 8 +++-- docs/security.md | 2 +- src/cli/commands/doctor/registry.ts | 3 +- src/cli/lib/mcp-registry.ts | 38 ++++++++++++++--------- src/config/schema/normalize.ts | 7 +++-- src/gateway/run.ts | 11 ++++++- src/protocols/http.ts | 10 ++++++ tests/unit/cli/doctor-registry.test.ts | 3 +- tests/unit/cli/mcp-registry.test.ts | 19 ++++++++++++ tests/unit/config/schema.test.ts | 12 +++++++ tests/unit/gateway/main.test.ts | 43 ++++++++++++++++++++++++++ 14 files changed, 151 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index cb6e729..01ebd49 100644 --- a/README.md +++ b/README.md @@ -541,9 +541,10 @@ status, score or exit code; an unreachable gateway still fails its check. `--registry` (experimental) adds an `MCP Registry` check. It fetches the latest listing for `protocols.mcp.registry.name` from -`registry.modelcontextprotocol.io`, sending only that name, and compares it -with what `export mcp-registry` would write. Differences, deprecated or deleted -listings, missing listings and request failures produce WARN rather than FAIL. +`registry.modelcontextprotocol.io`, sending only that name and a fixed +`include_deleted=true` flag, and compares it with what `export mcp-registry` +would write. Differences, deprecated or deleted listings, missing listings and +request failures produce WARN rather than FAIL. Recognized transport failures also get the `unreachable` marker. The check names differing fields and uses fixed messages for known lifecycle statuses, without echoing arbitrary registry values or request error messages. See diff --git a/docs/configuration.md b/docs/configuration.md index ccfe1bb..1419394 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -219,8 +219,10 @@ about the field is OpenAPI-specific. Experimental and optional. This block supplies the listing fields that [`agent-commerce export mcp-registry`](protocols/mcp.md#mcp-registry-listing) writes to `server.json` and `doctor --registry` compares with the live -listing. Config loading validates these fields; the MCP adapter does not use -them. +listing. Config loading validates these fields. When started with this block, +the gateway also reports `name` and `version` as its MCP `serverInfo` at +`initialize`. Without the block, it reports `agent-commerce` and the package +version. ```yaml protocols: @@ -696,6 +698,11 @@ Requests without a URL mapping keep the `resource://` form. MPP challenges are unchanged. Enabling the option requires `merchant.publicBaseUrl` to be an http:// or https:// URL; otherwise config loading fails with `CONFIG_INVALID`. +The URL parser writes each URL with a lowercase scheme and host and no default +port. `agent-commerce export mcp-registry` uses the same form for the MCP +endpoint, which gives the Registry listing and x402 challenges matching URL +strings. + After the option changes, proofs that echo the previous URL are rejected, including proofs for A2A tasks still awaiting payment after a restart. Proofs that echo another surface's URL are also rejected. Both cases return diff --git a/docs/contracts.md b/docs/contracts.md index 41e8d38..b5aad28 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -474,8 +474,8 @@ persistence must not fail the commerce flow. context without one, an ACP request, or a surface without an entry keeps the `resource://` form. - With `payments.x402.publicResourceUrl: true`, config normalization fills - `GatewayConfig.payments.x402.resourceUrls`. MPP's internal x402 provider - does not receive this map. + `GatewayConfig.payments.x402.resourceUrls`, with each URL in the URL + parser's form. MPP's internal x402 provider does not receive this map. - Without the option, challenges are unchanged. - 2.8.0: experimental `X402ProviderOptions.resourceBazaar` maps resource ids and request surfaces (`http` or `mcp`) to each challenge's `extensions.bazaar` @@ -495,8 +495,9 @@ persistence must not fail the commerce flow. `name`, `version` and `description` from `protocols.mcp.registry` and is absent when that block is omitted. Config loading validates these fields against the MCP Registry's name, length and version rules. - `agent-commerce export mcp-registry` and `doctor --registry` use the metadata; - the MCP adapter does not. + `agent-commerce export mcp-registry` and `doctor --registry` use the metadata. + `runGateway` passes `name` and `version` to the MCP adapter as `serverName` + and `serverVersion`; an adapter built without them keeps its defaults. ### Authorization and AP2 diff --git a/docs/protocols/mcp.md b/docs/protocols/mcp.md index 2861dcc..bd21df3 100644 --- a/docs/protocols/mcp.md +++ b/docs/protocols/mcp.md @@ -142,8 +142,12 @@ then publish it: with your config. The listing's version comes from `protocols.mcp.registry.version`, independently -of the package version. The registry recommends semantic versions and uses -their ordering to choose the latest. Publishing a prerelease such as `1.2.3-1` +of the package version. The registry's schema defines it as the server's +`Implementation.version`. When started with this block, the gateway reports the +listing's `name` and `version` as `serverInfo` at `initialize`. + +The registry recommends semantic versions and uses their ordering to choose +the latest. Publishing a prerelease such as `1.2.3-1` after its release, `1.2.3`, does not make it the latest. If your config names that prerelease, `doctor --registry` reports a version difference. diff --git a/docs/security.md b/docs/security.md index 4c8bed1..c8705fd 100644 --- a/docs/security.md +++ b/docs/security.md @@ -588,7 +588,7 @@ real funds. | **`doctor` reporting a gateway that answered as unreachable** | marks `Gateway` `unreachable` for recognized transport failures, including refused or reset connections and timeouts. Unresolvable hostnames, ports rejected by fetch, non-2xx `/health` responses and Host refusals fail unmarked; checks that need the discovery document are `skipped`. Responses with unusable document content leave those checks unmarked | `tests/unit/cli/doctor-certainty.test.ts` ("when %s", "says a gateway that answered non-2xx is unhealthy, not unreachable"), `tests/integration/doctor-certainty.test.ts` ("leaves Gateway unmarked, and says why, when fetch refuses the port") | | **the `doctor` Secrets check printing a value or a default** | reports placeholder names in text and JSON, never variable values or defaults | `tests/unit/cli/doctor-certainty.test.ts` ("FAILs naming every missing variable, and prints no value or default"), `tests/unit/config/env.test.ts` ("returns names only: no value and no default") | | **an MCP Registry answer injecting text into `doctor` output** | `doctor --registry` names differing fields and uses fixed messages for known lifecycle statuses, without echoing arbitrary answer values or request error messages in text or JSON | `tests/unit/cli/doctor-registry.test.ts` ("prints no value from a hostile answer, in text or JSON", "leaves a TLS failure unmarked and does not print its message") | -| **`doctor --registry` sending more than the server name** | sends a GET to `/v0.1/servers//versions/latest` with no custom headers or body, only when the flag is set and config yields a listing | `tests/unit/cli/doctor-registry.test.ts` ("asks for the configured name only, with no header or body", "adds no check and sends nothing to the registry without the flag", "sends nothing for an http public URL") | +| **`doctor --registry` sending more than the server name** | sends a GET to `/v0.1/servers//versions/latest?include_deleted=true` with no custom headers or body, only when the flag is set and config yields a listing | `tests/unit/cli/doctor-registry.test.ts` ("asks for the configured name only, with no header or body", "adds no check and sends nothing to the registry without the flag", "sends nothing for an http public URL") | | **another server name listing the gateway's URL, taken for the merchant's listing** | `doctor --registry` looks up the configured name only and reports a response with another name as a difference in `name` | `tests/unit/cli/doctor-registry.test.ts` ("asks for the configured name only, with no header or body", "reports a listing under another name") | A facilitator verdict is a returned result. The SDK throws when a remote diff --git a/src/cli/commands/doctor/registry.ts b/src/cli/commands/doctor/registry.ts index 27f0fb0..0522fb8 100644 --- a/src/cli/commands/doctor/registry.ts +++ b/src/cli/commands/doctor/registry.ts @@ -37,9 +37,10 @@ export async function registryCheck( }; } const local = built.document; + // The registry answers 404 for a deleted listing unless asked to include it const answer = await fetchJson( fetchImpl, - `${MCP_REGISTRY_URL}/v0.1/servers/${encodeURIComponent(local.name)}/versions/latest`, + `${MCP_REGISTRY_URL}/v0.1/servers/${encodeURIComponent(local.name)}/versions/latest?include_deleted=true`, REGISTRY_TIMEOUT_MS, ); // An error message can carry text from the far end, such as certificate names diff --git a/src/cli/lib/mcp-registry.ts b/src/cli/lib/mcp-registry.ts index 53ace55..8ab844c 100644 --- a/src/cli/lib/mcp-registry.ts +++ b/src/cli/lib/mcp-registry.ts @@ -1,5 +1,5 @@ // The MCP Registry listing (`server.json`) for a gateway, built from config alone -import { joinUrl } from '../../protocols/http'; +import { publicEndpointUrl } from '../../protocols/http'; import type { GatewayConfig } from './config-client'; /** The `server.json` schema revision the listing follows */ @@ -23,9 +23,11 @@ export interface RegistryProblem { /** * Builds a listing from validated `config`, or returns the problems found. * Requires MCP to be enabled and registry metadata to be present. The remote - * URL joins `merchant.publicBaseUrl` and the MCP mount; it must use HTTPS and - * must not name `localhost`, `127.0.0.1` or `*.localhost`. The version comes - * from `protocols.mcp.registry`, independently of the package version. + * URL joins `merchant.publicBaseUrl` and the MCP mount through + * `publicEndpointUrl`, matching the form of an x402 challenge's `resource.url`. + * It must use HTTPS and must not name `localhost`, `127.0.0.1` or `*.localhost`. + * The name and version come from `protocols.mcp.registry`; `runGateway` also + * uses them for MCP `serverInfo`. */ export function serverJson( config: GatewayConfig, @@ -45,9 +47,9 @@ export function serverJson( }); } const url = remoteUrl(config.merchant.publicBaseUrl, mcp.mountPath); - if (typeof url === 'string') problems.push({ key: 'merchant.publicBaseUrl', message: url }); + if ('problem' in url) problems.push({ key: 'merchant.publicBaseUrl', message: url.problem }); - if (mcp.registry === undefined || typeof url === 'string' || problems.length > 0) { + if (mcp.registry === undefined || 'problem' in url || problems.length > 0) { return { problems }; } return { @@ -56,23 +58,29 @@ export function serverJson( name: mcp.registry.name, description: mcp.registry.description, version: mcp.registry.version, - remotes: [{ type: 'streamable-http', url: url.href }], + remotes: [{ type: 'streamable-http', url: url.url }], }, }; } // Check the remote URL against the registry's `IsValidRemoteURL` rules -function remoteUrl(publicBaseUrl: string, mountPath: string): URL | string { - let url: URL; +function remoteUrl( + publicBaseUrl: string, + mountPath: string, +): { readonly url: string } | { readonly problem: string } { + let url: string; try { - url = new URL(joinUrl(publicBaseUrl, mountPath)); + url = publicEndpointUrl(publicBaseUrl, mountPath); } catch { - return 'is not a URL'; + return { problem: 'is not a URL' }; } - if (url.protocol !== 'https:') return 'must be an https:// URL: the MCP Registry refuses others'; - const host = url.hostname; + const parsed = new URL(url); + if (parsed.protocol !== 'https:') { + return { problem: 'must be an https:// URL: the MCP Registry refuses others' }; + } + const host = parsed.hostname; if (host === 'localhost' || host === '127.0.0.1' || host.endsWith('.localhost')) { - return `names ${host}, which the MCP Registry refuses`; + return { problem: `names ${host}, which the MCP Registry refuses` }; } - return url; + return { url }; } diff --git a/src/config/schema/normalize.ts b/src/config/schema/normalize.ts index d91038f..78f05d9 100644 --- a/src/config/schema/normalize.ts +++ b/src/config/schema/normalize.ts @@ -2,7 +2,7 @@ import type { CommerceResource } from '../../core'; import { CommerceError } from '../../core'; import { bazaarMetadata } from '../../payments/x402/provider/bazaar'; -import { joinUrl } from '../../protocols/http'; +import { publicEndpointUrl } from '../../protocols/http'; import { normalizeAcp, validateAcpCheckoutMapping } from './acp'; import { normalizeAp2, validateLegacyStoresIsolated } from './ap2'; import { normalizeMpp } from './mpp'; @@ -182,7 +182,10 @@ function publicResourceUrls( Object.fromEntries( (['http', 'mcp', 'a2a'] as const) .filter((surface) => resource.exposedVia.includes(surface)) - .map((surface) => [surface, joinUrl(publicBaseUrl, path(surface, resource.id))]), + .map((surface) => [ + surface, + publicEndpointUrl(publicBaseUrl, path(surface, resource.id)), + ]), ), ]), ); diff --git a/src/gateway/run.ts b/src/gateway/run.ts index 4c2cbf3..ccfc479 100644 --- a/src/gateway/run.ts +++ b/src/gateway/run.ts @@ -104,7 +104,16 @@ export async function runGateway(options: RunGatewayOptions = {}): Promise const protocolAdapters: ProtocolAdapter[] = []; if (mcpModule !== undefined) { - protocolAdapters.push(mcpModule.createMcpAdapter({ mountPath: mcp.mountPath })); + // The registry's `server.json` defines `version` as `Implementation.version`: + // a listed server reports the listing's name and version at `initialize` + protocolAdapters.push( + mcpModule.createMcpAdapter({ + mountPath: mcp.mountPath, + ...(mcp.registry !== undefined + ? { serverName: mcp.registry.name, serverVersion: mcp.registry.version } + : {}), + }), + ); } if (config.protocols.a2a.enabled) { protocolAdapters.push( diff --git a/src/protocols/http.ts b/src/protocols/http.ts index 1fde76d..4a8fee8 100644 --- a/src/protocols/http.ts +++ b/src/protocols/http.ts @@ -57,3 +57,13 @@ export async function readCappedBody(req: IncomingMessage, maxBytes: number): Pr export function joinUrl(baseUrl: string, mountPath: string): string { return `${baseUrl.replace(/\/+$/, '')}/${mountPath.replace(/^\/+|\/+$/g, '')}`; } + +/** + * Join the base and mount path with `joinUrl`, then normalize with the URL + * parser: lowercase scheme and host, no default port. x402 challenges and MCP + * Registry listings both use this form, which makes their endpoint URL strings + * match. Throws when the joined URL cannot be parsed. + */ +export function publicEndpointUrl(baseUrl: string, mountPath: string): string { + return new URL(joinUrl(baseUrl, mountPath)).href; +} diff --git a/tests/unit/cli/doctor-registry.test.ts b/tests/unit/cli/doctor-registry.test.ts index 2e83313..2296b93 100644 --- a/tests/unit/cli/doctor-registry.test.ts +++ b/tests/unit/cli/doctor-registry.test.ts @@ -14,8 +14,9 @@ import { } from './fixtures'; const GATEWAY = 'http://127.0.0.1:8080'; +// Request deleted listings explicitly; the registry otherwise returns 404 for them const LISTING_URL = - 'https://registry.modelcontextprotocol.io/v0.1/servers/io.github.acme%2Fweather/versions/latest'; + 'https://registry.modelcontextprotocol.io/v0.1/servers/io.github.acme%2Fweather/versions/latest?include_deleted=true'; const REGISTRY = { name: 'io.github.acme/weather', version: '1.0.0', diff --git a/tests/unit/cli/mcp-registry.test.ts b/tests/unit/cli/mcp-registry.test.ts index 12a1a81..b659441 100644 --- a/tests/unit/cli/mcp-registry.test.ts +++ b/tests/unit/cli/mcp-registry.test.ts @@ -5,7 +5,9 @@ import addFormats from 'ajv-formats'; import { describe, expect, it } from 'vitest'; import type { GatewayConfig } from '../../../src/cli/lib/config-client'; import { type ServerJson, serverJson } from '../../../src/cli/lib/mcp-registry'; +import { parseConfig } from '../../../src/config/schema'; import { PACKAGE_VERSION } from '../../../src/version'; +import { validRawConfig } from '../config/fixtures'; import { makeGatewayConfig } from './fixtures'; const SCHEMA_URL = 'https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json'; @@ -80,6 +82,23 @@ describe('serverJson', () => { }); }); + it('names the endpoint with the same string as the x402 challenge of an MCP resource', () => { + const raw = validRawConfig(); + (raw['merchant'] as Record)['publicBaseUrl'] = 'https://Shop.Example:443/gw/'; + (raw['protocols'] as { mcp: Record }).mcp['registry'] = REGISTRY; + (raw['payments'] as { x402: Record }).x402['publicResourceUrl'] = true; + const parsed = parseConfig(raw, {}); + + const result = serverJson(parsed); + + expect(result).toMatchObject({ + document: { remotes: [{ url: 'https://shop.example/gw/mcp' }] }, + }); + expect(parsed.payments.x402?.resourceUrls?.['market_report']?.mcp).toBe( + 'https://shop.example/gw/mcp', + ); + }); + it('takes the version from config, not from the package', () => { expect(PACKAGE_VERSION).not.toBe('0.3.1'); expect(listed({ ...REGISTRY, version: '0.3.1' })['version']).toBe('0.3.1'); diff --git a/tests/unit/config/schema.test.ts b/tests/unit/config/schema.test.ts index 862f217..66d10bd 100644 --- a/tests/unit/config/schema.test.ts +++ b/tests/unit/config/schema.test.ts @@ -2641,6 +2641,18 @@ describe('payments.x402.publicResourceUrl', () => { }); }); + it('writes each URL in the URL parser form, as the MCP Registry listing does', () => { + const raw = withPublicUrl(true, (r) => { + (r['merchant'] as Record)['publicBaseUrl'] = 'HTTPS://Shop.Example:443'; + }); + expect(parseConfig(raw, {}).payments.x402?.resourceUrls).toEqual({ + market_report: { + http: 'https://shop.example/api/resources/market_report/invoke', + mcp: 'https://shop.example/mcp', + }, + }); + }); + it('refuses the opt-in when merchant.publicBaseUrl is not an http(s) URL', () => { const raw = withPublicUrl(true, (r) => { (r['merchant'] as Record)['publicBaseUrl'] = 'localhost:8080'; diff --git a/tests/unit/gateway/main.test.ts b/tests/unit/gateway/main.test.ts index f4fe03a..b52f911 100644 --- a/tests/unit/gateway/main.test.ts +++ b/tests/unit/gateway/main.test.ts @@ -8,9 +8,13 @@ import * as nodeModule from 'node:module'; import type { AddressInfo } from 'node:net'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'; import Database from 'better-sqlite3'; import { describe, expect, it } from 'vitest'; import { A2A_X402_EXTENSION_URI } from '../../../src/protocols/a2a/x402-extension'; +import { PACKAGE_VERSION } from '../../../src/version'; const RPC_KEY = 'RPC-KEY-IN-PATH'; // Nothing listens on port 1, so no provider reaches a chain @@ -257,7 +261,41 @@ function hidePackage(dir: string, pkg: string): Record { return { NODE_OPTIONS: `--import ${hook}`, OAC_HIDDEN_PACKAGE: pkg }; } +// Read the gateway's MCP server identity from `initialize` +async function mcpServerInfo(gatewayUrl: string): Promise { + const client = new Client({ name: 'main-test', version: '0.0.0-test' }); + await client.connect( + new StreamableHTTPClientTransport(new URL(`${gatewayUrl}/mcp`)) as Transport, + ); + try { + return client.getServerVersion(); + } finally { + await client.close(); + } +} + describe.concurrent('gateway entry points (main.ts and agent-commerce start)', () => { + it('reports the MCP Registry listing name and version as the MCP server info', async () => { + const dir = tempDir(); + const config = baseConfig(dir); + (config.protocols['mcp'] as Section)['registry'] = { + name: 'io.github.acme/weather', + version: '1.4.0', + description: 'Weather forecasts, paid per call', + }; + const gateway = startMain(dir, config); + try { + await gateway.printed('"gateway listening"'); + expect(await mcpServerInfo(gateway.url())).toEqual({ + name: 'io.github.acme/weather', + version: '1.4.0', + }); + } finally { + gateway.stop(); + rmSync(dir, { recursive: true, force: true }); + } + }, 30_000); + it('boots x402 and MCP, prints the settlement origin without the RPC path, and exits 0 on SIGTERM', async () => { const dir = tempDir(); const gateway = startMain(dir, baseConfig(dir)); @@ -268,6 +306,11 @@ describe.concurrent('gateway entry points (main.ts and agent-commerce start)', ( const health = await fetch(`${gateway.url()}/health`); expect(health.status).toBe(200); expect(await health.json()).toEqual({ status: 'ok' }); + // Without Registry metadata, the server uses its default name and package version + expect(await mcpServerInfo(gateway.url())).toEqual({ + name: 'agent-commerce', + version: PACKAGE_VERSION, + }); // A provider may put its API key in the RPC path, so only the origin is printed expect(gateway.output.stdout).toContain('via http://127.0.0.1:1'); From f24ecb59d2948180c3378b1560ddbb097a86eec7 Mon Sep 17 00:00:00 2001 From: Revinand Date: Wed, 18 Nov 2026 23:14:56 +0100 Subject: [PATCH 13/14] fix(mcp): align serverInfo, endpoint URLs and doctor with the Registry listing --- biome.json | 2 +- docs/configuration.md | 17 ++++---- docs/contracts.md | 5 ++- docs/protocols/x402.md | 3 +- docs/security.md | 1 + src/config/schema/normalize.ts | 49 +++++++++++++--------- src/config/schema/resources.ts | 20 ++++++--- tests/e2e/payment/x402-bazaar.e2e.test.ts | 9 ++-- tests/integration/x402-bazaar.test.ts | 7 ++++ tests/unit/config/schema.test.ts | 51 +++++++++++++++++++++++ 10 files changed, 123 insertions(+), 41 deletions(-) diff --git a/biome.json b/biome.json index e3e01c0..fb7ff14 100644 --- a/biome.json +++ b/biome.json @@ -56,4 +56,4 @@ "arrowParentheses": "always" } } -} \ No newline at end of file +} diff --git a/docs/configuration.md b/docs/configuration.md index 1419394..1dd0407 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -695,8 +695,9 @@ payments: | A2A | `` | Requests without a URL mapping keep the `resource://` form. MPP challenges -are unchanged. Enabling the option requires `merchant.publicBaseUrl` to be an -http:// or https:// URL; otherwise config loading fails with `CONFIG_INVALID`. +are unchanged, and a resource served on MPP gets no mapping. Enabling the +option requires `merchant.publicBaseUrl` to be an http:// or https:// URL; +otherwise config loading fails with `CONFIG_INVALID`. The URL parser writes each URL with a lowercase scheme and host and no default port. `agent-commerce export mcp-registry` uses the same form for the MCP @@ -712,9 +713,10 @@ pay a new challenge. See [x402](protocols/x402.md#the-resource-url). ### Bazaar metadata Experimental and disabled by default. `bazaar.enabled: true` adds Bazaar -discovery metadata to x402 challenges on HTTP and MCP for resources whose -`payments` include `x402`. Enabling it requires `publicResourceUrl: true`; -otherwise config loading fails with `CONFIG_INVALID`. +discovery metadata to x402 challenges on HTTP and MCP for resources the +gateway serves on x402: those whose first enabled rail in `payments` is `x402`. +Enabling it requires `publicResourceUrl: true`; otherwise config loading fails +with `CONFIG_INVALID`. ```yaml payments: @@ -725,8 +727,9 @@ payments: ``` During config loading, omissions from HTTP/MCP metadata produce warnings with -the resource id, affected surfaces and reason. Omitting metadata leaves payment -behavior unchanged. +the resource id, affected surfaces and reason. A resource that lists `x402` +behind an enabled `mpp` gets a warning that names the rail serving it. +Omitting metadata leaves payment behavior unchanged. [x402](protocols/x402.md#bazaar-discovery-metadata) lists the rules. Choose a facilitator whose `/supported` response lists `bazaar` among its diff --git a/docs/contracts.md b/docs/contracts.md index b5aad28..8097983 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -474,8 +474,9 @@ persistence must not fail the commerce flow. context without one, an ACP request, or a surface without an entry keeps the `resource://` form. - With `payments.x402.publicResourceUrl: true`, config normalization fills - `GatewayConfig.payments.x402.resourceUrls`, with each URL in the URL - parser's form. MPP's internal x402 provider does not receive this map. + `GatewayConfig.payments.x402.resourceUrls` for resources whose first + enabled rail is x402, with each URL in the URL parser's form. MPP's + internal x402 provider does not receive this map. - Without the option, challenges are unchanged. - 2.8.0: experimental `X402ProviderOptions.resourceBazaar` maps resource ids and request surfaces (`http` or `mcp`) to each challenge's `extensions.bazaar` diff --git a/docs/protocols/x402.md b/docs/protocols/x402.md index 6fc6cad..41726e5 100644 --- a/docs/protocols/x402.md +++ b/docs/protocols/x402.md @@ -146,7 +146,8 @@ Experimental and disabled by default. With [`bazaar.enabled`](../configuration.md#bazaar-metadata), x402 challenges on HTTP and MCP carry `extensions.bazaar` metadata for a facilitator's catalog. Other surfaces carry no Bazaar metadata. A resource whose first enabled rail -is MPP receives an MPP challenge. +is MPP receives an MPP challenge and no metadata; config loading warns when +such a resource also lists `x402`. | Surface | `info.input` | `info.output` | | ------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | diff --git a/docs/security.md b/docs/security.md index c8705fd..1519d8f 100644 --- a/docs/security.md +++ b/docs/security.md @@ -344,6 +344,7 @@ real funds. | **an input schema the gateway accepts and a facilitator cannot compile, silently dropping the listing** | config loading omits metadata for malformed keyword values detected by the JSON Schema 2020-12 checks or an empty `enum`; warnings name the keyword and its path | `tests/unit/core/execution/validation.test.ts`, `tests/unit/payments-x402/bazaar.test.ts` ("leaves out a resource whose input schema has ..., which upstream validation refuses") | | **a facilitator that does not implement Bazaar refusing a payment over the forwarded fields, and the buyer blamed for it** | verify and settle forward `resource` and `extensions.bazaar` only to a remote facilitator that lists `bazaar` in `/supported`; when that read fails or takes over one second, the call sends neither | `tests/unit/payments-x402/bazaar-challenge.test.ts` ("Bazaar metadata and the facilitator /supported list"), `tests/integration/x402-bazaar.test.ts`, `tests/e2e/payment/x402-bazaar.e2e.test.ts` | | **a facilitator rejecting a Bazaar listing unnoticed, or adding unbounded reason text to the gateway log** | the gateway logs a `rejected` outcome in `EXTENSION-RESPONSES` at `warn` once per resource and provider instance; it redacts URLs in the reason to scheme and host before truncating it to 200 characters. This metadata outcome does not change the payment result | `tests/unit/payments-x402/bazaar-challenge.test.ts` ("Bazaar outcome from the facilitator") | +| **a resource served on MPP described in config as an x402 listing** | public URLs and Bazaar metadata are built only for resources whose first enabled rail is x402; a resource that lists `x402` behind an enabled `mpp` gets a warning naming the serving rail | `tests/unit/config/schema.test.ts`, `tests/integration/x402-bazaar.test.ts` | | **an AP2 mandate approved for one x402 offer, presented with a proof for another** | selected destination, network or asset fails mandate binding; no settlement | `tests/unit/core/execution/pipeline-authorization.test.ts` | | **an EIP-3009 authorization signed for one EVM chain, presented as another chain's offer** | `invalid_exact_evm_signature`: signature fails against the other chain's EIP-712 domain; neither chain's balances change | `tests/e2e/payment/x402-multichain.e2e.test.ts` | | **the same payer, token address and nonce on two EVM chains** | both settle: the replay key includes the chain id | same | diff --git a/src/config/schema/normalize.ts b/src/config/schema/normalize.ts index 78f05d9..0cacdae 100644 --- a/src/config/schema/normalize.ts +++ b/src/config/schema/normalize.ts @@ -7,7 +7,7 @@ import { normalizeAcp, validateAcpCheckoutMapping } from './acp'; import { normalizeAp2, validateLegacyStoresIsolated } from './ap2'; import { normalizeMpp } from './mpp'; import { isHttpUrl, type RawConfig, SUPPORTED_CONFIG_VERSION } from './raw'; -import { normalizeResource } from './resources'; +import { normalizeResource, servingRailOf } from './resources'; import type { GatewayConfig, NormalizedProtocols } from './types'; import { toBoolean, toNumber } from './values'; import { normalizeX402 } from './x402'; @@ -63,15 +63,19 @@ export function normalize(raw: RawConfig): GatewayConfig { return mimeType !== undefined ? [[resource.id, mimeType]] : []; }), ); + // Build URL mappings and metadata for resources whose serving rail is x402 + const rails = { x402: x402?.enabled === true, mpp: mpp?.enabled === true }; + const railOf = (resource: CommerceResource) => servingRailOf(resource.paymentMethods, rails); + const onX402 = resources.filter((resource) => railOf(resource) === 'x402'); const publicUrl = raw.payments.x402?.publicResourceUrl; const resourceUrls = publicUrl !== undefined && toBoolean(publicUrl, 'payments.x402.publicResourceUrl') - ? publicResourceUrls(raw.merchant.publicBaseUrl, protocols, resources) + ? publicResourceUrls(raw.merchant.publicBaseUrl, protocols, onX402) : undefined; const bazaarRaw = raw.payments.x402?.bazaar; const resourceBazaar = bazaarRaw !== undefined && toBoolean(bazaarRaw.enabled, 'payments.x402.bazaar.enabled') - ? bazaarExtensions(resourceUrls, resources, mimeTypes) + ? bazaarExtensions(resourceUrls, resources, mimeTypes, railOf) : undefined; const x402WithFlows = x402 !== undefined @@ -132,6 +136,7 @@ function bazaarExtensions( resourceUrls: Record>> | undefined, resources: readonly CommerceResource[], mimeTypes: Readonly>, + railOf: (resource: CommerceResource) => string | undefined, ): NonNullable['resourceBazaar'] { if (resourceUrls === undefined) { throw new CommerceError( @@ -143,7 +148,15 @@ function bazaarExtensions( return Object.fromEntries( resources.flatMap((resource) => { const urls = resourceUrls[resource.id]; - if (urls === undefined) return []; + if (urls === undefined) { + const rail = railOf(resource); + if (resource.paymentMethods.includes('x402') && rail !== undefined) { + console.warn( + `[agent-commerce] resource "${resource.id}" gets no Bazaar metadata: the gateway serves it on ${rail}, the first enabled rail in its payments, which issues no x402 challenge. Payment is unaffected.`, + ); + } + return []; + } const surfaces = (['http', 'mcp'] as const).filter((surface) => urls[surface] !== undefined); const { extensions, omitted } = bazaarMetadata(resource, surfaces, mimeTypes[resource.id]); for (const { surfaces: left, reason } of omitted) { @@ -156,8 +169,8 @@ function bazaarExtensions( ); } -// Build URLs for the surfaces exposing each x402 resource, using the public -// base URL so indexers can request endpoints instead of `resource://` identifiers +// Build public endpoint URLs for the surfaces exposing resources served on +// x402, which indexers can request, unlike `resource://` identifiers function publicResourceUrls( publicBaseUrl: string, protocols: NormalizedProtocols, @@ -175,19 +188,17 @@ function publicResourceUrls( ? `/api/resources/${encodeURIComponent(id)}/invoke` : protocols[surface].mountPath; return Object.fromEntries( - resources - .filter((resource) => resource.paymentMethods.includes('x402')) - .map((resource) => [ - resource.id, - Object.fromEntries( - (['http', 'mcp', 'a2a'] as const) - .filter((surface) => resource.exposedVia.includes(surface)) - .map((surface) => [ - surface, - publicEndpointUrl(publicBaseUrl, path(surface, resource.id)), - ]), - ), - ]), + resources.map((resource) => [ + resource.id, + Object.fromEntries( + (['http', 'mcp', 'a2a'] as const) + .filter((surface) => resource.exposedVia.includes(surface)) + .map((surface) => [ + surface, + publicEndpointUrl(publicBaseUrl, path(surface, resource.id)), + ]), + ), + ]), ); } diff --git a/src/config/schema/resources.ts b/src/config/schema/resources.ts index 1fce779..9de6146 100644 --- a/src/config/schema/resources.ts +++ b/src/config/schema/resources.ts @@ -237,12 +237,10 @@ export function normalizeResource( ); } - // The gateway serves a resource on the first rail it lists that is enabled - const servingRail = paymentMethods.find( - (method) => - (method === 'x402' && x402?.config.enabled === true) || - (method === 'mpp' && mpp?.enabled === true), - ); + const servingRail = servingRailOf(paymentMethods, { + x402: x402?.config.enabled === true, + mpp: mpp?.enabled === true, + }); const idempotency = normalizeResourceIdempotency(id, entry, paymentMethods, servingRail); const pricing: Pricing = @@ -285,6 +283,16 @@ export function normalizeResource( }; } +/** The resource's first enabled payment rail, which the gateway uses to serve it */ +export function servingRailOf( + paymentMethods: readonly string[], + enabled: { readonly x402: boolean; readonly mpp: boolean }, +): string | undefined { + return paymentMethods.find( + (method) => (method === 'x402' && enabled.x402) || (method === 'mpp' && enabled.mpp), + ); +} + function normalizeResourceIdempotency( id: string, entry: RawResourceEntry, diff --git a/tests/e2e/payment/x402-bazaar.e2e.test.ts b/tests/e2e/payment/x402-bazaar.e2e.test.ts index 9d5cc9a..8f9eba3 100644 --- a/tests/e2e/payment/x402-bazaar.e2e.test.ts +++ b/tests/e2e/payment/x402-bazaar.e2e.test.ts @@ -87,7 +87,7 @@ function rawConfig(facilitatorUrl: string, bazaar: boolean): Record { }); it('MPP beside Bazaar: settles with only x402Version, accepted and payload sent', async () => { - // Config has Bazaar metadata for this resource; MPP must omit it from settlement - expect(withBazaar.config.payments.x402?.resourceBazaar?.['forecast_mpp']).toHaveProperty( - 'http', - ); + // Config omits the x402 URL and metadata because MPP serves this resource + expect(withBazaar.config.payments.x402?.resourceBazaar).not.toHaveProperty('forecast_mpp'); + expect(withBazaar.config.payments.x402?.resourceUrls).not.toHaveProperty('forecast_mpp'); const bodies = await purchase( withBazaar, async () => { diff --git a/tests/integration/x402-bazaar.test.ts b/tests/integration/x402-bazaar.test.ts index 32a676c..be26637 100644 --- a/tests/integration/x402-bazaar.test.ts +++ b/tests/integration/x402-bazaar.test.ts @@ -295,6 +295,13 @@ describe('x402 Bazaar metadata through the gateway', () => { }); it('answers a resource whose first rail is MPP with an MPP challenge and no metadata', async () => { + expect(config.payments.x402?.resourceUrls).not.toHaveProperty('mpp_first'); + expect(config.payments.x402?.resourceBazaar).not.toHaveProperty('mpp_first'); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining( + 'resource "mpp_first" gets no Bazaar metadata: the gateway serves it on mpp', + ), + ); const res = await invoke('mpp_first', { city: 'Oslo', days: 1 }); expect(res.statusCode).toBe(402); diff --git a/tests/unit/config/schema.test.ts b/tests/unit/config/schema.test.ts index 66d10bd..5c6ed01 100644 --- a/tests/unit/config/schema.test.ts +++ b/tests/unit/config/schema.test.ts @@ -2795,6 +2795,57 @@ describe('payments.x402.bazaar', () => { input: { type: 'http', method: 'POST', bodyType: 'json', body: {} }, }); }); + + // Enable both rails and list them on the resource in the requested order + function withBothRails(payments: string[]) { + const raw = withBazaar(true); + (raw['payments'] as Record)['mpp'] = { + enabled: true, + rpcUrl: 'https://sepolia.example/v2/key', + asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', + assetName: 'USDC', + assetVersion: '2', + recipient: '0x1111111111111111111111111111111111111111', + realm: 'api.example.com', + challengeSecret: 'mpp-challenge-secret-'.padEnd(32, 'x'), + facilitator: { mode: 'remote', url: 'https://facilitator.example' }, + }; + marketReport(raw)['payments'] = payments; + return raw; + } + + it('builds no URL or metadata for a resource served on MPP, and says which rail serves it', () => { + const config = parseConfig(withBothRails(['mpp', 'x402']), {}); + + expect(config.payments.x402?.resourceUrls).toEqual({}); + expect(config.payments.x402?.resourceBazaar).toEqual({}); + expect(warn.mock.calls).toEqual([ + [ + '[agent-commerce] resource "market_report" gets no Bazaar metadata: the gateway serves it on mpp, the first enabled rail in its payments, which issues no x402 challenge. Payment is unaffected.', + ], + ]); + }); + + it('builds both for a resource that lists x402 first, without a warning', () => { + const config = parseConfig(withBothRails(['x402', 'mpp']), {}); + + expect(Object.keys(config.payments.x402?.resourceUrls ?? {})).toEqual(['market_report']); + expect(Object.keys(config.payments.x402?.resourceBazaar?.['market_report'] ?? {})).toEqual([ + 'http', + 'mcp', + ]); + expect(warn).not.toHaveBeenCalled(); + }); + + it('serves on x402, and builds both, when the MPP rail listed first is disabled', () => { + const raw = withBothRails(['mpp', 'x402']); + ((raw['payments'] as Record)['mpp'] as Record)['enabled'] = + false; + const config = parseConfig(raw, {}); + + expect(Object.keys(config.payments.x402?.resourceBazaar ?? {})).toEqual(['market_report']); + expect(warn).not.toHaveBeenCalled(); + }); }); describe('protocols.mcp.registry', () => { From 7b616cbe83fcf8f19b7cd54db26201f0054b6b71 Mon Sep 17 00:00:00 2001 From: Revinand Date: Wed, 18 Nov 2026 23:38:36 +0100 Subject: [PATCH 14/14] feat(x402): list the public URL and Bazaar options as descriptor capabilities --- README.md | 25 +++++++++++----- config.example.yaml | 14 +++++++++ docs/contracts.md | 3 ++ docs/protocols.md | 7 +++-- docs/protocols/x402.md | 37 ++++++++++++++++++++---- docs/security.md | 2 ++ src/payments/x402/provider/index.ts | 2 ++ src/support/x402.json | 10 ++++++- tests/integration/support-record.test.ts | 2 ++ 9 files changed, 86 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 01ebd49..3ddf7f8 100644 --- a/README.md +++ b/README.md @@ -341,11 +341,21 @@ prints the `unsupported` lists for A2A, ACP and AP2 when they are enabled. ### Versioning -Minor releases may break experimental configurations, integrations or types: -MPP, A2A, ACP, AP2, ERC-8409 quotes, `agent-commerce import openapi`, -`PaymentProvider.reconcile`, the `ReceiptStore` methods and types added in -2.6.0, the `idempotency` resource settings with the store and provider methods -added in 2.7.0, and the `./testing` entry. +Minor releases may break experimental configurations, integrations or types. +This includes MPP, A2A, ACP, AP2, ERC-8409 quotes, the +[public resource URL](docs/configuration.md#public-resource-url) and +[Bazaar metadata](docs/configuration.md#bazaar-metadata) in payment +challenges, and these interfaces: + +- `agent-commerce import openapi`. +- `agent-commerce export mcp-registry`, `doctor --registry` and the + `protocols.mcp.registry` keys. +- `PaymentProvider.reconcile` and the `ReceiptStore` methods and types added + in 2.6.0. +- The `idempotency` resource settings and the store and provider methods added + in 2.7.0. +- `PaymentContext.protocol` and `AdapterHealthComponent.undetermined` (added + in 2.8.0), and the `./testing` entry. A profile moves from experimental to supported only when it meets the [promotion criteria](docs/protocols.md#promotion-criteria). @@ -711,8 +721,9 @@ See [CONTRIBUTING.md](CONTRIBUTING.md). mainnet, Solana devnet and Solana mainnet, receipts, doctor, deterministic demo, experimental A2A v1.0.1 and ACP `2026-04-17` checkout adapters, experimental AP2 v0.2.0 mandate verification, experimental MPP `charge` -payments, experimental OpenAPI import, and experimental retries after a lost -response. +payments, experimental OpenAPI import, experimental retries after a lost +response, and experimental discovery metadata for x402 Bazaar and MCP Registry +listings. **Next** - a `doctor` GitHub Action · UCP · autonomous-mode AP2 (open mandates, agent key binding, constraint evaluation) · diff --git a/config.example.yaml b/config.example.yaml index 4923ea4..7a13df6 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -44,6 +44,13 @@ protocols: mcp: enabled: true mountPath: /mcp + # Experimental MCP Registry fields. Export them to server.json with + # `agent-commerce export mcp-registry`. The gateway also reports name and + # version in MCP serverInfo. See docs/configuration.md#protocolsmcpregistry. + # registry: + # name: io.github.acme/weather + # version: 1.0.0 + # description: Weather forecasts, paid per call # A2A (Agent2Agent) v1.0.1 - experimental, off by default. # Serves JSON-RPC `SendMessage` at mountPath and the Agent Card at # /.well-known/agent-card.json. Enable at least one resource with @@ -140,6 +147,13 @@ payments: # quote: # enabled: true # signerPrivateKey: ${X402_QUOTE_SIGNER_KEY} + # Experimental discovery. publicResourceUrl replaces resource:// identifiers + # with public endpoint URLs in x402 challenges on HTTP, MCP and A2A. + # bazaar adds catalog metadata on HTTP and MCP and requires publicResourceUrl. + # See docs/configuration.md#public-resource-url. + # publicResourceUrl: true + # bazaar: + # enabled: true # Settlement order: authorization (the default) calls the backend first # and settles only if it succeeds; upfront settles first. A paid resource # can set its own paymentFlow, which applies to the rail that serves it. diff --git a/docs/contracts.md b/docs/contracts.md index 8097983..bc000ee 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -477,6 +477,8 @@ persistence must not fail the commerce flow. `GatewayConfig.payments.x402.resourceUrls` for resources whose first enabled rail is x402, with each URL in the URL parser's form. MPP's internal x402 provider does not receive this map. + - A provider given the map lists `public-resource-url` in its descriptor's + `capabilities`. - Without the option, challenges are unchanged. - 2.8.0: experimental `X402ProviderOptions.resourceBazaar` maps resource ids and request surfaces (`http` or `mcp`) to each challenge's `extensions.bazaar` @@ -491,6 +493,7 @@ persistence must not fail the commerce flow. - An HTTP challenge omits the metadata unless its encoded `PAYMENT-REQUIRED` value plus the largest proof reserve among its offer families fits within 8192 bytes. + - A provider given the map lists `bazaar` in its descriptor's `capabilities`. - Without the option, challenges and facilitator bodies are unchanged. - 2.8.0: experimental `GatewayConfig.protocols.mcp.registry` holds the `name`, `version` and `description` from `protocols.mcp.registry` and is diff --git a/docs/protocols.md b/docs/protocols.md index 679e2e3..713d85e 100644 --- a/docs/protocols.md +++ b/docs/protocols.md @@ -49,6 +49,7 @@ on the wallet holder's machine, never in CI. | x402 | HTTP | - | E2E, local chain | `tests/e2e/payment/x402-settlement.e2e.test.ts` | | x402 | A2A | - | E2E, local chain | `tests/e2e/payment/x402-settlement.e2e.test.ts` | | x402 | HTTP | AP2 | E2E, local chain | `tests/e2e/authorization/ap2-x402.e2e.test.ts` | +| x402 | MCP | - | E2E, local chain | `tests/e2e/payment/x402-bazaar.e2e.test.ts` | | x402 | MCP | - | integration, no chain | `tests/integration/mcp-payment-bindings.test.ts` | | x402 | HTTP | - | public testnet | `tests/testnet/x402.smoke.test.ts` | | x402 | HTTP | - | mainnet | `tests/mainnet/x402.smoke.test.ts` | @@ -87,13 +88,15 @@ that status. Upstream does not label x402 v2 stable, and its record states that. - [HTTP surface](protocols/http.md): routes, and the payment headers each rail uses on the invoke route -- [MCP](protocols/mcp.md): tools, payment over MCP, and exclusions +- [MCP](protocols/mcp.md): tools, payment over MCP, MCP Registry listings, + and exclusions - [A2A](protocols/a2a.md): invocation and payment, the x402 extension, results, and exclusions - [ACP](protocols/acp.md): headers, checkout operations, the payment boundary, idempotency, errors, discovery, and exclusions - [x402](protocols/x402.md): the `exact` scheme on EVM, Solana and NEAR, - several options, payment flows, and mainnet guardrails + several options, payment flows, the public resource URL, Bazaar metadata, + and mainnet guardrails - [MPP](protocols/mpp.md): the pinned drafts, the `charge` profile, payment flow, problem documents, and exclusions - [AP2](protocols/ap2.md): mandate verification before a paid resource settles diff --git a/docs/protocols/x402.md b/docs/protocols/x402.md index 41726e5..823b4b6 100644 --- a/docs/protocols/x402.md +++ b/docs/protocols/x402.md @@ -128,11 +128,12 @@ By default, `resource.url` is a gateway identifier. A single offer uses share `resource://agent-commerce/resources/`. The `` and `` segments are percent-encoded. -With [`publicResourceUrl`](../configuration.md#public-resource-url), the URL -names the configured HTTP invoke route, MCP mount or A2A mount for the -request's surface. Every offer of that resource shares the URL on that surface; -`accepted` still selects the offer. The echo comparison above rejects these -proofs before calling the facilitator, and neither reaches settlement: +[`publicResourceUrl`](../configuration.md#public-resource-url) is experimental +and disabled by default. When enabled, the URL names the configured HTTP +invoke route, MCP mount or A2A mount for the request's surface. Every offer of +that resource shares the URL on that surface; `accepted` still selects the offer. +The echo comparison above rejects these proofs before calling the facilitator, +and neither reaches settlement: - a proof that echoes the previous URL after the option changes; - a proof that echoes another surface's URL. @@ -140,6 +141,9 @@ proofs before calling the facilitator, and neither reaches settlement: The buyer can request and pay a new challenge. These checks provide no security boundary: `resource.url` is unsigned, and a client may omit it. +Enabling this option adds `public-resource-url` to the x402 descriptor's +`capabilities` in `GET /.well-known/agent-commerce`. + ## Bazaar discovery metadata Experimental and disabled by default. With @@ -147,7 +151,8 @@ Experimental and disabled by default. With and MCP carry `extensions.bazaar` metadata for a facilitator's catalog. Other surfaces carry no Bazaar metadata. A resource whose first enabled rail is MPP receives an MPP challenge and no metadata; config loading warns when -such a resource also lists `x402`. +such a resource also lists `x402`. Enabling Bazaar adds `bazaar` to the x402 +descriptor's `capabilities` in `GET /.well-known/agent-commerce`. | Surface | `info.input` | `info.output` | | ------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | @@ -214,6 +219,26 @@ up to 200 characters of the reason, once per resource and provider instance. This metadata outcome does not change the payment result. The pinned x402 SDK also prints selected status, reason and code fields from each outcome to stdout. +### Getting listed + +The gateway supplies metadata; the facilitator decides what to index. +Coinbase's CDP facilitator +[documents](https://docs.cdp.coinbase.com/x402/seller/get-discovered) the +following rules (checked 2026-11-18): + +- An endpoint becomes eligible for indexing after CDP settles a payment whose + payload includes both `resource` and `extensions.bazaar`, the fields the + gateway forwards. +- Indexing probes send HTTP endpoints the example input, which must produce a + 402 challenge. MCP probes call tools with `info.input.example`; tools without + an example or an x402 payment challenge cannot be indexed. +- Resources are removed after 30 days without a settlement. Endpoints that stop + returning 402 are eventually removed too. + +The offline E2E suite verifies settlement with these forwarded fields on a local +chain through a test facilitator. It does not verify indexing by an external +facilitator. + ## Payment identifier Experimental and disabled by default. A resource with diff --git a/docs/security.md b/docs/security.md index 1519d8f..28e0e71 100644 --- a/docs/security.md +++ b/docs/security.md @@ -591,6 +591,8 @@ real funds. | **an MCP Registry answer injecting text into `doctor` output** | `doctor --registry` names differing fields and uses fixed messages for known lifecycle statuses, without echoing arbitrary answer values or request error messages in text or JSON | `tests/unit/cli/doctor-registry.test.ts` ("prints no value from a hostile answer, in text or JSON", "leaves a TLS failure unmarked and does not print its message") | | **`doctor --registry` sending more than the server name** | sends a GET to `/v0.1/servers//versions/latest?include_deleted=true` with no custom headers or body, only when the flag is set and config yields a listing | `tests/unit/cli/doctor-registry.test.ts` ("asks for the configured name only, with no header or body", "adds no check and sends nothing to the registry without the flag", "sends nothing for an http public URL") | | **another server name listing the gateway's URL, taken for the merchant's listing** | `doctor --registry` looks up the configured name only and reports a response with another name as a difference in `name` | `tests/unit/cli/doctor-registry.test.ts` ("asks for the configured name only, with no header or body", "reports a listing under another name") | +| **a support record citing a test or doc file that does not exist** | the drift check in `npm test` fails and names the record and the missing path | `tests/integration/support-record.test.ts` ("names the place of %s") | +| **a generated support table or list edited by hand in the README or docs** | the drift check fails and names the file and region; `npm run support:write` restores the region from the records | `tests/integration/support-record.test.ts` ("names the place of %s", "--write restores a hand-edited region and refuses a file with missing markers") | A facilitator verdict is a returned result. The SDK throws when a remote `/verify` answers with a non-2xx status; the binding turns that throw back into diff --git a/src/payments/x402/provider/index.ts b/src/payments/x402/provider/index.ts index 816f67d..1c53922 100644 --- a/src/payments/x402/provider/index.ts +++ b/src/payments/x402/provider/index.ts @@ -114,6 +114,8 @@ export function createX402PaymentProvider( 'upfront-flow', ...(severalOffers ? ['multiple-offers'] : []), ...(quotes ? ['erc-8409-quotes'] : []), + ...(options.resourceUrls !== undefined ? ['public-resource-url'] : []), + ...(options.resourceBazaar !== undefined ? ['bazaar'] : []), ], status: descriptorStatus(record), unsupported: exclusionNames(record), diff --git a/src/support/x402.json b/src/support/x402.json index 46c3433..4286bf1 100644 --- a/src/support/x402.json +++ b/src/support/x402.json @@ -56,7 +56,9 @@ "title": "ERC-8409", "role": "x402 feature: EIP-712 signed quotes on the EVM offers of a challenge.", "subset": "signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce`" - } + }, + { "name": "public-resource-url", "status": "experimental" }, + { "name": "bazaar", "status": "experimental" } ], "exclusions": [ { "name": "permit2 gas sponsoring extensions" }, @@ -106,6 +108,12 @@ "level": "e2e", "evidence": "tests/e2e/authorization/ap2-x402.e2e.test.ts" }, + { + "surface": "mcp", + "method": "x402", + "level": "e2e", + "evidence": "tests/e2e/payment/x402-bazaar.e2e.test.ts" + }, { "surface": "mcp", "method": "x402", diff --git a/tests/integration/support-record.test.ts b/tests/integration/support-record.test.ts index eece327..8c3ad16 100644 --- a/tests/integration/support-record.test.ts +++ b/tests/integration/support-record.test.ts @@ -122,6 +122,8 @@ const X402_MATRIX: Record> = { ], facilitator: REMOTE, quote: { enabled: true, signerPrivateKey: QUOTE_SIGNER }, + publicResourceUrl: true, + bazaar: { enabled: true }, }, 'Base mainnet': { network: 'eip155:8453',