kite-x402-hono 0.3.1 → 0.3.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/.env.example CHANGED
@@ -11,3 +11,7 @@ PORT=8080
11
11
  # MAX_BODY_BYTES=1048576
12
12
  # MAX_CONCURRENT_REQUESTS=64
13
13
  # FACILITATOR_TIMEOUT_MS=90000
14
+ # CORS_ORIGIN=*
15
+ # SHUTDOWN_TIMEOUT_MS=10000
16
+
17
+ # MAINTENANCE_MODE=false
package/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.3
4
+
5
+ - Implement graceful CLI shutdown on `SIGINT`/`SIGTERM` with active request draining (`server.stop(false)`) and configurable `SHUTDOWN_TIMEOUT_MS`.
6
+ - Add configuration validation and unit tests for `SHUTDOWN_TIMEOUT_MS` (range 1–60000 ms, default 10000 ms).
7
+ - Update documentation and environment example with graceful shutdown details.
8
+
9
+ - Add standard Kubernetes `GET /livez` liveness probe endpoint returning `200 {"ok":true,"status":"alive"}` with `Cache-Control: no-store` independent of external network or facilitator status.
10
+ - Add `X-Response-Time` performance timing header across all responses measuring wrapper execution latency.
11
+ - Expose `X-Response-Time` in CORS headers (`Access-Control-Expose-Headers`) for web dApps and browser clients.
12
+ - Add unit tests verifying `/livez`, timing header formatting, and CORS exposure.
13
+
14
+ - Preserve configured CORS headers on settlement refusals and facilitator errors
15
+ so allowed browser clients can inspect failure responses and payment receipts.
16
+
17
+ ## 0.3.2
18
+
19
+ - Forward conditional 304 responses through settlement while refusing other 3xx statuses.
20
+ - Add facilitator readiness, response request IDs and early declared-body size checks.
21
+ - Add operational metrics endpoint `GET /stats` providing uptime, active concurrency utilization, and payment challenge/success counters without contacting the facilitator.
22
+ - Validate readiness protocol/version and CORS configuration; preserve paid OPTIONS handling.
23
+ - Add configurable CORS support via `CORS_ORIGIN` (`*` or specific HTTP(S) origin) to allow browser dApps, Web3 extensions, and Kite AI web agents to interact with paid endpoints.
24
+ - Allow preflight `OPTIONS` requests to receive `204 No Content` with appropriate `Access-Control-Allow-*` headers without requiring payments.
25
+ - Expose essential x402 payment headers (`Payment-Required`, `Payment-Response`, `Retry-After`) to cross-origin browser clients.
26
+ - Add comprehensive CORS integration tests covering preflight, 402 challenges, paid responses, origin filtering, and configuration validation.
27
+ - Add automated tests in `tests/stats.test.ts` verifying metrics reporting, challenge recording, and zero-facilitator dependency.
28
+ - Update English and Chinese documentation and `.env.example`.
29
+
3
30
  ## 0.3.1
4
31
 
5
32
  - Make rejected-body and redirect stream cleanup non-blocking so stalled producer
package/README.md CHANGED
@@ -30,10 +30,22 @@ In another terminal in the same directory:
30
30
  ```sh
31
31
  bun run start
32
32
  curl -i http://localhost:8080/healthz
33
+ curl -i http://localhost:8080/readyz
34
+ curl -i http://localhost:8080/.well-known/x402
35
+ curl -i http://localhost:8080/stats
33
36
  curl -i 'http://localhost:8080/v1/echo?message=hello'
34
37
  ```
35
38
 
36
- `/healthz` returns 200 without contacting a facilitator. `/v1/echo` returns
39
+ `/healthz` returns 200 without contacting a facilitator. `/.well-known/x402` exposes
40
+ unmetered capability and pricing discovery (Kite network, token address, decimals,
41
+ atomic price, and receiver wallet) for autonomous AI agents. `/readyz` actually
42
+ calls the facilitator's `/supported` endpoint and returns 200 only when the
43
+ configured Kite network is offered with x402 v2 and the exact scheme, so orchestrators can distinguish
44
+ "process up" from "supported payment protocol". This does not prove that
45
+ the upstream is ready or that a payment will settle. `/stats` returns
46
+ operational telemetry (uptime, active capacity utilization, total received
47
+ requests, challenge counts, and success counts) with `Cache-Control: no-store`
48
+ without touching the facilitator. `/v1/echo` returns
37
49
  402 with an x402 v2 `PAYMENT-REQUIRED` header when the configured facilitator
38
50
  is reachable and supports the selected network. A facilitator outage returns
39
51
  503 instead; the upstream is never called without verified payment.
@@ -68,19 +80,27 @@ injection for tests. Never use a simulated facilitator in a production service.
68
80
 
69
81
  ## Configuration
70
82
 
71
- | Variable | Default | Meaning |
72
- | ---------------------- | ------------------------------------ | ------------------------------------------------------------------------------- |
73
- | `PAY_TO` | Required | Nonzero EVM receiving address |
74
- | `UPSTREAM_URL` | Required | Fixed HTTP(S) origin, with no path, credentials or query |
75
- | `KITE_NETWORK` | `mainnet` | `mainnet` or `testnet` |
76
- | `PRICE_USD` | `0.001` | Positive decimal, at most 6 fractional digits; optional `$` prefix |
77
- | `FACILITATOR_URL` | `https://facilitator.pieverse.io/v2` | Keep the `/v2` suffix |
78
- | `UPSTREAM_AUTH_HEADER` | `Authorization` | Upstream credential header name |
79
- | `UPSTREAM_AUTH_VALUE` | Empty | Server-side credential; replaces buyer-supplied values |
80
- | `SERVICE_DESCRIPTION` | Kite paid API description | Included in the payment challenge |
81
- | `PORT` | `8080` | Wrapper port |
82
- | `UPSTREAM_TIMEOUT_MS` | `10000` | Timeout for reading the request body, then separately for upstream headers/body |
83
- | `MAX_BODY_BYTES` | `1048576` | Request and response byte limit; maximum 16 MiB |
83
+ | Variable | Default | Meaning |
84
+ | ------------------------- | ------------------------------------ | ------------------------------------------------------------------------------- |
85
+ | `PAY_TO` | Required | Nonzero EVM receiving address |
86
+ | `UPSTREAM_URL` | Required | Fixed HTTP(S) origin, with no path, credentials or query |
87
+ | `KITE_NETWORK` | `mainnet` | `mainnet` or `testnet` |
88
+ | `PRICE_USD` | `0.001` | Positive decimal, at most 6 fractional digits; optional `$` prefix |
89
+ | `FACILITATOR_URL` | `https://facilitator.pieverse.io/v2` | Keep the `/v2` suffix |
90
+ | `UPSTREAM_AUTH_HEADER` | `Authorization` | Upstream credential header name |
91
+ | `UPSTREAM_AUTH_VALUE` | Empty | Server-side credential; replaces buyer-supplied values |
92
+ | `SERVICE_DESCRIPTION` | Kite paid API description | Included in the payment challenge |
93
+ | `PORT` | `8080` | Wrapper port |
94
+ | `UPSTREAM_TIMEOUT_MS` | `10000` | Timeout for reading the request body, then separately for upstream headers/body |
95
+ | `MAX_BODY_BYTES` | `1048576` | Request and response byte limit; maximum 16 MiB |
96
+ | `MAX_CONCURRENT_REQUESTS` | `64` | Concurrency admission limit for `/v1/*` requests (1 to 10000) |
97
+ | `FACILITATOR_TIMEOUT_MS` | `90000` | Timeout in ms for facilitator network requests (1 to 300000) |
98
+ | `CORS_ORIGIN` | Unset | Allowed origin for CORS (`*` or HTTP(S) origin); enables browser dApp clients |
99
+ | `SHUTDOWN_TIMEOUT_MS` | `10000` | Timeout in ms to drain active in-flight requests on SIGINT/SIGTERM (1 to 60000) |
100
+
101
+ | `MAINTENANCE_MODE` | `false` | Drain switch (`true` or `1`); `/readyz` & `/v1/*` return 503 with Retry-After |
102
+ | `LOG_FORMAT` | `json` | Access log output format (`json` or `dev`) |
103
+ | `LOG_ENABLED` | `true` | Enable structured request logging (`true` or `false`) |
84
104
 
85
105
  HTTPS is required for upstream/facilitator URLs except localhost development.
86
106
  The example `.env` explicitly selects testnet; the compatibility default remains
@@ -100,7 +120,7 @@ integer arithmetic, including for testnet's 18 decimals.
100
120
  1. No payment or invalid payment: return 402; do not call the upstream.
101
121
  2. Verified payment: strip `/v1`, preserve the query/method/body, inject the
102
122
  configured upstream credential, and call the fixed upstream origin.
103
- 3. Upstream 2xx: buffer the bounded response, then ask the facilitator to settle.
123
+ 3. Upstream 2xx or conditional 304: buffer the bounded response, then ask the facilitator to settle.
104
124
  4. Successful settlement: return the upstream response and `PAYMENT-RESPONSE`.
105
125
  5. Upstream 4xx/5xx, timeout, oversized body or connection failure: do not settle.
106
126
  6. Settlement refusal: return the SDK failure response, withholding protected data.
@@ -112,21 +132,47 @@ Compatibility notes:
112
132
  - Unlike the reference template's general below-400 rule, this template **refuses
113
133
  upstream redirects** with 502, without settlement, so credentials cannot follow
114
134
  redirects to a different host. Use the final upstream origin directly.
135
+ Conditional `304 Not Modified` answers are not redirects and are forwarded, so
136
+ client-side `If-None-Match` / `If-Modified-Since` still works.
115
137
  - Payment headers, client authorization/cookies, proxy headers and hop-by-hop
116
138
  headers are removed. Upstream authentication response headers and cookies are
117
139
  also stripped. The upstream is trusted: do not select one that echoes secrets
118
140
  into response bodies or unrelated headers.
119
141
  - Response buffering is deliberate. Streaming/SSE, WebSocket and unbounded
120
142
  downloads are outside this template's scope.
143
+ - Requests whose valid `Content-Length` already exceeds `MAX_BODY_BYTES` are
144
+ rejected before facilitator verification. Streaming, chunked and incorrectly
145
+ declared bodies are still enforced while the proxy reads them.
146
+ - Stalled or aborted request body uploads are bounded by `UPSTREAM_TIMEOUT_MS`. If a
147
+ client disconnects or stalls while streaming upload chunks, the body reader aborts
148
+ promptly with `408 Request Timeout` (`{"error":"request_timeout_or_abort"}`) and cleans up
149
+ stream locks and timer handles without contacting upstream.
121
150
  - Upstream actions happen before settlement. For non-idempotent POST operations,
122
151
  settlement failure does not undo the upstream action. Use an upstream with
123
152
  idempotency support; the wrapper does not provide exactly-once execution.
124
153
  - A facilitator timeout may leave the on-chain settlement outcome unknown. An
125
154
  error response is not proof of no charge. Reconcile before retrying a payment.
126
- - `/healthz` is process liveness, not proof of upstream/facilitator readiness.
155
+ - `/healthz` and `/livez` provide lightweight process liveness checks without
156
+ contacting backends or consuming concurrency slots.
157
+ - `/readyz` checks downstream readiness: the wrapper process is up and the facilitator
158
+ advertises the configured protocol and network. Each probe contacts the facilitator;
159
+ use an appropriate probe interval. It does not verify upstream health or actual settlement.
160
+ - `/metrics` exposes internal diagnostics (uptime, total/active requests, HTTP status
161
+ distribution counts, and process memory usage) without contacting backends.
162
+ - Every response carries an `X-Request-ID` header. Send your own `x-request-id`
163
+ (letters, digits, `.`, `_`, `~`, `-`, up to 128 chars) and it is echoed back and
164
+ forwarded upstream so agent, wrapper and upstream logs correlate; unsafe
165
+ values are replaced with a minted UUID in the response and stripped upstream.
166
+ IDs are caller-controlled correlation labels, not authentication or payment deduplication keys.
167
+ Generated IDs label the wrapper response; they are not injected upstream.
127
168
  - The CLI disables Bun's short idle timeout so it does not disconnect a client
128
169
  during settlement. SDK facilitator calls default to a configurable 90-second timeout;
129
170
  deploy behind a reverse proxy with suitable request deadlines and rate limits.
171
+ - Every response carries standard HTTP security headers (`X-Content-Type-Options: nosniff`,
172
+ `X-Frame-Options: SAMEORIGIN`, `X-XSS-Protection: 0`, `Referrer-Policy: no-referrer`) to
173
+ protect against MIME-sniffing, clickjacking, and XSS.
174
+ - Unmatched or unknown routes return structured JSON `404 {"error":"not_found"}` with
175
+ `Cache-Control: no-store` rather than unformatted plaintext error responses.
130
176
 
131
177
  ## Verification
132
178
 
@@ -146,6 +192,19 @@ for upstream capacity and response sizes; use edge rate limits for hostile traff
146
192
  Do not treat every 503 as safe to retry: only this wrapper's `service_busy`
147
193
  response denotes pre-payment rejection. Settlement errors still need reconciliation.
148
194
 
195
+ ### Rate limiting (added in 0.3.3)
196
+
197
+ `RATE_LIMIT_RPS` and `RATE_LIMIT_BURST` provide built-in in-memory token-bucket request throttling:
198
+
199
+ - `RATE_LIMIT_RPS`: Allowed requests per second per client IP (optional; rate limiting is disabled when unset).
200
+ - `RATE_LIMIT_BURST`: Maximum burst capacity (defaults to `2 * RATE_LIMIT_RPS`).
201
+ - Evaluated responses include standard rate limit headers:
202
+ - `X-RateLimit-Limit`: configured RPS limit.
203
+ - `X-RateLimit-Remaining`: available token capacity.
204
+ - `X-RateLimit-Reset`: seconds until bucket refill.
205
+ - Exceeding clients receive `429 {"error":"rate_limit_exceeded"}` with `Retry-After: <seconds>` and `Cache-Control: no-store` before payment verification or upstream proxying.
206
+ - `/healthz` health probes and browser `OPTIONS` preflights are always exempt from rate limiting.
207
+
149
208
  ### Facilitator deadlines (added in 0.3.0)
150
209
 
151
210
  `FACILITATOR_TIMEOUT_MS` accepts integers from 1 to 300000, default 90000.
@@ -174,6 +233,37 @@ original bytes. Cleanup is best-effort: an injected stream producer still owns i
174
233
  underlying resources. This does not cancel or undo payment settlement, and does
175
234
  not add payment retries.
176
235
 
236
+ ### CORS support (added in 0.3.2)
237
+
238
+ Configure `CORS_ORIGIN` with `*` or a specific origin (e.g. `https://agent.kite.ai`)
239
+ to enable web browsers, dApps, and AI agent frontends to make paid cross-origin calls:
240
+
241
+ - Preflight `OPTIONS` requests receive `204 No Content` with appropriate
242
+ `Access-Control-Allow-*` headers without triggering payment middleware.
243
+ Only OPTIONS with Origin and Access-Control-Request-Method is preflight;
244
+ other OPTIONS requests still require payment. Upstream CORS headers are stripped
245
+ so the wrapper controls origin policy. CORS is not server-side authentication.
246
+ - `402 Payment Required` challenge responses and successful responses expose
247
+ `Payment-Required`, `Payment-Response`, `Retry-After`, `X-Request-ID`, `X-Response-Time`, allowing browser `fetch`
248
+ clients to inspect payment requirements and payment settlement tokens.
249
+ Settlement refusals and facilitator errors also retain these CORS headers, so
250
+ allowed browser clients can read the actual failure response and any failure receipt.
251
+ - When `CORS_ORIGIN` is unset (the default), CORS middleware is omitted entirely
252
+ with zero overhead and backwards-compatible behavior.
253
+
254
+ ### Graceful shutdown (added in 0.3.3)
255
+
256
+ On receiving `SIGINT` or `SIGTERM` (e.g. during container restarts or deployments),
257
+ the CLI server immediately stops accepting new connections via `server.stop(false)`,
258
+ allowing in-flight paid requests and settlement handshakes to drain cleanly before
259
+ the process exits. If in-flight requests do not complete within `SHUTDOWN_TIMEOUT_MS`
260
+ (default 10000ms), connections are forcibly closed to prevent hanging deployments.
261
+
262
+ ### Liveness probe and timing instrumentation (added in 0.3.3)
263
+
264
+ - `GET /livez`: Standard Kubernetes liveness probe that immediately returns `200 {"ok":true,"status":"alive"}` with `Cache-Control: no-store`. It requires zero network I/O and runs completely independently of facilitator availability, preventing container restart loops during transient facilitator downtime.
265
+ - `X-Response-Time`: Measures total end-to-end request duration through the wrapper (formatted as `${ms}ms`), allowing cloud monitoring tools and browser dApps (via CORS `Access-Control-Expose-Headers`) to distinguish wrapper processing latency from upstream execution and on-chain payment settlement.
266
+
177
267
  ### Commands
178
268
 
179
269
  ```sh
@@ -202,3 +292,11 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for local checks and
202
292
  [docs/week-1.md](docs/week-1.md) for the bounty scope and evidence checklist.
203
293
  AI tools assisted development; BrK reviews and owns the contribution. Original
204
294
  wrapper/configuration/test work is distinguished from upstream SDK functionality.
295
+
296
+ ### Operational endpoint scope
297
+
298
+ `/stats` and `/metrics` are public, process-local diagnostics and reset on restart. Restrict them at your ingress if traffic or memory data should be private. `successful` counts final 2xx responses after payment middleware completes.
299
+
300
+ `/.well-known/x402` is this wrapper's discovery format, not an official x402 discovery schema. Payment challenges remain authoritative. `MAINTENANCE_MODE` is read at startup; restart to change it.
301
+
302
+ Access logs omit query strings, bodies and payment signatures. `clientIp` is an unverified forwarded-header claim; do not use it for access decisions. JSON is recommended for production.
package/README.zh-CN.md CHANGED
@@ -28,10 +28,15 @@ bun run example
28
28
  ```sh
29
29
  bun run start
30
30
  curl -i http://localhost:8080/healthz
31
+ curl -i http://localhost:8080/readyz
32
+ curl -i http://localhost:8080/.well-known/x402
33
+ curl -i http://localhost:8080/stats
31
34
  curl -i 'http://localhost:8080/v1/echo?message=hello'
32
35
  ```
33
36
 
34
- `/healthz` 返回 200,且不会访问 facilitator。`/v1/echo` 在 facilitator 可访问并支持
37
+ `/healthz` 返回 200,且不会访问 facilitator。`/.well-known/x402` 暴露免付费的协议与定价元数据(Kite 网络、代币合约与精度、原子价格与收款地址),供自主 AI Agent 自动发现。`/readyz` 会实际调用
38
+ facilitator 的 `/supported` 接口,只有当前配置的 Kite 网络、x402 v2 和 exact 模式均被支持时才返回
39
+ 200;这不保证上游就绪或实际结算成功。`/stats` 返回运行指标(运行秒数、当前并发占用率、请求总量、挑战数与成功数),携带 `Cache-Control: no-store` 且无需访问 facilitator。`/v1/echo` 在 facilitator 可访问并支持
35
40
  所选网络时,未付款请求会返回带有 x402 v2 `PAYMENT-REQUIRED` 的 402。如果 facilitator
36
41
  不可用,会返回 503;未完成付款验证前,代理不会调用上游。
37
42
 
@@ -64,19 +69,25 @@ Bun.serve({ port: config.port, fetch: app.fetch });
64
69
 
65
70
  ## 配置项
66
71
 
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 |
72
+ | 变量 | 默认值 | 说明 |
73
+ | ------------------------- | ------------------------------------ | ------------------------------------------------------------ |
74
+ | `PAY_TO` | 必填 | 非零 EVM 收款地址 |
75
+ | `UPSTREAM_URL` | 必填 | 固定的 HTTP(S) origin,不得包含路径、凭据或查询参数 |
76
+ | `KITE_NETWORK` | `mainnet` | `mainnet` 或 `testnet` |
77
+ | `PRICE_USD` | `0.001` | 正小数,最多 6 位小数,可带 `$` 前缀 |
78
+ | `FACILITATOR_URL` | `https://facilitator.pieverse.io/v2` | 保留 `/v2` 后缀 |
79
+ | `UPSTREAM_AUTH_HEADER` | `Authorization` | 发给上游的认证头名称 |
80
+ | `UPSTREAM_AUTH_VALUE` | 空 | 服务端上游凭据,会覆盖买方提供的同名值 |
81
+ | `SERVICE_DESCRIPTION` | Kite paid API description | 写入付款挑战的服务说明 |
82
+ | `PORT` | `8080` | 代理监听端口 |
83
+ | `UPSTREAM_TIMEOUT_MS` | `10000` | 请求体读取、上游响应头和响应体的超时时间 |
84
+ | `MAX_BODY_BYTES` | `1048576` | 请求和响应大小限制,最大 16 MiB |
85
+ | `MAX_CONCURRENT_REQUESTS` | `64` | `/v1/*` 路径的并发准入上限(1 至 10000) |
86
+ | `FACILITATOR_TIMEOUT_MS` | `90000` | 请求 facilitator 的网络超时毫秒数(1 至 300000) |
87
+ | `CORS_ORIGIN` | 未配置 | 允许的跨域来源(`*` 或 HTTP(S) origin),支持浏览器 |
88
+ | `SHUTDOWN_TIMEOUT_MS` | `10000` | 接收 SIGINT/SIGTERM 信号时排空在途请求的毫秒数(1 至 60000) |
89
+
90
+ | `MAINTENANCE_MODE` | `false` | 维护排空开关(`true` 或 `1`);`/readyz` 与 `/v1/*` 返回 503 与 Retry-After |
80
91
 
81
92
  除本地开发外,上游和 facilitator 必须使用 HTTPS。示例 `.env` 明确选择 testnet,
82
93
  但兼容性默认值仍是 mainnet。本代理不需要钱包私钥。
@@ -93,7 +104,7 @@ Bun.serve({ port: config.port, fetch: app.fetch });
93
104
 
94
105
  1. 没有付款或付款无效:返回 402,不调用上游。
95
106
  2. 付款验证成功:去掉 `/v1` 前缀,保留查询参数、方法和请求体,注入配置的上游凭据,调用固定 origin。
96
- 3. 上游返回 2xx:缓存有大小上限的响应,然后请求 facilitator 结算。
107
+ 3. 上游返回 2xx 或条件请求 304:缓存有大小上限的响应,然后请求 facilitator 结算。
97
108
  4. 结算成功:返回上游响应和 `PAYMENT-RESPONSE`。
98
109
  5. 上游返回 4xx/5xx、超时、请求或响应超限、连接失败:不结算。
99
110
  6. 结算拒绝:返回 SDK 的失败响应,不泄露受保护数据。
@@ -102,12 +113,15 @@ Bun.serve({ port: config.port, fetch: app.fetch });
102
113
 
103
114
  - `/v1/echo` 会映射到上游 `/echo`;`/v1/v1/forecast` 会映射到上游 `/v1/forecast`。
104
115
  - `/v1/*` 下的所有 HTTP 方法都需要付款;上游必须支持对应方法。
105
- - 本模板拒绝上游重定向并返回 502,不结算,避免凭据被带到其他主机。请直接配置最终上游 origin。
116
+ - 本模板拒绝上游重定向并返回 502,不结算,避免凭据被带到其他主机。请直接配置最终上游 origin。条件请求的 304 Not Modified 不属于重定向,会正常转发,客户端的 If-None-Match / If-Modified-Since 仍然有效。
106
117
  - 会删除支付头、客户端认证头、Cookie、代理头和 hop-by-hop 头;上游返回的认证头和 Cookie 也会被删除。
107
118
  - 响应会被缓存,因此本模板不支持流式响应、SSE、WebSocket 和无限大小下载。
119
+ - 有效 `Content-Length` 已超过 `MAX_BODY_BYTES` 的请求会在 facilitator 验证前被拒绝;
120
+ 流式、分块或错误声明长度的请求仍会在代理读取时执行大小限制。
108
121
  - 上游动作发生在结算之前。非幂等 POST 在结算失败时不会回滚;需要 exactly-once 行为时,上游必须自行提供幂等机制。
109
122
  - facilitator 超时可能无法确定链上结算结果;错误响应不等于确定没有扣款,重试前应先核对。
110
- - `/healthz` 只表示进程存活,不代表上游或 facilitator 已就绪。
123
+ - `/healthz` 只表示进程存活,不代表上游或 facilitator 已就绪。可用 `/readyz` 检查 facilitator 是否可达且支持所配置的网络。
124
+ - 每个响应都带 `X-Request-ID` 头。调用方传入自己的 `x-request-id`(仅限字母、数字、`.`、`_`、`~`、`-`,最长 128 字符)会被原样回显并透传上游,使 agent、wrapper 与上游日志可用同一 ID 关联;不安全的值会被替换为新 UUID。
111
125
 
112
126
  ## 验证
113
127
 
@@ -144,6 +158,29 @@ Bun.serve({ port: config.port, fetch: app.fetch });
144
158
  清理属于尽力执行:自定义流生产者仍须管理底层资源。
145
159
  此改动不会取消或撤销付款结算,也不增加付款重试。
146
160
 
161
+ ### 跨域资源共享 (CORS) 支持(0.3.2 新增)
162
+
163
+ 配置 `CORS_ORIGIN` 为 `*` 或指定 origin(例如 `https://agent.kite.ai`)可支持 Web 浏览器、dApp 及 AI Agent 前端调用付费 API:
164
+
165
+ - 预检 `OPTIONS` 请求返回 `204 No Content` 及对应的 `Access-Control-Allow-*` 头部,无需先触发付费。
166
+ - 付费挑战 `402 Payment Required` 与正常响应均通过 `Access-Control-Expose-Headers` 暴露 `Payment-Required`、`Payment-Response`、`Retry-After`,方便浏览器端 `fetch` 读取付款挑战及结算回执。
167
+ - 结算拒绝和 facilitator 错误响应也保留 CORS 头部,使允许的浏览器客户端可以读取实际错误及失败回执(如有)。
168
+ - 未配置 `CORS_ORIGIN` 时(默认),不注册 CORS 中间件,保持零额外开销与向下兼容。
169
+
170
+ ### 优雅停机 (Graceful Shutdown)(0.3.3 新增)
171
+
172
+ 在接收到 `SIGINT` 或 `SIGTERM` 信号时(如容器重启、停止或部署滚动更新),CLI 服务器会通过 `server.stop(false)` 立即停止接收新的入站连接,并等待当前正在执行的付费请求、上游代理及结算流程平滑完成。如果正在进行的请求在 `SHUTDOWN_TIMEOUT_MS`(默认 10000 毫秒)内仍未完成,服务将强制关闭未完成连接并退出,防止挂起部署。
173
+
174
+ ### 存活探针与耗时追踪 (Liveness Probe & Response Timing)(0.3.3 新增)
175
+
176
+ - `GET /livez`: 标准 Kubernetes 存活探针,立即返回 `200 {"ok":true,"status":"alive"}` 及 `Cache-Control: no-store`。该探针无需任何网络 I/O,完全独立于 facilitator 可用性,可有效防止容器编排平台在 facilitator 瞬时波动时误杀容器。
177
+ - `X-Response-Time`: 在所有入站响应中添加毫秒级处理耗时头部(如 `12.45ms`),并通过 CORS `Access-Control-Expose-Headers` 暴露给前端 dApp 与监控系统,便于准确区分网络传输、上游响应与链上结算各阶段延迟。
178
+
179
+ ### 安全响应头与结构化 404(0.3.3 新增)
180
+
181
+ - 所有响应均自动携带基础 HTTP 安全头部(`X-Content-Type-Options: nosniff`、`X-Frame-Options: SAMEORIGIN`、`X-XSS-Protection: 0`、`Referrer-Policy: no-referrer`),防御 MIME 嗅探、点击劫持与跨站脚本威胁。
182
+ - 未匹配路由统一返回结构化 JSON 响应 `404 {"error":"not_found"}`,并附加 `Cache-Control: no-store` 头部,取代默认纯文本报错。
183
+
147
184
  ### 检查命令
148
185
 
149
186
  ```sh
@@ -167,3 +204,8 @@ pieUSD 会话,并保存真实响应和交易哈希。主网交易不是本地
167
204
  贡献流程见 [CONTRIBUTING.md](CONTRIBUTING.md),活动范围和证据清单见 [docs/week-1.md](docs/week-1.md)。
168
205
  AI 工具参与了开发;BrK 审核并负责此贡献。项目自己的 Wrapper、配置校验、代理逻辑、测试和
169
206
  打包工作与上游 x402 SDK 功能已明确区分。
207
+
208
+ 就绪探针每次访问 facilitator,部署时请设置合理探测间隔;它不保证上游健康或真实结算成功。
209
+ 请求 ID 是调用方可控的关联标签,不能用作身份凭证或付款去重键。生成的 UUID 只标记代理响应;非法调用方 ID 不会透传上游。
210
+ 仅同时携带 Origin 和 Access-Control-Request-Method 的 OPTIONS 属于免费预检,其他 OPTIONS 仍需付款。
211
+ 代理会过滤上游的 CORS 响应头,保持自身来源策略;CORS 不是服务器端鉴权。跨域响应也暴露 X-Request-ID。
package/dist/app.d.ts CHANGED
@@ -1,9 +1,17 @@
1
- import { Hono } from "hono";
1
+ import { Hono, type Context } from "hono";
2
2
  import { type FacilitatorClient } from "@x402/core/server";
3
3
  import { type Config } from "./config.js";
4
4
  import { type FetchUpstream } from "./proxy.js";
5
+ import { type RateLimiterOptions } from "./rate-limiter.js";
6
+ import { IdempotencyCache } from "./idempotency.js";
7
+ import { PaymentNonceReplayGuard } from "./nonce-guard.js";
5
8
  export interface AppOptions {
6
9
  facilitator?: FacilitatorClient;
7
10
  fetchUpstream?: FetchUpstream;
11
+ rateLimiter?: RateLimiterOptions;
12
+ idempotencyCache?: IdempotencyCache;
13
+ nonceGuard?: PaymentNonceReplayGuard;
14
+ clientIp?: (c: Context) => string | null;
15
+ logSink?: ((line: string) => void) | undefined;
8
16
  }
9
17
  export declare function createApp(config?: Config, options?: AppOptions): Hono;