Skip to content
Back to search

cbp-guard

Pre-sign x402 hook and stdio MCP server that checks a payTo with CertBeforePay before signing

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/teddytigers--cbp-guard/badge.svg)](/listings/teddytigers--cbp-guard)

HTML

<a href="/listings/teddytigers--cbp-guard"><img src="/api/listings/teddytigers--cbp-guard/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 181 lines
  1. # cbp-guard
  2. cbp-guard checks the wallet your AI agent is about to pay, before it signs, and stops payments to known scam or lookalike wallets. Each wallet check is $0.01 in USDC on Base via x402.
  3. ```bash
  4. npm install cbp-guard # library: the pre-sign hook
  5. npx cbp-guard mcp # stdio MCP server (needs CBP_GUARD_PRIVATE_KEY)
  6. ```
  7. It has two parts:
  8. - **A pre-sign hook** for the official x402 v2 client (`@x402/core`, used by `@x402/fetch` and `@x402/axios`). It runs in `onBeforePaymentCreation`: before your agent signs a 402 payment, it asks [CertBeforePay](https://certbeforepay.com) `POST /v1/wallet/check` about the `payTo`.
  9. - **A stdio MCP server** (`npx cbp-guard mcp`) with the tools `wallet_check`, `gate` and `peer_challenge`.
  10. ## What the guard does
  11. | CertBeforePay answer | Default | Option |
  12. | ------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------- | ---------------------------------------- |
  13. | `block` | refuse; throws `cbp-guard: block (<reason>)`, nothing is signed | none (always refused) |
  14. | `caution` (including `address_poisoning_lookalike`) | refuse | `onCaution: "block" \| "allow" \| "ask"` |
  15. | `clear` | allow the payment | |
  16. | no usable answer (CertBeforePay down, timeout, `503` stale/misconfigured list, the check's own payment failed, malformed answer, daily budget reached) | refuse | `failMode: "block" \| "allow"` |
  17. The defaults are fail-closed. Allowing a caution or a missing answer has to be switched on explicitly.
  18. A **lookalike** is an address that starts and ends like a known address (same first 4 and last 4 hex characters) but is a different address, a common address-poisoning trick. CertBeforePay compares against well-known addresses (such as USDC on Base) and against the addresses you pass as `known_recipients` (your address book or the payTo you used last time, up to 50). When the guard stops a payment, the error carries the verdict, the reasons and, for a lookalike, the matched address, its label and a note.
  19. The wallet check is a risk signal (scam/phishing lists and lookalikes), not an OFAC or sanctions screen, and not a guarantee. CertBeforePay itself never stops a payment; only this guard does, and only if you install it.
  20. ## Use the hook
  21. ```ts
  22. import { x402Client } from "@x402/core/client";
  23. import { wrapFetchWithPayment } from "@x402/fetch";
  24. import { ExactEvmScheme, toClientEvmSigner } from "@x402/evm";
  25. import { privateKeyToAccount } from "viem/accounts";
  26. import { withCbpGuard } from "cbp-guard";
  27. const account = privateKeyToAccount(process.env.MY_AGENT_KEY as `0x${string}`);
  28. const client = new x402Client().register("eip155:8453", new ExactEvmScheme(toClientEvmSigner(account)));
  29. const guard = withCbpGuard(client, {
  30. // all optional; these are the defaults unless noted
  31. onCaution: "block", // "block" | "allow" | "ask" (with ask: async (decision) => boolean)
  32. failMode: "block", // "block" | "allow"
  33. knownRecipients: [], // up to 50 0x addresses, or a function returning them
  34. minAmountUsd: 0, // skip the check for USDC payments below this amount (0 = check all)
  35. dailyBudgetUsd: 2.5, // USD cap on wallet-check spend per UTC day; Infinity removes the cap
  36. cacheTtlMs: 5 * 60_000, // cache real verdicts per address; max 15 minutes; 0 disables
  37. baseUrl: "https://certbeforepay.com",
  38. onDecision: (d) => console.log(d.action, d.verdict, d.reasons),
  39. });
  40. const fetchWithPay = wrapFetchWithPayment(fetch, client);
  41. await fetchWithPay("https://seller.example/paid"); // throws "... cbp-guard: block (...)" when stopped
  42. ```
  43. - Each wallet check is paid by x402 from **your own wallet** (the client you pass in), at $0.01. The guard checks CertBeforePay's 402 before signing: the payTo must be CertBeforePay's, the payment must be USDC on Base (`eip155:8453`), and the amount must not exceed $0.01 (gate $0.02, peer challenge $0.01; override with `maxPriceAtomic`).
  44. - Payments to CertBeforePay's own payTo (`0xfcae7e8373264acf7f7d00e9d0171671dcdb095c`) are never checked, so you do not pay us to check us (and the check's own payment does not loop).
  45. - Only real verdicts are cached, for minutes. Failures such as a `503` are never cached.
  46. - Every request to CertBeforePay carries `User-Agent: cbp-guard/<version>`.
  47. - The guard sends CertBeforePay the payTo, the chain, your `known_recipients` (if any) and the seller's resource URL without its query string or fragment (origin and path only).
  48. - `baseUrl` must use https. Plain http is accepted only for `localhost`, `127.0.0.1` and `[::1]`, or for any host if you set `allowInsecureHttp: true` (for local testing only).
  49. - Each request to CertBeforePay has one deadline (15 seconds by default) that covers reading the whole answer, and answers over 64 KB are rejected. Either way there is no usable answer, so `failMode` applies.
  50. - Legacy x402 v1 packages and wrapping a viem account (transfers, approvals) are not supported in this release.
  51. ### Daily budget
  52. By default the guard spends at most $2.50 in USDC per UTC day on wallet checks. The amount is reserved before each check's payment is signed, so checks running in parallel cannot go over the cap, and a signed payment counts even if the answer that comes back is unusable. When the budget is used up, the guard treats the check as having no usable answer, so with the default `failMode: "block"` payments are refused until the next UTC day. Cached verdicts and skipped payments do not count against the budget. Set `dailyBudgetUsd` to raise or lower the cap, or to `Infinity` to remove it. The budget is kept in memory per guard, so it starts again when your process restarts.
  53. ## Examples
  54. ### @x402/fetch
  55. ```ts
  56. import { x402Client } from "@x402/core/client";
  57. import { ExactEvmScheme, toClientEvmSigner } from "@x402/evm";
  58. import { wrapFetchWithPayment } from "@x402/fetch";
  59. import { withCbpGuard } from "cbp-guard";
  60. import { privateKeyToAccount } from "viem/accounts";
  61. const account = privateKeyToAccount(process.env.MY_AGENT_KEY as `0x${string}`);
  62. const client = new x402Client().register("eip155:8453", new ExactEvmScheme(toClientEvmSigner(account)));
  63. withCbpGuard(client, { knownRecipients: ["0x1111111111111111111111111111111111111111"] });
  64. const fetchWithPay = wrapFetchWithPayment(fetch, client);
  65. try {
  66. const res = await fetchWithPay("https://seller.example/paid");
  67. console.log(res.status, await res.text());
  68. } catch (err) {
  69. console.error((err as Error).message); // "... cbp-guard: block (...)" when the guard stopped it
  70. }
  71. ```
  72. ### Coinbase AgentKit
  73. AgentKit's built-in `x402ActionProvider` builds its own x402 client inside each action and has no hook option, so cbp-guard cannot attach to it. Instead, add a custom action that builds a guarded client from the AgentKit wallet, and use it in place of the built-in x402 actions.
  74. ```ts
  75. import { AgentKit, CdpEvmWalletProvider, customActionProvider, type EvmWalletProvider } from "@coinbase/agentkit";
  76. import { x402Client } from "@x402/core/client";
  77. import { ExactEvmScheme, toClientEvmSigner } from "@x402/evm";
  78. import { wrapFetchWithPayment } from "@x402/fetch";
  79. import { withCbpGuard } from "cbp-guard";
  80. import { z } from "zod";
  81. // Reads CDP_API_KEY_ID, CDP_API_KEY_SECRET and CDP_WALLET_SECRET from the environment.
  82. const walletProvider = await CdpEvmWalletProvider.configureWithWallet({ networkId: "base-mainnet" });
  83. const guardedPaidFetch = customActionProvider<EvmWalletProvider>({
  84. name: "guarded_paid_fetch",
  85. description: "Fetch a URL and pay its x402 402 only after cbp-guard checks the payTo.",
  86. schema: z.object({ url: z.string().url() }),
  87. invoke: async (wallet, args: { url: string }) => {
  88. const client = new x402Client().register("eip155:8453", new ExactEvmScheme(toClientEvmSigner(wallet.toSigner())));
  89. withCbpGuard(client);
  90. try {
  91. const res = await wrapFetchWithPayment(fetch, client)(args.url);
  92. return `${res.status} ${await res.text()}`;
  93. } catch (err) {
  94. return `Payment refused: ${(err as Error).message}`;
  95. }
  96. },
  97. });
  98. const agentkit = await AgentKit.from({ walletProvider, actionProviders: [guardedPaidFetch] });
  99. ```
  100. This example was type-checked against `@coinbase/agentkit` 0.10.4 and `@x402/*` 2.32.0 (zod 3, as AgentKit uses). It has not been run against a live CDP wallet.
  101. ## Use the MCP server
  102. ```bash
  103. CBP_GUARD_PRIVATE_KEY=0x... npx cbp-guard mcp
  104. ```
  105. Example client config:
  106. ```json
  107. {
  108. "mcpServers": {
  109. "cbp-guard": {
  110. "command": "npx",
  111. "args": ["-y", "cbp-guard", "mcp"],
  112. "env": { "CBP_GUARD_PRIVATE_KEY": "<your low-balance wallet key>" }
  113. }
  114. }
  115. }
  116. ```
  117. | Tool | Endpoint | Price |
  118. | ---------------------------------------------------------------------------- | ------------------------- | ----- |
  119. | `wallet_check` (`address`, optional `chain`, `resource`, `known_recipients`) | `POST /v1/wallet/check` | $0.01 |
  120. | `gate` (`skill`, `skills`, `mcp` or `content`) | `POST /v1/gate` | $0.02 |
  121. | `peer_challenge` (`certificate`, optional `min_score`, `require_tier`) | `POST /v1/peer/challenge` | $0.01 |
  122. - `CBP_GUARD_PRIVATE_KEY` (required): the private key of **your** wallet that pays for each call via x402 (USDC on Base). The server refuses to start without it. Use a dedicated low-balance wallet. The key is read from the environment only; it is never logged, returned or written to disk, and neither is any payment signature. If the key is invalid, the error says so without repeating it.
  123. - `CBP_GUARD_BASE_URL` (optional): default `https://certbeforepay.com`. It must use https; plain http is accepted only for `localhost`, `127.0.0.1` and `[::1]` (the MCP server has no `allowInsecureHttp` setting).
  124. - `CBP_GUARD_DAILY_BUDGET_USD` (optional): the most this server process spends per UTC day, default `2.50`. The price of each paid call is reserved against it before signing; when it is used up, tools return a `budget_exhausted` error and nothing is signed until the next UTC day. Set it to `Infinity` to remove the cap. It is kept in memory, so it starts again when the server restarts.
  125. - CertBeforePay's own `POST /mcp` is discovery-only; this stdio server is the one that performs paid calls.
  126. ### Use a dedicated low-balance wallet
  127. Use a dedicated wallet that holds only a small USDC balance for `CBP_GUARD_PRIVATE_KEY`, not your main wallet. Top it up as needed. If the key ever leaks, only that small balance is at risk.
  128. ## Development
  129. ```bash
  130. npm ci
  131. npm run typecheck && npm run lint && npm test && npm run build
  132. ```
  133. All CertBeforePay HTTP calls in the tests are mocked; the tests never reach production or spend USDC. Test keys are generated at run time and never funded.
  134. ## Releases
  135. Releases are published to npm with provenance from GitHub Actions.
  136. ## License
  137. MIT. This package contains no scam-list data; lists stay on the CertBeforePay server.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.