@absol-labs/agent 0.10.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 (331) hide show
  1. package/README.md +106 -30
  2. package/dist/capability/invocation-capability.d.ts +20 -8
  3. package/dist/capability/invocation-capability.d.ts.map +1 -1
  4. package/dist/capability/invocation-capability.js.map +1 -1
  5. package/dist/capability/probe-capability.d.ts +225 -0
  6. package/dist/capability/probe-capability.d.ts.map +1 -0
  7. package/dist/capability/probe-capability.js +248 -0
  8. package/dist/capability/probe-capability.js.map +1 -0
  9. package/dist/cli/args.d.ts +11 -0
  10. package/dist/cli/args.d.ts.map +1 -1
  11. package/dist/cli/args.js +23 -0
  12. package/dist/cli/args.js.map +1 -1
  13. package/dist/cli/commands/claim.d.ts.map +1 -1
  14. package/dist/cli/commands/claim.js +21 -5
  15. package/dist/cli/commands/claim.js.map +1 -1
  16. package/dist/cli/commands/close.d.ts.map +1 -1
  17. package/dist/cli/commands/close.js +51 -7
  18. package/dist/cli/commands/close.js.map +1 -1
  19. package/dist/cli/commands/invoke.d.ts +2 -0
  20. package/dist/cli/commands/invoke.d.ts.map +1 -1
  21. package/dist/cli/commands/invoke.js +3 -2
  22. package/dist/cli/commands/invoke.js.map +1 -1
  23. package/dist/cli/commands/mcp.d.ts.map +1 -1
  24. package/dist/cli/commands/mcp.js +15 -2
  25. package/dist/cli/commands/mcp.js.map +1 -1
  26. package/dist/cli/commands/open.d.ts.map +1 -1
  27. package/dist/cli/commands/open.js +121 -15
  28. package/dist/cli/commands/open.js.map +1 -1
  29. package/dist/cli/commands/pay.d.ts +19 -0
  30. package/dist/cli/commands/pay.d.ts.map +1 -0
  31. package/dist/cli/commands/pay.js +355 -0
  32. package/dist/cli/commands/pay.js.map +1 -0
  33. package/dist/cli/commands/reclaim-unverified.d.ts.map +1 -1
  34. package/dist/cli/commands/reclaim-unverified.js +15 -6
  35. package/dist/cli/commands/reclaim-unverified.js.map +1 -1
  36. package/dist/cli/commands/reclaim.d.ts +23 -2
  37. package/dist/cli/commands/reclaim.d.ts.map +1 -1
  38. package/dist/cli/commands/reclaim.js +200 -21
  39. package/dist/cli/commands/reclaim.js.map +1 -1
  40. package/dist/cli/commands/refund.d.ts +13 -0
  41. package/dist/cli/commands/refund.d.ts.map +1 -0
  42. package/dist/cli/commands/refund.js +224 -0
  43. package/dist/cli/commands/refund.js.map +1 -0
  44. package/dist/cli/commands/status.d.ts.map +1 -1
  45. package/dist/cli/commands/status.js +10 -1
  46. package/dist/cli/commands/status.js.map +1 -1
  47. package/dist/cli/commands/streams.js +9 -13
  48. package/dist/cli/commands/streams.js.map +1 -1
  49. package/dist/cli/commands/watch.d.ts.map +1 -1
  50. package/dist/cli/commands/watch.js +2 -1
  51. package/dist/cli/commands/watch.js.map +1 -1
  52. package/dist/cli/config.d.ts +44 -26
  53. package/dist/cli/config.d.ts.map +1 -1
  54. package/dist/cli/config.js +88 -38
  55. package/dist/cli/config.js.map +1 -1
  56. package/dist/cli/deps.d.ts +86 -7
  57. package/dist/cli/deps.d.ts.map +1 -1
  58. package/dist/cli/deps.js +102 -16
  59. package/dist/cli/deps.js.map +1 -1
  60. package/dist/cli/errors.d.ts.map +1 -1
  61. package/dist/cli/errors.js +21 -1
  62. package/dist/cli/errors.js.map +1 -1
  63. package/dist/cli/escape-hatch.d.ts +6 -4
  64. package/dist/cli/escape-hatch.d.ts.map +1 -1
  65. package/dist/cli/escape-hatch.js +6 -2
  66. package/dist/cli/escape-hatch.js.map +1 -1
  67. package/dist/cli/listings.d.ts +18 -0
  68. package/dist/cli/listings.d.ts.map +1 -1
  69. package/dist/cli/listings.js +22 -12
  70. package/dist/cli/listings.js.map +1 -1
  71. package/dist/cli/preflight.d.ts +20 -14
  72. package/dist/cli/preflight.d.ts.map +1 -1
  73. package/dist/cli/preflight.js +34 -20
  74. package/dist/cli/preflight.js.map +1 -1
  75. package/dist/cli/privy.d.ts +83 -0
  76. package/dist/cli/privy.d.ts.map +1 -0
  77. package/dist/cli/privy.js +232 -0
  78. package/dist/cli/privy.js.map +1 -0
  79. package/dist/cli/reclaimability.d.ts +82 -0
  80. package/dist/cli/reclaimability.d.ts.map +1 -0
  81. package/dist/cli/reclaimability.js +80 -0
  82. package/dist/cli/reclaimability.js.map +1 -0
  83. package/dist/cli/run.d.ts +2 -1
  84. package/dist/cli/run.d.ts.map +1 -1
  85. package/dist/cli/run.js +40 -11
  86. package/dist/cli/run.js.map +1 -1
  87. package/dist/cli/scan-range.d.ts +2 -2
  88. package/dist/cli/scan-range.js +2 -2
  89. package/dist/cli/spend-policy.d.ts +60 -0
  90. package/dist/cli/spend-policy.d.ts.map +1 -0
  91. package/dist/cli/spend-policy.js +65 -0
  92. package/dist/cli/spend-policy.js.map +1 -0
  93. package/dist/cli/status.d.ts +3 -1
  94. package/dist/cli/status.d.ts.map +1 -1
  95. package/dist/cli/status.js +15 -3
  96. package/dist/cli/status.js.map +1 -1
  97. package/dist/cli/wallet.d.ts +109 -40
  98. package/dist/cli/wallet.d.ts.map +1 -1
  99. package/dist/cli/wallet.js +109 -44
  100. package/dist/cli/wallet.js.map +1 -1
  101. package/dist/discovery/rate-band.d.ts +74 -0
  102. package/dist/discovery/rate-band.d.ts.map +1 -0
  103. package/dist/discovery/rate-band.js +114 -0
  104. package/dist/discovery/rate-band.js.map +1 -0
  105. package/dist/escrow-generation.d.ts +81 -0
  106. package/dist/escrow-generation.d.ts.map +1 -0
  107. package/dist/escrow-generation.js +76 -0
  108. package/dist/escrow-generation.js.map +1 -0
  109. package/dist/frameworks/agentkit.d.ts +8 -4
  110. package/dist/frameworks/agentkit.d.ts.map +1 -1
  111. package/dist/frameworks/agentkit.js +27 -10
  112. package/dist/frameworks/agentkit.js.map +1 -1
  113. package/dist/frameworks/eliza.d.ts +3 -3
  114. package/dist/frameworks/eliza.d.ts.map +1 -1
  115. package/dist/frameworks/eliza.js +15 -6
  116. package/dist/frameworks/eliza.js.map +1 -1
  117. package/dist/frameworks/langchain.d.ts.map +1 -1
  118. package/dist/frameworks/langchain.js +8 -0
  119. package/dist/frameworks/langchain.js.map +1 -1
  120. package/dist/gateway/caller-auth-gateway.d.ts +91 -4
  121. package/dist/gateway/caller-auth-gateway.d.ts.map +1 -1
  122. package/dist/gateway/caller-auth-gateway.js +184 -7
  123. package/dist/gateway/caller-auth-gateway.js.map +1 -1
  124. package/dist/gateway/http-server.d.ts +121 -1
  125. package/dist/gateway/http-server.d.ts.map +1 -1
  126. package/dist/gateway/http-server.js +474 -5
  127. package/dist/gateway/http-server.js.map +1 -1
  128. package/dist/gateway/probe-auth.d.ts +112 -0
  129. package/dist/gateway/probe-auth.d.ts.map +1 -0
  130. package/dist/gateway/probe-auth.js +127 -0
  131. package/dist/gateway/probe-auth.js.map +1 -0
  132. package/dist/gateway/signed-rate-bounds.d.ts +51 -0
  133. package/dist/gateway/signed-rate-bounds.d.ts.map +1 -0
  134. package/dist/gateway/signed-rate-bounds.js +94 -0
  135. package/dist/gateway/signed-rate-bounds.js.map +1 -0
  136. package/dist/gateway/x402-opener-mode.d.ts +215 -0
  137. package/dist/gateway/x402-opener-mode.d.ts.map +1 -0
  138. package/dist/gateway/x402-opener-mode.js +639 -0
  139. package/dist/gateway/x402-opener-mode.js.map +1 -0
  140. package/dist/index.d.ts +11 -5
  141. package/dist/index.d.ts.map +1 -1
  142. package/dist/index.js +15 -5
  143. package/dist/index.js.map +1 -1
  144. package/dist/mandates/env.d.ts +3 -2
  145. package/dist/mandates/env.d.ts.map +1 -1
  146. package/dist/mandates/env.js +3 -2
  147. package/dist/mandates/env.js.map +1 -1
  148. package/dist/mcp/server.d.ts +100 -0
  149. package/dist/mcp/server.d.ts.map +1 -1
  150. package/dist/mcp/server.js +719 -39
  151. package/dist/mcp/server.js.map +1 -1
  152. package/dist/mcp/service-invoker.d.ts +97 -0
  153. package/dist/mcp/service-invoker.d.ts.map +1 -0
  154. package/dist/mcp/service-invoker.js +167 -0
  155. package/dist/mcp/service-invoker.js.map +1 -0
  156. package/dist/mcp/x402-tools.d.ts +104 -0
  157. package/dist/mcp/x402-tools.d.ts.map +1 -0
  158. package/dist/mcp/x402-tools.js +434 -0
  159. package/dist/mcp/x402-tools.js.map +1 -0
  160. package/dist/network.d.ts +119 -0
  161. package/dist/network.d.ts.map +1 -0
  162. package/dist/network.js +199 -0
  163. package/dist/network.js.map +1 -0
  164. package/dist/sdk/invoke.d.ts +23 -4
  165. package/dist/sdk/invoke.d.ts.map +1 -1
  166. package/dist/sdk/invoke.js +71 -10
  167. package/dist/sdk/invoke.js.map +1 -1
  168. package/dist/wallet/autonomous-wallet-broker.d.ts +3 -0
  169. package/dist/wallet/autonomous-wallet-broker.d.ts.map +1 -1
  170. package/dist/wallet/autonomous-wallet-broker.js +27 -23
  171. package/dist/wallet/autonomous-wallet-broker.js.map +1 -1
  172. package/dist/wallet/autonomous-wallet-protocol.d.ts +8 -2
  173. package/dist/wallet/autonomous-wallet-protocol.d.ts.map +1 -1
  174. package/dist/wallet/autonomous-wallet-protocol.js +9 -2
  175. package/dist/wallet/autonomous-wallet-protocol.js.map +1 -1
  176. package/dist/wallet/autonomous-wallet.d.ts.map +1 -1
  177. package/dist/wallet/autonomous-wallet.js +3 -2
  178. package/dist/wallet/autonomous-wallet.js.map +1 -1
  179. package/dist/wallet/broker-escrows.d.ts +222 -0
  180. package/dist/wallet/broker-escrows.d.ts.map +1 -0
  181. package/dist/wallet/broker-escrows.js +36 -0
  182. package/dist/wallet/broker-escrows.js.map +1 -0
  183. package/dist/wallet/lifecycle.d.ts +21 -5
  184. package/dist/wallet/lifecycle.d.ts.map +1 -1
  185. package/dist/wallet/lifecycle.js +32 -12
  186. package/dist/wallet/lifecycle.js.map +1 -1
  187. package/dist/wallet/privy-broker-server.d.ts.map +1 -1
  188. package/dist/wallet/privy-broker-server.js +31 -26
  189. package/dist/wallet/privy-broker-server.js.map +1 -1
  190. package/dist/wallet/privy-session-broker.d.ts +14 -5
  191. package/dist/wallet/privy-session-broker.d.ts.map +1 -1
  192. package/dist/wallet/privy-session-broker.js +29 -17
  193. package/dist/wallet/privy-session-broker.js.map +1 -1
  194. package/dist/wallet/privy-session-provider.d.ts +3 -1
  195. package/dist/wallet/privy-session-provider.d.ts.map +1 -1
  196. package/dist/wallet/privy-session-provider.js +5 -3
  197. package/dist/wallet/privy-session-provider.js.map +1 -1
  198. package/dist/wallet/provider.d.ts.map +1 -1
  199. package/dist/wallet/provider.js +15 -8
  200. package/dist/wallet/provider.js.map +1 -1
  201. package/dist/x402/facilitator.d.ts +42 -17
  202. package/dist/x402/facilitator.d.ts.map +1 -1
  203. package/dist/x402/facilitator.js +49 -33
  204. package/dist/x402/facilitator.js.map +1 -1
  205. package/dist/x402-buyer/guarded-fetch.d.ts +51 -0
  206. package/dist/x402-buyer/guarded-fetch.d.ts.map +1 -0
  207. package/dist/x402-buyer/guarded-fetch.js +147 -0
  208. package/dist/x402-buyer/guarded-fetch.js.map +1 -0
  209. package/dist/x402-buyer/index.d.ts +10 -0
  210. package/dist/x402-buyer/index.d.ts.map +1 -0
  211. package/dist/x402-buyer/index.js +10 -0
  212. package/dist/x402-buyer/index.js.map +1 -0
  213. package/dist/x402-buyer/pay.d.ts +135 -0
  214. package/dist/x402-buyer/pay.d.ts.map +1 -0
  215. package/dist/x402-buyer/pay.js +336 -0
  216. package/dist/x402-buyer/pay.js.map +1 -0
  217. package/dist/x402-opener/abi.d.ts +684 -0
  218. package/dist/x402-opener/abi.d.ts.map +1 -0
  219. package/dist/x402-opener/abi.js +880 -0
  220. package/dist/x402-opener/abi.js.map +1 -0
  221. package/dist/x402-opener/facilitator-entry.d.ts +3 -0
  222. package/dist/x402-opener/facilitator-entry.d.ts.map +1 -0
  223. package/dist/x402-opener/facilitator-entry.js +37 -0
  224. package/dist/x402-opener/facilitator-entry.js.map +1 -0
  225. package/dist/x402-opener/facilitator-server.d.ts +180 -0
  226. package/dist/x402-opener/facilitator-server.d.ts.map +1 -0
  227. package/dist/x402-opener/facilitator-server.js +696 -0
  228. package/dist/x402-opener/facilitator-server.js.map +1 -0
  229. package/dist/x402-opener/index.d.ts +14 -0
  230. package/dist/x402-opener/index.d.ts.map +1 -0
  231. package/dist/x402-opener/index.js +14 -0
  232. package/dist/x402-opener/index.js.map +1 -0
  233. package/dist/x402-opener/listing-resolver.d.ts +55 -0
  234. package/dist/x402-opener/listing-resolver.d.ts.map +1 -0
  235. package/dist/x402-opener/listing-resolver.js +125 -0
  236. package/dist/x402-opener/listing-resolver.js.map +1 -0
  237. package/dist/x402-opener/refund-relay.d.ts +240 -0
  238. package/dist/x402-opener/refund-relay.d.ts.map +1 -0
  239. package/dist/x402-opener/refund-relay.js +1240 -0
  240. package/dist/x402-opener/refund-relay.js.map +1 -0
  241. package/dist/x402-opener/relayer-queue.d.ts +14 -0
  242. package/dist/x402-opener/relayer-queue.d.ts.map +1 -0
  243. package/dist/x402-opener/relayer-queue.js +18 -0
  244. package/dist/x402-opener/relayer-queue.js.map +1 -0
  245. package/dist/x402-opener/scheme.d.ts +217 -0
  246. package/dist/x402-opener/scheme.d.ts.map +1 -0
  247. package/dist/x402-opener/scheme.js +749 -0
  248. package/dist/x402-opener/scheme.js.map +1 -0
  249. package/dist/x402-opener/terms.d.ts +105 -0
  250. package/dist/x402-opener/terms.d.ts.map +1 -0
  251. package/dist/x402-opener/terms.js +212 -0
  252. package/dist/x402-opener/terms.js.map +1 -0
  253. package/dist/zktls/reclaim.d.ts +2 -2
  254. package/docs/agent-layer.md +13 -8
  255. package/docs/autonomous-privy-wallet.md +188 -0
  256. package/docs/cli.md +342 -53
  257. package/docs/langchain.md +5 -0
  258. package/docs/mcp-hosted.md +4 -3
  259. package/docs/mcp-reference.md +245 -0
  260. package/docs/probe-capability.md +191 -0
  261. package/docs/quickstart.md +54 -5
  262. package/docs/threat-model.md +24 -3
  263. package/docs/x402.md +681 -0
  264. package/package.json +19 -6
  265. package/src/capability/invocation-capability.ts +17 -1
  266. package/src/capability/probe-capability.ts +355 -0
  267. package/src/cli/args.ts +29 -0
  268. package/src/cli/commands/claim.ts +31 -5
  269. package/src/cli/commands/close.ts +56 -7
  270. package/src/cli/commands/invoke.ts +6 -2
  271. package/src/cli/commands/mcp.ts +18 -2
  272. package/src/cli/commands/open.ts +151 -14
  273. package/src/cli/commands/pay.ts +442 -0
  274. package/src/cli/commands/reclaim-unverified.ts +24 -6
  275. package/src/cli/commands/reclaim.ts +274 -19
  276. package/src/cli/commands/refund.ts +277 -0
  277. package/src/cli/commands/status.ts +17 -1
  278. package/src/cli/commands/streams.ts +11 -15
  279. package/src/cli/commands/watch.ts +7 -1
  280. package/src/cli/config.ts +139 -52
  281. package/src/cli/deps.ts +189 -25
  282. package/src/cli/errors.ts +24 -1
  283. package/src/cli/escape-hatch.ts +19 -5
  284. package/src/cli/listings.ts +43 -10
  285. package/src/cli/preflight.ts +36 -21
  286. package/src/cli/privy.ts +398 -0
  287. package/src/cli/reclaimability.ts +154 -0
  288. package/src/cli/run.ts +54 -11
  289. package/src/cli/scan-range.ts +2 -2
  290. package/src/cli/spend-policy.ts +139 -0
  291. package/src/cli/status.ts +14 -1
  292. package/src/cli/wallet.ts +189 -58
  293. package/src/discovery/rate-band.ts +172 -0
  294. package/src/escrow-generation.ts +135 -0
  295. package/src/frameworks/agentkit.ts +45 -11
  296. package/src/frameworks/eliza.ts +27 -5
  297. package/src/frameworks/langchain.ts +14 -0
  298. package/src/gateway/caller-auth-gateway.ts +336 -13
  299. package/src/gateway/http-server.ts +690 -7
  300. package/src/gateway/probe-auth.ts +191 -0
  301. package/src/gateway/signed-rate-bounds.ts +164 -0
  302. package/src/gateway/x402-opener-mode.ts +974 -0
  303. package/src/index.ts +112 -14
  304. package/src/mandates/env.ts +3 -2
  305. package/src/mcp/server.ts +973 -44
  306. package/src/mcp/service-invoker.ts +285 -0
  307. package/src/mcp/x402-tools.ts +621 -0
  308. package/src/network.ts +302 -0
  309. package/src/sdk/invoke.ts +96 -17
  310. package/src/wallet/autonomous-wallet-broker.ts +46 -20
  311. package/src/wallet/autonomous-wallet-protocol.ts +11 -2
  312. package/src/wallet/autonomous-wallet.ts +4 -2
  313. package/src/wallet/broker-escrows.ts +66 -0
  314. package/src/wallet/lifecycle.ts +53 -18
  315. package/src/wallet/privy-broker-server.ts +35 -25
  316. package/src/wallet/privy-session-broker.ts +58 -25
  317. package/src/wallet/privy-session-provider.ts +7 -3
  318. package/src/wallet/provider.ts +20 -15
  319. package/src/x402/facilitator.ts +85 -46
  320. package/src/x402-buyer/guarded-fetch.ts +213 -0
  321. package/src/x402-buyer/index.ts +9 -0
  322. package/src/x402-buyer/pay.ts +517 -0
  323. package/src/x402-opener/abi.ts +881 -0
  324. package/src/x402-opener/facilitator-entry.ts +45 -0
  325. package/src/x402-opener/facilitator-server.ts +1014 -0
  326. package/src/x402-opener/index.ts +13 -0
  327. package/src/x402-opener/listing-resolver.ts +202 -0
  328. package/src/x402-opener/refund-relay.ts +1743 -0
  329. package/src/x402-opener/relayer-queue.ts +18 -0
  330. package/src/x402-opener/scheme.ts +1133 -0
  331. package/src/x402-opener/terms.ts +300 -0
@@ -0,0 +1,974 @@
1
+ import {
2
+ HTTPFacilitatorClient,
3
+ SETTLEMENT_OVERRIDES_HEADER,
4
+ withPrivateCacheControl,
5
+ x402HTTPResourceServer,
6
+ x402ResourceServer,
7
+ type FacilitatorClient,
8
+ type HTTPAdapter,
9
+ type HTTPProcessResult,
10
+ type HTTPRequestContext,
11
+ type HTTPResponseInstructions,
12
+ type ProcessSettleResultResponse,
13
+ type RouteConfig,
14
+ type SettleResultContext,
15
+ } from "@x402/core/server";
16
+ import type { Network } from "@x402/core/types";
17
+ import { decodePaymentSignatureHeader } from "@x402/core/http";
18
+ import { ExactEvmScheme } from "@x402/evm/exact/server";
19
+ import {
20
+ createPublicClient,
21
+ formatUnits,
22
+ getAddress,
23
+ http,
24
+ isAddress,
25
+ type Address,
26
+ type PublicClient,
27
+ } from "viem";
28
+
29
+ import { x402StreamOpenerFactoryAbi } from "../x402-opener/abi.js";
30
+ import {
31
+ RegistryListingResolver,
32
+ type OperatorSignedListingResolver,
33
+ } from "../x402-opener/listing-resolver.js";
34
+ import { readOpenerFacilitatorMarker } from "../x402-opener/scheme.js";
35
+ import {
36
+ assertValidPrice,
37
+ assertValidTerms,
38
+ chainIdFromNetwork,
39
+ assertSchemaDeclaration,
40
+ DEFAULT_OPENER_DOCS_URL,
41
+ isHttpLink,
42
+ OPENER_EXTRA_KEY,
43
+ OPENER_SCHEME,
44
+ termsToExtra,
45
+ termsTuple,
46
+ type OpenerTerms,
47
+ type X402SchemaDeclaration,
48
+ } from "../x402-opener/terms.js";
49
+
50
+ /**
51
+ * The gateway's x402 v2 mode (metrik-agent#116): answer an uncapabilitied
52
+ * request with a standard x402 v2 `402` whose `payTo` is the listing's
53
+ * `X402StreamOpener` address, and settle every accepted payment INTO a
54
+ * `StreamEscrowV2` stream through the Metrik opener facilitator.
55
+ *
56
+ * The wire format is the official `@x402/core` resource server's, not a
57
+ * re-implementation: `x402HTTPResourceServer` builds `PAYMENT-REQUIRED`,
58
+ * matches `PAYMENT-SIGNATURE`, verifies and settles through the facilitator and
59
+ * builds `PAYMENT-RESPONSE`.
60
+ *
61
+ * ## The opener payTo must ONLY ever be settled by the Metrik opener facilitator
62
+ *
63
+ * A stock x402 `exact` facilitator settles by calling
64
+ * `USDC.transferWithAuthorization(to = payTo)` directly. Pointed at an opener,
65
+ * that strands 100% of the payer's funds in the opener permanently (there is,
66
+ * deliberately, no sweep). So this mode:
67
+ *
68
+ * - refuses to START unless the configured facilitator's `GET /supported`
69
+ * advertises the opener marker for exactly this factory, escrow, token and
70
+ * chain; and re-checks that marker on a timer, failing CLOSED (503, no
71
+ * `payTo` quoted, nothing verified or settled) whenever it cannot;
72
+ * - uses exactly one facilitator client, never a fallback list;
73
+ * - registers no discovery (Bazaar) extension and never submits the route to
74
+ * any catalog. When (and only when) the operator configures an input/output
75
+ * schema, it is DECLARED in the 402 in the standard `extensions.bazaar`
76
+ * shape so a client can read what to send; only the Metrik opener
77
+ * facilitator ever sees the payment, and it catalogs nothing;
78
+ * - states plainly in the 402 `description` what is bought (the stream
79
+ * window, rate, that the seller earns only verified seconds, and that
80
+ * unearned money is refundable without ETH through the facilitator's
81
+ * refund relay) and refuses to start unless that facilitator advertises
82
+ * the relay (`refundRelay: true` in its marker) — the 402 never promises a
83
+ * refund path that is not there. Refunds are not automatic;
84
+ * - authenticates the opener only as `factory.predict(terms)` — never by code
85
+ * or codehash, which a clone outside the factory can reproduce;
86
+ * - serves one EIP-3009 authorization at most once: a `PAYMENT-SIGNATURE`
87
+ * whose authorization is in flight or already settled gets `409` WITHOUT an
88
+ * upstream call (in-memory, per gateway instance). A retry after
89
+ * `settlement_pending` is let through so it can reconcile;
90
+ * - refuses to start if its price is below the facilitator's advertised
91
+ * minimum, or if its facilitator timeout would not outlast the facilitator's
92
+ * receipt wait.
93
+ */
94
+
95
+ /** How long a successful `/supported` marker check is trusted, seconds. */
96
+ export const DEFAULT_FACILITATOR_MARKER_TTL_SECONDS = 300;
97
+
98
+ /** Default per-request facilitator HTTP timeout. Must outlast its receipt wait. */
99
+ export const DEFAULT_FACILITATOR_TIMEOUT_MS = 120_000;
100
+
101
+ /** Headroom the facilitator timeout must leave over the facilitator's receipt wait. */
102
+ const FACILITATOR_TIMEOUT_HEADROOM_MS = 30_000;
103
+
104
+ export interface GatewayX402OpenerModeConfig {
105
+ /** Base URL of the Metrik opener facilitator (e.g. `https://facilitator.example`). */
106
+ readonly facilitatorUrl: string;
107
+ /** Bearer token the facilitator requires on `/settle`. */
108
+ readonly facilitatorToken: string;
109
+ /** CAIP-2 network (`eip155:<chainId>`), as the registry gives it. */
110
+ readonly network: Network;
111
+ readonly factoryAddress: Address;
112
+ /** The escrow this gateway checks streams against; the factory must point at it. */
113
+ readonly escrowAddress: Address;
114
+ /** Settlement token; must equal the factory's. */
115
+ readonly asset: Address;
116
+ /** EIP-712 domain of the token (Circle USDC: `USDC` / `2`). */
117
+ readonly assetName: string;
118
+ readonly assetVersion: string;
119
+ /** Opener terms. `operator` + `serviceRef` must resolve to one operator-signed listing. */
120
+ readonly terms: OpenerTerms;
121
+ /** Price per paid request in token base units. Becomes the stream deposit. */
122
+ readonly price: bigint;
123
+ /** Authorization validity the client signs for. Default 300s. */
124
+ readonly maxTimeoutSeconds?: number;
125
+ /** Public origin clients reach this gateway at, for the 402 `resource.url`. */
126
+ readonly resourceBaseUrl?: string;
127
+ /**
128
+ * What the service does, in one sentence. Prefixed to the fixed disclosure
129
+ * of what the payment buys ({@link describeOpenerPurchase}); it can never
130
+ * replace that disclosure.
131
+ */
132
+ readonly description?: string;
133
+ /**
134
+ * Public base URL of the facilitator's refund relay (`/streams/:streamId`).
135
+ * Default `facilitatorUrl`. When different, its `/supported` must advertise
136
+ * the same opener marker with `refundRelay: true` (checked at startup).
137
+ */
138
+ readonly refundBaseUrl?: string;
139
+ /** Docs link carried in the 402. Default {@link DEFAULT_OPENER_DOCS_URL}. */
140
+ readonly docsUrl?: string;
141
+ /** Token decimals for the human-readable amounts in the description. Default 6 (USDC). */
142
+ readonly assetDecimals?: number;
143
+ /**
144
+ * Optional input/output schema, declared in the 402 as
145
+ * `extensions.bazaar` (`{info: {input, output}, schema}`). Declared only;
146
+ * never registered with any discovery catalog.
147
+ */
148
+ readonly schemaDeclaration?: X402SchemaDeclaration;
149
+ /** Registry used to prove the listing at startup. Default the public registry. */
150
+ readonly registryUrl?: string;
151
+ readonly markerTtlSeconds?: number;
152
+ /**
153
+ * Per-request facilitator HTTP timeout, ms. Default
154
+ * {@link DEFAULT_FACILITATOR_TIMEOUT_MS}. Must exceed the facilitator's
155
+ * advertised receipt timeout by 30 s, so the gateway never gives up on a
156
+ * settlement the facilitator is still waiting for.
157
+ */
158
+ readonly facilitatorTimeoutMs?: number;
159
+ }
160
+
161
+ /**
162
+ * The plain statement of what one payment buys, used as the 402 resource
163
+ * `description`. It names the window, the rate, that the seller earns only for
164
+ * seconds Metrik's verifier confirms, and where unearned money is refundable
165
+ * without ETH. It says that refunds are not automatic, because they are not:
166
+ * someone has to call the refund relay.
167
+ */
168
+ export function describeOpenerPurchase(input: {
169
+ readonly terms: OpenerTerms;
170
+ readonly price: bigint;
171
+ readonly assetDecimals: number;
172
+ readonly assetSymbol: string;
173
+ /** Refund URL template containing `{streamId}`. */
174
+ readonly refundUrlTemplate: string;
175
+ readonly docsUrl: string;
176
+ readonly serviceDescription?: string;
177
+ }): string {
178
+ const amount = (value: bigint) =>
179
+ `${formatUnits(value, input.assetDecimals)} ${input.assetSymbol}`;
180
+ const { ratePerSecond, maxDuration } = input.terms;
181
+ const cap =
182
+ input.price < ratePerSecond * maxDuration
183
+ ? ` (the seller can earn at most ${amount(input.price)})`
184
+ : "";
185
+ const prefix =
186
+ input.serviceDescription === undefined ||
187
+ input.serviceDescription.trim().length === 0
188
+ ? ""
189
+ : `${input.serviceDescription.trim()} `;
190
+ return (
191
+ `${prefix}Pays for one call. Your payment of ${amount(input.price)} funds a Metrik escrow stream of ` +
192
+ `${maxDuration.toString()} seconds at ${amount(ratePerSecond)}/s${cap}; ` +
193
+ "the seller earns only for seconds Metrik's verifier confirms the service is delivering, " +
194
+ `and anything unearned is refundable to you (no ETH needed) via ${input.refundUrlTemplate}. ` +
195
+ "Refunds are not automatic: close the stream and reclaim there, using the streamId from the PAYMENT-RESPONSE. " +
196
+ `Docs: ${input.docsUrl}`
197
+ );
198
+ }
199
+
200
+ /**
201
+ * The stock `exact` server scheme, plus ONE additive settlement enrichment:
202
+ * the successful `PAYMENT-RESPONSE` gets `extra.metrikStreamOpener.refundUrl`
203
+ * for the opened stream. It never touches the settlement outcome fields
204
+ * (`@x402/core` enforces that the enrichment is additive).
205
+ */
206
+ class OpenerExactServerScheme extends ExactEvmScheme {
207
+ constructor(private readonly refundBaseUrl: string) {
208
+ super();
209
+ }
210
+
211
+ enrichSettlementResponse = async (
212
+ context: SettleResultContext,
213
+ ): Promise<Record<string, unknown> | undefined> => {
214
+ if (!context.result.success) return undefined;
215
+ const opened = context.result.extra?.[OPENER_EXTRA_KEY] as
216
+ | Record<string, unknown>
217
+ | undefined;
218
+ const streamId = opened?.streamId;
219
+ if (
220
+ typeof streamId !== "string" ||
221
+ !/^0x[0-9a-fA-F]{64}$/.test(streamId) ||
222
+ opened?.refundUrl !== undefined
223
+ ) {
224
+ return undefined;
225
+ }
226
+ return {
227
+ [OPENER_EXTRA_KEY]: {
228
+ refundUrl: `${this.refundBaseUrl}/streams/${streamId.toLowerCase()}`,
229
+ },
230
+ };
231
+ };
232
+ }
233
+
234
+ export interface GatewayX402OpenerModeDeps {
235
+ /** Read client for the factory. Default built from `rpcUrl`. */
236
+ readonly publicClient?: PublicClient;
237
+ readonly rpcUrl?: string;
238
+ readonly listingResolver?: OperatorSignedListingResolver;
239
+ /** Override the facilitator transport (tests). Default {@link HTTPFacilitatorClient}. */
240
+ readonly facilitatorClient?: FacilitatorClient;
241
+ readonly now?: () => number;
242
+ /** HTTP client for checking a separate `refundBaseUrl`. Default global fetch. */
243
+ readonly fetch?: typeof fetch;
244
+ }
245
+
246
+ export interface GatewayX402OpenerMode {
247
+ /** The predicted opener address quoted as `payTo`. */
248
+ readonly payTo: Address;
249
+ readonly network: Network;
250
+ readonly terms: OpenerTerms;
251
+ readonly price: bigint;
252
+ readonly resourceBaseUrl: string | undefined;
253
+ /** The 402 `description` (what the payment buys). */
254
+ readonly description: string;
255
+ /** Refund relay base; a stream's refund page is `${refundBaseUrl}/streams/:streamId`. */
256
+ readonly refundBaseUrl: string;
257
+ readonly httpServer: x402HTTPResourceServer;
258
+ /** One-use accounting of authorizations this gateway has seen. */
259
+ readonly authorizations: GatewayAuthorizationLedger;
260
+ /**
261
+ * Resolves once the facilitator is proven to be the Metrik opener
262
+ * facilitator for this factory (cached for the marker TTL) and the resource
263
+ * server is initialized. Rejects otherwise — callers must fail closed.
264
+ */
265
+ ready(): Promise<void>;
266
+ /** Serves one x402-mode request over the supplied transport. Never throws. */
267
+ handle(io: X402GatewayRequestIO): Promise<void>;
268
+ }
269
+
270
+ /** JSON reasons the x402 path can answer with, beyond the gateway's own. */
271
+ export type X402GatewayResponseReason =
272
+ | "x402-facilitator-unavailable"
273
+ | "x402-settlement-failed"
274
+ | "internal-error"
275
+ | "upstream-unavailable"
276
+ | "x402-payment-already-used";
277
+
278
+ export interface X402UpstreamResult {
279
+ readonly status: number;
280
+ readonly headers: Record<string, string>;
281
+ readonly body: Buffer;
282
+ }
283
+
284
+ /** The transport the HTTP server hands the x402 path. */
285
+ export interface X402GatewayRequestIO {
286
+ readonly requestUrl: URL;
287
+ readonly method: string;
288
+ /** Lower-cased request headers. */
289
+ readonly headers: Readonly<Record<string, string | undefined>>;
290
+ /** Proxies the request upstream (payment headers stripped) and buffers the response. */
291
+ callUpstream(): Promise<X402UpstreamResult>;
292
+ writeJson(status: number, reason: X402GatewayResponseReason): void;
293
+ write(
294
+ status: number,
295
+ headers: Record<string, string>,
296
+ body: Buffer | string,
297
+ ): void;
298
+ logError(context: string, error: unknown): void;
299
+ }
300
+
301
+ const PAYMENT_SIGNATURE_HEADER = "payment-signature";
302
+
303
+ /**
304
+ * Per-gateway, in-memory record of EIP-3009 authorizations (chain + asset +
305
+ * payer + nonce): `in-flight` while a request is being verified/served/
306
+ * settled, `pending` after a `settlement_pending` (a retry may reconcile), and
307
+ * `settled` once a success was delivered. In-flight and settled
308
+ * authorizations are refused before the upstream is ever called. Entries are
309
+ * dropped once the authorization's `validBefore` has passed (plus a grace).
310
+ */
311
+ export class GatewayAuthorizationLedger {
312
+ private readonly entries = new Map<
313
+ string,
314
+ { state: "in-flight" | "pending" | "settled"; validBefore: bigint }
315
+ >();
316
+
317
+ constructor(
318
+ private readonly now: () => number,
319
+ private readonly maxEntries = 100_000,
320
+ ) {}
321
+
322
+ /** Claims the authorization for one request; false if it is in flight or settled. */
323
+ claim(key: string, validBefore: bigint): boolean {
324
+ this.prune();
325
+ const entry = this.entries.get(key);
326
+ if (entry !== undefined && entry.state !== "pending") return false;
327
+ if (entry === undefined && this.entries.size >= this.maxEntries)
328
+ return false;
329
+ this.entries.set(key, { state: "in-flight", validBefore });
330
+ return true;
331
+ }
332
+
333
+ release(key: string): void {
334
+ this.entries.delete(key);
335
+ }
336
+
337
+ markPending(key: string, validBefore: bigint): void {
338
+ this.entries.set(key, { state: "pending", validBefore });
339
+ }
340
+
341
+ markSettled(key: string, validBefore: bigint): void {
342
+ this.entries.set(key, { state: "settled", validBefore });
343
+ }
344
+
345
+ private prune(): void {
346
+ const now = BigInt(this.now());
347
+ for (const [key, entry] of this.entries) {
348
+ if (entry.state !== "in-flight" && entry.validBefore + 600n < now) {
349
+ this.entries.delete(key);
350
+ }
351
+ }
352
+ }
353
+ }
354
+
355
+ /** Ledger key for a `PAYMENT-SIGNATURE`, or undefined if it does not decode. */
356
+ function authorizationKey(
357
+ header: string,
358
+ ): { readonly key: string; readonly validBefore: bigint } | undefined {
359
+ try {
360
+ const payload = decodePaymentSignatureHeader(header);
361
+ const authorization = (
362
+ payload.payload as {
363
+ authorization?: {
364
+ from?: unknown;
365
+ nonce?: unknown;
366
+ validBefore?: unknown;
367
+ };
368
+ }
369
+ ).authorization;
370
+ const network = payload.accepted?.network;
371
+ const asset = payload.accepted?.asset;
372
+ if (
373
+ typeof authorization?.from !== "string" ||
374
+ typeof authorization.nonce !== "string" ||
375
+ typeof authorization.validBefore !== "string" ||
376
+ !/^\d+$/.test(authorization.validBefore) ||
377
+ typeof network !== "string" ||
378
+ typeof asset !== "string"
379
+ ) {
380
+ return undefined;
381
+ }
382
+ return {
383
+ key: [
384
+ network,
385
+ asset.toLowerCase(),
386
+ authorization.from.toLowerCase(),
387
+ authorization.nonce.toLowerCase(),
388
+ ].join(":"),
389
+ validBefore: BigInt(authorization.validBefore),
390
+ };
391
+ } catch {
392
+ return undefined;
393
+ }
394
+ }
395
+
396
+ export class X402OpenerModeConfigError extends Error {
397
+ constructor(message: string) {
398
+ super(message);
399
+ this.name = "X402OpenerModeConfigError";
400
+ }
401
+ }
402
+
403
+ export class X402OpenerFacilitatorUnverifiedError extends Error {
404
+ constructor(message: string, options?: { readonly cause?: unknown }) {
405
+ super(message, options);
406
+ this.name = "X402OpenerFacilitatorUnverifiedError";
407
+ }
408
+ }
409
+
410
+ /**
411
+ * Builds the x402 mode and proves, before returning, every fact it will quote:
412
+ * valid terms and price, one operator-signed listing for the terms, the
413
+ * factory's escrow and token, the predicted `payTo`, and the facilitator's
414
+ * opener marker. Throws on any doubt; the gateway then refuses to start.
415
+ */
416
+ export async function buildGatewayX402OpenerMode(
417
+ config: GatewayX402OpenerModeConfig,
418
+ deps: GatewayX402OpenerModeDeps = {},
419
+ ): Promise<GatewayX402OpenerMode> {
420
+ try {
421
+ assertValidTerms(config.terms);
422
+ assertValidPrice(config.price, config.terms);
423
+ } catch (error) {
424
+ throw new X402OpenerModeConfigError(
425
+ error instanceof Error ? error.message : String(error),
426
+ );
427
+ }
428
+ const chainId = chainIdFromNetwork(config.network);
429
+ for (const [name, value] of [
430
+ ["factoryAddress", config.factoryAddress],
431
+ ["escrowAddress", config.escrowAddress],
432
+ ["asset", config.asset],
433
+ ] as const) {
434
+ if (!isAddress(value)) {
435
+ throw new X402OpenerModeConfigError(`${name} must be an EVM address`);
436
+ }
437
+ }
438
+ const maxTimeoutSeconds = config.maxTimeoutSeconds ?? 300;
439
+ if (!Number.isInteger(maxTimeoutSeconds) || maxTimeoutSeconds < 30) {
440
+ throw new X402OpenerModeConfigError(
441
+ "maxTimeoutSeconds must be an integer >= 30",
442
+ );
443
+ }
444
+ if (config.facilitatorToken.length === 0) {
445
+ throw new X402OpenerModeConfigError("facilitatorToken is required");
446
+ }
447
+ if (config.resourceBaseUrl !== undefined) {
448
+ // eslint-disable-next-line no-new -- validates the URL is well-formed.
449
+ new URL(config.resourceBaseUrl);
450
+ }
451
+ const refundBaseUrl = (config.refundBaseUrl ?? config.facilitatorUrl).replace(
452
+ /\/+$/,
453
+ "",
454
+ );
455
+ const docsUrl = config.docsUrl ?? DEFAULT_OPENER_DOCS_URL;
456
+ for (const [name, value] of [
457
+ ["refundBaseUrl", refundBaseUrl],
458
+ ["docsUrl", docsUrl],
459
+ ] as const) {
460
+ if (!isHttpLink(value)) {
461
+ throw new X402OpenerModeConfigError(`${name} must be an http(s) URL`);
462
+ }
463
+ }
464
+ const assetDecimals = config.assetDecimals ?? 6;
465
+ if (
466
+ !Number.isInteger(assetDecimals) ||
467
+ assetDecimals < 0 ||
468
+ assetDecimals > 36
469
+ ) {
470
+ throw new X402OpenerModeConfigError(
471
+ "assetDecimals must be an integer in [0, 36]",
472
+ );
473
+ }
474
+ if (config.schemaDeclaration !== undefined) {
475
+ try {
476
+ assertSchemaDeclaration(config.schemaDeclaration);
477
+ } catch (error) {
478
+ throw new X402OpenerModeConfigError(
479
+ error instanceof Error ? error.message : String(error),
480
+ );
481
+ }
482
+ }
483
+
484
+ const publicClient =
485
+ deps.publicClient ??
486
+ (deps.rpcUrl === undefined
487
+ ? undefined
488
+ : createPublicClient({ transport: http(deps.rpcUrl) }));
489
+ if (publicClient === undefined) {
490
+ throw new X402OpenerModeConfigError(
491
+ "an RPC (publicClient or rpcUrl) is required to predict the opener address",
492
+ );
493
+ }
494
+ const rpcChainId = await publicClient.getChainId();
495
+ if (rpcChainId !== chainId) {
496
+ throw new X402OpenerModeConfigError(
497
+ `RPC chain id ${rpcChainId} does not match network ${config.network}`,
498
+ );
499
+ }
500
+
501
+ const factory = getAddress(config.factoryAddress);
502
+ const escrow = getAddress(config.escrowAddress);
503
+ const asset = getAddress(config.asset);
504
+ const [factoryEscrow, factoryUsdc, predicted] = await Promise.all([
505
+ publicClient.readContract({
506
+ address: factory,
507
+ abi: x402StreamOpenerFactoryAbi,
508
+ functionName: "escrow",
509
+ }),
510
+ publicClient.readContract({
511
+ address: factory,
512
+ abi: x402StreamOpenerFactoryAbi,
513
+ functionName: "usdc",
514
+ }),
515
+ publicClient.readContract({
516
+ address: factory,
517
+ abi: x402StreamOpenerFactoryAbi,
518
+ functionName: "predict",
519
+ args: [termsTuple(config.terms)],
520
+ }),
521
+ ]);
522
+ if (getAddress(factoryEscrow) !== escrow) {
523
+ throw new X402OpenerModeConfigError(
524
+ `factory ${factory} settles into ${factoryEscrow}, not this gateway's escrow ${escrow}`,
525
+ );
526
+ }
527
+ if (getAddress(factoryUsdc) !== asset) {
528
+ throw new X402OpenerModeConfigError(
529
+ `factory token ${factoryUsdc} is not the configured asset ${asset}`,
530
+ );
531
+ }
532
+ const payTo = getAddress(predicted);
533
+
534
+ const resolver =
535
+ deps.listingResolver ??
536
+ new RegistryListingResolver(
537
+ config.registryUrl === undefined
538
+ ? {}
539
+ : { registryUrl: config.registryUrl },
540
+ );
541
+ const listing = await resolver.resolve(config.terms);
542
+ if (!listing.ok) {
543
+ throw new X402OpenerModeConfigError(
544
+ `listing check failed (${listing.reason}): ${listing.message}`,
545
+ );
546
+ }
547
+
548
+ const facilitatorTimeoutMs =
549
+ config.facilitatorTimeoutMs ?? DEFAULT_FACILITATOR_TIMEOUT_MS;
550
+ if (!Number.isInteger(facilitatorTimeoutMs) || facilitatorTimeoutMs <= 0) {
551
+ throw new X402OpenerModeConfigError(
552
+ "facilitatorTimeoutMs must be a positive integer",
553
+ );
554
+ }
555
+ const facilitatorClient =
556
+ deps.facilitatorClient ??
557
+ new HTTPFacilitatorClient({
558
+ url: config.facilitatorUrl,
559
+ timeoutMs: facilitatorTimeoutMs,
560
+ createAuthHeaders: async () => {
561
+ const headers = { Authorization: `Bearer ${config.facilitatorToken}` };
562
+ return { verify: headers, settle: headers, supported: headers };
563
+ },
564
+ });
565
+
566
+ const now = deps.now ?? (() => Math.floor(Date.now() / 1000));
567
+ const markerTtl =
568
+ config.markerTtlSeconds ?? DEFAULT_FACILITATOR_MARKER_TTL_SECONDS;
569
+ let markerCheckedAt: number | undefined;
570
+ const checkMarker = async (): Promise<void> => {
571
+ let supported;
572
+ try {
573
+ supported = await facilitatorClient.getSupported();
574
+ } catch (cause) {
575
+ throw new X402OpenerFacilitatorUnverifiedError(
576
+ `the x402 facilitator at ${config.facilitatorUrl} is unreachable`,
577
+ { cause },
578
+ );
579
+ }
580
+ const kind = supported.kinds.find(
581
+ (candidate) =>
582
+ candidate.x402Version === 2 &&
583
+ candidate.scheme === OPENER_SCHEME &&
584
+ candidate.network === config.network,
585
+ );
586
+ const marker = readOpenerFacilitatorMarker(kind?.extra);
587
+ if (
588
+ marker === undefined ||
589
+ marker.factory !== factory ||
590
+ marker.escrow !== escrow ||
591
+ marker.usdc !== asset ||
592
+ marker.chainId !== chainId
593
+ ) {
594
+ throw new X402OpenerFacilitatorUnverifiedError(
595
+ `the x402 facilitator at ${config.facilitatorUrl} does not advertise Metrik opener settlement for factory ${factory} on ${config.network}. ` +
596
+ "Refusing to quote an opener payTo: a stock exact facilitator would transfer the payment straight to the opener and strand it permanently.",
597
+ );
598
+ }
599
+ if (marker.refundRelay !== true) {
600
+ throw new X402OpenerFacilitatorUnverifiedError(
601
+ `the x402 facilitator at ${config.facilitatorUrl} does not advertise the gasless refund relay (refundRelay: true). ` +
602
+ "Refusing to quote: the 402 tells payers unearned money is refundable without ETH, which needs that relay.",
603
+ );
604
+ }
605
+ if (config.price < BigInt(marker.minAmount)) {
606
+ throw new X402OpenerModeConfigError(
607
+ `price ${config.price} is below the facilitator minimum ${marker.minAmount}`,
608
+ );
609
+ }
610
+ if (
611
+ facilitatorTimeoutMs <
612
+ marker.receiptTimeoutSeconds * 1000 + FACILITATOR_TIMEOUT_HEADROOM_MS
613
+ ) {
614
+ throw new X402OpenerModeConfigError(
615
+ `the facilitator timeout ${facilitatorTimeoutMs}ms does not outlast the facilitator's ${marker.receiptTimeoutSeconds}s receipt wait by ${FACILITATOR_TIMEOUT_HEADROOM_MS / 1000}s`,
616
+ );
617
+ }
618
+ };
619
+
620
+ const resourceServer = new x402ResourceServer(facilitatorClient).register(
621
+ config.network,
622
+ new OpenerExactServerScheme(refundBaseUrl),
623
+ );
624
+ const description = describeOpenerPurchase({
625
+ terms: config.terms,
626
+ price: config.price,
627
+ assetDecimals,
628
+ assetSymbol: config.assetName,
629
+ refundUrlTemplate: `${refundBaseUrl}/streams/{streamId}`,
630
+ docsUrl,
631
+ ...(config.description === undefined
632
+ ? {}
633
+ : { serviceDescription: config.description }),
634
+ });
635
+ const route: RouteConfig = {
636
+ accepts: {
637
+ scheme: OPENER_SCHEME,
638
+ network: config.network,
639
+ payTo,
640
+ price: {
641
+ asset,
642
+ amount: config.price.toString(),
643
+ extra: {
644
+ name: config.assetName,
645
+ version: config.assetVersion,
646
+ assetTransferMethod: "eip3009",
647
+ [OPENER_EXTRA_KEY]: {
648
+ ...termsToExtra(factory, config.terms),
649
+ refundUrl: `${refundBaseUrl}/streams/{streamId}`,
650
+ docsUrl,
651
+ },
652
+ },
653
+ },
654
+ maxTimeoutSeconds,
655
+ },
656
+ description,
657
+ mimeType: "application/json",
658
+ ...(config.schemaDeclaration === undefined
659
+ ? {}
660
+ : { extensions: { bazaar: config.schemaDeclaration } }),
661
+ unpaidResponseBody: () => ({
662
+ contentType: "application/json",
663
+ body: { authorized: false, reason: "payment-required" },
664
+ }),
665
+ };
666
+ const httpServer = new x402HTTPResourceServer(resourceServer, route);
667
+
668
+ let initialized: Promise<void> | undefined;
669
+ const ready = async (): Promise<void> => {
670
+ const nowSeconds = now();
671
+ if (
672
+ markerCheckedAt === undefined ||
673
+ nowSeconds - markerCheckedAt >= markerTtl
674
+ ) {
675
+ markerCheckedAt = undefined;
676
+ await checkMarker();
677
+ markerCheckedAt = nowSeconds;
678
+ }
679
+ if (initialized === undefined) {
680
+ initialized = httpServer.initialize().catch((error: unknown) => {
681
+ initialized = undefined;
682
+ throw new X402OpenerFacilitatorUnverifiedError(
683
+ "the x402 resource server could not initialize against the facilitator",
684
+ { cause: error },
685
+ );
686
+ });
687
+ }
688
+ await initialized;
689
+ };
690
+
691
+ // Prove the facilitator at startup: refuse to start otherwise.
692
+ await ready();
693
+ if (refundBaseUrl !== config.facilitatorUrl.replace(/\/+$/, "")) {
694
+ await checkRefundRelayAt(refundBaseUrl, deps.fetch ?? fetch, {
695
+ factory,
696
+ escrow,
697
+ asset,
698
+ chainId,
699
+ network: config.network,
700
+ });
701
+ }
702
+
703
+ const mode: GatewayX402OpenerMode = {
704
+ payTo,
705
+ network: config.network,
706
+ terms: config.terms,
707
+ price: config.price,
708
+ resourceBaseUrl: config.resourceBaseUrl,
709
+ description,
710
+ refundBaseUrl,
711
+ httpServer,
712
+ authorizations: new GatewayAuthorizationLedger(now),
713
+ ready,
714
+ handle: (io) =>
715
+ handleX402GatewayRequest(mode, io).catch((error: unknown) => {
716
+ io.logError("x402 request failed", error);
717
+ io.writeJson(500, "internal-error");
718
+ }),
719
+ };
720
+ return mode;
721
+ }
722
+
723
+ /**
724
+ * A refund base URL other than the facilitator URL (e.g. the public origin of
725
+ * the same service) must serve the same opener marker with the relay on, so
726
+ * the 402 never points payers at a URL that cannot refund them.
727
+ */
728
+ async function checkRefundRelayAt(
729
+ refundBaseUrl: string,
730
+ fetchImpl: typeof fetch,
731
+ expected: {
732
+ readonly factory: Address;
733
+ readonly escrow: Address;
734
+ readonly asset: Address;
735
+ readonly chainId: number;
736
+ readonly network: Network;
737
+ },
738
+ ): Promise<void> {
739
+ let supported: {
740
+ kinds?: {
741
+ x402Version?: unknown;
742
+ scheme?: unknown;
743
+ network?: unknown;
744
+ extra?: Record<string, unknown>;
745
+ }[];
746
+ };
747
+ try {
748
+ const response = await fetchImpl(`${refundBaseUrl}/supported`, {
749
+ signal: AbortSignal.timeout(10_000),
750
+ });
751
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
752
+ supported = (await response.json()) as typeof supported;
753
+ } catch (cause) {
754
+ throw new X402OpenerFacilitatorUnverifiedError(
755
+ `the refund relay at ${refundBaseUrl} is unreachable`,
756
+ { cause },
757
+ );
758
+ }
759
+ const kind = supported.kinds?.find(
760
+ (candidate) =>
761
+ candidate.x402Version === 2 &&
762
+ candidate.scheme === OPENER_SCHEME &&
763
+ candidate.network === expected.network,
764
+ );
765
+ const marker = readOpenerFacilitatorMarker(kind?.extra);
766
+ if (
767
+ marker === undefined ||
768
+ marker.factory !== expected.factory ||
769
+ marker.escrow !== expected.escrow ||
770
+ marker.usdc !== expected.asset ||
771
+ marker.chainId !== expected.chainId ||
772
+ marker.refundRelay !== true
773
+ ) {
774
+ throw new X402OpenerFacilitatorUnverifiedError(
775
+ `${refundBaseUrl} does not serve the Metrik opener refund relay for factory ${expected.factory}; refusing to advertise it as the refund URL`,
776
+ );
777
+ }
778
+ }
779
+
780
+ /**
781
+ * One x402-mode request, mirroring the reference `@x402/*` middleware: verify
782
+ * via the facilitator, run the upstream, and settle ONLY when the upstream
783
+ * status is < 400 — before any upstream byte is sent. A failed settlement sends
784
+ * no upstream body. Every facilitator error fails closed: never a free call.
785
+ */
786
+ async function handleX402GatewayRequest(
787
+ mode: GatewayX402OpenerMode,
788
+ io: X402GatewayRequestIO,
789
+ ): Promise<void> {
790
+ try {
791
+ await mode.ready();
792
+ } catch (error) {
793
+ // The facilitator is not provably the Metrik opener facilitator right now:
794
+ // quote no payTo and verify nothing (a stock facilitator would strand it).
795
+ io.logError("x402 facilitator unverified", error);
796
+ io.writeJson(503, "x402-facilitator-unavailable");
797
+ return;
798
+ }
799
+
800
+ const { requestUrl, method, headers } = io;
801
+ const origin =
802
+ mode.resourceBaseUrl ?? `http://${headers.host ?? "localhost"}`;
803
+ const fullUrl = new URL(
804
+ requestUrl.pathname + requestUrl.search,
805
+ origin,
806
+ ).toString();
807
+ const adapter: HTTPAdapter = {
808
+ getHeader: (name) => headers[name.toLowerCase()],
809
+ getMethod: () => method,
810
+ getPath: () => requestUrl.pathname,
811
+ getUrl: () => fullUrl,
812
+ getAcceptHeader: () => headers.accept ?? "",
813
+ getUserAgent: () => headers["user-agent"] ?? "",
814
+ };
815
+ const paymentHeader = headers[PAYMENT_SIGNATURE_HEADER]?.trim();
816
+ const context: HTTPRequestContext = {
817
+ adapter,
818
+ path: requestUrl.pathname,
819
+ method,
820
+ ...(paymentHeader === undefined || paymentHeader.length === 0
821
+ ? {}
822
+ : { paymentHeader }),
823
+ };
824
+
825
+ // One authorization, at most one served response: claim it before verify so
826
+ // a concurrent duplicate never reaches the facilitator or the upstream.
827
+ const claim =
828
+ paymentHeader === undefined || paymentHeader.length === 0
829
+ ? undefined
830
+ : authorizationKey(paymentHeader);
831
+ if (
832
+ claim !== undefined &&
833
+ !mode.authorizations.claim(claim.key, claim.validBefore)
834
+ ) {
835
+ io.writeJson(409, "x402-payment-already-used");
836
+ return;
837
+ }
838
+ const release = () => {
839
+ if (claim !== undefined) mode.authorizations.release(claim.key);
840
+ };
841
+
842
+ let result: HTTPProcessResult;
843
+ try {
844
+ result = await mode.httpServer.processHTTPRequest(context);
845
+ } catch (error) {
846
+ release();
847
+ io.logError("x402 verification failed", error);
848
+ io.writeJson(402, "x402-facilitator-unavailable");
849
+ return;
850
+ }
851
+
852
+ if (result.type === "no-payment-required") {
853
+ // The route covers every path; reaching here is a misconfiguration.
854
+ release();
855
+ io.writeJson(500, "internal-error");
856
+ return;
857
+ }
858
+ if (result.type === "payment-error") {
859
+ release();
860
+ writeInstructions(io, result.response);
861
+ return;
862
+ }
863
+
864
+ const {
865
+ cancellationDispatcher,
866
+ beforeHandlerSettlement,
867
+ paymentPayload,
868
+ paymentRequirements,
869
+ declaredExtensions,
870
+ } = result;
871
+
872
+ let upstream: X402UpstreamResult;
873
+ try {
874
+ upstream = await io.callUpstream();
875
+ } catch (error) {
876
+ await cancellationDispatcher
877
+ .cancel({ reason: "handler_threw", error })
878
+ .catch(() => undefined);
879
+ release();
880
+ io.logError("upstream request failed", error);
881
+ io.writeJson(502, "upstream-unavailable");
882
+ return;
883
+ }
884
+
885
+ // The seller's upstream must not steer settlement.
886
+ const upstreamHeaders: Record<string, string> = {};
887
+ for (const [key, value] of Object.entries(upstream.headers)) {
888
+ if (key.toLowerCase() === SETTLEMENT_OVERRIDES_HEADER.toLowerCase())
889
+ continue;
890
+ upstreamHeaders[key] = value;
891
+ }
892
+
893
+ if (upstream.status >= 400) {
894
+ // Nothing is settled for a failed upstream: the authorization is never
895
+ // submitted, so no funds move.
896
+ await cancellationDispatcher
897
+ .cancel({ reason: "handler_failed", responseStatus: upstream.status })
898
+ .catch(() => undefined);
899
+ release();
900
+ io.write(upstream.status, upstreamHeaders, upstream.body);
901
+ return;
902
+ }
903
+
904
+ let settled: ProcessSettleResultResponse;
905
+ try {
906
+ settled = await mode.httpServer.processSettlement(
907
+ paymentPayload,
908
+ paymentRequirements,
909
+ declaredExtensions,
910
+ {
911
+ request: context,
912
+ responseBody: upstream.body,
913
+ responseHeaders: upstreamHeaders,
914
+ },
915
+ undefined,
916
+ beforeHandlerSettlement,
917
+ );
918
+ } catch (error) {
919
+ // Unknown outcome (e.g. the facilitator timed out): let a retry of the same
920
+ // signature through so the facilitator's ledger can reconcile it — that
921
+ // ledger, not this one, guarantees at most one success.
922
+ if (claim !== undefined) {
923
+ mode.authorizations.markPending(claim.key, claim.validBefore);
924
+ }
925
+ io.logError("x402 settlement failed", error);
926
+ io.writeJson(402, "x402-settlement-failed");
927
+ return;
928
+ }
929
+ if (!settled.success) {
930
+ if (claim !== undefined) {
931
+ if (settled.errorReason === "settlement_pending") {
932
+ mode.authorizations.markPending(claim.key, claim.validBefore);
933
+ } else if (settled.errorReason === "duplicate_settlement") {
934
+ mode.authorizations.markSettled(claim.key, claim.validBefore);
935
+ } else {
936
+ release();
937
+ }
938
+ }
939
+ // No upstream body on a failed settlement.
940
+ writeInstructions(io, settled.response);
941
+ return;
942
+ }
943
+ if (claim !== undefined) {
944
+ mode.authorizations.markSettled(claim.key, claim.validBefore);
945
+ }
946
+
947
+ const responseHeaders: Record<string, string> = {};
948
+ let existingCacheControl: string | null = null;
949
+ for (const [key, value] of Object.entries(upstreamHeaders)) {
950
+ if (key.toLowerCase() === "cache-control") {
951
+ existingCacheControl = value;
952
+ continue;
953
+ }
954
+ responseHeaders[key] = value;
955
+ }
956
+ Object.assign(responseHeaders, settled.headers);
957
+ responseHeaders["Cache-Control"] =
958
+ withPrivateCacheControl(existingCacheControl);
959
+ io.write(upstream.status, responseHeaders, upstream.body);
960
+ }
961
+
962
+ function writeInstructions(
963
+ io: X402GatewayRequestIO,
964
+ response: HTTPResponseInstructions,
965
+ ): void {
966
+ const headers: Record<string, string> = { ...response.headers };
967
+ if (response.isHtml === true) {
968
+ headers["Content-Type"] = "text/html; charset=utf-8";
969
+ io.write(response.status, headers, String(response.body ?? ""));
970
+ return;
971
+ }
972
+ headers["Content-Type"] = "application/json";
973
+ io.write(response.status, headers, JSON.stringify(response.body ?? {}));
974
+ }