kite-x402-hono 0.5.0 → 0.7.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 CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.0
4
+
5
+ - Review PRs #63–#64: export validated, copy-isolated LRU receipt storage and an opt-in CORS allowlist with full-origin matching and strict preflight checks. Ordinary OPTIONS still reaches payment handling.
6
+
7
+ ## 0.6.0
8
+
9
+ - Review PR #62: export a structured JSON error handler for explicit `app.onError` registration, with validated request IDs, generic no-store 500 responses, optional server-only stacks, and isolated logging failures.
10
+
3
11
  ## 0.5.0
4
12
 
5
13
  - Integrate reviewed PRs #52–#61, including fee snapshot isolation, atomic response cache updates, and per-network settlement reconciliation.
package/README.md CHANGED
@@ -343,3 +343,23 @@ Socket peer addresses are used by default (`TRUST_PROXY_HEADERS=false`). Direct
343
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.
344
344
 
345
345
  Review and integration contracts for PRs #52–#61: [November review](docs/pr-review-2026-11-06.md). New utilities require explicit integration.
346
+
347
+ ### Optional structured error handler
348
+
349
+ ```ts
350
+ import { Hono } from "hono";
351
+ import { structuredErrorLogger } from "kite-x402-hono";
352
+
353
+ const app = new Hono();
354
+ app.onError(structuredErrorLogger({ sink: (line) => console.error(line) }));
355
+ ```
356
+
357
+ Register with `app.onError`, not `app.use`: Hono handles route exceptions internally before `next()` returns. This opt-in handler replaces the application's previous error handler. Every caught exception becomes a generic HTTP 500, including thrown HTTP exceptions; return deliberate business responses normally or compose a separate error policy. Existing `createApp()` behavior is unchanged unless you replace its handler explicitly.
358
+
359
+ Valid incoming `X-Request-ID` values are reused; missing/invalid IDs receive a UUID. IDs are correlation labels, not trusted identities. The response contains `{ error: "internal_error", requestId }` and `Cache-Control: no-store`. Logs are JSON; raw error messages are omitted by default. `includeStack: true` includes stacks only in server logs, which may then contain secrets. This handler does not emit `X-Trace-ID`. A custom outer request-ID middleware should preserve the response ID instead of replacing it.
360
+
361
+ ### Optional receipt cache and CORS allowlist
362
+
363
+ `ReceiptMemoryCache` stores caller-verified receipts with TTL (milliseconds) and LRU eviction. Both `get` and `has` refresh recency. Inputs/outputs are copied; atomic amounts accept bigint, decimal integer strings, or safe integers (uint256 range). This local cache does not verify payments, provide durable replay protection, or separate chains/assets: callers must scope instances and receipt IDs appropriately. Use the existing `ReceiptStore`/`SettlementReconciler` for indexed receipt queries and reconciliation.
364
+
365
+ `corsAllowlistValidator({ allowedDomains, credentials: false })` is optional middleware for explicit integration, replacing other CORS middleware. Strings are exact serialized HTTP(S) origins; regexes must match the whole origin, with global/sticky flags removed. Enable credentials explicitly only for trusted origins. Only valid preflights return 204; denied preflights return 403; ordinary OPTIONS continues downstream. Payment-Signature and Idempotency-Key are allowed, and payment response headers are exposed. CORS does not authenticate callers or block non-browser requests. Neither utility is automatically enabled by createApp.
package/README.zh-CN.md CHANGED
@@ -239,3 +239,15 @@ AI 工具参与了开发;BrK 审核并负责此贡献。项目自己的 Wrappe
239
239
  下一版本包含的可选组件、安全修正与使用边界见[PR 审查报告](docs/pr-review-2026-11-04.md)。这些工具需要显式接入,不会自动启用动态定价、付款验证缓存、Webhook、会话、分布式限流或响应压缩。默认使用连接 IP;部署在反向代理后时需显式配置可信代理。
240
240
 
241
241
  PR #52–#61 的审查结果与使用约定见 [11 月审查记录](docs/pr-review-2026-11-06.md)。新增工具需要显式接入应用。
242
+
243
+ ### 可选的结构化错误处理器
244
+
245
+ 通过 `app.onError(structuredErrorLogger({ sink: console.error }))` 显式注册;不要使用 `app.use`,因为 Hono 会先处理路由异常。该工具从包根目录导出,注册会替换原有异常处理器,所有捕获异常统一返回 500(包括抛出的 HTTP 异常);业务响应应正常返回,或另行组合异常策略。默认 `createApp()` 行为保持不变。
246
+
247
+ 响应为 `{ error: "internal_error", requestId }`,禁止缓存。沿用经过校验的 `X-Request-ID`,缺失或非法时生成 UUID;不再新增 `X-Trace-ID`。服务端输出 JSON 日志,默认不记录原始异常消息。`includeStack: true` 仅在服务端日志中加入堆栈,日志可能因此包含敏感信息。外层自定义请求 ID 中间件应保留错误响应已有的 ID。
248
+
249
+ ### 可选回执缓存与 CORS 白名单
250
+
251
+ `ReceiptMemoryCache` 提供毫秒 TTL 和 LRU 淘汰,读取及 has 查询都会更新访问顺序,输入输出均隔离复制。金额支持 uint256 范围的 bigint、十进制整数字符串或安全整数。它只保存调用者已经验证的回执,不提供支付验证、持久化防重放或自动跨链隔离;不同链和资产应使用独立实例或明确隔离的键。索引查询和对账可使用已有 ReceiptStore、SettlementReconciler。
252
+
253
+ `corsAllowlistValidator({ allowedDomains, credentials: false })` 需要显式接入并替换其他 CORS 中间件。字符串匹配完整 HTTP(S) origin,正则必须匹配整个 origin;凭证需要显式开启。仅合法浏览器预检返回 204,拒绝的预检返回 403,普通 OPTIONS 继续进入支付处理。支持 Payment-Signature、Idempotency-Key 并暴露支付响应头。CORS 不提供身份认证。两项工具均不会由 createApp 自动启用。
package/dist/index.d.ts CHANGED
@@ -32,3 +32,6 @@ export * from "./middleware/token-blacklist.js";
32
32
  export * from "./events/settlement-bus.js";
33
33
  export * from "./middleware/adaptiveRateLimiter.js";
34
34
  export * from "./utils/hmacSignatureVerifier.js";
35
+ export * from "./middleware/structuredErrorLogger.js";
36
+ export * from "./services/receiptMemoryCache.js";
37
+ export * from "./middleware/corsAllowlistValidator.js";
package/dist/index.js CHANGED
@@ -32,3 +32,6 @@ export * from "./middleware/token-blacklist.js";
32
32
  export * from "./events/settlement-bus.js";
33
33
  export * from "./middleware/adaptiveRateLimiter.js";
34
34
  export * from "./utils/hmacSignatureVerifier.js";
35
+ export * from "./middleware/structuredErrorLogger.js";
36
+ export * from "./services/receiptMemoryCache.js";
37
+ export * from "./middleware/corsAllowlistValidator.js";
@@ -0,0 +1,9 @@
1
+ import type { MiddlewareHandler } from "hono";
2
+ export interface CorsAllowlistOptions {
3
+ /** Exact serialized origins or full-origin regex matches. */
4
+ allowedDomains: (string | RegExp)[];
5
+ credentials?: boolean;
6
+ }
7
+ /** Explicit opt-in CORS policy; use instead of another CORS middleware. */
8
+ export declare function corsAllowlistValidator(options: CorsAllowlistOptions): MiddlewareHandler;
9
+ export default corsAllowlistValidator;
@@ -0,0 +1,77 @@
1
+ import { isSerializedOrigin } from "./cors-preflight-guard.js";
2
+ /** Explicit opt-in CORS policy; use instead of another CORS middleware. */
3
+ export function corsAllowlistValidator(options) {
4
+ const patterns = options.allowedDomains.map((p) => {
5
+ if (typeof p === "string") {
6
+ if (!isSerializedOrigin(p))
7
+ throw new Error("Invalid allowed origin");
8
+ return p;
9
+ }
10
+ return new RegExp(p.source, p.flags.replace(/[gy]/g, ""));
11
+ });
12
+ const credentials = options.credentials === true;
13
+ const methods = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
14
+ const headers = [
15
+ "content-type",
16
+ "authorization",
17
+ "payment-signature",
18
+ "idempotency-key",
19
+ "x-request-id",
20
+ ];
21
+ return async (c, next) => {
22
+ const origin = c.req.header("origin");
23
+ const requestedMethod = c.req.header("access-control-request-method");
24
+ const preflight = c.req.method === "OPTIONS" && !!origin && !!requestedMethod;
25
+ const allowed = !!origin &&
26
+ isSerializedOrigin(origin) &&
27
+ patterns.some((p) => {
28
+ if (typeof p === "string")
29
+ return p === origin;
30
+ const match = p.exec(origin);
31
+ return match !== null && match.index === 0 && match[0] === origin;
32
+ });
33
+ if (preflight) {
34
+ const requestedHeaders = c.req.header("access-control-request-headers");
35
+ const validHeaders = requestedHeaders === undefined ||
36
+ requestedHeaders
37
+ .split(",")
38
+ .every((h) => headers.includes(h.trim().toLowerCase()));
39
+ const vary = "Origin, Access-Control-Request-Method, Access-Control-Request-Headers";
40
+ if (!allowed || !methods.includes(requestedMethod) || !validHeaders)
41
+ return c.json({ error: "cors_preflight_denied" }, 403, {
42
+ Vary: vary,
43
+ "Cache-Control": "no-store",
44
+ });
45
+ return new Response(null, {
46
+ status: 204,
47
+ headers: {
48
+ Vary: vary,
49
+ "Cache-Control": "no-store",
50
+ "Access-Control-Allow-Origin": origin,
51
+ "Access-Control-Allow-Methods": methods.join(", "),
52
+ "Access-Control-Allow-Headers": headers.join(", "),
53
+ ...(credentials
54
+ ? { "Access-Control-Allow-Credentials": "true" }
55
+ : {}),
56
+ },
57
+ });
58
+ }
59
+ // Ordinary OPTIONS must reach payment/application middleware.
60
+ await next();
61
+ for (const key of [...c.res.headers.keys()])
62
+ if (key.toLowerCase().startsWith("access-control-"))
63
+ c.res.headers.delete(key);
64
+ const vary = c.res.headers.get("vary");
65
+ if (!vary
66
+ ?.split(",")
67
+ .some((v) => ["origin", "*"].includes(v.trim().toLowerCase())))
68
+ c.header("Vary", vary ? `${vary}, Origin` : "Origin");
69
+ if (allowed) {
70
+ c.header("Access-Control-Allow-Origin", origin);
71
+ if (credentials)
72
+ c.header("Access-Control-Allow-Credentials", "true");
73
+ c.header("Access-Control-Expose-Headers", "Payment-Required, Payment-Response, Retry-After, X-Request-ID, X-Response-Time");
74
+ }
75
+ };
76
+ }
77
+ export default corsAllowlistValidator;
@@ -0,0 +1,9 @@
1
+ import type { ErrorHandler } from "hono";
2
+ export interface StructuredErrorLoggerOptions {
3
+ /** Include stack traces in server logs only. Logs may contain sensitive data. */
4
+ includeStack?: boolean;
5
+ sink?: (line: string) => void;
6
+ }
7
+ /** Register with app.onError(); Hono handles exceptions before next() returns. */
8
+ export declare function structuredErrorLogger(options?: StructuredErrorLoggerOptions): ErrorHandler;
9
+ export default structuredErrorLogger;
@@ -0,0 +1,29 @@
1
+ const validId = /^[A-Za-z0-9._~-]{1,128}$/;
2
+ /** Register with app.onError(); Hono handles exceptions before next() returns. */
3
+ export function structuredErrorLogger(options = {}) {
4
+ const sink = options.sink ?? console.error;
5
+ return (err, c) => {
6
+ const candidate = c.req.header("x-request-id");
7
+ const requestId = candidate && validId.test(candidate) ? candidate : crypto.randomUUID();
8
+ // Arbitrary error.status/code/message values are never public response data.
9
+ const timestamp = new Date().toISOString();
10
+ try {
11
+ sink(JSON.stringify({
12
+ level: "error",
13
+ timestamp,
14
+ requestId,
15
+ status: 500,
16
+ error: "internal_error",
17
+ ...(options.includeStack && { stack: err.stack }),
18
+ }));
19
+ }
20
+ catch {
21
+ // A broken logging sink must not prevent the error response.
22
+ }
23
+ return c.json({ error: "internal_error", requestId }, 500, {
24
+ "x-request-id": requestId,
25
+ "cache-control": "no-store",
26
+ });
27
+ };
28
+ }
29
+ export default structuredErrorLogger;
@@ -0,0 +1,18 @@
1
+ export interface CachedReceipt {
2
+ receiptId: string;
3
+ payer: string;
4
+ /** Nonnegative atomic units; use bigint/string above the safe integer range. */
5
+ amount: bigint | string | number;
6
+ timestamp: number;
7
+ }
8
+ /** Local LRU storage of caller-verified receipts; not payment verification or durable replay protection. */
9
+ export declare class ReceiptMemoryCache {
10
+ private readonly defaultTtlMs;
11
+ private readonly maxCapacity;
12
+ private cache;
13
+ constructor(defaultTtlMs?: number, maxCapacity?: number);
14
+ set(receiptId: string, data: CachedReceipt, ttlMs?: number): void;
15
+ get(receiptId: string): CachedReceipt | null;
16
+ has(receiptId: string): boolean;
17
+ }
18
+ export default ReceiptMemoryCache;
@@ -0,0 +1,64 @@
1
+ /** Local LRU storage of caller-verified receipts; not payment verification or durable replay protection. */
2
+ export class ReceiptMemoryCache {
3
+ defaultTtlMs;
4
+ maxCapacity;
5
+ cache = new Map();
6
+ constructor(defaultTtlMs = 300000, maxCapacity = 1000) {
7
+ this.defaultTtlMs = defaultTtlMs;
8
+ this.maxCapacity = maxCapacity;
9
+ if (!Number.isSafeInteger(defaultTtlMs) ||
10
+ defaultTtlMs < 1 ||
11
+ !Number.isSafeInteger(maxCapacity) ||
12
+ maxCapacity < 1)
13
+ throw new Error("Invalid cache limits");
14
+ }
15
+ set(receiptId, data, ttlMs = this.defaultTtlMs) {
16
+ const now = Date.now();
17
+ if (!receiptId ||
18
+ receiptId.length > 512 ||
19
+ data.receiptId !== receiptId ||
20
+ !data.payer ||
21
+ data.payer.length > 512 ||
22
+ !Number.isSafeInteger(data.timestamp) ||
23
+ data.timestamp < 0 ||
24
+ !Number.isSafeInteger(ttlMs) ||
25
+ ttlMs < 1 ||
26
+ !Number.isSafeInteger(now + ttlMs) ||
27
+ !["bigint", "number", "string"].includes(typeof data.amount) ||
28
+ (typeof data.amount === "number" && !Number.isSafeInteger(data.amount)) ||
29
+ (typeof data.amount === "string" &&
30
+ (!/^\d+$/.test(data.amount) || data.amount.length > 256)) ||
31
+ BigInt(data.amount) < 0n ||
32
+ BigInt(data.amount) >= 1n << 256n)
33
+ throw new Error("Invalid receipt or TTL");
34
+ const copy = {
35
+ receiptId,
36
+ payer: data.payer,
37
+ amount: data.amount,
38
+ timestamp: data.timestamp,
39
+ };
40
+ for (const [key, entry] of this.cache)
41
+ if (entry.expiresAt <= now)
42
+ this.cache.delete(key);
43
+ this.cache.delete(receiptId);
44
+ if (this.cache.size >= this.maxCapacity)
45
+ this.cache.delete(this.cache.keys().next().value);
46
+ this.cache.set(receiptId, { data: copy, expiresAt: now + ttlMs });
47
+ }
48
+ get(receiptId) {
49
+ const entry = this.cache.get(receiptId);
50
+ if (!entry)
51
+ return null;
52
+ if (entry.expiresAt <= Date.now()) {
53
+ this.cache.delete(receiptId);
54
+ return null;
55
+ }
56
+ this.cache.delete(receiptId);
57
+ this.cache.set(receiptId, entry);
58
+ return { ...entry.data };
59
+ }
60
+ has(receiptId) {
61
+ return this.get(receiptId) !== null;
62
+ }
63
+ }
64
+ export default ReceiptMemoryCache;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kite-x402-hono",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Bun and Hono reverse proxy for x402 payments on Kite",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",