kite-x402-hono 0.3.1 → 0.3.2

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,4 @@ PORT=8080
11
11
  # MAX_BODY_BYTES=1048576
12
12
  # MAX_CONCURRENT_REQUESTS=64
13
13
  # FACILITATOR_TIMEOUT_MS=90000
14
+ # CORS_ORIGIN=*
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.2
4
+
5
+ - Forward conditional 304 responses through settlement while refusing other 3xx statuses.
6
+ - Add facilitator readiness, response request IDs and early declared-body size checks.
7
+ - Validate readiness protocol/version and CORS configuration; preserve paid OPTIONS handling.
8
+ - 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
+ - Allow preflight `OPTIONS` requests to receive `204 No Content` with appropriate `Access-Control-Allow-*` headers without requiring payments.
10
+ - Expose essential x402 payment headers (`Payment-Required`, `Payment-Response`, `Retry-After`) to cross-origin browser clients.
11
+ - Add comprehensive CORS integration tests covering preflight, 402 challenges, paid responses, origin filtering, and configuration validation.
12
+ - Update English and Chinese documentation and `.env.example`.
13
+
3
14
  ## 0.3.1
4
15
 
5
16
  - Make rejected-body and redirect stream cleanup non-blocking so stalled producer
package/README.md CHANGED
@@ -30,10 +30,15 @@ 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
33
34
  curl -i 'http://localhost:8080/v1/echo?message=hello'
34
35
  ```
35
36
 
36
- `/healthz` returns 200 without contacting a facilitator. `/v1/echo` returns
37
+ `/healthz` returns 200 without contacting a facilitator. `/readyz` actually
38
+ calls the facilitator's `/supported` endpoint and returns 200 only when the
39
+ configured Kite network is offered with x402 v2 and the exact scheme, so orchestrators can distinguish
40
+ "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
37
42
  402 with an x402 v2 `PAYMENT-REQUIRED` header when the configured facilitator
38
43
  is reachable and supports the selected network. A facilitator outage returns
39
44
  503 instead; the upstream is never called without verified payment.
@@ -68,19 +73,22 @@ injection for tests. Never use a simulated facilitator in a production service.
68
73
 
69
74
  ## Configuration
70
75
 
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 |
76
+ | Variable | Default | Meaning |
77
+ | ------------------------- | ------------------------------------ | ------------------------------------------------------------------------------- |
78
+ | `PAY_TO` | Required | Nonzero EVM receiving address |
79
+ | `UPSTREAM_URL` | Required | Fixed HTTP(S) origin, with no path, credentials or query |
80
+ | `KITE_NETWORK` | `mainnet` | `mainnet` or `testnet` |
81
+ | `PRICE_USD` | `0.001` | Positive decimal, at most 6 fractional digits; optional `$` prefix |
82
+ | `FACILITATOR_URL` | `https://facilitator.pieverse.io/v2` | Keep the `/v2` suffix |
83
+ | `UPSTREAM_AUTH_HEADER` | `Authorization` | Upstream credential header name |
84
+ | `UPSTREAM_AUTH_VALUE` | Empty | Server-side credential; replaces buyer-supplied values |
85
+ | `SERVICE_DESCRIPTION` | Kite paid API description | Included in the payment challenge |
86
+ | `PORT` | `8080` | Wrapper port |
87
+ | `UPSTREAM_TIMEOUT_MS` | `10000` | Timeout for reading the request body, then separately for upstream headers/body |
88
+ | `MAX_BODY_BYTES` | `1048576` | Request and response byte limit; maximum 16 MiB |
89
+ | `MAX_CONCURRENT_REQUESTS` | `64` | Concurrency admission limit for `/v1/*` requests (1 to 10000) |
90
+ | `FACILITATOR_TIMEOUT_MS` | `90000` | Timeout in ms for facilitator network requests (1 to 300000) |
91
+ | `CORS_ORIGIN` | Unset | Allowed origin for CORS (`*` or HTTP(S) origin); enables browser dApp clients |
84
92
 
85
93
  HTTPS is required for upstream/facilitator URLs except localhost development.
86
94
  The example `.env` explicitly selects testnet; the compatibility default remains
@@ -100,7 +108,7 @@ integer arithmetic, including for testnet's 18 decimals.
100
108
  1. No payment or invalid payment: return 402; do not call the upstream.
101
109
  2. Verified payment: strip `/v1`, preserve the query/method/body, inject the
102
110
  configured upstream credential, and call the fixed upstream origin.
103
- 3. Upstream 2xx: buffer the bounded response, then ask the facilitator to settle.
111
+ 3. Upstream 2xx or conditional 304: buffer the bounded response, then ask the facilitator to settle.
104
112
  4. Successful settlement: return the upstream response and `PAYMENT-RESPONSE`.
105
113
  5. Upstream 4xx/5xx, timeout, oversized body or connection failure: do not settle.
106
114
  6. Settlement refusal: return the SDK failure response, withholding protected data.
@@ -112,18 +120,32 @@ Compatibility notes:
112
120
  - Unlike the reference template's general below-400 rule, this template **refuses
113
121
  upstream redirects** with 502, without settlement, so credentials cannot follow
114
122
  redirects to a different host. Use the final upstream origin directly.
123
+ Conditional `304 Not Modified` answers are not redirects and are forwarded, so
124
+ client-side `If-None-Match` / `If-Modified-Since` still works.
115
125
  - Payment headers, client authorization/cookies, proxy headers and hop-by-hop
116
126
  headers are removed. Upstream authentication response headers and cookies are
117
127
  also stripped. The upstream is trusted: do not select one that echoes secrets
118
128
  into response bodies or unrelated headers.
119
129
  - Response buffering is deliberate. Streaming/SSE, WebSocket and unbounded
120
130
  downloads are outside this template's scope.
131
+ - Requests whose valid `Content-Length` already exceeds `MAX_BODY_BYTES` are
132
+ rejected before facilitator verification. Streaming, chunked and incorrectly
133
+ declared bodies are still enforced while the proxy reads them.
121
134
  - Upstream actions happen before settlement. For non-idempotent POST operations,
122
135
  settlement failure does not undo the upstream action. Use an upstream with
123
136
  idempotency support; the wrapper does not provide exactly-once execution.
124
137
  - A facilitator timeout may leave the on-chain settlement outcome unknown. An
125
138
  error response is not proof of no charge. Reconcile before retrying a payment.
126
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;
142
+ use an appropriate probe interval. It does not verify upstream health or actual settlement.
143
+ - Every response carries an `X-Request-ID` header. Send your own `x-request-id`
144
+ (letters, digits, `.`, `_`, `~`, `-`, up to 128 chars) and it is echoed back and
145
+ forwarded upstream so agent, wrapper and upstream logs correlate; unsafe
146
+ values are replaced with a minted UUID in the response and stripped upstream.
147
+ IDs are caller-controlled correlation labels, not authentication or payment deduplication keys.
148
+ Generated IDs label the wrapper response; they are not injected upstream.
127
149
  - The CLI disables Bun's short idle timeout so it does not disconnect a client
128
150
  during settlement. SDK facilitator calls default to a configurable 90-second timeout;
129
151
  deploy behind a reverse proxy with suitable request deadlines and rate limits.
@@ -174,6 +196,22 @@ original bytes. Cleanup is best-effort: an injected stream producer still owns i
174
196
  underlying resources. This does not cancel or undo payment settlement, and does
175
197
  not add payment retries.
176
198
 
199
+ ### CORS support (added in 0.3.2)
200
+
201
+ Configure `CORS_ORIGIN` with `*` or a specific origin (e.g. `https://agent.kite.ai`)
202
+ to enable web browsers, dApps, and AI agent frontends to make paid cross-origin calls:
203
+
204
+ - Preflight `OPTIONS` requests receive `204 No Content` with appropriate
205
+ `Access-Control-Allow-*` headers without triggering payment middleware.
206
+ Only OPTIONS with Origin and Access-Control-Request-Method is preflight;
207
+ other OPTIONS requests still require payment. Upstream CORS headers are stripped
208
+ so the wrapper controls origin policy. CORS is not server-side authentication.
209
+ - `402 Payment Required` challenge responses and successful responses expose
210
+ `Payment-Required`, `Payment-Response`, `Retry-After`, `X-Request-ID`, allowing browser `fetch`
211
+ clients to inspect payment requirements and payment settlement tokens.
212
+ - When `CORS_ORIGIN` is unset (the default), CORS middleware is omitted entirely
213
+ with zero overhead and backwards-compatible behavior.
214
+
177
215
  ### Commands
178
216
 
179
217
  ```sh
package/README.zh-CN.md CHANGED
@@ -28,10 +28,13 @@ 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
31
32
  curl -i 'http://localhost:8080/v1/echo?message=hello'
32
33
  ```
33
34
 
34
- `/healthz` 返回 200,且不会访问 facilitator。`/v1/echo` 在 facilitator 可访问并支持
35
+ `/healthz` 返回 200,且不会访问 facilitator。`/readyz` 会实际调用
36
+ facilitator 的 `/supported` 接口,只有当前配置的 Kite 网络、x402 v2 和 exact 模式均被支持时才返回
37
+ 200;这不保证上游就绪或实际结算成功。`/v1/echo` 在 facilitator 可访问并支持
35
38
  所选网络时,未付款请求会返回带有 x402 v2 `PAYMENT-REQUIRED` 的 402。如果 facilitator
36
39
  不可用,会返回 503;未完成付款验证前,代理不会调用上游。
37
40
 
@@ -64,19 +67,22 @@ Bun.serve({ port: config.port, fetch: app.fetch });
64
67
 
65
68
  ## 配置项
66
69
 
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 |
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),支持浏览器 |
80
86
 
81
87
  除本地开发外,上游和 facilitator 必须使用 HTTPS。示例 `.env` 明确选择 testnet,
82
88
  但兼容性默认值仍是 mainnet。本代理不需要钱包私钥。
@@ -93,7 +99,7 @@ Bun.serve({ port: config.port, fetch: app.fetch });
93
99
 
94
100
  1. 没有付款或付款无效:返回 402,不调用上游。
95
101
  2. 付款验证成功:去掉 `/v1` 前缀,保留查询参数、方法和请求体,注入配置的上游凭据,调用固定 origin。
96
- 3. 上游返回 2xx:缓存有大小上限的响应,然后请求 facilitator 结算。
102
+ 3. 上游返回 2xx 或条件请求 304:缓存有大小上限的响应,然后请求 facilitator 结算。
97
103
  4. 结算成功:返回上游响应和 `PAYMENT-RESPONSE`。
98
104
  5. 上游返回 4xx/5xx、超时、请求或响应超限、连接失败:不结算。
99
105
  6. 结算拒绝:返回 SDK 的失败响应,不泄露受保护数据。
@@ -102,12 +108,15 @@ Bun.serve({ port: config.port, fetch: app.fetch });
102
108
 
103
109
  - `/v1/echo` 会映射到上游 `/echo`;`/v1/v1/forecast` 会映射到上游 `/v1/forecast`。
104
110
  - `/v1/*` 下的所有 HTTP 方法都需要付款;上游必须支持对应方法。
105
- - 本模板拒绝上游重定向并返回 502,不结算,避免凭据被带到其他主机。请直接配置最终上游 origin。
111
+ - 本模板拒绝上游重定向并返回 502,不结算,避免凭据被带到其他主机。请直接配置最终上游 origin。条件请求的 304 Not Modified 不属于重定向,会正常转发,客户端的 If-None-Match / If-Modified-Since 仍然有效。
106
112
  - 会删除支付头、客户端认证头、Cookie、代理头和 hop-by-hop 头;上游返回的认证头和 Cookie 也会被删除。
107
113
  - 响应会被缓存,因此本模板不支持流式响应、SSE、WebSocket 和无限大小下载。
114
+ - 有效 `Content-Length` 已超过 `MAX_BODY_BYTES` 的请求会在 facilitator 验证前被拒绝;
115
+ 流式、分块或错误声明长度的请求仍会在代理读取时执行大小限制。
108
116
  - 上游动作发生在结算之前。非幂等 POST 在结算失败时不会回滚;需要 exactly-once 行为时,上游必须自行提供幂等机制。
109
117
  - facilitator 超时可能无法确定链上结算结果;错误响应不等于确定没有扣款,重试前应先核对。
110
- - `/healthz` 只表示进程存活,不代表上游或 facilitator 已就绪。
118
+ - `/healthz` 只表示进程存活,不代表上游或 facilitator 已就绪。可用 `/readyz` 检查 facilitator 是否可达且支持所配置的网络。
119
+ - 每个响应都带 `X-Request-ID` 头。调用方传入自己的 `x-request-id`(仅限字母、数字、`.`、`_`、`~`、`-`,最长 128 字符)会被原样回显并透传上游,使 agent、wrapper 与上游日志可用同一 ID 关联;不安全的值会被替换为新 UUID。
111
120
 
112
121
  ## 验证
113
122
 
@@ -144,6 +153,14 @@ Bun.serve({ port: config.port, fetch: app.fetch });
144
153
  清理属于尽力执行:自定义流生产者仍须管理底层资源。
145
154
  此改动不会取消或撤销付款结算,也不增加付款重试。
146
155
 
156
+ ### 跨域资源共享 (CORS) 支持(0.3.2 新增)
157
+
158
+ 配置 `CORS_ORIGIN` 为 `*` 或指定 origin(例如 `https://agent.kite.ai`)可支持 Web 浏览器、dApp 及 AI Agent 前端调用付费 API:
159
+
160
+ - 预检 `OPTIONS` 请求返回 `204 No Content` 及对应的 `Access-Control-Allow-*` 头部,无需先触发付费。
161
+ - 付费挑战 `402 Payment Required` 与正常响应均通过 `Access-Control-Expose-Headers` 暴露 `Payment-Required`、`Payment-Response`、`Retry-After`,方便浏览器端 `fetch` 读取付款挑战及结算回执。
162
+ - 未配置 `CORS_ORIGIN` 时(默认),不注册 CORS 中间件,保持零额外开销与向下兼容。
163
+
147
164
  ### 检查命令
148
165
 
149
166
  ```sh
@@ -167,3 +184,8 @@ pieUSD 会话,并保存真实响应和交易哈希。主网交易不是本地
167
184
  贡献流程见 [CONTRIBUTING.md](CONTRIBUTING.md),活动范围和证据清单见 [docs/week-1.md](docs/week-1.md)。
168
185
  AI 工具参与了开发;BrK 审核并负责此贡献。项目自己的 Wrapper、配置校验、代理逻辑、测试和
169
186
  打包工作与上游 x402 SDK 功能已明确区分。
187
+
188
+ 就绪探针每次访问 facilitator,部署时请设置合理探测间隔;它不保证上游健康或真实结算成功。
189
+ 请求 ID 是调用方可控的关联标签,不能用作身份凭证或付款去重键。生成的 UUID 只标记代理响应;非法调用方 ID 不会透传上游。
190
+ 仅同时携带 Origin 和 Access-Control-Request-Method 的 OPTIONS 属于免费预检,其他 OPTIONS 仍需付款。
191
+ 代理会过滤上游的 CORS 响应头,保持自身来源策略;CORS 不是服务器端鉴权。跨域响应也暴露 X-Request-ID。
package/dist/app.js CHANGED
@@ -1,12 +1,68 @@
1
1
  import { Hono } from "hono";
2
+ import { cors } from "hono/cors";
2
3
  import { paymentMiddlewareFromHTTPServer, x402HTTPResourceServer, x402ResourceServer, } from "@x402/hono";
3
4
  import { HTTPFacilitatorClient, } from "@x402/core/server";
4
5
  import { ExactEvmScheme } from "@x402/evm/exact/server";
5
- import { loadConfig } from "./config.js";
6
+ import { loadConfig, parseCorsOrigin } from "./config.js";
6
7
  import { parsePrice } from "./networks.js";
7
- import { proxy } from "./proxy.js";
8
+ import { proxy, REQUEST_ID_PATTERN } from "./proxy.js";
8
9
  export function createApp(config = loadConfig(), options = {}) {
9
10
  const app = new Hono();
11
+ // Label every response — paid answers, 402 challenges, guard-rail rejections
12
+ // and errors alike — with a request ID the caller can quote back in issues
13
+ // and correlate across agent, wrapper and upstream logs. A caller-supplied
14
+ // value is echoed only when it fits a conservative token alphabet, so the
15
+ // header cannot smuggle control characters or flood logs; anything else
16
+ // gets a freshly minted UUID. Caller-supplied IDs also travel upstream,
17
+ // because x-request-id is not on the proxy's blocked list.
18
+ app.use("*", async (c, next) => {
19
+ const inbound = c.req.header("x-request-id");
20
+ const requestId = inbound && REQUEST_ID_PATTERN.test(inbound)
21
+ ? inbound
22
+ : crypto.randomUUID();
23
+ await next();
24
+ c.res.headers.set("x-request-id", requestId);
25
+ });
26
+ if (config.corsOrigin) {
27
+ const corsMiddleware = cors({
28
+ origin: parseCorsOrigin(config.corsOrigin),
29
+ allowMethods: [
30
+ "GET",
31
+ "HEAD",
32
+ "POST",
33
+ "PUT",
34
+ "DELETE",
35
+ "PATCH",
36
+ "OPTIONS",
37
+ ],
38
+ allowHeaders: [
39
+ "Content-Type",
40
+ "Authorization",
41
+ "Payment-Signature",
42
+ "X-Payment",
43
+ "X-Requested-With",
44
+ "X-Request-ID",
45
+ ],
46
+ exposeHeaders: [
47
+ "Payment-Required",
48
+ "Payment-Response",
49
+ "X-Payment-Required",
50
+ "X-Payment-Response",
51
+ "Retry-After",
52
+ "X-Request-ID",
53
+ ],
54
+ maxAge: 86400,
55
+ });
56
+ app.use("*", (c, next) => {
57
+ // 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"))) {
61
+ return next();
62
+ }
63
+ return corsMiddleware(c, next);
64
+ });
65
+ }
10
66
  const facilitatorTimeoutMs = config.facilitatorTimeoutMs ?? 90000;
11
67
  if (!Number.isInteger(facilitatorTimeoutMs) ||
12
68
  facilitatorTimeoutMs < 1 ||
@@ -18,6 +74,21 @@ export function createApp(config = loadConfig(), options = {}) {
18
74
  throw new Error("maxConcurrentRequests must be an integer between 1 and 10000");
19
75
  }
20
76
  let active = 0;
77
+ // Reject a body that is already known to exceed the configured limit before
78
+ // contacting the facilitator. Chunked or incorrectly declared bodies remain
79
+ // protected by proxy's bounded stream reader.
80
+ app.use("/v1/*", async (c, next) => {
81
+ if (!["GET", "HEAD"].includes(c.req.method)) {
82
+ const declaredLength = c.req.header("content-length");
83
+ if (declaredLength &&
84
+ /^\d+$/.test(declaredLength) &&
85
+ BigInt(declaredLength) > BigInt(config.maxBodyBytes)) {
86
+ c.header("Cache-Control", "no-store");
87
+ return c.json({ error: "request_too_large" }, 413);
88
+ }
89
+ }
90
+ await next();
91
+ });
21
92
  // Cover initialization, verification, upstream and settlement, not just proxy I/O.
22
93
  // Never queue payment-bearing requests or retain their signatures.
23
94
  app.use("/v1/*", async (c, next) => {
@@ -62,6 +133,35 @@ export function createApp(config = loadConfig(), options = {}) {
62
133
  asset: config.chain.symbol,
63
134
  price: `$${config.price}`,
64
135
  }));
136
+ // Readiness is stronger than liveness: the process is up and the facilitator
137
+ // advertises the configured protocol and network; this does not prove settlement.
138
+ app.get("/readyz", async (c) => {
139
+ let supported;
140
+ try {
141
+ supported = await facilitator.getSupported();
142
+ }
143
+ catch {
144
+ return c.json({ ok: false, error: "facilitator_unavailable" }, 503, {
145
+ "cache-control": "no-store",
146
+ });
147
+ }
148
+ const offered = supported.kinds.some((kind) => kind.network === config.chain.network &&
149
+ kind.scheme === "exact" &&
150
+ kind.x402Version === 2);
151
+ if (!offered) {
152
+ return c.json({
153
+ ok: false,
154
+ error: "network_not_offered",
155
+ network: config.chain.network,
156
+ }, 503, { "cache-control": "no-store" });
157
+ }
158
+ return c.json({
159
+ ok: true,
160
+ network: config.chain.network,
161
+ asset: config.chain.symbol,
162
+ price: `$${config.price}`,
163
+ }, 200, { "cache-control": "no-store" });
164
+ });
65
165
  app.use("/v1/*", async (c, next) => {
66
166
  c.header("cache-control", "no-store");
67
167
  try {
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\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\nSee README.md for configuration and examples.");
6
6
  }
7
7
  else {
8
8
  try {
package/dist/config.d.ts CHANGED
@@ -13,5 +13,7 @@ export interface Config {
13
13
  maxBodyBytes: number;
14
14
  maxConcurrentRequests?: number;
15
15
  facilitatorTimeoutMs?: number;
16
+ corsOrigin?: string | undefined;
16
17
  }
18
+ export declare function parseCorsOrigin(value: string): string;
17
19
  export declare function loadConfig(env?: Record<string, string | undefined>): Config;
package/dist/config.js CHANGED
@@ -1,4 +1,9 @@
1
1
  import { KITE_NETWORKS, parsePrice } from "./networks.js";
2
+ export function parseCorsOrigin(value) {
3
+ if (value === "*")
4
+ return "*";
5
+ return httpUrl(value, "CORS_ORIGIN", true);
6
+ }
2
7
  function integer(value, key, max) {
3
8
  if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > max) {
4
9
  throw new Error(`${key} must be an integer between 1 and ${max}`);
@@ -80,5 +85,8 @@ export function loadConfig(env = process.env) {
80
85
  maxBodyBytes: integer(get("MAX_BODY_BYTES", "1048576"), "MAX_BODY_BYTES", 16777216),
81
86
  maxConcurrentRequests: integer(get("MAX_CONCURRENT_REQUESTS", "64"), "MAX_CONCURRENT_REQUESTS", 10000),
82
87
  facilitatorTimeoutMs: integer(get("FACILITATOR_TIMEOUT_MS", "90000"), "FACILITATOR_TIMEOUT_MS", 300000),
88
+ corsOrigin: get("CORS_ORIGIN")
89
+ ? parseCorsOrigin(get("CORS_ORIGIN"))
90
+ : undefined,
83
91
  };
84
92
  }
package/dist/proxy.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Config } from "./config.js";
2
2
  export type FetchUpstream = (request: Request) => Promise<Response>;
3
+ export declare const REQUEST_ID_PATTERN: RegExp;
3
4
  export declare function cleanHeaders(source: Headers, authHeader: string): Headers;
4
5
  export declare function readLimited(stream: ReadableStream<Uint8Array> | null, limit: number, signal?: AbortSignal): Promise<Uint8Array<ArrayBuffer>>;
5
6
  export declare function proxy(request: Request, config: Config, fetchUpstream: FetchUpstream): Promise<Response>;
package/dist/proxy.js CHANGED
@@ -1,3 +1,4 @@
1
+ export const REQUEST_ID_PATTERN = /^[A-Za-z0-9._~-]{1,128}$/;
1
2
  const blocked = new Set([
2
3
  "connection",
3
4
  "keep-alive",
@@ -31,9 +32,12 @@ export function cleanHeaders(source, authHeader) {
31
32
  .map((token) => token.trim().toLowerCase());
32
33
  for (const key of [...headers.keys()]) {
33
34
  if (blocked.has(key) ||
35
+ (key === "x-request-id" &&
36
+ !REQUEST_ID_PATTERN.test(headers.get(key) ?? "")) ||
34
37
  key === authHeader ||
35
38
  connectionTokens.includes(key) ||
36
- key.startsWith("x402-"))
39
+ key.startsWith("x402-") ||
40
+ key.startsWith("access-control-"))
37
41
  headers.delete(key);
38
42
  }
39
43
  return headers;
@@ -128,8 +132,11 @@ export async function proxy(request, config, fetchUpstream) {
128
132
  signal: controller.signal,
129
133
  redirect: "manual",
130
134
  }));
131
- // No redirect following: an upstream cannot forward the injected credential to another host.
132
- if (upstream.status >= 300 && upstream.status < 400) {
135
+ // Only 304 is a supported non-2xx success; refuse other 3xx without settlement.
136
+ // Never follow redirects with the injected credential.
137
+ if (upstream.status >= 300 &&
138
+ upstream.status < 400 &&
139
+ upstream.status !== 304) {
133
140
  void upstream.body?.cancel().catch(() => { });
134
141
  return Response.json({ error: "upstream_redirect_refused" }, { status: 502 });
135
142
  }
package/docs/week-4.md CHANGED
@@ -24,7 +24,8 @@ pending read, and successful multi-chunk reads at the exact size limit.
24
24
 
25
25
  Against the previous source, seven of these nine tests fail. With the fix all nine
26
26
  pass. Test payment verification is simulated; no real on-chain payment is claimed.
27
- The fix is included in version 0.3.1; registry publication is verified separately.
27
+ The stream cleanup fix was published in version 0.3.1. Community PR features
28
+ described in the root changelog are included in version 0.3.2.
28
29
 
29
30
  Cancellation is best-effort, not proof the producer released external resources.
30
31
  An injected stream must manage its own resources. This change neither aborts an
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kite-x402-hono",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Bun and Hono reverse proxy for x402 payments on Kite",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",