kite-x402-hono 0.3.2 → 0.4.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 +3 -0
- package/CHANGELOG.md +24 -0
- package/README.md +107 -6
- package/README.zh-CN.md +66 -18
- package/dist/app.d.ts +9 -1
- package/dist/app.js +212 -20
- package/dist/audit-trace-emitter.d.ts +22 -0
- package/dist/audit-trace-emitter.js +30 -0
- package/dist/cache/payment-auth-cache.d.ts +15 -0
- package/dist/cache/payment-auth-cache.js +44 -0
- package/dist/cli.js +21 -6
- package/dist/client-ip.d.ts +4 -0
- package/dist/client-ip.js +52 -0
- package/dist/config.d.ts +10 -0
- package/dist/config.js +22 -5
- package/dist/firewall.d.ts +32 -0
- package/dist/firewall.js +139 -0
- package/dist/idempotency.d.ts +37 -0
- package/dist/idempotency.js +105 -0
- package/dist/index.d.ts +25 -1
- package/dist/index.js +25 -1
- package/dist/logger.d.ts +22 -0
- package/dist/logger.js +73 -0
- package/dist/middleware/brotli-compression.d.ts +2 -0
- package/dist/middleware/brotli-compression.js +16 -0
- package/dist/middleware/cookie-session-store.d.ts +6 -0
- package/dist/middleware/cookie-session-store.js +28 -0
- package/dist/middleware/edge-rate-throttler.d.ts +14 -0
- package/dist/middleware/edge-rate-throttler.js +27 -0
- package/dist/middleware/payload-validator.d.ts +6 -0
- package/dist/middleware/payload-validator.js +27 -0
- package/dist/middleware/scheme-validator.d.ts +15 -0
- package/dist/middleware/scheme-validator.js +20 -0
- package/dist/middleware/sliding-window-limiter.d.ts +12 -0
- package/dist/middleware/sliding-window-limiter.js +45 -0
- package/dist/networks.d.ts +5 -0
- package/dist/networks.js +14 -0
- package/dist/nonce-guard.d.ts +67 -0
- package/dist/nonce-guard.js +118 -0
- package/dist/payment-protection.d.ts +8 -0
- package/dist/payment-protection.js +150 -0
- package/dist/prometheus-metrics.d.ts +33 -0
- package/dist/prometheus-metrics.js +94 -0
- package/dist/proxy.js +12 -6
- package/dist/rate-limiter.d.ts +71 -0
- package/dist/rate-limiter.js +218 -0
- package/dist/readiness-probe.d.ts +41 -0
- package/dist/readiness-probe.js +126 -0
- package/dist/receipt-store.d.ts +44 -0
- package/dist/receipt-store.js +90 -0
- package/dist/response-caching.d.ts +27 -0
- package/dist/response-caching.js +73 -0
- package/dist/response-signer.d.ts +38 -0
- package/dist/response-signer.js +73 -0
- package/dist/rpc-circuit-breaker.d.ts +29 -0
- package/dist/rpc-circuit-breaker.js +71 -0
- package/dist/settlement-reconciler.d.ts +40 -0
- package/dist/settlement-reconciler.js +107 -0
- package/dist/telemetry/latency-histogram.d.ts +17 -0
- package/dist/telemetry/latency-histogram.js +34 -0
- package/dist/tiered-fee-scheduler.d.ts +51 -0
- package/dist/tiered-fee-scheduler.js +112 -0
- package/dist/traffic-shaper.d.ts +33 -0
- package/dist/traffic-shaper.js +97 -0
- package/dist/webhook-dispatcher.d.ts +23 -0
- package/dist/webhook-dispatcher.js +44 -0
- package/docs/pr-review-2026-11-04.md +56 -0
- package/package.json +5 -5
package/.env.example
CHANGED
package/CHANGELOG.md
CHANGED
|
@@ -1,14 +1,38 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
- Integrate and review community PRs #22, #24, #28–#29, #31, #33–#51.
|
|
6
|
+
- Isolate paid idempotent retries; keep active reservations and nonce leases owner-bound; default to socket IP identity and validate IPv6 firewall rules.
|
|
7
|
+
- Repair optional component authentication, cache privacy/bounds, receipt retention/indexing, probe cleanup/coalescing, queue timers and policy enforcement. Export optional library utilities without automatically enabling them.
|
|
8
|
+
- Upgrade official x402 SDK packages to 2.29.0 and Hono to 4.13.16; retain paid ordinary OPTIONS explicitly after SDK route-matching changes.
|
|
9
|
+
- Add independent cryptographic and security regression coverage. See docs/pr-review-2026-11-04.md for component limits.
|
|
10
|
+
|
|
11
|
+
## 0.3.3
|
|
12
|
+
|
|
13
|
+
- Implement graceful CLI shutdown on `SIGINT`/`SIGTERM` with active request draining (`server.stop(false)`) and configurable `SHUTDOWN_TIMEOUT_MS`.
|
|
14
|
+
- Add configuration validation and unit tests for `SHUTDOWN_TIMEOUT_MS` (range 1–60000 ms, default 10000 ms).
|
|
15
|
+
- Update documentation and environment example with graceful shutdown details.
|
|
16
|
+
|
|
17
|
+
- 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.
|
|
18
|
+
- Add `X-Response-Time` performance timing header across all responses measuring wrapper execution latency.
|
|
19
|
+
- Expose `X-Response-Time` in CORS headers (`Access-Control-Expose-Headers`) for web dApps and browser clients.
|
|
20
|
+
- Add unit tests verifying `/livez`, timing header formatting, and CORS exposure.
|
|
21
|
+
|
|
22
|
+
- Preserve configured CORS headers on settlement refusals and facilitator errors
|
|
23
|
+
so allowed browser clients can inspect failure responses and payment receipts.
|
|
24
|
+
|
|
3
25
|
## 0.3.2
|
|
4
26
|
|
|
5
27
|
- Forward conditional 304 responses through settlement while refusing other 3xx statuses.
|
|
6
28
|
- Add facilitator readiness, response request IDs and early declared-body size checks.
|
|
29
|
+
- Add operational metrics endpoint `GET /stats` providing uptime, active concurrency utilization, and payment challenge/success counters without contacting the facilitator.
|
|
7
30
|
- Validate readiness protocol/version and CORS configuration; preserve paid OPTIONS handling.
|
|
8
31
|
- 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.
|
|
9
32
|
- Allow preflight `OPTIONS` requests to receive `204 No Content` with appropriate `Access-Control-Allow-*` headers without requiring payments.
|
|
10
33
|
- Expose essential x402 payment headers (`Payment-Required`, `Payment-Response`, `Retry-After`) to cross-origin browser clients.
|
|
11
34
|
- Add comprehensive CORS integration tests covering preflight, 402 challenges, paid responses, origin filtering, and configuration validation.
|
|
35
|
+
- Add automated tests in `tests/stats.test.ts` verifying metrics reporting, challenge recording, and zero-facilitator dependency.
|
|
12
36
|
- Update English and Chinese documentation and `.env.example`.
|
|
13
37
|
|
|
14
38
|
## 0.3.1
|
package/README.md
CHANGED
|
@@ -31,14 +31,21 @@ In another terminal in the same directory:
|
|
|
31
31
|
bun run start
|
|
32
32
|
curl -i http://localhost:8080/healthz
|
|
33
33
|
curl -i http://localhost:8080/readyz
|
|
34
|
+
curl -i http://localhost:8080/.well-known/x402
|
|
35
|
+
curl -i http://localhost:8080/stats
|
|
34
36
|
curl -i 'http://localhost:8080/v1/echo?message=hello'
|
|
35
37
|
```
|
|
36
38
|
|
|
37
|
-
`/healthz` returns 200 without contacting a facilitator.
|
|
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
|
|
38
42
|
calls the facilitator's `/supported` endpoint and returns 200 only when the
|
|
39
43
|
configured Kite network is offered with x402 v2 and the exact scheme, so orchestrators can distinguish
|
|
40
44
|
"process up" from "supported payment protocol". This does not prove that
|
|
41
|
-
the upstream is ready or that a payment will settle. `/
|
|
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
|
|
42
49
|
402 with an x402 v2 `PAYMENT-REQUIRED` header when the configured facilitator
|
|
43
50
|
is reachable and supports the selected network. A facilitator outage returns
|
|
44
51
|
503 instead; the upstream is never called without verified payment.
|
|
@@ -89,6 +96,11 @@ injection for tests. Never use a simulated facilitator in a production service.
|
|
|
89
96
|
| `MAX_CONCURRENT_REQUESTS` | `64` | Concurrency admission limit for `/v1/*` requests (1 to 10000) |
|
|
90
97
|
| `FACILITATOR_TIMEOUT_MS` | `90000` | Timeout in ms for facilitator network requests (1 to 300000) |
|
|
91
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`) |
|
|
92
104
|
|
|
93
105
|
HTTPS is required for upstream/facilitator URLs except localhost development.
|
|
94
106
|
The example `.env` explicitly selects testnet; the compatibility default remains
|
|
@@ -131,15 +143,22 @@ Compatibility notes:
|
|
|
131
143
|
- Requests whose valid `Content-Length` already exceeds `MAX_BODY_BYTES` are
|
|
132
144
|
rejected before facilitator verification. Streaming, chunked and incorrectly
|
|
133
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.
|
|
134
150
|
- Upstream actions happen before settlement. For non-idempotent POST operations,
|
|
135
151
|
settlement failure does not undo the upstream action. Use an upstream with
|
|
136
152
|
idempotency support; the wrapper does not provide exactly-once execution.
|
|
137
153
|
- A facilitator timeout may leave the on-chain settlement outcome unknown. An
|
|
138
154
|
error response is not proof of no charge. Reconcile before retrying a payment.
|
|
139
|
-
- `/healthz`
|
|
140
|
-
|
|
141
|
-
|
|
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;
|
|
142
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.
|
|
143
162
|
- Every response carries an `X-Request-ID` header. Send your own `x-request-id`
|
|
144
163
|
(letters, digits, `.`, `_`, `~`, `-`, up to 128 chars) and it is echoed back and
|
|
145
164
|
forwarded upstream so agent, wrapper and upstream logs correlate; unsafe
|
|
@@ -149,9 +168,40 @@ Compatibility notes:
|
|
|
149
168
|
- The CLI disables Bun's short idle timeout so it does not disconnect a client
|
|
150
169
|
during settlement. SDK facilitator calls default to a configurable 90-second timeout;
|
|
151
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.
|
|
176
|
+
|
|
177
|
+
Active nonce reservations remain held until their request finishes or settlement begins. The legacy `inFlightTtlMs` option is retained but does not evict active work. The middleware uses owner-bound reservations so an old request cannot release a replacement. Consumed retention remains process-local and time-limited; persistent or multi-process coordination belongs to the application.
|
|
152
178
|
|
|
153
179
|
## Verification
|
|
154
180
|
|
|
181
|
+
### Idempotent paid retries
|
|
182
|
+
|
|
183
|
+
Send an `Idempotency-Key` (1–128 letters, digits, `_`, `.`, `:`, `~`, or `-`)
|
|
184
|
+
with `PAYMENT-SIGNATURE` to cache a successfully settled 2xx response. Retries
|
|
185
|
+
must carry the same key and exact payment credential, HTTP method, URL (including
|
|
186
|
+
query), body bytes and forwarded headers. `X-Request-ID` may change for each
|
|
187
|
+
attempt. A matching retry returns the cached response and payment receipt with
|
|
188
|
+
`Idempotent-Replayed: true` without verification, another upstream call or another
|
|
189
|
+
settlement, including when an injected `PaymentNonceReplayGuard` is enabled.
|
|
190
|
+
|
|
191
|
+
A key alone cannot retrieve paid data: missing or invalid payment still returns 402. Different payment credentials have independent cache entries. Reusing the
|
|
192
|
+
same credential and key with different request content, or while the original
|
|
193
|
+
request is still running, returns `409 {"error":"idempotency_conflict"}`. Cache
|
|
194
|
+
indexes hash the credential and service configuration rather than storing raw
|
|
195
|
+
signatures as keys; injected shared caches are isolated across configurations.
|
|
196
|
+
|
|
197
|
+
The default in-memory cache expires completed responses after 10 minutes and is
|
|
198
|
+
bounded by 1,000 entries and 32 MiB of response bodies; entries may be evicted
|
|
199
|
+
earlier. Only successful settlements are cached. Process restarts, eviction,
|
|
200
|
+
expiration, upstream errors and failed or indeterminate settlements do not give
|
|
201
|
+
an exactly-once guarantee. Keep upstream idempotency and reconcile uncertain
|
|
202
|
+
charges before retrying. This changes the earlier behavior that allowed a user
|
|
203
|
+
key without the original payment credential to retrieve a cached result.
|
|
204
|
+
|
|
155
205
|
### Concurrency admission (added in 0.2.0)
|
|
156
206
|
|
|
157
207
|
`MAX_CONCURRENT_REQUESTS` defaults to 64 and accepts integers from 1 to 10000.
|
|
@@ -168,6 +218,26 @@ for upstream capacity and response sizes; use edge rate limits for hostile traff
|
|
|
168
218
|
Do not treat every 503 as safe to retry: only this wrapper's `service_busy`
|
|
169
219
|
response denotes pre-payment rejection. Settlement errors still need reconciliation.
|
|
170
220
|
|
|
221
|
+
Firewall allow/block lists accept IPv4, IPv6 and CIDR rules. Compressed IPv6 and IPv4-mapped addresses are normalized by the platform IP parser on both sides. Invalid rules fail configuration; invalid client identities are denied when filtering is enabled. Block rules take priority over allow rules.
|
|
222
|
+
|
|
223
|
+
### Rate limiting (added in 0.3.3)
|
|
224
|
+
|
|
225
|
+
`RATE_LIMIT_RPS` and `RATE_LIMIT_BURST` provide built-in in-memory token-bucket request throttling:
|
|
226
|
+
|
|
227
|
+
- `RATE_LIMIT_RPS`: Allowed requests per second per client IP (optional; rate limiting is disabled when unset).
|
|
228
|
+
- `RATE_LIMIT_BURST`: Maximum burst capacity (defaults to `2 * RATE_LIMIT_RPS`).
|
|
229
|
+
- Evaluated responses include standard rate limit headers:
|
|
230
|
+
- `X-RateLimit-Limit`: configured RPS limit.
|
|
231
|
+
- `X-RateLimit-Remaining`: available token capacity.
|
|
232
|
+
- `X-RateLimit-Reset`: seconds until bucket refill.
|
|
233
|
+
- Exceeding clients receive `429 {"error":"rate_limit_exceeded"}` with `Retry-After: <seconds>` and `Cache-Control: no-store` before payment verification or upstream proxying.
|
|
234
|
+
- `/healthz` health probes and browser `OPTIONS` preflights are always exempt from rate limiting.
|
|
235
|
+
|
|
236
|
+
The built-in limiter tracks at most 10,000 client buckets per app instance.
|
|
237
|
+
Requests trigger an idle-bucket sweep at most once per second. Only buckets
|
|
238
|
+
whose tokens have fully refilled are removed, preserving limits for active or
|
|
239
|
+
partially refilled clients while making room for new clients over time.
|
|
240
|
+
|
|
171
241
|
### Facilitator deadlines (added in 0.3.0)
|
|
172
242
|
|
|
173
243
|
`FACILITATOR_TIMEOUT_MS` accepts integers from 1 to 300000, default 90000.
|
|
@@ -207,11 +277,26 @@ to enable web browsers, dApps, and AI agent frontends to make paid cross-origin
|
|
|
207
277
|
other OPTIONS requests still require payment. Upstream CORS headers are stripped
|
|
208
278
|
so the wrapper controls origin policy. CORS is not server-side authentication.
|
|
209
279
|
- `402 Payment Required` challenge responses and successful responses expose
|
|
210
|
-
`Payment-Required`, `Payment-Response`, `Retry-After`, `X-Request-ID`, allowing browser `fetch`
|
|
280
|
+
`Payment-Required`, `Payment-Response`, `Retry-After`, `X-Request-ID`, `X-Response-Time`, allowing browser `fetch`
|
|
211
281
|
clients to inspect payment requirements and payment settlement tokens.
|
|
282
|
+
Settlement refusals and facilitator errors also retain these CORS headers, so
|
|
283
|
+
allowed browser clients can read the actual failure response and any failure receipt.
|
|
212
284
|
- When `CORS_ORIGIN` is unset (the default), CORS middleware is omitted entirely
|
|
213
285
|
with zero overhead and backwards-compatible behavior.
|
|
214
286
|
|
|
287
|
+
### Graceful shutdown (added in 0.3.3)
|
|
288
|
+
|
|
289
|
+
On receiving `SIGINT` or `SIGTERM` (e.g. during container restarts or deployments),
|
|
290
|
+
the CLI server immediately stops accepting new connections via `server.stop(false)`,
|
|
291
|
+
allowing in-flight paid requests and settlement handshakes to drain cleanly before
|
|
292
|
+
the process exits. If in-flight requests do not complete within `SHUTDOWN_TIMEOUT_MS`
|
|
293
|
+
(default 10000ms), connections are forcibly closed to prevent hanging deployments.
|
|
294
|
+
|
|
295
|
+
### Liveness probe and timing instrumentation (added in 0.3.3)
|
|
296
|
+
|
|
297
|
+
- `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.
|
|
298
|
+
- `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.
|
|
299
|
+
|
|
215
300
|
### Commands
|
|
216
301
|
|
|
217
302
|
```sh
|
|
@@ -240,3 +325,19 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for local checks and
|
|
|
240
325
|
[docs/week-1.md](docs/week-1.md) for the bounty scope and evidence checklist.
|
|
241
326
|
AI tools assisted development; BrK reviews and owns the contribution. Original
|
|
242
327
|
wrapper/configuration/test work is distinguished from upstream SDK functionality.
|
|
328
|
+
|
|
329
|
+
### Operational endpoint scope
|
|
330
|
+
|
|
331
|
+
`/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.
|
|
332
|
+
|
|
333
|
+
`/.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.
|
|
334
|
+
|
|
335
|
+
Access logs omit query strings, bodies and payment signatures. `clientIp` uses the same resolved identity as the firewall and rate limiter. JSON is recommended for production.
|
|
336
|
+
|
|
337
|
+
### Client IP and reverse proxies
|
|
338
|
+
|
|
339
|
+
Socket peer addresses are used by default (`TRUST_PROXY_HEADERS=false`). Direct clients cannot change their identity with forwarding headers. Enable `TRUST_PROXY_HEADERS=true` only behind an ingress that replaces inbound forwarding headers. Set `TRUSTED_PROXY_CIDRS` (comma-separated IPs or CIDRs) to restrict trusted peers; X-Forwarded-For is then read from right to left until the first untrusted hop. Without that list, the explicit legacy flag trusts forwarding claims and requires an isolated ingress. Missing or malformed claims fall back to the socket peer. Programmatic callers can provide `AppOptions.clientIp`; otherwise they must pass the socket peer as `c.env.clientIp`.
|
|
340
|
+
|
|
341
|
+
### Community component review
|
|
342
|
+
|
|
343
|
+
The next release includes optional library components and security corrections described in [the PR review report](docs/pr-review-2026-11-04.md). Utilities require explicit integration; adding a helper does not automatically enable dynamic prices, cached payment authorization, webhooks, sessions, distributed limiting or response compression. Forwarded client IP headers are disabled by default; configure trusted proxies explicitly when deploying behind an ingress.
|
package/README.zh-CN.md
CHANGED
|
@@ -29,12 +29,14 @@ bun run example
|
|
|
29
29
|
bun run start
|
|
30
30
|
curl -i http://localhost:8080/healthz
|
|
31
31
|
curl -i http://localhost:8080/readyz
|
|
32
|
+
curl -i http://localhost:8080/.well-known/x402
|
|
33
|
+
curl -i http://localhost:8080/stats
|
|
32
34
|
curl -i 'http://localhost:8080/v1/echo?message=hello'
|
|
33
35
|
```
|
|
34
36
|
|
|
35
|
-
`/healthz` 返回 200,且不会访问 facilitator
|
|
37
|
+
`/healthz` 返回 200,且不会访问 facilitator。`/.well-known/x402` 暴露免付费的协议与定价元数据(Kite 网络、代币合约与精度、原子价格与收款地址),供自主 AI Agent 自动发现。`/readyz` 会实际调用
|
|
36
38
|
facilitator 的 `/supported` 接口,只有当前配置的 Kite 网络、x402 v2 和 exact 模式均被支持时才返回
|
|
37
|
-
200;这不保证上游就绪或实际结算成功。`/v1/echo` 在 facilitator 可访问并支持
|
|
39
|
+
200;这不保证上游就绪或实际结算成功。`/stats` 返回运行指标(运行秒数、当前并发占用率、请求总量、挑战数与成功数),携带 `Cache-Control: no-store` 且无需访问 facilitator。`/v1/echo` 在 facilitator 可访问并支持
|
|
38
40
|
所选网络时,未付款请求会返回带有 x402 v2 `PAYMENT-REQUIRED` 的 402。如果 facilitator
|
|
39
41
|
不可用,会返回 503;未完成付款验证前,代理不会调用上游。
|
|
40
42
|
|
|
@@ -67,22 +69,25 @@ Bun.serve({ port: config.port, fetch: app.fetch });
|
|
|
67
69
|
|
|
68
70
|
## 配置项
|
|
69
71
|
|
|
70
|
-
| 变量 | 默认值 | 说明
|
|
71
|
-
| ------------------------- | ------------------------------------ |
|
|
72
|
-
| `PAY_TO` | 必填 | 非零 EVM 收款地址
|
|
73
|
-
| `UPSTREAM_URL` | 必填 | 固定的 HTTP(S) origin,不得包含路径、凭据或查询参数
|
|
74
|
-
| `KITE_NETWORK` | `mainnet` | `mainnet` 或 `testnet`
|
|
75
|
-
| `PRICE_USD` | `0.001` | 正小数,最多 6 位小数,可带 `$` 前缀
|
|
76
|
-
| `FACILITATOR_URL` | `https://facilitator.pieverse.io/v2` | 保留 `/v2` 后缀
|
|
77
|
-
| `UPSTREAM_AUTH_HEADER` | `Authorization` | 发给上游的认证头名称
|
|
78
|
-
| `UPSTREAM_AUTH_VALUE` | 空 | 服务端上游凭据,会覆盖买方提供的同名值
|
|
79
|
-
| `SERVICE_DESCRIPTION` | Kite paid API description | 写入付款挑战的服务说明
|
|
80
|
-
| `PORT` | `8080` | 代理监听端口
|
|
81
|
-
| `UPSTREAM_TIMEOUT_MS` | `10000` | 请求体读取、上游响应头和响应体的超时时间
|
|
82
|
-
| `MAX_BODY_BYTES` | `1048576` | 请求和响应大小限制,最大 16 MiB
|
|
83
|
-
| `MAX_CONCURRENT_REQUESTS` | `64` | `/v1/*` 路径的并发准入上限(1 至 10000)
|
|
84
|
-
| `FACILITATOR_TIMEOUT_MS` | `90000` | 请求 facilitator 的网络超时毫秒数(1 至 300000)
|
|
85
|
-
| `CORS_ORIGIN` | 未配置 | 允许的跨域来源(`*` 或 HTTP(S) origin),支持浏览器
|
|
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 |
|
|
86
91
|
|
|
87
92
|
除本地开发外,上游和 facilitator 必须使用 HTTPS。示例 `.env` 明确选择 testnet,
|
|
88
93
|
但兼容性默认值仍是 mainnet。本代理不需要钱包私钥。
|
|
@@ -118,8 +123,28 @@ Bun.serve({ port: config.port, fetch: app.fetch });
|
|
|
118
123
|
- `/healthz` 只表示进程存活,不代表上游或 facilitator 已就绪。可用 `/readyz` 检查 facilitator 是否可达且支持所配置的网络。
|
|
119
124
|
- 每个响应都带 `X-Request-ID` 头。调用方传入自己的 `x-request-id`(仅限字母、数字、`.`、`_`、`~`、`-`,最长 128 字符)会被原样回显并透传上游,使 agent、wrapper 与上游日志可用同一 ID 关联;不安全的值会被替换为新 UUID。
|
|
120
125
|
|
|
126
|
+
活跃 nonce 租约随请求生命周期保留,不再由 `inFlightTtlMs` 到期回收。中间件通过拥有者绑定的租约释放或提交,旧请求无法修改替换租约。已消费记录仍为进程内、有限保留时间;持久化与多实例协调需要应用提供。
|
|
127
|
+
|
|
121
128
|
## 验证
|
|
122
129
|
|
|
130
|
+
### 已支付请求的幂等重试
|
|
131
|
+
|
|
132
|
+
同时发送 `Idempotency-Key`(1–128 个字母、数字、`_`、`.`、`:`、`~` 或 `-`)与
|
|
133
|
+
`PAYMENT-SIGNATURE`,可缓存结算成功的 2xx 响应。重试必须携带相同的幂等键、原始支付凭证、
|
|
134
|
+
HTTP 方法、完整 URL(包含查询参数)、请求体字节与透传上游的请求头;每次的 `X-Request-ID`
|
|
135
|
+
可以不同。完全匹配时返回缓存结果及支付回执,附带 `Idempotent-Replayed: true`,
|
|
136
|
+
不会再次验证、请求上游或结算;注入 `PaymentNonceReplayGuard` 后也支持这种重试。
|
|
137
|
+
|
|
138
|
+
仅凭幂等键无法读取付费结果,缺少付款或付款无效仍返回 402。不同支付凭证的缓存彼此隔离。
|
|
139
|
+
相同凭证与幂等键对应的请求内容发生变化,或原请求仍在执行时,返回
|
|
140
|
+
`409 {"error":"idempotency_conflict"}`。缓存索引对凭证和服务配置进行哈希,
|
|
141
|
+
不以原始签名作为键;注入共享缓存时,不同服务配置也彼此隔离。
|
|
142
|
+
|
|
143
|
+
默认缓存保存在内存中,已完成响应的有效期为 10 分钟,上限为 1000 条记录和 32 MiB 响应体,
|
|
144
|
+
容量不足可能提前淘汰。只有结算成功的响应才会进入缓存。进程重启、淘汰、过期、上游失败、
|
|
145
|
+
结算失败或结果不明时,无法保证 exactly-once;仍需上游幂等支持,扣款不明时先核对再重试。
|
|
146
|
+
此行为修正了此前允许不携带原始支付凭证、仅凭幂等键读取缓存结果的逻辑。
|
|
147
|
+
|
|
123
148
|
### 并发准入限制(0.2.0 新增)
|
|
124
149
|
|
|
125
150
|
`MAX_CONCURRENT_REQUESTS` 默认 64,接受 1 至 10000 的整数。每个 `createApp()` 实例
|
|
@@ -132,6 +157,8 @@ Bun.serve({ port: config.port, fetch: app.fetch });
|
|
|
132
157
|
恶意流量仍应通过入口限流控制。不能把所有 503 都当成可安全重试:只有本代理的
|
|
133
158
|
`service_busy` 表示付款前拒绝;结算错误仍需先核对结果。
|
|
134
159
|
|
|
160
|
+
防火墙规则支持 IPv4、IPv6 和 CIDR,两侧均处理压缩 IPv6 与 IPv4 映射地址。非法规则在配置阶段报错;启用过滤时非法客户端地址被拒绝,阻止规则优先于允许规则。
|
|
161
|
+
|
|
135
162
|
### Facilitator 超时(0.3.0 新增)
|
|
136
163
|
|
|
137
164
|
`FACILITATOR_TIMEOUT_MS` 默认 90000 毫秒,允许 1 至 300000 的整数。
|
|
@@ -159,8 +186,23 @@ Bun.serve({ port: config.port, fetch: app.fetch });
|
|
|
159
186
|
|
|
160
187
|
- 预检 `OPTIONS` 请求返回 `204 No Content` 及对应的 `Access-Control-Allow-*` 头部,无需先触发付费。
|
|
161
188
|
- 付费挑战 `402 Payment Required` 与正常响应均通过 `Access-Control-Expose-Headers` 暴露 `Payment-Required`、`Payment-Response`、`Retry-After`,方便浏览器端 `fetch` 读取付款挑战及结算回执。
|
|
189
|
+
- 结算拒绝和 facilitator 错误响应也保留 CORS 头部,使允许的浏览器客户端可以读取实际错误及失败回执(如有)。
|
|
162
190
|
- 未配置 `CORS_ORIGIN` 时(默认),不注册 CORS 中间件,保持零额外开销与向下兼容。
|
|
163
191
|
|
|
192
|
+
### 优雅停机 (Graceful Shutdown)(0.3.3 新增)
|
|
193
|
+
|
|
194
|
+
在接收到 `SIGINT` 或 `SIGTERM` 信号时(如容器重启、停止或部署滚动更新),CLI 服务器会通过 `server.stop(false)` 立即停止接收新的入站连接,并等待当前正在执行的付费请求、上游代理及结算流程平滑完成。如果正在进行的请求在 `SHUTDOWN_TIMEOUT_MS`(默认 10000 毫秒)内仍未完成,服务将强制关闭未完成连接并退出,防止挂起部署。
|
|
195
|
+
|
|
196
|
+
### 存活探针与耗时追踪 (Liveness Probe & Response Timing)(0.3.3 新增)
|
|
197
|
+
|
|
198
|
+
- `GET /livez`: 标准 Kubernetes 存活探针,立即返回 `200 {"ok":true,"status":"alive"}` 及 `Cache-Control: no-store`。该探针无需任何网络 I/O,完全独立于 facilitator 可用性,可有效防止容器编排平台在 facilitator 瞬时波动时误杀容器。
|
|
199
|
+
- `X-Response-Time`: 在所有入站响应中添加毫秒级处理耗时头部(如 `12.45ms`),并通过 CORS `Access-Control-Expose-Headers` 暴露给前端 dApp 与监控系统,便于准确区分网络传输、上游响应与链上结算各阶段延迟。
|
|
200
|
+
|
|
201
|
+
### 安全响应头与结构化 404(0.3.3 新增)
|
|
202
|
+
|
|
203
|
+
- 所有响应均自动携带基础 HTTP 安全头部(`X-Content-Type-Options: nosniff`、`X-Frame-Options: SAMEORIGIN`、`X-XSS-Protection: 0`、`Referrer-Policy: no-referrer`),防御 MIME 嗅探、点击劫持与跨站脚本威胁。
|
|
204
|
+
- 未匹配路由统一返回结构化 JSON 响应 `404 {"error":"not_found"}`,并附加 `Cache-Control: no-store` 头部,取代默认纯文本报错。
|
|
205
|
+
|
|
164
206
|
### 检查命令
|
|
165
207
|
|
|
166
208
|
```sh
|
|
@@ -189,3 +231,9 @@ AI 工具参与了开发;BrK 审核并负责此贡献。项目自己的 Wrappe
|
|
|
189
231
|
请求 ID 是调用方可控的关联标签,不能用作身份凭证或付款去重键。生成的 UUID 只标记代理响应;非法调用方 ID 不会透传上游。
|
|
190
232
|
仅同时携带 Origin 和 Access-Control-Request-Method 的 OPTIONS 属于免费预检,其他 OPTIONS 仍需付款。
|
|
191
233
|
代理会过滤上游的 CORS 响应头,保持自身来源策略;CORS 不是服务器端鉴权。跨域响应也暴露 X-Request-ID。
|
|
234
|
+
|
|
235
|
+
客户端 IP 默认取连接地址(`TRUST_PROXY_HEADERS=false`),转发头不会改变直连客户端的身份。仅在入口代理替换转发头时启用 `TRUST_PROXY_HEADERS=true`,建议同时配置 `TRUSTED_PROXY_CIDRS`(逗号分隔的 IP/CIDR);此时从连接端向前解析代理链,到第一个非可信节点停止。未配置可信列表的兼容模式依赖隔离的入口。缺失或非法转发头回退连接地址;日志、防火墙和限流共用此身份。
|
|
236
|
+
|
|
237
|
+
### 社区组件审查
|
|
238
|
+
|
|
239
|
+
下一版本包含的可选组件、安全修正与使用边界见[PR 审查报告](docs/pr-review-2026-11-04.md)。这些工具需要显式接入,不会自动启用动态定价、付款验证缓存、Webhook、会话、分布式限流或响应压缩。默认使用连接 IP;部署在反向代理后时需显式配置可信代理。
|
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;
|