omnicell-router 0.8.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (400) hide show
  1. package/README.md +26 -7
  2. package/README.zh-CN.md +18 -5
  3. package/backend/dist/auth/api-keys.js +11 -0
  4. package/backend/dist/auth/key-models.d.ts +36 -0
  5. package/backend/dist/auth/key-models.js +99 -0
  6. package/backend/dist/capture/recorder.d.ts +4 -10
  7. package/backend/dist/capture/recorder.js +6 -58
  8. package/backend/dist/cli/clients/activity.js +2 -0
  9. package/backend/dist/cli/clients/base.d.ts +36 -11
  10. package/backend/dist/cli/clients/base.js +31 -15
  11. package/backend/dist/cli/clients/claude.d.ts +9 -0
  12. package/backend/dist/cli/clients/claude.js +6 -0
  13. package/backend/dist/cli/clients/codex.d.ts +78 -0
  14. package/backend/dist/cli/clients/codex.js +475 -57
  15. package/backend/dist/cli/clients/core-adapters.d.ts +1 -1
  16. package/backend/dist/cli/clients/core-adapters.js +1 -1
  17. package/backend/dist/cli/clients/dsh.d.ts +8 -0
  18. package/backend/dist/cli/clients/dsh.js +5 -0
  19. package/backend/dist/cli/clients/follow-catalog-sync.d.ts +62 -0
  20. package/backend/dist/cli/clients/follow-catalog-sync.js +435 -0
  21. package/backend/dist/cli/clients/grok.d.ts +15 -1
  22. package/backend/dist/cli/clients/grok.js +16 -2
  23. package/backend/dist/cli/clients/index.d.ts +13 -1
  24. package/backend/dist/cli/clients/index.js +97 -19
  25. package/backend/dist/cli/clients/kimi.d.ts +6 -0
  26. package/backend/dist/cli/clients/kimi.js +3 -0
  27. package/backend/dist/cli/clients/launcher.d.ts +1 -1
  28. package/backend/dist/cli/clients/model-meta.js +6 -3
  29. package/backend/dist/cli/clients/omp.d.ts +6 -0
  30. package/backend/dist/cli/clients/omp.js +3 -0
  31. package/backend/dist/cli/clients/openclaw.d.ts +6 -0
  32. package/backend/dist/cli/clients/openclaw.js +3 -0
  33. package/backend/dist/cli/clients/opencode.d.ts +8 -0
  34. package/backend/dist/cli/clients/opencode.js +8 -2
  35. package/backend/dist/cli/clients/pi.d.ts +6 -0
  36. package/backend/dist/cli/clients/pi.js +3 -0
  37. package/backend/dist/cli/clients/reserved.js +2 -0
  38. package/backend/dist/cli/clients/update-check.d.ts +37 -0
  39. package/backend/dist/cli/clients/update-check.js +309 -0
  40. package/backend/dist/cli/clients/workbuddy.d.ts +19 -0
  41. package/backend/dist/cli/clients/workbuddy.js +66 -0
  42. package/backend/dist/cli/index.js +5 -4
  43. package/backend/dist/cli/paths.js +8 -0
  44. package/backend/dist/cli/types.d.ts +101 -16
  45. package/backend/dist/config/comments-en.js +34 -25
  46. package/backend/dist/config/comments-zh.js +33 -24
  47. package/backend/dist/config/defaults.d.ts +280 -22
  48. package/backend/dist/config/defaults.js +279 -21
  49. package/backend/dist/config/env.d.ts +10 -0
  50. package/backend/dist/config/env.js +3 -2
  51. package/backend/dist/config/index.d.ts +22 -1
  52. package/backend/dist/config/index.js +218 -43
  53. package/backend/dist/config/migrations/v0-to-v1.d.ts +2 -2
  54. package/backend/dist/config/migrations/v10-to-v11.d.ts +38 -0
  55. package/backend/dist/config/migrations/v10-to-v11.js +43 -0
  56. package/backend/dist/config/migrations/v4-to-v5.d.ts +36 -0
  57. package/backend/dist/config/migrations/v4-to-v5.js +42 -0
  58. package/backend/dist/config/migrations/v5-to-v6.d.ts +27 -0
  59. package/backend/dist/config/migrations/v5-to-v6.js +29 -0
  60. package/backend/dist/config/migrations/v6-to-v7.d.ts +45 -0
  61. package/backend/dist/config/migrations/v6-to-v7.js +97 -0
  62. package/backend/dist/config/migrations/v7-to-v8.d.ts +36 -0
  63. package/backend/dist/config/migrations/v7-to-v8.js +43 -0
  64. package/backend/dist/config/migrations/v8-to-v9.d.ts +38 -0
  65. package/backend/dist/config/migrations/v8-to-v9.js +43 -0
  66. package/backend/dist/config/migrations/v9-to-v10.d.ts +51 -0
  67. package/backend/dist/config/migrations/v9-to-v10.js +71 -0
  68. package/backend/dist/config/runtime.js +1 -1
  69. package/backend/dist/config/schema.d.ts +3 -3
  70. package/backend/dist/config/schema.js +18 -4
  71. package/backend/dist/config/types.d.ts +221 -41
  72. package/backend/dist/egress-proxy/asset-download.d.ts +54 -0
  73. package/backend/dist/egress-proxy/asset-download.js +420 -0
  74. package/backend/dist/egress-proxy/manual-node-spec.d.ts +92 -0
  75. package/backend/dist/egress-proxy/manual-node-spec.js +408 -0
  76. package/backend/dist/egress-proxy/mihomo-binary.d.ts +54 -0
  77. package/backend/dist/egress-proxy/mihomo-binary.js +278 -0
  78. package/backend/dist/egress-proxy/mihomo-client.d.ts +94 -0
  79. package/backend/dist/egress-proxy/mihomo-client.js +308 -0
  80. package/backend/dist/egress-proxy/mihomo-config.d.ts +40 -0
  81. package/backend/dist/egress-proxy/mihomo-config.js +161 -0
  82. package/backend/dist/egress-proxy/mihomo-geo.d.ts +87 -0
  83. package/backend/dist/egress-proxy/mihomo-geo.js +213 -0
  84. package/backend/dist/egress-proxy/mihomo-logs.d.ts +43 -0
  85. package/backend/dist/egress-proxy/mihomo-logs.js +84 -0
  86. package/backend/dist/egress-proxy/mihomo-pac.d.ts +37 -0
  87. package/backend/dist/egress-proxy/mihomo-pac.js +75 -0
  88. package/backend/dist/egress-proxy/mihomo-rules-import.d.ts +43 -0
  89. package/backend/dist/egress-proxy/mihomo-rules-import.js +193 -0
  90. package/backend/dist/egress-proxy/mihomo-sidecar.d.ts +81 -0
  91. package/backend/dist/egress-proxy/mihomo-sidecar.js +637 -0
  92. package/backend/dist/forward-proxy/egress.d.ts +50 -11
  93. package/backend/dist/forward-proxy/egress.js +63 -17
  94. package/backend/dist/forward-proxy/h2-forward.js +42 -15
  95. package/backend/dist/forward-proxy/index.d.ts +11 -8
  96. package/backend/dist/forward-proxy/index.js +27 -60
  97. package/backend/dist/forward-proxy/interceptor.d.ts +3 -2
  98. package/backend/dist/forward-proxy/interceptor.js +4 -4
  99. package/backend/dist/forward-proxy/relay.js +3 -3
  100. package/backend/dist/forward-proxy/rules.d.ts +4 -4
  101. package/backend/dist/forward-proxy/rules.js +25 -4
  102. package/backend/dist/forward-proxy/server.d.ts +12 -16
  103. package/backend/dist/forward-proxy/server.js +237 -171
  104. package/backend/dist/harness/host/hosts.js +3 -2
  105. package/backend/dist/index.js +59 -19
  106. package/backend/dist/ingress-proxy/access-log.d.ts +176 -0
  107. package/backend/dist/ingress-proxy/access-log.js +774 -0
  108. package/backend/dist/ingress-proxy/ca-inventory.d.ts +106 -0
  109. package/backend/dist/ingress-proxy/ca-inventory.js +525 -0
  110. package/backend/dist/ingress-proxy/ca-trust.d.ts +96 -0
  111. package/backend/dist/ingress-proxy/ca-trust.js +315 -0
  112. package/backend/dist/ingress-proxy/ca.d.ts +104 -0
  113. package/backend/dist/ingress-proxy/ca.js +273 -0
  114. package/backend/dist/ingress-proxy/data-dir.d.ts +28 -0
  115. package/backend/dist/ingress-proxy/data-dir.js +45 -0
  116. package/backend/dist/ingress-proxy/egress.d.ts +151 -0
  117. package/backend/dist/ingress-proxy/egress.js +364 -0
  118. package/backend/dist/ingress-proxy/h2-forward.d.ts +66 -0
  119. package/backend/dist/ingress-proxy/h2-forward.js +561 -0
  120. package/backend/dist/ingress-proxy/index.d.ts +24 -0
  121. package/backend/dist/ingress-proxy/index.js +144 -0
  122. package/backend/dist/ingress-proxy/interceptor.d.ts +25 -0
  123. package/backend/dist/ingress-proxy/interceptor.js +52 -0
  124. package/backend/dist/ingress-proxy/ordered-relay.d.ts +29 -0
  125. package/backend/dist/ingress-proxy/ordered-relay.js +46 -0
  126. package/backend/dist/ingress-proxy/relay.d.ts +54 -0
  127. package/backend/dist/ingress-proxy/relay.js +188 -0
  128. package/backend/dist/ingress-proxy/rules.d.ts +195 -0
  129. package/backend/dist/ingress-proxy/rules.js +348 -0
  130. package/backend/dist/ingress-proxy/server.d.ts +153 -0
  131. package/backend/dist/ingress-proxy/server.js +2065 -0
  132. package/backend/dist/ingress-proxy/sni.d.ts +35 -0
  133. package/backend/dist/ingress-proxy/sni.js +124 -0
  134. package/backend/dist/ingress-proxy/status.d.ts +32 -0
  135. package/backend/dist/ingress-proxy/status.js +15 -0
  136. package/backend/dist/ingress-proxy/system-proxy.d.ts +112 -0
  137. package/backend/dist/ingress-proxy/system-proxy.js +481 -0
  138. package/backend/dist/ingress-proxy/traffic-delete.d.ts +21 -0
  139. package/backend/dist/ingress-proxy/traffic-delete.js +64 -0
  140. package/backend/dist/ingress-proxy/traffic-delete.worker.d.ts +44 -0
  141. package/backend/dist/ingress-proxy/traffic-delete.worker.js +228 -0
  142. package/backend/dist/ingress-proxy/traffic-files.d.ts +10 -0
  143. package/backend/dist/ingress-proxy/traffic-files.js +10 -0
  144. package/backend/dist/ingress-proxy/upstream-tls.d.ts +46 -0
  145. package/backend/dist/ingress-proxy/upstream-tls.js +105 -0
  146. package/backend/dist/ingress-proxy/ws-frames.d.ts +45 -0
  147. package/backend/dist/ingress-proxy/ws-frames.js +153 -0
  148. package/backend/dist/ir/adapters/anthropic-messages-stream.js +6 -1
  149. package/backend/dist/ir/adapters/anthropic-messages.js +12 -5
  150. package/backend/dist/ir/adapters/google-gemini-stream.js +7 -2
  151. package/backend/dist/ir/adapters/google-gemini.js +5 -2
  152. package/backend/dist/ir/adapters/openai-chat-stream.js +5 -1
  153. package/backend/dist/ir/adapters/openai-chat.d.ts +25 -0
  154. package/backend/dist/ir/adapters/openai-chat.js +50 -6
  155. package/backend/dist/ir/adapters/openai-responses-output.d.ts +1 -0
  156. package/backend/dist/ir/adapters/openai-responses-output.js +67 -21
  157. package/backend/dist/ir/adapters/openai-responses-stream.d.ts +13 -0
  158. package/backend/dist/ir/adapters/openai-responses-stream.js +34 -1
  159. package/backend/dist/ir/adapters/openai-responses.d.ts +92 -1
  160. package/backend/dist/ir/adapters/openai-responses.js +163 -12
  161. package/backend/dist/ir/capabilities.js +4 -0
  162. package/backend/dist/ir/media.d.ts +20 -0
  163. package/backend/dist/ir/media.js +41 -0
  164. package/backend/dist/ir/tool-identity.d.ts +35 -0
  165. package/backend/dist/ir/tool-identity.js +40 -0
  166. package/backend/dist/ir/types.d.ts +9 -1
  167. package/backend/dist/ir/validate.d.ts +24 -0
  168. package/backend/dist/ir/validate.js +113 -63
  169. package/backend/dist/local/build-jobs.d.ts +66 -0
  170. package/backend/dist/local/build-jobs.js +243 -0
  171. package/backend/dist/local/detect.d.ts +32 -0
  172. package/backend/dist/local/detect.js +145 -0
  173. package/backend/dist/local/draft-match.d.ts +58 -0
  174. package/backend/dist/local/draft-match.js +124 -0
  175. package/backend/dist/local/engine-runtime.d.ts +522 -0
  176. package/backend/dist/local/engine-runtime.js +1 -0
  177. package/backend/dist/local/engines.d.ts +241 -0
  178. package/backend/dist/local/engines.js +651 -0
  179. package/backend/dist/local/gguf.d.ts +35 -0
  180. package/backend/dist/local/gguf.js +314 -0
  181. package/backend/dist/local/hf.d.ts +120 -0
  182. package/backend/dist/local/hf.js +304 -0
  183. package/backend/dist/local/install.d.ts +90 -0
  184. package/backend/dist/local/install.js +421 -0
  185. package/backend/dist/local/llamacpp.d.ts +55 -0
  186. package/backend/dist/local/llamacpp.js +177 -0
  187. package/backend/dist/local/local-provider.d.ts +81 -0
  188. package/backend/dist/local/local-provider.js +301 -0
  189. package/backend/dist/local/machine-stats.d.ts +87 -0
  190. package/backend/dist/local/machine-stats.js +332 -0
  191. package/backend/dist/local/model-store.d.ts +347 -0
  192. package/backend/dist/local/model-store.js +1215 -0
  193. package/backend/dist/local/part-sweep.d.ts +32 -0
  194. package/backend/dist/local/part-sweep.js +156 -0
  195. package/backend/dist/local/plan.d.ts +65 -0
  196. package/backend/dist/local/plan.js +146 -0
  197. package/backend/dist/local/resources.d.ts +49 -0
  198. package/backend/dist/local/resources.js +64 -0
  199. package/backend/dist/local/run-stats.d.ts +95 -0
  200. package/backend/dist/local/run-stats.js +195 -0
  201. package/backend/dist/local/runner.d.ts +235 -0
  202. package/backend/dist/local/runner.js +1392 -0
  203. package/backend/dist/local/settings.d.ts +79 -0
  204. package/backend/dist/local/settings.js +180 -0
  205. package/backend/dist/local/strata-catalog.d.ts +30 -0
  206. package/backend/dist/local/strata-catalog.js +511 -0
  207. package/backend/dist/local/strata-drafting.d.ts +46 -0
  208. package/backend/dist/local/strata-drafting.js +265 -0
  209. package/backend/dist/local/strata.d.ts +278 -0
  210. package/backend/dist/local/strata.js +1392 -0
  211. package/backend/dist/local/tar.d.ts +20 -0
  212. package/backend/dist/local/tar.js +367 -0
  213. package/backend/dist/local/transport.d.ts +35 -0
  214. package/backend/dist/local/transport.js +89 -0
  215. package/backend/dist/local/tune.d.ts +58 -0
  216. package/backend/dist/local/tune.js +324 -0
  217. package/backend/dist/observability/http-exchange.d.ts +2 -2
  218. package/backend/dist/opencode/catalog/auto-pull.d.ts +14 -3
  219. package/backend/dist/opencode/catalog/auto-pull.js +284 -77
  220. package/backend/dist/opencode/catalog/ocr-store.d.ts +7 -6
  221. package/backend/dist/opencode/catalog/ocr-store.js +4 -2
  222. package/backend/dist/opencode/catalog/overrides-store.d.ts +15 -4
  223. package/backend/dist/opencode/catalog/overrides-store.js +28 -19
  224. package/backend/dist/opencode/catalog/reasoning-declaration.d.ts +35 -0
  225. package/backend/dist/opencode/catalog/reasoning-declaration.js +66 -0
  226. package/backend/dist/opencode/catalog/repository.js +28 -5
  227. package/backend/dist/opencode/catalog/sources/models-dev.d.ts +3 -3
  228. package/backend/dist/opencode/catalog/sources/models-dev.js +42 -14
  229. package/backend/dist/opencode/catalog/types.d.ts +42 -12
  230. package/backend/dist/opencode/catalog/types.js +38 -1
  231. package/backend/dist/opencode/credentials/def-materialize.js +27 -21
  232. package/backend/dist/opencode/credentials/ocr-store.js +11 -2
  233. package/backend/dist/opencode/credentials/sync.js +12 -3
  234. package/backend/dist/opencode/credentials/types.d.ts +31 -4
  235. package/backend/dist/opencode/credentials/types.js +25 -0
  236. package/backend/dist/opencode/migrate/engine.d.ts +20 -0
  237. package/backend/dist/opencode/migrate/engine.js +71 -0
  238. package/backend/dist/opencode/migrate/migrator.d.ts +11 -0
  239. package/backend/dist/opencode/migrate/migrator.js +6 -0
  240. package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.d.ts +6 -0
  241. package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.js +31 -0
  242. package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.d.ts +6 -0
  243. package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.js +62 -0
  244. package/backend/dist/opencode/probe.d.ts +21 -4
  245. package/backend/dist/opencode/probe.js +34 -10
  246. package/backend/dist/opencode/provider-def-adapters.d.ts +12 -11
  247. package/backend/dist/opencode/provider-def-adapters.js +43 -27
  248. package/backend/dist/opencode/provider-defs.d.ts +10 -16
  249. package/backend/dist/opencode/provider-defs.js +45 -45
  250. package/backend/dist/opencode/user-config.d.ts +23 -26
  251. package/backend/dist/opencode/user-config.js +95 -77
  252. package/backend/dist/pipeline/directives.d.ts +9 -4
  253. package/backend/dist/pipeline/directives.js +14 -10
  254. package/backend/dist/pipeline/orchestrator.d.ts +42 -13
  255. package/backend/dist/pipeline/orchestrator.js +514 -172
  256. package/backend/dist/plugins/builtin/model-gateway.js +38 -12
  257. package/backend/dist/plugins/environment-ack.d.ts +51 -0
  258. package/backend/dist/plugins/environment-ack.js +81 -0
  259. package/backend/dist/plugins/gateways.d.ts +6 -6
  260. package/backend/dist/plugins/gateways.js +2 -2
  261. package/backend/dist/plugins/host.d.ts +100 -16
  262. package/backend/dist/plugins/host.js +637 -99
  263. package/backend/dist/plugins/install-run.d.ts +27 -0
  264. package/backend/dist/plugins/install-run.js +99 -0
  265. package/backend/dist/plugins/manifest.d.ts +84 -32
  266. package/backend/dist/plugins/manifest.js +149 -45
  267. package/backend/dist/plugins/market-install.d.ts +18 -0
  268. package/backend/dist/plugins/market-install.js +111 -0
  269. package/backend/dist/plugins/market-source.d.ts +100 -0
  270. package/backend/dist/plugins/market-source.js +449 -0
  271. package/backend/dist/plugins/market-updates.d.ts +70 -0
  272. package/backend/dist/plugins/market-updates.js +97 -0
  273. package/backend/dist/plugins/market.d.ts +677 -0
  274. package/backend/dist/plugins/market.js +2113 -0
  275. package/backend/dist/plugins/source-index.d.ts +155 -0
  276. package/backend/dist/plugins/source-index.js +217 -0
  277. package/backend/dist/plugins/types.d.ts +402 -37
  278. package/backend/dist/projects/worktrees.d.ts +88 -0
  279. package/backend/dist/projects/worktrees.js +220 -0
  280. package/backend/dist/providers/boot-direct.d.ts +41 -7
  281. package/backend/dist/providers/boot-direct.js +284 -44
  282. package/backend/dist/providers/compat/tool-markup-recovery.js +31 -6
  283. package/backend/dist/providers/dial-wire.d.ts +17 -0
  284. package/backend/dist/providers/dial-wire.js +49 -0
  285. package/backend/dist/providers/executors/dispatch.d.ts +17 -7
  286. package/backend/dist/providers/executors/dispatch.js +28 -9
  287. package/backend/dist/providers/executors/openai-chat.js +14 -2
  288. package/backend/dist/providers/executors/plugin-adapter.d.ts +23 -1
  289. package/backend/dist/providers/executors/plugin-adapter.js +59 -3
  290. package/backend/dist/providers/member-match.d.ts +32 -9
  291. package/backend/dist/providers/member-match.js +65 -21
  292. package/backend/dist/providers/model-resolution.d.ts +62 -0
  293. package/backend/dist/providers/model-resolution.js +62 -0
  294. package/backend/dist/providers/price-order.d.ts +51 -0
  295. package/backend/dist/providers/price-order.js +54 -0
  296. package/backend/dist/providers/protocols-field.d.ts +24 -0
  297. package/backend/dist/providers/protocols-field.js +66 -0
  298. package/backend/dist/providers/provider-takedown.d.ts +5 -2
  299. package/backend/dist/providers/registry.d.ts +87 -26
  300. package/backend/dist/providers/registry.js +232 -121
  301. package/backend/dist/providers/selection.d.ts +91 -0
  302. package/backend/dist/providers/selection.js +158 -0
  303. package/backend/dist/providers/virtual-meta.d.ts +33 -2
  304. package/backend/dist/providers/virtual-meta.js +74 -18
  305. package/backend/dist/quota/cli-login.d.ts +25 -4
  306. package/backend/dist/quota/cli-login.js +38 -6
  307. package/backend/dist/quota/coverage-generation.d.ts +24 -0
  308. package/backend/dist/quota/coverage-generation.js +29 -0
  309. package/backend/dist/quota/declarations.js +8 -4
  310. package/backend/dist/quota/engine.js +2 -2
  311. package/backend/dist/quota/prober.d.ts +43 -2
  312. package/backend/dist/quota/prober.js +97 -22
  313. package/backend/dist/ratelimit/rate-limiter.d.ts +1 -1
  314. package/backend/dist/resilience/error-classifier.js +29 -0
  315. package/backend/dist/router/index.d.ts +1 -1
  316. package/backend/dist/router/index.js +17 -1
  317. package/backend/dist/router/layer2-decision.d.ts +1 -1
  318. package/backend/dist/router/layer2-decision.js +2 -2
  319. package/backend/dist/routes/console.js +1043 -405
  320. package/backend/dist/routes/environments.js +1 -1
  321. package/backend/dist/routes/local-models.d.ts +2 -0
  322. package/backend/dist/routes/local-models.js +1414 -0
  323. package/backend/dist/routes/mihomo.d.ts +2 -2
  324. package/backend/dist/routes/mihomo.js +20 -11
  325. package/backend/dist/routes/projects.js +121 -0
  326. package/backend/dist/server.js +409 -15
  327. package/backend/dist/session/session-manager.d.ts +42 -5
  328. package/backend/dist/session/session-manager.js +64 -11
  329. package/backend/dist/session/session-row.d.ts +29 -8
  330. package/backend/dist/session/session-row.js +18 -13
  331. package/backend/dist/snapshot/bundle.d.ts +40 -0
  332. package/backend/dist/snapshot/bundle.js +177 -0
  333. package/backend/dist/snapshot/handoff/compress.d.ts +46 -0
  334. package/backend/dist/snapshot/handoff/compress.js +77 -0
  335. package/backend/dist/snapshot/handoff/index.d.ts +119 -0
  336. package/backend/dist/snapshot/handoff/index.js +160 -0
  337. package/backend/dist/snapshot/handoff/jsonl-writer.d.ts +78 -0
  338. package/backend/dist/snapshot/handoff/jsonl-writer.js +175 -0
  339. package/backend/dist/snapshot/handoff/opencode-writer.d.ts +51 -0
  340. package/backend/dist/snapshot/handoff/opencode-writer.js +214 -0
  341. package/backend/dist/snapshot/handoff/summarize.d.ts +39 -0
  342. package/backend/dist/snapshot/handoff/summarize.js +118 -0
  343. package/backend/dist/snapshot/handoff/transcript.d.ts +71 -0
  344. package/backend/dist/snapshot/handoff/transcript.js +167 -0
  345. package/backend/dist/snapshot/media-fs.d.ts +10 -0
  346. package/backend/dist/snapshot/media-fs.js +50 -0
  347. package/backend/dist/snapshot/media.d.ts +32 -0
  348. package/backend/dist/snapshot/media.js +87 -0
  349. package/backend/dist/snapshot/store.d.ts +226 -0
  350. package/backend/dist/snapshot/store.js +887 -0
  351. package/backend/dist/snapshot/tree.d.ts +112 -0
  352. package/backend/dist/snapshot/tree.js +207 -0
  353. package/backend/dist/snapshot/types.d.ts +212 -0
  354. package/backend/dist/snapshot/types.js +14 -0
  355. package/backend/dist/snapshot/view.d.ts +19 -0
  356. package/backend/dist/snapshot/view.js +57 -0
  357. package/backend/dist/snapshot/write-worker.d.ts +67 -0
  358. package/backend/dist/snapshot/write-worker.js +129 -0
  359. package/backend/dist/surfaces/anthropic.js +4 -1
  360. package/backend/dist/surfaces/body-admission.d.ts +344 -0
  361. package/backend/dist/surfaces/body-admission.js +818 -0
  362. package/backend/dist/surfaces/chat-pipeline.js +8 -0
  363. package/backend/dist/surfaces/decision-pipeline.js +10 -7
  364. package/backend/dist/surfaces/gateway-catalog.d.ts +26 -0
  365. package/backend/dist/surfaces/gateway-catalog.js +202 -0
  366. package/backend/dist/surfaces/gateway-chat.d.ts +7 -11
  367. package/backend/dist/surfaces/gateway-chat.js +50 -12
  368. package/backend/dist/surfaces/ocr-headers.d.ts +6 -4
  369. package/backend/dist/surfaces/ocr-headers.js +11 -7
  370. package/backend/dist/surfaces/systemone.js +1 -1
  371. package/backend/dist/surfaces/transport-fastify.js +32 -5
  372. package/backend/dist/surfaces/transport-node-http.d.ts +51 -6
  373. package/backend/dist/surfaces/transport-node-http.js +76 -16
  374. package/backend/dist/surfaces/types.d.ts +11 -3
  375. package/backend/dist/trace/persist.js +21 -1
  376. package/backend/dist/trace/tracker.d.ts +35 -3
  377. package/backend/dist/trace/tracker.js +23 -0
  378. package/backend/dist/types/openai.d.ts +8 -0
  379. package/backend/dist/types/router.d.ts +17 -6
  380. package/backend/dist/types/router.js +14 -2
  381. package/backend/dist/utils/client-families.d.ts +66 -0
  382. package/backend/dist/utils/client-families.js +127 -0
  383. package/backend/dist/utils/event-ring.d.ts +1 -1
  384. package/backend/dist/utils/event-ring.js +1 -1
  385. package/backend/dist/utils/proxy-node.js +1 -1
  386. package/backend/dist/utils/proxy.d.ts +135 -11
  387. package/backend/dist/utils/proxy.js +144 -29
  388. package/backend/dist/utils/run-command.d.ts +21 -1
  389. package/backend/dist/utils/run-command.js +64 -4
  390. package/backend/dist/utils/server-liveness.d.ts +28 -0
  391. package/backend/dist/utils/server-liveness.js +32 -0
  392. package/backend/dist/utils/session-file.d.ts +28 -0
  393. package/backend/dist/utils/session-file.js +34 -0
  394. package/frontend/dist/assets/antigravity.color-DXFfVr6X.svg +39 -0
  395. package/frontend/dist/assets/gemini-cli.color-BfquLd1p.svg +1 -0
  396. package/frontend/dist/assets/index-CTZNvn1d.js +1707 -0
  397. package/frontend/dist/assets/{index-DxZ9MHKB.css → index-CqDSOPQ0.css} +1 -1
  398. package/frontend/dist/index.html +2 -2
  399. package/package.json +3 -1
  400. package/frontend/dist/assets/index-55VVwfFQ.js +0 -1521
@@ -0,0 +1,2065 @@
1
+ import http from 'node:http';
2
+ import https from 'node:https';
3
+ import net from 'node:net';
4
+ import tls from 'node:tls';
5
+ import { OrderedRelay } from './ordered-relay.js';
6
+ import { CertMinter, ensureCa } from './ca.js';
7
+ import { peekClientHello } from './sni.js';
8
+ import { splice } from './relay.js';
9
+ import { DEFAULT_INGRESS_PROXY_MAX_CONNECTIONS, INGRESS_PROXY_ADMISSION_SWEEP_MS, INGRESS_PROXY_MAX_EXCHANGE_MS, INGRESS_PROXY_HANG_TIMEOUT_MS, INGRESS_PROXY_KEEPALIVE_MS, INGRESS_PROXY_STALE_TUNNEL_MS, } from '../config/defaults.js';
10
+ import { describeUpstreamFailure, resolveDialEgress, EGRESS_UNAVAILABLE_MESSAGE, failureLabel, filterHeaders, isRuleRejected, openViaProxy, parseProxy, ruleTunnels, setBootRules, setLiveIngressProxy, shouldRetryOriginLeg, 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 { applyInboundLiveness } from '../utils/server-liveness.js';
14
+ import { bodyLimitFor, settleContinuationExpectation, } from '../surfaces/body-admission.js';
15
+ import { closeH2Pool, forwardH2 } from './h2-forward.js';
16
+ import { createWsObserver } from './ws-frames.js';
17
+ import { findGateway, listGatewayHosts } from '../plugins/gateways.js';
18
+ import http2 from 'node:http2';
19
+ /**
20
+ * Inbound ingress proxy (the HTTP_PROXY / HTTPS_PROXY server).
21
+ *
22
+ * Design (settled & validated on Bun 1.3.14):
23
+ * - INTERCEPTION IS DECIDED (ADR-0018 Revision 4): a CONNECT is MITM'd only
24
+ * when a rule row says so, when a live client-gateway plugin CLAIMS the host,
25
+ * or when the operator turned on the audit posture (`intercept: 'all'`).
26
+ * Everything else is a blind tunnel. The decrypted request is inspected —
27
+ * LLM-protocol traffic (via `intercept`) enters the routing pipeline;
28
+ * everything else is forwarded transparently.
29
+ * - ONE ordered rule table decides both halves per host (ADR-0018,
30
+ * `ingressProxy.rules`): two fields per row — `ingress` = intercept (MITM) /
31
+ * passthrough (blind tunnel) / reject, `egress` = direct / proxy. First match
32
+ * wins; loopback is always passthrough (cycle safety + local dev); an
33
+ * unmatched host takes the catch-all's `egress` and is blind-tunneled unless
34
+ * claimed or the audit posture is on. `reject` is answered 403 on admission —
35
+ * before any tunnel is opened or certificate minted.
36
+ * - Bun node:tls gaps worked around (all verified experimentally):
37
+ * * no SNICallback → per-host tls.Server with an explicit cert, cached;
38
+ * the servername is read by peeking the raw ClientHello (sni.ts);
39
+ * * socket.pipe() from a TLSSocket does not flush buffered data →
40
+ * explicit relay (relay.ts);
41
+ * * tlsServer/httpServer.emit('connection', socket) is not honored →
42
+ * the decrypted stream is spliced over a loopback socket into an
43
+ * inner http.Server that does native Bun HTTP parsing;
44
+ * * the node:http 'upgrade' event is unusable (the handler's socket
45
+ * swallows every write and the parser then answers 505) → an
46
+ * `Upgrade:` handshake is caught on the decrypted stream before the
47
+ * inner server and relayed byte-verbatim (relayUpgrade).
48
+ * - Per-host terminators and minted certs are LRU-bounded
49
+ * (MAX_HOST_TERMINATORS / MAX_CACHED_CERTS): full capture sees every host
50
+ * a client visits, so an unbounded cache is an fd leak per host.
51
+ * - Transport-complete MITM: the decrypted stream is parsed by an h1 inner
52
+ * OR an h2 inner (prior-knowledge h2c loopback), picked by sniffing the
53
+ * first decrypted bytes for the h2 connection preface. Both inners run the
54
+ * SAME intercept chain and the SAME transparent forward — an h2 request is
55
+ * re-originated upstream over h2 (h2-forward.ts) so gRPC/Connect framing,
56
+ * trailers and bidi streams survive the hop, with an h1 fallback when the
57
+ * upstream refuses h2.
58
+ * - ALPN: every host offers both protocols, ordered by who is talking. Bun
59
+ * honours the SERVER's preference, so an unclaimed host offers
60
+ * ['http/1.1','h2'] (dual-offer clients keep the h1 path — zero regression;
61
+ * h2-only clients get h2) while a gateway-claimed host offers
62
+ * ['h2','http/1.1']. The negotiated protocol is only a hint: the preface is
63
+ * the authority (Bun does not reliably surface alpnProtocol at callback
64
+ * time).
65
+ *
66
+ * No-request-loss rule: the client's decoded stream may emit data the moment
67
+ * the handshake completes — the 'data' listener is attached SYNCHRONOUSLY in
68
+ * the secureConnection callback; pre-connect chunks are buffered.
69
+ */
70
+ const MAX_HELLO_BYTES = 32 * 1024;
71
+ /** Bound on the buffered HTTP/1 request head examined for an `Upgrade:`
72
+ * handshake; a head that outgrows it goes to the inner server unexamined. */
73
+ const MAX_HEAD_BYTES = 32 * 1024;
74
+ /** LRU bound on per-host TLS terminators (each = one listening loopback socket
75
+ * + one minted leaf cert). Full capture sees EVERY host a client visits, so an
76
+ * unbounded map leaks one file descriptor per host for the life of the process. */
77
+ const MAX_HOST_TERMINATORS = 256;
78
+ /**
79
+ * Grace window for an evicted terminator: long enough for a CONNECT that
80
+ * already resolved its port to finish dialing, short enough to keep the fd
81
+ * budget bounded. `server.close()` never touches established connections, so
82
+ * this is the ONLY cost of eviction.
83
+ */
84
+ const TERMINATOR_DRAIN_MS = 30_000;
85
+ /** Hard cap on the draining set — eviction must not become a second cache. */
86
+ const MAX_DRAINING_TERMINATORS = 64;
87
+ /**
88
+ * One ledger row per this window, per terminator. A client that rejects the
89
+ * intercepted leaf (pinning, missing CA) reconnects in a tight loop; without
90
+ * the dedupe it would flush every real row out of the access ring.
91
+ */
92
+ const CLIENT_TLS_ERROR_DEDUPE_MS = 5_000;
93
+ /**
94
+ * Upper bound on "the error envelope is on its way" — the abort normally fires
95
+ * the moment the envelope chunk reaches the client transport; this only covers
96
+ * the case where no chunk ever arrives.
97
+ */
98
+ const MITM_ABORT_FLUSH_MS = 1_000;
99
+ /**
100
+ * Framing-level refusals for the two HTTP/1 listener legs (RFC 9110 10.1.1: a
101
+ * request line or header block the parser cannot use gets a FINAL status, not a
102
+ * silent close). Mapped from the parser code so the two legs cannot drift:
103
+ * - header block overran the parser limit -> 431 (RFC 9110 15.5.21, and what
104
+ * node's own default clientError path sends when no listener exists);
105
+ * - unsupported message version -> 505 (RFC 9110 15.5.19);
106
+ * - everything else is malformed syntax -> 400.
107
+ * No body: a peer that could not frame a request is not being asked to parse
108
+ * JSON, and `Connection: close` (RFC 9110 9.6) says the connection is done —
109
+ * RFC 10.1.1's advice to state whether it will be closed.
110
+ */
111
+ function clientErrorResponse(err) {
112
+ const code = typeof err === 'object' && err !== null && typeof err.code === 'string'
113
+ ? err.code
114
+ : '';
115
+ const [status, reason] = code === 'HPE_HEADER_OVERFLOW'
116
+ ? [431, 'Request Header Fields Too Large']
117
+ : code === 'HPE_INVALID_VERSION'
118
+ ? [505, 'HTTP Version Not Supported']
119
+ : [400, 'Bad Request'];
120
+ return `HTTP/1.1 ${status} ${reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n`;
121
+ }
122
+ /**
123
+ * Answer a framing-level client error on its own socket, then close it.
124
+ *
125
+ * The write is DEFERRED one tick because bun's socket layer discards a write
126
+ * issued synchronously inside a `clientError` listener (verified on bun 1.3.14
127
+ * against node v24: bun sends nothing at all, so the client saw a bare reset and
128
+ * no status). Deferring is the portable half of the fix; the socket is still
129
+ * closed immediately after, so a stalled client cannot hold it open.
130
+ */
131
+ function answerClientError(socket, err, log, leg) {
132
+ log(`${leg} clientError ${describeClientError(err)}`);
133
+ const packet = clientErrorResponse(err);
134
+ setImmediate(() => {
135
+ try {
136
+ if (socket.destroyed || !socket.writable)
137
+ return;
138
+ socket.end(packet);
139
+ }
140
+ catch {
141
+ // The peer is already gone; nothing left to tell.
142
+ }
143
+ });
144
+ }
145
+ /**
146
+ * Credential-shaped header names in a raw packet head. The access log applies
147
+ * the same policy to captured headers (`DENY_HEADER_SUBSTRINGS`), and this log
148
+ * line must not become the one place a live key lands on disk.
149
+ */
150
+ const CREDENTIAL_HEADER_LINE = /^(?:proxy-)?authorization$|^cookie$|^set-cookie$|-key$|api[-_]?key|apikey|token|secret/i;
151
+ /** Blank the value of every credential-shaped header line, keep the rest. */
152
+ function redactPacketHead(raw) {
153
+ return raw
154
+ .split('\r\n')
155
+ .map((line) => {
156
+ const at = line.indexOf(':');
157
+ if (at <= 0)
158
+ return line;
159
+ const name = line.slice(0, at);
160
+ return CREDENTIAL_HEADER_LINE.test(name.trim()) ? `${name}: [REDACTED]` : line;
161
+ })
162
+ .join('\r\n');
163
+ }
164
+ /**
165
+ * One line describing a request the HTTP parser refused. The 400 that follows
166
+ * carries an EMPTY body, so without this the client only ever reports
167
+ * "400 Bad Request" with no headers and the operator has nothing to look at —
168
+ * the raw packet head (request line + first headers) is the only evidence of
169
+ * what the client actually sent.
170
+ */
171
+ function describeClientError(err) {
172
+ if (typeof err !== 'object' || err === null)
173
+ return String(err);
174
+ const code = 'code' in err && typeof err.code === 'string' ? err.code : 'unknown';
175
+ const raw = 'rawPacket' in err && Buffer.isBuffer(err.rawPacket)
176
+ ? redactPacketHead(err.rawPacket.subarray(0, 240).toString('latin1'))
177
+ : '';
178
+ return raw ? `${code} raw=${JSON.stringify(raw)}` : code;
179
+ }
180
+ /** Raw-socket 403 for a CONNECT whose host a rule rejects (ADR-0018).
181
+ * Answered on the raw socket BEFORE the 200, so no tunnel and no minted
182
+ * certificate ever exist for a rejected host. */
183
+ const RULE_REJECT_RESPONSE = 'HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n';
184
+ /**
185
+ * Raw-socket 502 for a CONNECT whose egress the machine cannot honour (the
186
+ * route says `proxy` but no outbound proxy is configured). Same shape as the
187
+ * 403 above, and answered BEFORE the 200 for the same reason: no tunnel is
188
+ * opened, and the body names the fix.
189
+ */
190
+ const EGRESS_UNAVAILABLE_RESPONSE = 'HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n' +
191
+ EGRESS_UNAVAILABLE_MESSAGE;
192
+ /**
193
+ * Dedupe window for pre-admission ledger rows (cap / bad request line).
194
+ * A client hammering the cap reconnects in a tight loop; the
195
+ * row is the audit signal, not a per-attempt count — one row per window per
196
+ * host keeps a hostile client from flushing real rows out of the access ring.
197
+ */
198
+ const PRE_ADMISSION_ROW_DEDUPE_MS = CLIENT_TLS_ERROR_DEDUPE_MS;
199
+ const preAdmissionRowAt = new Map();
200
+ /** true = this pre-admission row should be recorded; false = deduped. */
201
+ function shouldRecordPreAdmission(key) {
202
+ const now = Date.now();
203
+ const last = preAdmissionRowAt.get(key) ?? 0;
204
+ if (now - last < PRE_ADMISSION_ROW_DEDUPE_MS)
205
+ return false;
206
+ preAdmissionRowAt.set(key, now);
207
+ if (preAdmissionRowAt.size > 512) {
208
+ // Bounded: drop expired entries instead of growing per hostile host.
209
+ for (const [k, t] of preAdmissionRowAt)
210
+ if (now - t >= PRE_ADMISSION_ROW_DEDUPE_MS)
211
+ preAdmissionRowAt.delete(k);
212
+ if (preAdmissionRowAt.size > 512)
213
+ preAdmissionRowAt.clear();
214
+ }
215
+ return true;
216
+ }
217
+ /**
218
+ * Response legs currently streaming to a client. The descriptor leak this ADR
219
+ * revision fixes was invisible from outside (the operator could see the sockets
220
+ * but not who owned them), so the count is exported: the console status surface
221
+ * and the teardown tests both read it.
222
+ */
223
+ const OPEN_ORIGIN_LEGS = new Set();
224
+ /** How many proxied response legs are open right now (0 = nothing to reap). */
225
+ export function openOriginLegCount() {
226
+ return OPEN_ORIGIN_LEGS.size;
227
+ }
228
+ /** Split a `host[:port]` header value (bracketed IPv6 supported). */
229
+ function splitHostPort(value, defaultPort) {
230
+ const raw = (value || '').trim();
231
+ if (raw.startsWith('[')) {
232
+ const end = raw.indexOf(']');
233
+ const host = raw.slice(1, end);
234
+ const rest = raw.slice(end + 1);
235
+ return { host, port: rest.startsWith(':') ? parseInt(rest.slice(1), 10) || defaultPort : defaultPort };
236
+ }
237
+ const colon = raw.lastIndexOf(':');
238
+ // Exactly one colon ⇒ host:port; a bare IPv6 literal (several colons) has none.
239
+ if (colon > 0 && raw.indexOf(':') === colon) {
240
+ return { host: raw.slice(0, colon), port: parseInt(raw.slice(colon + 1), 10) || defaultPort };
241
+ }
242
+ return { host: raw, port: defaultPort };
243
+ }
244
+ /**
245
+ * The canonical spelling of a host for an `:authority` / `Host` value: the
246
+ * default HTTPS port is implicit, any other port is kept, and an IPv6 literal
247
+ * is bracketed. Mirrors the upstream rebuild in `h2-forward.ts` (`authorityOf`)
248
+ * so the value a gateway plugin reads matches the one the relay forwards.
249
+ */
250
+ function authoritySpelling(host, port) {
251
+ const bracketed = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
252
+ return port === 443 ? bracketed : `${bracketed}:${port}`;
253
+ }
254
+ /** Per-response slot carrying the connection's abort hook to `proxyFail`. */
255
+ const MITM_ABORT = Symbol('ocr.ingressProxy.mitmAbort');
256
+ /**
257
+ * Parse a request head that carries an `Upgrade:` handshake, else null.
258
+ *
259
+ * The head is read off the DECRYPTED stream (see `relayUpgrade` for why the
260
+ * runtime's own upgrade event cannot be used). Only the target and the method
261
+ * are extracted — the head itself is relayed byte-verbatim, so nothing about
262
+ * the handshake (subprotocols, extensions, cookies) is ever re-serialized.
263
+ */
264
+ function parseUpgradeHead(head, defaultPort) {
265
+ const lines = head.split('\r\n');
266
+ const requestLine = /^([A-Z]+) (\S+) HTTP\/1\.[01]$/.exec(lines[0] ?? '');
267
+ if (!requestLine)
268
+ return null;
269
+ const headers = {};
270
+ for (const line of lines.slice(1)) {
271
+ const colon = line.indexOf(':');
272
+ if (colon <= 0)
273
+ continue;
274
+ headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
275
+ }
276
+ const upgrade = headers.upgrade;
277
+ const connection = headers.connection;
278
+ const hostHeader = headers.host;
279
+ if (!upgrade || !connection || !hostHeader)
280
+ return null;
281
+ const tokens = String(connection).toLowerCase().split(',').map((v) => v.trim());
282
+ if (!tokens.includes('upgrade'))
283
+ return null;
284
+ // Same port precedence as the request leg (ADR-0018 §3a): an explicit Host
285
+ // port > the CONNECT authority's port > 443. A WebSocket client sends the
286
+ // plain host name, so defaulting to 443 sent an upgrade for a non-443 target
287
+ // to the wrong port.
288
+ const { host, port } = splitHostPort(String(hostHeader), defaultPort);
289
+ if (!host)
290
+ return null;
291
+ return { method: requestLine[1], path: requestLine[2], host, port, headers };
292
+ }
293
+ /** Send the request body upstream: the h2 relay's captured preface first (if
294
+ * any), then the live stream. With a tap, chunks tee into the access log
295
+ * alongside the upstream writes (both consumers see every chunk).
296
+ *
297
+ * A preface can be up to `GATEWAY_MAX_BODY_BYTES` (32 MiB, h2-forward.ts), so it is written
298
+ * under backpressure: the old loop queued every chunk regardless of
299
+ * `write()` returning false, spiking the outgoing buffer by the whole body. */
300
+ function pumpRequestBody(req, upstream, tap, preface) {
301
+ if (!preface) {
302
+ if (tap)
303
+ req.on('data', (d) => tap.onReqChunk(d));
304
+ req.pipe(upstream);
305
+ req.on('error', () => {
306
+ try {
307
+ upstream.destroy();
308
+ }
309
+ catch { }
310
+ });
311
+ return;
312
+ }
313
+ // Keep the live listener attached even while the preface drains: a paused
314
+ // stream does not restart itself, and Bun's h1 body may emit before the
315
+ // preface has been flushed. Chunks queue behind the preface to keep order.
316
+ const queue = [...preface.chunks];
317
+ let head = 0;
318
+ let ended = preface.ended;
319
+ let blocked = false;
320
+ let upstreamEnded = false;
321
+ const flush = () => {
322
+ if (blocked)
323
+ return;
324
+ while (head < queue.length) {
325
+ const chunk = queue[head];
326
+ tap?.onReqChunk(chunk);
327
+ const ok = upstream.write(chunk);
328
+ head += 1;
329
+ if (!ok) {
330
+ blocked = true;
331
+ req.pause();
332
+ upstream.once('drain', () => {
333
+ blocked = false;
334
+ req.resume();
335
+ flush();
336
+ });
337
+ return;
338
+ }
339
+ }
340
+ queue.length = 0;
341
+ head = 0;
342
+ if (ended && !upstreamEnded) {
343
+ upstreamEnded = true;
344
+ upstream.end();
345
+ }
346
+ };
347
+ req.on('data', (chunk) => {
348
+ queue.push(chunk);
349
+ flush();
350
+ });
351
+ req.on('end', () => {
352
+ ended = true;
353
+ flush();
354
+ });
355
+ req.on('error', () => {
356
+ try {
357
+ upstream.destroy();
358
+ }
359
+ catch { }
360
+ });
361
+ flush();
362
+ }
363
+ /** Pipe the upstream response to the client, teeing chunks into the tap. */
364
+ function pipeUpResponse(up, res, req, tap, maxExchangeMs = INGRESS_PROXY_MAX_EXCHANGE_MS) {
365
+ if (tap)
366
+ up.on('data', (d) => tap.onResChunk(d));
367
+ // A client that goes away mid-response must take the origin leg with it.
368
+ // Without this the upstream socket stays ESTABLISHED for the life of the
369
+ // process: the peer is a loopback hop (or a keep-alive origin) that never
370
+ // times out on its own. Measured on Windows/Bun 1.3.14: one dead loopback
371
+ // PAIR per client killed mid-stream, still there 12s later and after the
372
+ // proxy handle was closed.
373
+ //
374
+ // Bun does NOT emit `res` 'close' when the peer dies (verified), so the two
375
+ // signals used here are the ones that DO fire: `req` 'aborted', and — for a
376
+ // stream that keeps producing — the client socket's own state checked as
377
+ // chunks arrive (a killed peer leaves `destroyed`/`readyState: 'closed'`
378
+ // behind even though no response event arrives). `writableFinished` keeps a
379
+ // normally completed exchange alone: a finished response on a keep-alive
380
+ // socket is not an abandoned one.
381
+ const abortUpstream = () => {
382
+ if (res.writableFinished)
383
+ return;
384
+ // Destroying the UPSTREAM leg is always safe (it is this exchange's own
385
+ // socket, never the client's). Only the socket-STATE probe below has to skip
386
+ // an h2 client, where `res.socket` is the multiplexed session shared by every
387
+ // stream on it.
388
+ try {
389
+ up.destroy();
390
+ }
391
+ catch { }
392
+ };
393
+ req.once('aborted', abortUpstream);
394
+ res.once('close', abortUpstream);
395
+ const h2Client = Boolean(res.stream);
396
+ up.on('data', () => {
397
+ if (h2Client)
398
+ return;
399
+ const sock = res.socket;
400
+ if (sock && (sock.destroyed === true || sock.readyState === 'closed'))
401
+ abortUpstream();
402
+ });
403
+ // The bound that does not depend on any signal arriving. Measured on Bun
404
+ // 1.3.14: a killed client leaves the inner leg with `res.socket.destroyed ===
405
+ // false, readyState: 'open'` and no event at all, while the origin keeps
406
+ // producing — so both the event hooks above AND the state check are silent,
407
+ // and the origin socket stays ESTABLISHED for the life of the process. Far
408
+ // above any legitimate exchange (a long LLM stream is minutes); it only ever
409
+ // closes a leg that already outlived it.
410
+ OPEN_ORIGIN_LEGS.add(up);
411
+ const exchangeCap = setTimeout(abortUpstream, maxExchangeMs);
412
+ exchangeCap.unref?.();
413
+ const clearCap = () => {
414
+ clearTimeout(exchangeCap);
415
+ OPEN_ORIGIN_LEGS.delete(up);
416
+ };
417
+ up.once('end', clearCap);
418
+ up.once('close', clearCap);
419
+ up.once('error', clearCap);
420
+ up.pipe(res);
421
+ }
422
+ /**
423
+ * Relay one decrypted exchange upstream on the h1 leg (direct or through the
424
+ * outbound proxy), tapping both directions when a tap is given. Gateway
425
+ * plugins call this through the host SDK so transport policy lives in core.
426
+ */
427
+ export function forwardTo(req, res, t, upstreamTls) {
428
+ const egress = resolveDialEgress(t.host);
429
+ if (egress.via === 'blocked') {
430
+ t.tap?.finish(502, undefined, 'egress unavailable');
431
+ proxyFail(res, 502, EGRESS_UNAVAILABLE_MESSAGE);
432
+ return Promise.resolve();
433
+ }
434
+ if (egress.via === 'proxy') {
435
+ return t.secure
436
+ ? forwardSecureViaProxy(req, res, t, egress.url, upstreamTls)
437
+ : forwardPlainViaProxy(req, res, t, egress.url);
438
+ }
439
+ return forwardDirect(req, res, t, upstreamTls);
440
+ }
441
+ /**
442
+ * Arm the kernel probe on an upstream socket (see `INGRESS_PROXY_KEEPALIVE_MS`).
443
+ * A relayed leg has no application-level idle timeout — an SSE stream that has
444
+ * gone quiet is indistinguishable from one between tokens — so the peer that
445
+ * disappeared without FIN/RST is reaped by TCP keepalive instead. Failure is
446
+ * non-fatal: some injected test sockets are not real handles.
447
+ */
448
+ /**
449
+ * The synthetic error our hang guard destroys a request with. It carries a CODE
450
+ * so `describeUpstreamFailure` classifies it as a timeout (504) without string
451
+ * matching a message that any future edit could reword.
452
+ */
453
+ function hangGuardError() {
454
+ const err = new Error('upstream timeout');
455
+ err.code = UPSTREAM_TIMEOUT_CODE;
456
+ return err;
457
+ }
458
+ function armUpstreamKeepalive(req) {
459
+ req.on('socket', (s) => {
460
+ try {
461
+ s.setKeepAlive(true, INGRESS_PROXY_KEEPALIVE_MS);
462
+ }
463
+ catch { }
464
+ });
465
+ }
466
+ function forwardDirect(req, res, t, upstreamTls) {
467
+ return new Promise((resolve) => {
468
+ const transport = t.secure ? https : http;
469
+ const upstream = transport.request({
470
+ host: t.host,
471
+ port: t.port,
472
+ method: req.method,
473
+ path: t.path,
474
+ headers: filterHeaders(req.headers),
475
+ ...(t.secure ? { ...upstreamServernameOption(t.host), ...(upstreamTls.opts || {}) } : {}),
476
+ }, (up) => {
477
+ // Headers arrived — the request is alive; clear the hang-protection
478
+ // timer so long-lived streams (SSE direct forwards) are never killed.
479
+ // Keepalive is what still reaps a half-dead peer (see relay.ts).
480
+ upstream.setTimeout(0);
481
+ res.writeHead(up.statusCode || 502, filterHeaders(up.headers));
482
+ pipeUpResponse(up, res, req, t.tap, t.maxExchangeMs);
483
+ up.on('end', () => {
484
+ t.tap?.finish(up.statusCode, up.headers);
485
+ resolve();
486
+ });
487
+ up.on('error', () => {
488
+ try {
489
+ res.destroy();
490
+ }
491
+ catch { }
492
+ t.tap?.finish(up.statusCode, up.headers, 'upstream error mid-response');
493
+ resolve();
494
+ });
495
+ });
496
+ armUpstreamKeepalive(upstream);
497
+ // Hang protection: a blackholed upstream (packets dropped, no RST — e.g. a
498
+ // blocked host) would otherwise stall the client forever. Applies only
499
+ // until response headers arrive.
500
+ upstream.setTimeout(INGRESS_PROXY_HANG_TIMEOUT_MS, () => {
501
+ upstream.destroy(hangGuardError());
502
+ });
503
+ upstream.on('error', (err) => {
504
+ const failure = describeUpstreamFailure(err);
505
+ t.tap?.finish(undefined, undefined, failure.note);
506
+ proxyFail(res, failure.status, failure.message);
507
+ resolve();
508
+ });
509
+ pumpRequestBody(req, upstream, t.tap, t.preface);
510
+ });
511
+ }
512
+ /**
513
+ * The admission gate's refusal body, spelled ONCE (ADR-0018 §3): every leg
514
+ * that answers 403 for a `reject` row — plain proxy, intercepted inner server,
515
+ * client-gateway relay — says exactly this.
516
+ */
517
+ export const RULE_REJECTED_MESSAGE = 'Ingress proxy: host rejected by rule';
518
+ /**
519
+ * Answer with an error envelope and CLOSE the connection.
520
+ *
521
+ * `Connection: close` is not decoration: on Bun an error answer written through
522
+ * the MITM inner server left the client's TLS session open (verified 1.3.14), so
523
+ * a client that waits for the stream to end — every non-streaming HTTP client —
524
+ * hung on a response it had already received in full. An error envelope is
525
+ * terminal; the connection must say so.
526
+ */
527
+ export function proxyFail(res, code, msg) {
528
+ try {
529
+ if (!res.headersSent) {
530
+ res.writeHead(code, { 'content-type': 'text/plain; charset=utf-8', connection: 'close' });
531
+ }
532
+ res.end(msg);
533
+ // An error envelope is terminal: close the client transport. On the MITM
534
+ // leg the only working handle is the terminator's abort hook (the inner
535
+ // server's `res.socket.end()` is inert on Bun); on the plain-proxy leg the
536
+ // socket is ours to end. Never touch the h2 session socket — it is
537
+ // multiplexed, and the stream's own end is the answer; the h2 guard must
538
+ // run BEFORE the abort hook, which end()s the whole session.
539
+ // Runtime-attached fields the declared `res` type cannot express.
540
+ const resExt = res;
541
+ if (Boolean(resExt.stream))
542
+ return;
543
+ const abort = resExt[MITM_ABORT];
544
+ if (abort) {
545
+ abort();
546
+ return;
547
+ }
548
+ const endSocket = () => {
549
+ try {
550
+ if (res.socket && !res.socket.destroyed)
551
+ res.socket.end();
552
+ }
553
+ catch { }
554
+ };
555
+ // After 'finish', not right after `end()`: the envelope must be on the wire
556
+ // before the socket closes, or the client sees a truncated body.
557
+ if (res.writableFinished)
558
+ endSocket();
559
+ else
560
+ res.once('finish', endSocket);
561
+ }
562
+ catch { }
563
+ }
564
+ /**
565
+ * HTTPS target via an outbound HTTP proxy: CONNECT tunnel → one-shot loopback
566
+ * relay → https.request over the relay (TLS runs end-to-end through the
567
+ * tunnel, so the real target certificate is what gets validated).
568
+ */
569
+ function forwardSecureViaProxy(req, res, t, proxyUrl, upstreamTls, attempt = 0) {
570
+ // ES2022 lib here has no Promise.withResolvers; the executor form is the
571
+ // only way to keep `resolve` for the retry re-entry.
572
+ return new Promise((resolve) => {
573
+ // One relay attempt. `retry` re-enters this function with attempt + 1; the
574
+ // returned promise settles exactly once, from whichever attempt finishes.
575
+ const relayOnce = () => {
576
+ // The request stream is consumed ONLY once the origin leg is secure: a
577
+ // retry re-reads `req` from wherever it stands, and a chunk already handed
578
+ // to a dying TLS socket cannot be rewound. Deferring the pump makes
579
+ // "nothing reached the origin" and "nothing left the client" the same
580
+ // fact, so `sentBytes === 0` really is replay-safe. (The outbound proxy's
581
+ // usual failure — a tunnel closed right after CONNECT — dies before
582
+ // `secureConnect`, so this is exactly the case the retry exists for.)
583
+ let originSecure = false;
584
+ let pumping = false;
585
+ let sentBytes = 0;
586
+ // Assigned once the request leg exists (below); the relay's connection
587
+ // handler reads it to start the pump when the origin answers the handshake.
588
+ let startPump = () => { };
589
+ const countingTap = {
590
+ onReqChunk: (chunk) => {
591
+ if (originSecure)
592
+ sentBytes += chunk.length;
593
+ t.tap?.onReqChunk(chunk);
594
+ },
595
+ onResChunk: (chunk) => t.tap?.onResChunk(chunk),
596
+ finish: (status, headers, note) => t.tap?.finish(status, headers, note),
597
+ };
598
+ const retry = (err) => {
599
+ // A started pump means the client stream may already be partly consumed
600
+ // (and, on the h2 preface path, still has live listeners attached to
601
+ // it) — never replay that, even when no byte reached the origin.
602
+ if (pumping)
603
+ return false;
604
+ if (!shouldRetryOriginLeg(err, { headersSent: res.headersSent, sentBytes, attempts: attempt }))
605
+ return false;
606
+ // Do NOT finish the tap here: `AccessTap.finish` appends one ledger row,
607
+ // and the retry attempt completes the SAME tap (nothing was tapped yet —
608
+ // the pump never started). Finishing here would leave a ghost failed row
609
+ // beside the real one for a single exchange.
610
+ void forwardSecureViaProxy(req, res, t, proxyUrl, upstreamTls, attempt + 1).then(resolve);
611
+ return true;
612
+ };
613
+ openViaProxy(proxyUrl, t.host, t.port)
614
+ .then((pipeSock) => {
615
+ const relay = net.createServer((c) => {
616
+ // A retry tears the tunnel down mid-handshake; an unhandled error on
617
+ // the loopback leg would crash the process instead of failing the
618
+ // attempt.
619
+ c.on('error', () => c.destroy());
620
+ c.pipe(pipeSock);
621
+ pipeSock.pipe(c);
622
+ // A TLS server speaks first (ServerHello), so the first byte back
623
+ // through the tunnel proves the origin leg is live. This is the only
624
+ // liveness signal Bun offers — see the pump comment below.
625
+ pipeSock.once('data', (_d) => {
626
+ originSecure = true;
627
+ startPump();
628
+ });
629
+ });
630
+ const cleanup = () => {
631
+ try {
632
+ relay.close();
633
+ }
634
+ catch { }
635
+ try {
636
+ pipeSock.destroy();
637
+ }
638
+ catch { }
639
+ };
640
+ relay.on('error', cleanup);
641
+ relay.listen(0, '127.0.0.1', () => {
642
+ const relayPort = relay.address().port;
643
+ const upstream = https.request({
644
+ host: '127.0.0.1',
645
+ port: relayPort,
646
+ method: req.method,
647
+ path: t.path,
648
+ headers: filterHeaders(req.headers),
649
+ ...upstreamServernameOption(t.host),
650
+ ...(upstreamTls.opts || {}),
651
+ }, (up) => {
652
+ upstream.setTimeout(0);
653
+ res.writeHead(up.statusCode || 502, filterHeaders(up.headers));
654
+ pipeUpResponse(up, res, req, t.tap, t.maxExchangeMs);
655
+ up.on('end', () => {
656
+ t.tap?.finish(up.statusCode, up.headers);
657
+ cleanup();
658
+ resolve();
659
+ });
660
+ up.on('error', () => {
661
+ try {
662
+ res.destroy();
663
+ }
664
+ catch { }
665
+ t.tap?.finish(up.statusCode, up.headers, 'upstream error mid-response');
666
+ cleanup();
667
+ resolve();
668
+ });
669
+ });
670
+ // Nothing is read from `req` until the origin TLS leg is LIVE, so a
671
+ // retry sees the request untouched. Bun cannot prove liveness from
672
+ // the socket: it hands `https.request` a plain net.Socket that reports
673
+ // `connecting === false` on a brand-new connection and never emits
674
+ // `secureConnect` (verified on 1.3.14), so a socket-state gate always
675
+ // takes its eager branch and consumes the client body into a tunnel
676
+ // that never completed the handshake — the exact mis-replay the retry
677
+ // exists to prevent. The loopback relay sees the tunnel's raw bytes
678
+ // instead: a TLS server always speaks first (ServerHello), so the
679
+ // first byte back through `pipeSock` proves the leg is live.
680
+ // `req` has no listener until then; an inbound abort in that window
681
+ // must not surface as an unhandled 'error'.
682
+ req.on('error', () => {
683
+ try {
684
+ upstream.destroy();
685
+ }
686
+ catch { }
687
+ });
688
+ startPump = () => {
689
+ if (pumping)
690
+ return;
691
+ pumping = true;
692
+ pumpRequestBody(req, upstream, countingTap, t.preface);
693
+ };
694
+ upstream.on('socket', (sock) => {
695
+ // Node: a fresh connection exposes `connecting` + `secureConnect`;
696
+ // a socket reused from the keep-alive pool is already secure.
697
+ if (sock.connecting) {
698
+ sock.once('secureConnect', () => {
699
+ originSecure = true;
700
+ startPump();
701
+ });
702
+ }
703
+ else if (sock instanceof tls.TLSSocket) {
704
+ originSecure = true;
705
+ startPump();
706
+ }
707
+ // Bun's plain net.Socket matches neither branch; the relay's
708
+ // first-byte gate (above) is its liveness signal.
709
+ });
710
+ armUpstreamKeepalive(upstream);
711
+ // Bun's https.request does NOT open the connection (or send the TLS
712
+ // ClientHello) until the request stream is written — it only emits
713
+ // 'socket'. With the pump deferred until the handshake is live that is
714
+ // a deadlock: no bytes written → no handshake → no first byte back → the
715
+ // pump never starts. flushHeaders() kicks the connection WITHOUT
716
+ // consuming `req`, so the pump can stay deferred (replay-safe) and Bun
717
+ // still starts TLS. Node connects at request creation anyway, so this is
718
+ // a no-op there beyond writing the head it was about to write.
719
+ try {
720
+ upstream.flushHeaders();
721
+ }
722
+ catch { }
723
+ upstream.setTimeout(INGRESS_PROXY_HANG_TIMEOUT_MS, () => {
724
+ upstream.destroy(hangGuardError());
725
+ });
726
+ upstream.on('error', (err) => {
727
+ if (retry(err)) {
728
+ cleanup();
729
+ return;
730
+ }
731
+ const failure = describeUpstreamFailure(err, { proxied: true });
732
+ t.tap?.finish(undefined, undefined, failure.note);
733
+ proxyFail(res, failure.status, failure.message);
734
+ cleanup();
735
+ resolve();
736
+ });
737
+ });
738
+ })
739
+ .catch((err) => {
740
+ // Same rule for the CONNECT itself: nothing was written, so one fresh
741
+ // tunnel is safe. Otherwise report the outbound-proxy class distinctly.
742
+ if (retry(err))
743
+ return;
744
+ t.tap?.finish(undefined, undefined, `outbound proxy connect failed: ${failureLabel(err)}`);
745
+ proxyFail(res, 502, `Ingress proxy: outbound proxy connection failed (${failureLabel(err)})`);
746
+ resolve();
747
+ });
748
+ };
749
+ relayOnce();
750
+ });
751
+ }
752
+ /**
753
+ * Plain-HTTP target via an outbound HTTP proxy (absolute-URI request form).
754
+ * No TLS options: an absolute-URI hop is already plaintext from this proxy to
755
+ * the next one.
756
+ */
757
+ function forwardPlainViaProxy(req, res, t, proxyUrl) {
758
+ return new Promise((resolve) => {
759
+ const p = parseProxy(proxyUrl);
760
+ if (!p) {
761
+ // The egress resolved to `proxy` (an endpoint was configured) but this leg
762
+ // cannot parse it. Falling back to a direct dial would put the client's
763
+ // real address on traffic the operator asked to proxy — the same silent
764
+ // leak the host axle refuses everywhere else. Answer 502 instead.
765
+ t.tap?.finish(undefined, undefined, 'outbound proxy url unparseable');
766
+ proxyFail(res, 502, EGRESS_UNAVAILABLE_MESSAGE);
767
+ resolve();
768
+ return;
769
+ }
770
+ const headers = filterHeaders(req.headers);
771
+ if (p.auth)
772
+ headers['proxy-authorization'] = p.auth;
773
+ const upstream = http.request({
774
+ host: p.host,
775
+ port: p.port,
776
+ method: req.method,
777
+ path: `http://${t.host}:${t.port}${t.path}`,
778
+ headers,
779
+ }, (up) => {
780
+ upstream.setTimeout(0);
781
+ res.writeHead(up.statusCode || 502, filterHeaders(up.headers));
782
+ pipeUpResponse(up, res, req, t.tap, t.maxExchangeMs);
783
+ up.on('end', () => {
784
+ t.tap?.finish(up.statusCode, up.headers);
785
+ resolve();
786
+ });
787
+ up.on('error', () => {
788
+ try {
789
+ res.destroy();
790
+ }
791
+ catch { }
792
+ t.tap?.finish(up.statusCode, up.headers, 'upstream error mid-response');
793
+ resolve();
794
+ });
795
+ });
796
+ armUpstreamKeepalive(upstream);
797
+ upstream.setTimeout(INGRESS_PROXY_HANG_TIMEOUT_MS, () => {
798
+ upstream.destroy(hangGuardError());
799
+ });
800
+ upstream.on('error', (err) => {
801
+ const failure = describeUpstreamFailure(err, { proxied: true });
802
+ t.tap?.finish(undefined, undefined, failure.note);
803
+ proxyFail(res, failure.status, failure.message);
804
+ resolve();
805
+ });
806
+ pumpRequestBody(req, upstream, t.tap, t.preface);
807
+ });
808
+ }
809
+ export async function createIngressProxyServer(deps) {
810
+ const log = deps.log ?? (() => { });
811
+ // The surface registry seam is optional only so tests can boot the proxy
812
+ // without it; a production boot without it would silently lose the MITM-leg
813
+ // early 413/415, so say so once at startup rather than let it go quiet.
814
+ if (!deps.detectSurface)
815
+ log('inner 100-continue guard: no surface registry injected — header-decidable refusals fall through to the body gate');
816
+ setLiveIngressProxy(deps.liveIngressProxy);
817
+ setBootRules(deps.rules, deps.interceptPosture);
818
+ const ca = ensureCa(deps.caDir);
819
+ const minter = new CertMinter(ca);
820
+ // ── inner HTTP server: parses decrypted MITM traffic, intercept-or-forward ──
821
+ const inner = http.createServer((req, res) => {
822
+ void handleInnerRequest(req, res, false);
823
+ });
824
+ // Same liveness bounds as the native leg (utils/server-liveness): an intercepted
825
+ // client is the same kind of client, and "no bound armed" was Bun's default —
826
+ // which is how a stalled request could hold a MITM socket open forever.
827
+ applyInboundLiveness(inner);
828
+ /**
829
+ * `Expect: 100-continue` admission on the MITM legs (RFC 9110 10.1.1): a body whose
830
+ * declared length already exceeds the gateway cap is refused from the HEADERS, so
831
+ * the client never pays for an upload we would discard. Only a target the surface
832
+ * registry recognizes is judged -- a forward to a third-party host is not ours to
833
+ * size-limit, and refusing one would be the proxy inventing a rule it never agreed
834
+ * to. A caller that injected no `detectSurface` gets no early refusal here: the
835
+ * expectation is honoured and the post-body gate still enforces the cap. The cap is the configured one (`bodyLimits.maxBytes`), read at call time so a
836
+ * controlled restart picks the new value up without a rebuild.
837
+ *
838
+ * Installing these listeners suppresses the server's own delivery (verified on Bun
839
+ * 1.3.14 and Node 24), so each leg re-dispatches when the guard says continue. The
840
+ * h2 inner leg needs no guard: RFC 9113 8.2.2 forbids `Expect` in HTTP/2.
841
+ */
842
+ function mitmContinuationRoute(url, res) {
843
+ const surface = deps.detectSurface?.(url);
844
+ if (!surface)
845
+ return undefined;
846
+ const abort = res[MITM_ABORT];
847
+ return {
848
+ capBytes: bodyLimitFor('gateway'),
849
+ errorBody: (err) => surface.errorBody(err.statusCode, err.message, err.code),
850
+ leg: 'mitm',
851
+ // `res.end()` alone leaves the terminated TLS socket open on Bun, so the client
852
+ // would sit waiting for the rest of a body nobody is reading: the refusal must
853
+ // retire the terminator's own connection to be real.
854
+ refuse: typeof abort === 'function' ? abort : undefined,
855
+ };
856
+ }
857
+ inner.on('checkContinue', (req, res) => {
858
+ if (!settleContinuationExpectation(req, res, (url) => mitmContinuationRoute(url, res))) {
859
+ void handleInnerRequest(req, res, false);
860
+ }
861
+ });
862
+ inner.on('clientError', (err, socket) => {
863
+ answerClientError(socket, err, log, 'inner');
864
+ });
865
+ // ── h2 loopback inner (prior-knowledge h2c): the transport-complete half of
866
+ // the MITM leg. EVERY host may reach it (see the ALPN offer below) — h2 is
867
+ // not a vendor feature but the base transport of gRPC/Connect clients, and
868
+ // a proxy that terminates TLS must re-originate the protocol it accepted.
869
+ // Both legs dispatch through the same intercept chain, and the http2
870
+ // compatibility API mirrors the node-http req/res shape the gateway
871
+ // contract consumes.
872
+ const h2Inner = http2.createServer();
873
+ // No HTTP/1-style idle clocks here on purpose: an h2 session is multiplexed and
874
+ // may legitimately sit open between streams, so `keepAliveTimeout`/
875
+ // `headersTimeout` have no meaning on this listener. What DOES bound it: every
876
+ // gateway-dispatched body is read through `readRequestBody`, which arms
877
+ // `REQUEST_BODY_IDLE_TIMEOUT_MS` per chunk on both inner legs, and the session is
878
+ // reaped by the CONNECT lifetime (`INGRESS_PROXY_KEEPALIVE_MS`). If a
879
+ // session-level bound is ever wanted it is `sessionTimeout` on this factory —
880
+ // do not reach for the HTTP/1 knobs.
881
+ h2Inner.on('request', (req, res) => {
882
+ void handleInnerRequest(req, res, true);
883
+ });
884
+ h2Inner.on('sessionError', (err) => {
885
+ log(`h2 inner session error: ${err?.message || err}`);
886
+ });
887
+ async function handleInnerRequest(req, res, h2Leg) {
888
+ try {
889
+ // The CONNECT authority's per-connection entry (host/port + the abort
890
+ // hook); proxy admission carries no identity any more (ADR-0008 §3).
891
+ const mitmTarget = mitmTargets.get(req.socket?.remotePort ?? -1);
892
+ // h2 compatibility requests carry the target in `:authority` (there is
893
+ // no `host` header) — accept either so gateway-declined h2 traffic can
894
+ // still fall through to transparent forward.
895
+ const hostHeader = String(req.headers[':authority'] || req.headers.host || '');
896
+ // Port precedence: an explicit Host/`:authority` port > the CONNECT
897
+ // authority's port > 443. HTTPS clients routinely omit the port from the
898
+ // request head (they assume 443), so `CONNECT host:8443` + `Host: host`
899
+ // used to be forwarded to 443 — a silent wrong-port forward. The CONNECT
900
+ // port rides in on the per-connection `mitmTargets` entry (see
901
+ // onDecryptedConnection), keyed by the loopback source port.
902
+ const connectPort = mitmTarget?.port;
903
+ if (mitmTarget) {
904
+ res[MITM_ABORT] = mitmTarget.abort;
905
+ }
906
+ const { host, port } = splitHostPort(hostHeader, connectPort ?? 443);
907
+ // Normalize the h2 `:authority` BEFORE any gateway sees it. An h2 client
908
+ // may write the default port (`gw.test:443`), an h1 client's `Host`
909
+ // normally omits it — without this a gateway plugin reads a different
910
+ // host spelling per negotiated protocol and has to re-parse it. Same
911
+ // rule as the upstream rebuild (`h2-forward.ts` `authorityOf`): 443 is
912
+ // implicit, every other port is kept.
913
+ if (h2Leg && host && typeof req.headers[':authority'] === 'string') {
914
+ req.headers[':authority'] = authoritySpelling(host, port);
915
+ }
916
+ if (await deps.intercept(req, res))
917
+ return;
918
+ if (!host) {
919
+ proxyFail(res, 400, 'Ingress proxy: missing Host header');
920
+ return;
921
+ }
922
+ const tap = createAccessTap({
923
+ host,
924
+ port,
925
+ method: req.method,
926
+ path: req.url || '/',
927
+ wire: h2Leg ? 'h2' : String(req.headers.upgrade ?? '').toLowerCase().includes('websocket') ? 'ws' : 'h1',
928
+ // h2 pseudo-headers are transport framing, not wire headers — the row
929
+ // already carries host/method/path from them.
930
+ requestHeaders: h2Leg
931
+ ? Object.fromEntries(Object.entries(req.headers).filter(([k]) => !k.startsWith(':')))
932
+ : req.headers,
933
+ });
934
+ const target = {
935
+ host,
936
+ port,
937
+ path: req.url || '/',
938
+ secure: true,
939
+ tap,
940
+ maxExchangeMs: deps.maxExchangeMs,
941
+ };
942
+ // Rule admission on the MITM leg: the inner Host can differ from the
943
+ // CONNECT target, so the same gate runs here (403 lands in the ledger).
944
+ if (isRuleRejected(host)) {
945
+ tap?.finish(403, undefined, 'rejected by rule');
946
+ proxyFail(res, 403, RULE_REJECTED_MESSAGE);
947
+ return;
948
+ }
949
+ // Protocol fidelity: an h2 client is answered upstream over h2 (gRPC and
950
+ // Connect cannot survive an h1 hop). `forwardH2` reports false when the
951
+ // upstream is not h2 — nothing has reached the client at that point, so
952
+ // the h1 forwarder takes over (ADR-0017 §3).
953
+ const upstreamTls = resolveUpstreamTls(deps.upstreamTls);
954
+ if (h2Leg) {
955
+ const relay = await forwardH2(req, res, target, upstreamTls);
956
+ if (relay.owned)
957
+ return;
958
+ target.preface = relay.preface;
959
+ }
960
+ await forwardTo(req, res, target, upstreamTls);
961
+ }
962
+ catch {
963
+ proxyFail(res, 502, 'Ingress proxy error');
964
+ }
965
+ }
966
+ // ── per-host TLS terminators (explicit certs; SNICallback unsupported on Bun) ──
967
+ // EVERY host advertises h2; the ORDER is what differs. Bun honours the
968
+ // SERVER's preference (verified: server ['http/1.1','h2'] + client
969
+ // ['h2','http/1.1'] negotiates http/1.1), so:
970
+ // * unclaimed host → ['http/1.1','h2']: dual-offer clients (curl, browsers,
971
+ // most SDKs) keep the h1 path untouched, while h2-only clients
972
+ // (gRPC/Connect — Cursor included) get h2 instead of a broken h1
973
+ // downgrade. h1 interception therefore has ZERO regression surface.
974
+ // * gateway-claimed host → ['h2','http/1.1']: the plugin wants h2 even
975
+ // from dual-offer clients (it speaks the vendor's h2 wire).
976
+ // The negotiated protocol is only a hint — the preface sniff below is the
977
+ // authority. Ports are assigned at the bottom (before any CONNECT arrives).
978
+ let innerH1Port = 0;
979
+ let innerH2Port = 0;
980
+ // Per-host terminators, LRU-bounded (see MAX_HOST_TERMINATORS): insertion
981
+ // order IS the LRU order — a hit re-inserts. Eviction closes the listener
982
+ // only, never an established connection (server.close stops accepting).
983
+ const terminators = new Map();
984
+ const pendingTerminators = new Map();
985
+ /**
986
+ * Evicted terminators still finishing their grace window (see
987
+ * evictTerminators). Bounded: the whole point of the LRU is a finite fd
988
+ * budget, so draining may not become a second unbounded cache.
989
+ */
990
+ const drainingTerminators = new Map();
991
+ /**
992
+ * Per-connection CONNECT authority, keyed by the loopback source port of the
993
+ * connection this proxy dials into the inner server (= the inner server's
994
+ * `remotePort`). Entries live exactly as long as their connection.
995
+ */
996
+ const mitmTargets = new Map();
997
+ function hostTlsPort(host, targetPort) {
998
+ const h2First = listGatewayHosts().has(host);
999
+ // Cache by host + CONNECT port + ALPN mode: a runtime gateway install flips
1000
+ // a host's ALPN order, and a second CONNECT to another port of the same
1001
+ // host needs its own authority context. There is no identity to partition
1002
+ // by — proxy admission carries none (ADR-0008 §3).
1003
+ const cacheKey = `${host}:${targetPort}|${h2First ? 'gateway' : 'plain'}`;
1004
+ const live = terminators.get(cacheKey);
1005
+ if (live) {
1006
+ terminators.delete(cacheKey);
1007
+ terminators.set(cacheKey, live);
1008
+ return Promise.resolve(live.port);
1009
+ }
1010
+ const inflight = pendingTerminators.get(cacheKey);
1011
+ if (inflight)
1012
+ return inflight.then((t) => t.port);
1013
+ const created = createTerminator(host, targetPort, h2First, cacheKey).then((t) => {
1014
+ pendingTerminators.delete(cacheKey);
1015
+ return t;
1016
+ }, (err) => {
1017
+ // Never cache a FAILED creation — a transient listen error (e.g. an
1018
+ // ephemeral-port collision) must not permanently degrade this host to
1019
+ // the blind-tunnel fallback; the next connection retries from scratch.
1020
+ pendingTerminators.delete(cacheKey);
1021
+ throw err;
1022
+ });
1023
+ pendingTerminators.set(cacheKey, created);
1024
+ return created.then((t) => t.port);
1025
+ }
1026
+ function createTerminator(host, targetPort, h2First, cacheKey) {
1027
+ return new Promise((resolve, reject) => {
1028
+ const { key, cert } = minter.get(host);
1029
+ const target = { host, port: targetPort };
1030
+ let clientErrorLoggedAt = 0;
1031
+ /** One ledger row per dedupe window for a client that never got a request through. */
1032
+ const reportClientFailure = (reason) => {
1033
+ const now = Date.now();
1034
+ if (now - clientErrorLoggedAt < CLIENT_TLS_ERROR_DEDUPE_MS)
1035
+ return;
1036
+ clientErrorLoggedAt = now;
1037
+ recordProxyConnect({ host, port: targetPort, note: `connect (${reason})` });
1038
+ };
1039
+ const srv = tls.createServer({ key, cert, ALPNProtocols: h2First ? ['h2', 'http/1.1'] : ['http/1.1', 'h2'] }, (tlsSock) => onDecryptedConnection(tlsSock, target, reportClientFailure));
1040
+ // A client that REJECTS our leaf (certificate pinning, a missing CA in its
1041
+ // trust store) fails inside the handshake and never sends a request, so
1042
+ // this is the only place that failure is visible. The operator's question
1043
+ // is always "why does this app not work through the proxy" — a console
1044
+ // log line nobody tails is not an answer, so it lands in the ledger.
1045
+ //
1046
+ // Bun 1.3.14 does NOT emit `tlsClientError` when the client rejects the
1047
+ // certificate (verified: the server sees `secureConnection` and then a
1048
+ // bare socket close), so the abort is also caught on the decrypted stream
1049
+ // (see onDecryptedConnection). Both paths share this dedupe: a pinned
1050
+ // client retries in a tight loop and would otherwise evict every real row
1051
+ // from the ring.
1052
+ srv.on('tlsClientError', (e) => {
1053
+ const message = String(e?.message || e);
1054
+ log(`tlsClientError ${host}:${targetPort}: ${message}`);
1055
+ reportClientFailure(`client TLS handshake failed: ${message}`);
1056
+ });
1057
+ srv.on('error', reject);
1058
+ srv.listen(0, '127.0.0.1', () => {
1059
+ const terminator = {
1060
+ srv,
1061
+ port: srv.address().port,
1062
+ state: 'live',
1063
+ };
1064
+ terminators.set(cacheKey, terminator);
1065
+ evictTerminators();
1066
+ resolve(terminator);
1067
+ });
1068
+ });
1069
+ }
1070
+ /**
1071
+ * Retire the LRU tail into a DRAINING set instead of closing it outright.
1072
+ *
1073
+ * `srv.close()` stops accepting but leaves established connections alone —
1074
+ * however a CONNECT that already resolved this terminator's port and has not
1075
+ * dialed yet would hit ECONNREFUSED and degrade to a blind tunnel, silently
1076
+ * losing interception for that exchange. The grace window covers exactly that
1077
+ * window; a drained terminator is never reused for a NEW CONNECT (it is out
1078
+ * of `terminators`, so `hostTlsPort` misses and mints a fresh one).
1079
+ */
1080
+ function evictTerminators() {
1081
+ const bound = deps.maxHostTerminators ?? MAX_HOST_TERMINATORS;
1082
+ while (terminators.size > bound) {
1083
+ const oldest = terminators.keys().next();
1084
+ if (oldest.done)
1085
+ return;
1086
+ const victim = terminators.get(oldest.value);
1087
+ terminators.delete(oldest.value);
1088
+ if (!victim)
1089
+ continue;
1090
+ victim.state = 'draining';
1091
+ drainingTerminators.set(oldest.value, victim);
1092
+ const timer = setTimeout(() => {
1093
+ drainingTerminators.delete(oldest.value);
1094
+ try {
1095
+ victim.srv.close();
1096
+ }
1097
+ catch { }
1098
+ }, TERMINATOR_DRAIN_MS);
1099
+ // Never hold the process open for a drained listener.
1100
+ timer.unref?.();
1101
+ while (drainingTerminators.size > MAX_DRAINING_TERMINATORS) {
1102
+ const stale = drainingTerminators.keys().next();
1103
+ if (stale.done)
1104
+ break;
1105
+ const forced = drainingTerminators.get(stale.value);
1106
+ drainingTerminators.delete(stale.value);
1107
+ try {
1108
+ forced?.srv.close();
1109
+ }
1110
+ catch { }
1111
+ }
1112
+ log(`terminator evicted (LRU bound ${bound}), draining: ${oldest.value}`);
1113
+ }
1114
+ }
1115
+ /**
1116
+ * Decrypted-stream entry for one TLS session: decide h2 / h1 / Upgrade, then
1117
+ * hand the bytes on.
1118
+ *
1119
+ * Attach SYNCHRONOUSLY — a Bun TLSSocket may drop data that arrives with no
1120
+ * listener; buffer until the loopback conn is ready. Bun does not reliably
1121
+ * expose alpnProtocol on the server side at callback time, so the negotiated
1122
+ * ALPN is only a hint — the h2 connection preface ('PRI * HTTP/2.0') is the
1123
+ * authority. On the h1 path the request head is buffered until it is
1124
+ * complete so an `Upgrade:` handshake can be caught BEFORE the inner server
1125
+ * (relayUpgrade); a head that outgrows MAX_HEAD_BYTES goes to the inner
1126
+ * server unexamined.
1127
+ */
1128
+ function onDecryptedConnection(tlsSock, target, reportClientFailure) {
1129
+ /** Client plaintext, in arrival order, regardless of when the hop is ready. */
1130
+ const relay = new OrderedRelay();
1131
+ let conn = null;
1132
+ let decided = false;
1133
+ /**
1134
+ * True once the loopback hop to the inner server is CONNECTED. Until then
1135
+ * every decrypted chunk is held by `relay`, because `conn` exists
1136
+ * (net.connect returns before it connects) and writing to it would QUEUE
1137
+ * bytes ahead of the buffered head. That inversion is not cosmetic: a body
1138
+ * arrives as many chunks, so the tail would reach the parser before the
1139
+ * request line and the inner server answers 400 to a message it never saw —
1140
+ * the client's "request failed with empty body (code 400)" on large prompts.
1141
+ */
1142
+ let connected = false;
1143
+ /** Decrypted bytes seen so far — zero at close means the client never spoke. */
1144
+ let decryptedBytes = 0;
1145
+ /**
1146
+ * Set when the inner request answered with a terminal error envelope: the
1147
+ * client transport is closed as soon as that envelope has been handed over.
1148
+ * The next chunk the inner server emits IS the envelope, so this is exact —
1149
+ * no flush timing guesswork (an immediate `end()` truncated the response;
1150
+ * the inner server's own socket `end()` is inert on Bun).
1151
+ */
1152
+ let abortRequested = false;
1153
+ let abortTimer;
1154
+ const finishAbort = () => {
1155
+ if (abortTimer !== undefined) {
1156
+ clearTimeout(abortTimer);
1157
+ abortTimer = undefined;
1158
+ }
1159
+ if (!abortRequested)
1160
+ return;
1161
+ abortRequested = false;
1162
+ try {
1163
+ tlsSock.end();
1164
+ }
1165
+ catch { }
1166
+ };
1167
+ /** Whatever the relay hands over goes to the inner hop, in order. */
1168
+ const forward = (chunk) => {
1169
+ if (!conn.write(chunk)) {
1170
+ tlsSock.pause();
1171
+ conn.once('drain', () => tlsSock.resume());
1172
+ }
1173
+ };
1174
+ const onDecrypted = (d) => {
1175
+ decryptedBytes += d.length;
1176
+ relay.push(d);
1177
+ if (connected || decided)
1178
+ return;
1179
+ const buf = relay.snapshot();
1180
+ const isH2 = tlsSock.alpnProtocol === 'h2' || buf.subarray(0, 14).toString('latin1') === 'PRI * HTTP/2.0';
1181
+ if (!isH2) {
1182
+ const headEnd = buf.indexOf('\r\n\r\n');
1183
+ if (headEnd === -1) {
1184
+ // No complete head yet: keep buffering ONLY while the bytes still
1185
+ // look like an HTTP/1 request — a non-HTTP tunnel payload (or a head
1186
+ // past MAX_HEAD_BYTES) must not wait for a head that never arrives.
1187
+ const lineEnd = buf.indexOf('\r\n');
1188
+ const firstLine = (lineEnd === -1 ? buf.subarray(0, 64) : buf.subarray(0, lineEnd)).toString('latin1');
1189
+ const looksHttp = lineEnd === -1
1190
+ ? /^[A-Z]{1,8}( [^\r\n]*)?$/.test(firstLine) // still mid request-line
1191
+ : /^[A-Z]+ \S+ HTTP\/1\.[01]$/.test(firstLine);
1192
+ if (buf.length <= MAX_HEAD_BYTES && looksHttp)
1193
+ return;
1194
+ }
1195
+ else {
1196
+ const parsed = parseUpgradeHead(buf.subarray(0, headEnd + 4).toString('latin1'), target.port);
1197
+ if (parsed) {
1198
+ decided = true;
1199
+ tlsSock.removeListener('data', onDecrypted);
1200
+ void relayUpgrade(tlsSock, buf, parsed);
1201
+ return;
1202
+ }
1203
+ }
1204
+ }
1205
+ decided = true;
1206
+ conn = net.connect(isH2 ? innerH2Port : innerH1Port, '127.0.0.1', () => {
1207
+ // Register the CONNECT target BEFORE the first byte reaches the inner
1208
+ // server — the inner request must never run without its authority
1209
+ // context. The key is this loopback connection's source port, which is
1210
+ // exactly the inner server's `remotePort` for the same TCP connection.
1211
+ const localPort = conn.localPort;
1212
+ if (localPort) {
1213
+ mitmTargets.set(localPort, {
1214
+ host: target.host,
1215
+ port: target.port,
1216
+ abort: () => {
1217
+ if (abortRequested)
1218
+ return;
1219
+ abortRequested = true;
1220
+ // Safety net: an envelope that never produces a chunk (or a
1221
+ // response already mid-flight) still closes, just not instantly.
1222
+ abortTimer = setTimeout(finishAbort, MITM_ABORT_FLUSH_MS);
1223
+ abortTimer.unref?.();
1224
+ },
1225
+ });
1226
+ }
1227
+ connected = true;
1228
+ relay.attach(forward, () => {
1229
+ connected = true;
1230
+ });
1231
+ conn.on('data', (d2) => {
1232
+ if (!tlsSock.write(d2)) {
1233
+ conn.pause();
1234
+ tlsSock.once('drain', () => {
1235
+ conn.resume();
1236
+ finishAbort();
1237
+ });
1238
+ return;
1239
+ }
1240
+ finishAbort();
1241
+ });
1242
+ conn.on('end', () => {
1243
+ try {
1244
+ tlsSock.end();
1245
+ }
1246
+ catch { }
1247
+ });
1248
+ conn.on('error', () => {
1249
+ try {
1250
+ tlsSock.destroy();
1251
+ }
1252
+ catch { }
1253
+ });
1254
+ });
1255
+ conn.on('close', () => {
1256
+ const localPort = conn?.localPort;
1257
+ if (localPort)
1258
+ mitmTargets.delete(localPort);
1259
+ });
1260
+ conn.on('error', () => {
1261
+ try {
1262
+ tlsSock.destroy();
1263
+ }
1264
+ catch { }
1265
+ });
1266
+ };
1267
+ tlsSock.on('data', onDecrypted);
1268
+ tlsSock.on('end', () => {
1269
+ try {
1270
+ conn?.end();
1271
+ }
1272
+ catch { }
1273
+ });
1274
+ // The pinning signal Bun actually gives us: a TLS session that closes
1275
+ // WITHOUT a single decrypted byte. A client that rejects our leaf aborts
1276
+ // right after the handshake, so no request head ever arrives.
1277
+ tlsSock.on('close', () => {
1278
+ if (decryptedBytes === 0) {
1279
+ reportClientFailure('client closed the intercepted TLS session before any request (certificate rejected or client abort)');
1280
+ }
1281
+ });
1282
+ tlsSock.on('error', () => {
1283
+ try {
1284
+ conn?.destroy();
1285
+ }
1286
+ catch { }
1287
+ });
1288
+ }
1289
+ // ── tunnel (no decryption) ──
1290
+ function tunnel(socket, host, port, replay) {
1291
+ // Egress comes from the ordered rule table (ADR-0018), and a decision that
1292
+ // cannot be honoured refuses the tunnel instead of dialing direct. The
1293
+ // CONNECT admission gate already refused a blocked host before its 200, so
1294
+ // this is the backstop for the paths that run AFTER it (an MITM setup
1295
+ // failure falling back to a tunnel, and a hot config flip in between).
1296
+ const egress = resolveDialEgress(host);
1297
+ if (egress.via === 'blocked') {
1298
+ // Every caller of `tunnel()` runs AFTER the CONNECT's `200 Connection
1299
+ // Established` (the admission gate refuses a blocked host before it), so a
1300
+ // status line here would arrive inside the client's TLS stream and be read
1301
+ // as tunnel bytes. Closing is the only honest answer; the ledger row is the
1302
+ // operator's evidence.
1303
+ log(`refuse tunnel ${host}:${port} (egress unavailable, no outbound proxy)`);
1304
+ recordProxyConnect({ host, port, note: 'connect (egress unavailable, no outbound proxy)' });
1305
+ try {
1306
+ socket.destroy();
1307
+ }
1308
+ catch { }
1309
+ return;
1310
+ }
1311
+ const proxyUrl = egress.via === 'proxy' ? egress.url : undefined;
1312
+ // Tunnel observation (ADR-0020): a blind tunnel is opaque BY DESIGN, so the
1313
+ // identity we can see without decrypting (SNI, offered ALPN), the byte
1314
+ // totals and the lifetime are the whole story. The peek rides the relay's
1315
+ // own tap — it can never steal bytes from the splice.
1316
+ const started = Date.now();
1317
+ let reqBytes = replay?.length ?? 0;
1318
+ let respBytes = 0;
1319
+ let identity;
1320
+ let identityDone = false;
1321
+ const hello = [];
1322
+ let helloTotal = 0;
1323
+ const observe = (dir, chunk) => {
1324
+ if (dir === 'b2a') {
1325
+ respBytes += chunk.length;
1326
+ return;
1327
+ }
1328
+ reqBytes += chunk.length;
1329
+ if (identityDone)
1330
+ return;
1331
+ hello.push(chunk);
1332
+ helloTotal += chunk.length;
1333
+ const peek = peekClientHello(Buffer.concat(hello, helloTotal));
1334
+ if (!peek.isTls) {
1335
+ identityDone = true;
1336
+ identity = 'not tls';
1337
+ return;
1338
+ }
1339
+ if (peek.complete || helloTotal > MAX_HELLO_BYTES) {
1340
+ identityDone = true;
1341
+ // The peek buffer is only needed until the identity is known; a tunnel
1342
+ // can outlive it by hours, so do not pin the hello bytes.
1343
+ hello.length = 0;
1344
+ if (!peek.complete)
1345
+ return;
1346
+ const bits = [peek.sni ? `sni ${peek.sni}` : 'no sni'];
1347
+ // Space-separated: a protocol id may itself contain '/', so a slash
1348
+ // separator would make "h2" + "http/1.1" unreadable.
1349
+ if (peek.alpn?.length)
1350
+ bits.push(`alpn ${peek.alpn.join(' ')}`);
1351
+ identity = bits.join(', ');
1352
+ }
1353
+ };
1354
+ let closed = false;
1355
+ const closeRow = (note) => {
1356
+ if (closed)
1357
+ return;
1358
+ closed = true;
1359
+ recordProxyTunnel({
1360
+ host,
1361
+ port,
1362
+ note: identity ? `${note}, ${identity}` : note,
1363
+ reqBytes,
1364
+ respBytes,
1365
+ durationMs: Date.now() - started,
1366
+ });
1367
+ };
1368
+ socket.on('close', () => closeRow('connect (tunnel closed)'));
1369
+ if (proxyUrl) {
1370
+ openViaProxy(proxyUrl, host, port)
1371
+ .then((up) => {
1372
+ up.on('close', () => closeRow('connect (tunnel via outbound proxy closed)'));
1373
+ if (replay && replay.length)
1374
+ up.write(replay);
1375
+ splice(socket, up, { tap: observe, onActivity: () => touchAdmitted(socket), abandonedTunnelMs: deps.abandonedTunnelMs, halfCloseReapMs: deps.halfCloseReapMs });
1376
+ })
1377
+ .catch((err) => {
1378
+ log(`tunnel via outbound proxy failed for ${host}:${port}: ${err?.message || err}`);
1379
+ closeRow(`connect (tunnel failed: outbound proxy ${err?.code || err?.message || err})`);
1380
+ try {
1381
+ socket.destroy();
1382
+ }
1383
+ catch { }
1384
+ });
1385
+ return;
1386
+ }
1387
+ const up = net.connect(port, host, () => {
1388
+ if (replay && replay.length)
1389
+ up.write(replay);
1390
+ splice(socket, up, { tap: observe, onActivity: () => touchAdmitted(socket), abandonedTunnelMs: deps.abandonedTunnelMs, halfCloseReapMs: deps.halfCloseReapMs });
1391
+ });
1392
+ up.on('close', () => closeRow('connect (tunnel closed)'));
1393
+ up.on('error', (err) => closeRow(`connect (tunnel failed: ${err?.code || err?.message || err})`));
1394
+ up.on('error', () => {
1395
+ try {
1396
+ socket.destroy();
1397
+ }
1398
+ catch { }
1399
+ });
1400
+ socket.on('error', () => {
1401
+ try {
1402
+ up.destroy();
1403
+ }
1404
+ catch { }
1405
+ });
1406
+ }
1407
+ /**
1408
+ * WebSocket / generic `Upgrade:` relay on the MITM leg.
1409
+ *
1410
+ * Bun's node:http 'upgrade' event is NOT usable (verified on 1.3.14: the
1411
+ * socket handed to the handler swallows every write and the parser keeps
1412
+ * running, answering 505 to whatever the client sends next), so the
1413
+ * handshake is caught on the DECRYPTED stream before it reaches the inner
1414
+ * server and relayed byte-verbatim: request head (+ any bytes the client
1415
+ * already pipelined after it) → origin socket, then a raw bidirectional
1416
+ * splice. Nothing is re-serialized — an upgrade is a single hop, so the
1417
+ * client's own handshake headers are exactly what the origin must see, and
1418
+ * any upgrade protocol rides this path, not just WebSocket.
1419
+ *
1420
+ * Non-TLS `ws://` through the plain proxy port is NOT covered: that leg
1421
+ * never decrypts, and the same runtime gap blocks its 'upgrade' event.
1422
+ */
1423
+ async function relayUpgrade(tlsSock, head, parsed) {
1424
+ const { host, port } = parsed;
1425
+ // A client gateway may OWN the handshake (a WS-native vendor wire). Without
1426
+ // this hook an upgrade on a claimed host is relayed verbatim and the plugin
1427
+ // never sees it — the same host would be handled for requests but not for
1428
+ // sockets. Returning false (or throwing) falls through to the relay.
1429
+ const gateway = findGateway({ method: parsed.method, url: parsed.path, headers: parsed.headers });
1430
+ if (gateway?.handleUpgrade) {
1431
+ try {
1432
+ const owned = await gateway.handleUpgrade({
1433
+ socket: tlsSock,
1434
+ head,
1435
+ host,
1436
+ port,
1437
+ method: parsed.method,
1438
+ path: parsed.path,
1439
+ headers: parsed.headers,
1440
+ });
1441
+ if (owned)
1442
+ return;
1443
+ }
1444
+ catch {
1445
+ // Ownership was ambiguous — never leave the client hanging on a socket
1446
+ // nobody drives; the gateway already had its chance to answer.
1447
+ try {
1448
+ tlsSock.destroy();
1449
+ }
1450
+ catch { }
1451
+ return;
1452
+ }
1453
+ }
1454
+ const tap = createAccessTap({
1455
+ host,
1456
+ port,
1457
+ method: parsed.method,
1458
+ path: parsed.path,
1459
+ requestHeaders: parsed.headers,
1460
+ });
1461
+ let status;
1462
+ let finished = false;
1463
+ const finish = (note) => {
1464
+ if (finished)
1465
+ return;
1466
+ finished = true;
1467
+ tap?.finish(status, undefined, note);
1468
+ };
1469
+ // Only answer with an error envelope while the origin has said nothing —
1470
+ // once its bytes are flowing, the client owns the stream.
1471
+ const fail = (note) => {
1472
+ finish(note);
1473
+ if (status !== undefined) {
1474
+ try {
1475
+ tlsSock.destroy();
1476
+ }
1477
+ catch { }
1478
+ return;
1479
+ }
1480
+ try {
1481
+ tlsSock.write(`HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\nIngress proxy: ${note}`);
1482
+ tlsSock.end();
1483
+ }
1484
+ catch { }
1485
+ };
1486
+ /**
1487
+ * The same answer, built from a classified origin failure (ADR-0019): status,
1488
+ * client-facing sentence and ledger note all come from
1489
+ * `describeUpstreamFailure`, so an upgrade leg reports a TLS trust failure
1490
+ * exactly like the h1 and h2 legs do.
1491
+ */
1492
+ const failWith = (failure) => {
1493
+ finish(failure.note);
1494
+ if (status !== undefined) {
1495
+ try {
1496
+ tlsSock.destroy();
1497
+ }
1498
+ catch { }
1499
+ return;
1500
+ }
1501
+ try {
1502
+ tlsSock.write(`HTTP/1.1 ${failure.status} ${failure.status === 504 ? 'Gateway Timeout' : 'Bad Gateway'}\r\n` +
1503
+ 'Content-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n' +
1504
+ failure.message);
1505
+ tlsSock.end();
1506
+ }
1507
+ catch { }
1508
+ };
1509
+ const onOrigin = (origin) => {
1510
+ // Hang guard until the origin answers: a blackholed upgrade must not
1511
+ // hold the client's socket open forever. Cleared on the first byte so a
1512
+ // long-lived WebSocket is never killed.
1513
+ const hang = setTimeout(() => {
1514
+ try {
1515
+ origin.destroy();
1516
+ }
1517
+ catch { }
1518
+ fail('upgrade upstream timed out');
1519
+ }, INGRESS_PROXY_HANG_TIMEOUT_MS);
1520
+ // Frame-level observation (ADR-0020): the relay stays byte-verbatim, the
1521
+ // observer only counts what crosses it. Frames begin after the origin
1522
+ // response head, so the first chunk is split at its CRLFCRLF marker.
1523
+ const ws = createWsObserver();
1524
+ let responseHeadSeen = false;
1525
+ // The response head is accumulated across chunks: an origin may split it,
1526
+ // and the frames start at its end — guessing from a single chunk either
1527
+ // lost the status or fed handshake bytes to the frame parser.
1528
+ let responseHead = '';
1529
+ const noteFor = () => (status === 101 ? ws.note() : '');
1530
+ origin.on('data', (d) => {
1531
+ clearTimeout(hang);
1532
+ tap?.onResChunk(d);
1533
+ if (!responseHeadSeen) {
1534
+ responseHead += d.toString('latin1');
1535
+ const end = responseHead.indexOf('\r\n\r\n');
1536
+ if (end === -1) {
1537
+ if (responseHead.length > MAX_HEAD_BYTES)
1538
+ responseHeadSeen = true;
1539
+ return;
1540
+ }
1541
+ responseHeadSeen = true;
1542
+ if (status === undefined) {
1543
+ const m = /^HTTP\/1\.[01] (\d{3})/.exec(responseHead.slice(0, 16));
1544
+ if (m)
1545
+ status = Number(m[1]);
1546
+ }
1547
+ const rest = responseHead.slice(end + 4);
1548
+ if (rest.length)
1549
+ ws.push('s2c', Buffer.from(rest, 'latin1'));
1550
+ return;
1551
+ }
1552
+ ws.push('s2c', d);
1553
+ });
1554
+ tlsSock.on('data', (d) => {
1555
+ tap?.onReqChunk(d);
1556
+ ws.push('c2s', d);
1557
+ });
1558
+ origin.on('close', () => {
1559
+ clearTimeout(hang);
1560
+ finish(noteFor());
1561
+ });
1562
+ tlsSock.on('close', () => {
1563
+ clearTimeout(hang);
1564
+ finish(noteFor());
1565
+ });
1566
+ origin.write(head);
1567
+ splice(tlsSock, origin);
1568
+ };
1569
+ const egress = resolveDialEgress(host);
1570
+ if (egress.via === 'blocked') {
1571
+ // The same sentence every other leg answers: the body names the fix, the
1572
+ // ledger note names the cause.
1573
+ finish('egress unavailable, no outbound proxy');
1574
+ try {
1575
+ tlsSock.write('HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n' +
1576
+ EGRESS_UNAVAILABLE_MESSAGE);
1577
+ tlsSock.end();
1578
+ }
1579
+ catch { }
1580
+ return;
1581
+ }
1582
+ const proxyUrl = egress.via === 'proxy' ? egress.url : undefined;
1583
+ const upstreamTls = resolveUpstreamTls(deps.upstreamTls).opts;
1584
+ if (proxyUrl) {
1585
+ openViaProxy(proxyUrl, host, port)
1586
+ .then((tunnelSock) => {
1587
+ try {
1588
+ const origin = tls.connect({ socket: tunnelSock, ...upstreamServernameOption(host), ...(upstreamTls || {}) }, () => onOrigin(origin));
1589
+ origin.once('error', (err) => failWith(describeUpstreamFailure(err, { proxied: true })));
1590
+ }
1591
+ catch {
1592
+ // A synchronous TLS-option throw (bad servername, bad material) must
1593
+ // not escape a socket callback — answer the client instead.
1594
+ try {
1595
+ tunnelSock.destroy();
1596
+ }
1597
+ catch { }
1598
+ fail('upgrade upstream TLS setup failed');
1599
+ }
1600
+ })
1601
+ .catch((err) => fail(`upgrade outbound proxy connection failed${err?.code ? ` (${err.code})` : ''}`));
1602
+ return;
1603
+ }
1604
+ try {
1605
+ const origin = tls.connect({ host, port, ...upstreamServernameOption(host), ...(upstreamTls || {}) }, () => onOrigin(origin));
1606
+ origin.once('error', (err) => failWith(describeUpstreamFailure(err)));
1607
+ }
1608
+ catch {
1609
+ fail('upgrade upstream TLS setup failed');
1610
+ }
1611
+ }
1612
+ // ── CONNECT: peek ClientHello → MITM, else blind tunnel ──
1613
+ function handleConnect(req, socket, head) {
1614
+ // Bracket-aware: `[::1]:8443` is a valid authority, and `rawHost` becomes
1615
+ // the CERTIFICATE IDENTITY for a no-SNI client (see the MITM branch), so a
1616
+ // naive `split(':')` would mint a leaf for `[`.
1617
+ const { host: rawHost, port } = splitHostPort(String(req.url || ''), 443);
1618
+ if (!rawHost) {
1619
+ try {
1620
+ socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
1621
+ }
1622
+ catch { }
1623
+ return;
1624
+ }
1625
+ if (!admit(socket)) {
1626
+ // A raw socket may not be TLS-ready yet, so there is no status line to
1627
+ // write — closing it is the only honest answer.
1628
+ if (shouldRecordPreAdmission(`cap:${rawHost}`)) {
1629
+ recordProxyConnect({ host: rawHost, port, note: 'connect (503-equivalent, connection cap reached)' });
1630
+ }
1631
+ try {
1632
+ socket.destroy();
1633
+ }
1634
+ catch { }
1635
+ return;
1636
+ }
1637
+ // Rule admission (ADR-0018): a rejected host is answered 403 on the raw
1638
+ // socket BEFORE the 200, so no tunnel is opened and no certificate is
1639
+ // minted for a host this machine refuses to reach.
1640
+ if (isRuleRejected(rawHost)) {
1641
+ log(`reject CONNECT ${rawHost}:${port} (egress rule)`);
1642
+ recordProxyConnect({ host: rawHost, port, note: 'connect (rejected by rule)' });
1643
+ try {
1644
+ socket.end(RULE_REJECT_RESPONSE);
1645
+ }
1646
+ catch { }
1647
+ return;
1648
+ }
1649
+ // Egress admission for the BLIND-TUNNEL half (ADR-0018): a tunnel exists only
1650
+ // to send bytes somewhere, so a route that says `proxy` with no outbound
1651
+ // proxy is refused BEFORE the 200 — after it, a status line would be read as
1652
+ // tunnel bytes by the client. The MITM half is deliberately NOT gated here:
1653
+ // its request may never dial at all (a gateway interceptor answers it), so
1654
+ // the same refusal lives in the terminator's own forward legs.
1655
+ const tunnels = ruleTunnels(rawHost);
1656
+ if (tunnels && resolveDialEgress(rawHost).via === 'blocked') {
1657
+ log(`refuse CONNECT ${rawHost}:${port} (egress unavailable, no outbound proxy)`);
1658
+ recordProxyConnect({ host: rawHost, port, note: 'connect (egress unavailable, no outbound proxy)' });
1659
+ try {
1660
+ socket.end(EGRESS_UNAVAILABLE_RESPONSE);
1661
+ }
1662
+ catch { }
1663
+ return;
1664
+ }
1665
+ socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
1666
+ if (head && head.length)
1667
+ socket.unshift(head);
1668
+ if (tunnels) {
1669
+ recordProxyConnect({ host: rawHost, port, note: 'connect (blind tunnel)' });
1670
+ // Any bytes that arrived with the CONNECT are ALREADY back in the socket's
1671
+ // read buffer (the unshift above), so no replay is passed here: doing so
1672
+ // would duplicate the client's first bytes upstream. The identity peek
1673
+ // rides the relay's tap, which is attached at dial time.
1674
+ tunnel(socket, rawHost, port);
1675
+ return;
1676
+ }
1677
+ const chunks = [];
1678
+ let total = 0;
1679
+ let decided = false;
1680
+ const onData = (d) => {
1681
+ if (decided)
1682
+ return;
1683
+ chunks.push(d);
1684
+ total += d.length;
1685
+ const buf = Buffer.concat(chunks, total);
1686
+ const peek = peekClientHello(buf);
1687
+ if (!peek.isTls) {
1688
+ // Not a TLS handshake at all (SSH, IMAPS, a bespoke protocol): relay it
1689
+ // NOW. Waiting for a ClientHello that can never arrive used to stall
1690
+ // such a tunnel until 32 KiB had accumulated on the socket.
1691
+ decided = true;
1692
+ socket.pause();
1693
+ socket.removeListener('data', onData);
1694
+ log(`tunnel ${rawHost}:${port} (not tls)`);
1695
+ recordProxyConnect({ host: rawHost, port, note: 'connect (not tls, blind tunnel)' });
1696
+ tunnel(socket, rawHost, port, buf);
1697
+ return;
1698
+ }
1699
+ if (peek.complete) {
1700
+ // A ClientHello WITHOUT SNI is still interceptable: the CONNECT
1701
+ // authority is the only identity the client offered (IP-literal
1702
+ // targets can never carry SNI — RFC 6066 forbids an IP there). Falling
1703
+ // back to a blind tunnel here let any client opt out of interception
1704
+ // simply by omitting the extension.
1705
+ const identity = peek.sni || rawHost;
1706
+ decided = true;
1707
+ socket.pause();
1708
+ socket.removeListener('data', onData);
1709
+ log(peek.sni ? `MITM ${identity}` : `MITM ${identity} (no SNI, authority identity)`);
1710
+ void startMitm(socket, buf, identity, port, peek.sni ? 'sni' : 'authority');
1711
+ return;
1712
+ }
1713
+ if (total > MAX_HELLO_BYTES) {
1714
+ decided = true;
1715
+ socket.pause();
1716
+ socket.removeListener('data', onData);
1717
+ log(`tunnel ${rawHost}:${port} (ClientHello never completed)`);
1718
+ recordProxyConnect({ host: rawHost, port, note: 'connect (hello incomplete, blind tunnel)' });
1719
+ tunnel(socket, rawHost, port, buf);
1720
+ }
1721
+ };
1722
+ socket.on('data', onData);
1723
+ socket.on('error', () => {
1724
+ try {
1725
+ socket.destroy();
1726
+ }
1727
+ catch { }
1728
+ });
1729
+ }
1730
+ async function startMitm(socket, hello, identity, connectPort, by) {
1731
+ try {
1732
+ const port = await hostTlsPort(identity, connectPort);
1733
+ recordProxyConnect({
1734
+ host: identity,
1735
+ port: connectPort,
1736
+ note: by === 'sni' ? 'connect (mitm)' : 'connect (mitm by authority, no sni)',
1737
+ });
1738
+ const up = net.connect(port, '127.0.0.1', () => {
1739
+ up.write(hello);
1740
+ splice(socket, up, { onActivity: () => touchAdmitted(socket), abandonedTunnelMs: deps.abandonedTunnelMs, halfCloseReapMs: deps.halfCloseReapMs });
1741
+ });
1742
+ up.on('error', () => {
1743
+ try {
1744
+ socket.destroy();
1745
+ }
1746
+ catch { }
1747
+ });
1748
+ socket.on('error', () => {
1749
+ try {
1750
+ up.destroy();
1751
+ }
1752
+ catch { }
1753
+ });
1754
+ }
1755
+ catch (err) {
1756
+ log(`MITM setup failed for ${identity}: ${err?.message || err} — blind tunnel fallback`);
1757
+ recordProxyConnect({ host: identity, port: connectPort, note: 'connect (mitm setup failed, blind tunnel fallback)' });
1758
+ tunnel(socket, identity, connectPort);
1759
+ }
1760
+ }
1761
+ // ── outer proxy server: CONNECT + plain-HTTP absolute-URI requests ──
1762
+ const proxy = http.createServer((req, res) => {
1763
+ void handlePlainProxyRequest(req, res);
1764
+ });
1765
+ // The outer leg terminates client TCP too, so it gets the same bounds. The blind
1766
+ // TUNNEL behind it is deliberately NOT timed by an HTTP idle clock — a tunneled
1767
+ // protocol may sit idle on purpose (IMAP IDLE), which is what
1768
+ // INGRESS_PROXY_KEEPALIVE_MS exists to reap instead.
1769
+ applyInboundLiveness(proxy);
1770
+ proxy.on('checkContinue', (req, res) => {
1771
+ // Absolute-form target on this leg (`http://gw.test:8443/v1/chat/completions`);
1772
+ // `detectSurface` matches on the trailing path, so the spelling needs no rewrite,
1773
+ // but a non-gateway target simply never matches and gets the continue.
1774
+ if (!settleContinuationExpectation(req, res, (url) => mitmContinuationRoute(url, res))) {
1775
+ void handlePlainProxyRequest(req, res);
1776
+ }
1777
+ });
1778
+ proxy.on('connect', handleConnect);
1779
+ proxy.on('clientError', (err, socket) => {
1780
+ answerClientError(socket, err, log, 'proxy');
1781
+ });
1782
+ const liveSockets = new Map();
1783
+ const staleTunnelMs = deps.staleTunnelMs ?? INGRESS_PROXY_STALE_TUNNEL_MS;
1784
+ let capWarnedAt = 0;
1785
+ let pressureLoggedAt = 0;
1786
+ const currentCap = () => deps.liveIngressProxy?.()?.maxConnections ?? deps.maxConnections ?? DEFAULT_INGRESS_PROXY_MAX_CONNECTIONS;
1787
+ /**
1788
+ * Drop the entries the runtime already reports as dead. `destroyed` covers the
1789
+ * sockets something in this process closed; `readyState === 'closed'` is the
1790
+ * second signal Bun leaves behind (verified on 1.3.14: a CONNECT socket reads
1791
+ * `open`, then `writeOnly` once the peer half-closes, then `closed`).
1792
+ */
1793
+ const pruneDead = () => {
1794
+ let reaped = 0;
1795
+ for (const socket of [...liveSockets.keys()]) {
1796
+ if (!socket.destroyed && socket.readyState !== 'closed')
1797
+ continue;
1798
+ liveSockets.delete(socket);
1799
+ reaped++;
1800
+ }
1801
+ return reaped;
1802
+ };
1803
+ /**
1804
+ * Last resort before refusing a new exchange: retire the longest-silent
1805
+ * entries, oldest first, until the table has room again. A quiet tunnel is
1806
+ * never timed out by policy — an idle protocol is legitimate — so this runs
1807
+ * ONLY while the cap is full, where the alternative is refusing a live client.
1808
+ */
1809
+ const evictSilent = (cap) => {
1810
+ const now = Date.now();
1811
+ const stale = [...liveSockets.values()]
1812
+ .filter((e) => now - e.lastActivityAt >= staleTunnelMs)
1813
+ .sort((x, y) => x.lastActivityAt - y.lastActivityAt || x.admittedAt - y.admittedAt);
1814
+ let reaped = 0;
1815
+ for (const entry of stale) {
1816
+ if (liveSockets.size < cap)
1817
+ break;
1818
+ liveSockets.delete(entry.socket);
1819
+ reaped++;
1820
+ // destroy() also retires the spliced peer: splice() turns a local close
1821
+ // into a peer destroy, which is what returns the second descriptor.
1822
+ try {
1823
+ entry.socket.destroy();
1824
+ }
1825
+ catch { }
1826
+ }
1827
+ return reaped;
1828
+ };
1829
+ /** Liveness stamp for the eviction order — the relay calls it per chunk. */
1830
+ const touchAdmitted = (socket) => {
1831
+ const entry = liveSockets.get(socket);
1832
+ if (entry)
1833
+ entry.lastActivityAt = Date.now();
1834
+ };
1835
+ const admissionSweep = setInterval(() => {
1836
+ const cap = currentCap();
1837
+ const reaped = pruneDead();
1838
+ if (reaped > 0) {
1839
+ log(`admission ledger: pruned ${reaped} closed socket(s) (cap ${cap}, ${liveSockets.size} held)`);
1840
+ }
1841
+ // A cap that fills up is the ONE thing an operator cannot see from outside
1842
+ // (the sockets are already gone when they look), and it was three weeks of
1843
+ // "why is it slow" the first time. Say it out loud before it starts
1844
+ // refusing traffic, at most once a minute.
1845
+ const now = Date.now();
1846
+ if (liveSockets.size >= cap * 0.9 && now - pressureLoggedAt > 60_000) {
1847
+ pressureLoggedAt = now;
1848
+ log(`admission ledger: ${liveSockets.size}/${cap} slots held — reclaiming before the cap refuses traffic`);
1849
+ }
1850
+ }, deps.admissionSweepMs ?? INGRESS_PROXY_ADMISSION_SWEEP_MS);
1851
+ admissionSweep.unref?.();
1852
+ /** true = this socket may proceed; false = it was already refused. */
1853
+ const admit = (socket) => {
1854
+ const seen = liveSockets.get(socket);
1855
+ if (seen) {
1856
+ // A keep-alive plain-HTTP socket asks once per request; re-admission is free.
1857
+ seen.lastActivityAt = Date.now();
1858
+ return true;
1859
+ }
1860
+ const cap = currentCap();
1861
+ if (liveSockets.size >= cap) {
1862
+ const reaped = pruneDead() + evictSilent(cap);
1863
+ if (reaped > 0) {
1864
+ log(`connection cap (${cap}) was full: reclaimed ${reaped} dead/silent socket(s), ${liveSockets.size} held`);
1865
+ }
1866
+ }
1867
+ if (liveSockets.size >= cap) {
1868
+ const now = Date.now();
1869
+ if (now - capWarnedAt > CLIENT_TLS_ERROR_DEDUPE_MS) {
1870
+ capWarnedAt = now;
1871
+ log(`connection cap reached (${cap}) — refusing new exchanges`);
1872
+ }
1873
+ return false;
1874
+ }
1875
+ const now = Date.now();
1876
+ liveSockets.set(socket, { socket, admittedAt: now, lastActivityAt: now });
1877
+ // Releasing only on 'close' leaked a slot per finished tunnel and wedged the
1878
+ // cap shut on a live install, so all three terminal signals release here
1879
+ // (a double release is a no-op on a Map). NONE of them is guaranteed: the
1880
+ // shapes reproduced on loopback deliver `end` (and `close` once we destroy),
1881
+ // but the drift observed in production was entries whose sockets were
1882
+ // already gone with no event delivered at all — that is what the sweep and
1883
+ // the pressure pass above are for.
1884
+ const release = () => {
1885
+ liveSockets.delete(socket);
1886
+ };
1887
+ socket.once('close', release);
1888
+ socket.once('end', release);
1889
+ socket.once('error', release);
1890
+ return true;
1891
+ };
1892
+ async function handlePlainProxyRequest(req, res) {
1893
+ let target;
1894
+ let target0;
1895
+ try {
1896
+ target = new URL(req.url || '');
1897
+ target0 = target;
1898
+ }
1899
+ catch {
1900
+ const badReqHost = String(req.headers.host || req.socket.remoteAddress || 'unknown').split(':')[0];
1901
+ if (shouldRecordPreAdmission(`badreq:${badReqHost}`)) {
1902
+ recordProxyConnect({
1903
+ host: badReqHost,
1904
+ port: req.socket.remotePort || 0,
1905
+ note: `plain ${req.method || '?'} (400, not an absolute-form request URI)`,
1906
+ });
1907
+ }
1908
+ proxyFail(res, 400, 'Ingress proxy requires an absolute-form request URI');
1909
+ return;
1910
+ }
1911
+ if (!admit(req.socket)) {
1912
+ if (shouldRecordPreAdmission(`cap:${target0.hostname}`)) {
1913
+ recordProxyConnect({
1914
+ host: target0.hostname,
1915
+ port: parseInt(target0.port || '0', 10),
1916
+ note: `plain ${req.method} (503, connection cap reached)`,
1917
+ });
1918
+ }
1919
+ proxyFail(res, 503, 'Ingress proxy: connection limit reached');
1920
+ return;
1921
+ }
1922
+ // A PLAIN exchange holds its slot only while the exchange is in flight. The
1923
+ // socket it arrived on is a keep-alive wrapper the HTTP server owns, and on
1924
+ // this runtime it has no probeable handle at all (measured: `_handle === null`,
1925
+ // `destroyed` stays false, and not one of close/end/error/timeout ever fires
1926
+ // when the client process dies), so a slot released on socket-close leaks for
1927
+ // every abandoned keep-alive connection. CONNECT tunnels keep the connection
1928
+ // as their unit; a plain request's unit is the exchange (ADR-0018 Rev.6).
1929
+ //
1930
+ // The abandoned case is bounded, not event-driven: when the client vanishes
1931
+ // mid-exchange NONE of res 'finish'/'close' or req 'close'/'aborted' arrives
1932
+ // (measured on a real Bun server), so the slot carries the same wall clock as
1933
+ // its response leg.
1934
+ let slotCap;
1935
+ const releaseAfterExchange = () => {
1936
+ if (slotCap)
1937
+ clearTimeout(slotCap);
1938
+ liveSockets.delete(req.socket);
1939
+ };
1940
+ slotCap = setTimeout(releaseAfterExchange, deps.maxExchangeMs ?? INGRESS_PROXY_MAX_EXCHANGE_MS);
1941
+ slotCap.unref?.();
1942
+ res.once('finish', releaseAfterExchange);
1943
+ res.once('close', releaseAfterExchange);
1944
+ const intercept = !ruleTunnels(target.hostname);
1945
+ try {
1946
+ // `ingress: 'passthrough'` = a blind tunnel: the intercept chain never
1947
+ // runs and the exchange is forwarded transparently.
1948
+ if (intercept && (await deps.intercept(req, res)))
1949
+ return;
1950
+ const tap = createAccessTap({
1951
+ host: target.hostname,
1952
+ port: parseInt(target.port || (target.protocol === 'https:' ? '443' : '80'), 10),
1953
+ method: req.method,
1954
+ path: req.url || '/',
1955
+ wire: String(req.headers.upgrade ?? '').toLowerCase().includes('websocket') ? 'ws' : 'h1',
1956
+ requestHeaders: req.headers,
1957
+ });
1958
+ if (isRuleRejected(target.hostname)) {
1959
+ tap?.finish(403, undefined, 'rejected by rule');
1960
+ proxyFail(res, 403, RULE_REJECTED_MESSAGE);
1961
+ return;
1962
+ }
1963
+ await forwardTo(req, res, {
1964
+ host: target.hostname,
1965
+ port: parseInt(target.port || (target.protocol === 'https:' ? '443' : '80'), 10),
1966
+ path: target.pathname + target.search,
1967
+ secure: target.protocol === 'https:',
1968
+ tap,
1969
+ maxExchangeMs: deps.maxExchangeMs,
1970
+ }, resolveUpstreamTls(deps.upstreamTls));
1971
+ }
1972
+ catch {
1973
+ proxyFail(res, 502, 'Ingress proxy error');
1974
+ }
1975
+ }
1976
+ await listen(inner);
1977
+ innerH1Port = inner.address().port;
1978
+ await listen(h2Inner);
1979
+ innerH2Port = h2Inner.address().port;
1980
+ try {
1981
+ await listen(proxy, deps.port, deps.host);
1982
+ }
1983
+ catch (err) {
1984
+ // Fault-tolerance: never leak the inner listeners when our public listen
1985
+ // fails (port busy etc.) — the caller logs the error and the gateway
1986
+ // keeps running without the proxy.
1987
+ try {
1988
+ inner.close();
1989
+ }
1990
+ catch { }
1991
+ try {
1992
+ h2Inner.close();
1993
+ }
1994
+ catch { }
1995
+ throw err;
1996
+ }
1997
+ const port = proxy.address().port;
1998
+ log(`listening on ${deps.host}:${port} (inner h1 ${innerH1Port}, h2 ${innerH2Port})`);
1999
+ return {
2000
+ port,
2001
+ caCertPem: ca.caCertPem,
2002
+ activeConnections: () => liveSockets.size,
2003
+ close() {
2004
+ return new Promise((resolve) => {
2005
+ for (const terminator of terminators.values()) {
2006
+ try {
2007
+ terminator.srv.close();
2008
+ }
2009
+ catch { }
2010
+ }
2011
+ for (const terminator of drainingTerminators.values()) {
2012
+ try {
2013
+ terminator.srv.close();
2014
+ }
2015
+ catch { }
2016
+ }
2017
+ drainingTerminators.clear();
2018
+ try {
2019
+ proxy.close();
2020
+ }
2021
+ catch { }
2022
+ try {
2023
+ inner.close();
2024
+ }
2025
+ catch { }
2026
+ try {
2027
+ h2Inner.close();
2028
+ }
2029
+ catch { }
2030
+ closeH2Pool();
2031
+ clearInterval(admissionSweep);
2032
+ resolve();
2033
+ });
2034
+ },
2035
+ };
2036
+ }
2037
+ /**
2038
+ * Listen with one EADDRINUSE retry. Port 0 means the OS picks a free port, so
2039
+ * a collision should be impossible — but under concurrent test workers Bun has
2040
+ * been observed racing the ephemeral allocation (EADDRINUSE on port 0). The
2041
+ * retry keeps that infrastructure flake from masking real regressions.
2042
+ */
2043
+ async function listen(server, port = 0, host = '127.0.0.1') {
2044
+ for (let attempt = 0;; attempt++) {
2045
+ try {
2046
+ await new Promise((resolve, reject) => {
2047
+ server.once('error', reject);
2048
+ server.listen(port, host, () => {
2049
+ server.removeListener('error', reject);
2050
+ resolve();
2051
+ });
2052
+ });
2053
+ return;
2054
+ }
2055
+ catch (err) {
2056
+ if (attempt > 0 || err?.code !== 'EADDRINUSE')
2057
+ throw err;
2058
+ // Detach the dead listener state before retrying the same server.
2059
+ try {
2060
+ server.close();
2061
+ }
2062
+ catch { }
2063
+ }
2064
+ }
2065
+ }