Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
59 changes: 53 additions & 6 deletions src/canonical.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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,
};
Expand All @@ -96,16 +102,57 @@ export function validatePaidFetchInput(input: PaidFetchInput): ValidatedRequest
}

export function requestHash(request: ValidatedRequest): string {
const identity: Record<string, unknown> = {
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<string>();
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;
Expand Down
8 changes: 6 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ switch (command) {
" spendtree init <policy.json> [--ttl-minutes <minutes>]",
" spendtree daemon",
" spendtree address",
' spendtree pay <https-url> <idempotency-key> "<purpose>" [--method GET|POST] [--json \'{...}\'|--text "..."]',
' spendtree pay <https-url> <idempotency-key> "<purpose>" [--method GET|POST] [--json \'{...}\'|--text "..."] [--require-path <path>]...',
" spendtree summary",
"",
].join("\n"),
Expand Down Expand Up @@ -95,7 +95,7 @@ switch (command) {
const input = parsePayArgs(process.argv.slice(3));
if (!input) {
usage(
'SPENDTREE_CAPABILITY=... spendtree pay <https-url> <idempotency-key> "<purpose>" [--method GET|POST] [--json \'{...}\'|--text "..."]',
'SPENDTREE_CAPABILITY=... spendtree pay <https-url> <idempotency-key> "<purpose>" [--method GET|POST] [--json \'{...}\'|--text "..."] [--require-path <path>]...',
);
}
const result = await callDaemon<PaidFetchResult>(socketPath, capability, "/v1/paid-fetch", input);
Expand All @@ -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];
Expand All @@ -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}`);
}
Expand All @@ -154,6 +157,7 @@ function parsePayArgs(args: string[]): PaidFetchInput | null {
...(method ? { method } : {}),
...(body === undefined ? {} : { body }),
...(contentType === undefined ? {} : { contentType }),
...(requiredJsonPaths.length === 0 ? {} : { requiredJsonPaths }),
};
}

Expand Down
7 changes: 7 additions & 0 deletions src/daemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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(),
});
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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:
Expand Down
1 change: 1 addition & 0 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type SpendTreeErrorCode =
| "DUPLICATE_PAYMENT"
| "PAYMENT_REQUIRED_INVALID"
| "PAYMENT_INDETERMINATE"
| "OUTPUT_INVALID"
| "UPSTREAM_ERROR"
| "NOT_FOUND"
| "INTERNAL_ERROR";
Expand Down
5 changes: 5 additions & 0 deletions src/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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),
},
Expand Down
66 changes: 66 additions & 0 deletions src/output-contract.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>,
): OutputContractEvidence | undefined {
if (requiredJsonPaths.length === 0) return undefined;
const digest = sha256(stableJson({ schema: OUTPUT_CONTRACT_SCHEMA, requiredJsonPaths }));
const failure = (message: string, details: Record<string, unknown> = {}): 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<string, unknown>)[segment];
}
return true;
}
Loading