@buildanagent/harness 0.0.0-stage → 0.1.0-alpha.29

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 (397) hide show
  1. package/LICENSE +54 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +822 -2
  5. package/dist/ablation.d.ts +2 -0
  6. package/dist/ablation.js +3 -0
  7. package/dist/ablation.js.map +1 -0
  8. package/dist/completion/check.d.ts +64 -0
  9. package/dist/completion/check.js +152 -0
  10. package/dist/completion/check.js.map +1 -0
  11. package/dist/completion/checks.d.ts +45 -0
  12. package/dist/completion/checks.js +173 -0
  13. package/dist/completion/checks.js.map +1 -0
  14. package/dist/completion/flags.d.ts +25 -0
  15. package/dist/completion/flags.js +87 -0
  16. package/dist/completion/flags.js.map +1 -0
  17. package/dist/completion/index.d.ts +8 -0
  18. package/dist/completion/index.js +9 -0
  19. package/dist/completion/index.js.map +1 -0
  20. package/dist/completion/snapshot.d.ts +33 -0
  21. package/dist/completion/snapshot.js +83 -0
  22. package/dist/completion/snapshot.js.map +1 -0
  23. package/dist/context/cap.d.ts +32 -0
  24. package/dist/context/cap.js +50 -0
  25. package/dist/context/cap.js.map +1 -0
  26. package/dist/context/estimate.d.ts +18 -0
  27. package/dist/context/estimate.js +20 -0
  28. package/dist/context/estimate.js.map +1 -0
  29. package/dist/context/file-spill.d.ts +15 -0
  30. package/dist/context/file-spill.js +40 -0
  31. package/dist/context/file-spill.js.map +1 -0
  32. package/dist/context/index.d.ts +10 -0
  33. package/dist/context/index.js +10 -0
  34. package/dist/context/index.js.map +1 -0
  35. package/dist/context/mask.d.ts +27 -0
  36. package/dist/context/mask.js +71 -0
  37. package/dist/context/mask.js.map +1 -0
  38. package/dist/context/mid-turn.d.ts +40 -0
  39. package/dist/context/mid-turn.js +82 -0
  40. package/dist/context/mid-turn.js.map +1 -0
  41. package/dist/context/policy.d.ts +9 -0
  42. package/dist/context/policy.js +140 -0
  43. package/dist/context/policy.js.map +1 -0
  44. package/dist/context/spill-ledger.d.ts +25 -0
  45. package/dist/context/spill-ledger.js +54 -0
  46. package/dist/context/spill-ledger.js.map +1 -0
  47. package/dist/context/spill.d.ts +10 -0
  48. package/dist/context/spill.js +18 -0
  49. package/dist/context/spill.js.map +1 -0
  50. package/dist/context/summarize.d.ts +53 -0
  51. package/dist/context/summarize.js +204 -0
  52. package/dist/context/summarize.js.map +1 -0
  53. package/dist/context/summary-template.d.ts +29 -0
  54. package/dist/context/summary-template.js +69 -0
  55. package/dist/context/summary-template.js.map +1 -0
  56. package/dist/context/types.d.ts +150 -0
  57. package/dist/context/types.js +2 -0
  58. package/dist/context/types.js.map +1 -0
  59. package/dist/context/write-cap.d.ts +19 -0
  60. package/dist/context/write-cap.js +41 -0
  61. package/dist/context/write-cap.js.map +1 -0
  62. package/dist/create-harness.d.ts +7 -0
  63. package/dist/create-harness.js +21 -0
  64. package/dist/create-harness.js.map +1 -0
  65. package/dist/credentials/addresses.d.ts +14 -0
  66. package/dist/credentials/addresses.js +144 -0
  67. package/dist/credentials/addresses.js.map +1 -0
  68. package/dist/credentials/allowlist.d.ts +54 -0
  69. package/dist/credentials/allowlist.js +134 -0
  70. package/dist/credentials/allowlist.js.map +1 -0
  71. package/dist/credentials/egress-policy.d.ts +69 -0
  72. package/dist/credentials/egress-policy.js +170 -0
  73. package/dist/credentials/egress-policy.js.map +1 -0
  74. package/dist/credentials/egress-proxy.d.ts +82 -0
  75. package/dist/credentials/egress-proxy.js +650 -0
  76. package/dist/credentials/egress-proxy.js.map +1 -0
  77. package/dist/credentials/git-route.d.ts +68 -0
  78. package/dist/credentials/git-route.js +288 -0
  79. package/dist/credentials/git-route.js.map +1 -0
  80. package/dist/credentials/index.d.ts +13 -0
  81. package/dist/credentials/index.js +14 -0
  82. package/dist/credentials/index.js.map +1 -0
  83. package/dist/credentials/scrub.d.ts +23 -0
  84. package/dist/credentials/scrub.js +115 -0
  85. package/dist/credentials/scrub.js.map +1 -0
  86. package/dist/errors.d.ts +60 -0
  87. package/dist/errors.js +67 -0
  88. package/dist/errors.js.map +1 -0
  89. package/dist/extensions/compose.d.ts +27 -0
  90. package/dist/extensions/compose.js +83 -0
  91. package/dist/extensions/compose.js.map +1 -0
  92. package/dist/extensions/context-files-node.d.ts +28 -0
  93. package/dist/extensions/context-files-node.js +74 -0
  94. package/dist/extensions/context-files-node.js.map +1 -0
  95. package/dist/extensions/context-files.d.ts +68 -0
  96. package/dist/extensions/context-files.js +214 -0
  97. package/dist/extensions/context-files.js.map +1 -0
  98. package/dist/extensions/digest.d.ts +6 -0
  99. package/dist/extensions/digest.js +68 -0
  100. package/dist/extensions/digest.js.map +1 -0
  101. package/dist/extensions/index.d.ts +10 -0
  102. package/dist/extensions/index.js +10 -0
  103. package/dist/extensions/index.js.map +1 -0
  104. package/dist/extensions/load.d.ts +42 -0
  105. package/dist/extensions/load.js +211 -0
  106. package/dist/extensions/load.js.map +1 -0
  107. package/dist/extensions/lock.d.ts +8 -0
  108. package/dist/extensions/lock.js +95 -0
  109. package/dist/extensions/lock.js.map +1 -0
  110. package/dist/extensions/node.d.ts +10 -0
  111. package/dist/extensions/node.js +11 -0
  112. package/dist/extensions/node.js.map +1 -0
  113. package/dist/extensions/project-dirs.d.ts +24 -0
  114. package/dist/extensions/project-dirs.js +97 -0
  115. package/dist/extensions/project-dirs.js.map +1 -0
  116. package/dist/extensions/skills-node.d.ts +34 -0
  117. package/dist/extensions/skills-node.js +123 -0
  118. package/dist/extensions/skills-node.js.map +1 -0
  119. package/dist/extensions/skills.d.ts +51 -0
  120. package/dist/extensions/skills.js +175 -0
  121. package/dist/extensions/skills.js.map +1 -0
  122. package/dist/extensions/trust-file.d.ts +3 -0
  123. package/dist/extensions/trust-file.js +62 -0
  124. package/dist/extensions/trust-file.js.map +1 -0
  125. package/dist/extensions/trust-store-node.d.ts +10 -0
  126. package/dist/extensions/trust-store-node.js +33 -0
  127. package/dist/extensions/trust-store-node.js.map +1 -0
  128. package/dist/extensions/types.d.ts +42 -0
  129. package/dist/extensions/types.js +2 -0
  130. package/dist/extensions/types.js.map +1 -0
  131. package/dist/harness.d.ts +156 -0
  132. package/dist/harness.js +2 -0
  133. package/dist/harness.js.map +1 -0
  134. package/dist/index.d.ts +4 -0
  135. package/dist/index.js +5 -0
  136. package/dist/index.js.map +1 -0
  137. package/dist/mcp/connection.d.ts +22 -0
  138. package/dist/mcp/connection.js +267 -0
  139. package/dist/mcp/connection.js.map +1 -0
  140. package/dist/mcp/content.d.ts +27 -0
  141. package/dist/mcp/content.js +177 -0
  142. package/dist/mcp/content.js.map +1 -0
  143. package/dist/mcp/errors.d.ts +19 -0
  144. package/dist/mcp/errors.js +21 -0
  145. package/dist/mcp/errors.js.map +1 -0
  146. package/dist/mcp/index.d.ts +10 -0
  147. package/dist/mcp/index.js +10 -0
  148. package/dist/mcp/index.js.map +1 -0
  149. package/dist/mcp/manager.d.ts +7 -0
  150. package/dist/mcp/manager.js +173 -0
  151. package/dist/mcp/manager.js.map +1 -0
  152. package/dist/mcp/record.d.ts +7 -0
  153. package/dist/mcp/record.js +20 -0
  154. package/dist/mcp/record.js.map +1 -0
  155. package/dist/mcp/stdio.d.ts +39 -0
  156. package/dist/mcp/stdio.js +382 -0
  157. package/dist/mcp/stdio.js.map +1 -0
  158. package/dist/mcp/types.d.ts +172 -0
  159. package/dist/mcp/types.js +2 -0
  160. package/dist/mcp/types.js.map +1 -0
  161. package/dist/memory/index.d.ts +2 -0
  162. package/dist/memory/index.js +3 -0
  163. package/dist/memory/index.js.map +1 -0
  164. package/dist/permissions/default-rules.d.ts +7 -0
  165. package/dist/permissions/default-rules.js +42 -0
  166. package/dist/permissions/default-rules.js.map +1 -0
  167. package/dist/permissions/errors.d.ts +11 -0
  168. package/dist/permissions/errors.js +14 -0
  169. package/dist/permissions/errors.js.map +1 -0
  170. package/dist/permissions/index.d.ts +9 -0
  171. package/dist/permissions/index.js +9 -0
  172. package/dist/permissions/index.js.map +1 -0
  173. package/dist/permissions/match.d.ts +33 -0
  174. package/dist/permissions/match.js +287 -0
  175. package/dist/permissions/match.js.map +1 -0
  176. package/dist/permissions/pipeline.d.ts +9 -0
  177. package/dist/permissions/pipeline.js +235 -0
  178. package/dist/permissions/pipeline.js.map +1 -0
  179. package/dist/permissions/rules.d.ts +22 -0
  180. package/dist/permissions/rules.js +74 -0
  181. package/dist/permissions/rules.js.map +1 -0
  182. package/dist/permissions/shadow.d.ts +5 -0
  183. package/dist/permissions/shadow.js +22 -0
  184. package/dist/permissions/shadow.js.map +1 -0
  185. package/dist/permissions/types.d.ts +104 -0
  186. package/dist/permissions/types.js +2 -0
  187. package/dist/permissions/types.js.map +1 -0
  188. package/dist/sandbox/base.d.ts +45 -0
  189. package/dist/sandbox/base.js +74 -0
  190. package/dist/sandbox/base.js.map +1 -0
  191. package/dist/sandbox/docker/index.d.ts +41 -0
  192. package/dist/sandbox/docker/index.js +497 -0
  193. package/dist/sandbox/docker/index.js.map +1 -0
  194. package/dist/sandbox/errors.d.ts +44 -0
  195. package/dist/sandbox/errors.js +57 -0
  196. package/dist/sandbox/errors.js.map +1 -0
  197. package/dist/sandbox/host-files.d.ts +65 -0
  198. package/dist/sandbox/host-files.js +258 -0
  199. package/dist/sandbox/host-files.js.map +1 -0
  200. package/dist/sandbox/index.d.ts +10 -0
  201. package/dist/sandbox/index.js +10 -0
  202. package/dist/sandbox/index.js.map +1 -0
  203. package/dist/sandbox/none.d.ts +17 -0
  204. package/dist/sandbox/none.js +108 -0
  205. package/dist/sandbox/none.js.map +1 -0
  206. package/dist/sandbox/policy.d.ts +49 -0
  207. package/dist/sandbox/policy.js +149 -0
  208. package/dist/sandbox/policy.js.map +1 -0
  209. package/dist/sandbox/process.d.ts +61 -0
  210. package/dist/sandbox/process.js +253 -0
  211. package/dist/sandbox/process.js.map +1 -0
  212. package/dist/sandbox/spawn-env.d.ts +20 -0
  213. package/dist/sandbox/spawn-env.js +128 -0
  214. package/dist/sandbox/spawn-env.js.map +1 -0
  215. package/dist/sandbox/srt/index.d.ts +38 -0
  216. package/dist/sandbox/srt/index.js +283 -0
  217. package/dist/sandbox/srt/index.js.map +1 -0
  218. package/dist/sandbox/srt/settings.d.ts +60 -0
  219. package/dist/sandbox/srt/settings.js +84 -0
  220. package/dist/sandbox/srt/settings.js.map +1 -0
  221. package/dist/sandbox/types.d.ts +125 -0
  222. package/dist/sandbox/types.js +6 -0
  223. package/dist/sandbox/types.js.map +1 -0
  224. package/dist/server/answers.d.ts +16 -0
  225. package/dist/server/answers.js +43 -0
  226. package/dist/server/answers.js.map +1 -0
  227. package/dist/server/connection.d.ts +99 -0
  228. package/dist/server/connection.js +309 -0
  229. package/dist/server/connection.js.map +1 -0
  230. package/dist/server/dispatcher.d.ts +86 -0
  231. package/dist/server/dispatcher.js +800 -0
  232. package/dist/server/dispatcher.js.map +1 -0
  233. package/dist/server/index.d.ts +13 -0
  234. package/dist/server/index.js +12 -0
  235. package/dist/server/index.js.map +1 -0
  236. package/dist/server/local-transport.d.ts +44 -0
  237. package/dist/server/local-transport.js +103 -0
  238. package/dist/server/local-transport.js.map +1 -0
  239. package/dist/server/outbox.d.ts +31 -0
  240. package/dist/server/outbox.js +130 -0
  241. package/dist/server/outbox.js.map +1 -0
  242. package/dist/server/params.d.ts +25 -0
  243. package/dist/server/params.js +112 -0
  244. package/dist/server/params.js.map +1 -0
  245. package/dist/server/protocol.schema.json +2448 -0
  246. package/dist/server/rpc-session.d.ts +43 -0
  247. package/dist/server/rpc-session.js +167 -0
  248. package/dist/server/rpc-session.js.map +1 -0
  249. package/dist/server/stdio-streams.d.ts +67 -0
  250. package/dist/server/stdio-streams.js +218 -0
  251. package/dist/server/stdio-streams.js.map +1 -0
  252. package/dist/server/stdio.d.ts +59 -0
  253. package/dist/server/stdio.js +189 -0
  254. package/dist/server/stdio.js.map +1 -0
  255. package/dist/server/websocket.d.ts +106 -0
  256. package/dist/server/websocket.js +327 -0
  257. package/dist/server/websocket.js.map +1 -0
  258. package/dist/session/approvals.d.ts +81 -0
  259. package/dist/session/approvals.js +217 -0
  260. package/dist/session/approvals.js.map +1 -0
  261. package/dist/session/code-call-log.d.ts +42 -0
  262. package/dist/session/code-call-log.js +63 -0
  263. package/dist/session/code-call-log.js.map +1 -0
  264. package/dist/session/code-call-result.d.ts +19 -0
  265. package/dist/session/code-call-result.js +95 -0
  266. package/dist/session/code-call-result.js.map +1 -0
  267. package/dist/session/code-call.d.ts +49 -0
  268. package/dist/session/code-call.js +345 -0
  269. package/dist/session/code-call.js.map +1 -0
  270. package/dist/session/effect-scope.d.ts +11 -0
  271. package/dist/session/effect-scope.js +10 -0
  272. package/dist/session/effect-scope.js.map +1 -0
  273. package/dist/session/errors.d.ts +19 -0
  274. package/dist/session/errors.js +27 -0
  275. package/dist/session/errors.js.map +1 -0
  276. package/dist/session/file-index.d.ts +8 -0
  277. package/dist/session/file-index.js +70 -0
  278. package/dist/session/file-index.js.map +1 -0
  279. package/dist/session/file-key-store.d.ts +16 -0
  280. package/dist/session/file-key-store.js +169 -0
  281. package/dist/session/file-key-store.js.map +1 -0
  282. package/dist/session/file-lock.d.ts +52 -0
  283. package/dist/session/file-lock.js +324 -0
  284. package/dist/session/file-lock.js.map +1 -0
  285. package/dist/session/index.d.ts +22 -0
  286. package/dist/session/index.js +20 -0
  287. package/dist/session/index.js.map +1 -0
  288. package/dist/session/jsonl-store.d.ts +37 -0
  289. package/dist/session/jsonl-store.js +386 -0
  290. package/dist/session/jsonl-store.js.map +1 -0
  291. package/dist/session/jsonl.d.ts +9 -0
  292. package/dist/session/jsonl.js +10 -0
  293. package/dist/session/jsonl.js.map +1 -0
  294. package/dist/session/lock.d.ts +19 -0
  295. package/dist/session/lock.js +2 -0
  296. package/dist/session/lock.js.map +1 -0
  297. package/dist/session/memory-store.d.ts +12 -0
  298. package/dist/session/memory-store.js +60 -0
  299. package/dist/session/memory-store.js.map +1 -0
  300. package/dist/session/migrate.d.ts +41 -0
  301. package/dist/session/migrate.js +86 -0
  302. package/dist/session/migrate.js.map +1 -0
  303. package/dist/session/pointer.d.ts +15 -0
  304. package/dist/session/pointer.js +22 -0
  305. package/dist/session/pointer.js.map +1 -0
  306. package/dist/session/rebuild.d.ts +53 -0
  307. package/dist/session/rebuild.js +230 -0
  308. package/dist/session/rebuild.js.map +1 -0
  309. package/dist/session/resume.d.ts +26 -0
  310. package/dist/session/resume.js +128 -0
  311. package/dist/session/resume.js.map +1 -0
  312. package/dist/session/retention.d.ts +97 -0
  313. package/dist/session/retention.js +702 -0
  314. package/dist/session/retention.js.map +1 -0
  315. package/dist/session/runner.d.ts +156 -0
  316. package/dist/session/runner.js +656 -0
  317. package/dist/session/runner.js.map +1 -0
  318. package/dist/session/scheduler.d.ts +47 -0
  319. package/dist/session/scheduler.js +85 -0
  320. package/dist/session/scheduler.js.map +1 -0
  321. package/dist/session/secret-key-store.d.ts +47 -0
  322. package/dist/session/secret-key-store.js +79 -0
  323. package/dist/session/secret-key-store.js.map +1 -0
  324. package/dist/session/session.d.ts +106 -0
  325. package/dist/session/session.js +353 -0
  326. package/dist/session/session.js.map +1 -0
  327. package/dist/session/sticky.d.ts +48 -0
  328. package/dist/session/sticky.js +232 -0
  329. package/dist/session/sticky.js.map +1 -0
  330. package/dist/session/store.d.ts +108 -0
  331. package/dist/session/store.js +163 -0
  332. package/dist/session/store.js.map +1 -0
  333. package/dist/telemetry/index.d.ts +2 -0
  334. package/dist/telemetry/index.js +3 -0
  335. package/dist/telemetry/index.js.map +1 -0
  336. package/dist/testing/fake-sandbox.d.ts +52 -0
  337. package/dist/testing/fake-sandbox.js +370 -0
  338. package/dist/testing/fake-sandbox.js.map +1 -0
  339. package/dist/testing/index.d.ts +10 -0
  340. package/dist/testing/index.js +11 -0
  341. package/dist/testing/index.js.map +1 -0
  342. package/dist/testing/key-store-conformance.d.ts +22 -0
  343. package/dist/testing/key-store-conformance.js +97 -0
  344. package/dist/testing/key-store-conformance.js.map +1 -0
  345. package/dist/testing/run-cases.d.ts +21 -0
  346. package/dist/testing/run-cases.js +20 -0
  347. package/dist/testing/run-cases.js.map +1 -0
  348. package/dist/testing/sandbox-conformance.d.ts +64 -0
  349. package/dist/testing/sandbox-conformance.js +468 -0
  350. package/dist/testing/sandbox-conformance.js.map +1 -0
  351. package/dist/testing/scheduler-conformance.d.ts +32 -0
  352. package/dist/testing/scheduler-conformance.js +72 -0
  353. package/dist/testing/scheduler-conformance.js.map +1 -0
  354. package/dist/testing/store-conformance.d.ts +21 -0
  355. package/dist/testing/store-conformance.js +320 -0
  356. package/dist/testing/store-conformance.js.map +1 -0
  357. package/dist/tools/builtins/bash.d.ts +9 -0
  358. package/dist/tools/builtins/bash.js +75 -0
  359. package/dist/tools/builtins/bash.js.map +1 -0
  360. package/dist/tools/builtins/builtins.d.ts +38 -0
  361. package/dist/tools/builtins/builtins.js +48 -0
  362. package/dist/tools/builtins/builtins.js.map +1 -0
  363. package/dist/tools/builtins/descriptions.d.ts +69 -0
  364. package/dist/tools/builtins/descriptions.js +94 -0
  365. package/dist/tools/builtins/descriptions.js.map +1 -0
  366. package/dist/tools/builtins/fetch.d.ts +12 -0
  367. package/dist/tools/builtins/fetch.js +157 -0
  368. package/dist/tools/builtins/fetch.js.map +1 -0
  369. package/dist/tools/builtins/files.d.ts +27 -0
  370. package/dist/tools/builtins/files.js +274 -0
  371. package/dist/tools/builtins/files.js.map +1 -0
  372. package/dist/tools/builtins/paths.d.ts +30 -0
  373. package/dist/tools/builtins/paths.js +62 -0
  374. package/dist/tools/builtins/paths.js.map +1 -0
  375. package/dist/tools/builtins/results.d.ts +15 -0
  376. package/dist/tools/builtins/results.js +31 -0
  377. package/dist/tools/builtins/results.js.map +1 -0
  378. package/dist/tools/builtins/search.d.ts +18 -0
  379. package/dist/tools/builtins/search.js +217 -0
  380. package/dist/tools/builtins/search.js.map +1 -0
  381. package/dist/tools/errors.d.ts +13 -0
  382. package/dist/tools/errors.js +17 -0
  383. package/dist/tools/errors.js.map +1 -0
  384. package/dist/tools/index.d.ts +12 -0
  385. package/dist/tools/index.js +11 -0
  386. package/dist/tools/index.js.map +1 -0
  387. package/dist/tools/registry.d.ts +3 -0
  388. package/dist/tools/registry.js +234 -0
  389. package/dist/tools/registry.js.map +1 -0
  390. package/dist/tools/tool-search.d.ts +30 -0
  391. package/dist/tools/tool-search.js +118 -0
  392. package/dist/tools/tool-search.js.map +1 -0
  393. package/dist/tools/types.d.ts +106 -0
  394. package/dist/tools/types.js +2 -0
  395. package/dist/tools/types.js.map +1 -0
  396. package/llms.txt +469 -0
  397. package/package.json +118 -3
@@ -0,0 +1,650 @@
1
+ /**
2
+ * `startEgressProxy()`: the host-side proxy that keeps credentials out of the sandbox. Nothing leaves the sandbox except
3
+ * through it, it refuses everything that isn't on its allowlist, and it logs each request without its headers. A tool
4
+ * that needs a credential sends its request to a local route, such as `http://127.0.0.1:<port>/github/user`, with the
5
+ * route's sentinel where the credential goes. The proxy checks the sentinel and the method, swaps in the real secret and
6
+ * forwards the request over HTTPS. It never intercepts TLS: everything else leaves through `CONNECT` to an
7
+ * allowlisted name, and a name is connected to only at an address the proxy checked. It is Node-only.
8
+ */
9
+ import { HarnessError } from "../errors.js";
10
+ import { isAddressLiteral, isPublicAddress } from "./addresses.js";
11
+ import { isAllowed, parseAllow, parseRoutes, } from "./allowlist.js";
12
+ import { basicCarries, basicHeader, gitEndpoint, PushReader, pushVerdict } from "./git-route.js";
13
+ function nodeModules() {
14
+ if (typeof process === "undefined" || typeof process.getBuiltinModule !== "function") {
15
+ throw new HarnessError("invalid_egress_options", "the egress proxy needs Node's network modules, which this runtime lacks");
16
+ }
17
+ return {
18
+ http: process.getBuiltinModule("node:http"),
19
+ https: process.getBuiltinModule("node:https"),
20
+ net: process.getBuiltinModule("node:net"),
21
+ dns: process.getBuiltinModule("node:dns"),
22
+ crypto: process.getBuiltinModule("node:crypto"),
23
+ stream: process.getBuiltinModule("node:stream"),
24
+ };
25
+ }
26
+ // Headers that belong to one connection, and are never passed on to the next.
27
+ const HOP_BY_HOP = new Set([
28
+ "connection",
29
+ "keep-alive",
30
+ "proxy-authenticate",
31
+ "proxy-authorization",
32
+ "proxy-connection",
33
+ "te",
34
+ "trailer",
35
+ "transfer-encoding",
36
+ "upgrade",
37
+ "host",
38
+ ]);
39
+ const DEFAULT_IDLE_MS = 120_000;
40
+ const DEFAULT_PUSH_CHECK_MS = 60_000;
41
+ // How much of a refused request's unread body is discarded, and for how long, before its connection is closed.
42
+ const LINGER_BYTES = 1024 * 1024;
43
+ const LINGER_MS = 1000;
44
+ // The longest delay a timer takes; past it, `setTimeout` fires at once.
45
+ const MAX_TIMER_MS = 2_147_483_647;
46
+ // What Node refuses in a header value: anything but tab, printable ASCII and the Latin-1 range. A secret with a line break
47
+ // or another control character would split or break the request, so it is refused before it is sent.
48
+ const INVALID_HEADER_VALUE = /[^\t\x20-\x7e\x80-\xff]/;
49
+ // The origin an in-process tool uses for a route, in either mode, because a Unix socket has no address of its own.
50
+ const ROUTE_ORIGIN = "http://egress.proxy";
51
+ const refusal = (status, reason) => ({
52
+ status,
53
+ headers: { "content-type": "text/plain" },
54
+ body: undefined,
55
+ reason,
56
+ });
57
+ /**
58
+ * The answer to a git request whose credential is missing or wrong, or `undefined` when its HTTP Basic password is the
59
+ * route's sentinel. A missing one gets 401 with a Basic challenge, so git asks its credential helper.
60
+ */
61
+ function gitCredentialRefusal(presented, sentinel) {
62
+ if (presented === undefined) {
63
+ return { ...refusal(401, "git_credential_missing"), headers: { "www-authenticate": 'Basic realm="egress"' } };
64
+ }
65
+ return typeof presented === "string" && basicCarries(presented, sentinel) ? undefined : refusal(403, "bad_sentinel");
66
+ }
67
+ /**
68
+ * Checks a timeout option and returns the value to use: `fallback` when it is unset, or a whole number of milliseconds
69
+ * from `min` to the longest delay a timer takes. The message names the option and never quotes the value.
70
+ */
71
+ function timeoutOption(name, ms, min, fallback) {
72
+ if (ms === undefined)
73
+ return fallback;
74
+ if (typeof ms === "number" && Number.isInteger(ms) && ms >= min && ms <= MAX_TIMER_MS)
75
+ return ms;
76
+ throw new HarnessError("invalid_egress_options", `${name} must be a whole number of milliseconds from ${min} to ${MAX_TIMER_MS}`);
77
+ }
78
+ class EgressGate {
79
+ modules;
80
+ allow;
81
+ routes;
82
+ sentinels = {};
83
+ options;
84
+ unsafe;
85
+ sockets = new Set();
86
+ requests = new Set();
87
+ pushCheckMs;
88
+ // 0 means no idle timeout, as it does for `socket.setTimeout`.
89
+ idleMs;
90
+ origin = "";
91
+ constructor(modules, options) {
92
+ this.modules = modules;
93
+ this.options = options;
94
+ this.idleMs = timeoutOption("idleTimeoutMs", options.idleTimeoutMs, 0, DEFAULT_IDLE_MS);
95
+ this.pushCheckMs = timeoutOption("pushCheckTimeoutMs", options.pushCheckTimeoutMs, 1, DEFAULT_PUSH_CHECK_MS);
96
+ this.allow = parseAllow(options.allow);
97
+ this.routes = new Map(parseRoutes(options.routes ?? [], this.allow).map((route) => [route.route, route]));
98
+ this.unsafe = new Set(options.unsafeAllowAddresses ?? []);
99
+ for (const route of this.routes.keys()) {
100
+ this.sentinels[route] = `sentinel_${modules.crypto.randomBytes(18).toString("base64url")}`;
101
+ }
102
+ }
103
+ setOrigin(origin) {
104
+ this.origin = origin;
105
+ }
106
+ sentinelMap() {
107
+ return this.sentinels;
108
+ }
109
+ record(record) {
110
+ try {
111
+ this.options.log({ time: new Date().toISOString(), ...record });
112
+ }
113
+ catch {
114
+ // A logger that throws must not take the proxy down.
115
+ }
116
+ }
117
+ /** A `lookup` for `net` and `https`: it resolves in the proxy, checks every address, and connects only to those. */
118
+ checkedLookup = (hostname, lookupOptions, callback) => {
119
+ const resolve = this.options.resolve ??
120
+ (async (host) => (await this.modules.dns.promises.lookup(host, { all: true })).map((found) => found.address));
121
+ resolve(hostname).then((addresses) => {
122
+ const refused = addresses.length === 0 || addresses.some((a) => !isPublicAddress(a) && !this.unsafe.has(a));
123
+ if (refused) {
124
+ callback(Object.assign(new Error(`${hostname} resolves to an address the proxy refuses`), {
125
+ code: "EGRESS_ADDRESS",
126
+ }));
127
+ return;
128
+ }
129
+ const family = (address) => (address.includes(":") ? 6 : 4);
130
+ if (lookupOptions.all === true) {
131
+ callback(null, addresses.map((address) => ({ address, family: family(address) })));
132
+ }
133
+ else {
134
+ callback(null, addresses[0], family(addresses[0] ?? ""));
135
+ }
136
+ }, (error) => callback(error));
137
+ };
138
+ reasonOf(error) {
139
+ const code = error.code;
140
+ if (code === "EGRESS_ADDRESS")
141
+ return "address_refused";
142
+ return code === "ETIMEDOUT" ? "timeout" : "connect_failed";
143
+ }
144
+ /** The host and port of a `CONNECT` target, or `undefined` for one that isn't `host:port`. */
145
+ parseTarget(target) {
146
+ const match = /^(\[[0-9a-fA-F:.]+\]|[^:[\]]+):([0-9]{1,5})$/.exec(target);
147
+ if (match === null)
148
+ return undefined;
149
+ const host = (match[1] ?? "").toLowerCase().replace(/\.$/, "");
150
+ const port = Number(match[2]);
151
+ return port >= 1 && port <= 65535 ? { host, port } : undefined;
152
+ }
153
+ /** Handles one `CONNECT`: allow-checks the name, then tunnels to the address the proxy checked. */
154
+ handleConnect(request, client, head) {
155
+ this.track(client);
156
+ const target = this.parseTarget(request.url ?? "");
157
+ const host = target?.host ?? "(invalid)";
158
+ const port = target?.port ?? 0;
159
+ const deny = (reason, status = 403) => {
160
+ client.end(`HTTP/1.1 ${status} ${status === 403 ? "Forbidden" : "Bad Gateway"}\r\nConnection: close\r\n\r\n`);
161
+ this.record({ kind: "connect", host, port, method: "CONNECT", status, bytes: 0, reason });
162
+ };
163
+ const refusedBecause = target === undefined
164
+ ? "bad_target"
165
+ : isAddressLiteral(host)
166
+ ? "address_literal"
167
+ : isAllowed(this.allow, host, port)
168
+ ? undefined
169
+ : "not_allowed";
170
+ if (refusedBecause !== undefined) {
171
+ deny(refusedBecause);
172
+ return;
173
+ }
174
+ let established = false;
175
+ const upstream = this.modules.net.connect({ host, port, lookup: this.checkedLookup });
176
+ this.track(upstream);
177
+ // A client that leaves before the tunnel is up takes the connection attempt with it.
178
+ client.once("close", () => upstream.destroy());
179
+ upstream.setTimeout(this.idleMs, () => upstream.destroy(Object.assign(new Error("idle"), { code: "ETIMEDOUT" })));
180
+ upstream.once("error", (error) => {
181
+ if (established)
182
+ client.destroy();
183
+ else
184
+ deny(this.reasonOf(error), 502);
185
+ upstream.destroy();
186
+ });
187
+ upstream.once("connect", () => {
188
+ established = true;
189
+ client.write("HTTP/1.1 200 Connection Established\r\n\r\n");
190
+ if (head.length > 0)
191
+ upstream.write(head);
192
+ upstream.pipe(client);
193
+ client.pipe(upstream);
194
+ const done = () => {
195
+ client.destroy();
196
+ upstream.destroy();
197
+ };
198
+ client.once("close", done);
199
+ upstream.once("close", () => {
200
+ this.record({
201
+ kind: "connect",
202
+ host,
203
+ port,
204
+ method: "CONNECT",
205
+ status: 200,
206
+ bytes: upstream.bytesRead + upstream.bytesWritten,
207
+ });
208
+ done();
209
+ });
210
+ });
211
+ client.once("error", () => upstream.destroy());
212
+ }
213
+ track(socket) {
214
+ if (this.sockets.has(socket))
215
+ return;
216
+ this.sockets.add(socket);
217
+ socket.once("close", () => this.sockets.delete(socket));
218
+ socket.on("error", () => { });
219
+ }
220
+ /** Handles one request that isn't a `CONNECT`: a route request, or a refusal of anything else. */
221
+ handleRequest(request, response) {
222
+ this.track(request.socket);
223
+ const url = request.url ?? "";
224
+ if (!url.startsWith("/")) {
225
+ // A proxy request in absolute form: only a tunnel may leave, so the name is not even looked at.
226
+ this.finish(response, refusal(403, "only_connect"), {
227
+ kind: "route",
228
+ host: "(proxy request)",
229
+ port: 0,
230
+ method: request.method ?? "",
231
+ });
232
+ return;
233
+ }
234
+ // A client that goes away takes the upstream request with it, so a credential isn't spent for nobody.
235
+ const gone = new AbortController();
236
+ response.once("close", () => gone.abort());
237
+ const base = {
238
+ kind: "route",
239
+ host: "(route)",
240
+ port: 0,
241
+ method: request.method ?? "GET",
242
+ route: undefined,
243
+ };
244
+ this.routeRequest(request.method ?? "GET", url, request.headers, request, gone.signal).then((reply) => this.finish(response, reply.reply, reply.base, request), () => this.finish(response, refusal(502, "request_failed"), base, request));
245
+ }
246
+ finish(response, reply, base, request) {
247
+ let bytes = 0;
248
+ const report = () => this.record({
249
+ ...base,
250
+ status: reply.status,
251
+ bytes,
252
+ ...(reply.reason === undefined ? {} : { reason: reply.reason }),
253
+ });
254
+ if (reply.body === undefined && reply.status >= 400 && request !== undefined && !request.complete) {
255
+ this.refuseAndClose(request, response, reply);
256
+ report();
257
+ return;
258
+ }
259
+ response.writeHead(reply.status, reply.headers);
260
+ if (reply.body === undefined) {
261
+ response.end(reply.status === 403 || reply.status >= 400 ? `${reply.reason ?? "refused"}\n` : undefined);
262
+ report();
263
+ return;
264
+ }
265
+ reply.body.on("data", (chunk) => {
266
+ bytes += chunk.length;
267
+ });
268
+ reply.body.once("close", report);
269
+ reply.body.once("error", () => response.destroy());
270
+ response.once("close", () => reply.body?.destroy());
271
+ reply.body.pipe(response);
272
+ }
273
+ /**
274
+ * Refuses a request whose body has not been read to its end, and closes its connection. Node would otherwise read and
275
+ * discard the rest of the body, a whole pack perhaps, to keep the connection alive. The answer is written whole, with
276
+ * its length and `Connection: close`, and the response is ended, which closes the socket, only after the bytes already
277
+ * on their way are discarded, up to `LINGER_BYTES` or for `LINGER_MS`. Closing a socket with unread bytes resets the
278
+ * connection, and a client that has not yet read the answer would lose it.
279
+ */
280
+ refuseAndClose(request, response, reply) {
281
+ const text = `${reply.reason ?? "refused"}\n`;
282
+ response.writeHead(reply.status, { ...reply.headers, connection: "close", "content-length": String(text.length) });
283
+ response.write(text);
284
+ let discarded = 0;
285
+ const done = () => {
286
+ clearTimeout(timer);
287
+ request.off("data", onData);
288
+ request.off("end", done);
289
+ request.off("close", done);
290
+ request.pause();
291
+ response.end();
292
+ };
293
+ const onData = (chunk) => {
294
+ discarded += chunk.length;
295
+ if (discarded >= LINGER_BYTES)
296
+ done();
297
+ };
298
+ const timer = setTimeout(done, LINGER_MS);
299
+ request.on("data", onData);
300
+ request.once("end", done);
301
+ request.once("close", done);
302
+ request.resume();
303
+ }
304
+ /**
305
+ * Resolves a request for `/<route>/…`. It checks the route, the method and the sentinel, swaps in the secret, and
306
+ * forwards the request to the route's host. A request that fails any check is answered here, and nothing is sent.
307
+ */
308
+ async routeRequest(method, rawPath, headers, body, signal) {
309
+ const match = /^\/([^/?#]+)(\/[^?#]*)?(\?[^#]*)?$/.exec(rawPath);
310
+ const route = match === null ? undefined : this.routes.get(match[1] ?? "");
311
+ const base = {
312
+ kind: "route",
313
+ host: route?.hostname ?? "(no route)",
314
+ port: route?.port ?? 0,
315
+ method,
316
+ route: route?.route,
317
+ };
318
+ if (route === undefined || match === null)
319
+ return { reply: refusal(403, "unknown_route"), base };
320
+ if (!route.methods.has(method.toUpperCase()))
321
+ return { reply: refusal(405, "method_not_allowed"), base };
322
+ const target = { path: match[2] ?? "/", query: match[3] ?? "" };
323
+ const reply = route.git === undefined
324
+ ? await this.headerRequest(route, method, target, headers, body, signal)
325
+ : await this.gitRequest(route, route.git, method, target, headers, body, signal);
326
+ return { reply, base };
327
+ }
328
+ /** Resolves a request on a header route: it swaps the sentinel in the route's header for the secret. */
329
+ async headerRequest(route, method, target, headers, body, signal) {
330
+ const presented = headers[route.header];
331
+ const sentinel = this.sentinels[route.route] ?? "";
332
+ if (typeof presented !== "string" || sentinel === "" || !presented.includes(sentinel)) {
333
+ return refusal(403, "bad_sentinel");
334
+ }
335
+ const secret = await route.secret().catch(() => "");
336
+ if (secret === "" || INVALID_HEADER_VALUE.test(secret))
337
+ return refusal(502, "secret_unavailable");
338
+ const outgoing = this.outgoingHeaders(headers, route, presented.replaceAll(sentinel, () => secret));
339
+ return this.forward(route, method, `${target.path}${target.query}`, outgoing, body, signal);
340
+ }
341
+ /**
342
+ * Resolves a request on a git route. The endpoint and repository are checked first, then the sentinel in HTTP Basic,
343
+ * then a push's command list, and only then is the secret read and the request forwarded with it. A missing
344
+ * credential gets 401 with a Basic challenge, so git asks its credential helper for the sentinel.
345
+ */
346
+ async gitRequest(route, filter, method, target, headers, body, signal) {
347
+ const endpoint = gitEndpoint(filter, method, target.path, target.query);
348
+ if ("refused" in endpoint)
349
+ return refusal(403, endpoint.refused);
350
+ const unauthorized = gitCredentialRefusal(headers.authorization, this.sentinels[route.route] ?? "");
351
+ if (unauthorized !== undefined)
352
+ return unauthorized;
353
+ let forwarded = body;
354
+ if (endpoint.service === "git-receive-pack" && endpoint.phase === "rpc") {
355
+ const encoding = headers["content-encoding"];
356
+ if (encoding !== undefined && encoding !== "identity")
357
+ return refusal(403, "git_encoded_push");
358
+ const checked = await this.checkPush(body, filter);
359
+ if ("refused" in checked)
360
+ return refusal(403, checked.refused);
361
+ forwarded = checked.body;
362
+ }
363
+ const secret = await route.secret().catch(() => "");
364
+ if (secret === "" || INVALID_HEADER_VALUE.test(secret))
365
+ return refusal(502, "secret_unavailable");
366
+ const outgoing = this.outgoingHeaders(headers, route, basicHeader(filter.username, secret));
367
+ return this.forward(route, method, `${target.path}${target.query}`, outgoing, forwarded, signal);
368
+ }
369
+ /**
370
+ * Reads a push's command list and checks it, then hands back a body that starts with what was read. `PushReader`
371
+ * reads each chunk once, so the check is linear in the bytes however small the chunks. The check gives up once the
372
+ * body is idle for the idle timeout, which each chunk resets, or once `pushCheckTimeoutMs` has passed since it
373
+ * started, which nothing resets.
374
+ */
375
+ checkPush(body, filter) {
376
+ if (body === undefined)
377
+ return Promise.resolve({ refused: "git_bad_pkt_line" });
378
+ if (body instanceof Uint8Array) {
379
+ const verdict = pushVerdict(body, filter, true);
380
+ return Promise.resolve(verdict === "allowed" ? { body } : { refused: verdict.refused });
381
+ }
382
+ return new Promise((resolve) => {
383
+ const reader = new PushReader(filter);
384
+ const chunks = [];
385
+ const timedOut = () => settle({ refused: "git_timeout" });
386
+ // An idle timeout of 0 is off, so only the deadline ends a quiet body.
387
+ const startIdle = () => (this.idleMs === 0 ? undefined : setTimeout(timedOut, this.idleMs));
388
+ let idle = startIdle();
389
+ const deadline = setTimeout(timedOut, this.pushCheckMs);
390
+ const settle = (outcome) => {
391
+ clearTimeout(idle);
392
+ clearTimeout(deadline);
393
+ body.off("data", onData);
394
+ body.off("end", onEnd);
395
+ body.off("error", onError);
396
+ body.off("close", onError);
397
+ // A refused body is not read further; the answer closes its connection.
398
+ if ("refused" in outcome)
399
+ body.pause();
400
+ resolve(outcome);
401
+ };
402
+ const judge = (verdict, ended) => {
403
+ if (verdict === "incomplete")
404
+ return;
405
+ if (verdict !== "allowed") {
406
+ settle(verdict);
407
+ return;
408
+ }
409
+ const rest = new this.modules.stream.PassThrough();
410
+ for (const chunk of chunks)
411
+ rest.write(chunk);
412
+ settle({ body: rest });
413
+ if (ended)
414
+ rest.end();
415
+ else
416
+ body.pipe(rest);
417
+ };
418
+ const onData = (chunk) => {
419
+ clearTimeout(idle);
420
+ idle = startIdle();
421
+ chunks.push(chunk);
422
+ judge(reader.add(chunk), false);
423
+ };
424
+ const onEnd = () => judge(reader.end(), true);
425
+ const onError = () => settle({ refused: "request_failed" });
426
+ body.on("data", onData);
427
+ body.once("end", onEnd);
428
+ body.once("error", onError);
429
+ // A client that goes away before its command list ends would otherwise hold the check until a timeout.
430
+ body.once("close", onError);
431
+ });
432
+ }
433
+ outgoingHeaders(headers, route, credential) {
434
+ const out = {};
435
+ for (const [name, value] of Object.entries(headers)) {
436
+ if (value !== undefined && !HOP_BY_HOP.has(name))
437
+ out[name] = value;
438
+ }
439
+ out[route.header] = credential;
440
+ out.host = route.port === 443 ? route.hostname : `${route.hostname}:${route.port}`;
441
+ return out;
442
+ }
443
+ forward(route, method, path, headers, body, signal) {
444
+ return new Promise((resolve) => {
445
+ let upstream;
446
+ try {
447
+ upstream = this.openRoute(route, method, path, headers);
448
+ }
449
+ catch {
450
+ resolve(refusal(502, "request_invalid"));
451
+ return;
452
+ }
453
+ const stop = () => upstream.destroy(new Error("client gone"));
454
+ if (signal?.aborted === true)
455
+ stop();
456
+ else
457
+ signal?.addEventListener("abort", stop, { once: true });
458
+ upstream.once("close", () => signal?.removeEventListener("abort", stop));
459
+ this.requests.add(upstream);
460
+ upstream.setTimeout(this.idleMs, () => upstream.destroy(new Error("idle")));
461
+ upstream.once("close", () => this.requests.delete(upstream));
462
+ upstream.once("response", (reply) => {
463
+ const passed = {};
464
+ for (const [name, value] of Object.entries(reply.headers)) {
465
+ if (value !== undefined && !HOP_BY_HOP.has(name))
466
+ passed[name] = value;
467
+ }
468
+ resolve({ status: reply.statusCode ?? 502, headers: passed, body: reply });
469
+ });
470
+ upstream.once("error", (error) => resolve(refusal(502, this.reasonOf(error))));
471
+ if (body === undefined)
472
+ upstream.end();
473
+ else if (body instanceof Uint8Array)
474
+ upstream.end(body);
475
+ else
476
+ body.pipe(upstream);
477
+ });
478
+ }
479
+ /** Opens the HTTPS request to a route's host, which throws for a header or path Node refuses. */
480
+ openRoute(route, method, path, headers) {
481
+ return this.modules.https.request({
482
+ host: route.hostname,
483
+ port: route.port,
484
+ servername: route.hostname,
485
+ method,
486
+ path,
487
+ headers,
488
+ agent: false,
489
+ lookup: this.checkedLookup,
490
+ ...(this.options.ca === undefined ? {} : { ca: this.options.ca }),
491
+ });
492
+ }
493
+ /** An in-process fetch under the same allowlist, with the same address checks and pinned connection. */
494
+ async fetch(input, init) {
495
+ const request = new Request(input, init);
496
+ request.signal.throwIfAborted();
497
+ const url = new URL(request.url);
498
+ const host = url.hostname.toLowerCase().replace(/\.$/, "");
499
+ const port = url.port === "" ? 443 : Number(url.port);
500
+ const bodyBytes = request.method === "GET" || request.method === "HEAD" ? undefined : new Uint8Array(await request.arrayBuffer());
501
+ if (url.origin === ROUTE_ORIGIN || (this.origin !== "" && url.origin === this.origin)) {
502
+ return this.fetchRoute(request, url, bodyBytes);
503
+ }
504
+ const refuse = (reason) => {
505
+ this.record({ kind: "fetch", host, port, method: request.method, status: 403, bytes: 0, reason });
506
+ throw new HarnessError("egress_denied", `the egress proxy refused ${url.host}: ${reason}`);
507
+ };
508
+ if (url.protocol !== "https:")
509
+ return refuse("only_https");
510
+ if (isAddressLiteral(host))
511
+ return refuse("address_literal");
512
+ if (!isAllowed(this.allow, host, port))
513
+ return refuse("not_allowed");
514
+ return this.sendFetch(request, url, host, port, bodyBytes);
515
+ }
516
+ async fetchRoute(request, url, body) {
517
+ const headers = {};
518
+ request.headers.forEach((value, name) => {
519
+ headers[name.toLowerCase()] = value;
520
+ });
521
+ const path = `${url.pathname}${url.search}`;
522
+ const { reply, base } = await this.routeRequest(request.method, path, headers, body, request.signal);
523
+ const stream = reply.body;
524
+ let bytes = 0;
525
+ stream?.on("data", (chunk) => {
526
+ bytes += chunk.length;
527
+ });
528
+ const finished = () => this.record({
529
+ ...base,
530
+ status: reply.status,
531
+ bytes,
532
+ ...(reply.reason === undefined ? {} : { reason: reply.reason }),
533
+ });
534
+ if (stream === undefined)
535
+ finished();
536
+ else
537
+ stream.once("close", finished);
538
+ return this.toResponse(reply.status, reply.headers, stream);
539
+ }
540
+ sendFetch(request, url, host, port, body) {
541
+ return new Promise((resolve, reject) => {
542
+ const headers = {};
543
+ request.headers.forEach((value, name) => {
544
+ if (!HOP_BY_HOP.has(name.toLowerCase()))
545
+ headers[name] = value;
546
+ });
547
+ const upstream = this.modules.https.request({
548
+ host,
549
+ port,
550
+ servername: host,
551
+ method: request.method,
552
+ path: `${url.pathname}${url.search}`,
553
+ headers: { ...headers, host: url.host },
554
+ agent: false,
555
+ lookup: this.checkedLookup,
556
+ ...(this.options.ca === undefined ? {} : { ca: this.options.ca }),
557
+ });
558
+ this.requests.add(upstream);
559
+ const abort = () => upstream.destroy(request.signal.reason);
560
+ request.signal.addEventListener("abort", abort, { once: true });
561
+ upstream.once("close", () => {
562
+ this.requests.delete(upstream);
563
+ request.signal.removeEventListener("abort", abort);
564
+ });
565
+ upstream.setTimeout(this.idleMs, () => upstream.destroy(new Error("idle")));
566
+ upstream.once("response", (reply) => {
567
+ let bytes = 0;
568
+ reply.on("data", (chunk) => {
569
+ bytes += chunk.length;
570
+ });
571
+ // The record is written when the response is done with, which also covers one that is never read to its end.
572
+ reply.once("close", () => this.record({ kind: "fetch", host, port, method: request.method, status: reply.statusCode ?? 0, bytes }));
573
+ resolve(this.toResponse(reply.statusCode ?? 502, reply.headers, reply));
574
+ });
575
+ upstream.once("error", (error) => {
576
+ if (request.signal.aborted) {
577
+ reject(request.signal.reason);
578
+ return;
579
+ }
580
+ const reason = this.reasonOf(error);
581
+ this.record({ kind: "fetch", host, port, method: request.method, status: 502, bytes: 0, reason });
582
+ reject(new HarnessError("egress_denied", `the egress proxy could not reach ${url.host}: ${reason}`, {
583
+ cause: error,
584
+ }));
585
+ });
586
+ upstream.end(body);
587
+ });
588
+ }
589
+ toResponse(status, headers, stream) {
590
+ const out = new Headers();
591
+ for (const [name, value] of Object.entries(headers)) {
592
+ for (const one of Array.isArray(value) ? value : [value])
593
+ out.append(name, one);
594
+ }
595
+ const bodiless = stream === undefined || [101, 204, 205, 304].includes(status);
596
+ // A response with no body is drained, so its socket and its log record don't wait for a reader that never comes.
597
+ if (bodiless)
598
+ stream?.resume();
599
+ const web = bodiless ? null : this.modules.stream.Readable.toWeb(stream);
600
+ return new Response(web, { status, headers: out });
601
+ }
602
+ async knownSecrets() {
603
+ const secrets = await Promise.all([...this.routes.values()].map((route) => route.secret().catch(() => "")));
604
+ return [...new Set(secrets.filter((secret) => secret !== ""))];
605
+ }
606
+ close(server) {
607
+ return new Promise((resolve) => {
608
+ for (const socket of this.sockets)
609
+ socket.destroy();
610
+ for (const request of this.requests)
611
+ request.destroy();
612
+ server.close(() => resolve());
613
+ server.closeAllConnections();
614
+ });
615
+ }
616
+ }
617
+ /**
618
+ * Starts the egress proxy on `127.0.0.1` with a port the system picks, or on `socketPath`. The allowlist and routes are
619
+ * checked first, and a bad entry throws `invalid_egress_options`. Give the sandbox `proxy.url` as `HTTPS_PROXY`, and
620
+ * give a tool that needs a credential the route's URL and its sentinel.
621
+ */
622
+ export async function startEgressProxy(options) {
623
+ const modules = nodeModules();
624
+ const proxy = new EgressGate(modules, options);
625
+ const server = modules.http.createServer((request, response) => proxy.handleRequest(request, response));
626
+ server.on("connect", (request, socket, head) => proxy.handleConnect(request, socket, head));
627
+ server.on("clientError", (_error, socket) => socket.destroy());
628
+ await new Promise((resolve, reject) => {
629
+ server.once("error", reject);
630
+ if (options.socketPath === undefined)
631
+ server.listen(0, "127.0.0.1", resolve);
632
+ else
633
+ server.listen(options.socketPath, resolve);
634
+ });
635
+ const address = server.address();
636
+ const url = options.socketPath !== undefined
637
+ ? `unix:${options.socketPath}`
638
+ : `http://127.0.0.1:${address.port}`;
639
+ if (options.socketPath === undefined)
640
+ proxy.setOrigin(url);
641
+ return {
642
+ url,
643
+ ...(options.socketPath === undefined ? {} : { socketPath: options.socketPath }),
644
+ sentinels: proxy.sentinelMap(),
645
+ fetch: (input, init) => proxy.fetch(input, init),
646
+ knownSecrets: () => proxy.knownSecrets(),
647
+ close: () => proxy.close(server),
648
+ };
649
+ }
650
+ //# sourceMappingURL=egress-proxy.js.map