@x402-guard/policy
v0.1.1
Published
The missing @x402/policy: a persistent spending-policy layer for x402 AI agents. Wires a budget/allowlist/quote-sanity engine into x402's own registerPolicy() + onBeforePaymentCreation() sockets, settling on Hedera. One line: createGuardedFetch(config, le
Downloads
39
Maintainers
Readme
@x402-guard/policy
The missing @x402/policy. x402's client libraries will sign any payment they're handed — the v2 wrapFetchWithPayment(fetch, client) removed v1's maxValue cap, and the replacement extension point (registerPolicy()) is a stateless pure function with no budget, memory, or history. This package fills that socket: a persistent spending-policy layer (budgets, allowlists, quote-sanity, loop detection, rate limits) wired into x402's own hooks, settling on Hedera.
Part of x402-guard — the trust layer between an agent and its money.
Install
npm install @x402-guard/policy @x402-guard/coreUse — one line
createGuardedFetch returns a drop-in fetch that pays x402 resources automatically but aborts before signing when a policy rule fires:
import { createGuardedFetch } from "@x402-guard/policy";
import { Ledger } from "@x402-guard/core";
const config = {
version: 1, network: "hedera:testnet", asset: "hbar", onUnknown: "deny",
budgets: [{ id: "daily", window: "24h", limit: "5.0" }],
rules: { maxSinglePayment: "0.5", allowlist: { recipients: ["0.0.9693047"] } },
};
const fetch = createGuardedFetch(config, new Ledger("./spend.sqlite"), {
accountId: process.env.AGENT_ACCOUNT_ID, // your agent Hedera account (0.0.x)
privateKey: process.env.AGENT_PRIVATE_KEY, // agent ECDSA key — signs payments
});
const res = await fetch("https://data.example.com/quote"); // paid if 402; denied if over budget/off-allowlistThe third argument is the agent's signing credentials. Omit it to fall back to AGENT_ACCOUNT_ID + AGENT_PRIVATE_KEY in the environment.
A blocked payment never signs — the promise resolves to a 403 with { denied, reason, ruleId }, and the spend is recorded to the persistent ledger so budgets survive restarts.
Also exported
guardPolicy(config)→ aPaymentPolicyforx402Client.registerPolicy()(stateless filter).guardHook(config, ledger)→ aBeforePaymentCreationHookforonBeforePaymentCreation()(stateful, ledger-backed enforcement).
What the config supports
Per-window budgets (global / origin / recipient scope), maxSinglePayment, origin/recipient allowlists, quoteSanity (reject a 402 quoting far more than advertised), loopDetection, rateLimit (calls/window), and allowedHours (UTC time-of-day). Money is integer base units end to end — never floats.
For the full gateway (HCS tamper-evident audit, Mirror settlement re-confirmation, facilitator quarantine, aggregating MCP proxy, macOS app), see the x402-guard repo.
License
Apache-2.0
