kite-x402-hono 0.3.2 → 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
@@ -12,3 +12,6 @@ PORT=8080
12
12
  # MAX_CONCURRENT_REQUESTS=64
13
13
  # FACILITATOR_TIMEOUT_MS=90000
14
14
  # CORS_ORIGIN=*
15
+ # SHUTDOWN_TIMEOUT_MS=10000
16
+
17
+ # MAINTENANCE_MODE=false
package/CHANGELOG.md CHANGED
@@ -1,14 +1,30 @@
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
+
3
17
  ## 0.3.2
4
18
 
5
19
  - Forward conditional 304 responses through settlement while refusing other 3xx statuses.
6
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.
7
22
  - Validate readiness protocol/version and CORS configuration; preserve paid OPTIONS handling.
8
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.
9
24
  - Allow preflight `OPTIONS` requests to receive `204 No Content` with appropriate `Access-Control-Allow-*` headers without requiring payments.
10
25
  - Expose essential x402 payment headers (`Payment-Required`, `Payment-Response`, `Retry-After`) to cross-origin browser clients.
11
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.
12
28
  - Update English and Chinese documentation and `.env.example`.
13
29
 
14
30
  ## 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. `/readyz` actually
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. `/v1/echo` returns
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` is process liveness, not proof of upstream/facilitator readiness.
140
- Use `/readyz` to check that the facilitator is reachable and offers the
141
- configured network, x402 v2 and exact scheme. Each probe contacts the facilitator;
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,6 +168,11 @@ 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.
152
176
 
153
177
  ## Verification
154
178
 
@@ -168,6 +192,19 @@ for upstream capacity and response sizes; use edge rate limits for hostile traff
168
192
  Do not treat every 503 as safe to retry: only this wrapper's `service_busy`
169
193
  response denotes pre-payment rejection. Settlement errors still need reconciliation.
170
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
+
171
208
  ### Facilitator deadlines (added in 0.3.0)
172
209
 
173
210
  `FACILITATOR_TIMEOUT_MS` accepts integers from 1 to 300000, default 90000.
@@ -207,11 +244,26 @@ to enable web browsers, dApps, and AI agent frontends to make paid cross-origin
207
244
  other OPTIONS requests still require payment. Upstream CORS headers are stripped
208
245
  so the wrapper controls origin policy. CORS is not server-side authentication.
209
246
  - `402 Payment Required` challenge responses and successful responses expose
210
- `Payment-Required`, `Payment-Response`, `Retry-After`, `X-Request-ID`, allowing browser `fetch`
247
+ `Payment-Required`, `Payment-Response`, `Retry-After`, `X-Request-ID`, `X-Response-Time`, allowing browser `fetch`
211
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.
212
251
  - When `CORS_ORIGIN` is unset (the default), CORS middleware is omitted entirely
213
252
  with zero overhead and backwards-compatible behavior.
214
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
+
215
267
  ### Commands
216
268
 
217
269
  ```sh
@@ -240,3 +292,11 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for local checks and
240
292
  [docs/week-1.md](docs/week-1.md) for the bounty scope and evidence checklist.
241
293
  AI tools assisted development; BrK reviews and owns the contribution. Original
242
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
@@ -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。`/readyz` 会实际调用
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。本代理不需要钱包私钥。
@@ -159,8 +164,23 @@ Bun.serve({ port: config.port, fetch: app.fetch });
159
164
 
160
165
  - 预检 `OPTIONS` 请求返回 `204 No Content` 及对应的 `Access-Control-Allow-*` 头部,无需先触发付费。
161
166
  - 付费挑战 `402 Payment Required` 与正常响应均通过 `Access-Control-Expose-Headers` 暴露 `Payment-Required`、`Payment-Response`、`Retry-After`,方便浏览器端 `fetch` 读取付款挑战及结算回执。
167
+ - 结算拒绝和 facilitator 错误响应也保留 CORS 头部,使允许的浏览器客户端可以读取实际错误及失败回执(如有)。
162
168
  - 未配置 `CORS_ORIGIN` 时(默认),不注册 CORS 中间件,保持零额外开销与向下兼容。
163
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
+
164
184
  ### 检查命令
165
185
 
166
186
  ```sh
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;
package/dist/app.js CHANGED
@@ -1,13 +1,32 @@
1
1
  import { Hono } from "hono";
2
2
  import { cors } from "hono/cors";
3
+ import { secureHeaders } from "hono/secure-headers";
3
4
  import { paymentMiddlewareFromHTTPServer, x402HTTPResourceServer, x402ResourceServer, } from "@x402/hono";
4
5
  import { HTTPFacilitatorClient, } from "@x402/core/server";
5
6
  import { ExactEvmScheme } from "@x402/evm/exact/server";
6
7
  import { loadConfig, parseCorsOrigin } from "./config.js";
7
8
  import { parsePrice } from "./networks.js";
8
9
  import { proxy, REQUEST_ID_PATTERN } from "./proxy.js";
10
+ import { TokenBucketRateLimiter, createRateLimiterMiddleware, } from "./rate-limiter.js";
11
+ import { evaluateIpFilter, extractClientIp } from "./firewall.js";
12
+ import { createPaymentProtection } from "./payment-protection.js";
13
+ import { createAccessLogger } from "./logger.js";
9
14
  export function createApp(config = loadConfig(), options = {}) {
10
15
  const app = new Hono();
16
+ // Attach standard security headers to protect against MIME-sniffing,
17
+ // clickjacking, and XSS across all routes.
18
+ app.use("*", secureHeaders());
19
+ const startTime = Date.now();
20
+ let totalRequests = 0;
21
+ let activeRequests = 0;
22
+ const statusCounts = {};
23
+ if (config.logEnabled !== false) {
24
+ app.use("*", createAccessLogger({
25
+ format: config.logFormat,
26
+ enabled: config.logEnabled,
27
+ skipHealthz: true,
28
+ }, options.logSink));
29
+ }
11
30
  // Label every response — paid answers, 402 challenges, guard-rail rejections
12
31
  // and errors alike — with a request ID the caller can quote back in issues
13
32
  // and correlate across agent, wrapper and upstream logs. A caller-supplied
@@ -16,12 +35,26 @@ export function createApp(config = loadConfig(), options = {}) {
16
35
  // gets a freshly minted UUID. Caller-supplied IDs also travel upstream,
17
36
  // because x-request-id is not on the proxy's blocked list.
18
37
  app.use("*", async (c, next) => {
38
+ const start = performance.now();
39
+ totalRequests++;
40
+ activeRequests++;
19
41
  const inbound = c.req.header("x-request-id");
20
42
  const requestId = inbound && REQUEST_ID_PATTERN.test(inbound)
21
43
  ? inbound
22
44
  : crypto.randomUUID();
23
- await next();
45
+ try {
46
+ await next();
47
+ }
48
+ finally {
49
+ activeRequests--;
50
+ const statusGroup = `${Math.floor(c.res.status / 100)}xx`;
51
+ statusCounts[statusGroup] = (statusCounts[statusGroup] ?? 0) + 1;
52
+ statusCounts[String(c.res.status)] =
53
+ (statusCounts[String(c.res.status)] ?? 0) + 1;
54
+ }
55
+ const durationMs = performance.now() - start;
24
56
  c.res.headers.set("x-request-id", requestId);
57
+ c.res.headers.set("x-response-time", `${durationMs.toFixed(2)}ms`);
25
58
  });
26
59
  if (config.corsOrigin) {
27
60
  const corsMiddleware = cors({
@@ -42,6 +75,7 @@ export function createApp(config = loadConfig(), options = {}) {
42
75
  "X-Payment",
43
76
  "X-Requested-With",
44
77
  "X-Request-ID",
78
+ "Idempotency-Key",
45
79
  ],
46
80
  exposeHeaders: [
47
81
  "Payment-Required",
@@ -50,19 +84,70 @@ export function createApp(config = loadConfig(), options = {}) {
50
84
  "X-Payment-Response",
51
85
  "Retry-After",
52
86
  "X-Request-ID",
87
+ "X-Response-Time",
88
+ "Idempotent-Replayed",
53
89
  ],
54
90
  maxAge: 86400,
55
91
  });
56
- app.use("*", (c, next) => {
92
+ app.use("*", async (c, next) => {
57
93
  // Only browser preflight bypasses the paid OPTIONS route.
58
- if (c.req.method === "OPTIONS" &&
59
- !(c.req.header("origin") &&
60
- c.req.header("access-control-request-method"))) {
94
+ if (c.req.method === "OPTIONS") {
95
+ if (c.req.header("origin") &&
96
+ c.req.header("access-control-request-method")) {
97
+ return corsMiddleware(c, next);
98
+ }
61
99
  return next();
62
100
  }
63
- return corsMiddleware(c, next);
101
+ // Settlement errors can replace the response in the payment middleware.
102
+ // Apply CORS to the final response so browsers can read those failures too.
103
+ await next();
104
+ return corsMiddleware(c, async () => { });
105
+ });
106
+ }
107
+ const getClientIp = options.clientIp ??
108
+ ((c) => config.trustProxyHeaders !== false
109
+ ? extractClientIp(c.req.raw.headers)
110
+ : (c.env?.clientIp ?? null));
111
+ if (config.firewallAllowlist?.length || config.firewallBlocklist?.length) {
112
+ app.use("/v1/*", async (c, next) => {
113
+ const ip = getClientIp(c);
114
+ const verdict = evaluateIpFilter(ip, {
115
+ allowlist: config.firewallAllowlist,
116
+ blocklist: config.firewallBlocklist,
117
+ });
118
+ if (!verdict.allowed)
119
+ return c.json({
120
+ error: "forbidden_ip",
121
+ reason: verdict.reason,
122
+ ip: ip ?? "unknown",
123
+ }, 403, { "cache-control": "no-store" });
124
+ return next();
64
125
  });
65
126
  }
127
+ if (config.rateLimitRps) {
128
+ const rateLimiter = new TokenBucketRateLimiter(config.rateLimitBurst === undefined
129
+ ? { rps: config.rateLimitRps }
130
+ : { rps: config.rateLimitRps, burst: config.rateLimitBurst });
131
+ app.use("/v1/*", async (c, next) => {
132
+ const clientIp = getClientIp(c) ?? "global";
133
+ const decision = rateLimiter.consume(clientIp);
134
+ if (!decision.allowed) {
135
+ c.header("Retry-After", String(decision.resetSeconds));
136
+ c.header("X-RateLimit-Limit", String(decision.limit));
137
+ c.header("X-RateLimit-Remaining", "0");
138
+ c.header("X-RateLimit-Reset", String(decision.resetSeconds));
139
+ c.header("Cache-Control", "no-store");
140
+ return c.json({ error: "rate_limit_exceeded" }, 429);
141
+ }
142
+ await next();
143
+ c.res.headers.set("X-RateLimit-Limit", String(decision.limit));
144
+ c.res.headers.set("X-RateLimit-Remaining", String(decision.remaining));
145
+ c.res.headers.set("X-RateLimit-Reset", String(decision.resetSeconds));
146
+ });
147
+ }
148
+ if (options.rateLimiter) {
149
+ app.use("/v1/*", createRateLimiterMiddleware(options.rateLimiter));
150
+ }
66
151
  const facilitatorTimeoutMs = config.facilitatorTimeoutMs ?? 90000;
67
152
  if (!Number.isInteger(facilitatorTimeoutMs) ||
68
153
  facilitatorTimeoutMs < 1 ||
@@ -74,15 +159,25 @@ export function createApp(config = loadConfig(), options = {}) {
74
159
  throw new Error("maxConcurrentRequests must be an integer between 1 and 10000");
75
160
  }
76
161
  let active = 0;
162
+ const startedAt = Date.now();
163
+ const metrics = {
164
+ total: 0,
165
+ successful: 0,
166
+ challenges: 0,
167
+ busy: 0,
168
+ tooLarge: 0,
169
+ };
77
170
  // Reject a body that is already known to exceed the configured limit before
78
171
  // contacting the facilitator. Chunked or incorrectly declared bodies remain
79
172
  // protected by proxy's bounded stream reader.
80
173
  app.use("/v1/*", async (c, next) => {
174
+ metrics.total++;
81
175
  if (!["GET", "HEAD"].includes(c.req.method)) {
82
176
  const declaredLength = c.req.header("content-length");
83
177
  if (declaredLength &&
84
178
  /^\d+$/.test(declaredLength) &&
85
179
  BigInt(declaredLength) > BigInt(config.maxBodyBytes)) {
180
+ metrics.tooLarge++;
86
181
  c.header("Cache-Control", "no-store");
87
182
  return c.json({ error: "request_too_large" }, 413);
88
183
  }
@@ -93,6 +188,7 @@ export function createApp(config = loadConfig(), options = {}) {
93
188
  // Never queue payment-bearing requests or retain their signatures.
94
189
  app.use("/v1/*", async (c, next) => {
95
190
  if (active >= capacity) {
191
+ metrics.busy++;
96
192
  c.header("Retry-After", "1");
97
193
  c.header("Cache-Control", "no-store");
98
194
  return c.json({ error: "service_busy" }, 503);
@@ -110,7 +206,8 @@ export function createApp(config = loadConfig(), options = {}) {
110
206
  url: config.facilitatorUrl,
111
207
  timeoutMs: facilitatorTimeoutMs,
112
208
  });
113
- const server = new x402ResourceServer(facilitator).register(config.chain.network, new ExactEvmScheme());
209
+ const protection = createPaymentProtection(facilitator, config, options);
210
+ const server = new x402ResourceServer(protection.facilitator).register(config.chain.network, new ExactEvmScheme());
114
211
  const httpServer = new x402HTTPResourceServer(server, {
115
212
  "/v1/*": {
116
213
  accepts: {
@@ -133,9 +230,62 @@ export function createApp(config = loadConfig(), options = {}) {
133
230
  asset: config.chain.symbol,
134
231
  price: `$${config.price}`,
135
232
  }));
233
+ // Standard Kubernetes liveness probe (independent of facilitator and network dependencies)
234
+ app.get("/livez", (c) => c.json({
235
+ ok: true,
236
+ status: "alive",
237
+ }, 200, { "cache-control": "no-store" }));
238
+ // Public runtime diagnostics
239
+ app.get("/metrics", (c) => c.json({
240
+ uptime_seconds: Math.floor((Date.now() - startTime) / 1000),
241
+ total_requests: totalRequests,
242
+ active_requests: activeRequests,
243
+ status_counts: statusCounts,
244
+ network: config.chain.network,
245
+ asset: config.chain.symbol,
246
+ memory: {
247
+ rss: process.memoryUsage().rss,
248
+ heap_used: process.memoryUsage().heapUsed,
249
+ heap_total: process.memoryUsage().heapTotal,
250
+ },
251
+ }, 200, { "cache-control": "no-store" }));
252
+ // Machine-readable capability and pricing discovery for autonomous agents
253
+ app.get("/.well-known/x402", (c) => {
254
+ const priceInfo = parsePrice(config.price, config.chain);
255
+ return c.json({
256
+ x402Version: 2,
257
+ scheme: "exact",
258
+ network: config.chain.network,
259
+ asset: {
260
+ address: config.chain.asset,
261
+ symbol: config.chain.symbol,
262
+ decimals: config.chain.decimals,
263
+ name: config.chain.name,
264
+ version: config.chain.version,
265
+ },
266
+ pricing: {
267
+ usd: `$${config.price}`,
268
+ atomicAmount: priceInfo.amount,
269
+ payTo: config.payTo,
270
+ },
271
+ facilitator: config.facilitatorUrl,
272
+ description: config.description,
273
+ limits: {
274
+ maxBodyBytes: config.maxBodyBytes,
275
+ upstreamTimeoutMs: config.timeoutMs,
276
+ maxConcurrentRequests: config.maxConcurrentRequests ?? 64,
277
+ facilitatorTimeoutMs: config.facilitatorTimeoutMs ?? 90000,
278
+ },
279
+ });
280
+ });
136
281
  // Readiness is stronger than liveness: the process is up and the facilitator
137
282
  // advertises the configured protocol and network; this does not prove settlement.
138
283
  app.get("/readyz", async (c) => {
284
+ if (config.maintenanceMode) {
285
+ return c.json({ ok: false, error: "maintenance_mode" }, 503, {
286
+ "cache-control": "no-store",
287
+ });
288
+ }
139
289
  let supported;
140
290
  try {
141
291
  supported = await facilitator.getSupported();
@@ -162,8 +312,38 @@ export function createApp(config = loadConfig(), options = {}) {
162
312
  price: `$${config.price}`,
163
313
  }, 200, { "cache-control": "no-store" });
164
314
  });
315
+ // Stats returns operational metrics: uptime, capacity utilization, and request outcomes.
316
+ app.get("/stats", (c) => c.json({
317
+ ok: true,
318
+ uptime_seconds: Math.floor((Date.now() - startedAt) / 1000),
319
+ capacity: {
320
+ limit: capacity,
321
+ active,
322
+ },
323
+ traffic: {
324
+ total: metrics.total,
325
+ successful: metrics.successful,
326
+ challenges: metrics.challenges,
327
+ busy: metrics.busy,
328
+ too_large: metrics.tooLarge,
329
+ },
330
+ network: {
331
+ chain: config.chain.network,
332
+ asset: config.chain.symbol,
333
+ price: `$${config.price}`,
334
+ },
335
+ }, 200, { "cache-control": "no-store" }));
165
336
  app.use("/v1/*", async (c, next) => {
166
337
  c.header("cache-control", "no-store");
338
+ if (config.maintenanceMode) {
339
+ return c.json({
340
+ error: "maintenance_mode",
341
+ message: "Service is currently undergoing maintenance",
342
+ }, 503, {
343
+ "retry-after": "60",
344
+ "cache-control": "no-store",
345
+ });
346
+ }
167
347
  try {
168
348
  initialization ??= httpServer.initialize().catch((error) => {
169
349
  initialization = undefined;
@@ -174,9 +354,20 @@ export function createApp(config = loadConfig(), options = {}) {
174
354
  catch {
175
355
  return c.json({ error: "facilitator_unavailable" }, 503);
176
356
  }
177
- return payments(c, next);
357
+ const result = await protection.run(c, () => payments(c, next));
358
+ const status = (result instanceof Response ? result.status : undefined) ?? c.res?.status;
359
+ if (status === 402) {
360
+ metrics.challenges++;
361
+ }
362
+ if (status >= 200 && status < 300)
363
+ metrics.successful++;
364
+ return result;
365
+ });
366
+ app.all("/v1/*", async (c) => {
367
+ const response = await proxy(c.req.raw, config, options.fetchUpstream ?? ((request) => fetch(request)));
368
+ return response;
178
369
  });
179
- app.all("/v1/*", (c) => proxy(c.req.raw, config, options.fetchUpstream ?? ((request) => fetch(request))));
370
+ app.notFound((c) => c.json({ error: "not_found" }, 404, { "cache-control": "no-store" }));
180
371
  app.onError(() => Response.json({ error: "internal_error" }, { status: 500, headers: { "cache-control": "no-store" } }));
181
372
  return app;
182
373
  }
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, MAX_CONCURRENT_REQUESTS, FACILITATOR_TIMEOUT_MS, CORS_ORIGIN\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, FACILITATOR_TIMEOUT_MS, CORS_ORIGIN, SHUTDOWN_TIMEOUT_MS\nSee README.md for configuration and examples.");
6
6
  }
7
7
  else {
8
8
  try {
@@ -10,16 +10,31 @@ else {
10
10
  const app = createApp(config);
11
11
  const server = Bun.serve({
12
12
  port: config.port,
13
- fetch: app.fetch,
13
+ fetch: (request, server) => app.fetch(request, {
14
+ clientIp: server.requestIP(request)?.address ?? null,
15
+ }),
14
16
  maxRequestBodySize: config.maxBodyBytes,
15
17
  idleTimeout: 0,
16
18
  });
17
19
  console.log(`Kite x402 Hono listening at ${server.url} (${config.chain.network})`);
18
- const shutdown = () => {
19
- void server.stop(true);
20
+ let isShuttingDown = false;
21
+ const shutdown = (signal) => {
22
+ if (isShuttingDown)
23
+ return;
24
+ isShuttingDown = true;
25
+ console.log(`Received ${signal}, initiating graceful shutdown...`);
26
+ const stopped = server.stop(false);
27
+ const timeoutMs = config.shutdownTimeoutMs ?? 10000;
28
+ const timer = setTimeout(() => {
29
+ console.warn("Graceful shutdown timeout exceeded, forcing connection close.");
30
+ void server.stop(true);
31
+ process.exit(0);
32
+ }, timeoutMs);
33
+ timer.unref?.();
34
+ void stopped.finally(() => clearTimeout(timer));
20
35
  };
21
- process.once("SIGINT", shutdown);
22
- process.once("SIGTERM", shutdown);
36
+ process.once("SIGINT", () => shutdown("SIGINT"));
37
+ process.once("SIGTERM", () => shutdown("SIGTERM"));
23
38
  }
24
39
  catch (error) {
25
40
  console.error(error instanceof Error ? error.message : "Unable to start wrapper");
package/dist/config.d.ts CHANGED
@@ -14,6 +14,15 @@ export interface Config {
14
14
  maxConcurrentRequests?: number;
15
15
  facilitatorTimeoutMs?: number;
16
16
  corsOrigin?: string | undefined;
17
+ shutdownTimeoutMs?: number | undefined;
18
+ rateLimitRps?: number | undefined;
19
+ rateLimitBurst?: number | undefined;
20
+ firewallAllowlist?: string[] | undefined;
21
+ firewallBlocklist?: string[] | undefined;
22
+ trustProxyHeaders?: boolean | undefined;
23
+ maintenanceMode?: boolean;
24
+ logFormat?: "json" | "dev" | undefined;
25
+ logEnabled?: boolean | undefined;
17
26
  }
18
27
  export declare function parseCorsOrigin(value: string): string;
19
28
  export declare function loadConfig(env?: Record<string, string | undefined>): Config;