Agent Payments documentation
The README, architecture and security documents shipped in v1.0.0 of the package, published so you can judge the API before you buy. Markdown version.
Get Agent Payments · $49Source, tests and examples · v1.0.0 · one-time
Agent Payments (@softreuse/agent-payments) v1.0.0
Charge AI agents per request with HTTP 402. One paywall answers with both payment protocols agents use today, MPP (the "Payment" HTTP auth scheme Stripe co-authored, here with Shared Payment Tokens) and x402 v2 (stablecoins through a facilitator). It charges exactly once per payment, gives the money back or doesn't settle when your handler fails, and keeps a ledger in your Postgres. The other side is included too: a fetch that pays 402s for your agent, within a budget. About 1,700 lines of TypeScript with zero runtime dependencies.
- Node >= 20 · TypeScript strict · ESM · Web
Request/Response(Next.js, Hono, Bun, Deno) andnode:http/Express via an adapter - Wire formats follow draft-ryan-httpauth-payment, draft-stripe-charge and the x402 v2 spec. Checked against the reference SDKs
mppx0.15.0 and@x402/core2.28.0 (seetests/interop.test.ts) - PostgreSQL store included; any database through the
PaymentStoreinterface and its contract test suite
Why this exists
The protocol SDKs give you a 402 and a verify call. Running a paid endpoint in production needs the rest:
| What goes wrong | What this kit does |
|---|---|
| The agent's connection drops after it paid. It retries with the same credential. | The ledger replays the stored response: no second charge, no "already used" error. |
| Two copies of the paid request arrive at once. | A row lock lets one charge; the others get 409 and then the replay. |
| Your handler fails after the money moved. | MPP/Stripe: automatic refund. x402: settled only after your handler succeeds ("after" mode), so nothing is taken. |
| The process dies between charging and responding. | The charge is recorded first; the next attempt delivers without charging again (payment.recovered = true). |
| A challenge for a $0.01 route is replayed on a $5 route, or reused with another body. | Challenges are HMAC-bound to price, route, body digest and expiry, and are single-use. |
| A Shared Payment Token is presented on two challenges. | Proofs are single-use across the whole ledger (unique index). |
| Your agent loops on a paid API. | createPayingFetch enforces per-request and total limits, allowed origins and currency, and never pays an expired challenge. |
| "Did that agent pay for this?" | Every payment is a ledger row with method, payer, amount, provider reference and status; rows needing attention are one query away. |
Contents of this package
src/ the library
paywall.ts createPaywall: challenges, verification, ledger, charge/settle, refund, receipts
client.ts createPayingFetch: pays 402s with a budget
mpp.ts Payment auth scheme: challenges (HMAC binding), credentials, receipts, header parser
x402.ts x402 v2 headers and the facilitator client (verify / settle)
methods/stripe.ts MPP "stripe" charge method (Shared Payment Tokens → PaymentIntents, refunds)
methods/method.ts the MppMethod interface, to add other MPP methods
money.ts, encoding.ts exact decimal ↔ unit conversion, JCS (RFC 8785), base64url, digests
stores/ postgres.ts, memory.ts
adapters/node.ts node:http / Express
migrations/001_agent_payments.sql
tests/ 122 tests: both protocols end to end, failure paths, concurrency, crash recovery,
the paying client, interop vectors, store contract (Memory + Postgres), real HTTP
examples/
offline-demo/ runnable demo, no accounts needed (`npm run demo`)
next-app-router/ paywall setup, fixed and dynamic prices, ledger route, purge cron, a paying agent
node-http/ node:http server
docs/ARCHITECTURE.md how it works and why
docs/SECURITY.md threat model and deployment checklist
CHANGELOG.md · LICENSE.md
1. See it work (30 seconds)
npm install
npm run demo
A paid API and an agent with a $1 budget talk over in-process fetch; Stripe and the x402 facilitator are simulated. You see the 402 with both protocols, a $0.02 call paid over x402 (below Stripe's card minimum, so MPP isn't offered), a $0.75 call paid over MPP whose response is lost and replayed with a single PaymentIntent, a call refused by the budget, and the seller's ledger.
Run the tests: npm test. With DATABASE_URL=postgres://... npm test the Postgres store tests run too (they create and drop their own table).
2. Install into your project
Option A: copy the source (recommended). Copy src/ to e.g. src/lib/agent-payments/ and add migrations/001_agent_payments.sql to your migrations.
Option B: local package. npm run build, then npm install ../path/to/this/folder. Import from @softreuse/agent-payments.
3. Quick start (Next.js + Postgres)
// lib/paywall.ts
import { Pool } from "pg";
import { createPaywall, PostgresStore, stripeMethod, x402Facilitator } from "@softreuse/agent-payments";
export const paywall = createPaywall({
store: new PostgresStore(new Pool({ connectionString: process.env.DATABASE_URL })),
mpp: {
secret: process.env.MPP_SECRET!, // 32+ random bytes: openssl rand -base64 48
methods: [stripeMethod({ secretKey: process.env.STRIPE_SECRET_KEY!, networkId: process.env.STRIPE_PROFILE_ID! })],
},
x402: {
facilitator: x402Facilitator({ url: process.env.X402_FACILITATOR_URL! }),
accepts: [{ network: "eip155:8453", asset: process.env.USDC_ADDRESS!, payTo: process.env.PAY_TO!, decimals: 6, currency: "usd",
extra: { name: process.env.USDC_EIP712_NAME!, version: "2" } }],
},
});
// app/api/generate/route.ts
import { paywall } from "@/lib/paywall";
export const POST = paywall.protect(
{ price: { amount: "0.02", currency: "usd" }, description: "One text generation" },
async (request, { payment }) => {
const { prompt } = await request.json();
// runs once per payment; payment.key is a stable idempotency key for side effects
return Response.json({ text: await generate(prompt, payment.key) });
},
);
Configure only the protocol you want: mpp, x402, or both. Run the migration. More in examples/next-app-router/: dynamic prices from the body, an admin ledger route, a purge cron and a paying agent.
Stripe setup (MPP): create a Stripe profile and use its profile_… id as networkId (Stripe's MPP guide). Shared Payment Tokens are a Stripe preview feature: the method sends Stripe-Version: 2026-07-29.preview by default (override with apiVersion), and your account must have access. Stripe's documented SPT card minimum is 0.50 USD; cheaper prices are simply not offered over Stripe. Test with npx @stripe/link-cli mpp pay <url> in a sandbox.
x402 setup: pick a facilitator (Coinbase's, or another x402 v2 facilitator), use Base Sepolia (eip155:84532) and its test USDC while developing, and copy the token address and its EIP-712 domain name/version (sent in extra) from your facilitator's docs or /supported endpoint. Stripe can also receive stablecoins through MPP (Tempo); that method isn't included in v1.
4. What happens to a paid request
no credential ──────────────► 402 WWW-Authenticate: Payment … (one per MPP method) + PAYMENT-REQUIRED (x402)
credential ─► check binding ─► ledger lock ─► charge (MPP) / verify (x402) ─► your handler
│ │ │
invalid/expired replay | 409 | used chargeable (< 400 by default)?
→ 402 + new (no charge) yes → settle (x402 "after") → 200 + receipt, stored
challenges no → refund (MPP) / don't settle (x402) → your response
| Outcome | Status | Ledger |
|---|---|---|
| Paid and delivered | your status, with Payment-Receipt (MPP) or PAYMENT-RESPONSE (x402), Cache-Control: private |
completed, response stored for replay (24 h) |
| Same credential again, same request | stored response, Payment-Replayed: true |
unchanged |
| Same credential while the first is running | 409 + Retry-After |
unchanged |
| Challenge tampered, expired, used, or for another route/body/price | 402 + fresh challenges |
nothing written |
| Card declined / payment invalid | 402 verification-failed |
nothing kept: the challenge can be paid with another token |
| Stripe or facilitator down | 503 + Retry-After; retry with the same credential |
nothing kept |
| Handler fails, MPP | your response, no receipt | refunded (or, if the refund fails, kept redeliverable: the same credential retried gets the response without paying) |
| Handler fails, x402 "after" | your response | nothing kept: the same payment can be retried |
| x402 settlement fails | 402 with the failure in PAYMENT-RESPONSE; your response is withheld |
deleted, or settle_failed if a transaction was broadcast |
5. API
createPaywall(options): Paywall
paywall.charge(request, { price, description?, mimeType? }, handler) // → Response
paywall.protect({ price, ... }, handler) // → (request) => Response
paywall.payments.list({ status?, since?, needsAttention?, limit? }) // ledger rows
paywall.payments.get(key)
paywall.purge({ olderThanMs? }) // daily cron
handler(request, { payment: { protocol, method, amount, currency, payer, key, recovered } })
createPayingFetch({ budget, mpp?, x402?, allowedOrigins?, prefer?, retries?, onPayment? })
paidFetch(url, init) // like fetch; pays a 402 once, within the budget
paidFetch.spent() / .remaining()
stripeMethod({ secretKey, networkId, paymentMethodTypes?, currencies?, minimum?, apiVersion?, metadata? })
x402Facilitator({ url, headers?, verifyTimeoutMs?, settleTimeoutMs? })
PostgresStore(pool, { table? }) · MemoryStore() · toNodeHandler(fn)
price is a decimal string and a currency ({ amount: "0.05", currency: "usd" }), or a function of the request that returns one. Amounts are converted exactly; a method that can't represent a price (e.g. $0.001 in cents) is not offered rather than rounded.
Adding an MPP method. Implement MppMethod (request, proof, charge, optional refund) and add it to mpp.methods. The paywall does the binding, ledger, receipts and refund logic; your method only talks to its provider and must be idempotent on challengeId.
6. Configuration
| Option | Default | Notes |
|---|---|---|
mpp.secret |
required for MPP | ≥ 32 bytes. Rotating it voids unpaid challenges only. |
mpp.realm |
request host | Protection space in challenges. |
mpp.challengeTtlMs |
5 min | How long a challenge can be paid. |
x402.settle |
"after" |
"before" settles before your handler runs, for work you can't give away. |
chargeIf(status) |
status < 400 |
Which handler responses are paid for. |
leaseMs |
60 s | Must exceed your slowest handler. |
replayTtlMs / maxReplayBytes |
24 h / 1 MiB | Larger responses are delivered but not stored; a retry then gets 402. |
maxBodyBytes |
1 MiB | 413 above. |
excludeHeaders |
["set-cookie"] |
Never stored or replayed. |
onPaid(payment) |
none | After delivery; errors are logged, not surfaced. |
logger |
JSON lines | Never receives credentials, tokens or bodies. |
7. Troubleshooting
| Symptom | Cause / fix |
|---|---|
No configured payment method can charge … |
The price is below Stripe's minimum and no x402 token is configured, or the currency doesn't match any method. |
Every paid request gets invalid-challenge: price changed |
Your dynamic price isn't deterministic (time, randomness). It must depend only on the request. |
invalid-challenge: request body differs |
The client changed the body after receiving the challenge. Agents must resend the same bytes. |
| Stripe charge fails with an API version or unknown parameter error | SPTs need the preview API version and preview access on your account. |
| x402 payments rejected by the facilitator with signature errors | extra.name/extra.version must match the token's EIP-712 domain on that network. |
Rows in payments.list({ needsAttention: true }) |
Paid but not delivered (refund failed, crash) or an x402 settlement in doubt. Check the reference with your provider. |
409 responses |
A request with that credential is still running, or crashed and its lease (leaseMs) hasn't run out. |
Requirements and dependencies
Node 20+ (tested on 20, 22, 24 and 26). PostgreSQL 12+ for PostgresStore. Zero runtime dependencies. Development only: typescript, vitest, tsx, pg. You need a Stripe account with access to Shared Payment Tokens for MPP, and/or an x402 facilitator and a receiving wallet for x402.
Licence
Commercial, see LICENSE.md. Use it in unlimited projects you or your company own; don't redistribute it as a standalone product.
Architecture
The problem
HTTP 402 lets a server say "pay, then retry". Two protocols use it for agents: MPP (the Payment HTTP authentication scheme, an IETF Internet-Draft co-authored by Stripe and Tempo, with payment methods such as Stripe Shared Payment Tokens) and x402 (Coinbase's protocol, mostly stablecoins, verified and settled through a facilitator). Their SDKs produce challenges and verify payments. What they leave to you is the part that touches money twice: retries, concurrency, crashes, handler failures and bookkeeping. Agents retry a lot.
Flow
- Read the body (bounded) and compute the price for this exact request.
- Build the offers: for each MPP method, its request object for this price (or none if it can't charge it); for each x402 token, the exact amount in atomic units (or none if the price is finer than the token).
- No credential →
402with oneWWW-Authenticate: Paymentchallenge per MPP method and onePAYMENT-REQUIREDheader listing the x402 options. Nothing is stored: unpaid requests never write. - MPP credential → verify the stateless binding (below), then lock the ledger row keyed by the challenge id. x402 payload → check that its terms equal one of our offers, then lock the row keyed by the hash of the signed payload.
- Charge: MPP methods take the money now (Stripe confirms a PaymentIntent). x402 is verified now and settled after the handler ("after" mode) or before it ("before" mode). The charge is recorded on the row before the handler runs.
- Run the handler once. If the response is chargeable (default
< 400), attach the receipt, store the response for replay, and mark the rowcompleted. If not, refund (MPP) or don't settle (x402).
Challenge binding (MPP)
The challenge id is base64url(HMAC-SHA256(secret, realm|method|intent|request|expires|digest|opaque)), the stateless binding the draft recommends (§5.1.2.1.1); the reference SDK mppx computes the same value (checked with fixed vectors in tests/interop.test.ts). We fill the slots so that a challenge pays for exactly one thing:
requestis the JCS-encoded price for this method. On the paid retry the paywall recomputes it from the current request and compares: a cheaper route's challenge, an old price, or a different dynamic price fails.digestis the RFC 9530 SHA-256 of the request body, so a challenge issued for one body can't pay for another.opaquecarries the route (POST /v1/generate) and a 128-bit random nonce. The nonce makes every challenge id unique, which makes the id a single-use ledger key.expiresdefaults to 5 minutes. An expired challenge is refused before any charge, but a payment already taken stays deliverable and replayable after expiry.
No challenge is stored; the HMAC is the proof that we issued it. Rotating mpp.secret only invalidates unpaid challenges.
The ledger
One row per payment credential (agent_payments):
| Column | Role |
|---|---|
pay_key (PK) |
mpp:<challenge id> or x402:<sha-256 of the signed payload>. The row lock. |
proof (UNIQUE) |
The token inside the credential (stripe:spt_…). One token can't pay two challenges, even concurrently. |
fingerprint |
SHA-256 of method, path + query and body. A credential pays for one request; a different request with it is refused. |
charged, reference |
Money moved, and the provider's id for it (PaymentIntent, transaction hash). Written before the handler runs. |
lock_token, locked_until |
Lease. Only the holder can write; an abandoned lease is taken over by the same request after it expires. |
status |
processing → completed / refunded / settle_failed. |
response_*, replay_until |
The paid response, replayed byte for byte to retries. |
begin is a single INSERT … ON CONFLICT (pay_key) DO UPDATE … WHERE <lease expired and same request>, so exactly one concurrent request wins. release deletes an uncharged row (the credential can be presented again, e.g. after a provider outage) but keeps a charged one, unlocked, so a retry redelivers without charging. "Needs attention" is (charged AND status = 'processing') OR status = 'settle_failed': money taken without a delivered response, or a settlement in doubt.
Exactly once, case by case
- Retry after a lost response: same key, same fingerprint,
completed→ replay. - Concurrent duplicates: one wins the row; the rest get
409and, retried, the replay. - Provider outage during the charge: row released,
503. Stripe calls carry the idempotency key<challenge id>_<spt>, so a retry after an unknown outcome returns the same PaymentIntent instead of charging again (within Stripe's idempotency window, far longer than a challenge's life). - Crash after the charge: the row is
chargedwith its lease; afterleaseMsthe retry takes over, skips the charge and runs the handler withrecovered: true. The handler may have run before: usepayment.keyas the idempotency key for your side effects. - Crash before the charge was recorded: the takeover charges again with the same Stripe idempotency key, which returns the original PaymentIntent.
- Handler failure: MPP refunds (idempotency key
refund_<challenge id>), x402 "after" never settles. If a refund fails, the row stays charged and redeliverable and is logged aspayment.refund_failed.
x402 specifics
We send our requirements to the facilitator, never the client's: the client's accepted must match ours on scheme, network, amount, asset and pay-to, or it is refused before any facilitator call. Settlement failures withhold the handler's response (as the x402 HTTP transport specifies: 402 with the failure in PAYMENT-RESPONSE). A settlement_pending result, or a settle call whose outcome is unknown (timeout), is recorded as settle_failed with the transaction hash, flagged for attention, and not retried automatically, because blindly settling again could double-charge or fail confusingly. The request bodies we send to /verify and /settle are identical to those of @x402/core's HTTPFacilitatorClient.
The paying client
createPayingFetch reads both protocols from a 402, discards offers it can't pay (unknown method or token, other currency, expired, over maxPerRequest, or past maxTotal), picks the cheapest (tie-break prefer), reserves the amount synchronously (so concurrent calls can't overspend), asks your wallet callback for the credential, and resends. Network errors, 409 and 503 resend the same credential, which the paywall turns into a replay rather than a charge. A 402 reply to the paid request returns the reservation; anything else keeps it, because the server may have taken the money. Paid requests don't follow redirects, so a payment header only reaches the server that asked for it.
Choices and alternatives
- Why not just the protocol SDKs? Use them for what they're for:
mppxand@x402/coreare good at challenges, wallets and on-chain details. This kit is the production layer around the charge: the ledger, exactly-once delivery, refunds, failure handling, both protocols on one route, and budgets on the client. It has no dependencies, so it doesn't pin you to their release cycles. Wallet signing (EIP-3009, SPT issuance) stays with your provider's SDK, behind the client's callbacks. - Why a database row per payment and not stateless verification only? Stateless binding proves we issued a challenge; it can't prove it wasn't already used, or replay a response. Single use and replay need state.
- Why charge before the handler for MPP? Stripe confirms the PaymentIntent synchronously; doing it first means you never do paid work for a card that then declines. The refund covers the failure case.
- What about sessions, subscriptions and prepaid credits? MPP sessions and streaming payments are out of scope for v1. For prepaid credits, record them in
onPaidand check them before calling the paywall. - Interop checks. Before release, a paywall built from this package was exercised with
mppx0.15.0 (it parsed our challenges, verified their HMAC with the same secret, built a credential we accepted, and decoded our receipt) and with@x402/core2.28.0 (it decoded ourPAYMENT-REQUIREDandPAYMENT-RESPONSE, and our paywall accepted itsPAYMENT-SIGNATURE). Fixed vectors from those runs are intests/interop.test.ts.
Security notes
This package moves money on behalf of your API. These notes cover what it defends against, what it leaves to you, and how to deploy it.
Threat model
| Threat | Defence | Tested |
|---|---|---|
| Paying once, getting served many times (credential replay) | Ledger row per credential; a used credential replays the same response for the same request only, and is refused for any other request. | ✔ |
| Concurrent duplicates racing the charge | Primary-key lock in Postgres (INSERT … ON CONFLICT); exactly one request charges. Contract tests run 12 concurrent begins against a real database. |
✔ |
| Spending one Stripe Shared Payment Token twice | Unique proof column across all rows, including under concurrency. Stripe's own SPT limits apply as well. |
✔ |
| Forged or edited MPP challenge (cheaper price, other method, later expiry) | HMAC-SHA256 binding over all challenge fields with your secret (≥ 32 bytes), compared in constant time. | ✔ |
| Using a cheap route's challenge on an expensive route, or for another body | Route in the HMAC-bound opaque, body digest in digest, price recomputed and compared on every paid request. |
✔ |
| Paying an old price after a price change | Same: the current price must equal the challenged one. | ✔ |
x402 payload for different terms (lower amount, attacker's payTo, other network or token) |
The payload's accepted must equal one of our requirements; the facilitator is always called with our requirements. |
✔ |
| Charging for failed work | Refund (MPP) or no settlement (x402 "after") when the handler throws or returns a non-chargeable status. | ✔ |
| Double charge after a crash or provider timeout | Charge recorded before the handler; takeover skips charging; Stripe calls are idempotent on challenge + token. | ✔ |
| Ledger outage | Fail closed: 503, nothing charged. |
✔ |
| Agent overspending (client side) | Per-request and total budget, currency filter, allowed origins, expired challenges ignored, synchronous reservation under concurrency, no redirects on paid requests. | ✔ |
| Leaking credentials in logs | Logs carry route, amounts, statuses and a key prefix; never tokens, credentials, bodies or full keys. | ✔ |
| Header injection via descriptions | Challenge descriptions are reduced to printable ASCII and quoted. | ✔ |
| Oversized requests | Body read is capped (maxBodyBytes, default 1 MiB) before any work. |
✔ |
| SQL injection | All values are bound parameters; the table name is validated. | ✔ |
What it does NOT do
- It does not sign or hold funds. The client's wallet callbacks (SPT issuance, EIP-3009 signing) are yours, with your provider's SDK and key management.
- It does not verify on-chain payments itself. x402 verification and settlement are delegated to the facilitator you choose; you trust it as you would a payment processor.
- It does not authenticate users. A payment proves someone paid, not who they are. If a route also needs identity, authenticate before the paywall.
- It does not decide tax. Prices are what you set; if you sell to consumers in VAT/GST jurisdictions, decide with your adviser how agent payments are taxed and invoiced.
- It does not resolve disputed settlements automatically.
settle_failedrows and charged-but-undelivered rows are listed for you (needsAttention); resolve them with the provider reference. - Response replay stores paid responses (up to
maxReplayBytes, forreplayTtlMs) in your database. If responses are sensitive, lower the TTL or the size, or exclude headers.
Your deployment checklist
- Generate
mpp.secretwith ≥ 32 random bytes (openssl rand -base64 48), keep it in your secret manager, and don't reuse your Stripe key. - Use a restricted Stripe key limited to PaymentIntents (write) and Refunds (write).
- Test in a Stripe sandbox and on Base Sepolia before live mode; verify the token address and EIP-712 domain for your network.
- Run the migration; schedule
paywall.purge()daily; alert onpayment.refund_failed,payment.settle_pending,payment.settle_unknown,payment.finish_failedandpayment.store_unavailablelog lines, and checkpayments.list({ needsAttention: true }). - Set
leaseMsabove your slowest paid handler. - Use
payment.keyas the idempotency key for side effects in your handlers (a crash can re-run a handler without a new charge). - Validate input before calling the paywall, so malformed requests get
400without a402. - On the client: set
allowedOriginsand amaxTotalthat you are comfortable losing.
Dependencies
Zero runtime dependencies: Web Crypto, fetch, TextEncoder and atob/btoa only. npm audit --omit=dev is clean. Dev dependencies: typescript, vitest, tsx, pg.
Reporting a vulnerability
Email the address on the Softreuse support page with "security" in the subject. Please don't open public issues for vulnerabilities.
Get Agent Payments · $49Source, tests and examples · v1.0.0 · one-time