@keelcodes/x402-gate 0.1.1 → 0.1.3

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
@@ -53,7 +53,7 @@ export const GET = withX402(gateOptions, async () => Response.json({ price: 42 }
53
53
  | `paymentsUrl` | 支付引擎地址(自建或 `https://keel.codes/v1/payment`) |
54
54
  | `paymentsKey` | 支付引擎 Bearer key |
55
55
  | `payTo` | 收款地址(B 端自己的钱包;资金直达,不经平台) |
56
- | `amount` | 单次价格(最小单位);也可用 `amountFor(path)` 动态定价 |
56
+ | `amount` | 单次价格(最小单位);也可用 `amountFor(path, req)` 动态定价(A7.9.3:`req.query` 可取 `limit` 做阶梯)。不填时从第一个带 `amount` 的 accept 取价(`0.1.1` 起;再没有就**直接报错**,不会静默免费放行) |
57
57
  | `accepts` | 多链多资产;每项二选一:`eip3009: { name, version }` 或 `permit2: true` |
58
58
  | `exempt` | 免费路径前缀(默认已含 `/health`、`/metrics`) |
59
59
  | `passthroughHeaders` | 额外视为「已有平台凭证」的头(如 `x-tenant-id`) |
@@ -100,12 +100,65 @@ const gate = createX402Gate({
100
100
  > `X-PAYMENT-RESPONSE`。`PAYMENT-REQUIRED` 头始终是 v2。
101
101
 
102
102
  ```ts
103
- const keel = new KeelClient({
104
- x402: { address, signTypedData, signPermit2TypedData },
103
+ import { Keel } from '@keelcodes/sdk'
104
+
105
+ const keel = new Keel({
106
+ baseUrl: 'https://api.example', // 收费服务端(不是支付引擎)
107
+ x402: {
108
+ address: wallet.account.address, // viem WalletClient
109
+ signTypedData: (typed) => wallet.signTypedData(typed),
110
+ maxAmount: '2000', // 单笔上限(最小单位),超过直接拒付
111
+ },
105
112
  })
106
- await keel.get('https://api.example/quote') // 402 → 签名 → 重试 → 200
113
+ await keel.request('GET', '/quote') // 402 → 签名 → 重试 → 200
114
+ ```
115
+
116
+ ### 可运行 demo(agent 自付,零资金)
117
+
118
+ `projects/keel-sdk/examples/agent-autopay-demo.mjs` 把上面这条链路跑通,默认**全本地、离线、不上链**:
119
+
120
+ ```bash
121
+ cd projects/x402-gate && npm run build
122
+ cd ../keel-sdk && npm run build && node examples/agent-autopay-demo.mjs
123
+ ```
124
+
125
+ 输出依次覆盖:免费路径放行 → 未付款拿 `402`(v1 体 + v2 `PAYMENT-REQUIRED` 头 + `links`) →
126
+ Keel 自动签名重试 `200` → 超出 `maxAmount` 时拒付。demo 内置 mock facilitator,
127
+ 只验 EIP-712 签名并回一个假 `transaction`,所以**不需要真钱包余额、也不需要 gas**。
128
+
129
+ 接真环境时换成真收款地址/真付款私钥/真支付引擎(此时不再起本地服务):
130
+
131
+ ```bash
132
+ PAYMENTS_URL=https://keel.codes/v1/payment \
133
+ GATE_URL=https://your-service.example \
134
+ PAYER_PRIVATE_KEY=0x... PAY_TO=0x... \
135
+ node examples/agent-autopay-demo.mjs
136
+ ```
137
+
138
+ demo 只演示 EIP-3009 轨(Base USDC);BSC USDT/USDC 走 Permit2 时,同一份代码由 SDK
139
+ 自动改签 Permit2(`extra.assetTransferMethod=permit2`),首次使用需先按
140
+ 「Permit2 预算」授权一次(见下)。
141
+
142
+ ### Permit2 预算(授权上限)
143
+
144
+ Permit2 轨下,付款人要先给 **canonical Permit2 合约**(不是 proxy)一笔 ERC-20 allowance,
145
+ 这笔额度就是链上硬上限;`approve` 是覆盖写,撤销 = `approve(Permit2, 0)`:
146
+
147
+ ```bash
148
+ cd projects/payment/payments
149
+ npx tsx scripts/permit2-budget.ts --chain bsc --budget 5 # dry-run,只打印 calldata
150
+ npx tsx scripts/permit2-budget.ts --chain bsc --budget 5 --broadcast # 真广播
151
+ npx tsx scripts/permit2-budget.ts --chain bsc --revoke --broadcast # 撤销
107
152
  ```
108
153
 
154
+ ### per-key / per-agent 预算(可选身份头)
155
+
156
+ 网关会把调用方的 `x-keel-key-id` / `x-keel-agent-id` 转发给支付引擎(裁剪 256 字符),
157
+ 引擎据此把消费记到 `key:<sha256 前 16 位>` 或 `agent:<小写 id>` 主体;两者都缺省时退回按付款方地址。
158
+ 运营可用 `GET/PUT /v1/payment/spend-policies[/:subject]` 为这些主体配置日限额、单次上限与收款方白名单。
159
+
160
+ > 这两个头只应由**受信服务端**设置(例如你们自己的 API 网关),不要直接透传外部用户输入,否则调用方可伪造主体。
161
+
109
162
  ## 状态码
110
163
 
111
164
  | 场景 | 响应 |
package/dist/index.d.ts CHANGED
@@ -121,8 +121,8 @@ export interface X402GateOptions {
121
121
  accepts?: X402GateAccept[];
122
122
  /** 命中这些路径前缀的请求不收费(探针/文档) */
123
123
  exempt?: string[];
124
- /** 按请求覆盖价格(最小单位);返回 null 表示不收费 */
125
- amountFor?: (path: string) => string | null;
124
+ /** 按请求覆盖价格(最小单位);返回 null 表示不收费。A7.9.3:第二参可读 query 做 limit 阶梯 */
125
+ amountFor?: (path: string, req: GateRequest) => string | null;
126
126
  /** 额外视为「已有平台凭证」的请求头(如 x-tenant-id) */
127
127
  passthroughHeaders?: string[];
128
128
  /** 资源元数据(写进 402 的 resource;B13.1 目录展示用) */
@@ -145,6 +145,8 @@ export interface GateRequest {
145
145
  path: string;
146
146
  url: string;
147
147
  header: (name: string) => string | null;
148
+ /** 查询串(A7.9.3:`amountFor` 按 `limit` 阶梯计价用) */
149
+ query?: URLSearchParams;
148
150
  /** 调用方地址(免费额度分桶用;缺省视为同一桶) */
149
151
  ip?: string;
150
152
  }
package/dist/index.js CHANGED
@@ -209,9 +209,22 @@ function hasPlatformCredential(req, extra) {
209
209
  return typeof v === 'string' && v.trim().length > 0;
210
210
  });
211
211
  }
212
+ /**
213
+ * B5.1:透传调用方身份头,供支付引擎按 `key:<hash>` / `agent:<id>` 做预算主体。
214
+ * 只转发这两个命名空间内的头,并裁剪长度。
215
+ */
216
+ function identityHeaders(req) {
217
+ const out = {};
218
+ for (const name of ['x-keel-key-id', 'x-keel-agent-id']) {
219
+ const value = (req.header(name) ?? '').trim();
220
+ if (value)
221
+ out[name] = value.slice(0, 256);
222
+ }
223
+ return out;
224
+ }
212
225
  /**
213
226
  * 本次调用的价格(最小单位)。
214
- * 优先级:`amountFor(path)` > 顶层 `amount` > 第一个带价格的 accept。
227
+ * 优先级:`amountFor(path, req)` > 顶层 `amount` > 第一个带价格的 accept。
215
228
  * 只配 `accepts`(多币种)而不写顶层 `amount` 是文档里的标准用法,必须从 accept 取价,
216
229
  * 否则 `amount` 为 undefined 会命中下面的「不收费」分支,等于整站免费。
217
230
  */
@@ -228,7 +241,7 @@ async function authorizeX402(opts, req) {
228
241
  return { action: 'pass' };
229
242
  if (hasPlatformCredential(req, opts.passthroughHeaders ?? []))
230
243
  return { action: 'pass' };
231
- const amount = opts.amountFor ? opts.amountFor(req.path) : resolveAmount(opts);
244
+ const amount = opts.amountFor ? opts.amountFor(req.path, req) : resolveAmount(opts);
232
245
  // `amountFor` 返回 null = 该路径明确免费;但「压根没配价格」必须报错,
233
246
  // 不能静默放行(否则漏配一个 amount 就等于整站免费)。
234
247
  if (amount === null)
@@ -263,6 +276,7 @@ async function authorizeX402(opts, req) {
263
276
  headers: {
264
277
  'Content-Type': 'application/json',
265
278
  ...(opts.paymentsKey ? { Authorization: `Bearer ${opts.paymentsKey}` } : {}),
279
+ ...identityHeaders(req),
266
280
  },
267
281
  // 转发完整挑战:引擎按载荷在 `accepts[]` 中匹配(EIP-3009 / Permit2)。
268
282
  body: JSON.stringify({ paymentPayload: signature, paymentRequirements: challenge }),
@@ -362,6 +376,7 @@ function withX402(opts, handler) {
362
376
  const result = await authorizeX402(opts, {
363
377
  path: parsed.pathname,
364
378
  url,
379
+ query: parsed.searchParams,
365
380
  ip: request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || undefined,
366
381
  header: (name) => request.headers.get(name),
367
382
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keelcodes/x402-gate",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Keel x402 v2 resource gate — Express / Fetch / Next.js adapters (no keys, no chain access)",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -8,7 +8,8 @@
8
8
  ".": {
9
9
  "types": "./dist/index.d.ts",
10
10
  "default": "./dist/index.js"
11
- }
11
+ },
12
+ "./package.json": "./package.json"
12
13
  },
13
14
  "files": [
14
15
  "dist"