omnicell-router 0.7.0 → 0.8.2

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 (246) hide show
  1. package/backend/dist/cli/clients/activity.d.ts +35 -0
  2. package/backend/dist/cli/clients/activity.js +67 -0
  3. package/backend/dist/cli/clients/base.d.ts +13 -2
  4. package/backend/dist/cli/clients/claude.d.ts +2 -2
  5. package/backend/dist/cli/clients/codex.d.ts +2 -2
  6. package/backend/dist/cli/clients/core-adapters.d.ts +3 -4
  7. package/backend/dist/cli/clients/core-adapters.js +3 -4
  8. package/backend/dist/cli/clients/cursor-proxy.d.ts +88 -0
  9. package/backend/dist/cli/clients/cursor-proxy.js +421 -0
  10. package/backend/dist/cli/clients/dsh.d.ts +2 -2
  11. package/backend/dist/cli/clients/grok.d.ts +2 -2
  12. package/backend/dist/cli/clients/index.d.ts +8 -1
  13. package/backend/dist/cli/clients/index.js +55 -21
  14. package/backend/dist/cli/clients/kimi.d.ts +2 -2
  15. package/backend/dist/cli/clients/launcher.d.ts +8 -0
  16. package/backend/dist/cli/clients/model-meta.js +1 -1
  17. package/backend/dist/cli/clients/omp.d.ts +2 -2
  18. package/backend/dist/cli/clients/openclaw.d.ts +2 -2
  19. package/backend/dist/cli/clients/opencode-proxy.d.ts +11 -0
  20. package/backend/dist/cli/clients/opencode-proxy.js +351 -0
  21. package/backend/dist/cli/clients/opencode.d.ts +2 -2
  22. package/backend/dist/cli/clients/pi.d.ts +2 -2
  23. package/backend/dist/cli/clients/plugin-adapters.d.ts +3 -1
  24. package/backend/dist/cli/clients/plugin-adapters.js +6 -29
  25. package/backend/dist/cli/clients/qoder-proxy.d.ts +84 -0
  26. package/backend/dist/cli/clients/qoder-proxy.js +497 -0
  27. package/backend/dist/cli/clients/reserved.d.ts +2 -6
  28. package/backend/dist/cli/clients/reserved.js +2 -0
  29. package/backend/dist/cli/clients/workbuddy.d.ts +2 -2
  30. package/backend/dist/cli/index.js +60 -9
  31. package/backend/dist/cli/types.d.ts +29 -8
  32. package/backend/dist/compression/caveman-prompts.d.ts +1 -1
  33. package/backend/dist/config/comments-en.js +6 -12
  34. package/backend/dist/config/comments-zh.js +6 -12
  35. package/backend/dist/config/defaults.d.ts +56 -1
  36. package/backend/dist/config/defaults.js +68 -0
  37. package/backend/dist/config/index.d.ts +9 -2
  38. package/backend/dist/config/index.js +26 -3
  39. package/backend/dist/config/types.d.ts +55 -43
  40. package/backend/dist/forward-proxy/egress.d.ts +10 -2
  41. package/backend/dist/forward-proxy/egress.js +42 -4
  42. package/backend/dist/forward-proxy/ordered-relay.d.ts +29 -0
  43. package/backend/dist/forward-proxy/ordered-relay.js +46 -0
  44. package/backend/dist/forward-proxy/rules.d.ts +66 -19
  45. package/backend/dist/forward-proxy/rules.js +61 -14
  46. package/backend/dist/forward-proxy/server.js +226 -77
  47. package/backend/dist/forward-proxy/system-proxy.d.ts +42 -2
  48. package/backend/dist/forward-proxy/system-proxy.js +199 -22
  49. package/backend/dist/harness/common/market.d.ts +3 -3
  50. package/backend/dist/harness/host/adapters/amp.d.ts +1 -1
  51. package/backend/dist/harness/host/adapters/antigravity.d.ts +1 -1
  52. package/backend/dist/harness/host/adapters/claude.d.ts +1 -1
  53. package/backend/dist/harness/host/adapters/cline.d.ts +1 -1
  54. package/backend/dist/harness/host/adapters/codex.d.ts +1 -1
  55. package/backend/dist/harness/host/adapters/cursor.d.ts +1 -1
  56. package/backend/dist/harness/host/adapters/dsh.d.ts +2 -2
  57. package/backend/dist/harness/host/adapters/factory.d.ts +1 -1
  58. package/backend/dist/harness/host/adapters/gemini-cli.d.ts +1 -1
  59. package/backend/dist/harness/host/adapters/grok.d.ts +1 -1
  60. package/backend/dist/harness/host/adapters/kimi.d.ts +1 -1
  61. package/backend/dist/harness/host/adapters/omp.d.ts +1 -1
  62. package/backend/dist/harness/host/adapters/openclaw.d.ts +1 -1
  63. package/backend/dist/harness/host/adapters/opencode.d.ts +1 -1
  64. package/backend/dist/harness/host/adapters/pi.d.ts +1 -1
  65. package/backend/dist/harness/host/adapters/universal.d.ts +1 -1
  66. package/backend/dist/harness/host/adapters/windsurf.d.ts +1 -1
  67. package/backend/dist/harness/host/adapters/zed.d.ts +1 -1
  68. package/backend/dist/harness/skill/skills-sh.d.ts +1 -1
  69. package/backend/dist/harness/translation.js +64 -21
  70. package/backend/dist/harness/types.d.ts +1 -1
  71. package/backend/dist/harness/types.js +1 -1
  72. package/backend/dist/index.js +31 -18
  73. package/backend/dist/ir/adapters/anthropic-stream.d.ts +18 -0
  74. package/backend/dist/ir/adapters/anthropic-stream.js +247 -0
  75. package/backend/dist/ir/adapters/anthropic.d.ts +29 -0
  76. package/backend/dist/ir/adapters/anthropic.js +788 -0
  77. package/backend/dist/ir/adapters/chat.d.ts +15 -0
  78. package/backend/dist/ir/adapters/chat.js +602 -0
  79. package/backend/dist/ir/adapters/google-stream.d.ts +22 -0
  80. package/backend/dist/ir/adapters/google-stream.js +242 -0
  81. package/backend/dist/ir/adapters/google.d.ts +9 -0
  82. package/backend/dist/ir/adapters/google.js +317 -0
  83. package/backend/dist/ir/adapters/openai-responses-output.js +8 -5
  84. package/backend/dist/ir/adapters/openai-responses.d.ts +15 -0
  85. package/backend/dist/ir/adapters/openai-responses.js +26 -1
  86. package/backend/dist/ir/adapters/responses-output.d.ts +50 -0
  87. package/backend/dist/ir/adapters/responses-output.js +348 -0
  88. package/backend/dist/ir/adapters/responses-stream.d.ts +12 -0
  89. package/backend/dist/ir/adapters/responses-stream.js +178 -0
  90. package/backend/dist/ir/adapters/responses.d.ts +14 -0
  91. package/backend/dist/ir/adapters/responses.js +646 -0
  92. package/backend/dist/ir/errors.d.ts +2 -2
  93. package/backend/dist/ir/types.d.ts +2 -1
  94. package/backend/dist/metrics/request-cost.d.ts +11 -2
  95. package/backend/dist/metrics/request-cost.js +12 -3
  96. package/backend/dist/observability/request-identity.d.ts +1 -1
  97. package/backend/dist/observability/trace-id.d.ts +40 -0
  98. package/backend/dist/observability/trace-id.js +134 -0
  99. package/backend/dist/observability/upstream-events.d.ts +82 -60
  100. package/backend/dist/observability/upstream-events.js +142 -67
  101. package/backend/dist/opencode/catalog/types.d.ts +9 -0
  102. package/backend/dist/opencode/credentials/types.d.ts +2 -2
  103. package/backend/dist/opencode/probe.d.ts +24 -1
  104. package/backend/dist/opencode/probe.js +28 -4
  105. package/backend/dist/opencode/user-config.d.ts +5 -0
  106. package/backend/dist/pipeline/directives.d.ts +6 -2
  107. package/backend/dist/pipeline/directives.js +7 -3
  108. package/backend/dist/pipeline/orchestrator.d.ts +28 -27
  109. package/backend/dist/pipeline/orchestrator.js +220 -194
  110. package/backend/dist/pipeline/unresolved-model.d.ts +33 -0
  111. package/backend/dist/pipeline/unresolved-model.js +43 -0
  112. package/backend/dist/plugins/catalog-def.d.ts +143 -0
  113. package/backend/dist/plugins/catalog-def.js +177 -0
  114. package/backend/dist/plugins/gateways.d.ts +62 -3
  115. package/backend/dist/plugins/gateways.js +139 -2
  116. package/backend/dist/plugins/host.d.ts +42 -5
  117. package/backend/dist/plugins/host.js +454 -38
  118. package/backend/dist/plugins/manifest.d.ts +119 -10
  119. package/backend/dist/plugins/manifest.js +265 -14
  120. package/backend/dist/plugins/pack.js +26 -0
  121. package/backend/dist/plugins/types.d.ts +187 -21
  122. package/backend/dist/protocols/systemone/convert.d.ts +1 -0
  123. package/backend/dist/protocols/systemone/convert.js +6 -1
  124. package/backend/dist/protocols/systemone/decide.js +18 -8
  125. package/backend/dist/providers/anthropic-messages.d.ts +12 -0
  126. package/backend/dist/providers/anthropic-messages.js +53 -0
  127. package/backend/dist/providers/anthropic.d.ts +7 -8
  128. package/backend/dist/providers/anthropic.js +36 -324
  129. package/backend/dist/providers/base.d.ts +14 -2
  130. package/backend/dist/providers/boot-direct.js +68 -38
  131. package/backend/dist/providers/dispatch.d.ts +5 -19
  132. package/backend/dist/providers/dispatch.js +46 -58
  133. package/backend/dist/providers/executors/anthropic-messages.d.ts +1 -0
  134. package/backend/dist/providers/executors/anthropic-messages.js +3 -0
  135. package/backend/dist/providers/executors/dispatch.d.ts +16 -2
  136. package/backend/dist/providers/executors/dispatch.js +39 -9
  137. package/backend/dist/providers/executors/google-gemini.d.ts +1 -0
  138. package/backend/dist/providers/executors/google-gemini.js +3 -0
  139. package/backend/dist/providers/executors/http-stream.js +16 -3
  140. package/backend/dist/providers/executors/openai-chat.d.ts +1 -0
  141. package/backend/dist/providers/executors/openai-chat.js +3 -0
  142. package/backend/dist/providers/executors/openai-responses.d.ts +1 -0
  143. package/backend/dist/providers/executors/openai-responses.js +3 -0
  144. package/backend/dist/providers/executors/plugin-adapter.js +4 -4
  145. package/backend/dist/providers/google-gemini.d.ts +12 -0
  146. package/backend/dist/providers/google-gemini.js +50 -0
  147. package/backend/dist/providers/google.d.ts +7 -8
  148. package/backend/dist/providers/google.js +35 -308
  149. package/backend/dist/providers/http-json.d.ts +19 -0
  150. package/backend/dist/providers/http-json.js +104 -0
  151. package/backend/dist/providers/http-stream.d.ts +52 -0
  152. package/backend/dist/providers/http-stream.js +423 -0
  153. package/backend/dist/providers/member-match.d.ts +4 -5
  154. package/backend/dist/providers/member-match.js +4 -5
  155. package/backend/dist/providers/openai-chat.d.ts +13 -0
  156. package/backend/dist/providers/openai-chat.js +99 -0
  157. package/backend/dist/providers/openai-compatible.d.ts +7 -4
  158. package/backend/dist/providers/openai-compatible.js +71 -368
  159. package/backend/dist/providers/openai-responses.d.ts +12 -0
  160. package/backend/dist/providers/openai-responses.js +68 -0
  161. package/backend/dist/providers/opencode-proxy.d.ts +5 -5
  162. package/backend/dist/providers/opencode-proxy.js +49 -125
  163. package/backend/dist/providers/plugin-adapter.d.ts +9 -0
  164. package/backend/dist/providers/plugin-adapter.js +31 -0
  165. package/backend/dist/providers/registry.d.ts +49 -24
  166. package/backend/dist/providers/registry.js +97 -55
  167. package/backend/dist/providers/responses.d.ts +7 -28
  168. package/backend/dist/providers/responses.js +45 -253
  169. package/backend/dist/providers/tool-markup-leak.d.ts +41 -0
  170. package/backend/dist/providers/tool-markup-leak.js +57 -0
  171. package/backend/dist/providers/tool-markup-recovery.d.ts +27 -0
  172. package/backend/dist/providers/tool-markup-recovery.js +786 -0
  173. package/backend/dist/providers/virtual-meta.d.ts +21 -2
  174. package/backend/dist/providers/virtual-meta.js +49 -9
  175. package/backend/dist/proxy/asset-download.d.ts +54 -0
  176. package/backend/dist/proxy/asset-download.js +420 -0
  177. package/backend/dist/proxy/manual-node-spec.d.ts +16 -16
  178. package/backend/dist/proxy/mihomo-binary.d.ts +17 -2
  179. package/backend/dist/proxy/mihomo-binary.js +62 -51
  180. package/backend/dist/proxy/mihomo-client.js +15 -1
  181. package/backend/dist/proxy/mihomo-config.js +11 -2
  182. package/backend/dist/proxy/mihomo-geo.d.ts +87 -0
  183. package/backend/dist/proxy/mihomo-geo.js +213 -0
  184. package/backend/dist/proxy/mihomo-logs.d.ts +27 -0
  185. package/backend/dist/proxy/mihomo-logs.js +70 -0
  186. package/backend/dist/proxy/mihomo-pac.d.ts +11 -0
  187. package/backend/dist/proxy/mihomo-pac.js +15 -0
  188. package/backend/dist/proxy/mihomo-rules-import.d.ts +1 -1
  189. package/backend/dist/proxy/mihomo-rules-import.js +7 -7
  190. package/backend/dist/proxy/mihomo-sidecar.d.ts +17 -1
  191. package/backend/dist/proxy/mihomo-sidecar.js +148 -26
  192. package/backend/dist/quota/adapters/minimax.js +36 -13
  193. package/backend/dist/quota/cli-login.d.ts +8 -0
  194. package/backend/dist/quota/cli-login.js +18 -0
  195. package/backend/dist/quota/declarations.js +10 -0
  196. package/backend/dist/quota/dsl.js +18 -5
  197. package/backend/dist/quota/engine.d.ts +22 -1
  198. package/backend/dist/quota/engine.js +170 -29
  199. package/backend/dist/quota/prober.d.ts +5 -0
  200. package/backend/dist/quota/prober.js +11 -2
  201. package/backend/dist/quota/types.d.ts +87 -8
  202. package/backend/dist/quota/verdict.d.ts +35 -0
  203. package/backend/dist/quota/verdict.js +135 -0
  204. package/backend/dist/ratelimit/admission.d.ts +131 -0
  205. package/backend/dist/ratelimit/admission.js +233 -0
  206. package/backend/dist/ratelimit/rate-limiter.js +6 -0
  207. package/backend/dist/resilience/types.d.ts +2 -2
  208. package/backend/dist/router/layer2-decision.d.ts +1 -1
  209. package/backend/dist/router/layer2-decision.js +5 -8
  210. package/backend/dist/routes/console.js +248 -52
  211. package/backend/dist/routes/mihomo.d.ts +2 -0
  212. package/backend/dist/routes/mihomo.js +334 -29
  213. package/backend/dist/routes/responses.d.ts +87 -8
  214. package/backend/dist/routes/responses.js +314 -33
  215. package/backend/dist/server.js +34 -6
  216. package/backend/dist/session/session-manager.d.ts +6 -0
  217. package/backend/dist/session/session-manager.js +20 -9
  218. package/backend/dist/surfaces/chat-pipeline.d.ts +2 -2
  219. package/backend/dist/surfaces/chat-pipeline.js +17 -7
  220. package/backend/dist/surfaces/chat.js +15 -0
  221. package/backend/dist/surfaces/decision-pipeline.js +7 -10
  222. package/backend/dist/surfaces/direct-forward.d.ts +3 -0
  223. package/backend/dist/surfaces/direct-forward.js +206 -0
  224. package/backend/dist/surfaces/rate-limit-response.d.ts +17 -0
  225. package/backend/dist/surfaces/rate-limit-response.js +57 -0
  226. package/backend/dist/surfaces/types.d.ts +11 -0
  227. package/backend/dist/trace/tracker.d.ts +32 -1
  228. package/backend/dist/trace/tracker.js +29 -4
  229. package/backend/dist/types/router.d.ts +34 -12
  230. package/backend/dist/types/router.js +35 -6
  231. package/backend/dist/utils/chat-stream.d.ts +21 -8
  232. package/backend/dist/utils/chat-stream.js +46 -9
  233. package/backend/dist/utils/event-ring.d.ts +4 -0
  234. package/backend/dist/utils/event-ring.js +4 -0
  235. package/backend/dist/utils/popularity.js +29 -4
  236. package/backend/dist/utils/proxy.d.ts +7 -0
  237. package/backend/dist/utils/proxy.js +35 -10
  238. package/backend/dist/utils/retry-after.d.ts +21 -0
  239. package/backend/dist/utils/retry-after.js +36 -0
  240. package/bin/ocr.js +2 -2
  241. package/frontend/dist/assets/index-55VVwfFQ.js +1521 -0
  242. package/frontend/dist/assets/{index-CQSLGFTV.css → index-DxZ9MHKB.css} +1 -1
  243. package/frontend/dist/assets/workbuddy.color-DOMpQkxJ.svg +29 -0
  244. package/frontend/dist/index.html +2 -2
  245. package/package.json +1 -1
  246. package/frontend/dist/assets/index-CLvxJjp_.js +0 -1476
@@ -2,11 +2,12 @@ import http from 'node:http';
2
2
  import https from 'node:https';
3
3
  import net from 'node:net';
4
4
  import tls from 'node:tls';
5
+ import { OrderedRelay } from './ordered-relay.js';
5
6
  import { CertMinter, ensureCa } from './ca.js';
6
7
  import { peekClientHello } from './sni.js';
7
8
  import { splice } from './relay.js';
8
9
  import { DEFAULT_FORWARD_PROXY_MAX_CONNECTIONS, FORWARD_PROXY_HANG_TIMEOUT_MS, FORWARD_PROXY_KEEPALIVE_MS, } from '../config/defaults.js';
9
- import { describeUpstreamFailure, filterHeaders, isRuleRejected, openViaProxy, parseProxy, ruleTunnels, setBootRules, setLiveForwardProxy, transitEgressFor, transitProxyFor, UPSTREAM_TIMEOUT_CODE, upstreamServernameOption, } from './egress.js';
10
+ import { describeUpstreamFailure, failureLabel, filterHeaders, isRuleRejected, openViaProxy, parseProxy, ruleTunnels, setBootRules, setLiveForwardProxy, transitEgressFor, shouldRetryOriginLeg, transitProxyFor, UPSTREAM_TIMEOUT_CODE, upstreamServernameOption, } from './egress.js';
10
11
  import { resolveUpstreamTls } from './upstream-tls.js';
11
12
  import { createAccessTap, recordProxyConnect, recordProxyTunnel } from './access-log.js';
12
13
  import { closeH2Pool, forwardH2 } from './h2-forward.js';
@@ -100,6 +101,41 @@ const MITM_ABORT_FLUSH_MS = 1_000;
100
101
  * this only bounds the observation window for a server-speaks-first protocol.
101
102
  */
102
103
  const CLIENT_ERROR_RESPONSE = 'HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n';
104
+ /**
105
+ * Credential-shaped header names in a raw packet head. The access log applies
106
+ * the same policy to captured headers (`DENY_HEADER_SUBSTRINGS`), and this log
107
+ * line must not become the one place a live key lands on disk.
108
+ */
109
+ const CREDENTIAL_HEADER_LINE = /^(?:proxy-)?authorization$|^cookie$|^set-cookie$|-key$|api[-_]?key|apikey|token|secret/i;
110
+ /** Blank the value of every credential-shaped header line, keep the rest. */
111
+ function redactPacketHead(raw) {
112
+ return raw
113
+ .split('\r\n')
114
+ .map((line) => {
115
+ const at = line.indexOf(':');
116
+ if (at <= 0)
117
+ return line;
118
+ const name = line.slice(0, at);
119
+ return CREDENTIAL_HEADER_LINE.test(name.trim()) ? `${name}: [REDACTED]` : line;
120
+ })
121
+ .join('\r\n');
122
+ }
123
+ /**
124
+ * One line describing a request the HTTP parser refused. The 400 that follows
125
+ * carries an EMPTY body, so without this the client only ever reports
126
+ * "400 Bad Request" with no headers and the operator has nothing to look at —
127
+ * the raw packet head (request line + first headers) is the only evidence of
128
+ * what the client actually sent.
129
+ */
130
+ function describeClientError(err) {
131
+ if (typeof err !== 'object' || err === null)
132
+ return String(err);
133
+ const code = 'code' in err && typeof err.code === 'string' ? err.code : 'unknown';
134
+ const raw = 'rawPacket' in err && Buffer.isBuffer(err.rawPacket)
135
+ ? redactPacketHead(err.rawPacket.subarray(0, 240).toString('latin1'))
136
+ : '';
137
+ return raw ? `${code} raw=${JSON.stringify(raw)}` : code;
138
+ }
103
139
  /** Raw-socket 403 for a CONNECT whose host a rule rejects (ADR-0018).
104
140
  * Answered on the raw socket BEFORE the 200, so no tunnel and no minted
105
141
  * certificate ever exist for a rejected host. */
@@ -152,6 +188,16 @@ function splitHostPort(value, defaultPort) {
152
188
  }
153
189
  return { host: raw, port: defaultPort };
154
190
  }
191
+ /**
192
+ * The canonical spelling of a host for an `:authority` / `Host` value: the
193
+ * default HTTPS port is implicit, any other port is kept, and an IPv6 literal
194
+ * is bracketed. Mirrors the upstream rebuild in `h2-forward.ts` (`authorityOf`)
195
+ * so the value a gateway plugin reads matches the one the relay forwards.
196
+ */
197
+ function authoritySpelling(host, port) {
198
+ const bracketed = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
199
+ return port === 443 ? bracketed : `${bracketed}:${port}`;
200
+ }
155
201
  /** Per-response slot carrying the connection's abort hook to `proxyFail`. */
156
202
  const MITM_ABORT = Symbol('ocr.forwardProxy.mitmAbort');
157
203
  /**
@@ -410,75 +456,155 @@ export function proxyFail(res, code, msg) {
410
456
  * relay → https.request over the relay (TLS runs end-to-end through the
411
457
  * tunnel, so the real target certificate is what gets validated).
412
458
  */
413
- function forwardSecureViaProxy(req, res, t, proxyUrl, upstreamTls) {
459
+ function forwardSecureViaProxy(req, res, t, proxyUrl, upstreamTls, attempt = 0) {
460
+ // ES2022 lib here has no Promise.withResolvers; the executor form is the
461
+ // only way to keep `resolve` for the retry re-entry.
414
462
  return new Promise((resolve) => {
415
- openViaProxy(proxyUrl, t.host, t.port)
416
- .then((pipeSock) => {
417
- const relay = net.createServer((c) => {
418
- c.pipe(pipeSock);
419
- pipeSock.pipe(c);
420
- });
421
- const cleanup = () => {
422
- try {
423
- relay.close();
424
- }
425
- catch { }
426
- try {
427
- pipeSock.destroy();
428
- }
429
- catch { }
463
+ // One relay attempt. `retry` re-enters this function with attempt + 1; the
464
+ // returned promise settles exactly once, from whichever attempt finishes.
465
+ const relayOnce = () => {
466
+ // The request stream is consumed ONLY once the origin leg is secure: a
467
+ // retry re-reads `req` from wherever it stands, and a chunk already handed
468
+ // to a dying TLS socket cannot be rewound. Deferring the pump makes
469
+ // "nothing reached the origin" and "nothing left the client" the same
470
+ // fact, so `sentBytes === 0` really is replay-safe. (The outbound proxy's
471
+ // usual failure — a tunnel closed right after CONNECT — dies before
472
+ // `secureConnect`, so this is exactly the case the retry exists for.)
473
+ let originSecure = false;
474
+ let pumping = false;
475
+ let sentBytes = 0;
476
+ const countingTap = {
477
+ onReqChunk: (chunk) => {
478
+ if (originSecure)
479
+ sentBytes += chunk.length;
480
+ t.tap?.onReqChunk(chunk);
481
+ },
482
+ onResChunk: (chunk) => t.tap?.onResChunk(chunk),
483
+ finish: (status, headers, note) => t.tap?.finish(status, headers, note),
430
484
  };
431
- relay.on('error', cleanup);
432
- relay.listen(0, '127.0.0.1', () => {
433
- const relayPort = relay.address().port;
434
- const upstream = https.request({
435
- host: '127.0.0.1',
436
- port: relayPort,
437
- method: req.method,
438
- path: t.path,
439
- headers: filterHeaders(req.headers),
440
- ...upstreamServernameOption(t.host),
441
- ...(upstreamTls.opts || {}),
442
- }, (up) => {
443
- upstream.setTimeout(0);
444
- res.writeHead(up.statusCode || 502, filterHeaders(up.headers));
445
- pipeUpResponse(up, res, t.tap);
446
- up.on('end', () => {
447
- t.tap?.finish(up.statusCode, up.headers);
448
- cleanup();
449
- resolve();
485
+ const retry = (err) => {
486
+ // A started pump means the client stream may already be partly consumed
487
+ // (and, on the h2 preface path, still has live listeners attached to
488
+ // it) — never replay that, even when no byte reached the origin.
489
+ if (pumping)
490
+ return false;
491
+ if (!shouldRetryOriginLeg(err, { headersSent: res.headersSent, sentBytes, attempts: attempt }))
492
+ return false;
493
+ // Do NOT finish the tap here: `AccessTap.finish` appends one ledger row,
494
+ // and the retry attempt completes the SAME tap (nothing was tapped yet —
495
+ // the pump never started). Finishing here would leave a ghost failed row
496
+ // beside the real one for a single exchange.
497
+ void forwardSecureViaProxy(req, res, t, proxyUrl, upstreamTls, attempt + 1).then(resolve);
498
+ return true;
499
+ };
500
+ openViaProxy(proxyUrl, t.host, t.port)
501
+ .then((pipeSock) => {
502
+ const relay = net.createServer((c) => {
503
+ // A retry tears the tunnel down mid-handshake; an unhandled error on
504
+ // the loopback leg would crash the process instead of failing the
505
+ // attempt.
506
+ c.on('error', () => c.destroy());
507
+ c.pipe(pipeSock);
508
+ pipeSock.pipe(c);
509
+ });
510
+ const cleanup = () => {
511
+ try {
512
+ relay.close();
513
+ }
514
+ catch { }
515
+ try {
516
+ pipeSock.destroy();
517
+ }
518
+ catch { }
519
+ };
520
+ relay.on('error', cleanup);
521
+ relay.listen(0, '127.0.0.1', () => {
522
+ const relayPort = relay.address().port;
523
+ const upstream = https.request({
524
+ host: '127.0.0.1',
525
+ port: relayPort,
526
+ method: req.method,
527
+ path: t.path,
528
+ headers: filterHeaders(req.headers),
529
+ ...upstreamServernameOption(t.host),
530
+ ...(upstreamTls.opts || {}),
531
+ }, (up) => {
532
+ upstream.setTimeout(0);
533
+ res.writeHead(up.statusCode || 502, filterHeaders(up.headers));
534
+ pipeUpResponse(up, res, t.tap);
535
+ up.on('end', () => {
536
+ t.tap?.finish(up.statusCode, up.headers);
537
+ cleanup();
538
+ resolve();
539
+ });
540
+ up.on('error', () => {
541
+ try {
542
+ res.destroy();
543
+ }
544
+ catch { }
545
+ t.tap?.finish(up.statusCode, up.headers, 'upstream error mid-response');
546
+ cleanup();
547
+ resolve();
548
+ });
450
549
  });
451
- up.on('error', () => {
550
+ // Nothing is read from `req` until the origin TLS leg is live (see
551
+ // the pump comment above): `secureConnect` never fires on a tunnel
552
+ // that died at open, so a retry sees the request untouched. A socket
553
+ // reused from the keep-alive pool is already secure.
554
+ // `req` has no listener until then; an inbound abort in that window
555
+ // must not surface as an unhandled 'error'.
556
+ req.on('error', () => {
452
557
  try {
453
- res.destroy();
558
+ upstream.destroy();
454
559
  }
455
560
  catch { }
456
- t.tap?.finish(up.statusCode, up.headers, 'upstream error mid-response');
561
+ });
562
+ const startPump = () => {
563
+ if (pumping)
564
+ return;
565
+ pumping = true;
566
+ pumpRequestBody(req, upstream, countingTap, t.preface);
567
+ };
568
+ upstream.on('socket', (sock) => {
569
+ if (sock.connecting) {
570
+ sock.once('secureConnect', () => {
571
+ originSecure = true;
572
+ startPump();
573
+ });
574
+ }
575
+ else {
576
+ originSecure = true;
577
+ startPump();
578
+ }
579
+ });
580
+ armUpstreamKeepalive(upstream);
581
+ upstream.setTimeout(FORWARD_PROXY_HANG_TIMEOUT_MS, () => {
582
+ upstream.destroy(hangGuardError());
583
+ });
584
+ upstream.on('error', (err) => {
585
+ if (retry(err)) {
586
+ cleanup();
587
+ return;
588
+ }
589
+ const failure = describeUpstreamFailure(err, { proxied: true });
590
+ t.tap?.finish(undefined, undefined, failure.note);
591
+ proxyFail(res, failure.status, failure.message);
457
592
  cleanup();
458
593
  resolve();
459
594
  });
460
595
  });
461
- armUpstreamKeepalive(upstream);
462
- upstream.setTimeout(FORWARD_PROXY_HANG_TIMEOUT_MS, () => {
463
- upstream.destroy(hangGuardError());
464
- });
465
- upstream.on('error', (err) => {
466
- const failure = describeUpstreamFailure(err, { proxied: true });
467
- t.tap?.finish(undefined, undefined, failure.note);
468
- proxyFail(res, failure.status, failure.message);
469
- cleanup();
470
- resolve();
471
- });
472
- pumpRequestBody(req, upstream, t.tap, t.preface);
596
+ })
597
+ .catch((err) => {
598
+ // Same rule for the CONNECT itself: nothing was written, so one fresh
599
+ // tunnel is safe. Otherwise report the outbound-proxy class distinctly.
600
+ if (retry(err))
601
+ return;
602
+ t.tap?.finish(undefined, undefined, `outbound proxy connect failed: ${failureLabel(err)}`);
603
+ proxyFail(res, 502, `Forward proxy: outbound proxy connection failed (${failureLabel(err)})`);
604
+ resolve();
473
605
  });
474
- })
475
- .catch((err) => {
476
- // The CONNECT to the outbound proxy itself failed — a different class
477
- // from an origin failure, and the note must say so.
478
- t.tap?.finish(undefined, undefined, `outbound proxy connect failed: ${err?.code || err?.message || err}`);
479
- proxyFail(res, 502, `Forward proxy: outbound proxy connection failed (${err?.message || err})`);
480
- resolve();
481
- });
606
+ };
607
+ relayOnce();
482
608
  });
483
609
  }
484
610
  /** Plain-HTTP target via an outbound HTTP proxy (absolute-URI request form). */
@@ -538,7 +664,8 @@ export async function createForwardProxyServer(deps) {
538
664
  const inner = http.createServer((req, res) => {
539
665
  void handleInnerRequest(req, res, false);
540
666
  });
541
- inner.on('clientError', (_err, socket) => {
667
+ inner.on('clientError', (err, socket) => {
668
+ log(`inner clientError ${describeClientError(err)}`);
542
669
  try {
543
670
  socket.end(CLIENT_ERROR_RESPONSE);
544
671
  }
@@ -564,8 +691,6 @@ export async function createForwardProxyServer(deps) {
564
691
  // authenticated caller; the gateway leg reads it via ALS (ADR-0017).
565
692
  const mitmTarget = mitmTargets.get(req.socket?.remotePort ?? -1);
566
693
  markProxyCaller(req, mitmTarget?.caller);
567
- if (await deps.intercept(req, res))
568
- return;
569
694
  // h2 compatibility requests carry the target in `:authority` (there is
570
695
  // no `host` header) — accept either so gateway-declined h2 traffic can
571
696
  // still fall through to transparent forward.
@@ -581,6 +706,17 @@ export async function createForwardProxyServer(deps) {
581
706
  res[MITM_ABORT] = mitmTarget.abort;
582
707
  }
583
708
  const { host, port } = splitHostPort(hostHeader, connectPort ?? 443);
709
+ // Normalize the h2 `:authority` BEFORE any gateway sees it. An h2 client
710
+ // may write the default port (`gw.test:443`), an h1 client's `Host`
711
+ // normally omits it — without this a gateway plugin reads a different
712
+ // host spelling per negotiated protocol and has to re-parse it. Same
713
+ // rule as the upstream rebuild (`h2-forward.ts` `authorityOf`): 443 is
714
+ // implicit, every other port is kept.
715
+ if (h2Leg && host && typeof req.headers[':authority'] === 'string') {
716
+ req.headers[':authority'] = authoritySpelling(host, port);
717
+ }
718
+ if (await deps.intercept(req, res))
719
+ return;
584
720
  if (!host) {
585
721
  proxyFail(res, 400, 'Forward proxy: missing Host header');
586
722
  return;
@@ -786,9 +922,20 @@ export async function createForwardProxyServer(deps) {
786
922
  * server unexamined.
787
923
  */
788
924
  function onDecryptedConnection(tlsSock, target, reportClientFailure) {
789
- const pending = [];
925
+ /** Client plaintext, in arrival order, regardless of when the hop is ready. */
926
+ const relay = new OrderedRelay();
790
927
  let conn = null;
791
928
  let decided = false;
929
+ /**
930
+ * True once the loopback hop to the inner server is CONNECTED. Until then
931
+ * every decrypted chunk is held by `relay`, because `conn` exists
932
+ * (net.connect returns before it connects) and writing to it would QUEUE
933
+ * bytes ahead of the buffered head. That inversion is not cosmetic: a body
934
+ * arrives as many chunks, so the tail would reach the parser before the
935
+ * request line and the inner server answers 400 to a message it never saw —
936
+ * the client's "request failed with empty body (code 400)" on large prompts.
937
+ */
938
+ let connected = false;
792
939
  /** Decrypted bytes seen so far — zero at close means the client never spoke. */
793
940
  let decryptedBytes = 0;
794
941
  /**
@@ -813,19 +960,19 @@ export async function createForwardProxyServer(deps) {
813
960
  }
814
961
  catch { }
815
962
  };
963
+ /** Whatever the relay hands over goes to the inner hop, in order. */
964
+ const forward = (chunk) => {
965
+ if (!conn.write(chunk)) {
966
+ tlsSock.pause();
967
+ conn.once('drain', () => tlsSock.resume());
968
+ }
969
+ };
816
970
  const onDecrypted = (d) => {
817
971
  decryptedBytes += d.length;
818
- if (conn) {
819
- if (!conn.write(d)) {
820
- tlsSock.pause();
821
- conn.once('drain', () => tlsSock.resume());
822
- }
972
+ relay.push(d);
973
+ if (connected || decided)
823
974
  return;
824
- }
825
- pending.push(d);
826
- if (decided)
827
- return;
828
- const buf = Buffer.concat(pending);
975
+ const buf = relay.snapshot();
829
976
  const isH2 = tlsSock.alpnProtocol === 'h2' || buf.subarray(0, 14).toString('latin1') === 'PRI * HTTP/2.0';
830
977
  if (!isH2) {
831
978
  const headEnd = buf.indexOf('\r\n\r\n');
@@ -874,9 +1021,10 @@ export async function createForwardProxyServer(deps) {
874
1021
  },
875
1022
  });
876
1023
  }
877
- for (const p of pending)
878
- conn.write(p);
879
- pending.length = 0;
1024
+ connected = true;
1025
+ relay.attach(forward, () => {
1026
+ connected = true;
1027
+ });
880
1028
  conn.on('data', (d2) => {
881
1029
  if (!tlsSock.write(d2)) {
882
1030
  conn.pause();
@@ -1383,7 +1531,8 @@ export async function createForwardProxyServer(deps) {
1383
1531
  void handlePlainProxyRequest(req, res);
1384
1532
  });
1385
1533
  proxy.on('connect', handleConnect);
1386
- proxy.on('clientError', (_err, socket) => {
1534
+ proxy.on('clientError', (err, socket) => {
1535
+ log(`proxy clientError ${describeClientError(err)}`);
1387
1536
  try {
1388
1537
  socket.end(CLIENT_ERROR_RESPONSE);
1389
1538
  }
@@ -1,8 +1,12 @@
1
1
  export type SystemProxyState = 'off' | 'on' | 'external' | 'stale' | 'unsupported';
2
+ /** Which OCR endpoint the OS proxy points at. */
3
+ export type SystemProxyOwner = 'forward' | 'clash';
2
4
  export interface SystemProxyStatus {
3
5
  platform: NodeJS.Platform;
4
6
  supported: boolean;
5
7
  state: SystemProxyState;
8
+ /** Owner recorded in the snapshot; ABSENT while OCR owns nothing. */
9
+ owner?: SystemProxyOwner;
6
10
  /** OS proxy server currently configured, when readable. */
7
11
  currentServer?: string;
8
12
  /** The server WE would set / have set. */
@@ -48,12 +52,27 @@ interface SystemProxySnapshot {
48
52
  platform: NodeJS.Platform;
49
53
  setAt: number;
50
54
  targetServer: string;
55
+ /** Endpoint this OCR surface pointed the OS at. Absent in older snapshots =
56
+ * `forward`, the only owner that existed then. */
57
+ owner: SystemProxyOwner;
51
58
  win?: WinSnapshot;
52
59
  mac?: MacServiceSnapshot[];
53
60
  gnome?: GnomeSnapshot;
54
61
  }
55
62
  /** Loopback + the rule table's literal `direct` hosts, in the platform's override syntax. */
56
63
  export declare function buildOverride(bypassList: string[], platform: NodeJS.Platform): string;
64
+ /**
65
+ * What an enable call does with the snapshot slot:
66
+ * - `snapshot` — no owner yet, so the current OS settings ARE the user's and
67
+ * must be recorded before we overwrite them;
68
+ * - `refresh` — we already point the OS at this exact endpoint; re-enabling
69
+ * must NOT re-read the snapshot slot (the OS now holds OUR value);
70
+ * - `switch` — we own a different endpoint; rewrite the OS pointer and the
71
+ * snapshot's owner/target, keeping the PRE-OCR payload untouched.
72
+ */
73
+ export type SystemProxyPlan = 'snapshot' | 'refresh' | 'switch';
74
+ export declare function planSystemProxyAction(snapshot: Pick<SystemProxySnapshot, 'targetServer'> | undefined, targetServer: string): SystemProxyPlan;
75
+ export declare function lanBypassHosts(platform: NodeJS.Platform): string[];
57
76
  /**
58
77
  * Normalize the Windows Internet Settings into the single server the OS is
59
78
  * ACTUALLY using:
@@ -64,9 +83,30 @@ export declare function buildOverride(bypassList: string[], platform: NodeJS.Pla
64
83
  * label see a real endpoint.
65
84
  */
66
85
  export declare function normalizeProxyServer(raw: string, enabled: number, pac: string): string | undefined;
86
+ /** The HTTP proxy the OS itself is using right now, with its bypass list —
87
+ * the egress a normal application on this machine would take. A PAC
88
+ * (`AutoConfigURL`) is NOT resolvable from a socket probe, so it yields
89
+ * nothing and callers fall back to a direct connection instead of guessing. */
90
+ export interface OsProxyEndpoint {
91
+ /** `host:port`, possibly with `user:pass@` — Windows stores auth that way. */
92
+ server: string;
93
+ bypass: string[];
94
+ }
95
+ export declare function readOsProxyEndpoint(): Promise<OsProxyEndpoint | undefined>;
96
+ /**
97
+ * Would the OS send `host` through its proxy, given the OS bypass list?
98
+ * Covers the syntaxes the three platforms actually store: WinINET wildcards
99
+ * (`192.168.*`, `<local>`), macOS/Linux CIDR entries and domain suffixes.
100
+ * Loopback is ALWAYS direct — a proxy in front of a loopback target would
101
+ * either loop back into this gateway or fail for no diagnosable reason.
102
+ */
103
+ export declare function osProxyBypasses(host: string, bypass: string[]): boolean;
67
104
  export declare function getSystemProxyStatus(targetPort: number, bypassList: string[]): Promise<SystemProxyStatus>;
68
- /** Point the OS proxy at the inbound forward proxy, snapshotting first. */
69
- export declare function enableSystemProxy(targetPort: number, bypassList: string[]): Promise<SystemProxyStatus>;
105
+ /**
106
+ * Point the OS proxy at one of OCR's local endpoints, snapshotting first.
107
+ * See `planSystemProxyAction` for how an existing snapshot is treated.
108
+ */
109
+ export declare function enableSystemProxy(targetPort: number, bypassList: string[], owner?: SystemProxyOwner): Promise<SystemProxyStatus>;
70
110
  /** Restore whatever the OS proxy was before OCR took ownership. */
71
111
  export declare function disableSystemProxy(targetPort: number, bypassList: string[]): Promise<SystemProxyStatus>;
72
112
  export {};