kite-x402-hono 0.3.3 → 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/CHANGELOG.md +8 -0
- package/README.md +42 -1
- package/README.zh-CN.md +28 -0
- package/dist/app.js +18 -17
- 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/client-ip.d.ts +4 -0
- package/dist/client-ip.js +52 -0
- package/dist/config.d.ts +1 -0
- package/dist/config.js +2 -1
- package/dist/firewall.d.ts +1 -1
- package/dist/firewall.js +35 -15
- package/dist/idempotency.d.ts +4 -1
- package/dist/idempotency.js +16 -9
- package/dist/index.d.ts +19 -0
- package/dist/index.js +19 -0
- package/dist/logger.d.ts +2 -2
- package/dist/logger.js +2 -2
- 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/nonce-guard.d.ts +8 -5
- package/dist/nonce-guard.js +21 -12
- package/dist/payment-protection.js +78 -40
- package/dist/prometheus-metrics.d.ts +33 -0
- package/dist/prometheus-metrics.js +94 -0
- package/dist/rate-limiter.d.ts +2 -0
- package/dist/rate-limiter.js +18 -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/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
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
|
+
|
|
3
11
|
## 0.3.3
|
|
4
12
|
|
|
5
13
|
- Implement graceful CLI shutdown on `SIGINT`/`SIGTERM` with active request draining (`server.stop(false)`) and configurable `SHUTDOWN_TIMEOUT_MS`.
|
package/README.md
CHANGED
|
@@ -174,8 +174,34 @@ Compatibility notes:
|
|
|
174
174
|
- Unmatched or unknown routes return structured JSON `404 {"error":"not_found"}` with
|
|
175
175
|
`Cache-Control: no-store` rather than unformatted plaintext error responses.
|
|
176
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.
|
|
178
|
+
|
|
177
179
|
## Verification
|
|
178
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
|
+
|
|
179
205
|
### Concurrency admission (added in 0.2.0)
|
|
180
206
|
|
|
181
207
|
`MAX_CONCURRENT_REQUESTS` defaults to 64 and accepts integers from 1 to 10000.
|
|
@@ -192,6 +218,8 @@ for upstream capacity and response sizes; use edge rate limits for hostile traff
|
|
|
192
218
|
Do not treat every 503 as safe to retry: only this wrapper's `service_busy`
|
|
193
219
|
response denotes pre-payment rejection. Settlement errors still need reconciliation.
|
|
194
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
|
+
|
|
195
223
|
### Rate limiting (added in 0.3.3)
|
|
196
224
|
|
|
197
225
|
`RATE_LIMIT_RPS` and `RATE_LIMIT_BURST` provide built-in in-memory token-bucket request throttling:
|
|
@@ -205,6 +233,11 @@ response denotes pre-payment rejection. Settlement errors still need reconciliat
|
|
|
205
233
|
- Exceeding clients receive `429 {"error":"rate_limit_exceeded"}` with `Retry-After: <seconds>` and `Cache-Control: no-store` before payment verification or upstream proxying.
|
|
206
234
|
- `/healthz` health probes and browser `OPTIONS` preflights are always exempt from rate limiting.
|
|
207
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
|
+
|
|
208
241
|
### Facilitator deadlines (added in 0.3.0)
|
|
209
242
|
|
|
210
243
|
`FACILITATOR_TIMEOUT_MS` accepts integers from 1 to 300000, default 90000.
|
|
@@ -299,4 +332,12 @@ wrapper/configuration/test work is distinguished from upstream SDK functionality
|
|
|
299
332
|
|
|
300
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.
|
|
301
334
|
|
|
302
|
-
Access logs omit query strings, bodies and payment signatures. `clientIp`
|
|
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
|
@@ -123,8 +123,28 @@ Bun.serve({ port: config.port, fetch: app.fetch });
|
|
|
123
123
|
- `/healthz` 只表示进程存活,不代表上游或 facilitator 已就绪。可用 `/readyz` 检查 facilitator 是否可达且支持所配置的网络。
|
|
124
124
|
- 每个响应都带 `X-Request-ID` 头。调用方传入自己的 `x-request-id`(仅限字母、数字、`.`、`_`、`~`、`-`,最长 128 字符)会被原样回显并透传上游,使 agent、wrapper 与上游日志可用同一 ID 关联;不安全的值会被替换为新 UUID。
|
|
125
125
|
|
|
126
|
+
活跃 nonce 租约随请求生命周期保留,不再由 `inFlightTtlMs` 到期回收。中间件通过拥有者绑定的租约释放或提交,旧请求无法修改替换租约。已消费记录仍为进程内、有限保留时间;持久化与多实例协调需要应用提供。
|
|
127
|
+
|
|
126
128
|
## 验证
|
|
127
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
|
+
|
|
128
148
|
### 并发准入限制(0.2.0 新增)
|
|
129
149
|
|
|
130
150
|
`MAX_CONCURRENT_REQUESTS` 默认 64,接受 1 至 10000 的整数。每个 `createApp()` 实例
|
|
@@ -137,6 +157,8 @@ Bun.serve({ port: config.port, fetch: app.fetch });
|
|
|
137
157
|
恶意流量仍应通过入口限流控制。不能把所有 503 都当成可安全重试:只有本代理的
|
|
138
158
|
`service_busy` 表示付款前拒绝;结算错误仍需先核对结果。
|
|
139
159
|
|
|
160
|
+
防火墙规则支持 IPv4、IPv6 和 CIDR,两侧均处理压缩 IPv6 与 IPv4 映射地址。非法规则在配置阶段报错;启用过滤时非法客户端地址被拒绝,阻止规则优先于允许规则。
|
|
161
|
+
|
|
140
162
|
### Facilitator 超时(0.3.0 新增)
|
|
141
163
|
|
|
142
164
|
`FACILITATOR_TIMEOUT_MS` 默认 90000 毫秒,允许 1 至 300000 的整数。
|
|
@@ -209,3 +231,9 @@ AI 工具参与了开发;BrK 审核并负责此贡献。项目自己的 Wrappe
|
|
|
209
231
|
请求 ID 是调用方可控的关联标签,不能用作身份凭证或付款去重键。生成的 UUID 只标记代理响应;非法调用方 ID 不会透传上游。
|
|
210
232
|
仅同时携带 Origin 和 Access-Control-Request-Method 的 OPTIONS 属于免费预检,其他 OPTIONS 仍需付款。
|
|
211
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.js
CHANGED
|
@@ -8,11 +8,13 @@ import { loadConfig, parseCorsOrigin } from "./config.js";
|
|
|
8
8
|
import { parsePrice } from "./networks.js";
|
|
9
9
|
import { proxy, REQUEST_ID_PATTERN } from "./proxy.js";
|
|
10
10
|
import { TokenBucketRateLimiter, createRateLimiterMiddleware, } from "./rate-limiter.js";
|
|
11
|
-
import { evaluateIpFilter
|
|
11
|
+
import { evaluateIpFilter } from "./firewall.js";
|
|
12
12
|
import { createPaymentProtection } from "./payment-protection.js";
|
|
13
13
|
import { createAccessLogger } from "./logger.js";
|
|
14
|
+
import { clientIpResolver } from "./client-ip.js";
|
|
14
15
|
export function createApp(config = loadConfig(), options = {}) {
|
|
15
16
|
const app = new Hono();
|
|
17
|
+
const getClientIp = options.clientIp ?? clientIpResolver(config);
|
|
16
18
|
// Attach standard security headers to protect against MIME-sniffing,
|
|
17
19
|
// clickjacking, and XSS across all routes.
|
|
18
20
|
app.use("*", secureHeaders());
|
|
@@ -25,7 +27,7 @@ export function createApp(config = loadConfig(), options = {}) {
|
|
|
25
27
|
format: config.logFormat,
|
|
26
28
|
enabled: config.logEnabled,
|
|
27
29
|
skipHealthz: true,
|
|
28
|
-
}, options.logSink));
|
|
30
|
+
}, options.logSink, getClientIp));
|
|
29
31
|
}
|
|
30
32
|
// Label every response — paid answers, 402 challenges, guard-rail rejections
|
|
31
33
|
// and errors alike — with a request ID the caller can quote back in issues
|
|
@@ -104,10 +106,6 @@ export function createApp(config = loadConfig(), options = {}) {
|
|
|
104
106
|
return corsMiddleware(c, async () => { });
|
|
105
107
|
});
|
|
106
108
|
}
|
|
107
|
-
const getClientIp = options.clientIp ??
|
|
108
|
-
((c) => config.trustProxyHeaders !== false
|
|
109
|
-
? extractClientIp(c.req.raw.headers)
|
|
110
|
-
: (c.env?.clientIp ?? null));
|
|
111
109
|
if (config.firewallAllowlist?.length || config.firewallBlocklist?.length) {
|
|
112
110
|
app.use("/v1/*", async (c, next) => {
|
|
113
111
|
const ip = getClientIp(c);
|
|
@@ -208,18 +206,21 @@ export function createApp(config = loadConfig(), options = {}) {
|
|
|
208
206
|
});
|
|
209
207
|
const protection = createPaymentProtection(facilitator, config, options);
|
|
210
208
|
const server = new x402ResourceServer(protection.facilitator).register(config.chain.network, new ExactEvmScheme());
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
maxTimeoutSeconds: 60,
|
|
219
|
-
},
|
|
220
|
-
description: config.description,
|
|
221
|
-
mimeType: "application/json",
|
|
209
|
+
const paidRoute = {
|
|
210
|
+
accepts: {
|
|
211
|
+
scheme: "exact",
|
|
212
|
+
price: parsePrice(config.price, config.chain),
|
|
213
|
+
network: config.chain.network,
|
|
214
|
+
payTo: config.payTo,
|
|
215
|
+
maxTimeoutSeconds: 60,
|
|
222
216
|
},
|
|
217
|
+
description: config.description,
|
|
218
|
+
mimeType: "application/json",
|
|
219
|
+
};
|
|
220
|
+
const httpServer = new x402HTTPResourceServer(server, {
|
|
221
|
+
"/v1/*": paidRoute,
|
|
222
|
+
// SDK wildcards exclude OPTIONS; ordinary OPTIONS still requires payment.
|
|
223
|
+
"OPTIONS /v1/*": paidRoute,
|
|
223
224
|
});
|
|
224
225
|
const payments = paymentMiddlewareFromHTTPServer(httpServer, undefined, undefined, false);
|
|
225
226
|
// Initialize lazily so /healthz never needs network access and startup errors stay request-scoped.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structured Compliance Audit Trail and Latency Trace Emitter
|
|
3
|
+
* Records in-memory diagnostic traces (not tamper-evident audit proofs) for payment authorizations and facilitator requests.
|
|
4
|
+
*/
|
|
5
|
+
export interface AuditEventTrace {
|
|
6
|
+
traceId: string;
|
|
7
|
+
eventType: "PAYMENT_AUTH" | "PAYMENT_VERIFIED" | "PAYMENT_SETTLED" | "AUTH_FAILED";
|
|
8
|
+
timestamp: string;
|
|
9
|
+
payerAddress?: string;
|
|
10
|
+
amountUnits?: string;
|
|
11
|
+
network?: string;
|
|
12
|
+
latencyMs: number;
|
|
13
|
+
metadata?: Record<string, any>;
|
|
14
|
+
}
|
|
15
|
+
export declare class AuditTraceEmitter {
|
|
16
|
+
private traces;
|
|
17
|
+
private readonly maxTraces;
|
|
18
|
+
constructor(maxTraces?: number);
|
|
19
|
+
emit(event: Omit<AuditEventTrace, "timestamp">): AuditEventTrace;
|
|
20
|
+
getTraces(): readonly AuditEventTrace[];
|
|
21
|
+
clear(): void;
|
|
22
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structured Compliance Audit Trail and Latency Trace Emitter
|
|
3
|
+
* Records in-memory diagnostic traces (not tamper-evident audit proofs) for payment authorizations and facilitator requests.
|
|
4
|
+
*/
|
|
5
|
+
export class AuditTraceEmitter {
|
|
6
|
+
traces = [];
|
|
7
|
+
maxTraces;
|
|
8
|
+
constructor(maxTraces = 500) {
|
|
9
|
+
if (!Number.isSafeInteger(maxTraces) || maxTraces < 1)
|
|
10
|
+
throw new Error("Invalid trace limit");
|
|
11
|
+
this.maxTraces = maxTraces;
|
|
12
|
+
}
|
|
13
|
+
emit(event) {
|
|
14
|
+
const fullEvent = {
|
|
15
|
+
...event,
|
|
16
|
+
timestamp: new Date().toISOString(),
|
|
17
|
+
};
|
|
18
|
+
this.traces.push(structuredClone(fullEvent));
|
|
19
|
+
if (this.traces.length > this.maxTraces) {
|
|
20
|
+
this.traces.shift();
|
|
21
|
+
}
|
|
22
|
+
return fullEvent;
|
|
23
|
+
}
|
|
24
|
+
getTraces() {
|
|
25
|
+
return structuredClone(this.traces);
|
|
26
|
+
}
|
|
27
|
+
clear() {
|
|
28
|
+
this.traces = [];
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface CachedAuthEntry {
|
|
2
|
+
payerAddress: string;
|
|
3
|
+
scheme: string;
|
|
4
|
+
verifiedAt: number;
|
|
5
|
+
expiresAt: number;
|
|
6
|
+
}
|
|
7
|
+
export declare class PaymentAuthCache {
|
|
8
|
+
private cache;
|
|
9
|
+
private readonly ttlMs;
|
|
10
|
+
private readonly maxEntries;
|
|
11
|
+
constructor(ttlMs?: number, maxEntries?: number);
|
|
12
|
+
get(paymentKey: string): CachedAuthEntry | null;
|
|
13
|
+
set(paymentKey: string, payerAddress: string, scheme?: string): void;
|
|
14
|
+
size(): number;
|
|
15
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export class PaymentAuthCache {
|
|
2
|
+
cache = new Map();
|
|
3
|
+
ttlMs;
|
|
4
|
+
maxEntries;
|
|
5
|
+
constructor(ttlMs = 60000, maxEntries = 5000) {
|
|
6
|
+
if (!Number.isFinite(ttlMs) ||
|
|
7
|
+
ttlMs <= 0 ||
|
|
8
|
+
!Number.isSafeInteger(maxEntries) ||
|
|
9
|
+
maxEntries < 1)
|
|
10
|
+
throw new Error("Invalid cache limits");
|
|
11
|
+
this.ttlMs = ttlMs;
|
|
12
|
+
this.maxEntries = maxEntries;
|
|
13
|
+
}
|
|
14
|
+
get(paymentKey) {
|
|
15
|
+
const entry = this.cache.get(paymentKey);
|
|
16
|
+
if (!entry)
|
|
17
|
+
return null;
|
|
18
|
+
if (Date.now() > entry.expiresAt) {
|
|
19
|
+
this.cache.delete(paymentKey);
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
this.cache.delete(paymentKey);
|
|
23
|
+
this.cache.set(paymentKey, entry);
|
|
24
|
+
return { ...entry };
|
|
25
|
+
}
|
|
26
|
+
set(paymentKey, payerAddress, scheme = "x402") {
|
|
27
|
+
this.cache.delete(paymentKey);
|
|
28
|
+
if (this.cache.size >= this.maxEntries) {
|
|
29
|
+
const oldestKey = this.cache.keys().next().value;
|
|
30
|
+
if (oldestKey)
|
|
31
|
+
this.cache.delete(oldestKey);
|
|
32
|
+
}
|
|
33
|
+
const now = Date.now();
|
|
34
|
+
this.cache.set(paymentKey, {
|
|
35
|
+
payerAddress,
|
|
36
|
+
scheme,
|
|
37
|
+
verifiedAt: now,
|
|
38
|
+
expiresAt: now + this.ttlMs,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
size() {
|
|
42
|
+
return this.cache.size;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { BlockList, isIP } from "node:net";
|
|
2
|
+
import { extractClientIp } from "./firewall.js";
|
|
3
|
+
/** Resolve the socket peer by default; forwarded claims require explicit trust. */
|
|
4
|
+
export function clientIpResolver(config) {
|
|
5
|
+
const rules = config.trustedProxyCidrs ?? [];
|
|
6
|
+
const trusted = new BlockList();
|
|
7
|
+
for (const rule of rules) {
|
|
8
|
+
const [address, prefix, extra] = rule.split("/");
|
|
9
|
+
const family = address ? isIP(address) : 0;
|
|
10
|
+
const bits = family === 4 ? 32 : 128;
|
|
11
|
+
if (!family ||
|
|
12
|
+
extra !== undefined ||
|
|
13
|
+
(prefix !== undefined && (!/^\d+$/.test(prefix) || Number(prefix) > bits))) {
|
|
14
|
+
throw new Error("TRUSTED_PROXY_CIDRS contains an invalid IP or CIDR");
|
|
15
|
+
}
|
|
16
|
+
if (prefix === undefined)
|
|
17
|
+
trusted.addAddress(address, family === 4 ? "ipv4" : "ipv6");
|
|
18
|
+
else
|
|
19
|
+
trusted.addSubnet(address, Number(prefix), family === 4 ? "ipv4" : "ipv6");
|
|
20
|
+
}
|
|
21
|
+
const isTrusted = (ip) => {
|
|
22
|
+
const family = isIP(ip);
|
|
23
|
+
return !!family && trusted.check(ip, family === 4 ? "ipv4" : "ipv6");
|
|
24
|
+
};
|
|
25
|
+
return (c) => {
|
|
26
|
+
const peer = typeof c.env?.clientIp === "string" && isIP(c.env.clientIp)
|
|
27
|
+
? c.env.clientIp
|
|
28
|
+
: null;
|
|
29
|
+
if (config.trustProxyHeaders !== true)
|
|
30
|
+
return peer;
|
|
31
|
+
// The explicit legacy flag is supported for an ingress that strips inbound
|
|
32
|
+
// forwarding headers. CIDR rules additionally constrain trusted socket peers.
|
|
33
|
+
if (!rules.length) {
|
|
34
|
+
const claim = extractClientIp(c.req.raw.headers);
|
|
35
|
+
return claim && isIP(claim) ? claim : peer;
|
|
36
|
+
}
|
|
37
|
+
if (!peer || !isTrusted(peer))
|
|
38
|
+
return peer;
|
|
39
|
+
const forwarded = c.req.header("x-forwarded-for");
|
|
40
|
+
if (!forwarded) {
|
|
41
|
+
const claim = extractClientIp(c.req.raw.headers);
|
|
42
|
+
return claim && isIP(claim) ? claim : peer;
|
|
43
|
+
}
|
|
44
|
+
const hops = forwarded.split(",").map((ip) => ip.trim());
|
|
45
|
+
if (hops.length > 64 || hops.some((ip) => !isIP(ip)))
|
|
46
|
+
return peer;
|
|
47
|
+
let client = peer;
|
|
48
|
+
for (let i = hops.length - 1; i >= 0 && isTrusted(client); i--)
|
|
49
|
+
client = hops[i];
|
|
50
|
+
return client;
|
|
51
|
+
};
|
|
52
|
+
}
|
package/dist/config.d.ts
CHANGED
|
@@ -20,6 +20,7 @@ export interface Config {
|
|
|
20
20
|
firewallAllowlist?: string[] | undefined;
|
|
21
21
|
firewallBlocklist?: string[] | undefined;
|
|
22
22
|
trustProxyHeaders?: boolean | undefined;
|
|
23
|
+
trustedProxyCidrs?: string[] | undefined;
|
|
23
24
|
maintenanceMode?: boolean;
|
|
24
25
|
logFormat?: "json" | "dev" | undefined;
|
|
25
26
|
logEnabled?: boolean | undefined;
|
package/dist/config.js
CHANGED
|
@@ -101,7 +101,8 @@ export function loadConfig(env = process.env) {
|
|
|
101
101
|
: undefined,
|
|
102
102
|
firewallAllowlist: parseIpList(get("FIREWALL_ALLOWLIST")),
|
|
103
103
|
firewallBlocklist: parseIpList(get("FIREWALL_BLOCKLIST")),
|
|
104
|
-
trustProxyHeaders: get("TRUST_PROXY_HEADERS", "
|
|
104
|
+
trustProxyHeaders: get("TRUST_PROXY_HEADERS", "false") === "true",
|
|
105
|
+
trustedProxyCidrs: parseIpList(get("TRUSTED_PROXY_CIDRS")),
|
|
105
106
|
logFormat: get("LOG_FORMAT") === "dev" ? "dev" : "json",
|
|
106
107
|
logEnabled: get("LOG_ENABLED") !== "false",
|
|
107
108
|
};
|
package/dist/firewall.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export declare function ipv4ToNumber(ip: string): number | null;
|
|
|
19
19
|
*/
|
|
20
20
|
export declare function matchIpv4Cidr(ip: string, rule: string): boolean;
|
|
21
21
|
/**
|
|
22
|
-
*
|
|
22
|
+
* Matches IPv4, IPv6 and mapped addresses using the same parser on both sides.
|
|
23
23
|
*/
|
|
24
24
|
export declare function matchesIpRule(clientIp: string, rule: string): boolean;
|
|
25
25
|
/**
|
package/dist/firewall.js
CHANGED
|
@@ -1,13 +1,33 @@
|
|
|
1
|
+
import { BlockList, isIP } from "node:net";
|
|
1
2
|
/**
|
|
2
3
|
* Parses comma-separated IP or CIDR strings into a cleaned array.
|
|
3
4
|
*/
|
|
4
5
|
export function parseIpList(raw) {
|
|
5
6
|
if (!raw)
|
|
6
7
|
return [];
|
|
7
|
-
|
|
8
|
+
const rules = raw
|
|
8
9
|
.split(",")
|
|
9
10
|
.map((entry) => entry.trim())
|
|
10
11
|
.filter((entry) => entry.length > 0);
|
|
12
|
+
for (const rule of rules) {
|
|
13
|
+
if (!parseRule(rule))
|
|
14
|
+
throw new Error(`Invalid firewall IP or CIDR: ${rule}`);
|
|
15
|
+
}
|
|
16
|
+
return rules;
|
|
17
|
+
}
|
|
18
|
+
function parseRule(rule) {
|
|
19
|
+
const [address, prefix, extra] = rule.trim().split("/");
|
|
20
|
+
const version = address ? isIP(address) : 0;
|
|
21
|
+
if (!version ||
|
|
22
|
+
extra !== undefined ||
|
|
23
|
+
(prefix !== undefined &&
|
|
24
|
+
(!/^\d+$/.test(prefix) || Number(prefix) > (version === 4 ? 32 : 128))))
|
|
25
|
+
return null;
|
|
26
|
+
return {
|
|
27
|
+
address: address,
|
|
28
|
+
family: version === 4 ? "ipv4" : "ipv6",
|
|
29
|
+
...(prefix === undefined ? {} : { prefix: Number(prefix) }),
|
|
30
|
+
};
|
|
11
31
|
}
|
|
12
32
|
/**
|
|
13
33
|
* Converts an IPv4 string (e.g. "192.168.1.1") to a 32-bit unsigned integer.
|
|
@@ -34,7 +54,7 @@ export function matchIpv4Cidr(ip, rule) {
|
|
|
34
54
|
const parts = rule.split("/");
|
|
35
55
|
const subnet = parts[0];
|
|
36
56
|
const prefixStr = parts[1];
|
|
37
|
-
if (!subnet)
|
|
57
|
+
if (!subnet || !parseRule(rule) || isIP(subnet) !== 4)
|
|
38
58
|
return false;
|
|
39
59
|
const ipNum = ipv4ToNumber(ip);
|
|
40
60
|
const subnetNum = ipv4ToNumber(subnet);
|
|
@@ -54,20 +74,20 @@ export function matchIpv4Cidr(ip, rule) {
|
|
|
54
74
|
return (ipNum & mask) === (subnetNum & mask);
|
|
55
75
|
}
|
|
56
76
|
/**
|
|
57
|
-
*
|
|
77
|
+
* Matches IPv4, IPv6 and mapped addresses using the same parser on both sides.
|
|
58
78
|
*/
|
|
59
79
|
export function matchesIpRule(clientIp, rule) {
|
|
60
|
-
const
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
if (
|
|
64
|
-
return
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
return
|
|
80
|
+
const client = clientIp.trim();
|
|
81
|
+
const family = isIP(client);
|
|
82
|
+
const parsed = parseRule(rule);
|
|
83
|
+
if (!family || !parsed)
|
|
84
|
+
return false;
|
|
85
|
+
const list = new BlockList();
|
|
86
|
+
if (parsed.prefix === undefined)
|
|
87
|
+
list.addAddress(parsed.address, parsed.family);
|
|
88
|
+
else
|
|
89
|
+
list.addSubnet(parsed.address, parsed.prefix, parsed.family);
|
|
90
|
+
return list.check(client, family === 4 ? "ipv4" : "ipv6");
|
|
71
91
|
}
|
|
72
92
|
/**
|
|
73
93
|
* Evaluates a client IP against configured allowlists and blocklists.
|
|
@@ -77,7 +97,7 @@ export function evaluateIpFilter(clientIp, config) {
|
|
|
77
97
|
return { allowed: false, reason: "invalid_ip" };
|
|
78
98
|
}
|
|
79
99
|
const cleanIp = clientIp.trim();
|
|
80
|
-
if (cleanIp
|
|
100
|
+
if (!isIP(cleanIp)) {
|
|
81
101
|
return { allowed: false, reason: "invalid_ip" };
|
|
82
102
|
}
|
|
83
103
|
// 1. Check explicit blocklist first (highest priority)
|
package/dist/idempotency.d.ts
CHANGED
|
@@ -19,8 +19,11 @@ export declare class IdempotencyCache {
|
|
|
19
19
|
constructor(options?: IdempotencyCacheOptions);
|
|
20
20
|
validateKey(key: string | null | undefined): boolean;
|
|
21
21
|
cleanExpired(now?: number): void;
|
|
22
|
-
|
|
22
|
+
/** A supplied fingerprint must match for both in-flight and completed requests. */
|
|
23
|
+
acquire(key: string, ttlMs?: number, now?: number, fingerprint?: string): {
|
|
23
24
|
status: "acquired";
|
|
25
|
+
} | {
|
|
26
|
+
status: "conflict";
|
|
24
27
|
} | {
|
|
25
28
|
status: "in_flight";
|
|
26
29
|
} | {
|
package/dist/idempotency.js
CHANGED
|
@@ -22,35 +22,41 @@ export class IdempotencyCache {
|
|
|
22
22
|
const expiresAt = record.state === "in_flight"
|
|
23
23
|
? record.expiresAt
|
|
24
24
|
: record.response.expiresAt;
|
|
25
|
-
if (now >= expiresAt) {
|
|
25
|
+
if (record.state === "completed" && now >= expiresAt) {
|
|
26
26
|
this.records.delete(key);
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
|
-
|
|
30
|
+
/** A supplied fingerprint must match for both in-flight and completed requests. */
|
|
31
|
+
acquire(key, ttlMs = this.defaultTtlMs, now = Date.now(), fingerprint) {
|
|
31
32
|
this.cleanExpired(now);
|
|
32
33
|
const existing = this.records.get(key);
|
|
33
34
|
if (existing) {
|
|
35
|
+
if (existing.fingerprint !== fingerprint) {
|
|
36
|
+
return { status: "conflict" };
|
|
37
|
+
}
|
|
34
38
|
if (existing.state === "in_flight") {
|
|
35
39
|
return { status: "in_flight" };
|
|
36
40
|
}
|
|
37
41
|
return { status: "cached", response: existing.response };
|
|
38
42
|
}
|
|
39
43
|
if (this.records.size >= this.maxKeys) {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
+
const oldestKey = [...this.records].find(([, record]) => record.state === "completed")?.[0];
|
|
45
|
+
if (!oldestKey)
|
|
46
|
+
return { status: "conflict" };
|
|
47
|
+
this.records.delete(oldestKey);
|
|
44
48
|
}
|
|
45
49
|
this.records.set(key, {
|
|
46
50
|
state: "in_flight",
|
|
51
|
+
fingerprint,
|
|
47
52
|
startedAt: now,
|
|
48
|
-
expiresAt:
|
|
53
|
+
expiresAt: Number.POSITIVE_INFINITY, // Request owner releases the reservation.
|
|
49
54
|
});
|
|
50
55
|
return { status: "acquired" };
|
|
51
56
|
}
|
|
52
57
|
complete(key, statusCode, headers, body, ttlMs = this.defaultTtlMs, now = Date.now()) {
|
|
53
|
-
|
|
58
|
+
const record = this.records.get(key);
|
|
59
|
+
if (!record)
|
|
54
60
|
return;
|
|
55
61
|
const used = [...this.records.entries()].reduce((n, [k, r]) => n +
|
|
56
62
|
(k !== key && r.state === "completed" ? r.response.body.byteLength : 0), 0);
|
|
@@ -74,10 +80,11 @@ export class IdempotencyCache {
|
|
|
74
80
|
});
|
|
75
81
|
this.records.set(key, {
|
|
76
82
|
state: "completed",
|
|
83
|
+
fingerprint: record.fingerprint,
|
|
77
84
|
response: {
|
|
78
85
|
statusCode,
|
|
79
86
|
headers: headerEntries,
|
|
80
|
-
body,
|
|
87
|
+
body: body.slice(),
|
|
81
88
|
cachedAt: now,
|
|
82
89
|
expiresAt: now + ttlMs,
|
|
83
90
|
},
|
package/dist/index.d.ts
CHANGED
|
@@ -6,3 +6,22 @@ export { IdempotencyCache } from "./idempotency.js";
|
|
|
6
6
|
export { PaymentNonceReplayGuard } from "./nonce-guard.js";
|
|
7
7
|
export { TokenBucketRateLimiter, AdaptiveRateLimiter, createRateLimiterMiddleware, type RateLimiterOptions, } from "./rate-limiter.js";
|
|
8
8
|
export { evaluateIpFilter, parseIpList, matchesIpRule } from "./firewall.js";
|
|
9
|
+
export { ReadinessProbe, type ProbeTarget, type ReadinessProbeOptions, type ReadinessSnapshot, type TargetHealth, } from "./readiness-probe.js";
|
|
10
|
+
export { SettlementReconciler, type ReconcilerSummary, type SettlementQuery, type SettlementReceipt, } from "./settlement-reconciler.js";
|
|
11
|
+
export { TieredFeeScheduler, DEFAULT_FEE_TIERS, type FeeTier, type ClientVolumeRecord, type TierEvaluation, type TieredFeeSchedulerOptions, } from "./tiered-fee-scheduler.js";
|
|
12
|
+
export { ResponseSigner, type ResponseReceipt, type ResponseSignerOptions, } from "./response-signer.js";
|
|
13
|
+
export { ReceiptStore, type StoredReceipt, type ReceiptStoreConfig, } from "./receipt-store.js";
|
|
14
|
+
export { PrometheusMetricsExporter, type MetricsSnapshot, } from "./prometheus-metrics.js";
|
|
15
|
+
export * from "./traffic-shaper.js";
|
|
16
|
+
export * from "./response-caching.js";
|
|
17
|
+
export * from "./webhook-dispatcher.js";
|
|
18
|
+
export * from "./rpc-circuit-breaker.js";
|
|
19
|
+
export * from "./audit-trace-emitter.js";
|
|
20
|
+
export * from "./cache/payment-auth-cache.js";
|
|
21
|
+
export * from "./middleware/scheme-validator.js";
|
|
22
|
+
export * from "./middleware/payload-validator.js";
|
|
23
|
+
export * from "./telemetry/latency-histogram.js";
|
|
24
|
+
export * from "./middleware/sliding-window-limiter.js";
|
|
25
|
+
export * from "./middleware/cookie-session-store.js";
|
|
26
|
+
export * from "./middleware/brotli-compression.js";
|
|
27
|
+
export * from "./middleware/edge-rate-throttler.js";
|
package/dist/index.js
CHANGED
|
@@ -6,3 +6,22 @@ export { IdempotencyCache } from "./idempotency.js";
|
|
|
6
6
|
export { PaymentNonceReplayGuard } from "./nonce-guard.js";
|
|
7
7
|
export { TokenBucketRateLimiter, AdaptiveRateLimiter, createRateLimiterMiddleware, } from "./rate-limiter.js";
|
|
8
8
|
export { evaluateIpFilter, parseIpList, matchesIpRule } from "./firewall.js";
|
|
9
|
+
export { ReadinessProbe, } from "./readiness-probe.js";
|
|
10
|
+
export { SettlementReconciler, } from "./settlement-reconciler.js";
|
|
11
|
+
export { TieredFeeScheduler, DEFAULT_FEE_TIERS, } from "./tiered-fee-scheduler.js";
|
|
12
|
+
export { ResponseSigner, } from "./response-signer.js";
|
|
13
|
+
export { ReceiptStore, } from "./receipt-store.js";
|
|
14
|
+
export { PrometheusMetricsExporter, } from "./prometheus-metrics.js";
|
|
15
|
+
export * from "./traffic-shaper.js";
|
|
16
|
+
export * from "./response-caching.js";
|
|
17
|
+
export * from "./webhook-dispatcher.js";
|
|
18
|
+
export * from "./rpc-circuit-breaker.js";
|
|
19
|
+
export * from "./audit-trace-emitter.js";
|
|
20
|
+
export * from "./cache/payment-auth-cache.js";
|
|
21
|
+
export * from "./middleware/scheme-validator.js";
|
|
22
|
+
export * from "./middleware/payload-validator.js";
|
|
23
|
+
export * from "./telemetry/latency-histogram.js";
|
|
24
|
+
export * from "./middleware/sliding-window-limiter.js";
|
|
25
|
+
export * from "./middleware/cookie-session-store.js";
|
|
26
|
+
export * from "./middleware/brotli-compression.js";
|
|
27
|
+
export * from "./middleware/edge-rate-throttler.js";
|
package/dist/logger.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { MiddlewareHandler } from "hono";
|
|
1
|
+
import type { Context, MiddlewareHandler } from "hono";
|
|
2
2
|
export type LogFormat = "json" | "dev";
|
|
3
3
|
export interface LoggerConfig {
|
|
4
4
|
format?: LogFormat | undefined;
|
|
@@ -19,4 +19,4 @@ export interface AccessLogEntry {
|
|
|
19
19
|
/** Unverified forwarded-header claim; never use for access control. */
|
|
20
20
|
export declare function extractClientIp(headers: Headers): string | null;
|
|
21
21
|
export declare function formatLogEntry(entry: AccessLogEntry, format: LogFormat): string;
|
|
22
|
-
export declare function createAccessLogger(config?: LoggerConfig, sink?: (line: string) => void): MiddlewareHandler;
|
|
22
|
+
export declare function createAccessLogger(config?: LoggerConfig, sink?: (line: string) => void, resolveClientIp?: (c: Context) => string | null): MiddlewareHandler;
|