kite-x402-hono 0.1.0 → 0.2.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/.env.example CHANGED
@@ -9,3 +9,4 @@ PORT=8080
9
9
  # UPSTREAM_AUTH_VALUE=Bearer your-upstream-key
10
10
  # UPSTREAM_TIMEOUT_MS=10000
11
11
  # MAX_BODY_BYTES=1048576
12
+ # MAX_CONCURRENT_REQUESTS=64
package/CHANGELOG.md ADDED
@@ -0,0 +1,20 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0
4
+
5
+ - Bound the complete payment lifecycle with `MAX_CONCURRENT_REQUESTS` (default
6
+ 64). Excess requests receive a non-cacheable 503 `service_busy` and Retry-After
7
+ before payment verification. Slots remain held until settlement completes.
8
+ - Release slots on success and failure; keep health checks independent.
9
+ - Add deterministic concurrency, settlement, initialization and recovery tests.
10
+ - Include Chinese documentation and updated configuration/CLI guidance.
11
+ - Make the CI package installation check follow the package version automatically.
12
+
13
+ This release adds a default concurrency cap. Operators needing a different limit
14
+ can set a value from 1 to 10000. The limit is per app instance, not distributed;
15
+ it does not implement payment deduplication or automatic payment retries.
16
+
17
+ ## 0.1.0
18
+
19
+ - Initial Kite mainnet/testnet Bun/Hono x402 proxy, payment lifecycle tests,
20
+ bounded bodies, credential filtering and installable npm package.
package/CONTRIBUTING.md CHANGED
@@ -9,14 +9,15 @@ Any change affecting payments must test missing/invalid payment, successful
9
9
  verify -> upstream -> settle ordering, upstream failure, and settlement failure.
10
10
  Keep simulated-facilitator tests distinct from any real paid-call evidence.
11
11
 
12
- ## Release v0.1.0
12
+ ## Release
13
13
 
14
14
  1. Run checks and `npm audit --omit=dev --audit-level=high`.
15
15
  2. Run `npm pack --dry-run`, review contents, then `npm pack`.
16
16
  3. Install the tarball into an empty directory and exercise CLI help and health.
17
17
  4. Confirm the GitHub CI result for the commit being released.
18
18
  5. Authenticate to npm interactively; never put tokens or OTPs in committed files.
19
- 6. Publish the reviewed tarball: `npm publish kite-x402-hono-0.1.0.tgz --access public`.
19
+ 6. Publish the reviewed tarball for the version in package.json (for example,
20
+ `npm publish kite-x402-hono-0.2.0.tgz --access public`).
20
21
  7. Verify registry version/integrity, then tag the exact source revision.
21
22
 
22
23
  Do not claim a version has been published until the npm registry confirms it.
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # Kite x402 Hono
2
2
 
3
+ 中文文档:[README.zh-CN.md](README.zh-CN.md)
4
+
3
5
  [![CI](https://github.com/BrKDDD/kite-x402-hono/actions/workflows/ci.yml/badge.svg)](https://github.com/BrKDDD/kite-x402-hono/actions/workflows/ci.yml)
4
6
 
5
7
  A Bun/Hono reverse-proxy template for paid HTTP APIs on Kite. It complements
@@ -42,7 +44,7 @@ environment supplied to it.
42
44
 
43
45
  ## Package use
44
46
 
45
- After version 0.1.0 has been published to npm:
47
+ Install from [npm](https://www.npmjs.com/package/kite-x402-hono):
46
48
 
47
49
  ```sh
48
50
  npm install kite-x402-hono
@@ -115,7 +117,7 @@ Compatibility notes:
115
117
  also stripped. The upstream is trusted: do not select one that echoes secrets
116
118
  into response bodies or unrelated headers.
117
119
  - Response buffering is deliberate. Streaming/SSE, WebSocket and unbounded
118
- downloads are outside v0.1.0.
120
+ downloads are outside this template's scope.
119
121
  - Upstream actions happen before settlement. For non-idempotent POST operations,
120
122
  settlement failure does not undo the upstream action. Use an upstream with
121
123
  idempotency support; the wrapper does not provide exactly-once execution.
@@ -128,6 +130,24 @@ Compatibility notes:
128
130
 
129
131
  ## Verification
130
132
 
133
+ ### Concurrency admission (added in 0.2.0)
134
+
135
+ `MAX_CONCURRENT_REQUESTS` defaults to 64 and accepts integers from 1 to 10000.
136
+ The limit is per `createApp()` instance, covering every `/v1/*` request from
137
+ facilitator initialization through verification, upstream handling and settlement.
138
+ Overflow returns `503 {"error":"service_busy"}`, `Retry-After: 1` and
139
+ `Cache-Control: no-store` before any payment verification or upstream call.
140
+ Requests are not queued. Slots are released on completion or failure; `/healthz`
141
+ and unrelated routes do not consume slots. Unpaid challenges also count.
142
+
143
+ This is a concurrency bound, not a distributed rate limiter, payment replay
144
+ defense or idempotency mechanism. Replicas have separate limits. Tune the value
145
+ for upstream capacity and response sizes; use edge rate limits for hostile traffic.
146
+ Do not treat every 503 as safe to retry: only this wrapper's `service_busy`
147
+ response denotes pre-payment rejection. Settlement errors still need reconciliation.
148
+
149
+ ### Commands
150
+
131
151
  ```sh
132
152
  npm run typecheck
133
153
  bun test --coverage
@@ -0,0 +1,148 @@
1
+ # Kite x402 Hono
2
+
3
+ [![CI](https://github.com/BrKDDD/kite-x402-hono/actions/workflows/ci.yml/badge.svg)](https://github.com/BrKDDD/kite-x402-hono/actions/workflows/ci.yml)
4
+
5
+ English: [README.md](README.md)
6
+
7
+ 这是一个基于 Bun 和 Hono 的 HTTP 付费 API 反向代理模板,使用 x402 协议在 Kite
8
+ 网络上按请求收费。它补充了 [Kite 官方 Express 和 Go 模板](https://github.com/gokite-ai/kite-x402-services),
9
+ 复用相同的环境变量和 `/v1/*` 路由约定,并使用官方 `@x402/hono` 中间件处理支付。
10
+
11
+ 这是独立的社区项目,采用 Apache-2.0 许可证。上游来源和署名见 `NOTICE`。
12
+
13
+ ## 快速开始
14
+
15
+ 需要 Bun 1.3 或更高版本。npm 构建工具需要 Node.js 22 或更高版本;CI 使用 Bun 1.4.2。
16
+
17
+ ```sh
18
+ git clone https://github.com/BrKDDD/kite-x402-hono.git
19
+ cd kite-x402-hono
20
+ npm ci
21
+ cp .env.example .env
22
+ # 将 .env 中的 PAY_TO 替换为你自己的收款地址。
23
+ bun run example
24
+ ```
25
+
26
+ 在另一个终端启动代理:
27
+
28
+ ```sh
29
+ bun run start
30
+ curl -i http://localhost:8080/healthz
31
+ curl -i 'http://localhost:8080/v1/echo?message=hello'
32
+ ```
33
+
34
+ `/healthz` 返回 200,且不会访问 facilitator。`/v1/echo` 在 facilitator 可访问并支持
35
+ 所选网络时,未付款请求会返回带有 x402 v2 `PAYMENT-REQUIRED` 的 402。如果 facilitator
36
+ 不可用,会返回 503;未完成付款验证前,代理不会调用上游。
37
+
38
+ 示例是本地 echo API,不是已部署的服务,也不构成真实付费调用凭证。Bun 会自动读取
39
+ `.env`;库函数 `loadConfig()` 只读取传入的环境对象。
40
+
41
+ ## 安装 npm 包
42
+
43
+ ```sh
44
+ npm install kite-x402-hono
45
+ bunx kite-x402-hono --help
46
+ # 配置 PAY_TO 和 UPSTREAM_URL 后启动。
47
+ bunx kite-x402-hono
48
+ ```
49
+
50
+ 公开版本及安装信息:[kite-x402-hono](https://www.npmjs.com/package/kite-x402-hono)。
51
+
52
+ 也可以作为库使用:
53
+
54
+ ```ts
55
+ import { createApp, loadConfig } from "kite-x402-hono";
56
+
57
+ const config = loadConfig();
58
+ const app = createApp(config);
59
+ Bun.serve({ port: config.port, fetch: app.fetch });
60
+ ```
61
+
62
+ `createApp(config, { facilitator, fetchUpstream })` 支持依赖注入,便于测试。生产服务
63
+ 不要使用模拟 facilitator。
64
+
65
+ ## 配置项
66
+
67
+ | 变量 | 默认值 | 说明 |
68
+ | ---------------------- | ------------------------------------ | --------------------------------------------------- |
69
+ | `PAY_TO` | 必填 | 非零 EVM 收款地址 |
70
+ | `UPSTREAM_URL` | 必填 | 固定的 HTTP(S) origin,不得包含路径、凭据或查询参数 |
71
+ | `KITE_NETWORK` | `mainnet` | `mainnet` 或 `testnet` |
72
+ | `PRICE_USD` | `0.001` | 正小数,最多 6 位小数,可带 `$` 前缀 |
73
+ | `FACILITATOR_URL` | `https://facilitator.pieverse.io/v2` | 保留 `/v2` 后缀 |
74
+ | `UPSTREAM_AUTH_HEADER` | `Authorization` | 发给上游的认证头名称 |
75
+ | `UPSTREAM_AUTH_VALUE` | 空 | 服务端上游凭据,会覆盖买方提供的同名值 |
76
+ | `SERVICE_DESCRIPTION` | Kite paid API description | 写入付款挑战的服务说明 |
77
+ | `PORT` | `8080` | 代理监听端口 |
78
+ | `UPSTREAM_TIMEOUT_MS` | `10000` | 请求体读取、上游响应头和响应体的超时时间 |
79
+ | `MAX_BODY_BYTES` | `1048576` | 请求和响应大小限制,最大 16 MiB |
80
+
81
+ 除本地开发外,上游和 facilitator 必须使用 HTTPS。示例 `.env` 明确选择 testnet,
82
+ 但兼容性默认值仍是 mainnet。本代理不需要钱包私钥。
83
+
84
+ | 网络 | CAIP-2 | 代币 | 精度 | EIP-712 域 |
85
+ | ------ | ------------- | ------ | ---- | ---------------------------------- |
86
+ | 主网 | `eip155:2366` | USDC.e | 6 | `Bridged USDC (Kite AI)`,版本 `2` |
87
+ | 测试网 | `eip155:2368` | pieUSD | 18 | `pieUSD`,版本 `1` |
88
+
89
+ 代币地址固定在 `src/networks.ts`,来源是 Kite 官方模板 revision
90
+ `893a27509648b660bbba626b0da59619a94f04ab`。金额换算使用整数运算,包含测试网的 18 位精度。
91
+
92
+ ## 支付与代理流程
93
+
94
+ 1. 没有付款或付款无效:返回 402,不调用上游。
95
+ 2. 付款验证成功:去掉 `/v1` 前缀,保留查询参数、方法和请求体,注入配置的上游凭据,调用固定 origin。
96
+ 3. 上游返回 2xx:缓存有大小上限的响应,然后请求 facilitator 结算。
97
+ 4. 结算成功:返回上游响应和 `PAYMENT-RESPONSE`。
98
+ 5. 上游返回 4xx/5xx、超时、请求或响应超限、连接失败:不结算。
99
+ 6. 结算拒绝:返回 SDK 的失败响应,不泄露受保护数据。
100
+
101
+ 兼容性和安全行为:
102
+
103
+ - `/v1/echo` 会映射到上游 `/echo`;`/v1/v1/forecast` 会映射到上游 `/v1/forecast`。
104
+ - `/v1/*` 下的所有 HTTP 方法都需要付款;上游必须支持对应方法。
105
+ - 本模板拒绝上游重定向并返回 502,不结算,避免凭据被带到其他主机。请直接配置最终上游 origin。
106
+ - 会删除支付头、客户端认证头、Cookie、代理头和 hop-by-hop 头;上游返回的认证头和 Cookie 也会被删除。
107
+ - 响应会被缓存,因此本模板不支持流式响应、SSE、WebSocket 和无限大小下载。
108
+ - 上游动作发生在结算之前。非幂等 POST 在结算失败时不会回滚;需要 exactly-once 行为时,上游必须自行提供幂等机制。
109
+ - facilitator 超时可能无法确定链上结算结果;错误响应不等于确定没有扣款,重试前应先核对。
110
+ - `/healthz` 只表示进程存活,不代表上游或 facilitator 已就绪。
111
+
112
+ ## 验证
113
+
114
+ ### 并发准入限制(0.2.0 新增)
115
+
116
+ `MAX_CONCURRENT_REQUESTS` 默认 64,接受 1 至 10000 的整数。每个 `createApp()` 实例
117
+ 独立限制 `/v1/*` 的在途请求数,从 facilitator 初始化、付款验证、上游处理一直覆盖到结算完成。
118
+ 达到上限后立即返回 `503 {"error":"service_busy"}`,附带 `Retry-After: 1` 和
119
+ `Cache-Control: no-store`,不验证付款、不调用上游,也不排队保存请求。
120
+ 完成或失败都会释放名额;健康检查和无关路由不占用名额,未付款请求会占用名额。
121
+
122
+ 这不是跨实例限流、付款防重放或幂等机制。应根据上游能力和响应大小调整上限,多个副本分别计数,
123
+ 恶意流量仍应通过入口限流控制。不能把所有 503 都当成可安全重试:只有本代理的
124
+ `service_busy` 表示付款前拒绝;结算错误仍需先核对结果。
125
+
126
+ ### 检查命令
127
+
128
+ ```sh
129
+ npm run typecheck
130
+ bun test --coverage
131
+ npm run build
132
+ npm audit --omit=dev --audit-level=high
133
+ npm pack
134
+ ```
135
+
136
+ 测试使用真实的 x402 Hono 中间件。确定性的模拟 facilitator 提供验证和结算结果;另有 HTTP
137
+ 集成测试通过本地 `/v2/supported`、`/v2/verify`、`/v2/settle` 端点运行真实 HTTP 请求代理。
138
+ 测试 fixture 不是有效签名,也不是真实链上付款证明。CI 会执行测试、构建、依赖审计、打包和
139
+ 安装包验证,并保存覆盖率及 JUnit 报告。
140
+
141
+ 如需真实付费验收,请部署公开 HTTPS origin,替换 `PAY_TO`,使用 Kite Passport 测试网
142
+ pieUSD 会话,并保存真实响应和交易哈希。主网交易不是本地开发所必需的。
143
+
144
+ ## 发布与贡献
145
+
146
+ 贡献流程见 [CONTRIBUTING.md](CONTRIBUTING.md),活动范围和证据清单见 [docs/week-1.md](docs/week-1.md)。
147
+ AI 工具参与了开发;BrK 审核并负责此贡献。项目自己的 Wrapper、配置校验、代理逻辑、测试和
148
+ 打包工作与上游 x402 SDK 功能已明确区分。
package/dist/app.js CHANGED
@@ -7,6 +7,27 @@ import { parsePrice } from "./networks.js";
7
7
  import { proxy } from "./proxy.js";
8
8
  export function createApp(config = loadConfig(), options = {}) {
9
9
  const app = new Hono();
10
+ const capacity = config.maxConcurrentRequests ?? 64;
11
+ if (!Number.isInteger(capacity) || capacity < 1 || capacity > 10000) {
12
+ throw new Error("maxConcurrentRequests must be an integer between 1 and 10000");
13
+ }
14
+ let active = 0;
15
+ // Cover initialization, verification, upstream and settlement, not just proxy I/O.
16
+ // Never queue payment-bearing requests or retain their signatures.
17
+ app.use("/v1/*", async (c, next) => {
18
+ if (active >= capacity) {
19
+ c.header("Retry-After", "1");
20
+ c.header("Cache-Control", "no-store");
21
+ return c.json({ error: "service_busy" }, 503);
22
+ }
23
+ active++;
24
+ try {
25
+ await next();
26
+ }
27
+ finally {
28
+ active--;
29
+ }
30
+ });
10
31
  const facilitator = options.facilitator ??
11
32
  new HTTPFacilitatorClient({ url: config.facilitatorUrl });
12
33
  const server = new x402ResourceServer(facilitator).register(config.chain.network, new ExactEvmScheme());
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { createApp } from "./app.js";
3
3
  import { loadConfig } from "./config.js";
4
4
  if (process.argv.includes("--help")) {
5
- console.log("Usage: kite-x402-hono\nRequired: PAY_TO, UPSTREAM_URL\nOptional: KITE_NETWORK, PRICE_USD, PORT, FACILITATOR_URL, UPSTREAM_AUTH_HEADER, UPSTREAM_AUTH_VALUE, UPSTREAM_TIMEOUT_MS, MAX_BODY_BYTES\nSee README.md for configuration and examples.");
5
+ console.log("Usage: kite-x402-hono\nRequired: PAY_TO, UPSTREAM_URL\nOptional: KITE_NETWORK, PRICE_USD, PORT, FACILITATOR_URL, UPSTREAM_AUTH_HEADER, UPSTREAM_AUTH_VALUE, UPSTREAM_TIMEOUT_MS, MAX_BODY_BYTES, MAX_CONCURRENT_REQUESTS\nSee README.md for configuration and examples.");
6
6
  }
7
7
  else {
8
8
  try {
package/dist/config.d.ts CHANGED
@@ -11,5 +11,6 @@ export interface Config {
11
11
  port: number;
12
12
  timeoutMs: number;
13
13
  maxBodyBytes: number;
14
+ maxConcurrentRequests?: number;
14
15
  }
15
16
  export declare function loadConfig(env?: Record<string, string | undefined>): Config;
package/dist/config.js CHANGED
@@ -78,5 +78,6 @@ export function loadConfig(env = process.env) {
78
78
  port: integer(get("PORT", "8080"), "PORT", 65535),
79
79
  timeoutMs: integer(get("UPSTREAM_TIMEOUT_MS", "10000"), "UPSTREAM_TIMEOUT_MS", 120000),
80
80
  maxBodyBytes: integer(get("MAX_BODY_BYTES", "1048576"), "MAX_BODY_BYTES", 16777216),
81
+ maxConcurrentRequests: integer(get("MAX_CONCURRENT_REQUESTS", "64"), "MAX_CONCURRENT_REQUESTS", 10000),
81
82
  };
82
83
  }
package/docs/week-2.md ADDED
@@ -0,0 +1,43 @@
1
+ # Week 2: bounded concurrent payment requests
2
+
3
+ Direction: `x402-wrapper`. Continue in the original BrKDDD/kite-x402-hono repository.
4
+
5
+ ## Problem and change
6
+
7
+ The first version admitted unlimited concurrent payment requests. Slow upstreams
8
+ or settlement could accumulate work even though individual bodies had size limits.
9
+ Add per-app admission control across the entire payment lifecycle, with a default
10
+ capacity of 64 and configurable `MAX_CONCURRENT_REQUESTS` (1–10000).
11
+
12
+ Overflow gets an explicit non-cacheable 503 `service_busy` plus Retry-After before
13
+ verification. No payment-bearing requests are queued. The slot survives settlement
14
+ and is released on both success and failure. Health checks remain available.
15
+ Older programmatic Config objects use the default when the new optional field is absent.
16
+
17
+ ## Verification
18
+
19
+ `tests/concurrency.test.ts` exercises the official middleware with simulated payment
20
+ verification/settlement. Deterministic gates (not timing sleeps) hold requests during
21
+ upstream, initialization and settlement to test competing requests.
22
+
23
+ - Capacity 2: two admitted requests and 20 rejected requests; exactly two verify
24
+ and upstream calls before release, then subsequent requests work.
25
+ - Capacity remains reserved until settlement finishes.
26
+ - Initialization is shared; independent app instances do not share capacity.
27
+ - Invalid payment, upstream errors, verification exceptions, settlement failure,
28
+ settlement exceptions and initialization failure all release capacity.
29
+ - Config bounds and backwards-compatible programmatic defaults.
30
+
31
+ Run `npm run format:check`, `npm run check` and `npm run test:coverage`.
32
+ These are simulated payment tests, not real on-chain transactions.
33
+
34
+ ## Submission summary
35
+
36
+ 第二周在原仓库新增付费请求并发准入控制:通过 MAX_CONCURRENT_REQUESTS 限制完整的
37
+ 初始化、付款验证、上游调用和结算生命周期。超额请求在验证付款前返回 503 service_busy,
38
+ 附带 Retry-After,完成和异常路径均释放名额,健康检查不受影响。新增确定性的并发与故障
39
+ 回归测试,验证突发请求、结算期间名额保留、初始化共享和失败恢复;同步更新中英文文档及配置示例。
40
+
41
+ This feature is included in release 0.2.0; npm 0.1.0 does not contain it.
42
+ No on-chain payment is claimed. This is a per-process resource bound, not payment
43
+ deduplication, exactly-once execution or a distributed rate limiter.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kite-x402-hono",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Bun and Hono reverse proxy for x402 payments on Kite",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -26,8 +26,10 @@
26
26
  "files": [
27
27
  "dist",
28
28
  "README.md",
29
+ "README.zh-CN.md",
29
30
  "LICENSE",
30
31
  "NOTICE",
32
+ "CHANGELOG.md",
31
33
  "CONTRIBUTING.md",
32
34
  "SECURITY.md",
33
35
  "docs",