From 37810f3d0ebfc02bc27503b3c1f2b8d85a78e540 Mon Sep 17 00:00:00 2001 From: Mabolla <133767935+Mabolla@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:01:02 +0300 Subject: [PATCH] Harden agent checks and prepare reproducible Railway deployment --- .github/workflows/ci.yml | 2 +- Dockerfile | 4 +- README.md | 30 +++++++---- examples/agent-client.mjs | 23 +++++++++ railway.json | 13 +++++ src/assurance.ts | 56 ++++---------------- src/mcp.ts | 21 +++++--- src/public-http.ts | 104 ++++++++++++++++++++++++++++++++++++++ src/server.ts | 4 +- test/assurance.test.ts | 2 +- test/mcp.test.ts | 18 ++++++- test/public-http.test.ts | 56 ++++++++++++++++++++ 12 files changed, 261 insertions(+), 72 deletions(-) create mode 100644 examples/agent-client.mjs create mode 100644 railway.json create mode 100644 src/public-http.ts create mode 100644 test/public-http.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b1ddf6b..c9328c1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22 - - run: npm install + - run: npm ci - run: npm run typecheck - run: npm test - run: npm run build diff --git a/Dockerfile b/Dockerfile index 17b2803..e08b760 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ FROM node:22-alpine AS build WORKDIR /app COPY package*.json ./ -RUN npm install +RUN npm ci COPY tsconfig.json tsconfig.build.json ./ COPY src ./src RUN npm run build @@ -10,7 +10,7 @@ FROM node:22-alpine AS runtime ENV NODE_ENV=production WORKDIR /app COPY package*.json ./ -RUN npm install --omit=dev +RUN npm ci --omit=dev COPY --from=build /app/dist ./dist EXPOSE 4021 CMD ["npm", "start"] diff --git a/README.md b/README.md index 2de8860..2ed1084 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ For POST resources: npm run check -- https://api.example.com/paid-resource --method POST --body '{"query":"value"}' ``` -The CLI prints JSON. `FAIL` exits with code 1 and invalid input exits with code 2. `PASS` and `WARN` exit successfully so teams can choose their warning policy. The same workflow is available through `POST /api/check`. Public DNS resolution is checked and private, loopback, link-local, and carrier-grade NAT targets are rejected. +The CLI prints JSON. `FAIL` exits with code 1 and invalid input exits with code 2. `PASS` and `WARN` exit successfully so teams can choose their warning policy. The same workflow is available through `POST /api/check`. The checker rejects non-public IP addresses, connects only to the DNS addresses it validated, does not follow redirects, and caps response bodies at 128 KiB. Explicit POST checks can have effects on the target service; the MCP tool supports GET only. ## Agent interface (MCP) @@ -30,10 +30,10 @@ Base Agent Meter exposes a remote MCP Streamable HTTP endpoint at `/mcp`. It pub | Tool | Purpose | | --- | --- | -| `check_x402_endpoint` | Inspect a public seller endpoint's x402 v2 challenge, Base USDC terms, Bazaar metadata, Builder Code declaration, and optional pinned expectations. | +| `check_x402_endpoint` | Send an unpaid GET to inspect a public seller endpoint's x402 v2 challenge, Base USDC terms, Bazaar metadata, Builder Code declaration, and optional pinned expectations. | | `verify_base_settlement` | Verify an existing Base transaction's successful receipt and USDC transfer, with optional payer and Builder Code checks. | -Neither tool can create a payment, sign a transaction, or access payer credentials. The endpoint uses stateless Streamable HTTP; there is no MCP session state. Requests to `/mcp` are limited to 30 per minute per client IP. The older JSON endpoints remain available for scripts and CI. Once deployed, connect an MCP client to `https:///mcp`. +Neither tool can create a payment, sign a transaction, or access payer credentials. The endpoint uses stateless Streamable HTTP; there is no MCP session state. HTTP POST is the MCP transport method; GET and DELETE on `/mcp` return 405. Requests to `/mcp` are limited to 30 per minute per observed connection IP. Behind a reverse proxy this can be a shared limit; forwarded IP headers are not trusted. The older JSON endpoints remain available for scripts and CI. Once deployed, connect an MCP client to `https:///mcp`. Example tool inputs: @@ -42,10 +42,18 @@ Example tool inputs: ``` ```json -{"transactionHash":"0x...","expectedPayTo":"0xYourExpectedRecipient","expectedAmount":"1000","expectedPayer":"0xOptionalExpectedPayer"} +{"transactionHash":"0x...","expectedPayTo":"0xYourExpectedRecipient","expectedAmount":"1000","expectedPayer":"0xOptionalExpectedPayer","declaredBuilderCode":"seller_code"} ``` -`expectedAmount` is the integer amount in USDC's 6-decimal atomic units. A challenge can declare a Builder Code, but the tool only reports attribution as verified when it observes the configured code in the completed transaction. +`expectedAmount` is the integer amount in USDC's 6-decimal atomic units. `expectedPayer` and `declaredBuilderCode` are optional. Addresses and transaction hashes above are placeholders. The proof tool always reports observed attribution, and marks it verified only when it matches the explicitly supplied `declaredBuilderCode`. Omitting that field does not silently use this project's Builder Code. + +A runnable SDK example is provided for agent developers: + +```bash +node examples/agent-client.mjs https:///mcp https:///paid-resource +``` + +The automated MCP integration test uses the official SDK client against a real local HTTP listener to exercise discovery, tool calls, input validation, and unsupported transport methods. It does not establish public deployment availability. ## 2. Live paid canary @@ -85,9 +93,13 @@ After a completed canary, Base Agent Meter verifies transaction inclusion and st The canary writes a JSON artifact under `artifacts/` containing endpoint, timestamp, payment terms, payer, transaction hash, response status, latency, response body hash, USDC evidence, and builder-attribution evidence. Existing transactions can be checked through `POST /api/proof/verify`. -## Existing deployed seller fixture +## Deployment status and optional seller fixture + +The previously configured Railway host returned **HTTP 404, Application not found**, on 2026-10-01. Public availability of `/health` and `/mcp` is not verified. A passing build or a merged commit is not evidence of a live service. + +`railway.json` selects the Dockerfile, sets `/health` as the deployment health check, and configures up to three on-failure restarts. The Docker build and CI use the committed dependency lockfile. This configuration applies when an authorized Railway service deploys the repository; it does not create or reconnect that service. See [Railway's configuration reference](https://docs.railway.com/config-as-code/reference). -The repository preserves the original paid Base snapshot as an optional self-test fixture. The deployment predates the Production Assurance pivot. +The repository preserves the original paid Base snapshot as an optional self-test fixture. Its historical deployment predates the Production Assurance pivot. - Service: `https://base-agent-meter-production.up.railway.app` - Resource: `GET /api/base-snapshot` @@ -116,7 +128,7 @@ This evidence verifies the seller fixture's payment and attribution path. It doe ## Local server ```bash -npm install +npm ci npm run typecheck npm test npm run build @@ -136,7 +148,7 @@ BUILDER_CODE=bc_h2oqnbbh ## Safety boundaries -- Checks are read-only and never submit payment headers. +- The MCP checker sends unpaid GET requests and never submits payment headers. Explicit CLI/API POST checks may have effects on the target service. - Canary dry-runs do not load or require a private key. - Real payment requires pinned expectations and a confirmation token. - Secrets remain environment-only and are excluded from git. diff --git a/examples/agent-client.mjs b/examples/agent-client.mjs new file mode 100644 index 0000000..23307b8 --- /dev/null +++ b/examples/agent-client.mjs @@ -0,0 +1,23 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; + +// Run from this repository after its dependencies are available. +// Usage: node examples/agent-client.mjs +const [mcpUrl, sellerUrl] = process.argv.slice(2); +if (!mcpUrl || !sellerUrl) { + console.error("Usage: node examples/agent-client.mjs "); + process.exit(2); +} + +const client = new Client({ name: "base-agent-meter-example", version: "1.0.0" }); +try { + await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl))); + const result = await client.callTool({ name: "check_x402_endpoint", arguments: { url: sellerUrl } }); + console.log(JSON.stringify(result, null, 2)); + if (result.isError) process.exitCode = 1; +} catch (error) { + console.error(error instanceof Error ? error.message : "MCP request failed"); + process.exitCode = 1; +} finally { + await client.close(); +} diff --git a/railway.json b/railway.json new file mode 100644 index 0000000..684cc9a --- /dev/null +++ b/railway.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://railway.com/railway.schema.json", + "build": { + "builder": "DOCKERFILE", + "dockerfilePath": "Dockerfile" + }, + "deploy": { + "healthcheckPath": "/health", + "healthcheckTimeout": 60, + "restartPolicyType": "ON_FAILURE", + "restartPolicyMaxRetries": 3 + } +} diff --git a/src/assurance.ts b/src/assurance.ts index e33de97..cc61f3e 100644 --- a/src/assurance.ts +++ b/src/assurance.ts @@ -1,5 +1,5 @@ -import { lookup } from "node:dns/promises"; -import { isIP } from "node:net"; +import { CheckInputError, requestPublicTarget, resolvePublicTarget } from "./public-http.js"; +export { CheckInputError } from "./public-http.js"; import { decodePaymentRequiredHeader } from "@x402/core/http"; import { parsePaymentRequired } from "@x402/core/schemas"; import { getAddress, isAddress } from "viem"; @@ -58,52 +58,12 @@ export interface AssuranceReport { findings: AssuranceFinding[]; } -export class CheckInputError extends Error {} - interface CheckDependencies { fetchImpl?: typeof fetch; resolveHost?: (hostname: string) => Promise; now?: () => Date; } -function isPrivateAddress(address: string): boolean { - const normalized = address.toLowerCase(); - if (normalized === "::1" || normalized === "::" || normalized.startsWith("fe80:") || normalized.startsWith("fc") || normalized.startsWith("fd")) return true; - if (!isIP(address)) return true; - const parts = address.split(".").map(Number); - if (parts.length !== 4) return false; - return parts[0] === 10 - || parts[0] === 127 - || parts[0] === 0 - || (parts[0] === 169 && parts[1] === 254) - || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) - || (parts[0] === 192 && parts[1] === 168) - || (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127); -} - -async function defaultResolveHost(hostname: string): Promise { - const records = await lookup(hostname, { all: true, verbatim: true }); - return records.map(record => record.address); -} - -async function validatePublicUrl(rawUrl: string, resolveHost: (hostname: string) => Promise): Promise { - let url: URL; - try { - url = new URL(rawUrl); - } catch { - throw new CheckInputError("url must be a valid absolute URL"); - } - if (url.protocol !== "https:" && url.protocol !== "http:") { - throw new CheckInputError("url must use http or https"); - } - if (url.username || url.password) throw new CheckInputError("url credentials are not allowed"); - const addresses = await resolveHost(url.hostname); - if (addresses.length === 0 || addresses.some(isPrivateAddress)) { - throw new CheckInputError("url must resolve only to public IP addresses"); - } - return url; -} - function decodeChallenge(response: Response, body: unknown): unknown { const header = response.headers.get("payment-required"); if (header) return decodePaymentRequiredHeader(header); @@ -135,11 +95,10 @@ export async function checkX402Endpoint(input: CheckRequest, dependencies: Check if (!input || typeof input !== "object" || typeof input.url !== "string") { throw new CheckInputError("url must be a valid absolute URL"); } - const fetchImpl = dependencies.fetchImpl ?? fetch; - const resolveHost = dependencies.resolveHost ?? defaultResolveHost; const now = dependencies.now ?? (() => new Date()); const startedAt = performance.now(); - const url = await validatePublicUrl(input.url, resolveHost); + const target = await resolvePublicTarget(input.url, dependencies.resolveHost); + const url = target.url; const method = input.method ?? "GET"; if (method !== "GET" && method !== "POST") throw new CheckInputError("method must be GET or POST"); const expectations = input.expectations ?? {}; @@ -153,13 +112,16 @@ export async function checkX402Endpoint(input: CheckRequest, dependencies: Check let response: Response; let responseBody: unknown; try { - response = await fetchImpl(url, { + const request: RequestInit = { method, redirect: "manual", signal: AbortSignal.timeout(12_000), headers: method === "POST" ? { "content-type": "application/json", accept: "application/json" } : { accept: "application/json" }, body: method === "POST" ? JSON.stringify(input.body ?? {}) : undefined, - }); + }; + response = dependencies.fetchImpl + ? await dependencies.fetchImpl(url, request) + : await requestPublicTarget(target, request); const text = await response.text(); try { responseBody = text ? JSON.parse(text) : undefined; } catch { responseBody = text; } } catch (error) { diff --git a/src/mcp.ts b/src/mcp.ts index e4dfed6..33a0c95 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -10,7 +10,6 @@ interface McpDependencies { checkEndpoint?: typeof checkX402Endpoint; verifySettlement?: typeof verifyBaseSettlement; rpcUrl: string; - builderCode: string; } function jsonResult(value: unknown) { @@ -36,11 +35,10 @@ export function createMeterMcpServer(dependencies: McpDependencies) { "check_x402_endpoint", { title: "Check an x402 endpoint", - description: "Read a public HTTP endpoint and report whether its x402 v2 challenge advertises Base Mainnet USDC, stable payment details, Bazaar metadata, and Builder Code attribution. No payment is made. Private, loopback, link-local, and carrier-grade NAT destinations are rejected.", + description: "Send an unpaid GET to a public endpoint and report its x402 v2 Base Mainnet USDC challenge, payment details, Bazaar metadata, and declared Builder Code. Only GET is supported by this read-only tool; use the CLI or HTTP API for an explicitly requested POST check.", inputSchema: { url: z.string().url(), - method: z.enum(["GET", "POST"]).optional(), - body: z.unknown().optional(), + method: z.literal("GET").optional(), expectations: z.object({ network: z.string().optional(), asset: z.string().optional(), @@ -63,12 +61,13 @@ export function createMeterMcpServer(dependencies: McpDependencies) { "verify_base_settlement", { title: "Verify a Base settlement", - description: "Read a Base Mainnet transaction and verify its successful receipt and exact USDC transfer to the expected recipient, amount, and optional payer. Also reports whether the configured Builder Code appears in the transaction calldata. This does not submit or modify transactions.", + description: "Read a Base Mainnet transaction and verify its successful receipt and exact USDC transfer to the expected recipient, amount, and optional payer. Reports observed attribution and compares it with declaredBuilderCode only when supplied. This does not submit or modify transactions.", inputSchema: { transactionHash: z.string().refine(isHash, "must be a 32-byte transaction hash"), expectedPayTo: z.string().refine(isAddress, "must be a valid EVM address"), expectedAmount: z.string().regex(/^[1-9]\d*$/, "must be a positive atomic-unit amount"), expectedPayer: z.string().refine(isAddress, "must be a valid EVM address").optional(), + declaredBuilderCode: z.string().regex(/^[a-z0-9_]{1,32}$/).optional(), }, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, }, @@ -78,7 +77,6 @@ export function createMeterMcpServer(dependencies: McpDependencies) { verifiedAt: new Date().toISOString(), proof: await verifySettlement(dependencies.rpcUrl, { ...input, - declaredBuilderCode: dependencies.builderCode, }), }); } catch (error) { @@ -95,6 +93,11 @@ export async function handleMeterMcpRequest( res: ServerResponse, dependencies: McpDependencies, ) { + if (req.method !== "POST") { + res.writeHead(405, { Allow: "POST", "Content-Type": "application/json" }); + res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32000, message: "Method not allowed" } })); + return; + } const server = createMeterMcpServer(dependencies); const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true }); try { @@ -102,8 +105,10 @@ export async function handleMeterMcpRequest( await transport.handleRequest(req, res, req.body); } catch (error) { console.error("mcp_request_failed", error); - if (!res.headersSent) res.statusCode = 500; - if (!res.writableEnded) res.end(JSON.stringify({ error: "mcp_request_failed" })); + if (!res.headersSent) { + res.writeHead(500, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32603, message: "MCP request failed" } })); + } else if (!res.writableEnded) res.end(); } finally { await transport.close().catch(() => undefined); await server.close().catch(() => undefined); diff --git a/src/public-http.ts b/src/public-http.ts new file mode 100644 index 0000000..3bc7526 --- /dev/null +++ b/src/public-http.ts @@ -0,0 +1,104 @@ +import { lookup } from "node:dns/promises"; +import { request as httpRequest } from "node:http"; +import { request as httpsRequest } from "node:https"; +import { BlockList, isIP, type LookupFunction } from "node:net"; + +export class CheckInputError extends Error {} + +const blockedV4 = new BlockList(); +for (const [address, prefix] of [ + ["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], + ["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.0.2.0", 24], + ["192.88.99.0", 24], ["192.168.0.0", 16], ["198.18.0.0", 15], ["198.51.100.0", 24], + ["203.0.113.0", 24], ["224.0.0.0", 4], ["240.0.0.0", 4], +] as const) blockedV4.addSubnet(address, prefix, "ipv4"); +const globalV6 = new BlockList(); +globalV6.addSubnet("2000::", 3, "ipv6"); +const blockedV6 = new BlockList(); +for (const [address, prefix] of [["2001::", 23], ["2001:db8::", 32], ["2002::", 16], ["3fff::", 20]] as const) { + blockedV6.addSubnet(address, prefix, "ipv6"); +} + +export function isPublicAddress(address: string): boolean { + const family = isIP(address); + if (family === 4) return !blockedV4.check(address, "ipv4"); + // Restrict IPv6 to global unicast; this also rejects IPv4-mapped private addresses. + return family === 6 && globalV6.check(address, "ipv6") && !blockedV6.check(address, "ipv6"); +} + +export interface PublicTarget { url: URL; addresses: string[] } + +async function resolveHost(hostname: string): Promise { + const records = await lookup(hostname, { all: true, verbatim: true }); + return records.map(record => record.address); +} + +export async function resolvePublicTarget(rawUrl: string, resolver = resolveHost): Promise { + let url: URL; + try { url = new URL(rawUrl); } catch { throw new CheckInputError("url must be a valid absolute URL"); } + if (url.protocol !== "https:" && url.protocol !== "http:") throw new CheckInputError("url must use http or https"); + if (url.username || url.password) throw new CheckInputError("url credentials are not allowed"); + const hostname = url.hostname.replace(/^\[|\]$/g, ""); + let timer: ReturnType | undefined; + const addresses = isIP(hostname) ? [hostname] : await Promise.race([ + resolver(hostname), + new Promise((_, reject) => { + timer = setTimeout(() => reject(new CheckInputError("DNS resolution timed out")), 12_000); + }), + ]).finally(() => clearTimeout(timer)); + if (!addresses.length || addresses.some(address => !isPublicAddress(address))) { + throw new CheckInputError("url must resolve only to public IP addresses"); + } + return { url, addresses }; +} + +export function pinnedLookup(addresses: readonly string[]): LookupFunction { + const records = addresses.map(address => ({ address, family: isIP(address) })); + return (_hostname, options, callback) => { + if (options.all) callback(null, records); + else callback(null, records[0].address, records[0].family); + }; +} + +export const MAX_CHALLENGE_BYTES = 128 * 1024; + +/** Connect only to the addresses already checked; preserve hostname for Host and TLS SNI. */ +export async function requestPublicTarget(target: PublicTarget, init: RequestInit): Promise { + return new Promise((resolve, reject) => { + const request = target.url.protocol === "https:" ? httpsRequest : httpRequest; + const req = request(target.url, { + method: init.method ?? "GET", + headers: Object.fromEntries(new Headers(init.headers)), + lookup: pinnedLookup(target.addresses), + agent: false, + maxHeaderSize: 16 * 1024, + signal: init.signal ?? undefined, + }, res => { + const chunks: Buffer[] = []; + let size = 0; + res.on("error", reject); + res.on("data", (chunk: Buffer) => { + size += chunk.length; + if (size > MAX_CHALLENGE_BYTES) { + req.destroy(new Error("Endpoint response exceeds 128 KiB")); + return; + } + chunks.push(chunk); + }); + res.on("end", () => { + try { + const headers = new Headers(); + for (const [name, value] of Object.entries(res.headers)) { + if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(", ") : value); + } + const status = res.statusCode ?? 502; + resolve(new Response([204, 205, 304].includes(status) ? null : Buffer.concat(chunks), { status, headers })); + } catch (error) { + reject(error); + } + }); + }); + req.on("error", reject); + req.end(typeof init.body === "string" ? init.body : undefined); + }); +} diff --git a/src/server.ts b/src/server.ts index 06abc85..49a0465 100644 --- a/src/server.ts +++ b/src/server.ts @@ -23,8 +23,8 @@ const mcpLimiter = rateLimit({ windowMs: 60_000, limit: 30, standardHeaders: "dr app.get("/", (_req, res) => res.type("html").send(renderHomePage().replace("", `\n `))); app.get("/health", (_req, res) => res.json({ ok: true, service: "base-agent-meter", product: "x402-production-assurance", network: config.network })); app.get("/api/meta", (_req, res) => res.json({ service: "base-agent-meter", product: "x402-production-assurance", network: config.network, asset: "USDC", workflows: { mcp: { transport: "Streamable HTTP", endpoint: "/mcp", tools: ["check_x402_endpoint", "verify_base_settlement"], readOnly: true }, preDeployCheck: "POST /api/check", settlementProof: "POST /api/proof/verify", paidCanary: "npm run canary -- " }, sellerFixture: { enabled: Boolean(config.payTo && config.cdpConfigured), path: "/api/base-snapshot", builderAttribution: config.payTo ? { status: "declared", code: config.builderCode } : { status: "not_configured" } } })); -app.post("/mcp", mcpLimiter, (req, res) => { - void handleMeterMcpRequest(req, res, { rpcUrl: config.rpcUrl, builderCode: config.builderCode }); +app.all("/mcp", mcpLimiter, (req, res) => { + void handleMeterMcpRequest(req, res, { rpcUrl: config.rpcUrl }); }); app.post("/api/check", async (req, res) => { try { const report = await checkX402Endpoint(req.body as CheckRequest); res.status(report.status === "FAIL" ? 422 : 200).json(report); } catch (error) { if (error instanceof CheckInputError || error instanceof SyntaxError) { res.status(400).json({ status: "FAIL", error: "invalid_check_request", message: error.message }); return; } console.error("assurance_check_failed", error); res.status(500).json({ status: "FAIL", error: "assurance_check_failed" }); } }); app.post("/api/proof/verify", async (req, res) => { const { transactionHash, expectedPayer, expectedPayTo, expectedAmount, declaredBuilderCode } = req.body ?? {}; if (!isHash(transactionHash) || !isAddress(expectedPayTo) || typeof expectedAmount !== "string" || !/^\d+$/.test(expectedAmount)) { res.status(400).json({ error: "invalid_proof_request", message: "transactionHash, expectedPayTo, and atomic-unit expectedAmount are required." }); return; } if (expectedPayer !== undefined && !isAddress(expectedPayer)) { res.status(400).json({ error: "invalid_proof_request", message: "expectedPayer must be a valid EVM address when supplied." }); return; } try { res.json({ verifiedAt: new Date().toISOString(), proof: await verifyBaseSettlement(config.rpcUrl, { transactionHash, expectedPayer, expectedPayTo, expectedAmount, declaredBuilderCode }) }); } catch (error) { console.error("settlement_proof_failed", error); res.status(502).json({ error: "base_proof_unavailable", message: error instanceof Error ? error.message : "Base RPC verification failed." }); } }); diff --git a/test/assurance.test.ts b/test/assurance.test.ts index 36053f0..fecaac0 100644 --- a/test/assurance.test.ts +++ b/test/assurance.test.ts @@ -21,7 +21,7 @@ const challenge: PaymentRequired = { }, }; -const publicDns = async () => ["203.0.113.10"]; +const publicDns = async () => ["93.184.216.34"]; describe("checkX402Endpoint", () => { it("passes valid Base USDC negotiation and distinguishes declared attribution", async () => { diff --git a/test/mcp.test.ts b/test/mcp.test.ts index 19c896d..bd371d0 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -16,8 +16,8 @@ describe("Base Agent Meter MCP server", () => { })) as unknown as typeof verifyBaseSettlement; const app = express(); app.use(express.json()); - app.post("/mcp", (req, res) => { - void handleMeterMcpRequest(req, res, { rpcUrl: "https://rpc.example", builderCode: "bc_h2oqnbbh", verifySettlement }); + app.all("/mcp", (req, res) => { + void handleMeterMcpRequest(req, res, { rpcUrl: "https://rpc.example", verifySettlement }); }); let listener: Server | undefined; listener = app.listen(0, "127.0.0.1"); @@ -31,12 +31,23 @@ describe("Base Agent Meter MCP server", () => { expect(listed.tools.map(tool => tool.name)).toEqual(["check_x402_endpoint", "verify_base_settlement"]); expect(listed.tools.every(tool => tool.annotations?.readOnlyHint)).toBe(true); + const unsupportedMethod = await client.callTool({ name: "check_x402_endpoint", arguments: { url: "https://seller.example/paid", method: "POST" } }); + expect(unsupportedMethod.isError).toBe(true); + const privateTarget = await client.callTool({ name: "check_x402_endpoint", arguments: { url: "http://127.0.0.1/" } }); + expect(privateTarget.isError).toBe(true); + for (const method of ["GET", "DELETE"]) { + const response = await fetch(`http://127.0.0.1:${address.port}/mcp`, { method }); + expect(response.status).toBe(405); + expect(response.headers.get("allow")).toBe("POST"); + } + const result = await client.callTool({ name: "verify_base_settlement", arguments: { transactionHash: `0x${"1".repeat(64)}`, expectedPayTo: "0x0000000000000000000000000000000000000001", expectedAmount: "10000", + declaredBuilderCode: "seller_code", }, }); @@ -44,6 +55,9 @@ describe("Base Agent Meter MCP server", () => { const resultContent = result.content as Array<{ type: string; text?: string }>; expect(JSON.parse(resultContent[0].text ?? "{}").proof.settlementVerified).toBe(true); expect(verifySettlement).toHaveBeenCalledOnce(); + expect(verifySettlement).toHaveBeenCalledWith("https://rpc.example", expect.objectContaining({ declaredBuilderCode: "seller_code" })); + await client.callTool({ name: "verify_base_settlement", arguments: { transactionHash: `0x${"1".repeat(64)}`, expectedPayTo: "0x0000000000000000000000000000000000000001", expectedAmount: "10000" } }); + expect(vi.mocked(verifySettlement).mock.calls[1][1].declaredBuilderCode).toBeUndefined(); } finally { await client.close(); await new Promise((resolve, reject) => listener?.close(error => error ? reject(error) : resolve())); diff --git a/test/public-http.test.ts b/test/public-http.test.ts new file mode 100644 index 0000000..f1f10af --- /dev/null +++ b/test/public-http.test.ts @@ -0,0 +1,56 @@ +import { createServer } from "node:http"; +import { describe, expect, it, vi } from "vitest"; +import { CheckInputError, MAX_CHALLENGE_BYTES, pinnedLookup, requestPublicTarget, resolvePublicTarget } from "../src/public-http.js"; + +describe("public endpoint transport", () => { + it.each([ + "127.0.0.1", "10.0.0.1", "169.254.169.254", "100.64.0.1", "224.0.0.1", + "::1", "::ffff:127.0.0.1", "::ffff:a00:1", "fe90::1", "fd00::1", "ff02::1", + ])("rejects non-public DNS result %s", async address => { + await expect(resolvePublicTarget("https://seller.example", async () => [address])).rejects.toBeInstanceOf(CheckInputError); + }); + + it("rejects mixed public/private DNS answers and mapped literal URLs", async () => { + await expect(resolvePublicTarget("https://seller.example", async () => ["93.184.216.34", "10.0.0.1"])).rejects.toThrow(/public IP/); + await expect(resolvePublicTarget("http://[::ffff:127.0.0.1]/")).rejects.toThrow(/public IP/); + }); + + it("pins the checked DNS answer for the connection instead of resolving it again", async () => { + const resolver = vi.fn().mockResolvedValueOnce(["93.184.216.34"]).mockResolvedValue(["127.0.0.1"]); + const target = await resolvePublicTarget("https://seller.example/paid", resolver); + const callback = vi.fn(); + pinnedLookup(target.addresses)("seller.example", { all: true }, callback); + expect(callback).toHaveBeenCalledWith(null, [{ address: "93.184.216.34", family: 4 }]); + expect(resolver).toHaveBeenCalledTimes(1); + }); + + it("uses pinned routing, preserves Host, caps bodies, and does not follow redirects", async () => { + let redirectTargetCalls = 0; + const server = createServer((req, res) => { + if (req.url === "/invalid-status") { res.writeHead(600); res.end(); return; } + if (req.url === "/large") { res.end("a".repeat(MAX_CHALLENGE_BYTES + 1)); return; } + if (req.url === "/redirect") { res.writeHead(302, { location: "/target" }); res.end(); return; } + if (req.url === "/target") redirectTargetCalls++; + res.writeHead(402, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ host: req.headers.host, method: req.method })); + }); + server.listen(0, "127.0.0.1"); + await new Promise(resolve => server.once("listening", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("test server did not listen"); + // A prevalidated target is constructed only inside this local transport test. + const target = (path: string) => ({ url: new URL(`http://seller.invalid:${address.port}${path}`), addresses: ["127.0.0.1"] }); + try { + const response = await requestPublicTarget(target("/paid"), { method: "GET", signal: AbortSignal.timeout(2_000) }); + expect(response.status).toBe(402); + expect(await response.json()).toEqual({ host: `seller.invalid:${address.port}`, method: "GET" }); + const redirect = await requestPublicTarget(target("/redirect"), {}); + expect(redirect.status).toBe(302); + expect(redirectTargetCalls).toBe(0); + await expect(requestPublicTarget(target("/large"), {})).rejects.toThrow(/128 KiB/); + await expect(requestPublicTarget(target("/invalid-status"), {})).rejects.toThrow(/status/); + } finally { + await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); + } + }); +});