From 97dccb4ecdd2c696b0f8571faf67d85c85e243a0 Mon Sep 17 00:00:00 2001 From: epistemedeus Date: Sun, 30 Aug 2026 03:00:16 +0000 Subject: [PATCH 1/2] feat: validate buyer-required JSON output paths --- README.md | 22 ++++++++- src/canonical.ts | 59 +++++++++++++++++++++--- src/cli.ts | 8 +++- src/daemon.ts | 7 +++ src/errors.ts | 1 + src/mcp.ts | 5 ++ src/output-contract.ts | 66 +++++++++++++++++++++++++++ src/payment.ts | 31 +++++++++++-- src/types.ts | 10 ++++ test/output-contract.test.ts | 67 +++++++++++++++++++++++++++ test/payment.test.ts | 88 ++++++++++++++++++++++++++++++++++++ test/policy.test.ts | 41 ++++++++++++++++- 12 files changed, 391 insertions(+), 14 deletions(-) create mode 100644 src/output-contract.ts create mode 100644 test/output-contract.test.ts diff --git a/README.md b/README.md index b7e562c..6983707 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,8 @@ SpendTree never holds either party's money. Not in v0: arbitrary token transfers, swaps, `upto`, batch settlement, subscriptions, fiat/card payments, onramping, refunds, custody, or merchant -delivery guarantees. +attestations. v0 can enforce buyer-required JSON path presence, but it does not +turn that buyer check into a seller guarantee. ## Architecture @@ -162,7 +163,24 @@ SPENDTREE_CAPABILITY=st_cap_... \ ``` For POST resources, append `--json '{"key":"value"}'`. `--text` and an -explicit `--method GET|POST` are also supported. +explicit `--method GET|POST` are also supported. To reject a paid response that +does not contain the fields your agent needs, repeat `--require-path`: + +```sh +SPENDTREE_CAPABILITY=st_cap_... \ + spendtree pay \ + 'https://merchant.example/paid/resource' \ + 'smoke-with-contract-001' \ + 'Buy a result that includes the decision fields' \ + --require-path data.items \ + --require-path provenance.source +``` + +The canonical path list binds into the request identity before authorization. +SpendTree records settlement and the bounded response before checking it. If a +required path is missing, it returns `OUTPUT_INVALID` with the payment ID, +response hash, contract digest, and missing paths. Repeating the identical call +revalidates the stored response without another request, signature, or payment. This is a mainnet operation. If the quote satisfies the mandate, real USDC can move from the configured wallet. diff --git a/src/canonical.ts b/src/canonical.ts index 1909ff4..4a32836 100644 --- a/src/canonical.ts +++ b/src/canonical.ts @@ -5,6 +5,10 @@ import { SpendTreeError } from "./errors.js"; import type { HttpMethod, PaidFetchInput, ValidatedRequest } from "./types.js"; const IDEMPOTENCY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/; +const JSON_PATH_SEGMENT_PATTERN = /^[A-Za-z0-9_-]+$/; +const FORBIDDEN_JSON_PATH_SEGMENTS = new Set(["__proto__", "constructor", "prototype"]); +export const MAX_REQUIRED_JSON_PATHS = 16; +export const MAX_JSON_PATH_DEPTH = 8; export function sha256(value: string | Uint8Array): string { return createHash("sha256").update(value).digest("hex"); @@ -83,10 +87,12 @@ export function validatePaidFetchInput(input: PaidFetchInput): ValidatedRequest if (purpose.length < 1 || purpose.length > 500) { throw new SpendTreeError("BAD_INPUT", "purpose must be between 1 and 500 characters"); } + const requiredJsonPaths = normalizeRequiredJsonPaths(input.requiredJsonPaths); const result: ValidatedRequest = { url, method, + requiredJsonPaths, idempotencyKey: input.idempotencyKey, purpose, }; @@ -96,16 +102,57 @@ export function validatePaidFetchInput(input: PaidFetchInput): ValidatedRequest } export function requestHash(request: ValidatedRequest): string { + const identity: Record = { + url: request.url.href, + method: request.method, + bodyHash: sha256(request.body ?? ""), + contentType: request.contentType ?? null, + }; + if (request.requiredJsonPaths.length > 0) { + identity.requiredJsonPaths = request.requiredJsonPaths; + } return sha256( - stableJson({ - url: request.url.href, - method: request.method, - bodyHash: sha256(request.body ?? ""), - contentType: request.contentType ?? null, - }), + stableJson(identity), ); } +export function normalizeRequiredJsonPaths(input: string[] | undefined): string[] { + if (input === undefined) return []; + if (!Array.isArray(input)) { + throw new SpendTreeError("BAD_INPUT", "requiredJsonPaths must be an array"); + } + if (input.length > MAX_REQUIRED_JSON_PATHS) { + throw new SpendTreeError( + "BAD_INPUT", + `requiredJsonPaths must contain at most ${MAX_REQUIRED_JSON_PATHS} paths`, + ); + } + const normalized = new Set(); + for (const rawPath of input) { + if (typeof rawPath !== "string") { + throw new SpendTreeError("BAD_INPUT", "Every required JSON path must be a string"); + } + const path = rawPath.trim(); + const segments = path.split("."); + if ( + path.length < 1 || + path.length > 256 || + segments.length > MAX_JSON_PATH_DEPTH || + segments.some( + (segment) => + !JSON_PATH_SEGMENT_PATTERN.test(segment) || FORBIDDEN_JSON_PATH_SEGMENTS.has(segment), + ) + ) { + throw new SpendTreeError( + "BAD_INPUT", + `Required JSON paths must use 1-${MAX_JSON_PATH_DEPTH} safe dot-separated segments`, + ); + } + normalized.add(path); + } + return [...normalized].sort(); +} + function isForbiddenHostname(hostname: string): boolean { const host = hostname.toLowerCase().replace(/\.$/, ""); if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) return true; diff --git a/src/cli.ts b/src/cli.ts index 6980ddb..e2f3cf6 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -23,7 +23,7 @@ switch (command) { " spendtree init [--ttl-minutes ]", " spendtree daemon", " spendtree address", - ' spendtree pay "" [--method GET|POST] [--json \'{...}\'|--text "..."]', + ' spendtree pay "" [--method GET|POST] [--json \'{...}\'|--text "..."] [--require-path ]...', " spendtree summary", "", ].join("\n"), @@ -95,7 +95,7 @@ switch (command) { const input = parsePayArgs(process.argv.slice(3)); if (!input) { usage( - 'SPENDTREE_CAPABILITY=... spendtree pay "" [--method GET|POST] [--json \'{...}\'|--text "..."]', + 'SPENDTREE_CAPABILITY=... spendtree pay "" [--method GET|POST] [--json \'{...}\'|--text "..."] [--require-path ]...', ); } const result = await callDaemon(socketPath, capability, "/v1/paid-fetch", input); @@ -119,6 +119,7 @@ function parsePayArgs(args: string[]): PaidFetchInput | null { let method: HttpMethod | undefined; let body: string | undefined; let contentType: PaidFetchInput["contentType"]; + const requiredJsonPaths: string[] = []; for (let index = 0; index < options.length; index += 2) { const flag = options[index]; const value = options[index + 1]; @@ -142,6 +143,8 @@ function parsePayArgs(args: string[]): PaidFetchInput | null { body = value; contentType = "text/plain"; method ??= "POST"; + } else if (flag === "--require-path") { + requiredJsonPaths.push(value); } else { usage(`Unknown payment option: ${flag}`); } @@ -154,6 +157,7 @@ function parsePayArgs(args: string[]): PaidFetchInput | null { ...(method ? { method } : {}), ...(body === undefined ? {} : { body }), ...(contentType === undefined ? {} : { contentType }), + ...(requiredJsonPaths.length === 0 ? {} : { requiredJsonPaths }), }; } diff --git a/src/daemon.ts b/src/daemon.ts index 31cd9db..7d2b9c6 100644 --- a/src/daemon.ts +++ b/src/daemon.ts @@ -2,6 +2,7 @@ import { chmodSync, mkdirSync } from "node:fs"; import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; import { dirname } from "node:path"; import { z } from "zod"; +import { MAX_REQUIRED_JSON_PATHS } from "./canonical.js"; import { SpendTreeError, toSpendTreeError } from "./errors.js"; import { PaymentEngine } from "./payment.js"; import { parseDelegateMandate } from "./policy.js"; @@ -12,6 +13,7 @@ const paidFetchSchema = z.object({ method: z.enum(["GET", "POST"]).optional(), body: z.string().optional(), contentType: z.enum(["application/json", "text/plain"]).optional(), + requiredJsonPaths: z.array(z.string()).max(MAX_REQUIRED_JSON_PATHS).optional(), idempotencyKey: z.string(), purpose: z.string(), }); @@ -81,6 +83,9 @@ async function handleRequest( ...(parsed.method === undefined ? {} : { method: parsed.method }), ...(parsed.body === undefined ? {} : { body: parsed.body }), ...(parsed.contentType === undefined ? {} : { contentType: parsed.contentType }), + ...(parsed.requiredJsonPaths === undefined + ? {} + : { requiredJsonPaths: parsed.requiredJsonPaths }), }; sendJson(response, 200, { ok: true, result: await engine.paidFetch(capability, input) }); return; @@ -165,6 +170,8 @@ function statusFor(code: string): number { case "UPSTREAM_ERROR": case "PAYMENT_INDETERMINATE": return 502; + case "OUTPUT_INVALID": + return 422; case "NOT_FOUND": return 404; default: diff --git a/src/errors.ts b/src/errors.ts index f1b00b1..06a7cfe 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -8,6 +8,7 @@ export type SpendTreeErrorCode = | "DUPLICATE_PAYMENT" | "PAYMENT_REQUIRED_INVALID" | "PAYMENT_INDETERMINATE" + | "OUTPUT_INVALID" | "UPSTREAM_ERROR" | "NOT_FOUND" | "INTERNAL_ERROR"; diff --git a/src/mcp.ts b/src/mcp.ts index a0d431e..6ee4a41 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -2,6 +2,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { z } from "zod"; +import { MAX_REQUIRED_JSON_PATHS } from "./canonical.js"; import { callDaemon } from "./ipc.js"; import { spendTreePaths } from "./paths.js"; import type { CreatedMandate, PaidFetchResult, SpendSummary } from "./types.js"; @@ -26,6 +27,10 @@ server.registerTool( method: z.enum(["GET", "POST"]).default("GET"), body: z.string().optional(), contentType: z.enum(["application/json", "text/plain"]).optional(), + requiredJsonPaths: z + .array(z.string().describe("Required own-property JSON path, such as data.items")) + .max(MAX_REQUIRED_JSON_PATHS) + .optional(), idempotencyKey: z.string().min(1).max(128), purpose: z.string().min(1).max(500), }, diff --git a/src/output-contract.ts b/src/output-contract.ts new file mode 100644 index 0000000..618692c --- /dev/null +++ b/src/output-contract.ts @@ -0,0 +1,66 @@ +import { sha256, stableJson } from "./canonical.js"; +import { SpendTreeError } from "./errors.js"; +import type { OutputContractEvidence, StoredResponse } from "./types.js"; + +export const OUTPUT_CONTRACT_SCHEMA = "spendtree.required-json-paths.v1" as const; + +export function validateOutputContract( + response: StoredResponse, + requiredJsonPaths: string[], + context: Record, +): OutputContractEvidence | undefined { + if (requiredJsonPaths.length === 0) return undefined; + const digest = sha256(stableJson({ schema: OUTPUT_CONTRACT_SCHEMA, requiredJsonPaths })); + const failure = (message: string, details: Record = {}): never => { + throw new SpendTreeError("OUTPUT_INVALID", message, { + ...context, + outputContractSchema: OUTPUT_CONTRACT_SCHEMA, + outputContractDigest: digest, + requiredJsonPaths, + responseHash: response.responseHash, + ...details, + }); + }; + + if (response.status < 200 || response.status >= 300) { + failure("The response status does not satisfy the buyer-owned output contract", { + responseStatus: response.status, + }); + } + if (response.truncated) { + failure("The response was truncated before its output contract could be verified"); + } + + let value: unknown; + try { + value = JSON.parse(Buffer.from(response.bodyBase64, "base64").toString("utf8")); + } catch { + failure("The response is not valid JSON"); + } + + const missingPaths = requiredJsonPaths.filter((path) => !hasOwnPath(value, path)); + if (missingPaths.length > 0) { + failure("The response is missing buyer-required JSON paths", { missingPaths }); + } + return { + schema: OUTPUT_CONTRACT_SCHEMA, + digest, + requiredJsonPaths, + valid: true, + }; +} + +function hasOwnPath(value: unknown, path: string): boolean { + let current = value; + for (const segment of path.split(".")) { + if ( + current === null || + typeof current !== "object" || + !Object.prototype.hasOwnProperty.call(current, segment) + ) { + return false; + } + current = (current as Record)[segment]; + } + return true; +} diff --git a/src/payment.ts b/src/payment.ts index 9bdf979..cbed7a9 100644 --- a/src/payment.ts +++ b/src/payment.ts @@ -17,6 +17,7 @@ import { } from "./constants.js"; import { normalizeAddress, requestHash, sha256, stableJson, validatePaidFetchInput } from "./canonical.js"; import { SpendTreeError } from "./errors.js"; +import { validateOutputContract } from "./output-contract.js"; import { assertQuoteAllowed, assertRequestAllowed } from "./policy.js"; import { SpendStore } from "./store.js"; import type { @@ -93,7 +94,7 @@ export class PaymentEngine { request.idempotencyKey, frozenRequestHash, ); - if (existingReplay) return replayResult(existingReplay.payment, existingReplay.response); + if (existingReplay) return replayResult(existingReplay.payment, existingReplay.response, request); const requestInit = this.buildRequestInit(request); const initial = await this.safeFetch(request.url, requestInit, false); @@ -102,9 +103,14 @@ export class PaymentEngine { } if (initial.status !== 402) { const response = await readBoundedResponse(initial, this.maxResponseBytes); + const outputContract = validateOutputContract(response, request.requiredJsonPaths, { + paid: false, + settled: false, + }); return { paid: false, replayed: false, + ...(outputContract ? { outputContract } : {}), response: publicResponse(response), }; } @@ -119,7 +125,7 @@ export class PaymentEngine { }); if (reservation.kind === "replay") { - return replayResult(reservation.payment, reservation.response); + return replayResult(reservation.payment, reservation.response, request); } const restrictedRequired: PaymentRequired = { @@ -194,13 +200,21 @@ export class PaymentEngine { onchainVerified = false; verificationError = `Onchain verification pending or failed: ${errorMessage(error)}`; } - this.store.recordSettlement( + const settledPayment = this.store.recordSettlement( reservation.payment.id, { transaction: settlement.transaction, payer: settlement.payer ?? null }, response, onchainVerified, verificationError, ); + const outputContract = validateOutputContract(response, request.requiredJsonPaths, { + paymentId: reservation.payment.id, + paid: true, + settled: true, + paymentStatus: settledPayment.status, + onchainVerified: settledPayment.onchainVerified, + replayed: false, + }); return { paid: true, @@ -210,6 +224,7 @@ export class PaymentEngine { transaction: settlement.transaction, settlement, onchainVerified, + ...(outputContract ? { outputContract } : {}), response: publicResponse(response), }; } @@ -523,7 +538,16 @@ function publicResponse(response: StoredResponse): PaidFetchResult["response"] { function replayResult( payment: ReturnType, response: StoredResponse, + request: ValidatedRequest, ): PaidFetchResult { + const outputContract = validateOutputContract(response, request.requiredJsonPaths, { + paymentId: payment.id, + paid: true, + settled: true, + paymentStatus: payment.status, + onchainVerified: payment.onchainVerified, + replayed: true, + }); return { paid: true, replayed: true, @@ -531,6 +555,7 @@ function replayResult( amountAtomic: payment.amountAtomic, ...(payment.transaction ? { transaction: payment.transaction } : {}), onchainVerified: payment.onchainVerified, + ...(outputContract ? { outputContract } : {}), response: publicResponse(response), }; } diff --git a/src/types.ts b/src/types.ts index 53219a0..75914f8 100644 --- a/src/types.ts +++ b/src/types.ts @@ -59,6 +59,7 @@ export interface PaidFetchInput { method?: HttpMethod; body?: string; contentType?: "application/json" | "text/plain"; + requiredJsonPaths?: string[]; idempotencyKey: string; purpose: string; } @@ -68,10 +69,18 @@ export interface ValidatedRequest { method: HttpMethod; body?: string; contentType?: "application/json" | "text/plain"; + requiredJsonPaths: string[]; idempotencyKey: string; purpose: string; } +export interface OutputContractEvidence { + schema: "spendtree.required-json-paths.v1"; + digest: string; + requiredJsonPaths: string[]; + valid: true; +} + export interface ValidatedQuote { requirements: PaymentRequirements; amountAtomic: string; @@ -135,6 +144,7 @@ export interface PaidFetchResult { transaction?: string; settlement?: SettleResponse; onchainVerified?: boolean; + outputContract?: OutputContractEvidence; response: { status: number; contentType: string | null; diff --git a/test/output-contract.test.ts b/test/output-contract.test.ts new file mode 100644 index 0000000..8fd8300 --- /dev/null +++ b/test/output-contract.test.ts @@ -0,0 +1,67 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { sha256 } from "../src/canonical.js"; +import { SpendTreeError } from "../src/errors.js"; +import { validateOutputContract } from "../src/output-contract.js"; +import type { StoredResponse } from "../src/types.js"; + +test("output contracts require own nested JSON paths and return stable evidence", () => { + const response = stored('{"data":{"items":null},"provenance":{"source":"merchant"}}'); + const evidence = validateOutputContract(response, ["data.items", "provenance.source"], { + paid: true, + }); + assert.deepEqual(evidence, { + schema: "spendtree.required-json-paths.v1", + digest: evidence?.digest, + requiredJsonPaths: ["data.items", "provenance.source"], + valid: true, + }); + assert.match(evidence?.digest ?? "", /^[0-9a-f]{64}$/); + + const inherited = Object.create({ hidden: true }) as Record; + inherited.visible = true; + assert.throws( + () => validateOutputContract(stored(JSON.stringify(inherited)), ["hidden"], {}), + missingPath("hidden"), + ); +}); + +test("output contracts fail closed on malformed, truncated, and non-success responses", () => { + assert.throws( + () => validateOutputContract(stored("not-json"), ["data"], { paid: false }), + outputInvalid, + ); + assert.throws( + () => validateOutputContract({ ...stored('{"data":true}'), truncated: true }, ["data"], {}), + outputInvalid, + ); + assert.throws( + () => validateOutputContract({ ...stored('{"data":true}'), status: 500 }, ["data"], {}), + outputInvalid, + ); + assert.equal(validateOutputContract(stored("not-json"), [], {}), undefined); +}); + +function stored(body: string): StoredResponse { + return { + status: 200, + contentType: "application/json", + bodyBase64: Buffer.from(body).toString("base64"), + responseHash: sha256(body), + truncated: false, + }; +} + +function outputInvalid(error: unknown): boolean { + assert.ok(error instanceof SpendTreeError); + assert.equal(error.code, "OUTPUT_INVALID"); + return true; +} + +function missingPath(path: string): (error: unknown) => boolean { + return (error) => { + outputInvalid(error); + assert.deepEqual((error as SpendTreeError).details?.missingPaths, [path]); + return true; + }; +} diff --git a/test/payment.test.ts b/test/payment.test.ts index 0b7b2ba..d8e8229 100644 --- a/test/payment.test.ts +++ b/test/payment.test.ts @@ -8,6 +8,7 @@ import { import { keccak256, toBytes, toHex } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { BASE_MAINNET, BASE_USDC } from "../src/constants.js"; +import { SpendTreeError } from "../src/errors.js"; import { assertBaseUsdcPaymentReceipt, createConstrainedSigner, @@ -70,6 +71,7 @@ test("real EIP-3009 signing path settles once and replays the stored response", url, idempotencyKey: "real-signature-once", purpose: "Acquire premium test data", + requiredJsonPaths: ["premium"], }; const result = await engine.paidFetch(root.capability, input); assert.equal(result.paid, true); @@ -80,6 +82,13 @@ test("real EIP-3009 signing path settles once and replays the stored response", assert.deepEqual(JSON.parse(Buffer.from(result.response.bodyBase64, "base64").toString()), { premium: true, }); + assert.deepEqual(result.outputContract, { + schema: "spendtree.required-json-paths.v1", + digest: result.outputContract?.digest, + requiredJsonPaths: ["premium"], + valid: true, + }); + assert.match(result.outputContract?.digest ?? "", /^[0-9a-f]{64}$/); assert.equal(store.summary(root.capability).mandate.spentAtomic, "40"); const replay = await engine.paidFetch(root.capability, input); @@ -91,6 +100,85 @@ test("real EIP-3009 signing path settles once and replays the stored response", } }); +test("invalid settled output is preserved and replayed without another payment", async () => { + const store = new SpendStore(":memory:"); + try { + const root = store.createRoot(rootPolicy()); + const url = "https://api.example.com/paid/data"; + const account = privateKeyToAccount(TEST_PRIVATE_KEY as `0x${string}`); + let calls = 0; + let paidCalls = 0; + const fetchImpl: typeof fetch = async (_input, init) => { + calls += 1; + if (!new Headers(init?.headers).has("PAYMENT-SIGNATURE")) { + return new Response("", { + status: 402, + headers: { "PAYMENT-REQUIRED": encodePaymentRequiredHeader(paymentRequired(url)) }, + }); + } + paidCalls += 1; + return new Response('{"data":{"items":[]}}', { + status: 200, + headers: { + "Content-Type": "application/json", + "PAYMENT-RESPONSE": encodePaymentResponseHeader({ + success: true, + payer: account.address, + transaction: `0x${"56".repeat(32)}`, + network: BASE_MAINNET, + amount: "40", + }), + }, + }); + }; + const engine = new PaymentEngine({ + store, + privateKey: TEST_PRIVATE_KEY, + fetchImpl, + receiptVerifier: async () => {}, + }); + const input = { + url, + idempotencyKey: "invalid-delivery-once", + purpose: "Acquire a result with provenance", + requiredJsonPaths: ["data.items", "provenance.source"], + }; + + await assert.rejects( + engine.paidFetch(root.capability, input), + (error: unknown) => { + assert.ok(error instanceof SpendTreeError); + assert.equal(error.code, "OUTPUT_INVALID"); + assert.equal(error.details?.paid, true); + assert.equal(error.details?.settled, true); + assert.equal(error.details?.paymentStatus, "settled"); + assert.deepEqual(error.details?.missingPaths, ["provenance.source"]); + assert.match(String(error.details?.responseHash), /^[0-9a-f]{64}$/); + return true; + }, + ); + const payment = store.summary(root.capability).recentPayments[0]; + assert.equal(payment?.status, "settled"); + assert.equal(payment?.responseBodyBase64, Buffer.from('{"data":{"items":[]}}').toString("base64")); + assert.equal(store.summary(root.capability).mandate.spentAtomic, "40"); + + await assert.rejects( + engine.paidFetch(root.capability, input), + (error: unknown) => { + assert.ok(error instanceof SpendTreeError); + assert.equal(error.code, "OUTPUT_INVALID"); + assert.equal(error.details?.replayed, true); + assert.deepEqual(error.details?.missingPaths, ["provenance.source"]); + return true; + }, + ); + assert.equal(calls, 2, "replay must not contact the merchant again"); + assert.equal(paidCalls, 1, "replay must not submit another payment signature"); + } finally { + store.close(); + } +}); + test("missing settlement proof leaves committed budget indeterminate and never re-signs", async () => { const store = new SpendStore(":memory:"); try { diff --git a/test/policy.test.ts b/test/policy.test.ts index c5d8dee..ec7eda3 100644 --- a/test/policy.test.ts +++ b/test/policy.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { validatePaidFetchInput } from "../src/canonical.js"; +import { requestHash, sha256, stableJson, validatePaidFetchInput } from "../src/canonical.js"; import { assertRequestAllowed } from "../src/policy.js"; import { SpendStore } from "../src/store.js"; import { OTHER_PAY_TO, PAY_TO, future, rootPolicy } from "./helpers.js"; @@ -53,6 +53,45 @@ test("delegation can narrow but cannot broaden parent authority", () => { store.close(); } }); + +test("required JSON paths are canonical, bounded, safe, and request-bound", () => { + const base = { + url: "https://api.example.com/paid/search?q=x", + method: "GET" as const, + idempotencyKey: "contract-request-1", + purpose: "Test output contract", + }; + const withoutContract = validatePaidFetchInput(base); + const legacyHash = sha256( + stableJson({ + url: withoutContract.url.href, + method: withoutContract.method, + bodyHash: sha256(""), + contentType: null, + }), + ); + assert.equal(requestHash(withoutContract), legacyHash, "empty contracts preserve the v0 request identity"); + + const withContract = validatePaidFetchInput({ + ...base, + requiredJsonPaths: [" provenance.source ", "data.items", "data.items"], + }); + assert.deepEqual(withContract.requiredJsonPaths, ["data.items", "provenance.source"]); + assert.notEqual(requestHash(withContract), legacyHash); + assert.equal( + requestHash(withContract), + requestHash(validatePaidFetchInput({ ...base, requiredJsonPaths: ["data.items", "provenance.source"] })), + "path order and duplicates do not change the request identity", + ); + + for (const path of ["data..items", "data.__proto__.value", "a.b.c.d.e.f.g.h.i", "data.items[*]"]) { + assert.throws(() => validatePaidFetchInput({ ...base, requiredJsonPaths: [path] }), /safe dot-separated/); + } + assert.throws( + () => validatePaidFetchInput({ ...base, requiredJsonPaths: Array.from({ length: 17 }, (_, i) => `p${i}`) }), + /at most 16/, + ); +}); test("request policy is exact-origin, method, and path scoped", () => { const store = new SpendStore(":memory:"); try { From 782ee7704c3e9fd58b70efce227b469a53b22a9a Mon Sep 17 00:00:00 2001 From: epistemedeus Date: Sun, 30 Aug 2026 01:58:44 -0700 Subject: [PATCH 2/2] test: make flat suite runnable with npm --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 96cb640..80883d0 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,7 @@ "dev": "tsx src/cli.ts", "mcp": "tsx src/mcp.ts", "prepare": "npm run build", - "test": "tsx --test test/**/*.test.ts", + "test": "tsx --test test/*.test.ts", "typecheck": "tsc -p tsconfig.json --noEmit", "check": "npm run typecheck && npm test" },