@absol-labs/agent 0.11.0 → 0.12.0-rc.1

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.
Files changed (350) hide show
  1. package/README.md +42 -50
  2. package/dist/capability/invocation-capability.d.ts +2 -2
  3. package/dist/capability/probe-capability.d.ts +225 -0
  4. package/dist/capability/probe-capability.d.ts.map +1 -0
  5. package/dist/capability/probe-capability.js +248 -0
  6. package/dist/capability/probe-capability.js.map +1 -0
  7. package/dist/cli/args.d.ts +11 -0
  8. package/dist/cli/args.d.ts.map +1 -1
  9. package/dist/cli/args.js +23 -0
  10. package/dist/cli/args.js.map +1 -1
  11. package/dist/cli/commands/claim.js +1 -1
  12. package/dist/cli/commands/claim.js.map +1 -1
  13. package/dist/cli/commands/close.d.ts.map +1 -1
  14. package/dist/cli/commands/close.js +35 -3
  15. package/dist/cli/commands/close.js.map +1 -1
  16. package/dist/cli/commands/invoke.d.ts +2 -0
  17. package/dist/cli/commands/invoke.d.ts.map +1 -1
  18. package/dist/cli/commands/invoke.js +2 -2
  19. package/dist/cli/commands/invoke.js.map +1 -1
  20. package/dist/cli/commands/mcp.d.ts.map +1 -1
  21. package/dist/cli/commands/mcp.js +15 -2
  22. package/dist/cli/commands/mcp.js.map +1 -1
  23. package/dist/cli/commands/open.d.ts.map +1 -1
  24. package/dist/cli/commands/open.js +58 -4
  25. package/dist/cli/commands/open.js.map +1 -1
  26. package/dist/cli/commands/pay.d.ts +19 -0
  27. package/dist/cli/commands/pay.d.ts.map +1 -0
  28. package/dist/cli/commands/pay.js +355 -0
  29. package/dist/cli/commands/pay.js.map +1 -0
  30. package/dist/cli/commands/reclaim-unverified.d.ts.map +1 -1
  31. package/dist/cli/commands/reclaim-unverified.js +3 -2
  32. package/dist/cli/commands/reclaim-unverified.js.map +1 -1
  33. package/dist/cli/commands/reclaim.d.ts +23 -2
  34. package/dist/cli/commands/reclaim.d.ts.map +1 -1
  35. package/dist/cli/commands/reclaim.js +184 -16
  36. package/dist/cli/commands/reclaim.js.map +1 -1
  37. package/dist/cli/commands/refund.d.ts +13 -0
  38. package/dist/cli/commands/refund.d.ts.map +1 -0
  39. package/dist/cli/commands/refund.js +224 -0
  40. package/dist/cli/commands/refund.js.map +1 -0
  41. package/dist/cli/commands/status.d.ts.map +1 -1
  42. package/dist/cli/commands/status.js +10 -1
  43. package/dist/cli/commands/status.js.map +1 -1
  44. package/dist/cli/commands/streams.js +8 -12
  45. package/dist/cli/commands/streams.js.map +1 -1
  46. package/dist/cli/commands/watch.d.ts.map +1 -1
  47. package/dist/cli/commands/watch.js +2 -1
  48. package/dist/cli/commands/watch.js.map +1 -1
  49. package/dist/cli/config.d.ts +44 -26
  50. package/dist/cli/config.d.ts.map +1 -1
  51. package/dist/cli/config.js +88 -38
  52. package/dist/cli/config.js.map +1 -1
  53. package/dist/cli/deps.d.ts +33 -0
  54. package/dist/cli/deps.d.ts.map +1 -1
  55. package/dist/cli/deps.js +37 -1
  56. package/dist/cli/deps.js.map +1 -1
  57. package/dist/cli/errors.d.ts.map +1 -1
  58. package/dist/cli/errors.js +21 -1
  59. package/dist/cli/errors.js.map +1 -1
  60. package/dist/cli/escape-hatch.d.ts +6 -4
  61. package/dist/cli/escape-hatch.d.ts.map +1 -1
  62. package/dist/cli/escape-hatch.js +6 -2
  63. package/dist/cli/escape-hatch.js.map +1 -1
  64. package/dist/cli/listings.d.ts +18 -0
  65. package/dist/cli/listings.d.ts.map +1 -1
  66. package/dist/cli/listings.js +22 -12
  67. package/dist/cli/listings.js.map +1 -1
  68. package/dist/cli/preflight.d.ts +20 -14
  69. package/dist/cli/preflight.d.ts.map +1 -1
  70. package/dist/cli/preflight.js +34 -20
  71. package/dist/cli/preflight.js.map +1 -1
  72. package/dist/cli/privy.d.ts.map +1 -1
  73. package/dist/cli/privy.js +4 -2
  74. package/dist/cli/privy.js.map +1 -1
  75. package/dist/cli/reclaimability.d.ts +82 -0
  76. package/dist/cli/reclaimability.d.ts.map +1 -0
  77. package/dist/cli/reclaimability.js +80 -0
  78. package/dist/cli/reclaimability.js.map +1 -0
  79. package/dist/cli/run.d.ts +2 -1
  80. package/dist/cli/run.d.ts.map +1 -1
  81. package/dist/cli/run.js +40 -11
  82. package/dist/cli/run.js.map +1 -1
  83. package/dist/cli/scan-range.d.ts +2 -2
  84. package/dist/cli/scan-range.js +2 -2
  85. package/dist/cli/status.d.ts +3 -1
  86. package/dist/cli/status.d.ts.map +1 -1
  87. package/dist/cli/status.js +15 -3
  88. package/dist/cli/status.js.map +1 -1
  89. package/dist/cli/wallet.d.ts +1 -1
  90. package/dist/cli/wallet.js +2 -2
  91. package/dist/cli/wallet.js.map +1 -1
  92. package/dist/discovery/rate-band.d.ts +74 -0
  93. package/dist/discovery/rate-band.d.ts.map +1 -0
  94. package/dist/discovery/rate-band.js +114 -0
  95. package/dist/discovery/rate-band.js.map +1 -0
  96. package/dist/escrow-generation.d.ts +81 -0
  97. package/dist/escrow-generation.d.ts.map +1 -0
  98. package/dist/escrow-generation.js +76 -0
  99. package/dist/escrow-generation.js.map +1 -0
  100. package/dist/frameworks/agentkit.d.ts +8 -4
  101. package/dist/frameworks/agentkit.d.ts.map +1 -1
  102. package/dist/frameworks/agentkit.js +27 -10
  103. package/dist/frameworks/agentkit.js.map +1 -1
  104. package/dist/frameworks/eliza.d.ts +3 -3
  105. package/dist/frameworks/eliza.d.ts.map +1 -1
  106. package/dist/frameworks/eliza.js +15 -6
  107. package/dist/frameworks/eliza.js.map +1 -1
  108. package/dist/frameworks/langchain.d.ts.map +1 -1
  109. package/dist/frameworks/langchain.js +8 -0
  110. package/dist/frameworks/langchain.js.map +1 -1
  111. package/dist/gateway/caller-auth-gateway.d.ts +83 -31
  112. package/dist/gateway/caller-auth-gateway.d.ts.map +1 -1
  113. package/dist/gateway/caller-auth-gateway.js +180 -27
  114. package/dist/gateway/caller-auth-gateway.js.map +1 -1
  115. package/dist/gateway/http-server.d.ts +111 -44
  116. package/dist/gateway/http-server.d.ts.map +1 -1
  117. package/dist/gateway/http-server.js +439 -155
  118. package/dist/gateway/http-server.js.map +1 -1
  119. package/dist/gateway/probe-auth.d.ts +112 -0
  120. package/dist/gateway/probe-auth.d.ts.map +1 -0
  121. package/dist/gateway/probe-auth.js +127 -0
  122. package/dist/gateway/probe-auth.js.map +1 -0
  123. package/dist/gateway/signed-rate-bounds.d.ts +51 -0
  124. package/dist/gateway/signed-rate-bounds.d.ts.map +1 -0
  125. package/dist/gateway/signed-rate-bounds.js +94 -0
  126. package/dist/gateway/signed-rate-bounds.js.map +1 -0
  127. package/dist/gateway/x402-opener-mode.d.ts +215 -0
  128. package/dist/gateway/x402-opener-mode.d.ts.map +1 -0
  129. package/dist/gateway/x402-opener-mode.js +639 -0
  130. package/dist/gateway/x402-opener-mode.js.map +1 -0
  131. package/dist/index.d.ts +6 -2
  132. package/dist/index.d.ts.map +1 -1
  133. package/dist/index.js +10 -5
  134. package/dist/index.js.map +1 -1
  135. package/dist/mcp/server.d.ts +52 -1
  136. package/dist/mcp/server.d.ts.map +1 -1
  137. package/dist/mcp/server.js +228 -37
  138. package/dist/mcp/server.js.map +1 -1
  139. package/dist/mcp/x402-tools.d.ts +104 -0
  140. package/dist/mcp/x402-tools.d.ts.map +1 -0
  141. package/dist/mcp/x402-tools.js +434 -0
  142. package/dist/mcp/x402-tools.js.map +1 -0
  143. package/dist/network.d.ts +119 -0
  144. package/dist/network.d.ts.map +1 -0
  145. package/dist/network.js +199 -0
  146. package/dist/network.js.map +1 -0
  147. package/dist/sdk/invoke.d.ts +4 -0
  148. package/dist/sdk/invoke.d.ts.map +1 -1
  149. package/dist/sdk/invoke.js +2 -5
  150. package/dist/sdk/invoke.js.map +1 -1
  151. package/dist/wallet/autonomous-wallet-broker.d.ts +3 -0
  152. package/dist/wallet/autonomous-wallet-broker.d.ts.map +1 -1
  153. package/dist/wallet/autonomous-wallet-broker.js +27 -23
  154. package/dist/wallet/autonomous-wallet-broker.js.map +1 -1
  155. package/dist/wallet/autonomous-wallet-protocol.d.ts +8 -2
  156. package/dist/wallet/autonomous-wallet-protocol.d.ts.map +1 -1
  157. package/dist/wallet/autonomous-wallet-protocol.js +9 -2
  158. package/dist/wallet/autonomous-wallet-protocol.js.map +1 -1
  159. package/dist/wallet/autonomous-wallet.d.ts.map +1 -1
  160. package/dist/wallet/autonomous-wallet.js +3 -2
  161. package/dist/wallet/autonomous-wallet.js.map +1 -1
  162. package/dist/wallet/broker-escrows.d.ts +222 -0
  163. package/dist/wallet/broker-escrows.d.ts.map +1 -0
  164. package/dist/wallet/broker-escrows.js +36 -0
  165. package/dist/wallet/broker-escrows.js.map +1 -0
  166. package/dist/wallet/lifecycle.d.ts +21 -5
  167. package/dist/wallet/lifecycle.d.ts.map +1 -1
  168. package/dist/wallet/lifecycle.js +32 -12
  169. package/dist/wallet/lifecycle.js.map +1 -1
  170. package/dist/wallet/privy-broker-server.d.ts.map +1 -1
  171. package/dist/wallet/privy-broker-server.js +31 -26
  172. package/dist/wallet/privy-broker-server.js.map +1 -1
  173. package/dist/wallet/privy-session-broker.d.ts +14 -5
  174. package/dist/wallet/privy-session-broker.d.ts.map +1 -1
  175. package/dist/wallet/privy-session-broker.js +29 -17
  176. package/dist/wallet/privy-session-broker.js.map +1 -1
  177. package/dist/wallet/privy-session-provider.d.ts +3 -1
  178. package/dist/wallet/privy-session-provider.d.ts.map +1 -1
  179. package/dist/wallet/privy-session-provider.js +5 -3
  180. package/dist/wallet/privy-session-provider.js.map +1 -1
  181. package/dist/wallet/provider.d.ts.map +1 -1
  182. package/dist/wallet/provider.js +15 -8
  183. package/dist/wallet/provider.js.map +1 -1
  184. package/dist/x402/facilitator.d.ts +3 -30
  185. package/dist/x402/facilitator.d.ts.map +1 -1
  186. package/dist/x402/facilitator.js +0 -27
  187. package/dist/x402/facilitator.js.map +1 -1
  188. package/dist/x402-buyer/guarded-fetch.d.ts +51 -0
  189. package/dist/x402-buyer/guarded-fetch.d.ts.map +1 -0
  190. package/dist/x402-buyer/guarded-fetch.js +147 -0
  191. package/dist/x402-buyer/guarded-fetch.js.map +1 -0
  192. package/dist/x402-buyer/index.d.ts +10 -0
  193. package/dist/x402-buyer/index.d.ts.map +1 -0
  194. package/dist/x402-buyer/index.js +10 -0
  195. package/dist/x402-buyer/index.js.map +1 -0
  196. package/dist/x402-buyer/pay.d.ts +135 -0
  197. package/dist/x402-buyer/pay.d.ts.map +1 -0
  198. package/dist/x402-buyer/pay.js +336 -0
  199. package/dist/x402-buyer/pay.js.map +1 -0
  200. package/dist/x402-opener/abi.d.ts +684 -0
  201. package/dist/x402-opener/abi.d.ts.map +1 -0
  202. package/dist/x402-opener/abi.js +880 -0
  203. package/dist/x402-opener/abi.js.map +1 -0
  204. package/dist/x402-opener/facilitator-entry.d.ts +3 -0
  205. package/dist/x402-opener/facilitator-entry.d.ts.map +1 -0
  206. package/dist/x402-opener/facilitator-entry.js +37 -0
  207. package/dist/x402-opener/facilitator-entry.js.map +1 -0
  208. package/dist/x402-opener/facilitator-server.d.ts +180 -0
  209. package/dist/x402-opener/facilitator-server.d.ts.map +1 -0
  210. package/dist/x402-opener/facilitator-server.js +696 -0
  211. package/dist/x402-opener/facilitator-server.js.map +1 -0
  212. package/dist/x402-opener/index.d.ts +14 -0
  213. package/dist/x402-opener/index.d.ts.map +1 -0
  214. package/dist/x402-opener/index.js +14 -0
  215. package/dist/x402-opener/index.js.map +1 -0
  216. package/dist/x402-opener/listing-resolver.d.ts +55 -0
  217. package/dist/x402-opener/listing-resolver.d.ts.map +1 -0
  218. package/dist/x402-opener/listing-resolver.js +125 -0
  219. package/dist/x402-opener/listing-resolver.js.map +1 -0
  220. package/dist/x402-opener/refund-relay.d.ts +240 -0
  221. package/dist/x402-opener/refund-relay.d.ts.map +1 -0
  222. package/dist/x402-opener/refund-relay.js +1240 -0
  223. package/dist/x402-opener/refund-relay.js.map +1 -0
  224. package/dist/x402-opener/relayer-queue.d.ts +14 -0
  225. package/dist/x402-opener/relayer-queue.d.ts.map +1 -0
  226. package/dist/x402-opener/relayer-queue.js +18 -0
  227. package/dist/x402-opener/relayer-queue.js.map +1 -0
  228. package/dist/x402-opener/scheme.d.ts +217 -0
  229. package/dist/x402-opener/scheme.d.ts.map +1 -0
  230. package/dist/x402-opener/scheme.js +749 -0
  231. package/dist/x402-opener/scheme.js.map +1 -0
  232. package/dist/x402-opener/terms.d.ts +105 -0
  233. package/dist/x402-opener/terms.d.ts.map +1 -0
  234. package/dist/x402-opener/terms.js +212 -0
  235. package/dist/x402-opener/terms.js.map +1 -0
  236. package/dist/zktls/reclaim.d.ts +2 -2
  237. package/dist/zktls/t2-delivery-proof.d.ts +6 -6
  238. package/docs/agent-layer.md +3 -2
  239. package/docs/autonomous-privy-wallet.md +188 -0
  240. package/docs/cli.md +184 -31
  241. package/docs/langchain.md +5 -0
  242. package/docs/mcp-reference.md +75 -5
  243. package/docs/probe-capability.md +191 -0
  244. package/docs/quickstart.md +36 -1
  245. package/docs/threat-model.md +20 -0
  246. package/docs/x402.md +628 -595
  247. package/package.json +19 -17
  248. package/src/capability/probe-capability.ts +355 -0
  249. package/src/cli/args.ts +29 -0
  250. package/src/cli/commands/claim.ts +1 -1
  251. package/src/cli/commands/close.ts +36 -3
  252. package/src/cli/commands/invoke.ts +5 -2
  253. package/src/cli/commands/mcp.ts +18 -2
  254. package/src/cli/commands/open.ts +75 -4
  255. package/src/cli/commands/pay.ts +442 -0
  256. package/src/cli/commands/reclaim-unverified.ts +8 -2
  257. package/src/cli/commands/reclaim.ts +252 -14
  258. package/src/cli/commands/refund.ts +277 -0
  259. package/src/cli/commands/status.ts +17 -1
  260. package/src/cli/commands/streams.ts +10 -14
  261. package/src/cli/commands/watch.ts +7 -1
  262. package/src/cli/config.ts +139 -52
  263. package/src/cli/deps.ts +74 -1
  264. package/src/cli/errors.ts +24 -1
  265. package/src/cli/escape-hatch.ts +19 -5
  266. package/src/cli/listings.ts +43 -10
  267. package/src/cli/preflight.ts +36 -21
  268. package/src/cli/privy.ts +4 -2
  269. package/src/cli/reclaimability.ts +154 -0
  270. package/src/cli/run.ts +54 -11
  271. package/src/cli/scan-range.ts +2 -2
  272. package/src/cli/status.ts +14 -1
  273. package/src/cli/wallet.ts +2 -2
  274. package/src/discovery/rate-band.ts +172 -0
  275. package/src/escrow-generation.ts +135 -0
  276. package/src/frameworks/agentkit.ts +45 -11
  277. package/src/frameworks/eliza.ts +27 -5
  278. package/src/frameworks/langchain.ts +14 -0
  279. package/src/gateway/caller-auth-gateway.ts +320 -68
  280. package/src/gateway/http-server.ts +629 -220
  281. package/src/gateway/probe-auth.ts +191 -0
  282. package/src/gateway/signed-rate-bounds.ts +164 -0
  283. package/src/gateway/x402-opener-mode.ts +974 -0
  284. package/src/index.ts +82 -19
  285. package/src/mcp/server.ts +319 -42
  286. package/src/mcp/x402-tools.ts +621 -0
  287. package/src/network.ts +302 -0
  288. package/src/sdk/invoke.ts +6 -5
  289. package/src/wallet/autonomous-wallet-broker.ts +46 -20
  290. package/src/wallet/autonomous-wallet-protocol.ts +11 -2
  291. package/src/wallet/autonomous-wallet.ts +4 -2
  292. package/src/wallet/broker-escrows.ts +66 -0
  293. package/src/wallet/lifecycle.ts +53 -18
  294. package/src/wallet/privy-broker-server.ts +35 -25
  295. package/src/wallet/privy-session-broker.ts +58 -25
  296. package/src/wallet/privy-session-provider.ts +7 -3
  297. package/src/wallet/provider.ts +20 -15
  298. package/src/x402/facilitator.ts +3 -43
  299. package/src/x402-buyer/guarded-fetch.ts +213 -0
  300. package/src/x402-buyer/index.ts +9 -0
  301. package/src/x402-buyer/pay.ts +517 -0
  302. package/src/x402-opener/abi.ts +881 -0
  303. package/src/x402-opener/facilitator-entry.ts +45 -0
  304. package/src/x402-opener/facilitator-server.ts +1014 -0
  305. package/src/x402-opener/index.ts +13 -0
  306. package/src/x402-opener/listing-resolver.ts +202 -0
  307. package/src/x402-opener/refund-relay.ts +1743 -0
  308. package/src/x402-opener/relayer-queue.ts +18 -0
  309. package/src/x402-opener/scheme.ts +1133 -0
  310. package/src/x402-opener/terms.ts +300 -0
  311. package/dist/gateway/x402-mode.d.ts +0 -123
  312. package/dist/gateway/x402-mode.d.ts.map +0 -1
  313. package/dist/gateway/x402-mode.js +0 -212
  314. package/dist/gateway/x402-mode.js.map +0 -1
  315. package/dist/x402/delivery-oracle.d.ts +0 -108
  316. package/dist/x402/delivery-oracle.d.ts.map +0 -1
  317. package/dist/x402/delivery-oracle.js +0 -174
  318. package/dist/x402/delivery-oracle.js.map +0 -1
  319. package/dist/x402/facilitator-server-entry.d.ts +0 -3
  320. package/dist/x402/facilitator-server-entry.d.ts.map +0 -1
  321. package/dist/x402/facilitator-server-entry.js +0 -27
  322. package/dist/x402/facilitator-server-entry.js.map +0 -1
  323. package/dist/x402/facilitator-server.d.ts +0 -73
  324. package/dist/x402/facilitator-server.d.ts.map +0 -1
  325. package/dist/x402/facilitator-server.js +0 -305
  326. package/dist/x402/facilitator-server.js.map +0 -1
  327. package/dist/x402/payment-requirements.d.ts +0 -106
  328. package/dist/x402/payment-requirements.d.ts.map +0 -1
  329. package/dist/x402/payment-requirements.js +0 -138
  330. package/dist/x402/payment-requirements.js.map +0 -1
  331. package/dist/x402/relayer.d.ts +0 -41
  332. package/dist/x402/relayer.d.ts.map +0 -1
  333. package/dist/x402/relayer.js +0 -64
  334. package/dist/x402/relayer.js.map +0 -1
  335. package/dist/x402/resource-index.d.ts +0 -75
  336. package/dist/x402/resource-index.d.ts.map +0 -1
  337. package/dist/x402/resource-index.js +0 -126
  338. package/dist/x402/resource-index.js.map +0 -1
  339. package/dist/x402/verified-delivery-facilitator.d.ts +0 -285
  340. package/dist/x402/verified-delivery-facilitator.d.ts.map +0 -1
  341. package/dist/x402/verified-delivery-facilitator.js +0 -423
  342. package/dist/x402/verified-delivery-facilitator.js.map +0 -1
  343. package/src/gateway/x402-mode.ts +0 -350
  344. package/src/x402/delivery-oracle.ts +0 -285
  345. package/src/x402/facilitator-server-entry.ts +0 -35
  346. package/src/x402/facilitator-server.ts +0 -445
  347. package/src/x402/payment-requirements.ts +0 -231
  348. package/src/x402/relayer.ts +0 -122
  349. package/src/x402/resource-index.ts +0 -228
  350. package/src/x402/verified-delivery-facilitator.ts +0 -744
@@ -16,14 +16,27 @@ import {
16
16
  type CallerAuthDenialReason,
17
17
  } from "./caller-auth-gateway.js";
18
18
  import {
19
- createHttpFacilitatorClient,
20
- createListingPriceQuoter,
21
- encodeSettleResponseHeader,
22
- X402_PAYMENT_RESPONSE_HEADER,
23
- X402_SETTLEMENT_HEADROOM_SECONDS,
24
- type GatewayX402Mode,
25
- } from "./x402-mode.js";
26
- import { discoverServices } from "../discovery/registry.js";
19
+ DEFAULT_MAX_PROBES_PER_MINUTE,
20
+ DEFAULT_ORACLE_SIGNER_CACHE_SECONDS,
21
+ } from "./probe-auth.js";
22
+ import { PROBE_MARKER_HEADER_NAME } from "../capability/probe-capability.js";
23
+ import { networkForCaip2 } from "@absol-labs/sdk";
24
+ import {
25
+ chainIdFromNetwork,
26
+ assertSchemaDeclaration,
27
+ assertValidPrice,
28
+ assertValidTerms,
29
+ isHttpLink,
30
+ type OpenerTerms,
31
+ type X402SchemaDeclaration,
32
+ } from "../x402-opener/terms.js";
33
+ import type {
34
+ GatewayX402OpenerMode,
35
+ X402GatewayResponseReason,
36
+ X402UpstreamResult,
37
+ } from "./x402-opener-mode.js";
38
+ import { loadSignedRateBoundsFile } from "./signed-rate-bounds.js";
39
+ import { defaultNetwork, requireNetworkForChainId } from "../network.js";
27
40
 
28
41
  /**
29
42
  * Reference standalone reverse-proxy gateway server (metrik-agent#63).
@@ -60,11 +73,14 @@ export interface CallerAuthGatewayServerConfig {
60
73
  /** Extra request-timeout for the upstream fetch, in ms. Default 30000. */
61
74
  readonly upstreamTimeoutMs?: number;
62
75
  /**
63
- * The same {@link GatewayX402Mode} given to the gateway. Required for the
64
- * x402 path: the gateway VERIFIES a payment, this server SETTLES it once the
65
- * upstream has produced a response.
76
+ * Optional x402 v2 mode (metrik-agent#116): an uncapabilitied request gets a
77
+ * standard x402 `402` whose `payTo` is the listing's escrow opener, and a
78
+ * `PAYMENT-SIGNATURE` is verified, served, and settled into a
79
+ * `StreamEscrowV2` stream. OFF when unset — the server is then byte for byte
80
+ * the capability-only gateway (`test/gateway-http-baseline.test.ts`).
81
+ * Build it with `buildGatewayX402OpenerMode`.
66
82
  */
67
- readonly x402?: GatewayX402Mode;
83
+ readonly x402Opener?: GatewayX402OpenerMode;
68
84
  }
69
85
 
70
86
  export interface CallerAuthGatewayServer {
@@ -86,7 +102,7 @@ export function createCallerAuthGatewayServer(
86
102
  config.gateway,
87
103
  upstreamBase,
88
104
  upstreamTimeoutMs,
89
- config.x402,
105
+ config.x402Opener,
90
106
  ).catch((error) => {
91
107
  logError("unhandled request error", error);
92
108
  if (!res.headersSent) {
@@ -122,12 +138,37 @@ async function handleRequest(
122
138
  gateway: CallerAuthGateway,
123
139
  upstreamBase: URL,
124
140
  upstreamTimeoutMs: number,
125
- x402: GatewayX402Mode | undefined,
141
+ x402Opener: GatewayX402OpenerMode | undefined,
126
142
  ): Promise<void> {
127
143
  const requestUrl = new URL(req.url ?? "/", "http://localhost");
128
144
  const method = req.method ?? "GET";
129
145
  const headers = normalizeIncomingHeaders(req.headers);
130
146
 
147
+ if (x402Opener !== undefined) {
148
+ const route = routeX402(headers, gateway);
149
+ if (route === "ambiguous-probe-mode") {
150
+ writeJsonError(res, 400, "ambiguous-probe-mode");
151
+ return;
152
+ }
153
+ if (route === "ambiguous-capability-and-payment") {
154
+ writeJsonError(res, 400, "ambiguous-capability-and-payment");
155
+ return;
156
+ }
157
+ if (route === "x402") {
158
+ await handleX402Request(
159
+ req,
160
+ res,
161
+ x402Opener,
162
+ requestUrl,
163
+ method,
164
+ headers,
165
+ upstreamBase,
166
+ upstreamTimeoutMs,
167
+ );
168
+ return;
169
+ }
170
+ }
171
+
131
172
  const decision = await gateway.authorize({
132
173
  headers,
133
174
  method,
@@ -135,14 +176,6 @@ async function handleRequest(
135
176
  });
136
177
 
137
178
  if (!decision.authorized) {
138
- // The x402 challenge is a PROTOCOL body, not Metrik's `{authorized,reason}`
139
- // shape: `x402-fetch` parses `{x402Version, accepts}` and nothing else.
140
- if (decision.x402PaymentRequired !== undefined) {
141
- res
142
- .writeHead(402, { "Content-Type": "application/json" })
143
- .end(JSON.stringify(decision.x402PaymentRequired));
144
- return;
145
- }
146
179
  writeJsonError(
147
180
  res,
148
181
  decision.httpStatus ?? 403,
@@ -164,28 +197,23 @@ async function handleRequest(
164
197
  upstreamHeaders.set(key, value);
165
198
  }
166
199
 
200
+ // The probe marker is gateway-asserted, never client-asserted: strip any
201
+ // inbound copy first, so a paying caller cannot mark its own billable request
202
+ // as verification traffic and slip past the seller's metering.
203
+ upstreamHeaders.delete(PROBE_MARKER_HEADER_NAME);
204
+ if (decision.probe !== undefined) {
205
+ // Advisory marker so the seller's OWN metering can exclude verification
206
+ // traffic from billable usage. The gateway itself charges nothing for it.
207
+ upstreamHeaders.set(PROBE_MARKER_HEADER_NAME, "1");
208
+ }
209
+
167
210
  const upstreamUrl = new URL(
168
211
  requestUrl.pathname + requestUrl.search,
169
212
  upstreamBase,
170
213
  );
171
214
 
172
- // Bound the upstream by the payment's OWN deadline, not just by the server's
173
- // timeout. Settlement happens after the upstream returns, so an upstream that
174
- // outlives the signed authorization would produce its side effects and then
175
- // be unsettleable — the caller would get the work for free (never the response
176
- // body, which is only flushed after settlement, but the side effects are
177
- // real). Aborting early turns that into an ordinary 502.
178
- const effectiveTimeoutMs = boundedUpstreamTimeoutMs(
179
- upstreamTimeoutMs,
180
- decision.x402Payment?.validBefore,
181
- );
182
- if (effectiveTimeoutMs <= 0) {
183
- writeJsonError(res, 402, "x402-authorization-too-short");
184
- return;
185
- }
186
-
187
215
  const controller = new AbortController();
188
- const timeout = setTimeout(() => controller.abort(), effectiveTimeoutMs);
216
+ const timeout = setTimeout(() => controller.abort(), upstreamTimeoutMs);
189
217
  try {
190
218
  const upstreamResponse = await fetch(upstreamUrl, {
191
219
  method,
@@ -197,22 +225,6 @@ async function handleRequest(
197
225
  const buffer = Buffer.from(await upstreamResponse.arrayBuffer());
198
226
  const responseHeaders = headersToObject(upstreamResponse.headers);
199
227
 
200
- // Settle AFTER the upstream produced a response and BEFORE that response is
201
- // flushed. Buyer-favouring on both edges: a call that never produced a
202
- // response is never charged for, and a payment that cannot be settled
203
- // returns `402` instead of handing over the goods for free.
204
- if (decision.x402Payment !== undefined) {
205
- const settled = await settleX402(decision, x402);
206
- if (settled === undefined) {
207
- writeJsonError(res, 402, "x402-settlement-failed");
208
- return;
209
- }
210
- responseHeaders[X402_PAYMENT_RESPONSE_HEADER] =
211
- encodeSettleResponseHeader(settled);
212
- responseHeaders["access-control-expose-headers"] =
213
- X402_PAYMENT_RESPONSE_HEADER;
214
- }
215
-
216
228
  res.writeHead(upstreamResponse.status, responseHeaders);
217
229
  res.end(buffer);
218
230
  } catch (error) {
@@ -223,64 +235,127 @@ async function handleRequest(
223
235
  }
224
236
  }
225
237
 
238
+ /** x402 v2 request header (base64 `PaymentPayload`). */
239
+ const PAYMENT_SIGNATURE_HEADER = "payment-signature";
240
+ /** x402 v1 request header. Never forwarded upstream in x402 mode either. */
241
+ const LEGACY_PAYMENT_HEADER = "x-payment";
242
+
243
+ type X402Route =
244
+ | "x402"
245
+ | "capability-or-probe"
246
+ | "ambiguous-probe-mode"
247
+ | "ambiguous-capability-and-payment";
248
+
226
249
  /**
227
- * The upstream budget, capped so the signed authorization is still settleable
228
- * when the call returns. Returns <= 0 when there is no usable window at all.
250
+ * Decides which path an x402-mode request takes. A payment is never mixed with
251
+ * a capability or a probe: both-present is a `400`, not a guess.
229
252
  */
230
- export function boundedUpstreamTimeoutMs(
253
+ function routeX402(
254
+ headers: Record<string, string | undefined>,
255
+ gateway: CallerAuthGateway,
256
+ ): X402Route {
257
+ const present = (name: string) => {
258
+ const value = headers[name];
259
+ return value !== undefined && value.trim().length > 0;
260
+ };
261
+ const hasPayment = present(PAYMENT_SIGNATURE_HEADER);
262
+ const hasCapability = present(gateway.capabilityHeaderName);
263
+ const hasProbe = present(gateway.probeCapabilityHeaderName);
264
+ if (hasProbe && hasPayment) return "ambiguous-probe-mode";
265
+ if (hasCapability && hasPayment) return "ambiguous-capability-and-payment";
266
+ if (hasPayment) return "x402";
267
+ if (!hasCapability && !hasProbe) return "x402";
268
+ return "capability-or-probe";
269
+ }
270
+
271
+ /**
272
+ * The x402 v2 path. The protocol logic (verify → upstream → settle-before-body)
273
+ * lives with the mode in `./x402-opener-mode.ts`, so this module — and the
274
+ * package's root barrel — never loads `@x402/*` for a gateway that does not
275
+ * enable it. This function only supplies the transport.
276
+ */
277
+ async function handleX402Request(
278
+ req: IncomingMessage,
279
+ res: ServerResponse,
280
+ mode: GatewayX402OpenerMode,
281
+ requestUrl: URL,
282
+ method: string,
283
+ headers: Record<string, string | undefined>,
284
+ upstreamBase: URL,
231
285
  upstreamTimeoutMs: number,
232
- validBeforeSeconds: number | undefined,
233
- nowSeconds: number = Math.floor(Date.now() / 1000),
234
- ): number {
235
- if (validBeforeSeconds === undefined) {
236
- return upstreamTimeoutMs;
237
- }
238
- const remainingSeconds =
239
- validBeforeSeconds - nowSeconds - X402_SETTLEMENT_HEADROOM_SECONDS;
240
- if (remainingSeconds <= 0) {
241
- return 0;
242
- }
243
- return Math.min(upstreamTimeoutMs, remainingSeconds * 1000);
286
+ ): Promise<void> {
287
+ await mode.handle({
288
+ requestUrl,
289
+ method,
290
+ headers,
291
+ callUpstream: () =>
292
+ callUpstream(
293
+ req,
294
+ method,
295
+ headers,
296
+ requestUrl,
297
+ upstreamBase,
298
+ upstreamTimeoutMs,
299
+ ),
300
+ writeJson: (status, reason) => writeJsonError(res, status, reason),
301
+ write: (status, responseHeaders, body) => {
302
+ if (res.headersSent) {
303
+ res.end();
304
+ return;
305
+ }
306
+ res.writeHead(status, responseHeaders);
307
+ res.end(body);
308
+ },
309
+ logError,
310
+ });
244
311
  }
245
312
 
246
- /** Returns the settlement result, or `undefined` if nothing was settled. */
247
- async function settleX402(
248
- decision: CallerAuthDecision,
249
- x402: GatewayX402Mode | undefined,
250
- ): Promise<
251
- Awaited<ReturnType<GatewayX402Mode["facilitator"]["settle"]>> | undefined
252
- > {
253
- const payment = decision.x402Payment;
254
- if (payment === undefined) {
255
- return undefined;
313
+ /** Buffers one upstream call. Payment headers are never forwarded. */
314
+ async function callUpstream(
315
+ req: IncomingMessage,
316
+ method: string,
317
+ headers: Record<string, string | undefined>,
318
+ requestUrl: URL,
319
+ upstreamBase: URL,
320
+ upstreamTimeoutMs: number,
321
+ ): Promise<X402UpstreamResult> {
322
+ let body: Buffer | undefined;
323
+ if (method !== "GET" && method !== "HEAD") {
324
+ body = await readBody(req);
256
325
  }
257
- if (x402 === undefined) {
258
- // The gateway accepted an x402 payment but this server was given no
259
- // facilitator to settle it with. Refuse: serving here would be free service.
260
- logError(
261
- "x402 settlement",
262
- new Error(
263
- "gateway accepted an x402 payment but the server has no x402 facilitator configured",
264
- ),
265
- );
266
- return undefined;
326
+ const upstreamHeaders = new Headers();
327
+ for (const [key, value] of Object.entries(headers)) {
328
+ if (value === undefined || HOP_BY_HOP_HEADERS.has(key)) continue;
329
+ upstreamHeaders.set(key, value);
267
330
  }
331
+ // A signed payment authorization must never reach the upstream: anyone who
332
+ // holds it can submit it to USDC directly, which strands the payer's funds
333
+ // in the opener. The probe marker is gateway-asserted only.
334
+ upstreamHeaders.delete(PAYMENT_SIGNATURE_HEADER);
335
+ upstreamHeaders.delete(LEGACY_PAYMENT_HEADER);
336
+ upstreamHeaders.delete(PROBE_MARKER_HEADER_NAME);
337
+
338
+ const upstreamUrl = new URL(
339
+ requestUrl.pathname + requestUrl.search,
340
+ upstreamBase,
341
+ );
342
+ const controller = new AbortController();
343
+ const timeout = setTimeout(() => controller.abort(), upstreamTimeoutMs);
268
344
  try {
269
- const settled = await x402.facilitator.settle(
270
- payment.payload,
271
- payment.requirements,
272
- );
273
- if (settled.success !== true) {
274
- logError(
275
- "x402 settlement",
276
- new Error(settled.errorReason ?? "facilitator reported failure"),
277
- );
278
- return undefined;
279
- }
280
- return settled;
281
- } catch (error) {
282
- logError("x402 settlement", error);
283
- return undefined;
345
+ const response = await fetch(upstreamUrl, {
346
+ method,
347
+ headers: upstreamHeaders,
348
+ ...(body === undefined ? {} : { body }),
349
+ signal: controller.signal,
350
+ });
351
+ const buffer = Buffer.from(await response.arrayBuffer());
352
+ return {
353
+ status: response.status,
354
+ headers: headersToObject(response.headers),
355
+ body: buffer,
356
+ };
357
+ } finally {
358
+ clearTimeout(timeout);
284
359
  }
285
360
  }
286
361
 
@@ -328,8 +403,8 @@ function writeJsonError(
328
403
  | "unauthorized"
329
404
  | "internal-error"
330
405
  | "upstream-unavailable"
331
- | "x402-settlement-failed"
332
- | "x402-authorization-too-short",
406
+ | "ambiguous-capability-and-payment"
407
+ | X402GatewayResponseReason,
333
408
  ): void {
334
409
  if (res.headersSent) {
335
410
  res.end();
@@ -361,22 +436,50 @@ export interface CallerAuthGatewayEnvConfig {
361
436
  readonly corroboratingRpcUrls: readonly string[];
362
437
  /** Freshness bound for on-chain stream state, in seconds. */
363
438
  readonly maxStateStalenessSeconds: number;
364
- /** Set only when standard-x402 mode is enabled. */
365
- readonly x402?: CallerAuthGatewayX402EnvConfig;
439
+ /** Set only when oracle probe verification is enabled. */
440
+ readonly probe?: CallerAuthGatewayProbeEnvConfig;
441
+ /** Set only when the x402 v2 opener mode is enabled. */
442
+ readonly x402Opener?: CallerAuthGatewayX402OpenerEnvConfig;
443
+ /**
444
+ * Path of the operator-signed descriptor(s) whose rate band the capability
445
+ * path enforces (`METRIK_GATEWAY_SIGNED_DESCRIPTOR_FILE`). Loaded and
446
+ * verified at startup by {@link startCallerAuthGatewayServerFromEnv}.
447
+ */
448
+ readonly signedDescriptorFile?: string;
366
449
  }
367
450
 
368
- export interface CallerAuthGatewayX402EnvConfig {
369
- /** Per-call price in the asset's base units (micro-USDC). Seller-set, unsigned. */
370
- readonly pricePerCallBaseUnits: bigint;
371
- /** A facilitator exposing `/verify` and `/settle` — e.g. Metrik's own. */
451
+ /** Env view of the gateway's x402 v2 opener mode (see {@link parseGatewayX402OpenerEnvConfig}). */
452
+ export interface CallerAuthGatewayX402OpenerEnvConfig {
372
453
  readonly facilitatorUrl: string;
373
- /** The public origin buyers reach this gateway on. Becomes `resource`. */
374
- readonly resourceBaseUrl: string;
375
- /** Listing source used to derive `payTo` from the operator-signed descriptor. */
454
+ readonly facilitatorToken: string;
455
+ readonly network: `${string}:${string}`;
456
+ readonly factoryAddress: Address;
457
+ readonly asset: Address;
458
+ readonly assetName: string;
459
+ readonly assetVersion: string;
460
+ readonly terms: OpenerTerms;
461
+ readonly price: bigint;
462
+ readonly maxTimeoutSeconds: number;
463
+ /** Per-request facilitator HTTP timeout, ms. */
464
+ readonly facilitatorTimeoutMs: number;
465
+ readonly resourceBaseUrl?: string;
376
466
  readonly registryUrl?: string;
377
- readonly maxTimeoutSeconds?: number;
378
- /** Bearer token for the facilitator's `/settle`. Required by Metrik's own. */
379
- readonly facilitatorToken?: string;
467
+ /** Public base URL of the facilitator's refund relay (default: facilitatorUrl). */
468
+ readonly refundBaseUrl?: string;
469
+ readonly docsUrl?: string;
470
+ /** Token decimals for the 402 description (default 6). */
471
+ readonly assetDecimals?: number;
472
+ /** One-sentence service description, prefixed to the fixed disclosure. */
473
+ readonly description?: string;
474
+ /** Optional input/output schema, declared as `extensions.bazaar`. */
475
+ readonly schemaDeclaration?: X402SchemaDeclaration;
476
+ }
477
+
478
+ export interface CallerAuthGatewayProbeEnvConfig {
479
+ /** Free-probe budget per minute. */
480
+ readonly maxProbesPerMinute: number;
481
+ /** Freshness bound for the cached on-chain oracle signer set, in seconds. */
482
+ readonly signerCacheSeconds: number;
380
483
  }
381
484
 
382
485
  /**
@@ -395,8 +498,14 @@ export interface CallerAuthGatewayX402EnvConfig {
395
498
  * - `METRIK_GATEWAY_MAX_STATE_STALENESS_SECONDS` (optional) - reject stream
396
499
  * state observed more than N seconds behind the wall clock. Default
397
500
  * {@link DEFAULT_MAX_STATE_STALENESS_SECONDS}.
398
- * - `METRIK_GATEWAY_CHAIN_ID` (optional) - default `84532` (Base Sepolia).
501
+ * - `METRIK_GATEWAY_CHAIN_ID` (optional) - default the registry's default
502
+ * network. Must be a network the SDK registry knows.
399
503
  * - `METRIK_GATEWAY_HEADER_NAME` (optional) - default `x-metrik-capability`.
504
+ * - `METRIK_GATEWAY_SIGNED_DESCRIPTOR_FILE` (optional, recommended) - JSON file
505
+ * holding this service's operator-signed descriptor (or an array, one per
506
+ * served serviceRef). Verified at startup; the capability path then refuses
507
+ * any stream whose on-chain `ratePerSecond` is outside the signed
508
+ * `minRatePerSecond`/`maxRatePerSecond` (`stream-rate-out-of-bounds`).
400
509
  * - `PORT` / `METRIK_GATEWAY_PORT` (optional) - default `8787`.
401
510
  * - `METRIK_GATEWAY_HOST` (optional) - default `0.0.0.0`.
402
511
  *
@@ -429,11 +538,15 @@ export function parseCallerAuthGatewayEnvConfig(
429
538
  // eslint-disable-next-line no-new -- validates the URL is well-formed.
430
539
  new URL(upstreamUrl);
431
540
 
432
- const chainIdRaw = env.METRIK_GATEWAY_CHAIN_ID ?? "84532";
541
+ const chainIdRaw =
542
+ env.METRIK_GATEWAY_CHAIN_ID ?? String(defaultNetwork().chain.id);
433
543
  const chainId = Number(chainIdRaw);
434
544
  if (!Number.isInteger(chainId) || chainId <= 0) {
435
545
  throw new Error(`invalid METRIK_GATEWAY_CHAIN_ID: ${chainIdRaw}`);
436
546
  }
547
+ // The stream reader is built from the registry entry for this chain, so an
548
+ // unknown chain is refused at startup rather than at the first request.
549
+ requireNetworkForChainId(chainId, {}, "METRIK_GATEWAY_CHAIN_ID");
437
550
 
438
551
  const portRaw = env.METRIK_GATEWAY_PORT ?? env.PORT ?? "8787";
439
552
  const port = Number(portRaw);
@@ -481,7 +594,14 @@ export function parseCallerAuthGatewayEnvConfig(
481
594
  );
482
595
  }
483
596
 
484
- const x402 = parseGatewayX402EnvConfig(env);
597
+ const signedDescriptorFile =
598
+ env.METRIK_GATEWAY_SIGNED_DESCRIPTOR_FILE?.trim() || undefined;
599
+
600
+ const probe = parseGatewayProbeEnvConfig(env);
601
+ const x402Opener = parseGatewayX402OpenerEnvConfig(env, {
602
+ chainId,
603
+ serviceRef: serviceRef as Hex,
604
+ });
485
605
 
486
606
  return {
487
607
  host,
@@ -497,133 +617,319 @@ export function parseCallerAuthGatewayEnvConfig(
497
617
  corroboratingRpcUrls,
498
618
  maxStateStalenessSeconds,
499
619
  ...(headerName === undefined ? {} : { headerName }),
500
- ...(x402 === undefined ? {} : { x402 }),
620
+ ...(probe === undefined ? {} : { probe }),
621
+ ...(x402Opener === undefined ? {} : { x402Opener }),
622
+ ...(signedDescriptorFile === undefined ? {} : { signedDescriptorFile }),
501
623
  };
502
624
  }
503
625
 
504
626
  /**
505
- * x402 mode is OFF unless `METRIK_GATEWAY_X402_PRICE_BASE_UNITS` is set. Once
506
- * on, every other x402 var is required: a half-configured paywall would answer
507
- * `402` with a quote it cannot settle.
627
+ * The x402 v2 opener mode is OFF unless `METRIK_GATEWAY_X402V2_OPENER` is
628
+ * truthy. When on, an uncapabilitied request is answered with a standard x402
629
+ * v2 `402` whose `payTo` is the opener for this listing's terms, and payments
630
+ * settle into a `StreamEscrowV2` stream through the Metrik opener facilitator.
631
+ * The listing is the gateway's primary `METRIK_GATEWAY_SERVICE_REF`.
508
632
  *
509
- * Note what is NOT here: `payTo`. It is never configurable — it is resolved at
510
- * startup from the operator-signed descriptor for this gateway's `serviceRef`
511
- * (see {@link resolveSignedListingPayee}), and the gateway refuses to start if
512
- * that lookup fails.
633
+ * These names deliberately differ from the removed v1 mode's variables, so a
634
+ * leftover v1 environment can never switch a payment mode on by accident.
635
+ *
636
+ * - `METRIK_GATEWAY_X402V2_OPENER` — `1`/`true`/`yes`/`on` to enable.
637
+ * - `METRIK_GATEWAY_X402V2_FACILITATOR_URL` (required) — the Metrik opener facilitator.
638
+ * - `METRIK_GATEWAY_X402V2_FACILITATOR_TOKEN` (required) — its `/settle` bearer token.
639
+ * - `METRIK_GATEWAY_X402V2_FACTORY_ADDRESS` — the `X402StreamOpenerFactory`; default the
640
+ * network's registered factory (required where the registry has none).
641
+ * - `METRIK_GATEWAY_X402V2_OPERATOR` (required) — must be the signed listing's operator.
642
+ * - `METRIK_GATEWAY_X402V2_RATE_PER_SECOND` (required) — USDC base units per second.
643
+ * - `METRIK_GATEWAY_X402V2_MAX_DURATION_SECONDS` (required).
644
+ * - `METRIK_GATEWAY_X402V2_PRICE` (required) — base units per paid request (= deposit),
645
+ * `0 < price <= rate * maxDuration`.
646
+ * - `METRIK_GATEWAY_X402V2_NETWORK` — default `eip155:<METRIK_GATEWAY_CHAIN_ID>`.
647
+ * - `METRIK_GATEWAY_X402V2_ASSET` — default the network's registered USDC.
648
+ * - `METRIK_GATEWAY_X402V2_ASSET_NAME` / `_ASSET_VERSION` — EIP-712 domain, default the
649
+ * registered USDC's own EIP-712 name/version.
650
+ * - `METRIK_GATEWAY_X402V2_MAX_TIMEOUT_SECONDS` — authorization validity, default 300.
651
+ * - `METRIK_GATEWAY_X402V2_FACILITATOR_TIMEOUT_SECONDS` — per-request facilitator
652
+ * timeout, default 120; must exceed the facilitator's receipt wait by 30 s.
653
+ * - `METRIK_GATEWAY_X402V2_RESOURCE_BASE_URL` — public origin for the 402 `resource.url`.
654
+ * - `METRIK_GATEWAY_X402V2_REGISTRY_URL` — registry used to prove the listing.
655
+ * - `METRIK_GATEWAY_X402V2_REFUND_BASE_URL` — public base URL of the facilitator's
656
+ * gasless refund relay, advertised in the 402; default the facilitator URL. Its
657
+ * `/supported` must show the opener marker with `refundRelay: true`.
658
+ * - `METRIK_GATEWAY_X402V2_DOCS_URL` — docs link in the 402; default docs/x402.md on GitHub.
659
+ * - `METRIK_GATEWAY_X402V2_ASSET_DECIMALS` — decimals for the 402 description; default 6.
660
+ * - `METRIK_GATEWAY_X402V2_DESCRIPTION` — one sentence on what the service does,
661
+ * prefixed to the fixed disclosure of what the payment buys (at most 300 chars).
662
+ * - `METRIK_GATEWAY_X402V2_SCHEMA` — optional JSON `{info: {input, output}, schema}`
663
+ * declared in the 402 as `extensions.bazaar` (declared only, never registered).
513
664
  */
514
- export function parseGatewayX402EnvConfig(
515
- env: NodeJS.ProcessEnv = process.env,
516
- ): CallerAuthGatewayX402EnvConfig | undefined {
517
- const rawPrice = env.METRIK_GATEWAY_X402_PRICE_BASE_UNITS?.trim();
518
- if (rawPrice === undefined || rawPrice.length === 0) {
665
+ export function parseGatewayX402OpenerEnvConfig(
666
+ env: NodeJS.ProcessEnv,
667
+ context: { readonly chainId: number; readonly serviceRef: Hex },
668
+ ): CallerAuthGatewayX402OpenerEnvConfig | undefined {
669
+ const raw = env.METRIK_GATEWAY_X402V2_OPENER?.trim().toLowerCase();
670
+ if (
671
+ raw === undefined ||
672
+ raw.length === 0 ||
673
+ ["0", "false", "no", "off"].includes(raw)
674
+ ) {
519
675
  return undefined;
520
676
  }
521
- let pricePerCallBaseUnits: bigint;
522
- try {
523
- pricePerCallBaseUnits = BigInt(rawPrice);
524
- } catch {
677
+ if (!["1", "true", "yes", "on"].includes(raw)) {
678
+ throw new Error(
679
+ `invalid METRIK_GATEWAY_X402V2_OPENER: ${raw} (expected a boolean)`,
680
+ );
681
+ }
682
+ const facilitatorUrl = requireEnv(
683
+ env,
684
+ "METRIK_GATEWAY_X402V2_FACILITATOR_URL",
685
+ ).trim();
686
+ // eslint-disable-next-line no-new -- validates the URL is well-formed.
687
+ new URL(facilitatorUrl);
688
+ const facilitatorToken = requireEnv(
689
+ env,
690
+ "METRIK_GATEWAY_X402V2_FACILITATOR_TOKEN",
691
+ ).trim();
692
+ const network = (env.METRIK_GATEWAY_X402V2_NETWORK?.trim() ||
693
+ `eip155:${String(context.chainId)}`) as `${string}:${string}`;
694
+ if (chainIdFromNetwork(network) !== context.chainId) {
525
695
  throw new Error(
526
- `invalid METRIK_GATEWAY_X402_PRICE_BASE_UNITS: ${rawPrice} (integer base units, e.g. 1000 = 0.001 USDC)`,
696
+ `METRIK_GATEWAY_X402V2_NETWORK ${network} does not match METRIK_GATEWAY_CHAIN_ID ${context.chainId}`,
527
697
  );
528
698
  }
529
- if (pricePerCallBaseUnits <= 0n) {
530
- throw new Error("METRIK_GATEWAY_X402_PRICE_BASE_UNITS must be positive");
699
+ // Defaults come from the registry entry for THIS network only.
700
+ const registered = networkForCaip2(network);
701
+ const factoryRaw = env.METRIK_GATEWAY_X402V2_FACTORY_ADDRESS?.trim();
702
+ let factoryAddress: Address;
703
+ if (factoryRaw === undefined || factoryRaw.length === 0) {
704
+ if (registered?.openerFactory == null) {
705
+ throw new Error(
706
+ `METRIK_GATEWAY_X402V2_FACTORY_ADDRESS is required on ${network}: the network registry has no opener factory for it`,
707
+ );
708
+ }
709
+ factoryAddress = registered.openerFactory.address;
710
+ } else if (isAddress(factoryRaw)) {
711
+ factoryAddress = factoryRaw;
712
+ } else {
713
+ throw new Error(
714
+ "METRIK_GATEWAY_X402V2_FACTORY_ADDRESS must be an EVM address",
715
+ );
716
+ }
717
+ const operator = requireEnv(env, "METRIK_GATEWAY_X402V2_OPERATOR").trim();
718
+ if (!isAddress(operator)) {
719
+ throw new Error("METRIK_GATEWAY_X402V2_OPERATOR must be an EVM address");
720
+ }
721
+ const assetRaw = env.METRIK_GATEWAY_X402V2_ASSET?.trim();
722
+ let asset: Address;
723
+ if (assetRaw === undefined || assetRaw.length === 0) {
724
+ if (registered === undefined) {
725
+ throw new Error(
726
+ `METRIK_GATEWAY_X402V2_ASSET is required on ${network}: the network registry does not know it`,
727
+ );
728
+ }
729
+ asset = registered.usdc.address;
730
+ } else if (isAddress(assetRaw)) {
731
+ asset = assetRaw;
732
+ } else {
733
+ throw new Error("METRIK_GATEWAY_X402V2_ASSET must be an EVM address");
531
734
  }
532
- const facilitatorUrl = requireEnv(env, "METRIK_GATEWAY_X402_FACILITATOR_URL");
533
- const resourceBaseUrl = requireEnv(
735
+ const terms: OpenerTerms = {
736
+ operator,
737
+ serviceRef: context.serviceRef,
738
+ ratePerSecond: requireUintEnv(env, "METRIK_GATEWAY_X402V2_RATE_PER_SECOND"),
739
+ maxDuration: requireUintEnv(
740
+ env,
741
+ "METRIK_GATEWAY_X402V2_MAX_DURATION_SECONDS",
742
+ ),
743
+ };
744
+ const price = requireUintEnv(env, "METRIK_GATEWAY_X402V2_PRICE");
745
+ // Startup validation: rate/duration > 0 and 0 < price <= rate * maxDuration.
746
+ assertValidTerms(terms);
747
+ assertValidPrice(price, terms);
748
+ const maxTimeoutSeconds = requirePositiveIntEnv(
534
749
  env,
535
- "METRIK_GATEWAY_X402_RESOURCE_BASE_URL",
750
+ "METRIK_GATEWAY_X402V2_MAX_TIMEOUT_SECONDS",
751
+ 300,
536
752
  );
537
- for (const candidate of [facilitatorUrl, resourceBaseUrl]) {
753
+ const facilitatorTimeoutSeconds = requirePositiveIntEnv(
754
+ env,
755
+ "METRIK_GATEWAY_X402V2_FACILITATOR_TIMEOUT_SECONDS",
756
+ 120,
757
+ );
758
+ const resourceBaseUrl = env.METRIK_GATEWAY_X402V2_RESOURCE_BASE_URL?.trim();
759
+ if (resourceBaseUrl !== undefined && resourceBaseUrl.length > 0) {
760
+ // eslint-disable-next-line no-new -- validates the URL is well-formed.
761
+ new URL(resourceBaseUrl);
762
+ }
763
+ const registryUrl = env.METRIK_GATEWAY_X402V2_REGISTRY_URL?.trim();
764
+ if (registryUrl !== undefined && registryUrl.length > 0) {
538
765
  // eslint-disable-next-line no-new -- validates the URL is well-formed.
539
- new URL(candidate);
540
- }
541
- const registryUrl = env.METRIK_GATEWAY_X402_REGISTRY_URL;
542
- const facilitatorToken = env.METRIK_GATEWAY_X402_FACILITATOR_TOKEN?.trim();
543
- const rawTimeout = env.METRIK_GATEWAY_X402_MAX_TIMEOUT_SECONDS;
544
- let maxTimeoutSeconds: number | undefined;
545
- if (rawTimeout !== undefined && rawTimeout.trim().length > 0) {
546
- maxTimeoutSeconds = Number(rawTimeout);
547
- if (!Number.isInteger(maxTimeoutSeconds) || maxTimeoutSeconds <= 0) {
766
+ new URL(registryUrl);
767
+ }
768
+ const optionalLink = (name: string): string | undefined => {
769
+ const value = env[name]?.trim();
770
+ if (value === undefined || value.length === 0) return undefined;
771
+ if (!isHttpLink(value)) {
772
+ throw new Error(`${name} must be an absolute http(s) URL`);
773
+ }
774
+ return value.replace(/\/+$/, "");
775
+ };
776
+ const refundBaseUrl = optionalLink("METRIK_GATEWAY_X402V2_REFUND_BASE_URL");
777
+ const docsUrl = optionalLink("METRIK_GATEWAY_X402V2_DOCS_URL");
778
+ const decimalsRaw = env.METRIK_GATEWAY_X402V2_ASSET_DECIMALS?.trim();
779
+ let assetDecimals: number | undefined;
780
+ if (decimalsRaw !== undefined && decimalsRaw.length > 0) {
781
+ assetDecimals = Number(decimalsRaw);
782
+ if (
783
+ !/^\d+$/.test(decimalsRaw) ||
784
+ !Number.isInteger(assetDecimals) ||
785
+ assetDecimals > 36
786
+ ) {
548
787
  throw new Error(
549
- `invalid METRIK_GATEWAY_X402_MAX_TIMEOUT_SECONDS: ${rawTimeout}`,
788
+ `invalid METRIK_GATEWAY_X402V2_ASSET_DECIMALS: ${decimalsRaw} (expected an integer 0-36)`,
789
+ );
790
+ }
791
+ }
792
+ const description = env.METRIK_GATEWAY_X402V2_DESCRIPTION?.trim();
793
+ if (description !== undefined && description.length > 300) {
794
+ throw new Error(
795
+ "METRIK_GATEWAY_X402V2_DESCRIPTION must be at most 300 characters",
796
+ );
797
+ }
798
+ const schemaRaw = env.METRIK_GATEWAY_X402V2_SCHEMA?.trim();
799
+ let schemaDeclaration: X402SchemaDeclaration | undefined;
800
+ if (schemaRaw !== undefined && schemaRaw.length > 0) {
801
+ try {
802
+ const parsed: unknown = JSON.parse(schemaRaw);
803
+ assertSchemaDeclaration(parsed);
804
+ schemaDeclaration = parsed;
805
+ } catch (error) {
806
+ throw new Error(
807
+ `invalid METRIK_GATEWAY_X402V2_SCHEMA: ${error instanceof Error ? error.message : String(error)}`,
550
808
  );
551
809
  }
552
810
  }
553
-
554
811
  return {
555
- pricePerCallBaseUnits,
556
812
  facilitatorUrl,
557
- resourceBaseUrl,
558
- ...(registryUrl === undefined ? {} : { registryUrl }),
559
- ...(maxTimeoutSeconds === undefined ? {} : { maxTimeoutSeconds }),
560
- ...(facilitatorToken === undefined || facilitatorToken.length === 0
813
+ facilitatorToken,
814
+ network,
815
+ factoryAddress,
816
+ asset,
817
+ assetName: requireAssetDomainField(
818
+ env.METRIK_GATEWAY_X402V2_ASSET_NAME,
819
+ registered?.usdc.eip712.name,
820
+ "METRIK_GATEWAY_X402V2_ASSET_NAME",
821
+ network,
822
+ ),
823
+ assetVersion: requireAssetDomainField(
824
+ env.METRIK_GATEWAY_X402V2_ASSET_VERSION,
825
+ registered?.usdc.eip712.version,
826
+ "METRIK_GATEWAY_X402V2_ASSET_VERSION",
827
+ network,
828
+ ),
829
+ terms,
830
+ price,
831
+ maxTimeoutSeconds,
832
+ facilitatorTimeoutMs: facilitatorTimeoutSeconds * 1000,
833
+ ...(resourceBaseUrl === undefined || resourceBaseUrl.length === 0
561
834
  ? {}
562
- : { facilitatorToken }),
835
+ : { resourceBaseUrl }),
836
+ ...(registryUrl === undefined || registryUrl.length === 0
837
+ ? {}
838
+ : { registryUrl }),
839
+ ...(refundBaseUrl === undefined ? {} : { refundBaseUrl }),
840
+ ...(docsUrl === undefined ? {} : { docsUrl }),
841
+ ...(assetDecimals === undefined ? {} : { assetDecimals }),
842
+ ...(description === undefined || description.length === 0
843
+ ? {}
844
+ : { description }),
845
+ ...(schemaDeclaration === undefined ? {} : { schemaDeclaration }),
563
846
  };
564
847
  }
565
848
 
566
- export class UnresolvedListingPayeeError extends Error {
567
- constructor(serviceRef: string) {
568
- super(
569
- `no operator-signed listing found for serviceRef ${serviceRef}. ` +
570
- "x402 mode refuses to start: payTo is derived from the signed descriptor and " +
571
- "is never taken from configuration, so an unresolved listing has no payee.",
849
+ function requireAssetDomainField(
850
+ raw: string | undefined,
851
+ registered: string | undefined,
852
+ name: string,
853
+ network: string,
854
+ ): string {
855
+ const value = raw?.trim();
856
+ if (value !== undefined && value.length > 0) return value;
857
+ if (registered === undefined) {
858
+ throw new Error(
859
+ `${name} is required on ${network}: the network registry does not know the asset's EIP-712 domain`,
572
860
  );
573
- this.name = "UnresolvedListingPayeeError";
574
861
  }
862
+ return registered;
863
+ }
864
+
865
+ function requireUintEnv(env: NodeJS.ProcessEnv, name: string): bigint {
866
+ const raw = requireEnv(env, name).trim();
867
+ if (!/^(0|[1-9]\d*)$/.test(raw)) {
868
+ throw new Error(`invalid ${name}: ${raw} (expected a base-10 integer)`);
869
+ }
870
+ return BigInt(raw);
575
871
  }
576
872
 
577
873
  /**
578
- * Resolves `{serviceRef, operator}` from the registry. `discoverServices`
579
- * re-derives `serviceRef` from the signed content and recovers the operator's
580
- * EIP-712 signature, dropping anything that fails — so what comes back here is
581
- * signed, not merely served.
874
+ * Oracle probe verification is OFF unless `METRIK_GATEWAY_PROBE_CAPABILITY` is
875
+ * truthy. Turning it on lets the neutral verifier exercise this gateway's PAID
876
+ * route with an oracle-signed, single-use, short-lived `ProbeCapability`
877
+ * instead of only its health route.
878
+ *
879
+ * There is NO credential to configure — authority is an EIP-712 signature by an
880
+ * address in the escrow's public `getOracleSigners()` set, read from the same
881
+ * `METRIK_GATEWAY_RPC_URL` the stream check already uses.
882
+ *
883
+ * - `METRIK_GATEWAY_PROBE_CAPABILITY` — `1`/`true`/`yes`/`on` to enable.
884
+ * - `METRIK_GATEWAY_PROBE_MAX_PER_MINUTE` (optional) — free-probe budget.
885
+ * Default {@link DEFAULT_MAX_PROBES_PER_MINUTE}.
886
+ * - `METRIK_GATEWAY_PROBE_SIGNER_CACHE_SECONDS` (optional) — how long the
887
+ * on-chain signer set is cached. Default
888
+ * {@link DEFAULT_ORACLE_SIGNER_CACHE_SECONDS}.
582
889
  */
583
- export async function resolveSignedListingPayee(
584
- serviceRef: Hex,
585
- registryUrl?: string,
586
- ): Promise<{ readonly serviceRef: Hex; readonly operator: Address }> {
587
- const listings = await discoverServices(
588
- registryUrl === undefined ? {} : { registryUrl },
890
+ export function parseGatewayProbeEnvConfig(
891
+ env: NodeJS.ProcessEnv = process.env,
892
+ ): CallerAuthGatewayProbeEnvConfig | undefined {
893
+ const raw = env.METRIK_GATEWAY_PROBE_CAPABILITY?.trim().toLowerCase();
894
+ if (raw === undefined || raw.length === 0) {
895
+ return undefined;
896
+ }
897
+ if (!["1", "true", "yes", "on"].includes(raw)) {
898
+ if (["0", "false", "no", "off"].includes(raw)) {
899
+ return undefined;
900
+ }
901
+ throw new Error(
902
+ `invalid METRIK_GATEWAY_PROBE_CAPABILITY: ${raw} (expected a boolean)`,
903
+ );
904
+ }
905
+
906
+ const maxProbesPerMinute = requirePositiveIntEnv(
907
+ env,
908
+ "METRIK_GATEWAY_PROBE_MAX_PER_MINUTE",
909
+ DEFAULT_MAX_PROBES_PER_MINUTE,
589
910
  );
590
- const match = listings.find(
591
- (listing) => listing.serviceRef.toLowerCase() === serviceRef.toLowerCase(),
911
+ const signerCacheSeconds = requirePositiveIntEnv(
912
+ env,
913
+ "METRIK_GATEWAY_PROBE_SIGNER_CACHE_SECONDS",
914
+ DEFAULT_ORACLE_SIGNER_CACHE_SECONDS,
592
915
  );
593
- if (match === undefined) {
594
- throw new UnresolvedListingPayeeError(serviceRef);
595
- }
596
- return { serviceRef: match.serviceRef, operator: match.operator };
916
+ return { maxProbesPerMinute, signerCacheSeconds };
597
917
  }
598
918
 
599
- /** Builds the gateway's x402 mode, deriving `payTo` from the signed listing. */
600
- export async function buildGatewayX402Mode(
601
- config: CallerAuthGatewayEnvConfig,
602
- ): Promise<GatewayX402Mode | undefined> {
603
- if (config.x402 === undefined) {
604
- return undefined;
919
+ function requirePositiveIntEnv(
920
+ env: NodeJS.ProcessEnv,
921
+ name: string,
922
+ fallback: number,
923
+ ): number {
924
+ const raw = env[name]?.trim();
925
+ if (raw === undefined || raw.length === 0) {
926
+ return fallback;
605
927
  }
606
- const listing = await resolveSignedListingPayee(
607
- config.serviceRef,
608
- config.x402.registryUrl,
609
- );
610
- return {
611
- quote: createListingPriceQuoter({
612
- listing,
613
- resourceBaseUrl: config.x402.resourceBaseUrl,
614
- pricePerCallBaseUnits: config.x402.pricePerCallBaseUnits,
615
- chainId: config.chainId,
616
- ...(config.x402.maxTimeoutSeconds === undefined
617
- ? {}
618
- : { maxTimeoutSeconds: config.x402.maxTimeoutSeconds }),
619
- }),
620
- facilitator: createHttpFacilitatorClient({
621
- url: config.x402.facilitatorUrl,
622
- ...(config.x402.facilitatorToken === undefined
623
- ? {}
624
- : { token: config.x402.facilitatorToken }),
625
- }),
626
- };
928
+ const value = Number(raw);
929
+ if (!Number.isInteger(value) || value <= 0) {
930
+ throw new Error(`invalid ${name}: ${raw} (expected a positive integer)`);
931
+ }
932
+ return value;
627
933
  }
628
934
 
629
935
  function requireEnv(env: NodeJS.ProcessEnv, name: string): string {
@@ -639,8 +945,14 @@ export async function startCallerAuthGatewayServerFromEnv(
639
945
  env: NodeJS.ProcessEnv = process.env,
640
946
  ): Promise<CallerAuthGatewayServer & { readonly boundPort: number }> {
641
947
  const config = parseCallerAuthGatewayEnvConfig(env);
642
- const x402 = await buildGatewayX402Mode(config);
948
+ // Fail closed at startup: a configured descriptor that does not verify is a
949
+ // refusal to start, never a silently unenforced price band.
950
+ const signedRateBounds =
951
+ config.signedDescriptorFile === undefined
952
+ ? undefined
953
+ : await loadSignedRateBoundsFile(config.signedDescriptorFile);
643
954
  const gateway = new CallerAuthGateway({
955
+ ...(signedRateBounds === undefined ? {} : { signedRateBounds }),
644
956
  escrowAddress: config.escrowAddress,
645
957
  rpcUrl: config.rpcUrl,
646
958
  serviceRef: config.serviceRef,
@@ -651,8 +963,32 @@ export async function startCallerAuthGatewayServerFromEnv(
651
963
  ...(config.headerName === undefined
652
964
  ? {}
653
965
  : { headerName: config.headerName }),
654
- ...(x402 === undefined ? {} : { x402 }),
966
+ ...(config.probe === undefined
967
+ ? {}
968
+ : {
969
+ probe: {
970
+ maxProbesPerMinute: config.probe.maxProbesPerMinute,
971
+ signerCacheSeconds: config.probe.signerCacheSeconds,
972
+ },
973
+ }),
655
974
  });
975
+ if (signedRateBounds === undefined) {
976
+ console.error(
977
+ "[metrik-caller-auth-gateway] WARNING: no METRIK_GATEWAY_SIGNED_DESCRIPTOR_FILE — the " +
978
+ "operator-signed minRatePerSecond/maxRatePerSecond are NOT enforced here. The escrow " +
979
+ "accepts any non-zero rate, so a buyer who opens a stream directly against it can be " +
980
+ "served below your signed price (metrik-contracts#41).",
981
+ );
982
+ } else {
983
+ console.error(
984
+ `[metrik-caller-auth-gateway] enforcing operator-signed rate bounds for ${signedRateBounds
985
+ .map(
986
+ (bounds) =>
987
+ `${bounds.serviceRef} [${bounds.minRatePerSecond ?? "-"}, ${bounds.maxRatePerSecond ?? "-"}]`,
988
+ )
989
+ .join(", ")}`,
990
+ );
991
+ }
656
992
  if (config.corroboratingRpcUrls.length === 0) {
657
993
  console.error(
658
994
  "[metrik-caller-auth-gateway] WARNING: no METRIK_GATEWAY_CORROBORATING_RPC_URLS " +
@@ -662,18 +998,91 @@ export async function startCallerAuthGatewayServerFromEnv(
662
998
  "one INDEPENDENT provider to close that window.",
663
999
  );
664
1000
  }
665
- if (x402 !== undefined && config.x402 !== undefined) {
1001
+ if (config.probe !== undefined) {
1002
+ console.error(
1003
+ "[metrik-caller-auth-gateway] oracle probe verification ENABLED: a request carrying a " +
1004
+ "valid EIP-712 ProbeCapability signed by an address in this escrow's on-chain " +
1005
+ `getOracleSigners() set is proxied FREE, unmetered and unbilled, at most ` +
1006
+ `${config.probe.maxProbesPerMinute} per minute. This is what lets the neutral ` +
1007
+ "verifier check this gateway's PAID route instead of only its health route. " +
1008
+ "Leaving it off is safe — the oracle then reports this listing's paid route as " +
1009
+ "UNVERIFIABLE rather than as passing.",
1010
+ );
1011
+ } else {
1012
+ console.error(
1013
+ "[metrik-caller-auth-gateway] oracle probe verification is OFF " +
1014
+ "(METRIK_GATEWAY_PROBE_CAPABILITY unset). The verifier can only reach this service's " +
1015
+ "health route, so paid-route delivery here is UNVERIFIED.",
1016
+ );
1017
+ }
1018
+ let x402Opener: GatewayX402OpenerMode | undefined;
1019
+ if (config.x402Opener !== undefined) {
1020
+ // Loaded only when enabled, so a capability-only gateway never imports @x402/*.
1021
+ const { buildGatewayX402OpenerMode } =
1022
+ await import("./x402-opener-mode.js");
1023
+ x402Opener = await buildGatewayX402OpenerMode(
1024
+ {
1025
+ facilitatorUrl: config.x402Opener.facilitatorUrl,
1026
+ facilitatorToken: config.x402Opener.facilitatorToken,
1027
+ network: config.x402Opener.network,
1028
+ factoryAddress: config.x402Opener.factoryAddress,
1029
+ escrowAddress: config.escrowAddress,
1030
+ asset: config.x402Opener.asset,
1031
+ assetName: config.x402Opener.assetName,
1032
+ assetVersion: config.x402Opener.assetVersion,
1033
+ terms: config.x402Opener.terms,
1034
+ price: config.x402Opener.price,
1035
+ maxTimeoutSeconds: config.x402Opener.maxTimeoutSeconds,
1036
+ facilitatorTimeoutMs: config.x402Opener.facilitatorTimeoutMs,
1037
+ ...(config.x402Opener.resourceBaseUrl === undefined
1038
+ ? {}
1039
+ : { resourceBaseUrl: config.x402Opener.resourceBaseUrl }),
1040
+ ...(config.x402Opener.registryUrl === undefined
1041
+ ? {}
1042
+ : { registryUrl: config.x402Opener.registryUrl }),
1043
+ ...(config.x402Opener.refundBaseUrl === undefined
1044
+ ? {}
1045
+ : { refundBaseUrl: config.x402Opener.refundBaseUrl }),
1046
+ ...(config.x402Opener.docsUrl === undefined
1047
+ ? {}
1048
+ : { docsUrl: config.x402Opener.docsUrl }),
1049
+ ...(config.x402Opener.assetDecimals === undefined
1050
+ ? {}
1051
+ : { assetDecimals: config.x402Opener.assetDecimals }),
1052
+ ...(config.x402Opener.description === undefined
1053
+ ? {}
1054
+ : { description: config.x402Opener.description }),
1055
+ ...(config.x402Opener.schemaDeclaration === undefined
1056
+ ? {}
1057
+ : { schemaDeclaration: config.x402Opener.schemaDeclaration }),
1058
+ },
1059
+ { rpcUrl: config.rpcUrl },
1060
+ );
666
1061
  console.error(
667
- "[metrik-caller-auth-gateway] standard x402 mode ENABLED: callers with no Metrik " +
668
- `capability are quoted ${config.x402.pricePerCallBaseUnits} base units per call, ` +
669
- `settled through ${config.x402.facilitatorUrl}. This is a per-call payment with NO ` +
670
- "escrow and NO recoverability — the stream path remains the only recoverable one.",
1062
+ "[metrik-caller-auth-gateway] x402 v2 opener mode ENABLED: a request with neither a " +
1063
+ "capability nor PAYMENT-SIGNATURE gets a 402 quoting payTo " +
1064
+ `${x402Opener.payTo} (the escrow opener for serviceRef ${config.serviceRef}), price ` +
1065
+ `${config.x402Opener.price} base units. Payments settle into StreamEscrowV2 via the Metrik ` +
1066
+ `opener facilitator at ${config.x402Opener.facilitatorUrl}, and only after the upstream answers < 400. ` +
1067
+ `Refunds (no ETH needed, never automatic): ${x402Opener.refundBaseUrl}/streams/:streamId.`,
671
1068
  );
1069
+ const refundHost = new URL(x402Opener.refundBaseUrl).hostname;
1070
+ if (
1071
+ refundHost === "localhost" ||
1072
+ refundHost === "[::1]" ||
1073
+ refundHost.startsWith("127.")
1074
+ ) {
1075
+ console.error(
1076
+ "[metrik-caller-auth-gateway] WARNING: the 402 advertises a loopback refund URL " +
1077
+ `(${x402Opener.refundBaseUrl}), which payers cannot reach. Set ` +
1078
+ "METRIK_GATEWAY_X402V2_REFUND_BASE_URL to the facilitator's public origin.",
1079
+ );
1080
+ }
672
1081
  }
673
1082
  const server = createCallerAuthGatewayServer({
674
1083
  gateway,
675
1084
  upstreamUrl: config.upstreamUrl,
676
- ...(x402 === undefined ? {} : { x402 }),
1085
+ ...(x402Opener === undefined ? {} : { x402Opener }),
677
1086
  });
678
1087
  const { port } = await server.listen(config.port, config.host);
679
1088
  return Object.assign(server, { boundPort: port });