@agent402-dev/pay-server 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -77,6 +77,25 @@ export default {
77
77
  ```
78
78
  Rate stores: `memoryRateStore()` (default, tests), `fileRateStore(path)` from `@agent402-dev/pay-server/rates-file` (Node), or your own `RateStore` (for example a Cloudflare Durable Object; see the [Workers example](https://github.com/agent402-dev/agent402-toolkit/tree/main/packages/pay-server/examples/cloudflare-worker)). A Node example is in [`examples/node-server`](https://github.com/agent402-dev/agent402-toolkit/tree/main/packages/pay-server/examples/node-server).
79
79
 
80
+ ## Signed receipts (optional)
81
+ After a settled payment the gate can add an `X-Agent402-Receipt` header: a small JSON record, signed with Ed25519, that binds the request (method, path, body hash), the hash of the response body you delivered, and the payment (network, asset, amount, recipient, transaction). Buyers can keep it as evidence for disputes and settlement reports; `@agent402-dev/pay-mcp` checks it automatically.
82
+
83
+ ```ts
84
+ import { receiptSignerFromBytes } from '@agent402-dev/pay-server';
85
+
86
+ const signer = await receiptSignerFromBytes(receiptKeyBytes); // 64-byte Solana CLI key file, or a 32-byte seed
87
+ const gate = createPaymentGate({ /* ... */ receipts: { signer } });
88
+ ```
89
+ - Use a key made only for receipts (for example `solana-keygen new -o receipt-key.json`), never the key of your receiving wallet. The gate never needs the receiving wallet's key.
90
+ - Publish the receipt key's public key (`signer.publicKey`) so buyers can tell that receipts come from you.
91
+ - If signing fails, the paid resource is still delivered, without a receipt.
92
+
93
+ ## Data
94
+ - No telemetry and no analytics.
95
+ - It contacts only the facilitators you configure (`/supported`, `/verify`, `/settle`) and the RPC you pass to `rpcChain` (settlement checks, receiving token accounts, pool prices for the PREQ rate).
96
+ - Replay protection keeps payment identifiers in the ledger you configure (in memory by default). It stores no other buyer data.
97
+ - It writes nothing to the console except the A402 (v1) deprecation warning when you enable A402.
98
+
80
99
  ## License
81
100
  Apache-2.0. See [LICENSE](https://github.com/agent402-dev/agent402-toolkit/blob/main/LICENSE) and [NOTICE](https://github.com/agent402-dev/agent402-toolkit/blob/main/NOTICE).
82
101
 
package/dist/gate.d.ts CHANGED
@@ -2,6 +2,7 @@ import { type FacilitatorClient } from '@x402/core/server';
2
2
  import type { PaymentRequirements } from '@x402/core/types';
3
3
  import { type ChainReader } from './chain.js';
4
4
  import { type DailyRate } from './pricing.js';
5
+ import { type ReceiptSigner } from './receipt.js';
5
6
  import { type Asset, type X402Ledger } from './x402.js';
6
7
  /** A402 is deprecated (v1) */
7
8
  export type AssetSymbol = 'USDC' | 'PREQ' | 'A402';
@@ -82,6 +83,13 @@ export interface GateConfig {
82
83
  now?: () => number;
83
84
  /** Retry intervals for the on-chain recheck (default 1, 2, 4 s) */
84
85
  confirmDelaysMs?: number[];
86
+ /**
87
+ * Signed receipts (optional): after a settled payment, adds the X-Agent402-Receipt header signed with this key.
88
+ * Use a key made only for receipts (receiptSignerFromBytes), never the receiving wallet's key
89
+ */
90
+ receipts?: {
91
+ signer: ReceiptSigner;
92
+ };
85
93
  }
86
94
  export interface ReceivingAccount {
87
95
  asset: AssetSymbol;
package/dist/gate.js CHANGED
@@ -9,6 +9,7 @@ import { decodePaymentSignatureHeader, encodePaymentRequiredHeader } from '@x402
9
9
  import { HTTPFacilitatorClient } from '@x402/core/server';
10
10
  import { ataOf } from './chain.js';
11
11
  import { tokenAmountFor } from './pricing.js';
12
+ import { RECEIPT_HEADER, sha256Hex, signReceipt } from './receipt.js';
12
13
  import { A402_DEPRECATION_WARNING, PREQ_DECIMALS, PREQ_MAINNET_MINT, PREQ_TOKEN_PROGRAM } from './preq.js';
13
14
  import { buildRequirements, chooseFacilitator, memoryX402Ledger, paymentResponseHeader, settleVerified, verifyPaymentHeader, } from './x402.js';
14
15
  /**
@@ -199,6 +200,8 @@ export function createPaymentGate(c) {
199
200
  }
200
201
  // 2) Handler (time limit). No settlement on failure, timeout, or a 4xx/5xx response
201
202
  const payment = v.payment;
203
+ // Copy of the request for the receipt's request body hash (the handler may read the original body)
204
+ const reqCopy = c.receipts && req.body ? req.clone() : null;
202
205
  const info = { asset: payment.accepted.asset, amount: payment.accepted.amount, payTo: payment.accepted.payTo, network: payment.accepted.network };
203
206
  let res;
204
207
  let timer;
@@ -234,7 +237,24 @@ export function createPaymentGate(c) {
234
237
  h.set('payment-response', paymentResponseHeader(s.settlement));
235
238
  h.set('x-payment-confirmation', s.confirmation);
236
239
  h.set('access-control-expose-headers', 'PAYMENT-RESPONSE, X-Payment-Confirmation');
237
- return new Response(res.body, { status: res.status, headers: h });
240
+ if (!c.receipts)
241
+ return new Response(res.body, { status: res.status, headers: h });
242
+ const body = await res.arrayBuffer();
243
+ try {
244
+ const reqBody = reqCopy ? await reqCopy.arrayBuffer() : null;
245
+ const token = await signReceipt(c.receipts.signer, {
246
+ issuedAt: new Date(now()).toISOString(),
247
+ request: { method: req.method, path: `${url.pathname}${url.search}`, bodySha256: reqBody && reqBody.byteLength ? await sha256Hex(reqBody) : null },
248
+ response: { status: res.status, bodySha256: await sha256Hex(body) },
249
+ payment: { network: info.network, asset: info.asset, amount: info.amount, payTo: info.payTo, transaction: s.settlement.transaction || null },
250
+ });
251
+ h.set(RECEIPT_HEADER, token);
252
+ h.set('access-control-expose-headers', 'PAYMENT-RESPONSE, X-Payment-Confirmation, X-Agent402-Receipt');
253
+ }
254
+ catch {
255
+ // Receipts are optional: the paid resource is still delivered without one
256
+ }
257
+ return new Response(body, { status: res.status, headers: h });
238
258
  };
239
259
  }
240
260
  return { withPayment, quote, checkReceivingAccounts };
package/dist/index.d.ts CHANGED
@@ -3,4 +3,5 @@ export { PREQ_MAINNET_MINT, PREQ_MAINNET_POOL, A402_DEPRECATION_WARNING } from '
3
3
  export { rpcChain, receivedBy, type ChainReader, type ChainTx, type AccountFetcher } from './chain.js';
4
4
  export { createRateBook, memoryRateStore, type RateBook, type RateStore } from './rates.js';
5
5
  export { DEFAULT_GUARDS, fixRate, samplePrice, tokenAmountFor, PREQ_POOL_TARGET, A402_POOL_TARGET, type DailyRate, type PoolTarget, type PriceSample, type RateGuards, } from './pricing.js';
6
+ export { receiptSignerFromBytes, signReceipt, RECEIPT_HEADER, type Receipt, type ReceiptSigner } from './receipt.js';
6
7
  export { memoryX402Ledger, ledgerClaim, SETTLE_UNKNOWN_EXPIRY_MS, type X402Ledger, type LedgerEntry, type Asset } from './x402.js';
package/dist/index.js CHANGED
@@ -5,4 +5,5 @@ export { PREQ_MAINNET_MINT, PREQ_MAINNET_POOL, A402_DEPRECATION_WARNING } from '
5
5
  export { rpcChain, receivedBy } from './chain.js';
6
6
  export { createRateBook, memoryRateStore } from './rates.js';
7
7
  export { DEFAULT_GUARDS, fixRate, samplePrice, tokenAmountFor, PREQ_POOL_TARGET, A402_POOL_TARGET, } from './pricing.js';
8
+ export { receiptSignerFromBytes, signReceipt, RECEIPT_HEADER } from './receipt.js';
8
9
  export { memoryX402Ledger, ledgerClaim, SETTLE_UNKNOWN_EXPIRY_MS } from './x402.js';
@@ -0,0 +1,37 @@
1
+ export declare const RECEIPT_HEADER = "x-agent402-receipt";
2
+ export declare const RECEIPT_KIND = "agent402.x402-receipt";
3
+ export interface Receipt {
4
+ v: 1;
5
+ kind: typeof RECEIPT_KIND;
6
+ issuedAt: string;
7
+ /** path is the URL path and query as the server received it */
8
+ request: {
9
+ method: string;
10
+ path: string;
11
+ bodySha256: string | null;
12
+ };
13
+ response: {
14
+ status: number;
15
+ bodySha256: string;
16
+ };
17
+ payment: {
18
+ network: string;
19
+ asset: string;
20
+ amount: string;
21
+ payTo: string;
22
+ transaction: string | null;
23
+ };
24
+ /** Base58 Ed25519 public key of the receipt key */
25
+ signer: string;
26
+ }
27
+ export interface ReceiptSigner {
28
+ publicKey: string;
29
+ sign(data: Uint8Array): Promise<Uint8Array>;
30
+ }
31
+ export declare function b64url(u: Uint8Array): string;
32
+ export declare function b64urlDecode(s: string): Uint8Array;
33
+ export declare function sha256Hex(data: ArrayBuffer | Uint8Array): Promise<string>;
34
+ /** Receipt key from a Solana CLI key file (64 bytes: seed + public key) or a 32-byte seed */
35
+ export declare function receiptSignerFromBytes(bytes: Uint8Array): Promise<ReceiptSigner>;
36
+ /** Signs a receipt → header value "<base64url JSON>.<base64url signature>" (the signature covers the exact JSON bytes) */
37
+ export declare function signReceipt(signer: ReceiptSigner, r: Omit<Receipt, 'v' | 'kind' | 'signer'>): Promise<string>;
@@ -0,0 +1,50 @@
1
+ // Signed receipts (optional): after a settled payment the seller signs a small JSON record that binds
2
+ // the request, the hash of the response body and the payment. Buyers can keep it as evidence for disputes and settlement reports.
3
+ // Ed25519 through WebCrypto (Node 20+, Cloudflare Workers). Use a key made only for receipts, never the receiving wallet's key.
4
+ import { PublicKey } from '@solana/web3.js';
5
+ export const RECEIPT_HEADER = 'x-agent402-receipt';
6
+ export const RECEIPT_KIND = 'agent402.x402-receipt';
7
+ const PKCS8_ED25519_PREFIX = [0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20];
8
+ export function b64url(u) {
9
+ let s = '';
10
+ for (const b of u)
11
+ s += String.fromCharCode(b);
12
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
13
+ }
14
+ export function b64urlDecode(s) {
15
+ const b = atob(s.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (s.length % 4)) % 4));
16
+ return Uint8Array.from(b, (c) => c.charCodeAt(0));
17
+ }
18
+ export async function sha256Hex(data) {
19
+ const d = new Uint8Array(await crypto.subtle.digest('SHA-256', data));
20
+ return Array.from(d, (b) => b.toString(16).padStart(2, '0')).join('');
21
+ }
22
+ /** Receipt key from a Solana CLI key file (64 bytes: seed + public key) or a 32-byte seed */
23
+ export async function receiptSignerFromBytes(bytes) {
24
+ if (bytes.length !== 64 && bytes.length !== 32)
25
+ throw new Error('receipt key must be 64 bytes (Solana CLI key file) or a 32-byte seed');
26
+ const pkcs8 = new Uint8Array(48);
27
+ pkcs8.set(PKCS8_ED25519_PREFIX);
28
+ pkcs8.set(bytes.subarray(0, 32), 16);
29
+ try {
30
+ // Exportable copy only to read the public key; the signing key is not exportable
31
+ const tmp = await crypto.subtle.importKey('pkcs8', pkcs8, { name: 'Ed25519' }, true, ['sign']);
32
+ const pub = b64urlDecode((await crypto.subtle.exportKey('jwk', tmp)).x);
33
+ if (bytes.length === 64 && b64url(pub) !== b64url(bytes.subarray(32)))
34
+ throw new Error('receipt key: the public key does not match the secret');
35
+ const key = await crypto.subtle.importKey('pkcs8', pkcs8, { name: 'Ed25519' }, false, ['sign']);
36
+ return {
37
+ publicKey: new PublicKey(pub).toBase58(),
38
+ async sign(data) { return new Uint8Array(await crypto.subtle.sign('Ed25519', key, data)); },
39
+ };
40
+ }
41
+ finally {
42
+ pkcs8.fill(0);
43
+ }
44
+ }
45
+ /** Signs a receipt → header value "<base64url JSON>.<base64url signature>" (the signature covers the exact JSON bytes) */
46
+ export async function signReceipt(signer, r) {
47
+ const receipt = { v: 1, kind: RECEIPT_KIND, ...r, signer: signer.publicKey };
48
+ const bytes = new TextEncoder().encode(JSON.stringify(receipt));
49
+ return `${b64url(bytes)}.${b64url(await signer.sign(bytes))}`;
50
+ }
package/package.json CHANGED
@@ -25,7 +25,7 @@
25
25
  "@x402/core": "2.31.0",
26
26
  "@x402/svm": "2.31.0"
27
27
  },
28
- "version": "0.2.0",
28
+ "version": "0.3.0",
29
29
  "author": "Agent402",
30
30
  "license": "Apache-2.0",
31
31
  "type": "module",