kite-x402-hono 0.4.0 → 0.6.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,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0
4
+
5
+ - 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.
6
+
7
+ ## 0.5.0
8
+
9
+ - Integrate reviewed PRs #52–#61, including fee snapshot isolation, atomic response cache updates, and per-network settlement reconciliation.
10
+ - Export optional readiness snapshots, origin validators, bounded JWT revocations, settlement notifications, trusted-identity sliding-window middleware, and HMAC verification.
11
+ - Repair mutable snapshots, stateful origin regex matching, unbounded revocations, unsafe event amounts, spoofable limiter keys, and unsigned webhook timestamps. See docs/pr-review-2026-11-06.md for API contracts and integration limits.
12
+
3
13
  ## 0.4.0
4
14
 
5
15
  - Integrate and review community PRs #22, #24, #28–#29, #31, #33–#51.
package/README.md CHANGED
@@ -341,3 +341,19 @@ Socket peer addresses are used by default (`TRUST_PROXY_HEADERS=false`). Direct
341
341
  ### Community component review
342
342
 
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
+
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.
package/README.zh-CN.md CHANGED
@@ -237,3 +237,11 @@ AI 工具参与了开发;BrK 审核并负责此贡献。项目自己的 Wrappe
237
237
  ### 社区组件审查
238
238
 
239
239
  下一版本包含的可选组件、安全修正与使用边界见[PR 审查报告](docs/pr-review-2026-11-04.md)。这些工具需要显式接入,不会自动启用动态定价、付款验证缓存、Webhook、会话、分布式限流或响应压缩。默认使用连接 IP;部署在反向代理后时需显式配置可信代理。
240
+
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。
@@ -0,0 +1,11 @@
1
+ import { EventEmitter } from "node:events";
2
+ export interface SettlementEvent {
3
+ payer: string;
4
+ /** Atomic units; use bigint/string for values above Number.MAX_SAFE_INTEGER. */
5
+ amount: bigint | string | number;
6
+ txHash: string;
7
+ }
8
+ /** Synchronous in-process notifications; listener exceptions propagate to caller. */
9
+ export declare class SettlementBus extends EventEmitter {
10
+ emitSettlement(event: SettlementEvent): boolean;
11
+ }
@@ -0,0 +1,14 @@
1
+ import { EventEmitter } from "node:events";
2
+ /** Synchronous in-process notifications; listener exceptions propagate to caller. */
3
+ export class SettlementBus extends EventEmitter {
4
+ emitSettlement(event) {
5
+ if (!event.payer ||
6
+ !event.txHash ||
7
+ (typeof event.amount === "number" &&
8
+ !Number.isSafeInteger(event.amount)) ||
9
+ (typeof event.amount === "string" && !/^\d+$/.test(event.amount)) ||
10
+ BigInt(event.amount) < 0n)
11
+ throw new Error("Invalid settlement event");
12
+ return this.emit("settlement", Object.freeze({ ...event }));
13
+ }
14
+ }
package/dist/index.d.ts CHANGED
@@ -25,3 +25,11 @@ export * from "./middleware/sliding-window-limiter.js";
25
25
  export * from "./middleware/cookie-session-store.js";
26
26
  export * from "./middleware/brotli-compression.js";
27
27
  export * from "./middleware/edge-rate-throttler.js";
28
+ export * from "./telemetry/readiness-probe.js";
29
+ export * from "./middleware/cors-preflight-guard.js";
30
+ export * from "./middleware/dynamic-cors.js";
31
+ export * from "./middleware/token-blacklist.js";
32
+ export * from "./events/settlement-bus.js";
33
+ export * from "./middleware/adaptiveRateLimiter.js";
34
+ export * from "./utils/hmacSignatureVerifier.js";
35
+ export * from "./middleware/structuredErrorLogger.js";
package/dist/index.js CHANGED
@@ -25,3 +25,11 @@ export * from "./middleware/sliding-window-limiter.js";
25
25
  export * from "./middleware/cookie-session-store.js";
26
26
  export * from "./middleware/brotli-compression.js";
27
27
  export * from "./middleware/edge-rate-throttler.js";
28
+ export * from "./telemetry/readiness-probe.js";
29
+ export * from "./middleware/cors-preflight-guard.js";
30
+ export * from "./middleware/dynamic-cors.js";
31
+ export * from "./middleware/token-blacklist.js";
32
+ export * from "./events/settlement-bus.js";
33
+ export * from "./middleware/adaptiveRateLimiter.js";
34
+ export * from "./utils/hmacSignatureVerifier.js";
35
+ export * from "./middleware/structuredErrorLogger.js";
@@ -0,0 +1,10 @@
1
+ import type { Context, MiddlewareHandler } from "hono";
2
+ export interface AdaptiveRateLimiterOptions {
3
+ windowMs?: number;
4
+ maxRequests?: number;
5
+ /** Resolve a verified identity or trusted socket IP; forwarding headers are untrusted. */
6
+ keyGenerator: (c: Context) => string;
7
+ }
8
+ /** Fixed-budget sliding window middleware (does not dynamically adapt budgets). */
9
+ export declare function adaptiveRateLimiter(options: AdaptiveRateLimiterOptions): MiddlewareHandler;
10
+ export default adaptiveRateLimiter;
@@ -0,0 +1,24 @@
1
+ import { SlidingWindowLimiter } from "./sliding-window-limiter.js";
2
+ /** Fixed-budget sliding window middleware (does not dynamically adapt budgets). */
3
+ export function adaptiveRateLimiter(options) {
4
+ if (typeof options?.keyGenerator !== "function")
5
+ throw new Error("A trusted keyGenerator is required");
6
+ const windowMs = options.windowMs ?? 60000;
7
+ const maxRequests = options.maxRequests ?? 120;
8
+ const limiter = new SlidingWindowLimiter(windowMs, maxRequests);
9
+ return async (c, next) => {
10
+ const key = options.keyGenerator(c);
11
+ if (typeof key !== "string" || !key || key.length > 512)
12
+ return c.json({ error: "Missing trusted client identity" }, 503);
13
+ const result = limiter.check(key);
14
+ c.header("X-RateLimit-Limit", String(maxRequests));
15
+ c.header("X-RateLimit-Remaining", String(result.remaining));
16
+ if (!result.allowed) {
17
+ c.header("Retry-After", String(result.resetSeconds));
18
+ c.header("X-RateLimit-Reset", String(Math.ceil(Date.now() / 1000) + result.resetSeconds));
19
+ return c.json({ error: "Too Many Requests" }, 429);
20
+ }
21
+ await next();
22
+ };
23
+ }
24
+ export default adaptiveRateLimiter;
@@ -0,0 +1,3 @@
1
+ /** Accept only serialized HTTP(S) origins, never URL paths or credentials. */
2
+ export declare function isSerializedOrigin(origin: string): boolean;
3
+ export declare function isValidCorsOrigin(origin: string | undefined, allowedOrigins: string[], credentials?: boolean): boolean;
@@ -0,0 +1,17 @@
1
+ /** Accept only serialized HTTP(S) origins, never URL paths or credentials. */
2
+ export function isSerializedOrigin(origin) {
3
+ try {
4
+ const url = new URL(origin);
5
+ return ["http:", "https:"].includes(url.protocol) && url.origin === origin;
6
+ }
7
+ catch {
8
+ return false;
9
+ }
10
+ }
11
+ export function isValidCorsOrigin(origin, allowedOrigins, credentials = false) {
12
+ if (!origin || !isSerializedOrigin(origin))
13
+ return false;
14
+ if (allowedOrigins.includes(origin))
15
+ return true;
16
+ return !credentials && allowedOrigins.includes("*");
17
+ }
@@ -0,0 +1,2 @@
1
+ /** Caller supplies an anchored hostname allowlist; HTTPS serialized origins only. */
2
+ export declare function matchSubdomainOrigin(origin: string, pattern: RegExp): boolean;
@@ -0,0 +1,11 @@
1
+ import { isSerializedOrigin } from "./cors-preflight-guard.js";
2
+ /** Caller supplies an anchored hostname allowlist; HTTPS serialized origins only. */
3
+ export function matchSubdomainOrigin(origin, pattern) {
4
+ if (!isSerializedOrigin(origin) || !origin.startsWith("https://"))
5
+ return false;
6
+ // Copy to avoid changing caller state and disable stateful matching flags.
7
+ const stable = new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ""));
8
+ const hostname = new URL(origin).hostname;
9
+ const match = stable.exec(hostname);
10
+ return match !== null && match.index === 0 && match[0] === hostname;
11
+ }
@@ -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,9 @@
1
+ /** In-process revocations. Expiry is Unix milliseconds, not JWT exp seconds. */
2
+ export declare class TokenBlacklist {
3
+ private readonly maxEntries;
4
+ private revokedJtis;
5
+ constructor(maxEntries?: number);
6
+ revoke(jti: string, expiresAt: number): void;
7
+ revokeJwt(jti: string, expSeconds: number): void;
8
+ isRevoked(jti: string): boolean;
9
+ }
@@ -0,0 +1,41 @@
1
+ /** In-process revocations. Expiry is Unix milliseconds, not JWT exp seconds. */
2
+ export class TokenBlacklist {
3
+ maxEntries;
4
+ revokedJtis = new Map();
5
+ constructor(maxEntries = 10000) {
6
+ this.maxEntries = maxEntries;
7
+ if (!Number.isSafeInteger(maxEntries) || maxEntries < 1)
8
+ throw new Error("Invalid blacklist capacity");
9
+ }
10
+ revoke(jti, expiresAt) {
11
+ if (!jti ||
12
+ jti.length > 512 ||
13
+ !Number.isSafeInteger(expiresAt) ||
14
+ expiresAt < 0)
15
+ throw new Error("Invalid revocation");
16
+ const now = Date.now();
17
+ for (const [key, expiry] of this.revokedJtis)
18
+ if (expiry <= now)
19
+ this.revokedJtis.delete(key);
20
+ if (expiresAt <= now)
21
+ return;
22
+ if (!this.revokedJtis.has(jti) && this.revokedJtis.size >= this.maxEntries)
23
+ throw new Error("Blacklist capacity reached");
24
+ this.revokedJtis.set(jti, Math.max(expiresAt, this.revokedJtis.get(jti) ?? 0));
25
+ }
26
+ revokeJwt(jti, expSeconds) {
27
+ if (!Number.isSafeInteger(expSeconds))
28
+ throw new Error("Invalid JWT expiry");
29
+ this.revoke(jti, expSeconds * 1000);
30
+ }
31
+ isRevoked(jti) {
32
+ const expiry = this.revokedJtis.get(jti);
33
+ if (expiry === undefined)
34
+ return false;
35
+ if (expiry <= Date.now()) {
36
+ this.revokedJtis.delete(jti);
37
+ return false;
38
+ }
39
+ return true;
40
+ }
41
+ }
@@ -36,21 +36,20 @@ export class ResponseCacheStore {
36
36
  set(key, body, status, headers = {}, ttlSeconds) {
37
37
  if (Buffer.byteLength(body) > 1024 * 1024)
38
38
  throw new Error("Cached response exceeds 1 MiB");
39
- for (const [id, entry] of this.cache)
40
- if (entry.expiresAt <= Date.now())
41
- this.cache.delete(id);
42
- this.cache.delete(key);
43
- const bytes = [...this.cache.values()].reduce((n, e) => n + Buffer.byteLength(e.body), 0);
44
- if (bytes + Buffer.byteLength(body) > 32 * 1024 * 1024)
45
- throw new Error("Response cache exceeds 32 MiB");
46
- if (this.cache.size >= this.maxEntries) {
47
- const oldestKey = this.cache.keys().next().value;
48
- if (oldestKey)
49
- this.cache.delete(oldestKey);
50
- }
51
39
  const ttlMs = ttlSeconds === undefined ? this.defaultTtlMs : ttlSeconds * 1000;
52
- if (!Number.isFinite(ttlMs) || ttlMs <= 0)
40
+ const now = Date.now();
41
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0 || !Number.isFinite(now + ttlMs))
53
42
  throw new Error("Invalid cache TTL");
43
+ // Stage the replacement: validation failures must not remove live entries.
44
+ const next = new Map([...this.cache].filter(([id, entry]) => id !== key && entry.expiresAt > now));
45
+ if (next.size >= this.maxEntries) {
46
+ const oldest = next.keys().next().value;
47
+ if (oldest !== undefined)
48
+ next.delete(oldest);
49
+ }
50
+ const bytes = [...next.values()].reduce((n, entry) => n + Buffer.byteLength(entry.body), 0);
51
+ if (bytes + Buffer.byteLength(body) > 32 * 1024 * 1024)
52
+ throw new Error("Response cache exceeds 32 MiB");
54
53
  const etag = this.generateEtag(body);
55
54
  const entry = {
56
55
  body,
@@ -61,10 +60,11 @@ export class ResponseCacheStore {
61
60
  "Cache-Control": "private, no-store",
62
61
  },
63
62
  etag,
64
- createdAt: Date.now(),
65
- expiresAt: Date.now() + ttlMs,
63
+ createdAt: now,
64
+ expiresAt: now + ttlMs,
66
65
  };
67
- this.cache.set(key, entry);
66
+ next.set(key, entry);
67
+ this.cache = next;
68
68
  return structuredClone(entry);
69
69
  }
70
70
  clear() {
@@ -29,12 +29,14 @@ export declare class SettlementReconciler {
29
29
  private receiptsByPayer;
30
30
  private orderedTxHashes;
31
31
  private readonly maxCapacity;
32
- constructor(maxCapacity?: number);
32
+ private network;
33
+ constructor(maxCapacity?: number, network?: string);
33
34
  record(receipt: SettlementReceipt): void;
34
35
  getByTxHash(txHash: string): SettlementReceipt | undefined;
35
36
  getByPayer(payer: string): SettlementReceipt[];
36
37
  query(filter?: SettlementQuery): SettlementReceipt[];
37
38
  getSummary(): ReconcilerSummary;
38
39
  size(): number;
40
+ /** The network binding survives clear; use a new instance for another network. */
39
41
  clear(): void;
40
42
  }
@@ -8,15 +8,23 @@ export class SettlementReconciler {
8
8
  receiptsByPayer = new Map();
9
9
  orderedTxHashes = [];
10
10
  maxCapacity;
11
- constructor(maxCapacity = 5_000) {
11
+ network;
12
+ constructor(maxCapacity = 5_000, network) {
12
13
  if (!Number.isSafeInteger(maxCapacity) || maxCapacity < 1)
13
14
  throw new Error("Invalid receipt capacity");
15
+ if (network !== undefined && (!network || network.trim() !== network))
16
+ throw new Error("Invalid settlement network");
14
17
  this.maxCapacity = maxCapacity;
18
+ this.network = network;
15
19
  }
16
20
  record(receipt) {
17
21
  if (!receipt.txHash) {
18
22
  throw new Error("Missing transaction hash in settlement receipt");
19
23
  }
24
+ if (!receipt.network || receipt.network.trim() !== receipt.network)
25
+ throw new Error("Invalid settlement network");
26
+ if (this.network !== undefined && receipt.network !== this.network)
27
+ throw new Error("Settlement network does not match this reconciler");
20
28
  const txKey = receipt.txHash.toLowerCase();
21
29
  const payerKey = receipt.payer.toLowerCase();
22
30
  if (this.receiptsByTx.has(txKey))
@@ -40,6 +48,7 @@ export class SettlementReconciler {
40
48
  }
41
49
  }
42
50
  }
51
+ this.network ??= receipt.network;
43
52
  this.receiptsByTx.set(txKey, receipt);
44
53
  this.orderedTxHashes.push(txKey);
45
54
  const payerList = this.receiptsByPayer.get(payerKey) ?? [];
@@ -99,6 +108,7 @@ export class SettlementReconciler {
99
108
  size() {
100
109
  return this.receiptsByTx.size;
101
110
  }
111
+ /** The network binding survives clear; use a new instance for another network. */
102
112
  clear() {
103
113
  this.receiptsByTx.clear();
104
114
  this.receiptsByPayer.clear();
@@ -0,0 +1,13 @@
1
+ export interface ProbeResult {
2
+ ready: boolean;
3
+ checkedAt: number;
4
+ details: Record<string, boolean>;
5
+ }
6
+ export declare class CachedReadinessProbe {
7
+ private lastResult;
8
+ private ttlMs;
9
+ constructor(ttlMs?: number);
10
+ /** Returns a fresh snapshot or null; expired readiness is never served. */
11
+ getCachedOrStale(): ProbeResult | null;
12
+ recordStatus(ready: boolean, details: Record<string, boolean>): ProbeResult;
13
+ }
@@ -0,0 +1,26 @@
1
+ export class CachedReadinessProbe {
2
+ lastResult = null;
3
+ ttlMs;
4
+ constructor(ttlMs = 5000) {
5
+ if (!Number.isSafeInteger(ttlMs) || ttlMs < 1)
6
+ throw new Error("Invalid probe TTL");
7
+ this.ttlMs = ttlMs;
8
+ }
9
+ /** Returns a fresh snapshot or null; expired readiness is never served. */
10
+ getCachedOrStale() {
11
+ if (!this.lastResult)
12
+ return null;
13
+ if (Date.now() - this.lastResult.checkedAt >= this.ttlMs)
14
+ return null;
15
+ return structuredClone(this.lastResult);
16
+ }
17
+ recordStatus(ready, details) {
18
+ const result = {
19
+ ready,
20
+ checkedAt: Date.now(),
21
+ details: { ...details },
22
+ };
23
+ this.lastResult = result;
24
+ return structuredClone(result);
25
+ }
26
+ }
@@ -25,7 +25,9 @@ export class TieredFeeScheduler {
25
25
  tier.discountBps > 10000)
26
26
  throw new Error("Invalid fee tier");
27
27
  // Sort descending by minCumulativeVolumeAtomic for waterfall evaluation
28
- this.tiers = [...unsortedTiers].sort((a, b) => b.minCumulativeVolumeAtomic > a.minCumulativeVolumeAtomic ? 1 : -1);
28
+ this.tiers = unsortedTiers
29
+ .map((tier) => ({ ...tier }))
30
+ .sort((a, b) => b.minCumulativeVolumeAtomic > a.minCumulativeVolumeAtomic ? 1 : -1);
29
31
  }
30
32
  /**
31
33
  * Records a settled payment for a client.
@@ -57,7 +59,7 @@ export class TieredFeeScheduler {
57
59
  record.lastUpdatedMs = now;
58
60
  }
59
61
  this.clientVolumes.set(key, record);
60
- return record;
62
+ return { ...record };
61
63
  }
62
64
  /**
63
65
  * Evaluates the active tier and computes the discounted payment price.
@@ -101,7 +103,8 @@ export class TieredFeeScheduler {
101
103
  * Retrieves client record.
102
104
  */
103
105
  getClientRecord(clientAddress) {
104
- return this.clientVolumes.get(clientAddress.toLowerCase());
106
+ const record = this.clientVolumes.get(clientAddress.toLowerCase());
107
+ return record ? { ...record } : undefined;
105
108
  }
106
109
  /**
107
110
  * Resets all volume records.
@@ -0,0 +1,10 @@
1
+ export interface HmacVerificationResult {
2
+ isValid: boolean;
3
+ error?: string;
4
+ }
5
+ /** Raw payload mode matches WebhookDispatcher. Timestamp mode signs `${timestamp}.${payload}`
6
+ * with a Unix-millisecond timestamp; a timestamp must never be unsigned replay protection.
7
+ * Callers must also deduplicate event IDs to prevent replay inside the tolerance window.
8
+ */
9
+ export declare function verifyHmacSignature(payload: string, secret: string, signatureHex: string, timestampHeader?: string, maxToleranceMs?: number): Promise<HmacVerificationResult>;
10
+ export default verifyHmacSignature;
@@ -0,0 +1,26 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ /** Raw payload mode matches WebhookDispatcher. Timestamp mode signs `${timestamp}.${payload}`
3
+ * with a Unix-millisecond timestamp; a timestamp must never be unsigned replay protection.
4
+ * Callers must also deduplicate event IDs to prevent replay inside the tolerance window.
5
+ */
6
+ export async function verifyHmacSignature(payload, secret, signatureHex, timestampHeader, maxToleranceMs = 300000) {
7
+ if (Buffer.byteLength(secret) < 32 ||
8
+ !/^[a-fA-F0-9]{64}$/.test(signatureHex) ||
9
+ !Number.isSafeInteger(maxToleranceMs) ||
10
+ maxToleranceMs < 0)
11
+ return { isValid: false, error: "Invalid signature parameters" };
12
+ let message = payload;
13
+ if (timestampHeader !== undefined) {
14
+ const timestamp = Number(timestampHeader);
15
+ if (!/^\d+$/.test(timestampHeader) ||
16
+ !Number.isSafeInteger(timestamp) ||
17
+ Math.abs(Date.now() - timestamp) > maxToleranceMs)
18
+ return { isValid: false, error: "Invalid or expired timestamp" };
19
+ message = `${timestampHeader}.${payload}`;
20
+ }
21
+ const expected = createHmac("sha256", secret).update(message).digest();
22
+ return {
23
+ isValid: timingSafeEqual(expected, Buffer.from(signatureHex, "hex")),
24
+ };
25
+ }
26
+ export default verifyHmacSignature;
@@ -0,0 +1,22 @@
1
+ # PR review: 2026-11-06
2
+
3
+ Reviewed and integrated PRs #52–#61. These changes are included in the 0.5.0 release.
4
+
5
+ ## Repairs and behavior
6
+
7
+ - #52: `CachedReadinessProbe` is a manually populated snapshot cache, distinct from the existing active `ReadinessProbe`. Validate TTL, copy input/output, expire at the exact boundary. `getCachedOrStale()` returns null when expired despite its historical name. No new Kubernetes route is installed.
8
+ - #53: `isValidCorsOrigin` accepts serialized HTTP(S) origins only. Wildcard does not authorize credentialed requests; explicit origins may. The optional third argument defaults to false (no credentials).
9
+ - #54: `TokenBlacklist.revoke` accepts Unix milliseconds. `revokeJwt` explicitly converts JWT exp seconds. Expired records are reclaimed on writes, capacity defaults to 10,000, and a full store throws rather than evicting a live revocation. Callers must fail closed on capacity errors. Re-revocation cannot shorten an existing expiry. State is local to the process and is lost on restart.
10
+ - #55: `matchSubdomainOrigin` requires a serialized HTTPS origin and a full hostname regex match. Copies regex state and removes global/sticky flags. Callers remain responsible for their allowlist pattern and any port restrictions; this helper does not hardcode Kite domains.
11
+ - #56: settlement notifications preserve large atomic amounts via bigint/string and reject unsafe numeric amounts. Events are frozen snapshots. This is a synchronous EventEmitter: listener errors propagate, listeners need explicit removal, events have no persistence, deduplication, or delivery guarantee. Do not allow a notification exception to retry an already settled payment.
12
+ - #57: fee tiers and returned client records are copied, preventing external mutation of retained pricing/volume state.
13
+ - #58: stage cache replacements before eviction so an invalid write cannot destroy a valid entry. Existing privacy/size limits remain in force.
14
+ - #59: settlement reconciler binds to one network, inferred from its first receipt or supplied to its constructor. The binding survives clear; use a separate instance per network. This prevents mixed-chain totals and transaction-hash collisions across networks.
15
+ - #60: reuse the bounded `SlidingWindowLimiter`; require a trusted `keyGenerator` instead of trusting forwarding headers. Validate options, emit Retry-After, reject missing identities. Despite its inherited name, `adaptiveRateLimiter` implements a fixed sliding-window budget, not dynamic adaptation. The options type is `AdaptiveRateLimiterOptions` to avoid colliding with the existing public limiter type.
16
+ - #61: strict 64-character hex HMAC-SHA256 verification, minimum 32-byte secret, strict Unix-millisecond timestamp validation. Raw-payload mode matches `WebhookDispatcher.signPayload`. When a timestamp argument is supplied, sender must sign `timestamp + "." + payload`; changing an unsigned timestamp cannot refresh an old signature. Existing dispatcher sends raw-payload signatures without a timestamp header. Callers must deduplicate event IDs and, in raw mode, separately validate a timestamp inside the authenticated payload if freshness is required.
17
+
18
+ All new utilities are public exports but require explicit application integration. Existing proxy routes, JWT authentication, CORS settings and settlement dispatch are not automatically changed by importing them.
19
+
20
+ ## Validation
21
+
22
+ 271 tests passed across 44 files, including focused tests for expiry boundaries, snapshot isolation, CORS hostname attacks, blacklist capacity, precise settlement amounts, forwarded-header spoofing, malformed signatures and signed timestamps. Typecheck and TypeScript build passed. No real on-chain payment or production JWT infrastructure was exercised.
@@ -0,0 +1,5 @@
1
+ # Settlement network scope
2
+
3
+ A SettlementReconciler instance holds receipts for one network. Pass the network as the second constructor argument to bind it before the first record, or omit it to bind to the first accepted receipt. This preserves existing single-network callers while rejecting mixed-network data before deduplication or eviction.
4
+
5
+ Use a separate instance for each network (and asset/atomic unit). The summary adds raw atomic amounts; it does not convert currencies. clear() removes receipts but retains the network binding. Construct a new instance to change networks. Hash-only lookup is unambiguous within a bound instance.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kite-x402-hono",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Bun and Hono reverse proxy for x402 payments on Kite",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",