omnicell-router 0.3.1 → 0.8.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 (1077) hide show
  1. package/README.md +70 -10
  2. package/README.zh-CN.md +57 -8
  3. package/RELEASING.md +6 -0
  4. package/RELEASING.zh-CN.md +5 -0
  5. package/backend/dist/auth/api-keys.d.ts +14 -2
  6. package/backend/dist/auth/api-keys.js +26 -14
  7. package/backend/dist/auth/model-access.d.ts +27 -10
  8. package/backend/dist/auth/model-access.js +34 -17
  9. package/backend/dist/capture/migrate/engine.d.ts +38 -0
  10. package/backend/dist/capture/migrate/engine.js +307 -0
  11. package/backend/dist/capture/migrate/index.d.ts +18 -0
  12. package/backend/dist/capture/migrate/index.js +18 -0
  13. package/backend/dist/capture/migrate/migrator.d.ts +113 -0
  14. package/backend/dist/capture/migrate/migrator.js +16 -0
  15. package/backend/dist/capture/migrate/registry.d.ts +16 -0
  16. package/backend/dist/capture/migrate/registry.js +19 -0
  17. package/backend/dist/capture/migrate/steps/v1-to-v2.d.ts +86 -0
  18. package/backend/dist/capture/migrate/steps/v1-to-v2.js +396 -0
  19. package/backend/dist/capture/recorder.d.ts +422 -272
  20. package/backend/dist/capture/recorder.js +873 -417
  21. package/backend/dist/capture/turn-boundary.d.ts +17 -0
  22. package/backend/dist/capture/turn-boundary.js +31 -0
  23. package/backend/dist/cli/clients/base.d.ts +172 -26
  24. package/backend/dist/cli/clients/base.js +150 -4
  25. package/backend/dist/cli/clients/claude.d.ts +2 -1
  26. package/backend/dist/cli/clients/claude.js +4 -3
  27. package/backend/dist/cli/clients/codex.d.ts +2 -1
  28. package/backend/dist/cli/clients/codex.js +4 -3
  29. package/backend/dist/cli/clients/core-adapters.d.ts +24 -0
  30. package/backend/dist/cli/clients/core-adapters.js +43 -0
  31. package/backend/dist/cli/clients/cursor-proxy.d.ts +88 -0
  32. package/backend/dist/cli/clients/cursor-proxy.js +421 -0
  33. package/backend/dist/cli/clients/dsh.d.ts +4 -2
  34. package/backend/dist/cli/clients/dsh.js +29 -18
  35. package/backend/dist/cli/clients/grok.d.ts +53 -0
  36. package/backend/dist/cli/clients/grok.js +249 -0
  37. package/backend/dist/cli/clients/index.d.ts +35 -19
  38. package/backend/dist/cli/clients/index.js +196 -72
  39. package/backend/dist/cli/clients/kimi.d.ts +75 -0
  40. package/backend/dist/cli/clients/kimi.js +316 -0
  41. package/backend/dist/cli/clients/launcher.d.ts +56 -0
  42. package/backend/dist/cli/clients/launcher.js +41 -0
  43. package/backend/dist/cli/clients/model-meta.js +1 -1
  44. package/backend/dist/cli/clients/omp.d.ts +9 -19
  45. package/backend/dist/cli/clients/omp.js +28 -155
  46. package/backend/dist/cli/clients/openclaw.d.ts +55 -0
  47. package/backend/dist/cli/clients/openclaw.js +525 -0
  48. package/backend/dist/cli/clients/opencode-proxy.d.ts +5 -10
  49. package/backend/dist/cli/clients/opencode-proxy.js +37 -58
  50. package/backend/dist/cli/clients/opencode.d.ts +6 -19
  51. package/backend/dist/cli/clients/opencode.js +32 -159
  52. package/backend/dist/cli/clients/pi.d.ts +6 -20
  53. package/backend/dist/cli/clients/pi.js +32 -221
  54. package/backend/dist/cli/clients/plugin-adapters.d.ts +22 -0
  55. package/backend/dist/cli/clients/plugin-adapters.js +65 -0
  56. package/backend/dist/cli/clients/qoder-proxy.d.ts +84 -0
  57. package/backend/dist/cli/clients/qoder-proxy.js +497 -0
  58. package/backend/dist/cli/clients/reserved.d.ts +47 -0
  59. package/backend/dist/cli/clients/reserved.js +55 -0
  60. package/backend/dist/cli/clients/workbuddy.d.ts +31 -0
  61. package/backend/dist/cli/clients/workbuddy.js +259 -0
  62. package/backend/dist/cli/daemon.d.ts +105 -27
  63. package/backend/dist/cli/daemon.js +509 -151
  64. package/backend/dist/cli/index.d.ts +6 -1
  65. package/backend/dist/cli/index.js +289 -22
  66. package/backend/dist/cli/paths.d.ts +86 -0
  67. package/backend/dist/cli/paths.js +269 -0
  68. package/backend/dist/cli/shim.d.ts +47 -1
  69. package/backend/dist/cli/shim.js +180 -13
  70. package/backend/dist/cli/types.d.ts +114 -16
  71. package/backend/dist/cli/types.js +5 -4
  72. package/backend/dist/compression/caveman.d.ts +2 -16
  73. package/backend/dist/compression/caveman.js +25 -37
  74. package/backend/dist/compression/headroom.d.ts +4 -3
  75. package/backend/dist/compression/headroom.js +2 -2
  76. package/backend/dist/compression/index.d.ts +5 -26
  77. package/backend/dist/compression/index.js +79 -17
  78. package/backend/dist/compression/tool-output.d.ts +2 -20
  79. package/backend/dist/compression/tool-output.js +40 -47
  80. package/backend/dist/config/comments-en.d.ts +17 -0
  81. package/backend/dist/config/comments-en.js +226 -0
  82. package/backend/dist/config/comments-zh.d.ts +10 -0
  83. package/backend/dist/config/comments-zh.js +211 -0
  84. package/backend/dist/config/defaults.d.ts +245 -2
  85. package/backend/dist/config/defaults.js +259 -2
  86. package/backend/dist/config/env-archive.js +77 -38
  87. package/backend/dist/config/env.d.ts +4 -0
  88. package/backend/dist/config/env.js +16 -0
  89. package/backend/dist/config/index.d.ts +55 -12
  90. package/backend/dist/config/index.js +817 -368
  91. package/backend/dist/config/layout.d.ts +29 -0
  92. package/backend/dist/config/layout.js +86 -0
  93. package/backend/dist/config/migrations/v0-to-v1.d.ts +105 -0
  94. package/backend/dist/config/migrations/v0-to-v1.js +78 -0
  95. package/backend/dist/config/migrations/v1-to-v2.d.ts +14 -0
  96. package/backend/dist/config/migrations/v1-to-v2.js +41 -0
  97. package/backend/dist/config/migrations/v2-to-v3.d.ts +34 -0
  98. package/backend/dist/config/migrations/v2-to-v3.js +66 -0
  99. package/backend/dist/config/migrations/v3-to-v4.d.ts +34 -0
  100. package/backend/dist/config/migrations/v3-to-v4.js +61 -0
  101. package/backend/dist/config/runtime.d.ts +13 -0
  102. package/backend/dist/config/runtime.js +26 -0
  103. package/backend/dist/config/schema.d.ts +28 -0
  104. package/backend/dist/config/schema.js +98 -0
  105. package/backend/dist/config/types.d.ts +540 -121
  106. package/backend/dist/forward-proxy/access-log.d.ts +173 -0
  107. package/backend/dist/forward-proxy/access-log.js +657 -0
  108. package/backend/dist/forward-proxy/ca-trust.d.ts +42 -0
  109. package/backend/dist/forward-proxy/ca-trust.js +242 -0
  110. package/backend/dist/forward-proxy/ca.d.ts +66 -2
  111. package/backend/dist/forward-proxy/ca.js +146 -11
  112. package/backend/dist/forward-proxy/caller-context.d.ts +18 -0
  113. package/backend/dist/forward-proxy/caller-context.js +20 -0
  114. package/backend/dist/forward-proxy/egress.d.ts +112 -0
  115. package/backend/dist/forward-proxy/egress.js +318 -0
  116. package/backend/dist/forward-proxy/h2-forward.d.ts +66 -0
  117. package/backend/dist/forward-proxy/h2-forward.js +526 -0
  118. package/backend/dist/forward-proxy/index.d.ts +13 -1
  119. package/backend/dist/forward-proxy/index.js +148 -7
  120. package/backend/dist/forward-proxy/interceptor.d.ts +16 -13
  121. package/backend/dist/forward-proxy/interceptor.js +35 -57
  122. package/backend/dist/forward-proxy/ordered-relay.d.ts +29 -0
  123. package/backend/dist/forward-proxy/ordered-relay.js +46 -0
  124. package/backend/dist/forward-proxy/relay.d.ts +21 -1
  125. package/backend/dist/forward-proxy/relay.js +48 -1
  126. package/backend/dist/forward-proxy/rules.d.ts +195 -0
  127. package/backend/dist/forward-proxy/rules.js +327 -0
  128. package/backend/dist/forward-proxy/server.d.ts +102 -9
  129. package/backend/dist/forward-proxy/server.js +1504 -350
  130. package/backend/dist/forward-proxy/sni.d.ts +29 -7
  131. package/backend/dist/forward-proxy/sni.js +109 -47
  132. package/backend/dist/forward-proxy/system-proxy.d.ts +112 -0
  133. package/backend/dist/forward-proxy/system-proxy.js +480 -0
  134. package/backend/dist/forward-proxy/upstream-tls.d.ts +46 -0
  135. package/backend/dist/forward-proxy/upstream-tls.js +105 -0
  136. package/backend/dist/forward-proxy/ws-frames.d.ts +45 -0
  137. package/backend/dist/forward-proxy/ws-frames.js +153 -0
  138. package/backend/dist/harness/common/catalog-registry.d.ts +63 -0
  139. package/backend/dist/harness/common/catalog-registry.js +77 -0
  140. package/backend/dist/harness/common/github.d.ts +6 -0
  141. package/backend/dist/harness/common/github.js +13 -0
  142. package/backend/dist/harness/common/market.d.ts +590 -0
  143. package/backend/dist/harness/common/market.js +1079 -0
  144. package/backend/dist/harness/common/marketplace-rescan-scheduler.d.ts +24 -0
  145. package/backend/dist/harness/common/marketplace-rescan-scheduler.js +62 -0
  146. package/backend/dist/harness/{catalog-npm.d.ts → common/npm-catalog.d.ts} +5 -5
  147. package/backend/dist/harness/{catalog-npm.js → common/npm-catalog.js} +7 -7
  148. package/backend/dist/harness/common/npm-source.d.ts +29 -0
  149. package/backend/dist/harness/common/npm-source.js +121 -0
  150. package/backend/dist/harness/common/pypi-source.d.ts +28 -0
  151. package/backend/dist/harness/common/pypi-source.js +71 -0
  152. package/backend/dist/harness/common/source-views.d.ts +22 -0
  153. package/backend/dist/harness/common/source-views.js +25 -0
  154. package/backend/dist/harness/{stars.d.ts → common/stars.d.ts} +1 -1
  155. package/backend/dist/harness/{stars.js → common/stars.js} +2 -2
  156. package/backend/dist/harness/common/text.d.ts +11 -0
  157. package/backend/dist/harness/common/text.js +18 -0
  158. package/backend/dist/harness/config-file.d.ts +14 -1
  159. package/backend/dist/harness/config-file.js +38 -0
  160. package/backend/dist/harness/db-probe.d.ts +29 -0
  161. package/backend/dist/harness/db-probe.js +270 -0
  162. package/backend/dist/harness/detail.d.ts +10 -1
  163. package/backend/dist/harness/detail.js +144 -7
  164. package/backend/dist/harness/host/adapters/amp.d.ts +19 -0
  165. package/backend/dist/harness/host/adapters/amp.js +21 -0
  166. package/backend/dist/harness/host/adapters/antigravity.d.ts +18 -0
  167. package/backend/dist/harness/host/adapters/antigravity.js +21 -0
  168. package/backend/dist/harness/host/adapters/base.d.ts +225 -0
  169. package/backend/dist/harness/host/adapters/base.js +521 -0
  170. package/backend/dist/harness/host/adapters/claude.d.ts +54 -0
  171. package/backend/dist/harness/host/adapters/claude.js +145 -0
  172. package/backend/dist/harness/host/adapters/cline.d.ts +18 -0
  173. package/backend/dist/harness/host/adapters/cline.js +20 -0
  174. package/backend/dist/harness/host/adapters/codex.d.ts +54 -0
  175. package/backend/dist/harness/host/adapters/codex.js +133 -0
  176. package/backend/dist/harness/host/adapters/cursor.d.ts +18 -0
  177. package/backend/dist/harness/host/adapters/cursor.js +24 -0
  178. package/backend/dist/harness/host/adapters/declarative.d.ts +22 -0
  179. package/backend/dist/harness/host/adapters/declarative.js +38 -0
  180. package/backend/dist/harness/host/adapters/dsh.d.ts +76 -0
  181. package/backend/dist/harness/host/adapters/dsh.js +253 -0
  182. package/backend/dist/harness/host/adapters/factory.d.ts +36 -0
  183. package/backend/dist/harness/host/adapters/factory.js +34 -0
  184. package/backend/dist/harness/host/adapters/gemini-cli.d.ts +17 -0
  185. package/backend/dist/harness/host/adapters/gemini-cli.js +19 -0
  186. package/backend/dist/harness/host/adapters/grok.d.ts +66 -0
  187. package/backend/dist/harness/host/adapters/grok.js +136 -0
  188. package/backend/dist/harness/{adapters → host/adapters}/index.d.ts +9 -4
  189. package/backend/dist/harness/{adapters → host/adapters}/index.js +31 -10
  190. package/backend/dist/harness/host/adapters/kimi.d.ts +30 -0
  191. package/backend/dist/harness/host/adapters/kimi.js +59 -0
  192. package/backend/dist/harness/host/adapters/omp.d.ts +55 -0
  193. package/backend/dist/harness/host/adapters/omp.js +90 -0
  194. package/backend/dist/harness/host/adapters/openclaw.d.ts +54 -0
  195. package/backend/dist/harness/host/adapters/openclaw.js +141 -0
  196. package/backend/dist/harness/host/adapters/opencode.d.ts +24 -0
  197. package/backend/dist/harness/host/adapters/opencode.js +48 -0
  198. package/backend/dist/harness/host/adapters/pi.d.ts +27 -0
  199. package/backend/dist/harness/host/adapters/pi.js +58 -0
  200. package/backend/dist/harness/host/adapters/types.d.ts +395 -0
  201. package/backend/dist/harness/host/adapters/types.js +17 -0
  202. package/backend/dist/harness/host/adapters/universal.d.ts +14 -0
  203. package/backend/dist/harness/host/adapters/universal.js +18 -0
  204. package/backend/dist/harness/host/adapters/windsurf.d.ts +20 -0
  205. package/backend/dist/harness/host/adapters/windsurf.js +22 -0
  206. package/backend/dist/harness/host/adapters/zed.d.ts +12 -0
  207. package/backend/dist/harness/host/adapters/zed.js +14 -0
  208. package/backend/dist/harness/host/claude-mcp-runtime.d.ts +6 -0
  209. package/backend/dist/harness/host/claude-mcp-runtime.js +56 -0
  210. package/backend/dist/harness/{discover.d.ts → host/discover.d.ts} +54 -18
  211. package/backend/dist/harness/{discover.js → host/discover.js} +314 -53
  212. package/backend/dist/harness/{drift.d.ts → host/drift.d.ts} +1 -1
  213. package/backend/dist/harness/{drift.js → host/drift.js} +1 -1
  214. package/backend/dist/harness/host/grok-mcp-runtime.d.ts +6 -0
  215. package/backend/dist/harness/host/grok-mcp-runtime.js +56 -0
  216. package/backend/dist/harness/{hosts.d.ts → host/hosts.d.ts} +3 -3
  217. package/backend/dist/harness/{hosts.js → host/hosts.js} +7 -3
  218. package/backend/dist/harness/host/index.d.ts +10 -0
  219. package/backend/dist/harness/host/index.js +12 -0
  220. package/backend/dist/harness/host/install-log.d.ts +22 -0
  221. package/backend/dist/harness/host/install-log.js +106 -0
  222. package/backend/dist/harness/{install.d.ts → host/install.d.ts} +32 -13
  223. package/backend/dist/harness/{install.js → host/install.js} +133 -50
  224. package/backend/dist/harness/host/inventory.d.ts +30 -0
  225. package/backend/dist/harness/{inventory.js → host/inventory.js} +107 -16
  226. package/backend/dist/harness/host/kimi-mcp-runtime.d.ts +6 -0
  227. package/backend/dist/harness/host/kimi-mcp-runtime.js +84 -0
  228. package/backend/dist/harness/{ledger.d.ts → host/ledger.d.ts} +1 -1
  229. package/backend/dist/harness/{ledger.js → host/ledger.js} +3 -3
  230. package/backend/dist/harness/{maintenance.d.ts → host/maintenance.d.ts} +23 -6
  231. package/backend/dist/harness/{maintenance.js → host/maintenance.js} +355 -63
  232. package/backend/dist/harness/{manifest.d.ts → host/manifest.d.ts} +11 -2
  233. package/backend/dist/harness/{manifest.js → host/manifest.js} +76 -15
  234. package/backend/dist/harness/host/marketplace-sync.d.ts +64 -0
  235. package/backend/dist/harness/host/marketplace-sync.js +231 -0
  236. package/backend/dist/harness/host/mcp-cli.d.ts +44 -0
  237. package/backend/dist/harness/host/mcp-cli.js +545 -0
  238. package/backend/dist/harness/host/mcp-edit.d.ts +89 -0
  239. package/backend/dist/harness/host/mcp-edit.js +342 -0
  240. package/backend/dist/harness/host/mcp-entry.d.ts +100 -0
  241. package/backend/dist/harness/host/mcp-entry.js +435 -0
  242. package/backend/dist/harness/host/mcp-inspector.d.ts +125 -0
  243. package/backend/dist/harness/host/mcp-inspector.js +634 -0
  244. package/backend/dist/harness/host/mcp-registry.d.ts +66 -0
  245. package/backend/dist/harness/host/mcp-registry.js +331 -0
  246. package/backend/dist/harness/host/mcp-runtime.d.ts +19 -0
  247. package/backend/dist/harness/host/mcp-runtime.js +22 -0
  248. package/backend/dist/harness/host/opencode-mcp-runtime.d.ts +7 -0
  249. package/backend/dist/harness/host/opencode-mcp-runtime.js +73 -0
  250. package/backend/dist/harness/{probe.d.ts → host/probe.d.ts} +4 -4
  251. package/backend/dist/harness/{probe.js → host/probe.js} +8 -8
  252. package/backend/dist/harness/{registry.d.ts → host/registry.d.ts} +1 -1
  253. package/backend/dist/harness/host/registry.js +28 -0
  254. package/backend/dist/harness/host/request.d.ts +56 -0
  255. package/backend/dist/harness/host/request.js +1 -0
  256. package/backend/dist/harness/{sources → host/resolvers}/clawhub.d.ts +1 -1
  257. package/backend/dist/harness/{sources → host/resolvers}/clawhub.js +1 -1
  258. package/backend/dist/harness/host/resolvers/git-marketplace.d.ts +16 -0
  259. package/backend/dist/harness/host/resolvers/git-marketplace.js +53 -0
  260. package/backend/dist/harness/{sources → host/resolvers}/github.d.ts +1 -1
  261. package/backend/dist/harness/{sources → host/resolvers}/github.js +2 -2
  262. package/backend/dist/harness/host/resolvers/npm.d.ts +2 -0
  263. package/backend/dist/harness/{sources → host/resolvers}/npm.js +16 -10
  264. package/backend/dist/harness/host/resolvers/pypi.d.ts +2 -0
  265. package/backend/dist/harness/host/resolvers/pypi.js +100 -0
  266. package/backend/dist/harness/host/scopes.d.ts +11 -0
  267. package/backend/dist/harness/host/scopes.js +12 -0
  268. package/backend/dist/harness/host/timeouts.d.ts +8 -0
  269. package/backend/dist/harness/host/timeouts.js +8 -0
  270. package/backend/dist/harness/host/writers/kimi-web.d.ts +70 -0
  271. package/backend/dist/harness/host/writers/kimi-web.js +222 -0
  272. package/backend/dist/harness/host/writers/mcp.d.ts +119 -0
  273. package/backend/dist/harness/host/writers/mcp.js +359 -0
  274. package/backend/dist/harness/host/writers/plugin.d.ts +176 -0
  275. package/backend/dist/harness/host/writers/plugin.js +528 -0
  276. package/backend/dist/harness/{writers → host/writers}/skill.d.ts +3 -3
  277. package/backend/dist/harness/{writers → host/writers}/skill.js +6 -3
  278. package/backend/dist/harness/lang.d.ts +14 -0
  279. package/backend/dist/harness/lang.js +33 -0
  280. package/backend/dist/harness/net.d.ts +33 -0
  281. package/backend/dist/harness/net.js +63 -0
  282. package/backend/dist/harness/plugin/adapters/antigravity.d.ts +11 -0
  283. package/backend/dist/harness/plugin/adapters/antigravity.js +14 -0
  284. package/backend/dist/harness/plugin/adapters/base.d.ts +107 -0
  285. package/backend/dist/harness/plugin/adapters/base.js +454 -0
  286. package/backend/dist/harness/plugin/adapters/claude.d.ts +28 -0
  287. package/backend/dist/harness/plugin/adapters/claude.js +63 -0
  288. package/backend/dist/harness/plugin/adapters/codex.d.ts +13 -0
  289. package/backend/dist/harness/plugin/adapters/codex.js +16 -0
  290. package/backend/dist/harness/plugin/adapters/cursor.d.ts +13 -0
  291. package/backend/dist/harness/plugin/adapters/cursor.js +16 -0
  292. package/backend/dist/harness/plugin/adapters/dsh-plugin-net.d.ts +20 -0
  293. package/backend/dist/harness/plugin/adapters/dsh-plugin-net.js +371 -0
  294. package/backend/dist/harness/plugin/adapters/dsh.d.ts +22 -0
  295. package/backend/dist/harness/plugin/adapters/dsh.js +50 -0
  296. package/backend/dist/harness/plugin/adapters/factory.d.ts +11 -0
  297. package/backend/dist/harness/plugin/adapters/factory.js +19 -0
  298. package/backend/dist/harness/plugin/adapters/gemini.d.ts +12 -0
  299. package/backend/dist/harness/plugin/adapters/gemini.js +22 -0
  300. package/backend/dist/harness/plugin/adapters/grok.d.ts +15 -0
  301. package/backend/dist/harness/plugin/adapters/grok.js +23 -0
  302. package/backend/dist/harness/plugin/adapters/index.d.ts +41 -0
  303. package/backend/dist/harness/plugin/adapters/index.js +143 -0
  304. package/backend/dist/harness/plugin/adapters/kimi.d.ts +6 -0
  305. package/backend/dist/harness/plugin/adapters/kimi.js +35 -0
  306. package/backend/dist/harness/plugin/adapters/omp.d.ts +19 -0
  307. package/backend/dist/harness/plugin/adapters/omp.js +26 -0
  308. package/backend/dist/harness/plugin/adapters/openclaw.d.ts +20 -0
  309. package/backend/dist/harness/plugin/adapters/openclaw.js +36 -0
  310. package/backend/dist/harness/plugin/adapters/pi-dev.d.ts +124 -0
  311. package/backend/dist/harness/plugin/adapters/pi-dev.js +420 -0
  312. package/backend/dist/harness/plugin/adapters/pi-github.d.ts +18 -0
  313. package/backend/dist/harness/plugin/adapters/pi-github.js +27 -0
  314. package/backend/dist/harness/plugin/adapters/universal.d.ts +11 -0
  315. package/backend/dist/harness/plugin/adapters/universal.js +18 -0
  316. package/backend/dist/harness/plugin/builtin.d.ts +13 -0
  317. package/backend/dist/harness/plugin/builtin.js +34 -0
  318. package/backend/dist/harness/plugin/catalog.d.ts +30 -0
  319. package/backend/dist/harness/plugin/catalog.js +200 -0
  320. package/backend/dist/harness/plugin/index.d.ts +9 -0
  321. package/backend/dist/harness/plugin/index.js +9 -0
  322. package/backend/dist/harness/plugin/types.d.ts +164 -0
  323. package/backend/dist/harness/plugin/types.js +1 -0
  324. package/backend/dist/harness/{clawhub.d.ts → skill/clawhub.d.ts} +28 -5
  325. package/backend/dist/harness/{clawhub.js → skill/clawhub.js} +170 -5
  326. package/backend/dist/harness/skill/skills-sh.d.ts +47 -0
  327. package/backend/dist/harness/skill/skills-sh.js +270 -0
  328. package/backend/dist/harness/skill/sources.d.ts +41 -0
  329. package/backend/dist/harness/skill/sources.js +131 -0
  330. package/backend/dist/harness/spi.d.ts +11 -7
  331. package/backend/dist/harness/tcp-reach.d.ts +30 -0
  332. package/backend/dist/harness/tcp-reach.js +61 -0
  333. package/backend/dist/harness/translation.d.ts +31 -13
  334. package/backend/dist/harness/translation.js +265 -80
  335. package/backend/dist/harness/types.d.ts +62 -17
  336. package/backend/dist/harness/types.js +1 -1
  337. package/backend/dist/index.js +183 -16
  338. package/backend/dist/ir/adapters/anthropic-messages-stream.d.ts +18 -0
  339. package/backend/dist/ir/adapters/anthropic-messages-stream.js +266 -0
  340. package/backend/dist/ir/adapters/anthropic-messages.d.ts +30 -0
  341. package/backend/dist/ir/adapters/anthropic-messages.js +870 -0
  342. package/backend/dist/ir/adapters/anthropic-stream.d.ts +18 -0
  343. package/backend/dist/ir/adapters/anthropic-stream.js +247 -0
  344. package/backend/dist/ir/adapters/anthropic.d.ts +29 -0
  345. package/backend/dist/ir/adapters/anthropic.js +788 -0
  346. package/backend/dist/ir/adapters/chat.d.ts +15 -0
  347. package/backend/dist/ir/adapters/chat.js +602 -0
  348. package/backend/dist/ir/adapters/google-gemini-stream.d.ts +22 -0
  349. package/backend/dist/ir/adapters/google-gemini-stream.js +246 -0
  350. package/backend/dist/ir/adapters/google-gemini.d.ts +9 -0
  351. package/backend/dist/ir/adapters/google-gemini.js +450 -0
  352. package/backend/dist/ir/adapters/google-stream.d.ts +22 -0
  353. package/backend/dist/ir/adapters/google-stream.js +242 -0
  354. package/backend/dist/ir/adapters/google.d.ts +9 -0
  355. package/backend/dist/ir/adapters/google.js +317 -0
  356. package/backend/dist/ir/adapters/openai-chat-stream.d.ts +41 -0
  357. package/backend/dist/ir/adapters/openai-chat-stream.js +369 -0
  358. package/backend/dist/ir/adapters/openai-chat.d.ts +17 -0
  359. package/backend/dist/ir/adapters/openai-chat.js +670 -0
  360. package/backend/dist/ir/adapters/openai-responses-output.d.ts +50 -0
  361. package/backend/dist/ir/adapters/openai-responses-output.js +356 -0
  362. package/backend/dist/ir/adapters/openai-responses-stream.d.ts +12 -0
  363. package/backend/dist/ir/adapters/openai-responses-stream.js +193 -0
  364. package/backend/dist/ir/adapters/openai-responses.d.ts +29 -0
  365. package/backend/dist/ir/adapters/openai-responses.js +695 -0
  366. package/backend/dist/ir/adapters/responses-output.d.ts +50 -0
  367. package/backend/dist/ir/adapters/responses-output.js +348 -0
  368. package/backend/dist/ir/adapters/responses-stream.d.ts +12 -0
  369. package/backend/dist/ir/adapters/responses-stream.js +178 -0
  370. package/backend/dist/ir/adapters/responses.d.ts +14 -0
  371. package/backend/dist/ir/adapters/responses.js +646 -0
  372. package/backend/dist/ir/capabilities.d.ts +41 -0
  373. package/backend/dist/ir/capabilities.js +147 -0
  374. package/backend/dist/ir/errors.d.ts +23 -0
  375. package/backend/dist/ir/errors.js +31 -0
  376. package/backend/dist/ir/index.d.ts +5 -0
  377. package/backend/dist/ir/index.js +5 -0
  378. package/backend/dist/ir/media.d.ts +2 -0
  379. package/backend/dist/ir/media.js +2 -0
  380. package/backend/dist/ir/stream.d.ts +17 -0
  381. package/backend/dist/ir/stream.js +250 -0
  382. package/backend/dist/ir/types.d.ts +524 -0
  383. package/backend/dist/ir/types.js +19 -0
  384. package/backend/dist/ir/validate.d.ts +18 -0
  385. package/backend/dist/ir/validate.js +272 -0
  386. package/backend/dist/metrics/request-cost.d.ts +11 -10
  387. package/backend/dist/metrics/request-cost.js +18 -27
  388. package/backend/dist/observability/failure-events.d.ts +20 -4
  389. package/backend/dist/observability/failure-events.js +9 -1
  390. package/backend/dist/observability/http-exchange.d.ts +75 -27
  391. package/backend/dist/observability/http-exchange.js +136 -39
  392. package/backend/dist/observability/request-identity.d.ts +40 -0
  393. package/backend/dist/observability/request-identity.js +102 -0
  394. package/backend/dist/observability/traffic-live-hidden.d.ts +24 -0
  395. package/backend/dist/observability/traffic-live-hidden.js +82 -0
  396. package/backend/dist/observability/upstream-body-redaction.d.ts +23 -0
  397. package/backend/dist/observability/upstream-body-redaction.js +72 -0
  398. package/backend/dist/observability/upstream-events.d.ts +90 -62
  399. package/backend/dist/observability/upstream-events.js +145 -64
  400. package/backend/dist/opencode/agents.d.ts +3 -2
  401. package/backend/dist/opencode/catalog/auto-pull.d.ts +35 -1
  402. package/backend/dist/opencode/catalog/auto-pull.js +169 -33
  403. package/backend/dist/opencode/catalog/ocr-store.d.ts +6 -6
  404. package/backend/dist/opencode/catalog/ocr-store.js +2 -2
  405. package/backend/dist/opencode/catalog/overrides-store.d.ts +6 -5
  406. package/backend/dist/opencode/catalog/overrides-store.js +28 -3
  407. package/backend/dist/opencode/catalog/repository.d.ts +4 -0
  408. package/backend/dist/opencode/catalog/repository.js +19 -0
  409. package/backend/dist/opencode/catalog/sources/models-dev.d.ts +4 -0
  410. package/backend/dist/opencode/catalog/sources/models-dev.js +15 -4
  411. package/backend/dist/opencode/catalog/types.d.ts +19 -7
  412. package/backend/dist/opencode/connector.d.ts +2 -2
  413. package/backend/dist/opencode/connector.js +2 -2
  414. package/backend/dist/opencode/credentials/def-materialize.d.ts +0 -5
  415. package/backend/dist/opencode/credentials/def-materialize.js +149 -11
  416. package/backend/dist/opencode/credentials/ocr-store.d.ts +18 -0
  417. package/backend/dist/opencode/credentials/ocr-store.js +88 -7
  418. package/backend/dist/opencode/credentials/opencode-v2-store.d.ts +24 -13
  419. package/backend/dist/opencode/credentials/opencode-v2-store.js +70 -29
  420. package/backend/dist/opencode/credentials/paths.d.ts +8 -0
  421. package/backend/dist/opencode/credentials/paths.js +10 -0
  422. package/backend/dist/opencode/credentials/sync.d.ts +1 -1
  423. package/backend/dist/opencode/credentials/sync.js +4 -4
  424. package/backend/dist/opencode/credentials/types.d.ts +38 -2
  425. package/backend/dist/opencode/probe.d.ts +33 -6
  426. package/backend/dist/opencode/probe.js +96 -19
  427. package/backend/dist/opencode/provider-defs.js +59 -2
  428. package/backend/dist/opencode/provider-package.d.ts +31 -0
  429. package/backend/dist/opencode/provider-package.js +70 -0
  430. package/backend/dist/opencode/user-config.d.ts +16 -17
  431. package/backend/dist/opencode/user-config.js +42 -66
  432. package/backend/dist/pipeline/credential-selection.d.ts +13 -0
  433. package/backend/dist/pipeline/credential-selection.js +29 -1
  434. package/backend/dist/pipeline/directives.d.ts +18 -22
  435. package/backend/dist/pipeline/directives.js +129 -71
  436. package/backend/dist/pipeline/orchestrator.d.ts +70 -34
  437. package/backend/dist/pipeline/orchestrator.js +901 -405
  438. package/backend/dist/pipeline/prompt-optimizer.d.ts +6 -13
  439. package/backend/dist/pipeline/prompt-optimizer.js +9 -52
  440. package/backend/dist/pipeline/streaming-posture.d.ts +29 -0
  441. package/backend/dist/pipeline/streaming-posture.js +27 -0
  442. package/backend/dist/pipeline/tool-pairing.d.ts +10 -0
  443. package/backend/dist/pipeline/tool-pairing.js +90 -0
  444. package/backend/dist/pipeline/unresolved-model.d.ts +33 -0
  445. package/backend/dist/pipeline/unresolved-model.js +43 -0
  446. package/backend/dist/plugins/builtin/model-gateway.d.ts +30 -0
  447. package/backend/dist/plugins/builtin/model-gateway.js +98 -0
  448. package/backend/dist/plugins/catalog-def.d.ts +143 -0
  449. package/backend/dist/plugins/catalog-def.js +177 -0
  450. package/backend/dist/plugins/config.d.ts +41 -0
  451. package/backend/dist/plugins/config.js +113 -0
  452. package/backend/dist/plugins/gateways.d.ts +157 -0
  453. package/backend/dist/plugins/gateways.js +288 -0
  454. package/backend/dist/plugins/host.d.ts +240 -0
  455. package/backend/dist/plugins/host.js +1726 -0
  456. package/backend/dist/plugins/manifest.d.ts +152 -0
  457. package/backend/dist/plugins/manifest.js +713 -0
  458. package/backend/dist/plugins/pack.d.ts +32 -0
  459. package/backend/dist/plugins/pack.js +248 -0
  460. package/backend/dist/plugins/seed.d.ts +53 -0
  461. package/backend/dist/plugins/seed.js +136 -0
  462. package/backend/dist/plugins/types.d.ts +887 -0
  463. package/backend/dist/plugins/types.js +1 -0
  464. package/backend/dist/projects/store.d.ts +56 -0
  465. package/backend/dist/projects/store.js +194 -0
  466. package/backend/dist/projects/types.d.ts +12 -0
  467. package/backend/dist/projects/types.js +1 -0
  468. package/backend/dist/protocols/chat-compat.d.ts +2 -0
  469. package/backend/dist/protocols/chat-compat.js +137 -0
  470. package/backend/dist/protocols/systemone/convert.d.ts +6 -4
  471. package/backend/dist/protocols/systemone/convert.js +78 -27
  472. package/backend/dist/protocols/systemone/decide.js +144 -57
  473. package/backend/dist/protocols/systemone/native.d.ts +1 -1
  474. package/backend/dist/protocols/systemone/native.js +6 -6
  475. package/backend/dist/providers/anthropic-messages.d.ts +12 -0
  476. package/backend/dist/providers/anthropic-messages.js +53 -0
  477. package/backend/dist/providers/anthropic.d.ts +7 -8
  478. package/backend/dist/providers/anthropic.js +36 -324
  479. package/backend/dist/providers/base.d.ts +18 -45
  480. package/backend/dist/providers/boot-direct.d.ts +20 -2
  481. package/backend/dist/providers/boot-direct.js +140 -61
  482. package/backend/dist/providers/compat/tool-markup-leak.d.ts +41 -0
  483. package/backend/dist/providers/compat/tool-markup-leak.js +57 -0
  484. package/backend/dist/providers/compat/tool-markup-recovery.d.ts +27 -0
  485. package/backend/dist/providers/compat/tool-markup-recovery.js +831 -0
  486. package/backend/dist/providers/dispatch.d.ts +5 -22
  487. package/backend/dist/providers/dispatch.js +49 -55
  488. package/backend/dist/providers/executors/anthropic-messages.d.ts +13 -0
  489. package/backend/dist/providers/executors/anthropic-messages.js +59 -0
  490. package/backend/dist/providers/executors/dispatch.d.ts +28 -0
  491. package/backend/dist/providers/executors/dispatch.js +101 -0
  492. package/backend/dist/providers/executors/google-gemini.d.ts +13 -0
  493. package/backend/dist/providers/executors/google-gemini.js +56 -0
  494. package/backend/dist/providers/executors/http-json.d.ts +19 -0
  495. package/backend/dist/providers/executors/http-json.js +125 -0
  496. package/backend/dist/providers/executors/http-stream.d.ts +53 -0
  497. package/backend/dist/providers/executors/http-stream.js +485 -0
  498. package/backend/dist/providers/executors/openai-chat.d.ts +14 -0
  499. package/backend/dist/providers/executors/openai-chat.js +92 -0
  500. package/backend/dist/providers/executors/openai-responses.d.ts +13 -0
  501. package/backend/dist/providers/executors/openai-responses.js +74 -0
  502. package/backend/dist/providers/executors/plugin-adapter.d.ts +9 -0
  503. package/backend/dist/providers/executors/plugin-adapter.js +31 -0
  504. package/backend/dist/providers/google-gemini.d.ts +12 -0
  505. package/backend/dist/providers/google-gemini.js +50 -0
  506. package/backend/dist/providers/google.d.ts +7 -8
  507. package/backend/dist/providers/google.js +35 -308
  508. package/backend/dist/providers/http-json.d.ts +19 -0
  509. package/backend/dist/providers/http-json.js +104 -0
  510. package/backend/dist/providers/http-stream.d.ts +52 -0
  511. package/backend/dist/providers/http-stream.js +423 -0
  512. package/backend/dist/providers/member-match.d.ts +4 -5
  513. package/backend/dist/providers/member-match.js +4 -5
  514. package/backend/dist/providers/openai-chat.d.ts +13 -0
  515. package/backend/dist/providers/openai-chat.js +99 -0
  516. package/backend/dist/providers/openai-compatible.d.ts +7 -4
  517. package/backend/dist/providers/openai-compatible.js +71 -368
  518. package/backend/dist/providers/openai-responses.d.ts +12 -0
  519. package/backend/dist/providers/openai-responses.js +68 -0
  520. package/backend/dist/providers/opencode-proxy.d.ts +5 -5
  521. package/backend/dist/providers/opencode-proxy.js +49 -125
  522. package/backend/dist/providers/plugin-adapter.d.ts +9 -0
  523. package/backend/dist/providers/plugin-adapter.js +31 -0
  524. package/backend/dist/providers/plugin-wires.d.ts +34 -0
  525. package/backend/dist/providers/plugin-wires.js +82 -0
  526. package/backend/dist/providers/pool-refresh.d.ts +14 -0
  527. package/backend/dist/providers/pool-refresh.js +13 -0
  528. package/backend/dist/providers/protocol.d.ts +4 -0
  529. package/backend/dist/providers/protocol.js +61 -0
  530. package/backend/dist/providers/provider-takedown.d.ts +59 -0
  531. package/backend/dist/providers/provider-takedown.js +135 -0
  532. package/backend/dist/providers/registry.d.ts +85 -44
  533. package/backend/dist/providers/registry.js +299 -162
  534. package/backend/dist/providers/responses.d.ts +7 -26
  535. package/backend/dist/providers/responses.js +45 -250
  536. package/backend/dist/providers/tool-markup-leak.d.ts +41 -0
  537. package/backend/dist/providers/tool-markup-leak.js +57 -0
  538. package/backend/dist/providers/tool-markup-recovery.d.ts +27 -0
  539. package/backend/dist/providers/tool-markup-recovery.js +786 -0
  540. package/backend/dist/providers/virtual-meta.d.ts +21 -2
  541. package/backend/dist/providers/virtual-meta.js +49 -9
  542. package/backend/dist/providers/vocabulary.d.ts +24 -6
  543. package/backend/dist/providers/vocabulary.js +75 -33
  544. package/backend/dist/providers/wire.d.ts +12 -17
  545. package/backend/dist/providers/wire.js +43 -91
  546. package/backend/dist/proxy/asset-download.d.ts +54 -0
  547. package/backend/dist/proxy/asset-download.js +420 -0
  548. package/backend/dist/proxy/manual-node-spec.d.ts +92 -0
  549. package/backend/dist/proxy/manual-node-spec.js +408 -0
  550. package/backend/dist/proxy/mihomo-binary.d.ts +54 -0
  551. package/backend/dist/proxy/mihomo-binary.js +278 -0
  552. package/backend/dist/proxy/mihomo-client.d.ts +94 -0
  553. package/backend/dist/proxy/mihomo-client.js +308 -0
  554. package/backend/dist/proxy/mihomo-config.d.ts +40 -0
  555. package/backend/dist/proxy/mihomo-config.js +161 -0
  556. package/backend/dist/proxy/mihomo-geo.d.ts +87 -0
  557. package/backend/dist/proxy/mihomo-geo.js +213 -0
  558. package/backend/dist/proxy/mihomo-logs.d.ts +27 -0
  559. package/backend/dist/proxy/mihomo-logs.js +70 -0
  560. package/backend/dist/proxy/mihomo-pac.d.ts +37 -0
  561. package/backend/dist/proxy/mihomo-pac.js +75 -0
  562. package/backend/dist/proxy/mihomo-rules-import.d.ts +43 -0
  563. package/backend/dist/proxy/mihomo-rules-import.js +193 -0
  564. package/backend/dist/proxy/mihomo-sidecar.d.ts +81 -0
  565. package/backend/dist/proxy/mihomo-sidecar.js +637 -0
  566. package/backend/dist/quota/adapters/minimax.js +36 -13
  567. package/backend/dist/quota/cli-login.d.ts +8 -0
  568. package/backend/dist/quota/cli-login.js +18 -0
  569. package/backend/dist/quota/declarations.js +10 -0
  570. package/backend/dist/quota/dsl.js +18 -5
  571. package/backend/dist/quota/engine.d.ts +31 -3
  572. package/backend/dist/quota/engine.js +189 -30
  573. package/backend/dist/quota/prober.d.ts +13 -4
  574. package/backend/dist/quota/prober.js +20 -12
  575. package/backend/dist/quota/types.d.ts +87 -8
  576. package/backend/dist/quota/verdict.d.ts +35 -0
  577. package/backend/dist/quota/verdict.js +135 -0
  578. package/backend/dist/ratelimit/admission.d.ts +131 -0
  579. package/backend/dist/ratelimit/admission.js +233 -0
  580. package/backend/dist/ratelimit/rate-limiter.d.ts +119 -6
  581. package/backend/dist/ratelimit/rate-limiter.js +364 -20
  582. package/backend/dist/ratelimit/window-store.d.ts +34 -0
  583. package/backend/dist/ratelimit/window-store.js +70 -0
  584. package/backend/dist/resilience/breaker-state.js +8 -1
  585. package/backend/dist/resilience/circuit-breaker-manager.d.ts +229 -132
  586. package/backend/dist/resilience/circuit-breaker-manager.js +566 -297
  587. package/backend/dist/resilience/circuit-breaker.d.ts +11 -0
  588. package/backend/dist/resilience/circuit-breaker.js +39 -7
  589. package/backend/dist/resilience/error-classifier.d.ts +31 -3
  590. package/backend/dist/resilience/error-classifier.js +159 -31
  591. package/backend/dist/resilience/health-prober.d.ts +21 -4
  592. package/backend/dist/resilience/health-prober.js +100 -18
  593. package/backend/dist/resilience/types.d.ts +54 -7
  594. package/backend/dist/resilience/types.js +1 -1
  595. package/backend/dist/router/index.d.ts +6 -29
  596. package/backend/dist/router/index.js +15 -61
  597. package/backend/dist/router/layer2-decision.d.ts +3 -3
  598. package/backend/dist/router/layer2-decision.js +26 -26
  599. package/backend/dist/router/request-traits.d.ts +4 -11
  600. package/backend/dist/router/request-traits.js +5 -13
  601. package/backend/dist/routes/console.js +2145 -259
  602. package/backend/dist/routes/environments.d.ts +3 -2
  603. package/backend/dist/routes/environments.js +8 -4
  604. package/backend/dist/routes/harness.d.ts +3 -1
  605. package/backend/dist/routes/harness.js +1162 -356
  606. package/backend/dist/routes/mihomo.d.ts +7 -0
  607. package/backend/dist/routes/mihomo.js +1187 -0
  608. package/backend/dist/routes/projects.d.ts +2 -0
  609. package/backend/dist/routes/projects.js +90 -0
  610. package/backend/dist/routes/responses.d.ts +107 -9
  611. package/backend/dist/routes/responses.js +378 -35
  612. package/backend/dist/routes/translation.d.ts +9 -0
  613. package/backend/dist/routes/translation.js +155 -0
  614. package/backend/dist/server.js +379 -73
  615. package/backend/dist/session/resp-store.d.ts +18 -49
  616. package/backend/dist/session/resp-store.js +114 -122
  617. package/backend/dist/session/session-manager.d.ts +228 -81
  618. package/backend/dist/session/session-manager.js +449 -190
  619. package/backend/dist/session/session-row.d.ts +81 -2
  620. package/backend/dist/session/session-row.js +69 -1
  621. package/backend/dist/surfaces/anthropic.d.ts +1 -15
  622. package/backend/dist/surfaces/anthropic.js +63 -44
  623. package/backend/dist/surfaces/chat-pipeline.d.ts +10 -6
  624. package/backend/dist/surfaces/chat-pipeline.js +119 -42
  625. package/backend/dist/surfaces/chat.d.ts +1 -9
  626. package/backend/dist/surfaces/chat.js +67 -29
  627. package/backend/dist/surfaces/decision-pipeline.js +32 -27
  628. package/backend/dist/surfaces/direct-forward.d.ts +3 -0
  629. package/backend/dist/surfaces/direct-forward.js +206 -0
  630. package/backend/dist/surfaces/gateway-chat.d.ts +53 -0
  631. package/backend/dist/surfaces/gateway-chat.js +204 -0
  632. package/backend/dist/surfaces/ocr-headers.d.ts +25 -4
  633. package/backend/dist/surfaces/ocr-headers.js +52 -6
  634. package/backend/dist/surfaces/rate-limit-response.d.ts +17 -0
  635. package/backend/dist/surfaces/rate-limit-response.js +57 -0
  636. package/backend/dist/surfaces/responses.d.ts +9 -1
  637. package/backend/dist/surfaces/responses.js +141 -141
  638. package/backend/dist/surfaces/systemone-probe.js +1 -1
  639. package/backend/dist/surfaces/systemone.d.ts +1 -1
  640. package/backend/dist/surfaces/systemone.js +1 -1
  641. package/backend/dist/surfaces/table.d.ts +15 -0
  642. package/backend/dist/surfaces/table.js +15 -0
  643. package/backend/dist/surfaces/transport-backpressure.d.ts +46 -0
  644. package/backend/dist/surfaces/transport-backpressure.js +122 -0
  645. package/backend/dist/surfaces/transport-fastify.js +92 -21
  646. package/backend/dist/surfaces/transport-node-http.js +92 -18
  647. package/backend/dist/surfaces/types.d.ts +85 -12
  648. package/backend/dist/trace/persist.d.ts +5 -0
  649. package/backend/dist/trace/persist.js +185 -24
  650. package/backend/dist/trace/tracker.d.ts +185 -17
  651. package/backend/dist/trace/tracker.js +106 -31
  652. package/backend/dist/translation/index.d.ts +151 -0
  653. package/backend/dist/translation/index.js +735 -0
  654. package/backend/dist/types/openai.d.ts +82 -1
  655. package/backend/dist/types/router.d.ts +104 -17
  656. package/backend/dist/types/router.js +68 -7
  657. package/backend/dist/update/check.d.ts +43 -0
  658. package/backend/dist/update/check.js +126 -0
  659. package/backend/dist/utils/chat-sse.d.ts +2 -22
  660. package/backend/dist/utils/chat-sse.js +1 -69
  661. package/backend/dist/utils/chat-stream.d.ts +23 -9
  662. package/backend/dist/utils/chat-stream.js +46 -9
  663. package/backend/dist/utils/client-envelope.d.ts +108 -0
  664. package/backend/dist/utils/client-envelope.js +305 -0
  665. package/backend/dist/utils/event-ring.d.ts +12 -1
  666. package/backend/dist/utils/event-ring.js +17 -5
  667. package/backend/dist/utils/harness-profiles.d.ts +51 -0
  668. package/backend/dist/utils/harness-profiles.js +70 -0
  669. package/backend/dist/utils/percentile.d.ts +16 -0
  670. package/backend/dist/utils/percentile.js +29 -0
  671. package/backend/dist/utils/popularity.d.ts +4 -0
  672. package/backend/dist/utils/popularity.js +58 -0
  673. package/backend/dist/utils/probe-interval.d.ts +12 -0
  674. package/backend/dist/utils/probe-interval.js +16 -0
  675. package/backend/dist/utils/proxy-node.d.ts +13 -0
  676. package/backend/dist/utils/proxy-node.js +471 -0
  677. package/backend/dist/utils/proxy.d.ts +19 -0
  678. package/backend/dist/utils/proxy.js +79 -14
  679. package/backend/dist/utils/retry-after.d.ts +21 -0
  680. package/backend/dist/utils/retry-after.js +36 -0
  681. package/backend/dist/utils/run-command.d.ts +42 -0
  682. package/backend/dist/utils/run-command.js +93 -0
  683. package/backend/dist/utils/self-url.d.ts +13 -0
  684. package/backend/dist/utils/self-url.js +90 -2
  685. package/backend/dist/utils/semver.d.ts +22 -0
  686. package/backend/dist/utils/semver.js +75 -0
  687. package/backend/dist/utils/stream-relay.d.ts +35 -0
  688. package/backend/dist/utils/stream-relay.js +1 -0
  689. package/backend/dist/utils/upstream-url-guard.d.ts +15 -0
  690. package/backend/dist/utils/upstream-url-guard.js +107 -0
  691. package/backend/dist/validator/parser.d.ts +2 -5
  692. package/backend/dist/validator/parser.js +12 -16
  693. package/backend/dist/validator/schema-assertion.d.ts +3 -2
  694. package/backend/dist/validator/schema-assertion.js +53 -8
  695. package/bin/ocr.js +2 -2
  696. package/frontend/dist/assets/index-Cn3QMOQx.js +1487 -0
  697. package/frontend/dist/assets/index-DxZ9MHKB.css +1 -0
  698. package/frontend/dist/assets/qoder.color-tVX5GCcD.svg +5 -0
  699. package/frontend/dist/index.html +2 -2
  700. package/frontend/dist/provider-logos/302ai.svg +7 -0
  701. package/frontend/dist/provider-logos/NOTICE.txt +39 -0
  702. package/frontend/dist/provider-logos/abacus.svg +14 -0
  703. package/frontend/dist/provider-logos/abliteration-ai.svg +6 -0
  704. package/frontend/dist/provider-logos/above.svg +3 -0
  705. package/frontend/dist/provider-logos/agentrouter.svg +4 -0
  706. package/frontend/dist/provider-logos/agnes.svg +1 -0
  707. package/frontend/dist/provider-logos/ai-router.svg +5 -0
  708. package/frontend/dist/provider-logos/ai21.svg +3 -0
  709. package/frontend/dist/provider-logos/aiand.svg +4 -0
  710. package/frontend/dist/provider-logos/aihubmix.svg +3 -0
  711. package/frontend/dist/provider-logos/aimlapi.svg +3 -0
  712. package/frontend/dist/provider-logos/ainetcafe.svg +1 -0
  713. package/frontend/dist/provider-logos/aixy.svg +4 -0
  714. package/frontend/dist/provider-logos/aki-io.svg +8 -0
  715. package/frontend/dist/provider-logos/alibaba-cn.svg +3 -0
  716. package/frontend/dist/provider-logos/alibaba-coding-plan-cn.svg +3 -0
  717. package/frontend/dist/provider-logos/alibaba-coding-plan.svg +3 -0
  718. package/frontend/dist/provider-logos/alibaba-token-plan-cn.svg +1 -0
  719. package/frontend/dist/provider-logos/alibaba-token-plan.svg +1 -0
  720. package/frontend/dist/provider-logos/alibaba.svg +3 -0
  721. package/frontend/dist/provider-logos/amazon-bedrock.svg +3 -0
  722. package/frontend/dist/provider-logos/ambient.svg +3 -0
  723. package/frontend/dist/provider-logos/amd.svg +3 -0
  724. package/frontend/dist/provider-logos/anthropic.svg +3 -0
  725. package/frontend/dist/provider-logos/anyapi.svg +3 -0
  726. package/frontend/dist/provider-logos/arcee.svg +3 -0
  727. package/frontend/dist/provider-logos/atomic-chat.svg +1 -0
  728. package/frontend/dist/provider-logos/auriko.svg +6 -0
  729. package/frontend/dist/provider-logos/azure-cognitive-services.svg +3 -0
  730. package/frontend/dist/provider-logos/azure.svg +3 -0
  731. package/frontend/dist/provider-logos/bailing.svg +3 -0
  732. package/frontend/dist/provider-logos/baseten.svg +3 -0
  733. package/frontend/dist/provider-logos/bee.svg +1 -0
  734. package/frontend/dist/provider-logos/berget.svg +3 -0
  735. package/frontend/dist/provider-logos/blueclaw.svg +3 -0
  736. package/frontend/dist/provider-logos/bothub.svg +33 -0
  737. package/frontend/dist/provider-logos/boundless.svg +12 -0
  738. package/frontend/dist/provider-logos/cerebras.svg +4 -0
  739. package/frontend/dist/provider-logos/chutes.svg +24 -0
  740. package/frontend/dist/provider-logos/clarifai.svg +3 -0
  741. package/frontend/dist/provider-logos/claudinio.svg +19 -0
  742. package/frontend/dist/provider-logos/cline-pass.svg +24 -0
  743. package/frontend/dist/provider-logos/cloudferro-sherlock.svg +5 -0
  744. package/frontend/dist/provider-logos/cloudflare-ai-gateway.svg +4 -0
  745. package/frontend/dist/provider-logos/cloudflare-workers-ai.svg +4 -0
  746. package/frontend/dist/provider-logos/cohere.svg +5 -0
  747. package/frontend/dist/provider-logos/commandcode.svg +11 -0
  748. package/frontend/dist/provider-logos/coralbricks.svg +6 -0
  749. package/frontend/dist/provider-logos/cortecs.svg +24 -0
  750. package/frontend/dist/provider-logos/crossmodel.svg +5 -0
  751. package/frontend/dist/provider-logos/crusoe.svg +23 -0
  752. package/frontend/dist/provider-logos/daoxe.svg +3 -0
  753. package/frontend/dist/provider-logos/databricks.svg +3 -0
  754. package/frontend/dist/provider-logos/deepinfra.svg +4 -0
  755. package/frontend/dist/provider-logos/deepseek.svg +3 -0
  756. package/frontend/dist/provider-logos/digitalocean.svg +6 -0
  757. package/frontend/dist/provider-logos/dinference.svg +1 -0
  758. package/frontend/dist/provider-logos/drun.svg +8 -0
  759. package/frontend/dist/provider-logos/ebcloud.svg +8 -0
  760. package/frontend/dist/provider-logos/echo.svg +7 -0
  761. package/frontend/dist/provider-logos/edenai.svg +8 -0
  762. package/frontend/dist/provider-logos/empiriolabs.svg +1 -0
  763. package/frontend/dist/provider-logos/engy.svg +1 -0
  764. package/frontend/dist/provider-logos/evroc.svg +3 -0
  765. package/frontend/dist/provider-logos/fastrouter.svg +3 -0
  766. package/frontend/dist/provider-logos/fireworks-ai.svg +3 -0
  767. package/frontend/dist/provider-logos/freemodel.svg +3 -0
  768. package/frontend/dist/provider-logos/friendli.svg +3 -0
  769. package/frontend/dist/provider-logos/frogbot.svg +36 -0
  770. package/frontend/dist/provider-logos/github-copilot.svg +3 -0
  771. package/frontend/dist/provider-logos/gitlab.svg +3 -0
  772. package/frontend/dist/provider-logos/gmicloud.svg +24 -0
  773. package/frontend/dist/provider-logos/google-vertex-anthropic.svg +10 -0
  774. package/frontend/dist/provider-logos/google-vertex.svg +10 -0
  775. package/frontend/dist/provider-logos/google.svg +3 -0
  776. package/frontend/dist/provider-logos/greenpt.svg +6 -0
  777. package/frontend/dist/provider-logos/groq.svg +3 -0
  778. package/frontend/dist/provider-logos/helicone.svg +6 -0
  779. package/frontend/dist/provider-logos/hetzner.svg +3 -0
  780. package/frontend/dist/provider-logos/hopper.svg +4 -0
  781. package/frontend/dist/provider-logos/hpc-ai.svg +446 -0
  782. package/frontend/dist/provider-logos/huggingface.svg +3 -0
  783. package/frontend/dist/provider-logos/hyper.svg +20 -0
  784. package/frontend/dist/provider-logos/impossibl.svg +3 -0
  785. package/frontend/dist/provider-logos/inception.svg +14 -0
  786. package/frontend/dist/provider-logos/inceptron.svg +14 -0
  787. package/frontend/dist/provider-logos/inco.svg +3 -0
  788. package/frontend/dist/provider-logos/infer.svg +4 -0
  789. package/frontend/dist/provider-logos/inference.svg +3 -0
  790. package/frontend/dist/provider-logos/inferx.svg +5 -0
  791. package/frontend/dist/provider-logos/infomaniak.svg +3 -0
  792. package/frontend/dist/provider-logos/io-net.svg +5 -0
  793. package/frontend/dist/provider-logos/iteracompute.svg +7 -0
  794. package/frontend/dist/provider-logos/jalapeno.svg +8 -0
  795. package/frontend/dist/provider-logos/jiekou.svg +4 -0
  796. package/frontend/dist/provider-logos/kenari.svg +4 -0
  797. package/frontend/dist/provider-logos/kilo.svg +4 -0
  798. package/frontend/dist/provider-logos/kimi-code-plan-cn.svg +3 -0
  799. package/frontend/dist/provider-logos/kimi-code-plan-global.svg +3 -0
  800. package/frontend/dist/provider-logos/klokintegration.svg +11 -0
  801. package/frontend/dist/provider-logos/kosmik.svg +28 -0
  802. package/frontend/dist/provider-logos/kuae-cloud-coding-plan.svg +3 -0
  803. package/frontend/dist/provider-logos/lilac.svg +6 -0
  804. package/frontend/dist/provider-logos/liquid.svg +1 -0
  805. package/frontend/dist/provider-logos/llmgateway-providers.svg +6 -0
  806. package/frontend/dist/provider-logos/llmgateway.svg +6 -0
  807. package/frontend/dist/provider-logos/llmtech.svg +6 -0
  808. package/frontend/dist/provider-logos/llmtr.svg +12 -0
  809. package/frontend/dist/provider-logos/lmstudio.svg +3 -0
  810. package/frontend/dist/provider-logos/longcat.svg +6 -0
  811. package/frontend/dist/provider-logos/lowrouter.svg +8 -0
  812. package/frontend/dist/provider-logos/lucidquery.svg +3 -0
  813. package/frontend/dist/provider-logos/lynkr.svg +1 -0
  814. package/frontend/dist/provider-logos/meganova.svg +3 -0
  815. package/frontend/dist/provider-logos/melious.svg +3 -0
  816. package/frontend/dist/provider-logos/merge-gateway.svg +4 -0
  817. package/frontend/dist/provider-logos/meta.svg +3 -0
  818. package/frontend/dist/provider-logos/minimax-cn-coding-plan.svg +3 -0
  819. package/frontend/dist/provider-logos/minimax-cn.svg +3 -0
  820. package/frontend/dist/provider-logos/minimax-coding-plan.svg +3 -0
  821. package/frontend/dist/provider-logos/minimax.svg +3 -0
  822. package/frontend/dist/provider-logos/mistral.svg +3 -0
  823. package/frontend/dist/provider-logos/mixlayer.svg +9 -0
  824. package/frontend/dist/provider-logos/moark.svg +3 -0
  825. package/frontend/dist/provider-logos/modal.svg +3 -0
  826. package/frontend/dist/provider-logos/model-oracle-ai.svg +11 -0
  827. package/frontend/dist/provider-logos/modelis.svg +1 -0
  828. package/frontend/dist/provider-logos/modelscope.svg +5 -0
  829. package/frontend/dist/provider-logos/modular.svg +3 -0
  830. package/frontend/dist/provider-logos/moonshotai-cn.svg +3 -0
  831. package/frontend/dist/provider-logos/moonshotai.svg +3 -0
  832. package/frontend/dist/provider-logos/morph.svg +24 -0
  833. package/frontend/dist/provider-logos/munito-eu.svg +1 -0
  834. package/frontend/dist/provider-logos/munito.svg +1 -0
  835. package/frontend/dist/provider-logos/nan.svg +1 -0
  836. package/frontend/dist/provider-logos/nano-gpt.svg +3 -0
  837. package/frontend/dist/provider-logos/nearai.svg +1 -0
  838. package/frontend/dist/provider-logos/nebius.svg +4 -0
  839. package/frontend/dist/provider-logos/neon.svg +3 -0
  840. package/frontend/dist/provider-logos/neosmith.svg +6 -0
  841. package/frontend/dist/provider-logos/neuralwatt.svg +27 -0
  842. package/frontend/dist/provider-logos/nova.svg +3 -0
  843. package/frontend/dist/provider-logos/novita-ai.svg +10 -0
  844. package/frontend/dist/provider-logos/nvidia.svg +3 -0
  845. package/frontend/dist/provider-logos/oci.svg +3 -0
  846. package/frontend/dist/provider-logos/ofox.svg +5 -0
  847. package/frontend/dist/provider-logos/ollama-cloud.svg +7 -0
  848. package/frontend/dist/provider-logos/openai.svg +3 -0
  849. package/frontend/dist/provider-logos/opencode-go.svg +4 -0
  850. package/frontend/dist/provider-logos/opencode.svg +4 -0
  851. package/frontend/dist/provider-logos/openreason.svg +8 -0
  852. package/frontend/dist/provider-logos/openrouter.svg +5 -0
  853. package/frontend/dist/provider-logos/opper.svg +3 -0
  854. package/frontend/dist/provider-logos/orcarouter.svg +2 -0
  855. package/frontend/dist/provider-logos/ovhcloud.svg +3 -0
  856. package/frontend/dist/provider-logos/pareto.svg +5 -0
  857. package/frontend/dist/provider-logos/pendra.svg +10 -0
  858. package/frontend/dist/provider-logos/perplexity-agent.svg +3 -0
  859. package/frontend/dist/provider-logos/perplexity.svg +3 -0
  860. package/frontend/dist/provider-logos/pioneer.svg +3 -0
  861. package/frontend/dist/provider-logos/poe.svg +7 -0
  862. package/frontend/dist/provider-logos/poolside.svg +3 -0
  863. package/frontend/dist/provider-logos/prime.svg +7 -0
  864. package/frontend/dist/provider-logos/privatemode-ai.svg +5 -0
  865. package/frontend/dist/provider-logos/qihang-ai.svg +9 -0
  866. package/frontend/dist/provider-logos/qiniu-ai.svg +7 -0
  867. package/frontend/dist/provider-logos/qvac.svg +6 -0
  868. package/frontend/dist/provider-logos/reflection.svg +3 -0
  869. package/frontend/dist/provider-logos/regolo-ai.svg +46 -0
  870. package/frontend/dist/provider-logos/requesty.svg +24 -0
  871. package/frontend/dist/provider-logos/routing-run.svg +4 -0
  872. package/frontend/dist/provider-logos/runinfra.svg +10 -0
  873. package/frontend/dist/provider-logos/sakana.svg +24 -0
  874. package/frontend/dist/provider-logos/salad-cloud.svg +15 -0
  875. package/frontend/dist/provider-logos/sambanova.svg +26 -0
  876. package/frontend/dist/provider-logos/sap-ai-core.svg +24 -0
  877. package/frontend/dist/provider-logos/sarvam.svg +24 -0
  878. package/frontend/dist/provider-logos/scaleway.svg +5 -0
  879. package/frontend/dist/provider-logos/scnet-token-plan.svg +8 -0
  880. package/frontend/dist/provider-logos/scx-ai.svg +1 -0
  881. package/frontend/dist/provider-logos/sensenova.svg +18 -0
  882. package/frontend/dist/provider-logos/siliconflow-cn.svg +3 -0
  883. package/frontend/dist/provider-logos/siliconflow.svg +3 -0
  884. package/frontend/dist/provider-logos/snowflake-cortex.svg +3 -0
  885. package/frontend/dist/provider-logos/stackit.svg +4 -0
  886. package/frontend/dist/provider-logos/standardcompute.svg +5 -0
  887. package/frontend/dist/provider-logos/stepfun-ai-step-plan.svg +16 -0
  888. package/frontend/dist/provider-logos/stepfun-ai.svg +16 -0
  889. package/frontend/dist/provider-logos/stepfun-step-plan.svg +16 -0
  890. package/frontend/dist/provider-logos/stepfun.svg +16 -0
  891. package/frontend/dist/provider-logos/subconscious.svg +3 -0
  892. package/frontend/dist/provider-logos/submodel.svg +3 -0
  893. package/frontend/dist/provider-logos/synthetic.svg +24 -0
  894. package/frontend/dist/provider-logos/tempr.svg +4 -0
  895. package/frontend/dist/provider-logos/tencent-coding-plan.svg +5 -0
  896. package/frontend/dist/provider-logos/tencent-token-plan.svg +3 -0
  897. package/frontend/dist/provider-logos/tencent-tokenhub.svg +3 -0
  898. package/frontend/dist/provider-logos/tensorx.svg +6 -0
  899. package/frontend/dist/provider-logos/the-grid-ai.svg +14 -0
  900. package/frontend/dist/provider-logos/thinkingmachines.svg +3 -0
  901. package/frontend/dist/provider-logos/tinfoil.svg +3 -0
  902. package/frontend/dist/provider-logos/togetherai.svg +4 -0
  903. package/frontend/dist/provider-logos/tokengo.svg +3 -0
  904. package/frontend/dist/provider-logos/tokenrouter.svg +4 -0
  905. package/frontend/dist/provider-logos/trustedrouter.svg +4 -0
  906. package/frontend/dist/provider-logos/umans-ai-coding-plan.svg +29 -0
  907. package/frontend/dist/provider-logos/umans-ai.svg +29 -0
  908. package/frontend/dist/provider-logos/unorouter.svg +7 -0
  909. package/frontend/dist/provider-logos/upstage.svg +24 -0
  910. package/frontend/dist/provider-logos/vancine.svg +6 -0
  911. package/frontend/dist/provider-logos/venice.svg +4 -0
  912. package/frontend/dist/provider-logos/vercel.svg +3 -0
  913. package/frontend/dist/provider-logos/vispark.svg +3 -0
  914. package/frontend/dist/provider-logos/vivgrid.svg +4 -0
  915. package/frontend/dist/provider-logos/volcengine-coding-plan.svg +1 -0
  916. package/frontend/dist/provider-logos/volcengine.svg +1 -0
  917. package/frontend/dist/provider-logos/vultr.svg +6 -0
  918. package/frontend/dist/provider-logos/wafer.ai.svg +3 -0
  919. package/frontend/dist/provider-logos/wallaby.svg +4 -0
  920. package/frontend/dist/provider-logos/wally.svg +1 -0
  921. package/frontend/dist/provider-logos/wandb.svg +6 -0
  922. package/frontend/dist/provider-logos/watsonx.svg +5 -0
  923. package/frontend/dist/provider-logos/xai.svg +3 -0
  924. package/frontend/dist/provider-logos/xiaomi-token-plan-ams.svg +3 -0
  925. package/frontend/dist/provider-logos/xiaomi-token-plan-cn.svg +3 -0
  926. package/frontend/dist/provider-logos/xiaomi-token-plan-sgp.svg +3 -0
  927. package/frontend/dist/provider-logos/xiaomi.svg +3 -0
  928. package/frontend/dist/provider-logos/xpersona.svg +8 -0
  929. package/frontend/dist/provider-logos/zai-coding-plan.svg +3 -0
  930. package/frontend/dist/provider-logos/zai.svg +3 -0
  931. package/frontend/dist/provider-logos/zeldoc.svg +3 -0
  932. package/frontend/dist/provider-logos/zenifra.svg +4 -0
  933. package/frontend/dist/provider-logos/zenmux.svg +4 -0
  934. package/frontend/dist/provider-logos/zhipuai-coding-plan.svg +3 -0
  935. package/frontend/dist/provider-logos/zhipuai.svg +3 -0
  936. package/package.json +13 -5
  937. package/backend/dist/budget/budget-manager.d.ts +0 -25
  938. package/backend/dist/budget/budget-manager.js +0 -54
  939. package/backend/dist/config/governance-limits.d.ts +0 -68
  940. package/backend/dist/config/governance-limits.js +0 -261
  941. package/backend/dist/flywheel/collector.d.ts +0 -74
  942. package/backend/dist/flywheel/collector.js +0 -235
  943. package/backend/dist/flywheel/dataset.d.ts +0 -130
  944. package/backend/dist/flywheel/dataset.js +0 -638
  945. package/backend/dist/flywheel/decision-capture.d.ts +0 -68
  946. package/backend/dist/flywheel/decision-capture.js +0 -85
  947. package/backend/dist/flywheel/prune.d.ts +0 -133
  948. package/backend/dist/flywheel/prune.js +0 -495
  949. package/backend/dist/flywheel/schema.d.ts +0 -108
  950. package/backend/dist/flywheel/schema.js +0 -117
  951. package/backend/dist/flywheel/trainer.d.ts +0 -84
  952. package/backend/dist/flywheel/trainer.js +0 -198
  953. package/backend/dist/forward-proxy/bypass.d.ts +0 -20
  954. package/backend/dist/forward-proxy/bypass.js +0 -28
  955. package/backend/dist/harness/adapters/amp.d.ts +0 -2
  956. package/backend/dist/harness/adapters/amp.js +0 -8
  957. package/backend/dist/harness/adapters/claude.d.ts +0 -2
  958. package/backend/dist/harness/adapters/claude.js +0 -8
  959. package/backend/dist/harness/adapters/cline.d.ts +0 -2
  960. package/backend/dist/harness/adapters/cline.js +0 -8
  961. package/backend/dist/harness/adapters/codex.d.ts +0 -2
  962. package/backend/dist/harness/adapters/codex.js +0 -8
  963. package/backend/dist/harness/adapters/cursor.d.ts +0 -5
  964. package/backend/dist/harness/adapters/cursor.js +0 -11
  965. package/backend/dist/harness/adapters/declarative.d.ts +0 -64
  966. package/backend/dist/harness/adapters/declarative.js +0 -216
  967. package/backend/dist/harness/adapters/dsh.d.ts +0 -5
  968. package/backend/dist/harness/adapters/dsh.js +0 -6
  969. package/backend/dist/harness/adapters/gemini-cli.d.ts +0 -2
  970. package/backend/dist/harness/adapters/gemini-cli.js +0 -8
  971. package/backend/dist/harness/adapters/github-copilot.d.ts +0 -5
  972. package/backend/dist/harness/adapters/github-copilot.js +0 -11
  973. package/backend/dist/harness/adapters/omp.d.ts +0 -11
  974. package/backend/dist/harness/adapters/omp.js +0 -22
  975. package/backend/dist/harness/adapters/opencode.d.ts +0 -2
  976. package/backend/dist/harness/adapters/opencode.js +0 -56
  977. package/backend/dist/harness/adapters/pi.d.ts +0 -1
  978. package/backend/dist/harness/adapters/pi.js +0 -23
  979. package/backend/dist/harness/adapters/types.d.ts +0 -189
  980. package/backend/dist/harness/adapters/types.js +0 -12
  981. package/backend/dist/harness/adapters/universal.d.ts +0 -6
  982. package/backend/dist/harness/adapters/universal.js +0 -10
  983. package/backend/dist/harness/adapters/windsurf.d.ts +0 -2
  984. package/backend/dist/harness/adapters/windsurf.js +0 -11
  985. package/backend/dist/harness/adapters/zed.d.ts +0 -2
  986. package/backend/dist/harness/adapters/zed.js +0 -8
  987. package/backend/dist/harness/awesome-opencode.d.ts +0 -40
  988. package/backend/dist/harness/awesome-opencode.js +0 -75
  989. package/backend/dist/harness/browse.d.ts +0 -202
  990. package/backend/dist/harness/browse.js +0 -1214
  991. package/backend/dist/harness/inventory.d.ts +0 -10
  992. package/backend/dist/harness/opencode-cafe.d.ts +0 -40
  993. package/backend/dist/harness/opencode-cafe.js +0 -85
  994. package/backend/dist/harness/opencode-ecosystem.d.ts +0 -34
  995. package/backend/dist/harness/opencode-ecosystem.js +0 -246
  996. package/backend/dist/harness/pi-dev.d.ts +0 -81
  997. package/backend/dist/harness/pi-dev.js +0 -187
  998. package/backend/dist/harness/registry.js +0 -26
  999. package/backend/dist/harness/scopes.d.ts +0 -21
  1000. package/backend/dist/harness/scopes.js +0 -22
  1001. package/backend/dist/harness/skills-sh.d.ts +0 -109
  1002. package/backend/dist/harness/skills-sh.js +0 -178
  1003. package/backend/dist/harness/smithery.d.ts +0 -64
  1004. package/backend/dist/harness/smithery.js +0 -146
  1005. package/backend/dist/harness/sources/awesome-opencode.d.ts +0 -11
  1006. package/backend/dist/harness/sources/awesome-opencode.js +0 -39
  1007. package/backend/dist/harness/sources/mcp-official.d.ts +0 -2
  1008. package/backend/dist/harness/sources/mcp-official.js +0 -110
  1009. package/backend/dist/harness/sources/npm.d.ts +0 -2
  1010. package/backend/dist/harness/sources/opencode-cafe.d.ts +0 -11
  1011. package/backend/dist/harness/sources/opencode-cafe.js +0 -41
  1012. package/backend/dist/harness/sources/smithery.d.ts +0 -2
  1013. package/backend/dist/harness/sources/smithery.js +0 -81
  1014. package/backend/dist/harness/writers/extension.d.ts +0 -116
  1015. package/backend/dist/harness/writers/extension.js +0 -219
  1016. package/backend/dist/harness/writers/mcp.d.ts +0 -72
  1017. package/backend/dist/harness/writers/mcp.js +0 -195
  1018. package/backend/dist/opencode/catalog/custom-store.d.ts +0 -50
  1019. package/backend/dist/opencode/catalog/custom-store.js +0 -144
  1020. package/backend/dist/opencode/credentials/push.d.ts +0 -38
  1021. package/backend/dist/opencode/credentials/push.js +0 -116
  1022. package/backend/dist/opencode/credentials/reconcile.d.ts +0 -49
  1023. package/backend/dist/opencode/credentials/reconcile.js +0 -216
  1024. package/backend/dist/opencode/sync.d.ts +0 -29
  1025. package/backend/dist/opencode/sync.js +0 -186
  1026. package/backend/dist/pipeline/account-selection.d.ts +0 -101
  1027. package/backend/dist/pipeline/account-selection.js +0 -112
  1028. package/backend/dist/providers/systemone.d.ts +0 -29
  1029. package/backend/dist/providers/systemone.js +0 -170
  1030. package/backend/dist/ratelimit/duration.d.ts +0 -24
  1031. package/backend/dist/ratelimit/duration.js +0 -43
  1032. package/backend/dist/ratelimit/governance-runtime.d.ts +0 -121
  1033. package/backend/dist/ratelimit/governance-runtime.js +0 -183
  1034. package/backend/dist/ratelimit/index.d.ts +0 -4
  1035. package/backend/dist/ratelimit/index.js +0 -4
  1036. package/backend/dist/ratelimit/limiter.d.ts +0 -157
  1037. package/backend/dist/ratelimit/limiter.js +0 -244
  1038. package/backend/dist/ratelimit/sliding-window-counter.d.ts +0 -63
  1039. package/backend/dist/ratelimit/sliding-window-counter.js +0 -103
  1040. package/backend/dist/ratelimit/subject.d.ts +0 -26
  1041. package/backend/dist/ratelimit/subject.js +0 -28
  1042. package/backend/dist/resilience/account-state.d.ts +0 -84
  1043. package/backend/dist/resilience/account-state.js +0 -228
  1044. package/backend/dist/router/layer1-classifier.d.ts +0 -111
  1045. package/backend/dist/router/layer1-classifier.js +0 -467
  1046. package/backend/dist/router/layer2-judge.d.ts +0 -111
  1047. package/backend/dist/router/layer2-judge.js +0 -373
  1048. package/backend/dist/router/retry-escalation.d.ts +0 -89
  1049. package/backend/dist/router/retry-escalation.js +0 -99
  1050. package/backend/dist/routes/flywheel.d.ts +0 -3
  1051. package/backend/dist/routes/flywheel.js +0 -268
  1052. package/backend/dist/routes/systemone.d.ts +0 -3
  1053. package/backend/dist/routes/systemone.js +0 -90
  1054. package/backend/dist/surfaces/governance-envelope.d.ts +0 -34
  1055. package/backend/dist/surfaces/governance-envelope.js +0 -47
  1056. package/backend/dist/utils/token-estimator.d.ts +0 -7
  1057. package/backend/dist/utils/token-estimator.js +0 -20
  1058. package/frontend/dist/assets/index-B7GKsUyU.js +0 -982
  1059. package/frontend/dist/assets/index-DLKLOkQJ.css +0 -1
  1060. package/frontend/dist/assets/inter-cyrillic-800-normal-C7MGvYyJ.woff2 +0 -0
  1061. package/frontend/dist/assets/inter-cyrillic-800-normal-CCHyn08d.woff +0 -0
  1062. package/frontend/dist/assets/inter-cyrillic-ext-800-normal-BZOjs1Xv.woff2 +0 -0
  1063. package/frontend/dist/assets/inter-cyrillic-ext-800-normal-Ca-gJeZY.woff +0 -0
  1064. package/frontend/dist/assets/inter-greek-800-normal-BU00tryP.woff +0 -0
  1065. package/frontend/dist/assets/inter-greek-800-normal-CLIouy3y.woff2 +0 -0
  1066. package/frontend/dist/assets/inter-greek-ext-800-normal-B--PVpEC.woff2 +0 -0
  1067. package/frontend/dist/assets/inter-greek-ext-800-normal-DUe57HfS.woff +0 -0
  1068. package/frontend/dist/assets/inter-latin-800-normal-BYj_oED-.woff2 +0 -0
  1069. package/frontend/dist/assets/inter-latin-800-normal-D1mf63XC.woff +0 -0
  1070. package/frontend/dist/assets/inter-latin-ext-800-normal-BOMpwxm3.woff +0 -0
  1071. package/frontend/dist/assets/inter-latin-ext-800-normal-DZJjya6U.woff2 +0 -0
  1072. package/frontend/dist/assets/inter-vietnamese-800-normal-Cm7tD1pz.woff2 +0 -0
  1073. package/frontend/dist/assets/inter-vietnamese-800-normal-DDlpr_Ee.woff +0 -0
  1074. /package/backend/dist/harness/{adapters → host/adapters}/skills-paths.d.ts +0 -0
  1075. /package/backend/dist/harness/{adapters → host/adapters}/skills-paths.js +0 -0
  1076. /package/backend/dist/harness/{skill-md.d.ts → skill/skill-md.d.ts} +0 -0
  1077. /package/backend/dist/harness/{skill-md.js → skill/skill-md.js} +0 -0
@@ -2,24 +2,36 @@ import http from 'node:http';
2
2
  import https from 'node:https';
3
3
  import net from 'node:net';
4
4
  import tls from 'node:tls';
5
+ import { OrderedRelay } from './ordered-relay.js';
5
6
  import { CertMinter, ensureCa } from './ca.js';
6
- import { parseClientHelloSNI } from './sni.js';
7
+ import { peekClientHello } from './sni.js';
7
8
  import { splice } from './relay.js';
8
- import { matchBypass } from './bypass.js';
9
- import { resolveProxyUrl } from '../utils/proxy.js';
10
- import { FORWARD_PROXY_HANG_TIMEOUT_MS } from '../config/defaults.js';
9
+ import { DEFAULT_FORWARD_PROXY_MAX_CONNECTIONS, FORWARD_PROXY_HANG_TIMEOUT_MS, FORWARD_PROXY_KEEPALIVE_MS, } from '../config/defaults.js';
10
+ import { describeUpstreamFailure, failureLabel, filterHeaders, isRuleRejected, openViaProxy, parseProxy, ruleTunnels, setBootRules, setLiveForwardProxy, transitEgressFor, shouldRetryOriginLeg, transitProxyFor, UPSTREAM_TIMEOUT_CODE, upstreamServernameOption, } from './egress.js';
11
+ import { resolveUpstreamTls } from './upstream-tls.js';
12
+ import { createAccessTap, recordProxyConnect, recordProxyTunnel } from './access-log.js';
13
+ import { closeH2Pool, forwardH2 } from './h2-forward.js';
14
+ import { createWsObserver } from './ws-frames.js';
15
+ import { findGateway, listGatewayHosts } from '../plugins/gateways.js';
16
+ import { markProxyCaller } from './caller-context.js';
17
+ import http2 from 'node:http2';
11
18
  /**
12
19
  * Inbound forward proxy (the HTTP_PROXY / HTTPS_PROXY server).
13
20
  *
14
21
  * Design (settled & validated on Bun 1.3.14):
15
- * - FULL CAPTURE by default: every HTTPS CONNECT is MITM'd. The decrypted
16
- * request is inspected — LLM-protocol traffic (via `intercept`) enters the
17
- * routing pipeline; everything else is forwarded transparently.
18
- * - Transit egress optionally via the outbound proxy policy
19
- * (`viaOutboundProxy` — CONNECT through config.proxy, e.g. clash), so
20
- * network-blocked targets stay reachable for tunnels and forwards.
21
- * - Exceptions are blind-tunneled, never decrypted: loopback targets and
22
- * `bypassHosts` matches.
22
+ * - INTERCEPTION IS DECIDED (ADR-0018 Revision 4): a CONNECT is MITM'd only
23
+ * when a rule row says so, when a live client-gateway plugin CLAIMS the host,
24
+ * or when the operator turned on the audit posture (`intercept: 'all'`).
25
+ * Everything else is a blind tunnel. The decrypted request is inspected —
26
+ * LLM-protocol traffic (via `intercept`) enters the routing pipeline;
27
+ * everything else is forwarded transparently.
28
+ * - ONE ordered rule table decides both halves per host (ADR-0018,
29
+ * `forwardProxy.rules`): two fields per row — `ingress` = intercept (MITM) /
30
+ * passthrough (blind tunnel) / reject, `egress` = direct / proxy. First match
31
+ * wins; loopback is always passthrough (cycle safety + local dev); an
32
+ * unmatched host takes the catch-all's `egress` and is blind-tunneled unless
33
+ * claimed or the audit posture is on. `reject` is answered 403 on admission —
34
+ * before any tunnel is opened or certificate minted.
23
35
  * - Bun node:tls gaps worked around (all verified experimentally):
24
36
  * * no SNICallback → per-host tls.Server with an explicit cert, cached;
25
37
  * the servername is read by peeking the raw ClientHello (sni.ts);
@@ -27,136 +39,321 @@ import { FORWARD_PROXY_HANG_TIMEOUT_MS } from '../config/defaults.js';
27
39
  * explicit relay (relay.ts);
28
40
  * * tlsServer/httpServer.emit('connection', socket) is not honored →
29
41
  * the decrypted stream is spliced over a loopback socket into an
30
- * inner http.Server that does native Bun HTTP parsing.
31
- * - ALPN is pinned to http/1.1 so clients never negotiate h2 into the
32
- * HTTP/1.1 inner parser.
42
+ * inner http.Server that does native Bun HTTP parsing;
43
+ * * the node:http 'upgrade' event is unusable (the handler's socket
44
+ * swallows every write and the parser then answers 505) → an
45
+ * `Upgrade:` handshake is caught on the decrypted stream before the
46
+ * inner server and relayed byte-verbatim (relayUpgrade).
47
+ * - Per-host terminators and minted certs are LRU-bounded
48
+ * (MAX_HOST_TERMINATORS / MAX_CACHED_CERTS): full capture sees every host
49
+ * a client visits, so an unbounded cache is an fd leak per host.
50
+ * - Transport-complete MITM: the decrypted stream is parsed by an h1 inner
51
+ * OR an h2 inner (prior-knowledge h2c loopback), picked by sniffing the
52
+ * first decrypted bytes for the h2 connection preface. Both inners run the
53
+ * SAME intercept chain and the SAME transparent forward — an h2 request is
54
+ * re-originated upstream over h2 (h2-forward.ts) so gRPC/Connect framing,
55
+ * trailers and bidi streams survive the hop, with an h1 fallback when the
56
+ * upstream refuses h2.
57
+ * - ALPN: every host offers both protocols, ordered by who is talking. Bun
58
+ * honours the SERVER's preference, so an unclaimed host offers
59
+ * ['http/1.1','h2'] (dual-offer clients keep the h1 path — zero regression;
60
+ * h2-only clients get h2) while a gateway-claimed host offers
61
+ * ['h2','http/1.1']. The negotiated protocol is only a hint: the preface is
62
+ * the authority (Bun does not reliably surface alpnProtocol at callback
63
+ * time).
33
64
  *
34
65
  * No-request-loss rule: the client's decoded stream may emit data the moment
35
66
  * the handshake completes — the 'data' listener is attached SYNCHRONOUSLY in
36
67
  * the secureConnection callback; pre-connect chunks are buffered.
37
68
  */
38
69
  const MAX_HELLO_BYTES = 32 * 1024;
70
+ /** Bound on the buffered HTTP/1 request head examined for an `Upgrade:`
71
+ * handshake; a head that outgrows it goes to the inner server unexamined. */
72
+ const MAX_HEAD_BYTES = 32 * 1024;
73
+ /** LRU bound on per-host TLS terminators (each = one listening loopback socket
74
+ * + one minted leaf cert). Full capture sees EVERY host a client visits, so an
75
+ * unbounded map leaks one file descriptor per host for the life of the process. */
76
+ const MAX_HOST_TERMINATORS = 256;
77
+ /**
78
+ * Grace window for an evicted terminator: long enough for a CONNECT that
79
+ * already resolved its port to finish dialing, short enough to keep the fd
80
+ * budget bounded. `server.close()` never touches established connections, so
81
+ * this is the ONLY cost of eviction.
82
+ */
83
+ const TERMINATOR_DRAIN_MS = 30_000;
84
+ /** Hard cap on the draining set — eviction must not become a second cache. */
85
+ const MAX_DRAINING_TERMINATORS = 64;
86
+ /**
87
+ * One ledger row per this window, per terminator. A client that rejects the
88
+ * intercepted leaf (pinning, missing CA) reconnects in a tight loop; without
89
+ * the dedupe it would flush every real row out of the access ring.
90
+ */
91
+ const CLIENT_TLS_ERROR_DEDUPE_MS = 5_000;
92
+ /**
93
+ * Upper bound on "the error envelope is on its way" — the abort normally fires
94
+ * the moment the envelope chunk reaches the client transport; this only covers
95
+ * the case where no chunk ever arrives.
96
+ */
97
+ const MITM_ABORT_FLUSH_MS = 1_000;
98
+ /**
99
+ * How long a blind tunnel waits for client bytes before recording its decision
100
+ * row without an identity. Never a relay delay — the tunnel is already flowing;
101
+ * this only bounds the observation window for a server-speaks-first protocol.
102
+ */
39
103
  const CLIENT_ERROR_RESPONSE = 'HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n';
40
- const HOP_BY_HOP = new Set([
41
- 'connection',
42
- 'proxy-connection',
43
- 'keep-alive',
44
- 'proxy-authenticate',
45
- 'proxy-authorization',
46
- 'te',
47
- 'trailer',
48
- 'transfer-encoding',
49
- 'upgrade',
50
- ]);
51
- function filterHeaders(headers) {
52
- const out = {};
53
- for (const [k, v] of Object.entries(headers)) {
54
- if (v === undefined)
55
- continue;
56
- if (HOP_BY_HOP.has(k.toLowerCase()))
57
- continue;
58
- out[k] = v;
59
- }
60
- return out;
104
+ /**
105
+ * Credential-shaped header names in a raw packet head. The access log applies
106
+ * the same policy to captured headers (`DENY_HEADER_SUBSTRINGS`), and this log
107
+ * line must not become the one place a live key lands on disk.
108
+ */
109
+ const CREDENTIAL_HEADER_LINE = /^(?:proxy-)?authorization$|^cookie$|^set-cookie$|-key$|api[-_]?key|apikey|token|secret/i;
110
+ /** Blank the value of every credential-shaped header line, keep the rest. */
111
+ function redactPacketHead(raw) {
112
+ return raw
113
+ .split('\r\n')
114
+ .map((line) => {
115
+ const at = line.indexOf(':');
116
+ if (at <= 0)
117
+ return line;
118
+ const name = line.slice(0, at);
119
+ return CREDENTIAL_HEADER_LINE.test(name.trim()) ? `${name}: [REDACTED]` : line;
120
+ })
121
+ .join('\r\n');
61
122
  }
62
- // ── outbound-proxy transit (config.proxy policy) ──────────────────────────
63
- // When enabled, bypass tunnels and non-intercepted forwards egress through
64
- // the configured outbound proxy (e.g. clash/v2ray) via CONNECT, so
65
- // network-blocked targets become reachable without touching interception.
66
- // Module-level because only one forward proxy instance exists per process;
67
- // createForwardProxyServer sets it (last created wins).
68
- let transitViaOutboundProxy = false;
69
- function transitProxyFor(host, port, force) {
70
- // force: per-host egress choice (bypass entries carry it); undefined = the
71
- // global `viaOutboundProxy` flag (non-intercepted forwards).
72
- const enabled = force === undefined ? transitViaOutboundProxy : force;
73
- if (!enabled)
74
- return undefined;
75
- return resolveProxyUrl(`https://${host}:${port}/`, { model: host });
123
+ /**
124
+ * One line describing a request the HTTP parser refused. The 400 that follows
125
+ * carries an EMPTY body, so without this the client only ever reports
126
+ * "400 Bad Request" with no headers and the operator has nothing to look at —
127
+ * the raw packet head (request line + first headers) is the only evidence of
128
+ * what the client actually sent.
129
+ */
130
+ function describeClientError(err) {
131
+ if (typeof err !== 'object' || err === null)
132
+ return String(err);
133
+ const code = 'code' in err && typeof err.code === 'string' ? err.code : 'unknown';
134
+ const raw = 'rawPacket' in err && Buffer.isBuffer(err.rawPacket)
135
+ ? redactPacketHead(err.rawPacket.subarray(0, 240).toString('latin1'))
136
+ : '';
137
+ return raw ? `${code} raw=${JSON.stringify(raw)}` : code;
76
138
  }
77
- function parseProxy(proxyUrl) {
78
- try {
79
- const u = new URL(proxyUrl);
80
- const port = parseInt(u.port || (u.protocol === 'https:' ? '443' : '80'), 10);
81
- const auth = u.username
82
- ? 'Basic ' + Buffer.from(`${decodeURIComponent(u.username)}:${decodeURIComponent(u.password)}`).toString('base64')
83
- : undefined;
84
- return { host: u.hostname, port, auth };
139
+ /** Raw-socket 403 for a CONNECT whose host a rule rejects (ADR-0018).
140
+ * Answered on the raw socket BEFORE the 200, so no tunnel and no minted
141
+ * certificate ever exist for a rejected host. */
142
+ const RULE_REJECT_RESPONSE = 'HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n';
143
+ /** Realm for the proxy-auth challenge (407). */
144
+ const PROXY_AUTH_REALM = 'OmniCellRouter';
145
+ /** Raw-socket 407: a CONNECT may arrive before any TLS material, so the only
146
+ * thing we can write is a plain HTTP/1.1 status line. */
147
+ const PROXY_AUTH_REQUIRED_RESPONSE = 'HTTP/1.1 407 Proxy Authentication Required\r\n' +
148
+ `Proxy-Authenticate: Basic realm="${PROXY_AUTH_REALM}"\r\n` +
149
+ 'Content-Length: 0\r\nConnection: close\r\n\r\n';
150
+ /**
151
+ * Dedupe window for pre-admission ledger rows (407 / cap / bad request line).
152
+ * A client failing auth or hammering the cap reconnects in a tight loop; the
153
+ * row is the audit signal, not a per-attempt count — one row per window per
154
+ * host keeps a hostile client from flushing real rows out of the access ring.
155
+ */
156
+ const PRE_ADMISSION_ROW_DEDUPE_MS = CLIENT_TLS_ERROR_DEDUPE_MS;
157
+ const preAdmissionRowAt = new Map();
158
+ /** true = this pre-admission row should be recorded; false = deduped. */
159
+ function shouldRecordPreAdmission(key) {
160
+ const now = Date.now();
161
+ const last = preAdmissionRowAt.get(key) ?? 0;
162
+ if (now - last < PRE_ADMISSION_ROW_DEDUPE_MS)
163
+ return false;
164
+ preAdmissionRowAt.set(key, now);
165
+ if (preAdmissionRowAt.size > 512) {
166
+ // Bounded: drop expired entries instead of growing per hostile host.
167
+ for (const [k, t] of preAdmissionRowAt)
168
+ if (now - t >= PRE_ADMISSION_ROW_DEDUPE_MS)
169
+ preAdmissionRowAt.delete(k);
170
+ if (preAdmissionRowAt.size > 512)
171
+ preAdmissionRowAt.clear();
85
172
  }
86
- catch {
87
- return null;
173
+ return true;
174
+ }
175
+ /** Split a `host[:port]` header value (bracketed IPv6 supported). */
176
+ function splitHostPort(value, defaultPort) {
177
+ const raw = (value || '').trim();
178
+ if (raw.startsWith('[')) {
179
+ const end = raw.indexOf(']');
180
+ const host = raw.slice(1, end);
181
+ const rest = raw.slice(end + 1);
182
+ return { host, port: rest.startsWith(':') ? parseInt(rest.slice(1), 10) || defaultPort : defaultPort };
183
+ }
184
+ const colon = raw.lastIndexOf(':');
185
+ // Exactly one colon ⇒ host:port; a bare IPv6 literal (several colons) has none.
186
+ if (colon > 0 && raw.indexOf(':') === colon) {
187
+ return { host: raw.slice(0, colon), port: parseInt(raw.slice(colon + 1), 10) || defaultPort };
88
188
  }
189
+ return { host: raw, port: defaultPort };
89
190
  }
90
191
  /**
91
- * Open a raw byte pipe to `host:port` through an HTTP CONNECT proxy.
92
- * Resolves with the tunneled socket (paused — consumers must splice/pipe,
93
- * which resumes it; Bun drops listener-less early data, hence the pause).
192
+ * The canonical spelling of a host for an `:authority` / `Host` value: the
193
+ * default HTTPS port is implicit, any other port is kept, and an IPv6 literal
194
+ * is bracketed. Mirrors the upstream rebuild in `h2-forward.ts` (`authorityOf`)
195
+ * so the value a gateway plugin reads matches the one the relay forwards.
94
196
  */
95
- function openViaProxy(proxyUrl, host, port) {
96
- return new Promise((resolve, reject) => {
97
- const p = parseProxy(proxyUrl);
98
- if (!p)
99
- return reject(new Error('invalid outbound proxy url'));
100
- const sock = net.connect(p.port, p.host);
101
- let settled = false;
102
- const timer = setTimeout(() => {
103
- if (!settled) {
104
- settled = true;
105
- sock.destroy();
106
- reject(new Error('outbound proxy connect timeout'));
107
- }
108
- }, 15000);
109
- let buf = '';
110
- const onData = (d) => {
111
- buf += d.toString('latin1');
112
- const idx = buf.indexOf('\r\n\r\n');
113
- if (idx === -1)
114
- return;
115
- settled = true;
116
- clearTimeout(timer);
117
- sock.removeListener('data', onData);
118
- const head = buf.slice(0, idx);
119
- const rest = buf.slice(idx + 4);
120
- if (!/^HTTP\/1\.[01] 200/.test(head)) {
121
- sock.destroy();
122
- reject(new Error(`outbound proxy rejected CONNECT: ${head.split('\r\n')[0] || 'no status'}`));
123
- return;
124
- }
125
- if (rest.length)
126
- sock.unshift(Buffer.from(rest, 'latin1'));
127
- sock.pause();
128
- resolve(sock);
129
- };
130
- sock.on('data', onData);
131
- sock.on('error', (err) => {
132
- if (!settled) {
133
- settled = true;
134
- clearTimeout(timer);
135
- reject(err);
197
+ function authoritySpelling(host, port) {
198
+ const bracketed = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
199
+ return port === 443 ? bracketed : `${bracketed}:${port}`;
200
+ }
201
+ /** Per-response slot carrying the connection's abort hook to `proxyFail`. */
202
+ const MITM_ABORT = Symbol('ocr.forwardProxy.mitmAbort');
203
+ /**
204
+ * Parse a request head that carries an `Upgrade:` handshake, else null.
205
+ *
206
+ * The head is read off the DECRYPTED stream (see `relayUpgrade` for why the
207
+ * runtime's own upgrade event cannot be used). Only the target and the method
208
+ * are extracted — the head itself is relayed byte-verbatim, so nothing about
209
+ * the handshake (subprotocols, extensions, cookies) is ever re-serialized.
210
+ */
211
+ function parseUpgradeHead(head, defaultPort) {
212
+ const lines = head.split('\r\n');
213
+ const requestLine = /^([A-Z]+) (\S+) HTTP\/1\.[01]$/.exec(lines[0] ?? '');
214
+ if (!requestLine)
215
+ return null;
216
+ const headers = {};
217
+ for (const line of lines.slice(1)) {
218
+ const colon = line.indexOf(':');
219
+ if (colon <= 0)
220
+ continue;
221
+ headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
222
+ }
223
+ const upgrade = headers.upgrade;
224
+ const connection = headers.connection;
225
+ const hostHeader = headers.host;
226
+ if (!upgrade || !connection || !hostHeader)
227
+ return null;
228
+ const tokens = String(connection).toLowerCase().split(',').map((v) => v.trim());
229
+ if (!tokens.includes('upgrade'))
230
+ return null;
231
+ // Same port precedence as the request leg (ADR-0018 §3a): an explicit Host
232
+ // port > the CONNECT authority's port > 443. A WebSocket client sends the
233
+ // plain host name, so defaulting to 443 sent an upgrade for a non-443 target
234
+ // to the wrong port.
235
+ const { host, port } = splitHostPort(String(hostHeader), defaultPort);
236
+ if (!host)
237
+ return null;
238
+ return { method: requestLine[1], path: requestLine[2], host, port, headers };
239
+ }
240
+ /** Send the request body upstream: the h2 relay's captured preface first (if
241
+ * any), then the live stream. With a tap, chunks tee into the access log
242
+ * alongside the upstream writes (both consumers see every chunk).
243
+ *
244
+ * A preface can be up to 16 MB (`DEFAULT_MAX_BODY_BYTES`), so it is written
245
+ * under backpressure: the old loop queued every chunk regardless of
246
+ * `write()` returning false, spiking the outgoing buffer by the whole body. */
247
+ function pumpRequestBody(req, upstream, tap, preface) {
248
+ if (!preface) {
249
+ if (tap)
250
+ req.on('data', (d) => tap.onReqChunk(d));
251
+ req.pipe(upstream);
252
+ req.on('error', () => {
253
+ try {
254
+ upstream.destroy();
136
255
  }
256
+ catch { }
137
257
  });
138
- sock.on('connect', () => {
139
- const lines = [
140
- `CONNECT ${host}:${port} HTTP/1.1`,
141
- `Host: ${host}:${port}`,
142
- ...(p.auth ? [`Proxy-Authorization: ${p.auth}`] : []),
143
- '',
144
- '',
145
- ];
146
- sock.write(lines.join('\r\n'));
147
- });
258
+ return;
259
+ }
260
+ // Keep the live listener attached even while the preface drains: a paused
261
+ // stream does not restart itself, and Bun's h1 body may emit before the
262
+ // preface has been flushed. Chunks queue behind the preface to keep order.
263
+ const queue = [...preface.chunks];
264
+ let head = 0;
265
+ let ended = preface.ended;
266
+ let blocked = false;
267
+ let upstreamEnded = false;
268
+ const flush = () => {
269
+ if (blocked)
270
+ return;
271
+ while (head < queue.length) {
272
+ const chunk = queue[head];
273
+ tap?.onReqChunk(chunk);
274
+ const ok = upstream.write(chunk);
275
+ head += 1;
276
+ if (!ok) {
277
+ blocked = true;
278
+ req.pause();
279
+ upstream.once('drain', () => {
280
+ blocked = false;
281
+ req.resume();
282
+ flush();
283
+ });
284
+ return;
285
+ }
286
+ }
287
+ queue.length = 0;
288
+ head = 0;
289
+ if (ended && !upstreamEnded) {
290
+ upstreamEnded = true;
291
+ upstream.end();
292
+ }
293
+ };
294
+ req.on('data', (chunk) => {
295
+ queue.push(chunk);
296
+ flush();
297
+ });
298
+ req.on('end', () => {
299
+ ended = true;
300
+ flush();
148
301
  });
302
+ req.on('error', () => {
303
+ try {
304
+ upstream.destroy();
305
+ }
306
+ catch { }
307
+ });
308
+ flush();
309
+ }
310
+ /** Pipe the upstream response to the client, teeing chunks into the tap. */
311
+ function pipeUpResponse(up, res, tap) {
312
+ if (tap)
313
+ up.on('data', (d) => tap.onResChunk(d));
314
+ up.pipe(res);
149
315
  }
150
- /** Stream one http request to its real target and pipe the response back. */
151
- function forwardTo(req, res, t) {
152
- const proxyUrl = transitProxyFor(t.host, t.port, t.viaProxy);
316
+ /**
317
+ * Relay one decrypted exchange upstream on the h1 leg (direct or through the
318
+ * outbound proxy), tapping both directions when a tap is given. Gateway
319
+ * plugins call this through the host SDK so transport policy lives in core.
320
+ */
321
+ export function forwardTo(req, res, t, upstreamTls) {
322
+ const egress = transitEgressFor(t.host);
323
+ const proxyUrl = transitProxyFor(egress.proxy);
153
324
  if (proxyUrl) {
154
- return t.secure ? forwardSecureViaProxy(req, res, t, proxyUrl) : forwardPlainViaProxy(req, res, t, proxyUrl);
325
+ return t.secure
326
+ ? forwardSecureViaProxy(req, res, t, proxyUrl, upstreamTls)
327
+ : forwardPlainViaProxy(req, res, t, proxyUrl, upstreamTls);
155
328
  }
156
- return forwardDirect(req, res, t);
329
+ return forwardDirect(req, res, t, upstreamTls);
157
330
  }
158
- /** Direct upstream request (no outbound proxy involved). */
159
- function forwardDirect(req, res, t) {
331
+ /**
332
+ * Arm the kernel probe on an upstream socket (see `FORWARD_PROXY_KEEPALIVE_MS`).
333
+ * A relayed leg has no application-level idle timeout — an SSE stream that has
334
+ * gone quiet is indistinguishable from one between tokens — so the peer that
335
+ * disappeared without FIN/RST is reaped by TCP keepalive instead. Failure is
336
+ * non-fatal: some injected test sockets are not real handles.
337
+ */
338
+ /**
339
+ * The synthetic error our hang guard destroys a request with. It carries a CODE
340
+ * so `describeUpstreamFailure` classifies it as a timeout (504) without string
341
+ * matching a message that any future edit could reword.
342
+ */
343
+ function hangGuardError() {
344
+ const err = new Error('upstream timeout');
345
+ err.code = UPSTREAM_TIMEOUT_CODE;
346
+ return err;
347
+ }
348
+ function armUpstreamKeepalive(req) {
349
+ req.on('socket', (s) => {
350
+ try {
351
+ s.setKeepAlive(true, FORWARD_PROXY_KEEPALIVE_MS);
352
+ }
353
+ catch { }
354
+ });
355
+ }
356
+ function forwardDirect(req, res, t, upstreamTls) {
160
357
  return new Promise((resolve) => {
161
358
  const transport = t.secure ? https : http;
162
359
  const upstream = transport.request({
@@ -165,52 +362,92 @@ function forwardDirect(req, res, t) {
165
362
  method: req.method,
166
363
  path: t.path,
167
364
  headers: filterHeaders(req.headers),
168
- ...(t.secure ? { servername: t.host.replace(/^\[|\]$/g, '') } : {}),
365
+ ...(t.secure ? { ...upstreamServernameOption(t.host), ...(upstreamTls.opts || {}) } : {}),
169
366
  }, (up) => {
170
367
  // Headers arrived — the request is alive; clear the hang-protection
171
- // timer so long-lived streams (SSE passthrough) are never killed.
368
+ // timer so long-lived streams (SSE direct forwards) are never killed.
369
+ // Keepalive is what still reaps a half-dead peer (see relay.ts).
172
370
  upstream.setTimeout(0);
173
371
  res.writeHead(up.statusCode || 502, filterHeaders(up.headers));
174
- up.pipe(res);
175
- up.on('end', resolve);
372
+ pipeUpResponse(up, res, t.tap);
373
+ up.on('end', () => {
374
+ t.tap?.finish(up.statusCode, up.headers);
375
+ resolve();
376
+ });
176
377
  up.on('error', () => {
177
378
  try {
178
379
  res.destroy();
179
380
  }
180
381
  catch { }
382
+ t.tap?.finish(up.statusCode, up.headers, 'upstream error mid-response');
181
383
  resolve();
182
384
  });
183
385
  });
386
+ armUpstreamKeepalive(upstream);
184
387
  // Hang protection: a blackholed upstream (packets dropped, no RST — e.g. a
185
388
  // blocked host) would otherwise stall the client forever. Applies only
186
389
  // until response headers arrive.
187
390
  upstream.setTimeout(FORWARD_PROXY_HANG_TIMEOUT_MS, () => {
188
- upstream.destroy(new Error('upstream timeout'));
391
+ upstream.destroy(hangGuardError());
189
392
  });
190
393
  upstream.on('error', (err) => {
191
- const timedOut = err?.message === 'upstream timeout';
192
- try {
193
- if (!res.headersSent)
194
- res.writeHead(timedOut ? 504 : 502, { 'content-type': 'text/plain; charset=utf-8' });
195
- res.end(timedOut ? 'Forward proxy: upstream timed out (target unreachable from this machine?)' : 'Forward proxy: upstream connection failed');
196
- }
197
- catch { }
394
+ const failure = describeUpstreamFailure(err);
395
+ t.tap?.finish(undefined, undefined, failure.note);
396
+ proxyFail(res, failure.status, failure.message);
198
397
  resolve();
199
398
  });
200
- req.pipe(upstream);
201
- req.on('error', () => {
202
- try {
203
- upstream.destroy();
204
- }
205
- catch { }
206
- });
399
+ pumpRequestBody(req, upstream, t.tap, t.preface);
207
400
  });
208
401
  }
209
- function proxyFail(res, code, msg) {
402
+ /**
403
+ * The admission gate's refusal body, spelled ONCE (ADR-0018 §3): every leg
404
+ * that answers 403 for a `reject` row — plain proxy, intercepted inner server,
405
+ * client-gateway relay — says exactly this.
406
+ */
407
+ export const RULE_REJECTED_MESSAGE = 'Forward proxy: host rejected by rule';
408
+ /**
409
+ * Answer with an error envelope and CLOSE the connection.
410
+ *
411
+ * `Connection: close` is not decoration: on Bun an error answer written through
412
+ * the MITM inner server left the client's TLS session open (verified 1.3.14), so
413
+ * a client that waits for the stream to end — every non-streaming HTTP client —
414
+ * hung on a response it had already received in full. An error envelope is
415
+ * terminal; the connection must say so.
416
+ */
417
+ export function proxyFail(res, code, msg) {
210
418
  try {
211
- if (!res.headersSent)
212
- res.writeHead(code, { 'content-type': 'text/plain; charset=utf-8' });
419
+ if (!res.headersSent) {
420
+ res.writeHead(code, { 'content-type': 'text/plain; charset=utf-8', connection: 'close' });
421
+ }
213
422
  res.end(msg);
423
+ // An error envelope is terminal: close the client transport. On the MITM
424
+ // leg the only working handle is the terminator's abort hook (the inner
425
+ // server's `res.socket.end()` is inert on Bun); on the plain-proxy leg the
426
+ // socket is ours to end. Never touch the h2 session socket — it is
427
+ // multiplexed, and the stream's own end is the answer; the h2 guard must
428
+ // run BEFORE the abort hook, which end()s the whole session.
429
+ // Runtime-attached fields the declared `res` type cannot express.
430
+ const resExt = res;
431
+ if (Boolean(resExt.stream))
432
+ return;
433
+ const abort = resExt[MITM_ABORT];
434
+ if (abort) {
435
+ abort();
436
+ return;
437
+ }
438
+ const endSocket = () => {
439
+ try {
440
+ if (res.socket && !res.socket.destroyed)
441
+ res.socket.end();
442
+ }
443
+ catch { }
444
+ };
445
+ // After 'finish', not right after `end()`: the envelope must be on the wire
446
+ // before the socket closes, or the client sees a truncated body.
447
+ if (res.writableFinished)
448
+ endSocket();
449
+ else
450
+ res.once('finish', endSocket);
214
451
  }
215
452
  catch { }
216
453
  }
@@ -219,81 +456,163 @@ function proxyFail(res, code, msg) {
219
456
  * relay → https.request over the relay (TLS runs end-to-end through the
220
457
  * tunnel, so the real target certificate is what gets validated).
221
458
  */
222
- function forwardSecureViaProxy(req, res, t, proxyUrl) {
459
+ function forwardSecureViaProxy(req, res, t, proxyUrl, upstreamTls, attempt = 0) {
460
+ // ES2022 lib here has no Promise.withResolvers; the executor form is the
461
+ // only way to keep `resolve` for the retry re-entry.
223
462
  return new Promise((resolve) => {
224
- openViaProxy(proxyUrl, t.host, t.port)
225
- .then((pipeSock) => {
226
- const relay = net.createServer((c) => {
227
- c.pipe(pipeSock);
228
- pipeSock.pipe(c);
229
- });
230
- const cleanup = () => {
231
- try {
232
- relay.close();
233
- }
234
- catch { }
235
- try {
236
- pipeSock.destroy();
237
- }
238
- catch { }
463
+ // One relay attempt. `retry` re-enters this function with attempt + 1; the
464
+ // returned promise settles exactly once, from whichever attempt finishes.
465
+ const relayOnce = () => {
466
+ // The request stream is consumed ONLY once the origin leg is secure: a
467
+ // retry re-reads `req` from wherever it stands, and a chunk already handed
468
+ // to a dying TLS socket cannot be rewound. Deferring the pump makes
469
+ // "nothing reached the origin" and "nothing left the client" the same
470
+ // fact, so `sentBytes === 0` really is replay-safe. (The outbound proxy's
471
+ // usual failure — a tunnel closed right after CONNECT — dies before
472
+ // `secureConnect`, so this is exactly the case the retry exists for.)
473
+ let originSecure = false;
474
+ let pumping = false;
475
+ let sentBytes = 0;
476
+ const countingTap = {
477
+ onReqChunk: (chunk) => {
478
+ if (originSecure)
479
+ sentBytes += chunk.length;
480
+ t.tap?.onReqChunk(chunk);
481
+ },
482
+ onResChunk: (chunk) => t.tap?.onResChunk(chunk),
483
+ finish: (status, headers, note) => t.tap?.finish(status, headers, note),
239
484
  };
240
- relay.on('error', cleanup);
241
- relay.listen(0, '127.0.0.1', () => {
242
- const relayPort = relay.address().port;
243
- const upstream = https.request({
244
- host: '127.0.0.1',
245
- port: relayPort,
246
- method: req.method,
247
- path: t.path,
248
- headers: filterHeaders(req.headers),
249
- servername: t.host.replace(/^\[|\]$/g, ''),
250
- }, (up) => {
251
- upstream.setTimeout(0);
252
- res.writeHead(up.statusCode || 502, filterHeaders(up.headers));
253
- up.pipe(res);
254
- up.on('end', () => {
255
- cleanup();
256
- resolve();
485
+ const retry = (err) => {
486
+ // A started pump means the client stream may already be partly consumed
487
+ // (and, on the h2 preface path, still has live listeners attached to
488
+ // it) — never replay that, even when no byte reached the origin.
489
+ if (pumping)
490
+ return false;
491
+ if (!shouldRetryOriginLeg(err, { headersSent: res.headersSent, sentBytes, attempts: attempt }))
492
+ return false;
493
+ // Do NOT finish the tap here: `AccessTap.finish` appends one ledger row,
494
+ // and the retry attempt completes the SAME tap (nothing was tapped yet —
495
+ // the pump never started). Finishing here would leave a ghost failed row
496
+ // beside the real one for a single exchange.
497
+ void forwardSecureViaProxy(req, res, t, proxyUrl, upstreamTls, attempt + 1).then(resolve);
498
+ return true;
499
+ };
500
+ openViaProxy(proxyUrl, t.host, t.port)
501
+ .then((pipeSock) => {
502
+ const relay = net.createServer((c) => {
503
+ // A retry tears the tunnel down mid-handshake; an unhandled error on
504
+ // the loopback leg would crash the process instead of failing the
505
+ // attempt.
506
+ c.on('error', () => c.destroy());
507
+ c.pipe(pipeSock);
508
+ pipeSock.pipe(c);
509
+ });
510
+ const cleanup = () => {
511
+ try {
512
+ relay.close();
513
+ }
514
+ catch { }
515
+ try {
516
+ pipeSock.destroy();
517
+ }
518
+ catch { }
519
+ };
520
+ relay.on('error', cleanup);
521
+ relay.listen(0, '127.0.0.1', () => {
522
+ const relayPort = relay.address().port;
523
+ const upstream = https.request({
524
+ host: '127.0.0.1',
525
+ port: relayPort,
526
+ method: req.method,
527
+ path: t.path,
528
+ headers: filterHeaders(req.headers),
529
+ ...upstreamServernameOption(t.host),
530
+ ...(upstreamTls.opts || {}),
531
+ }, (up) => {
532
+ upstream.setTimeout(0);
533
+ res.writeHead(up.statusCode || 502, filterHeaders(up.headers));
534
+ pipeUpResponse(up, res, t.tap);
535
+ up.on('end', () => {
536
+ t.tap?.finish(up.statusCode, up.headers);
537
+ cleanup();
538
+ resolve();
539
+ });
540
+ up.on('error', () => {
541
+ try {
542
+ res.destroy();
543
+ }
544
+ catch { }
545
+ t.tap?.finish(up.statusCode, up.headers, 'upstream error mid-response');
546
+ cleanup();
547
+ resolve();
548
+ });
257
549
  });
258
- up.on('error', () => {
550
+ // Nothing is read from `req` until the origin TLS leg is live (see
551
+ // the pump comment above): `secureConnect` never fires on a tunnel
552
+ // that died at open, so a retry sees the request untouched. A socket
553
+ // reused from the keep-alive pool is already secure.
554
+ // `req` has no listener until then; an inbound abort in that window
555
+ // must not surface as an unhandled 'error'.
556
+ req.on('error', () => {
259
557
  try {
260
- res.destroy();
558
+ upstream.destroy();
261
559
  }
262
560
  catch { }
561
+ });
562
+ const startPump = () => {
563
+ if (pumping)
564
+ return;
565
+ pumping = true;
566
+ pumpRequestBody(req, upstream, countingTap, t.preface);
567
+ };
568
+ upstream.on('socket', (sock) => {
569
+ if (sock.connecting) {
570
+ sock.once('secureConnect', () => {
571
+ originSecure = true;
572
+ startPump();
573
+ });
574
+ }
575
+ else {
576
+ originSecure = true;
577
+ startPump();
578
+ }
579
+ });
580
+ armUpstreamKeepalive(upstream);
581
+ upstream.setTimeout(FORWARD_PROXY_HANG_TIMEOUT_MS, () => {
582
+ upstream.destroy(hangGuardError());
583
+ });
584
+ upstream.on('error', (err) => {
585
+ if (retry(err)) {
586
+ cleanup();
587
+ return;
588
+ }
589
+ const failure = describeUpstreamFailure(err, { proxied: true });
590
+ t.tap?.finish(undefined, undefined, failure.note);
591
+ proxyFail(res, failure.status, failure.message);
263
592
  cleanup();
264
593
  resolve();
265
594
  });
266
595
  });
267
- upstream.setTimeout(FORWARD_PROXY_HANG_TIMEOUT_MS, () => {
268
- upstream.destroy(new Error('upstream timeout'));
269
- });
270
- upstream.on('error', (err) => {
271
- const timedOut = err?.message === 'upstream timeout';
272
- proxyFail(res, timedOut ? 504 : 502, timedOut ? 'Forward proxy: upstream timed out (via outbound proxy)' : 'Forward proxy: upstream connection failed (via outbound proxy)');
273
- cleanup();
274
- resolve();
275
- });
276
- req.pipe(upstream);
277
- req.on('error', () => {
278
- try {
279
- upstream.destroy();
280
- }
281
- catch { }
282
- });
596
+ })
597
+ .catch((err) => {
598
+ // Same rule for the CONNECT itself: nothing was written, so one fresh
599
+ // tunnel is safe. Otherwise report the outbound-proxy class distinctly.
600
+ if (retry(err))
601
+ return;
602
+ t.tap?.finish(undefined, undefined, `outbound proxy connect failed: ${failureLabel(err)}`);
603
+ proxyFail(res, 502, `Forward proxy: outbound proxy connection failed (${failureLabel(err)})`);
604
+ resolve();
283
605
  });
284
- })
285
- .catch((err) => {
286
- proxyFail(res, 502, `Forward proxy: outbound proxy connection failed (${err?.message || err})`);
287
- resolve();
288
- });
606
+ };
607
+ relayOnce();
289
608
  });
290
609
  }
291
610
  /** Plain-HTTP target via an outbound HTTP proxy (absolute-URI request form). */
292
- function forwardPlainViaProxy(req, res, t, proxyUrl) {
611
+ function forwardPlainViaProxy(req, res, t, proxyUrl, upstreamTls) {
293
612
  return new Promise((resolve) => {
294
613
  const p = parseProxy(proxyUrl);
295
614
  if (!p) {
296
- void forwardDirect(req, res, t).then(resolve);
615
+ void forwardDirect(req, res, t, upstreamTls).then(resolve);
297
616
  return;
298
617
  }
299
618
  const headers = filterHeaders(req.headers);
@@ -308,143 +627,421 @@ function forwardPlainViaProxy(req, res, t, proxyUrl) {
308
627
  }, (up) => {
309
628
  upstream.setTimeout(0);
310
629
  res.writeHead(up.statusCode || 502, filterHeaders(up.headers));
311
- up.pipe(res);
312
- up.on('end', resolve);
630
+ pipeUpResponse(up, res, t.tap);
631
+ up.on('end', () => {
632
+ t.tap?.finish(up.statusCode, up.headers);
633
+ resolve();
634
+ });
313
635
  up.on('error', () => {
314
636
  try {
315
637
  res.destroy();
316
638
  }
317
639
  catch { }
640
+ t.tap?.finish(up.statusCode, up.headers, 'upstream error mid-response');
318
641
  resolve();
319
642
  });
320
643
  });
644
+ armUpstreamKeepalive(upstream);
321
645
  upstream.setTimeout(FORWARD_PROXY_HANG_TIMEOUT_MS, () => {
322
- upstream.destroy(new Error('upstream timeout'));
646
+ upstream.destroy(hangGuardError());
323
647
  });
324
648
  upstream.on('error', (err) => {
325
- const timedOut = err?.message === 'upstream timeout';
326
- proxyFail(res, timedOut ? 504 : 502, timedOut ? 'Forward proxy: upstream timed out (via outbound proxy)' : 'Forward proxy: upstream connection failed (via outbound proxy)');
649
+ const failure = describeUpstreamFailure(err, { proxied: true });
650
+ t.tap?.finish(undefined, undefined, failure.note);
651
+ proxyFail(res, failure.status, failure.message);
327
652
  resolve();
328
653
  });
329
- req.pipe(upstream);
330
- req.on('error', () => {
331
- try {
332
- upstream.destroy();
333
- }
334
- catch { }
335
- });
654
+ pumpRequestBody(req, upstream, t.tap, t.preface);
336
655
  });
337
656
  }
338
657
  export async function createForwardProxyServer(deps) {
339
658
  const log = deps.log ?? (() => { });
340
- transitViaOutboundProxy = deps.viaOutboundProxy === true;
659
+ setLiveForwardProxy(deps.liveForwardProxy);
660
+ setBootRules(deps.rules, deps.interceptPosture);
341
661
  const ca = ensureCa(deps.caDir);
342
662
  const minter = new CertMinter(ca);
343
663
  // ── inner HTTP server: parses decrypted MITM traffic, intercept-or-forward ──
344
664
  const inner = http.createServer((req, res) => {
345
- void handleInnerRequest(req, res);
665
+ void handleInnerRequest(req, res, false);
346
666
  });
347
- inner.on('clientError', (_err, socket) => {
667
+ inner.on('clientError', (err, socket) => {
668
+ log(`inner clientError ${describeClientError(err)}`);
348
669
  try {
349
670
  socket.end(CLIENT_ERROR_RESPONSE);
350
671
  }
351
672
  catch { }
352
673
  });
353
- async function handleInnerRequest(req, res) {
674
+ // ── h2 loopback inner (prior-knowledge h2c): the transport-complete half of
675
+ // the MITM leg. EVERY host may reach it (see the ALPN offer below) — h2 is
676
+ // not a vendor feature but the base transport of gRPC/Connect clients, and
677
+ // a proxy that terminates TLS must re-originate the protocol it accepted.
678
+ // Both legs dispatch through the same intercept chain, and the http2
679
+ // compatibility API mirrors the node-http req/res shape the gateway
680
+ // contract consumes.
681
+ const h2Inner = http2.createServer();
682
+ h2Inner.on('request', (req, res) => {
683
+ void handleInnerRequest(req, res, true);
684
+ });
685
+ h2Inner.on('sessionError', (err) => {
686
+ log(`h2 inner session error: ${err?.message || err}`);
687
+ });
688
+ async function handleInnerRequest(req, res, h2Leg) {
354
689
  try {
690
+ // The CONNECT authority's per-connection entry also carries the
691
+ // authenticated caller; the gateway leg reads it via ALS (ADR-0017).
692
+ const mitmTarget = mitmTargets.get(req.socket?.remotePort ?? -1);
693
+ markProxyCaller(req, mitmTarget?.caller);
694
+ // h2 compatibility requests carry the target in `:authority` (there is
695
+ // no `host` header) — accept either so gateway-declined h2 traffic can
696
+ // still fall through to transparent forward.
697
+ const hostHeader = String(req.headers[':authority'] || req.headers.host || '');
698
+ // Port precedence: an explicit Host/`:authority` port > the CONNECT
699
+ // authority's port > 443. HTTPS clients routinely omit the port from the
700
+ // request head (they assume 443), so `CONNECT host:8443` + `Host: host`
701
+ // used to be forwarded to 443 — a silent wrong-port forward. The CONNECT
702
+ // port rides in on the per-connection `mitmTargets` entry (see
703
+ // onDecryptedConnection), keyed by the loopback source port.
704
+ const connectPort = mitmTarget?.port;
705
+ if (mitmTarget) {
706
+ res[MITM_ABORT] = mitmTarget.abort;
707
+ }
708
+ const { host, port } = splitHostPort(hostHeader, connectPort ?? 443);
709
+ // Normalize the h2 `:authority` BEFORE any gateway sees it. An h2 client
710
+ // may write the default port (`gw.test:443`), an h1 client's `Host`
711
+ // normally omits it — without this a gateway plugin reads a different
712
+ // host spelling per negotiated protocol and has to re-parse it. Same
713
+ // rule as the upstream rebuild (`h2-forward.ts` `authorityOf`): 443 is
714
+ // implicit, every other port is kept.
715
+ if (h2Leg && host && typeof req.headers[':authority'] === 'string') {
716
+ req.headers[':authority'] = authoritySpelling(host, port);
717
+ }
355
718
  if (await deps.intercept(req, res))
356
719
  return;
357
- const hostHeader = String(req.headers.host || '');
358
- let host = hostHeader;
359
- let port = 443;
360
- if (hostHeader.startsWith('[')) {
361
- const i = hostHeader.indexOf(']');
362
- host = hostHeader.slice(1, i);
363
- const rest = hostHeader.slice(i + 1);
364
- if (rest.startsWith(':'))
365
- port = parseInt(rest.slice(1), 10) || 443;
366
- }
367
- else if (hostHeader.includes(':')) {
368
- const [h, p] = hostHeader.split(':');
369
- host = h;
370
- port = parseInt(p, 10) || 443;
371
- }
372
720
  if (!host) {
373
- res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
374
- res.end('Forward proxy: missing Host header');
721
+ proxyFail(res, 400, 'Forward proxy: missing Host header');
722
+ return;
723
+ }
724
+ const tap = createAccessTap({
725
+ host,
726
+ port,
727
+ method: req.method,
728
+ path: req.url || '/',
729
+ wire: h2Leg ? 'h2' : String(req.headers.upgrade ?? '').toLowerCase().includes('websocket') ? 'ws' : 'h1',
730
+ // h2 pseudo-headers are transport framing, not wire headers — the row
731
+ // already carries host/method/path from them.
732
+ requestHeaders: h2Leg
733
+ ? Object.fromEntries(Object.entries(req.headers).filter(([k]) => !k.startsWith(':')))
734
+ : req.headers,
735
+ });
736
+ const target = { host, port, path: req.url || '/', secure: true, tap };
737
+ // Rule admission on the MITM leg: the inner Host can differ from the
738
+ // CONNECT target, so the same gate runs here (403 lands in the ledger).
739
+ if (isRuleRejected(host)) {
740
+ tap?.finish(403, undefined, 'rejected by rule');
741
+ proxyFail(res, 403, RULE_REJECTED_MESSAGE);
375
742
  return;
376
743
  }
377
- await forwardTo(req, res, { host, port, path: req.url || '/', secure: true });
744
+ // Protocol fidelity: an h2 client is answered upstream over h2 (gRPC and
745
+ // Connect cannot survive an h1 hop). `forwardH2` reports false when the
746
+ // upstream is not h2 — nothing has reached the client at that point, so
747
+ // the h1 forwarder takes over (ADR-0017 §3).
748
+ const upstreamTls = resolveUpstreamTls(deps.upstreamTls);
749
+ if (h2Leg) {
750
+ const relay = await forwardH2(req, res, target, upstreamTls);
751
+ if (relay.owned)
752
+ return;
753
+ target.preface = relay.preface;
754
+ }
755
+ await forwardTo(req, res, target, upstreamTls);
378
756
  }
379
757
  catch {
380
- try {
381
- if (!res.headersSent)
382
- res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
383
- res.end('Forward proxy error');
384
- }
385
- catch { }
758
+ proxyFail(res, 502, 'Forward proxy error');
386
759
  }
387
760
  }
388
761
  // ── per-host TLS terminators (explicit certs; SNICallback unsupported on Bun) ──
389
- const hostServers = new Map();
390
- const hostPorts = new Map();
391
- function hostTlsPort(host) {
392
- const existing = hostPorts.get(host);
393
- if (existing)
394
- return existing;
395
- const p = new Promise((resolve, reject) => {
762
+ // EVERY host advertises h2; the ORDER is what differs. Bun honours the
763
+ // SERVER's preference (verified: server ['http/1.1','h2'] + client
764
+ // ['h2','http/1.1'] negotiates http/1.1), so:
765
+ // * unclaimed host → ['http/1.1','h2']: dual-offer clients (curl, browsers,
766
+ // most SDKs) keep the h1 path untouched, while h2-only clients
767
+ // (gRPC/Connect — Cursor included) get h2 instead of a broken h1
768
+ // downgrade. h1 interception therefore has ZERO regression surface.
769
+ // * gateway-claimed host → ['h2','http/1.1']: the plugin wants h2 even
770
+ // from dual-offer clients (it speaks the vendor's h2 wire).
771
+ // The negotiated protocol is only a hint — the preface sniff below is the
772
+ // authority. Ports are assigned at the bottom (before any CONNECT arrives).
773
+ let innerH1Port = 0;
774
+ let innerH2Port = 0;
775
+ // Per-host terminators, LRU-bounded (see MAX_HOST_TERMINATORS): insertion
776
+ // order IS the LRU order — a hit re-inserts. Eviction closes the listener
777
+ // only, never an established connection (server.close stops accepting).
778
+ const terminators = new Map();
779
+ const pendingTerminators = new Map();
780
+ /**
781
+ * Evicted terminators still finishing their grace window (see
782
+ * evictTerminators). Bounded: the whole point of the LRU is a finite fd
783
+ * budget, so draining may not become a second unbounded cache.
784
+ */
785
+ const drainingTerminators = new Map();
786
+ /**
787
+ * Per-connection CONNECT authority, keyed by the loopback source port of the
788
+ * connection this proxy dials into the inner server (= the inner server's
789
+ * `remotePort`). Entries live exactly as long as their connection.
790
+ */
791
+ const mitmTargets = new Map();
792
+ function hostTlsPort(host, targetPort, caller) {
793
+ const h2First = listGatewayHosts().has(host);
794
+ // Cache by host + CONNECT port + ALPN mode + authenticated key: a runtime
795
+ // gateway install flips a host's ALPN order, a second CONNECT to another
796
+ // port of the same host needs its own authority context, and two keys must
797
+ // never share a terminator — the decrypted connection inherits the key of
798
+ // the CONNECT that created it (ADR-0017 attribution).
799
+ const cacheKey = `${host}:${targetPort}|${h2First ? 'gateway' : 'plain'}|${caller?.keyId ?? ''}`;
800
+ const live = terminators.get(cacheKey);
801
+ if (live) {
802
+ terminators.delete(cacheKey);
803
+ terminators.set(cacheKey, live);
804
+ return Promise.resolve(live.port);
805
+ }
806
+ const inflight = pendingTerminators.get(cacheKey);
807
+ if (inflight)
808
+ return inflight.then((t) => t.port);
809
+ const created = createTerminator(host, targetPort, h2First, cacheKey, caller).then((t) => {
810
+ pendingTerminators.delete(cacheKey);
811
+ return t;
812
+ }, (err) => {
813
+ // Never cache a FAILED creation — a transient listen error (e.g. an
814
+ // ephemeral-port collision) must not permanently degrade this host to
815
+ // the blind-tunnel fallback; the next connection retries from scratch.
816
+ pendingTerminators.delete(cacheKey);
817
+ throw err;
818
+ });
819
+ pendingTerminators.set(cacheKey, created);
820
+ return created.then((t) => t.port);
821
+ }
822
+ function createTerminator(host, targetPort, h2First, cacheKey, caller) {
823
+ return new Promise((resolve, reject) => {
396
824
  const { key, cert } = minter.get(host);
397
- const srv = tls.createServer({ key, cert, ALPNProtocols: ['http/1.1'] }, (tlsSock) => {
398
- // Attach SYNCHRONOUSLY — a Bun TLSSocket may drop data that arrives
399
- // with no listener; buffer until the loopback conn is ready.
400
- const pending = [];
401
- let conn = null;
402
- tlsSock.on('data', (d) => {
403
- if (conn) {
404
- if (!conn.write(d)) {
405
- tlsSock.pause();
406
- conn.once('drain', () => tlsSock.resume());
407
- }
408
- }
409
- else {
410
- pending.push(d);
825
+ const target = { host, port: targetPort, ...(caller ? { caller } : {}) };
826
+ let clientErrorLoggedAt = 0;
827
+ /** One ledger row per dedupe window for a client that never got a request through. */
828
+ const reportClientFailure = (reason) => {
829
+ const now = Date.now();
830
+ if (now - clientErrorLoggedAt < CLIENT_TLS_ERROR_DEDUPE_MS)
831
+ return;
832
+ clientErrorLoggedAt = now;
833
+ recordProxyConnect({ host, port: targetPort, note: `connect (${reason})` });
834
+ };
835
+ const srv = tls.createServer({ key, cert, ALPNProtocols: h2First ? ['h2', 'http/1.1'] : ['http/1.1', 'h2'] }, (tlsSock) => onDecryptedConnection(tlsSock, target, reportClientFailure));
836
+ // A client that REJECTS our leaf (certificate pinning, a missing CA in its
837
+ // trust store) fails inside the handshake and never sends a request, so
838
+ // this is the only place that failure is visible. The operator's question
839
+ // is always "why does this app not work through the proxy" — a console
840
+ // log line nobody tails is not an answer, so it lands in the ledger.
841
+ //
842
+ // Bun 1.3.14 does NOT emit `tlsClientError` when the client rejects the
843
+ // certificate (verified: the server sees `secureConnection` and then a
844
+ // bare socket close), so the abort is also caught on the decrypted stream
845
+ // (see onDecryptedConnection). Both paths share this dedupe: a pinned
846
+ // client retries in a tight loop and would otherwise evict every real row
847
+ // from the ring.
848
+ srv.on('tlsClientError', (e) => {
849
+ const message = String(e?.message || e);
850
+ log(`tlsClientError ${host}:${targetPort}: ${message}`);
851
+ reportClientFailure(`client TLS handshake failed: ${message}`);
852
+ });
853
+ srv.on('error', reject);
854
+ srv.listen(0, '127.0.0.1', () => {
855
+ const terminator = {
856
+ srv,
857
+ port: srv.address().port,
858
+ state: 'live',
859
+ };
860
+ terminators.set(cacheKey, terminator);
861
+ evictTerminators();
862
+ resolve(terminator);
863
+ });
864
+ });
865
+ }
866
+ /**
867
+ * Retire the LRU tail into a DRAINING set instead of closing it outright.
868
+ *
869
+ * `srv.close()` stops accepting but leaves established connections alone —
870
+ * however a CONNECT that already resolved this terminator's port and has not
871
+ * dialed yet would hit ECONNREFUSED and degrade to a blind tunnel, silently
872
+ * losing interception for that exchange. The grace window covers exactly that
873
+ * window; a drained terminator is never reused for a NEW CONNECT (it is out
874
+ * of `terminators`, so `hostTlsPort` misses and mints a fresh one).
875
+ */
876
+ function evictTerminators() {
877
+ const bound = deps.maxHostTerminators ?? MAX_HOST_TERMINATORS;
878
+ while (terminators.size > bound) {
879
+ const oldest = terminators.keys().next();
880
+ if (oldest.done)
881
+ return;
882
+ const victim = terminators.get(oldest.value);
883
+ terminators.delete(oldest.value);
884
+ if (!victim)
885
+ continue;
886
+ victim.state = 'draining';
887
+ drainingTerminators.set(oldest.value, victim);
888
+ const timer = setTimeout(() => {
889
+ drainingTerminators.delete(oldest.value);
890
+ try {
891
+ victim.srv.close();
892
+ }
893
+ catch { }
894
+ }, TERMINATOR_DRAIN_MS);
895
+ // Never hold the process open for a drained listener.
896
+ timer.unref?.();
897
+ while (drainingTerminators.size > MAX_DRAINING_TERMINATORS) {
898
+ const stale = drainingTerminators.keys().next();
899
+ if (stale.done)
900
+ break;
901
+ const forced = drainingTerminators.get(stale.value);
902
+ drainingTerminators.delete(stale.value);
903
+ try {
904
+ forced?.srv.close();
905
+ }
906
+ catch { }
907
+ }
908
+ log(`terminator evicted (LRU bound ${bound}), draining: ${oldest.value}`);
909
+ }
910
+ }
911
+ /**
912
+ * Decrypted-stream entry for one TLS session: decide h2 / h1 / Upgrade, then
913
+ * hand the bytes on.
914
+ *
915
+ * Attach SYNCHRONOUSLY — a Bun TLSSocket may drop data that arrives with no
916
+ * listener; buffer until the loopback conn is ready. Bun does not reliably
917
+ * expose alpnProtocol on the server side at callback time, so the negotiated
918
+ * ALPN is only a hint — the h2 connection preface ('PRI * HTTP/2.0') is the
919
+ * authority. On the h1 path the request head is buffered until it is
920
+ * complete so an `Upgrade:` handshake can be caught BEFORE the inner server
921
+ * (relayUpgrade); a head that outgrows MAX_HEAD_BYTES goes to the inner
922
+ * server unexamined.
923
+ */
924
+ function onDecryptedConnection(tlsSock, target, reportClientFailure) {
925
+ /** Client plaintext, in arrival order, regardless of when the hop is ready. */
926
+ const relay = new OrderedRelay();
927
+ let conn = null;
928
+ let decided = false;
929
+ /**
930
+ * True once the loopback hop to the inner server is CONNECTED. Until then
931
+ * every decrypted chunk is held by `relay`, because `conn` exists
932
+ * (net.connect returns before it connects) and writing to it would QUEUE
933
+ * bytes ahead of the buffered head. That inversion is not cosmetic: a body
934
+ * arrives as many chunks, so the tail would reach the parser before the
935
+ * request line and the inner server answers 400 to a message it never saw —
936
+ * the client's "request failed with empty body (code 400)" on large prompts.
937
+ */
938
+ let connected = false;
939
+ /** Decrypted bytes seen so far — zero at close means the client never spoke. */
940
+ let decryptedBytes = 0;
941
+ /**
942
+ * Set when the inner request answered with a terminal error envelope: the
943
+ * client transport is closed as soon as that envelope has been handed over.
944
+ * The next chunk the inner server emits IS the envelope, so this is exact —
945
+ * no flush timing guesswork (an immediate `end()` truncated the response;
946
+ * the inner server's own socket `end()` is inert on Bun).
947
+ */
948
+ let abortRequested = false;
949
+ let abortTimer;
950
+ const finishAbort = () => {
951
+ if (abortTimer !== undefined) {
952
+ clearTimeout(abortTimer);
953
+ abortTimer = undefined;
954
+ }
955
+ if (!abortRequested)
956
+ return;
957
+ abortRequested = false;
958
+ try {
959
+ tlsSock.end();
960
+ }
961
+ catch { }
962
+ };
963
+ /** Whatever the relay hands over goes to the inner hop, in order. */
964
+ const forward = (chunk) => {
965
+ if (!conn.write(chunk)) {
966
+ tlsSock.pause();
967
+ conn.once('drain', () => tlsSock.resume());
968
+ }
969
+ };
970
+ const onDecrypted = (d) => {
971
+ decryptedBytes += d.length;
972
+ relay.push(d);
973
+ if (connected || decided)
974
+ return;
975
+ const buf = relay.snapshot();
976
+ const isH2 = tlsSock.alpnProtocol === 'h2' || buf.subarray(0, 14).toString('latin1') === 'PRI * HTTP/2.0';
977
+ if (!isH2) {
978
+ const headEnd = buf.indexOf('\r\n\r\n');
979
+ if (headEnd === -1) {
980
+ // No complete head yet: keep buffering ONLY while the bytes still
981
+ // look like an HTTP/1 request — a non-HTTP tunnel payload (or a head
982
+ // past MAX_HEAD_BYTES) must not wait for a head that never arrives.
983
+ const lineEnd = buf.indexOf('\r\n');
984
+ const firstLine = (lineEnd === -1 ? buf.subarray(0, 64) : buf.subarray(0, lineEnd)).toString('latin1');
985
+ const looksHttp = lineEnd === -1
986
+ ? /^[A-Z]{1,8}( [^\r\n]*)?$/.test(firstLine) // still mid request-line
987
+ : /^[A-Z]+ \S+ HTTP\/1\.[01]$/.test(firstLine);
988
+ if (buf.length <= MAX_HEAD_BYTES && looksHttp)
989
+ return;
990
+ }
991
+ else {
992
+ const parsed = parseUpgradeHead(buf.subarray(0, headEnd + 4).toString('latin1'), target.port);
993
+ if (parsed) {
994
+ decided = true;
995
+ tlsSock.removeListener('data', onDecrypted);
996
+ void relayUpgrade(tlsSock, buf, parsed);
997
+ return;
411
998
  }
999
+ }
1000
+ }
1001
+ decided = true;
1002
+ conn = net.connect(isH2 ? innerH2Port : innerH1Port, '127.0.0.1', () => {
1003
+ // Register the CONNECT target BEFORE the first byte reaches the inner
1004
+ // server — the inner request must never run without its authority
1005
+ // context. The key is this loopback connection's source port, which is
1006
+ // exactly the inner server's `remotePort` for the same TCP connection.
1007
+ const localPort = conn.localPort;
1008
+ if (localPort) {
1009
+ mitmTargets.set(localPort, {
1010
+ host: target.host,
1011
+ port: target.port,
1012
+ ...(target.caller ? { caller: target.caller } : {}),
1013
+ abort: () => {
1014
+ if (abortRequested)
1015
+ return;
1016
+ abortRequested = true;
1017
+ // Safety net: an envelope that never produces a chunk (or a
1018
+ // response already mid-flight) still closes, just not instantly.
1019
+ abortTimer = setTimeout(finishAbort, MITM_ABORT_FLUSH_MS);
1020
+ abortTimer.unref?.();
1021
+ },
1022
+ });
1023
+ }
1024
+ connected = true;
1025
+ relay.attach(forward, () => {
1026
+ connected = true;
412
1027
  });
413
- tlsSock.on('end', () => {
414
- try {
415
- conn?.end();
1028
+ conn.on('data', (d2) => {
1029
+ if (!tlsSock.write(d2)) {
1030
+ conn.pause();
1031
+ tlsSock.once('drain', () => {
1032
+ conn.resume();
1033
+ finishAbort();
1034
+ });
1035
+ return;
416
1036
  }
417
- catch { }
1037
+ finishAbort();
418
1038
  });
419
- tlsSock.on('error', () => {
1039
+ conn.on('end', () => {
420
1040
  try {
421
- conn?.destroy();
1041
+ tlsSock.end();
422
1042
  }
423
1043
  catch { }
424
1044
  });
425
- conn = net.connect(innerPort, '127.0.0.1', () => {
426
- for (const d of pending)
427
- conn.write(d);
428
- pending.length = 0;
429
- conn.on('data', (d) => {
430
- if (!tlsSock.write(d)) {
431
- conn.pause();
432
- tlsSock.once('drain', () => conn.resume());
433
- }
434
- });
435
- conn.on('end', () => {
436
- try {
437
- tlsSock.end();
438
- }
439
- catch { }
440
- });
441
- conn.on('error', () => {
442
- try {
443
- tlsSock.destroy();
444
- }
445
- catch { }
446
- });
447
- });
448
1045
  conn.on('error', () => {
449
1046
  try {
450
1047
  tlsSock.destroy();
@@ -452,37 +1049,113 @@ export async function createForwardProxyServer(deps) {
452
1049
  catch { }
453
1050
  });
454
1051
  });
455
- srv.on('tlsClientError', (e) => log(`tlsClientError ${host}: ${e?.message || e}`));
456
- srv.on('error', reject);
457
- srv.listen(0, '127.0.0.1', () => {
458
- hostServers.set(host, srv);
459
- resolve(srv.address().port);
1052
+ conn.on('close', () => {
1053
+ const localPort = conn?.localPort;
1054
+ if (localPort)
1055
+ mitmTargets.delete(localPort);
460
1056
  });
1057
+ conn.on('error', () => {
1058
+ try {
1059
+ tlsSock.destroy();
1060
+ }
1061
+ catch { }
1062
+ });
1063
+ };
1064
+ tlsSock.on('data', onDecrypted);
1065
+ tlsSock.on('end', () => {
1066
+ try {
1067
+ conn?.end();
1068
+ }
1069
+ catch { }
461
1070
  });
462
- const guarded = p.catch((err) => {
463
- // Never cache a FAILED creation — a transient listen error (e.g. an
464
- // ephemeral-port collision) must not permanently degrade this host to
465
- // the blind-tunnel fallback; the next connection retries from scratch.
466
- hostPorts.delete(host);
467
- throw err;
1071
+ // The pinning signal Bun actually gives us: a TLS session that closes
1072
+ // WITHOUT a single decrypted byte. A client that rejects our leaf aborts
1073
+ // right after the handshake, so no request head ever arrives.
1074
+ tlsSock.on('close', () => {
1075
+ if (decryptedBytes === 0) {
1076
+ reportClientFailure('client closed the intercepted TLS session before any request (certificate rejected or client abort)');
1077
+ }
1078
+ });
1079
+ tlsSock.on('error', () => {
1080
+ try {
1081
+ conn?.destroy();
1082
+ }
1083
+ catch { }
468
1084
  });
469
- hostPorts.set(host, guarded);
470
- return guarded;
471
1085
  }
472
1086
  // ── tunnel (no decryption) ──
473
- function tunnel(socket, host, port, replay, viaProxy) {
474
- // Per-host egress: bypass entries carry their own viaProxy flag (object
475
- // form); undefined (no-SNI/MITM-failure fallback) = global flag.
476
- const proxyUrl = transitProxyFor(host, port, viaProxy);
1087
+ function tunnel(socket, host, port, replay) {
1088
+ // Egress comes from the ordered rule table (ADR-0018).
1089
+ const egress = transitEgressFor(host);
1090
+ const proxyUrl = transitProxyFor(egress.proxy);
1091
+ // Tunnel observation (ADR-0020): a blind tunnel is opaque BY DESIGN, so the
1092
+ // identity we can see without decrypting (SNI, offered ALPN), the byte
1093
+ // totals and the lifetime are the whole story. The peek rides the relay's
1094
+ // own tap — it can never steal bytes from the splice.
1095
+ const started = Date.now();
1096
+ let reqBytes = replay?.length ?? 0;
1097
+ let respBytes = 0;
1098
+ let identity;
1099
+ let identityDone = false;
1100
+ const hello = [];
1101
+ let helloTotal = 0;
1102
+ const observe = (dir, chunk) => {
1103
+ if (dir === 'b2a') {
1104
+ respBytes += chunk.length;
1105
+ return;
1106
+ }
1107
+ reqBytes += chunk.length;
1108
+ if (identityDone)
1109
+ return;
1110
+ hello.push(chunk);
1111
+ helloTotal += chunk.length;
1112
+ const peek = peekClientHello(Buffer.concat(hello, helloTotal));
1113
+ if (!peek.isTls) {
1114
+ identityDone = true;
1115
+ identity = 'not tls';
1116
+ return;
1117
+ }
1118
+ if (peek.complete || helloTotal > MAX_HELLO_BYTES) {
1119
+ identityDone = true;
1120
+ // The peek buffer is only needed until the identity is known; a tunnel
1121
+ // can outlive it by hours, so do not pin the hello bytes.
1122
+ hello.length = 0;
1123
+ if (!peek.complete)
1124
+ return;
1125
+ const bits = [peek.sni ? `sni ${peek.sni}` : 'no sni'];
1126
+ // Space-separated: a protocol id may itself contain '/', so a slash
1127
+ // separator would make "h2" + "http/1.1" unreadable.
1128
+ if (peek.alpn?.length)
1129
+ bits.push(`alpn ${peek.alpn.join(' ')}`);
1130
+ identity = bits.join(', ');
1131
+ }
1132
+ };
1133
+ let closed = false;
1134
+ const closeRow = (note) => {
1135
+ if (closed)
1136
+ return;
1137
+ closed = true;
1138
+ recordProxyTunnel({
1139
+ host,
1140
+ port,
1141
+ note: identity ? `${note}, ${identity}` : note,
1142
+ reqBytes,
1143
+ respBytes,
1144
+ durationMs: Date.now() - started,
1145
+ });
1146
+ };
1147
+ socket.on('close', () => closeRow('connect (tunnel closed)'));
477
1148
  if (proxyUrl) {
478
1149
  openViaProxy(proxyUrl, host, port)
479
1150
  .then((up) => {
1151
+ up.on('close', () => closeRow('connect (tunnel via outbound proxy closed)'));
480
1152
  if (replay && replay.length)
481
1153
  up.write(replay);
482
- splice(socket, up);
1154
+ splice(socket, up, observe);
483
1155
  })
484
1156
  .catch((err) => {
485
1157
  log(`tunnel via outbound proxy failed for ${host}:${port}: ${err?.message || err}`);
1158
+ closeRow(`connect (tunnel failed: outbound proxy ${err?.code || err?.message || err})`);
486
1159
  try {
487
1160
  socket.destroy();
488
1161
  }
@@ -493,8 +1166,10 @@ export async function createForwardProxyServer(deps) {
493
1166
  const up = net.connect(port, host, () => {
494
1167
  if (replay && replay.length)
495
1168
  up.write(replay);
496
- splice(socket, up);
1169
+ splice(socket, up, observe);
497
1170
  });
1171
+ up.on('close', () => closeRow('connect (tunnel closed)'));
1172
+ up.on('error', (err) => closeRow(`connect (tunnel failed: ${err?.code || err?.message || err})`));
498
1173
  up.on('error', () => {
499
1174
  try {
500
1175
  socket.destroy();
@@ -508,16 +1183,263 @@ export async function createForwardProxyServer(deps) {
508
1183
  catch { }
509
1184
  });
510
1185
  }
1186
+ /**
1187
+ * WebSocket / generic `Upgrade:` relay on the MITM leg.
1188
+ *
1189
+ * Bun's node:http 'upgrade' event is NOT usable (verified on 1.3.14: the
1190
+ * socket handed to the handler swallows every write and the parser keeps
1191
+ * running, answering 505 to whatever the client sends next), so the
1192
+ * handshake is caught on the DECRYPTED stream before it reaches the inner
1193
+ * server and relayed byte-verbatim: request head (+ any bytes the client
1194
+ * already pipelined after it) → origin socket, then a raw bidirectional
1195
+ * splice. Nothing is re-serialized — an upgrade is a single hop, so the
1196
+ * client's own handshake headers are exactly what the origin must see, and
1197
+ * any upgrade protocol rides this path, not just WebSocket.
1198
+ *
1199
+ * Non-TLS `ws://` through the plain proxy port is NOT covered: that leg
1200
+ * never decrypts, and the same runtime gap blocks its 'upgrade' event.
1201
+ */
1202
+ async function relayUpgrade(tlsSock, head, parsed) {
1203
+ const { host, port } = parsed;
1204
+ // A client gateway may OWN the handshake (a WS-native vendor wire). Without
1205
+ // this hook an upgrade on a claimed host is relayed verbatim and the plugin
1206
+ // never sees it — the same host would be handled for requests but not for
1207
+ // sockets. Returning false (or throwing) falls through to the relay.
1208
+ const gateway = findGateway({ method: parsed.method, url: parsed.path, headers: parsed.headers });
1209
+ if (gateway?.handleUpgrade) {
1210
+ try {
1211
+ const owned = await gateway.handleUpgrade({
1212
+ socket: tlsSock,
1213
+ head,
1214
+ host,
1215
+ port,
1216
+ method: parsed.method,
1217
+ path: parsed.path,
1218
+ headers: parsed.headers,
1219
+ });
1220
+ if (owned)
1221
+ return;
1222
+ }
1223
+ catch {
1224
+ // Ownership was ambiguous — never leave the client hanging on a socket
1225
+ // nobody drives; the gateway already had its chance to answer.
1226
+ try {
1227
+ tlsSock.destroy();
1228
+ }
1229
+ catch { }
1230
+ return;
1231
+ }
1232
+ }
1233
+ const tap = createAccessTap({
1234
+ host,
1235
+ port,
1236
+ method: parsed.method,
1237
+ path: parsed.path,
1238
+ requestHeaders: parsed.headers,
1239
+ });
1240
+ let status;
1241
+ let finished = false;
1242
+ const finish = (note) => {
1243
+ if (finished)
1244
+ return;
1245
+ finished = true;
1246
+ tap?.finish(status, undefined, note);
1247
+ };
1248
+ // Only answer with an error envelope while the origin has said nothing —
1249
+ // once its bytes are flowing, the client owns the stream.
1250
+ const fail = (note) => {
1251
+ finish(note);
1252
+ if (status !== undefined) {
1253
+ try {
1254
+ tlsSock.destroy();
1255
+ }
1256
+ catch { }
1257
+ return;
1258
+ }
1259
+ try {
1260
+ tlsSock.write(`HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\nForward proxy: ${note}`);
1261
+ tlsSock.end();
1262
+ }
1263
+ catch { }
1264
+ };
1265
+ /**
1266
+ * The same answer, built from a classified origin failure (ADR-0019): status,
1267
+ * client-facing sentence and ledger note all come from
1268
+ * `describeUpstreamFailure`, so an upgrade leg reports a TLS trust failure
1269
+ * exactly like the h1 and h2 legs do.
1270
+ */
1271
+ const failWith = (failure) => {
1272
+ finish(failure.note);
1273
+ if (status !== undefined) {
1274
+ try {
1275
+ tlsSock.destroy();
1276
+ }
1277
+ catch { }
1278
+ return;
1279
+ }
1280
+ try {
1281
+ tlsSock.write(`HTTP/1.1 ${failure.status} ${failure.status === 504 ? 'Gateway Timeout' : 'Bad Gateway'}\r\n` +
1282
+ 'Content-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n' +
1283
+ failure.message);
1284
+ tlsSock.end();
1285
+ }
1286
+ catch { }
1287
+ };
1288
+ const onOrigin = (origin) => {
1289
+ // Hang guard until the origin answers: a blackholed upgrade must not
1290
+ // hold the client's socket open forever. Cleared on the first byte so a
1291
+ // long-lived WebSocket is never killed.
1292
+ const hang = setTimeout(() => {
1293
+ try {
1294
+ origin.destroy();
1295
+ }
1296
+ catch { }
1297
+ fail('upgrade upstream timed out');
1298
+ }, FORWARD_PROXY_HANG_TIMEOUT_MS);
1299
+ // Frame-level observation (ADR-0020): the relay stays byte-verbatim, the
1300
+ // observer only counts what crosses it. Frames begin after the origin
1301
+ // response head, so the first chunk is split at its CRLFCRLF marker.
1302
+ const ws = createWsObserver();
1303
+ let responseHeadSeen = false;
1304
+ // The response head is accumulated across chunks: an origin may split it,
1305
+ // and the frames start at its end — guessing from a single chunk either
1306
+ // lost the status or fed handshake bytes to the frame parser.
1307
+ let responseHead = '';
1308
+ const noteFor = () => (status === 101 ? ws.note() : '');
1309
+ origin.on('data', (d) => {
1310
+ clearTimeout(hang);
1311
+ tap?.onResChunk(d);
1312
+ if (!responseHeadSeen) {
1313
+ responseHead += d.toString('latin1');
1314
+ const end = responseHead.indexOf('\r\n\r\n');
1315
+ if (end === -1) {
1316
+ if (responseHead.length > MAX_HEAD_BYTES)
1317
+ responseHeadSeen = true;
1318
+ return;
1319
+ }
1320
+ responseHeadSeen = true;
1321
+ if (status === undefined) {
1322
+ const m = /^HTTP\/1\.[01] (\d{3})/.exec(responseHead.slice(0, 16));
1323
+ if (m)
1324
+ status = Number(m[1]);
1325
+ }
1326
+ const rest = responseHead.slice(end + 4);
1327
+ if (rest.length)
1328
+ ws.push('s2c', Buffer.from(rest, 'latin1'));
1329
+ return;
1330
+ }
1331
+ ws.push('s2c', d);
1332
+ });
1333
+ tlsSock.on('data', (d) => {
1334
+ tap?.onReqChunk(d);
1335
+ ws.push('c2s', d);
1336
+ });
1337
+ origin.on('close', () => {
1338
+ clearTimeout(hang);
1339
+ finish(noteFor());
1340
+ });
1341
+ tlsSock.on('close', () => {
1342
+ clearTimeout(hang);
1343
+ finish(noteFor());
1344
+ });
1345
+ origin.write(head);
1346
+ splice(tlsSock, origin);
1347
+ };
1348
+ const egress = transitEgressFor(host);
1349
+ const proxyUrl = transitProxyFor(egress.proxy);
1350
+ const upstreamTls = resolveUpstreamTls(deps.upstreamTls).opts;
1351
+ if (proxyUrl) {
1352
+ openViaProxy(proxyUrl, host, port)
1353
+ .then((tunnelSock) => {
1354
+ try {
1355
+ const origin = tls.connect({ socket: tunnelSock, ...upstreamServernameOption(host), ...(upstreamTls || {}) }, () => onOrigin(origin));
1356
+ origin.once('error', (err) => failWith(describeUpstreamFailure(err, { proxied: true })));
1357
+ }
1358
+ catch {
1359
+ // A synchronous TLS-option throw (bad servername, bad material) must
1360
+ // not escape a socket callback — answer the client instead.
1361
+ try {
1362
+ tunnelSock.destroy();
1363
+ }
1364
+ catch { }
1365
+ fail('upgrade upstream TLS setup failed');
1366
+ }
1367
+ })
1368
+ .catch((err) => fail(`upgrade outbound proxy connection failed${err?.code ? ` (${err.code})` : ''}`));
1369
+ return;
1370
+ }
1371
+ try {
1372
+ const origin = tls.connect({ host, port, ...upstreamServernameOption(host), ...(upstreamTls || {}) }, () => onOrigin(origin));
1373
+ origin.once('error', (err) => failWith(describeUpstreamFailure(err)));
1374
+ }
1375
+ catch {
1376
+ fail('upgrade upstream TLS setup failed');
1377
+ }
1378
+ }
511
1379
  // ── CONNECT: peek ClientHello → MITM, else blind tunnel ──
512
1380
  function handleConnect(req, socket, head) {
513
- const [rawHost, rawPort] = String(req.url || '').split(':');
514
- const port = parseInt(rawPort || '443', 10) || 443;
1381
+ // Bracket-aware: `[::1]:8443` is a valid authority, and `rawHost` becomes
1382
+ // the CERTIFICATE IDENTITY for a no-SNI client (see the MITM branch), so a
1383
+ // naive `split(':')` would mint a leaf for `[`.
1384
+ const { host: rawHost, port } = splitHostPort(String(req.url || ''), 443);
1385
+ if (!rawHost) {
1386
+ try {
1387
+ socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
1388
+ }
1389
+ catch { }
1390
+ return;
1391
+ }
1392
+ const auth = authorize(req.headers['proxy-authorization']);
1393
+ if (!auth.ok) {
1394
+ if (shouldRecordPreAdmission(`407:${rawHost}`)) {
1395
+ recordProxyConnect({ host: rawHost, port, note: 'connect (407, missing or bad proxy auth)' });
1396
+ }
1397
+ try {
1398
+ socket.end(PROXY_AUTH_REQUIRED_RESPONSE);
1399
+ }
1400
+ catch { }
1401
+ return;
1402
+ }
1403
+ const caller = auth.caller;
1404
+ if (!admit(socket)) {
1405
+ // A raw socket may not be TLS-ready yet, so there is no status line to
1406
+ // write — closing it is the only honest answer.
1407
+ if (shouldRecordPreAdmission(`cap:${rawHost}`)) {
1408
+ recordProxyConnect({ host: rawHost, port, note: 'connect (503-equivalent, connection cap reached)' });
1409
+ }
1410
+ try {
1411
+ socket.destroy();
1412
+ }
1413
+ catch { }
1414
+ return;
1415
+ }
1416
+ // Rule admission (ADR-0018): a rejected host is answered 403 on the raw
1417
+ // socket BEFORE the 200, so no tunnel is opened and no certificate is
1418
+ // minted for a host this machine refuses to reach.
1419
+ if (isRuleRejected(rawHost)) {
1420
+ log(`reject CONNECT ${rawHost}:${port} (egress rule)`);
1421
+ recordProxyConnect({ host: rawHost, port, note: 'connect (rejected by rule)' });
1422
+ try {
1423
+ socket.end(RULE_REJECT_RESPONSE);
1424
+ }
1425
+ catch { }
1426
+ return;
1427
+ }
515
1428
  socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
516
1429
  if (head && head.length)
517
1430
  socket.unshift(head);
518
- const bb = matchBypass(rawHost, deps.bypassHosts);
519
- if (bb.bypassed) {
520
- tunnel(socket, rawHost, port, undefined, bb.viaProxy);
1431
+ // A credential-less admission is legal only while the live config allows
1432
+ // it; remember the opened tunnel so a later `requireCredential` save can
1433
+ // retire it (admission itself is per-connection).
1434
+ if (!caller)
1435
+ trackUnauthenticatedTunnel(socket);
1436
+ if (ruleTunnels(rawHost)) {
1437
+ recordProxyConnect({ host: rawHost, port, note: 'connect (blind tunnel)' });
1438
+ // Any bytes that arrived with the CONNECT are ALREADY back in the socket's
1439
+ // read buffer (the unshift above), so no replay is passed here: doing so
1440
+ // would duplicate the client's first bytes upstream. The identity peek
1441
+ // rides the relay's tap, which is attached at dial time.
1442
+ tunnel(socket, rawHost, port);
521
1443
  return;
522
1444
  }
523
1445
  const chunks = [];
@@ -529,20 +1451,39 @@ export async function createForwardProxyServer(deps) {
529
1451
  chunks.push(d);
530
1452
  total += d.length;
531
1453
  const buf = Buffer.concat(chunks, total);
532
- const sni = parseClientHelloSNI(buf);
533
- if (sni) {
1454
+ const peek = peekClientHello(buf);
1455
+ if (!peek.isTls) {
1456
+ // Not a TLS handshake at all (SSH, IMAPS, a bespoke protocol): relay it
1457
+ // NOW. Waiting for a ClientHello that can never arrive used to stall
1458
+ // such a tunnel until 32 KiB had accumulated on the socket.
534
1459
  decided = true;
535
1460
  socket.pause();
536
1461
  socket.removeListener('data', onData);
537
- log(`MITM ${sni}`);
538
- void startMitm(socket, buf, sni);
1462
+ log(`tunnel ${rawHost}:${port} (not tls)`);
1463
+ recordProxyConnect({ host: rawHost, port, note: 'connect (not tls, blind tunnel)' });
1464
+ tunnel(socket, rawHost, port, buf);
1465
+ return;
1466
+ }
1467
+ if (peek.complete) {
1468
+ // A ClientHello WITHOUT SNI is still interceptable: the CONNECT
1469
+ // authority is the only identity the client offered (IP-literal
1470
+ // targets can never carry SNI — RFC 6066 forbids an IP there). Falling
1471
+ // back to a blind tunnel here let any client opt out of interception
1472
+ // simply by omitting the extension.
1473
+ const identity = peek.sni || rawHost;
1474
+ decided = true;
1475
+ socket.pause();
1476
+ socket.removeListener('data', onData);
1477
+ log(peek.sni ? `MITM ${identity}` : `MITM ${identity} (no SNI, authority identity)`);
1478
+ void startMitm(socket, buf, identity, port, peek.sni ? 'sni' : 'authority', caller);
539
1479
  return;
540
1480
  }
541
1481
  if (total > MAX_HELLO_BYTES) {
542
1482
  decided = true;
543
1483
  socket.pause();
544
1484
  socket.removeListener('data', onData);
545
- log(`tunnel ${rawHost}:${port} (no SNI parsed)`);
1485
+ log(`tunnel ${rawHost}:${port} (ClientHello never completed)`);
1486
+ recordProxyConnect({ host: rawHost, port, note: 'connect (hello incomplete, blind tunnel)' });
546
1487
  tunnel(socket, rawHost, port, buf);
547
1488
  }
548
1489
  };
@@ -554,9 +1495,14 @@ export async function createForwardProxyServer(deps) {
554
1495
  catch { }
555
1496
  });
556
1497
  }
557
- async function startMitm(socket, hello, sni) {
1498
+ async function startMitm(socket, hello, identity, connectPort, by, caller) {
558
1499
  try {
559
- const port = await hostTlsPort(sni);
1500
+ const port = await hostTlsPort(identity, connectPort, caller);
1501
+ recordProxyConnect({
1502
+ host: identity,
1503
+ port: connectPort,
1504
+ note: by === 'sni' ? 'connect (mitm)' : 'connect (mitm by authority, no sni)',
1505
+ });
560
1506
  const up = net.connect(port, '127.0.0.1', () => {
561
1507
  up.write(hello);
562
1508
  splice(socket, up);
@@ -575,8 +1521,9 @@ export async function createForwardProxyServer(deps) {
575
1521
  });
576
1522
  }
577
1523
  catch (err) {
578
- log(`MITM setup failed for ${sni}: ${err?.message || err} — blind tunnel fallback`);
579
- tunnel(socket, sni, 443);
1524
+ log(`MITM setup failed for ${identity}: ${err?.message || err} — blind tunnel fallback`);
1525
+ recordProxyConnect({ host: identity, port: connectPort, note: 'connect (mitm setup failed, blind tunnel fallback)' });
1526
+ tunnel(socket, identity, connectPort);
580
1527
  }
581
1528
  }
582
1529
  // ── outer proxy server: CONNECT + plain-HTTP absolute-URI requests ──
@@ -584,71 +1531,253 @@ export async function createForwardProxyServer(deps) {
584
1531
  void handlePlainProxyRequest(req, res);
585
1532
  });
586
1533
  proxy.on('connect', handleConnect);
587
- proxy.on('clientError', (_err, socket) => {
1534
+ proxy.on('clientError', (err, socket) => {
1535
+ log(`proxy clientError ${describeClientError(err)}`);
588
1536
  try {
589
1537
  socket.end(CLIENT_ERROR_RESPONSE);
590
1538
  }
591
1539
  catch { }
592
1540
  });
1541
+ /**
1542
+ * The ONLY proxy credential (ADR-0017): the Basic password must resolve to
1543
+ * an enabled, unexpired OCR API key, and the tunnel inherits its identity.
1544
+ * Username is ignored (browsers and several SDKs cannot set one; key names
1545
+ * are not unique). Loopback without a credential remains open (historical
1546
+ * posture) unless `forwardProxy.requireCredential` is enabled; a non-loopback
1547
+ * bind is `authRequired` and fails closed.
1548
+ */
1549
+ const authorize = (header) => {
1550
+ // Strict mode (hot-applies): `forwardProxy.requireCredential` closes the
1551
+ // loopback loophole, so a gateway plugin's bound key can never act as the
1552
+ // identity of an unauthenticated local process.
1553
+ const required = deps.authRequired === true || deps.liveForwardProxy?.()?.requireCredential === true;
1554
+ const raw = Array.isArray(header) ? header[0] : header;
1555
+ if (!raw)
1556
+ return required ? { ok: false } : { ok: true };
1557
+ const scheme = /^Basic\s+(.+)$/i.exec(raw.trim());
1558
+ if (!scheme)
1559
+ return { ok: false };
1560
+ let decoded;
1561
+ try {
1562
+ decoded = Buffer.from(scheme[1], 'base64').toString('utf8');
1563
+ }
1564
+ catch {
1565
+ return { ok: false };
1566
+ }
1567
+ const colon = decoded.indexOf(':');
1568
+ const secret = colon === -1 ? decoded : decoded.slice(colon + 1);
1569
+ const key = deps.resolveApiKey?.(secret);
1570
+ return key ? { ok: true, caller: { keyId: key.id, name: key.name } } : { ok: false };
1571
+ };
1572
+ // ── strict credential mode: retire tunnels admitted WITHOUT one ──
1573
+ // Admission is per-connection, so a CONNECT opened before the operator
1574
+ // enabled `forwardProxy.requireCredential` would otherwise keep its tunnel
1575
+ // (and its capture/egress) until the client closed it. Track exactly those
1576
+ // tunnels and close them as soon as the live config demands a credential;
1577
+ // the timer only exists while at least one such tunnel is open.
1578
+ const unauthenticatedTunnels = new Set();
1579
+ let strictSweep;
1580
+ function stopStrictSweepIfIdle() {
1581
+ if (unauthenticatedTunnels.size === 0 && strictSweep) {
1582
+ clearInterval(strictSweep);
1583
+ strictSweep = undefined;
1584
+ }
1585
+ }
1586
+ function trackUnauthenticatedTunnel(socket) {
1587
+ unauthenticatedTunnels.add(socket);
1588
+ socket.once('close', () => {
1589
+ unauthenticatedTunnels.delete(socket);
1590
+ stopStrictSweepIfIdle();
1591
+ });
1592
+ if (strictSweep)
1593
+ return;
1594
+ strictSweep = setInterval(() => {
1595
+ if (deps.liveForwardProxy?.()?.requireCredential !== true)
1596
+ return;
1597
+ for (const tunnel of unauthenticatedTunnels) {
1598
+ try {
1599
+ tunnel.destroy();
1600
+ }
1601
+ catch { }
1602
+ }
1603
+ unauthenticatedTunnels.clear();
1604
+ stopStrictSweepIfIdle();
1605
+ }, 1000);
1606
+ strictSweep.unref?.();
1607
+ }
1608
+ // ── inbound socket cap ──
1609
+ // Every tunneled/MITM'd socket costs TWO fds (the accepted socket plus its
1610
+ // decrypted loopback peer) and, when MITM'd, a TLS terminator — so an
1611
+ // unbounded proxy listener is a local fd-exhaustion vector: one client can
1612
+ // open CONNECTs faster than the OS reclaims them.
1613
+ //
1614
+ // The cap is enforced at ADMISSION (the two points where the proxy starts
1615
+ // spending resources: a CONNECT tunnel and a plain-HTTP request), not at
1616
+ // accept time, because Bun's node:http exposes none of the accept-side hooks
1617
+ // (verified on 1.3.14: no `'connection'` event on http.Server, and both
1618
+ // `server.maxConnections` and `server.timeout` are inert). A socket that
1619
+ // never sends a byte is therefore bounded only by the listen backlog; the
1620
+ // admission cap covers the part that multiplies. The cap is read per
1621
+ // admission, so a console save hot-applies.
1622
+ const liveSockets = new Set();
1623
+ let capWarnedAt = 0;
1624
+ const currentCap = () => deps.liveForwardProxy?.()?.maxConnections ?? deps.maxConnections ?? DEFAULT_FORWARD_PROXY_MAX_CONNECTIONS;
1625
+ /** true = this socket may proceed; false = it was already refused. */
1626
+ const admit = (socket) => {
1627
+ if (liveSockets.has(socket))
1628
+ return true;
1629
+ const cap = currentCap();
1630
+ if (liveSockets.size >= cap) {
1631
+ const now = Date.now();
1632
+ if (now - capWarnedAt > CLIENT_TLS_ERROR_DEDUPE_MS) {
1633
+ capWarnedAt = now;
1634
+ log(`connection cap reached (${cap}) — refusing new exchanges`);
1635
+ }
1636
+ return false;
1637
+ }
1638
+ liveSockets.add(socket);
1639
+ // Bun emits 'end' but NOT 'close' on the socket it hands to an http.Server
1640
+ // 'connect' handler (verified on 1.3.14), so releasing only on 'close'
1641
+ // would leak a slot per finished tunnel and wedge the cap shut. All three
1642
+ // terminal signals release; a double release is a no-op on a Set.
1643
+ const release = () => {
1644
+ liveSockets.delete(socket);
1645
+ };
1646
+ socket.once('close', release);
1647
+ socket.once('end', release);
1648
+ socket.once('error', release);
1649
+ return true;
1650
+ };
593
1651
  async function handlePlainProxyRequest(req, res) {
1652
+ const auth = authorize(req.headers['proxy-authorization']);
1653
+ if (!auth.ok) {
1654
+ const plainAuthHost = String(req.headers.host || req.socket.remoteAddress || 'unknown').split(':')[0];
1655
+ if (shouldRecordPreAdmission(`407:${plainAuthHost}`)) {
1656
+ recordProxyConnect({
1657
+ host: plainAuthHost,
1658
+ port: req.socket.remotePort || 0,
1659
+ note: `plain ${req.method || '?'} (407, missing or bad proxy auth)`,
1660
+ });
1661
+ }
1662
+ try {
1663
+ res.writeHead(407, {
1664
+ 'proxy-authenticate': `Basic realm="${PROXY_AUTH_REALM}"`,
1665
+ 'content-length': '0',
1666
+ connection: 'close',
1667
+ });
1668
+ res.end();
1669
+ }
1670
+ catch { }
1671
+ return;
1672
+ }
1673
+ markProxyCaller(req, auth.caller);
594
1674
  let target;
1675
+ let target0;
595
1676
  try {
596
1677
  target = new URL(req.url || '');
1678
+ target0 = target;
597
1679
  }
598
1680
  catch {
599
- res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
600
- res.end('Forward proxy requires an absolute-form request URI');
1681
+ const badReqHost = String(req.headers.host || req.socket.remoteAddress || 'unknown').split(':')[0];
1682
+ if (shouldRecordPreAdmission(`badreq:${badReqHost}`)) {
1683
+ recordProxyConnect({
1684
+ host: badReqHost,
1685
+ port: req.socket.remotePort || 0,
1686
+ note: `plain ${req.method || '?'} (400, not an absolute-form request URI)`,
1687
+ });
1688
+ }
1689
+ proxyFail(res, 400, 'Forward proxy requires an absolute-form request URI');
1690
+ return;
1691
+ }
1692
+ if (!admit(req.socket)) {
1693
+ if (shouldRecordPreAdmission(`cap:${target0.hostname}`)) {
1694
+ recordProxyConnect({
1695
+ host: target0.hostname,
1696
+ port: parseInt(target0.port || '0', 10),
1697
+ note: `plain ${req.method} (503, connection cap reached)`,
1698
+ });
1699
+ }
1700
+ proxyFail(res, 503, 'Forward proxy: connection limit reached');
601
1701
  return;
602
1702
  }
603
- const bb = matchBypass(target.hostname, deps.bypassHosts);
1703
+ const intercept = !ruleTunnels(target.hostname);
604
1704
  try {
605
- if (!bb.bypassed && (await deps.intercept(req, res)))
1705
+ // `ingress: 'passthrough'` = a blind tunnel: the intercept chain never
1706
+ // runs and the exchange is forwarded transparently.
1707
+ if (intercept && (await deps.intercept(req, res)))
606
1708
  return;
1709
+ const tap = createAccessTap({
1710
+ host: target.hostname,
1711
+ port: parseInt(target.port || (target.protocol === 'https:' ? '443' : '80'), 10),
1712
+ method: req.method,
1713
+ path: req.url || '/',
1714
+ wire: String(req.headers.upgrade ?? '').toLowerCase().includes('websocket') ? 'ws' : 'h1',
1715
+ requestHeaders: req.headers,
1716
+ });
1717
+ if (isRuleRejected(target.hostname)) {
1718
+ tap?.finish(403, undefined, 'rejected by rule');
1719
+ proxyFail(res, 403, RULE_REJECTED_MESSAGE);
1720
+ return;
1721
+ }
607
1722
  await forwardTo(req, res, {
608
1723
  host: target.hostname,
609
1724
  port: parseInt(target.port || (target.protocol === 'https:' ? '443' : '80'), 10),
610
1725
  path: target.pathname + target.search,
611
1726
  secure: target.protocol === 'https:',
612
- viaProxy: bb.bypassed ? bb.viaProxy : undefined,
613
- });
1727
+ tap,
1728
+ }, resolveUpstreamTls(deps.upstreamTls));
614
1729
  }
615
1730
  catch {
616
- try {
617
- if (!res.headersSent)
618
- res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
619
- res.end('Forward proxy error');
620
- }
621
- catch { }
1731
+ proxyFail(res, 502, 'Forward proxy error');
622
1732
  }
623
1733
  }
624
1734
  await listen(inner);
625
- const innerPort = inner.address().port;
1735
+ innerH1Port = inner.address().port;
1736
+ await listen(h2Inner);
1737
+ innerH2Port = h2Inner.address().port;
626
1738
  try {
627
1739
  await listen(proxy, deps.port, deps.host);
628
1740
  }
629
1741
  catch (err) {
630
- // Fault-tolerance: never leak the inner listener when our public listen
1742
+ // Fault-tolerance: never leak the inner listeners when our public listen
631
1743
  // fails (port busy etc.) — the caller logs the error and the gateway
632
1744
  // keeps running without the proxy.
633
1745
  try {
634
1746
  inner.close();
635
1747
  }
636
1748
  catch { }
1749
+ try {
1750
+ h2Inner.close();
1751
+ }
1752
+ catch { }
637
1753
  throw err;
638
1754
  }
639
1755
  const port = proxy.address().port;
640
- log(`listening on ${deps.host}:${port} (inner ${innerPort})`);
1756
+ log(`listening on ${deps.host}:${port} (inner h1 ${innerH1Port}, h2 ${innerH2Port})`);
641
1757
  return {
642
1758
  port,
643
1759
  caCertPem: ca.caCertPem,
1760
+ activeConnections: () => liveSockets.size,
644
1761
  close() {
645
1762
  return new Promise((resolve) => {
646
- for (const srv of hostServers.values()) {
1763
+ for (const terminator of terminators.values()) {
647
1764
  try {
648
- srv.close();
1765
+ terminator.srv.close();
649
1766
  }
650
1767
  catch { }
651
1768
  }
1769
+ for (const terminator of drainingTerminators.values()) {
1770
+ try {
1771
+ terminator.srv.close();
1772
+ }
1773
+ catch { }
1774
+ }
1775
+ if (strictSweep) {
1776
+ clearInterval(strictSweep);
1777
+ strictSweep = undefined;
1778
+ }
1779
+ unauthenticatedTunnels.clear();
1780
+ drainingTerminators.clear();
652
1781
  try {
653
1782
  proxy.close();
654
1783
  }
@@ -657,17 +1786,42 @@ export async function createForwardProxyServer(deps) {
657
1786
  inner.close();
658
1787
  }
659
1788
  catch { }
1789
+ try {
1790
+ h2Inner.close();
1791
+ }
1792
+ catch { }
1793
+ closeH2Pool();
660
1794
  resolve();
661
1795
  });
662
1796
  },
663
1797
  };
664
1798
  }
665
- function listen(server, port = 0, host = '127.0.0.1') {
666
- return new Promise((resolve, reject) => {
667
- server.once('error', reject);
668
- server.listen(port, host, () => {
669
- server.removeListener('error', reject);
670
- resolve();
671
- });
672
- });
1799
+ /**
1800
+ * Listen with one EADDRINUSE retry. Port 0 means the OS picks a free port, so
1801
+ * a collision should be impossible — but under concurrent test workers Bun has
1802
+ * been observed racing the ephemeral allocation (EADDRINUSE on port 0). The
1803
+ * retry keeps that infrastructure flake from masking real regressions.
1804
+ */
1805
+ async function listen(server, port = 0, host = '127.0.0.1') {
1806
+ for (let attempt = 0;; attempt++) {
1807
+ try {
1808
+ await new Promise((resolve, reject) => {
1809
+ server.once('error', reject);
1810
+ server.listen(port, host, () => {
1811
+ server.removeListener('error', reject);
1812
+ resolve();
1813
+ });
1814
+ });
1815
+ return;
1816
+ }
1817
+ catch (err) {
1818
+ if (attempt > 0 || err?.code !== 'EADDRINUSE')
1819
+ throw err;
1820
+ // Detach the dead listener state before retrying the same server.
1821
+ try {
1822
+ server.close();
1823
+ }
1824
+ catch { }
1825
+ }
1826
+ }
673
1827
  }