@chroxy/server 0.11.0 → 0.11.10

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 (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +69 -5
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
package/src/doctor.js CHANGED
@@ -1,18 +1,22 @@
1
1
  import { execFileSync } from 'child_process'
2
- import { existsSync, readFileSync } from 'fs'
2
+ import { existsSync, readFileSync, realpathSync } from 'fs'
3
3
  import { dirname, isAbsolute, join, resolve } from 'path'
4
4
  import { fileURLToPath } from 'url'
5
- import { homedir } from 'os'
6
5
  import { createServer } from 'net'
7
- import { validateConfig } from './config.js'
6
+ import { validateConfig, resolveBinaryProvenanceMode, isBinarySignatureGateEnabled, mergeConfig } from './config.js'
8
7
  import { resolveBinary } from './utils/resolve-binary.js'
9
8
  import { verifyBinary as defaultVerifyBinary, BINARY_STATUS, describeBinaryHealth } from './utils/verify-binary.js'
9
+ import { resolveDeclaredMinVersion } from './utils/binary-version.js'
10
+ import { isShellShim, buildBinaryProvenanceOptions } from './utils/preflight.js'
11
+ import { verifyProvenance as defaultVerifyProvenance, PROVENANCE_STATUS } from './utils/verify-provenance.js'
10
12
  import { prepareSpawn } from './utils/win-spawn.js'
13
+ import { buildClaudeLaunchEnv } from './utils/spawn-env.js'
11
14
  import { cloudflaredInstallHint } from './platform.js'
12
- import { getProvider, DEFAULT_PROVIDER } from './providers.js'
15
+ import { getProvider, DEFAULT_PROVIDER, resolveDaemonDefaultProvider } from './providers.js'
13
16
  import { registerAnthropicCompatibleProviders } from './anthropic-compatible-session.js'
14
17
  import { registerOpenAiCompatibleProviders } from './openai-compatible-session.js'
15
18
  import { parseTunnelArg } from './tunnel/index.js'
19
+ import { CLOUDFLARED_CANDIDATES } from './tunnel/cloudflare.js'
16
20
  import { TESTED_CLAUDE_TUI_CLI_VERSION } from './claude-tui/tested-cli-version.js'
17
21
  import { detectSilentMeteredDefault } from './doctor-billing.js'
18
22
  import { keychainHealth } from './keychain.js'
@@ -23,6 +27,15 @@ import {
23
27
  PROGRAMMATIC_CREDIT_ERA_START,
24
28
  } from './billing-class.js'
25
29
  import { checkDependencies } from './utils/check-dependencies.js'
30
+ import { configPath } from './config-dir.js'
31
+ import { applyStrandedAck, detectStrandedState } from './config-dir-migration.js'
32
+ import { CLAUDE_LOGIN_COMMAND } from './utils/claude-login-command.js'
33
+ import { BinaryProvenanceLedger } from './binary-provenance-trust.js'
34
+ import { createLogger } from './logger.js'
35
+ import { countUserLevelChroxyHooks, userSettingsPath } from './permission-hook.js'
36
+ import { defaultClaudeConfigDir } from './utils/claude-config-dir.js'
37
+
38
+ const log = createLogger('doctor')
26
39
 
27
40
  // Resolve the server package root (the directory containing package.json
28
41
  // and node_modules) so dependency checks work regardless of where the
@@ -38,7 +51,9 @@ const SERVER_PKG_DIR = dirname(dirname(__filename))
38
51
  // tests/_setup.mjs redirecting CHROXY_CONFIG_DIR to a tmp dir — which would let
39
52
  // the named-tunnel routability probe (#5328) fire a live network request from
40
53
  // a maintainer's real config during the suite.
41
- const CONFIG_FILE = join(process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy'), 'config.json')
54
+ function configFile() {
55
+ return configPath('config.json')
56
+ }
42
57
 
43
58
  /**
44
59
  * Parse the leading `major.minor.patch` semver out of an arbitrary version
@@ -112,17 +127,54 @@ export function isBundledOrSupervisedContext() {
112
127
  /**
113
128
  * Resolve the list of providers to preflight check.
114
129
  *
130
+ * #8151 review round 2 (Critical 2) — the S6 version of this function (a
131
+ * hand-written copy of config.js's CLI > ENV > file > default precedence)
132
+ * was itself a regression outside Docker. It read `CHROXY_PROVIDERS`
133
+ * (plural) as a comma-separated list of PROVIDER NAMES — but
134
+ * `CHROXY_PROVIDERS` is a REAL, documented env var for `config.providers`
135
+ * (the anthropic-compatible/openai-compatible endpoint registrations: array
136
+ * OR object, see config.js's `CONFIG_SCHEMA` and `parseEnvValue`), not a
137
+ * provider roster. A daemon that set `CHROXY_PROVIDERS` to its own
138
+ * documented JSON-object form got that comma-split into garbage tokens here
139
+ * (3 bogus "names", `claude-sdk` never checked) — and even in the simple
140
+ * case, `CHROXY_PROVIDER=claude-sdk` with an unrelated `CHROXY_PROVIDERS`
141
+ * set made doctor check the WRONG provider while the daemon actually ran
142
+ * claude-sdk, because this function answered two different questions
143
+ * ("what provider does the daemon run" vs. "what is config.providers") with
144
+ * the same hand-rolled env read.
145
+ *
146
+ * Fixed by dropping this function's own env/file reads entirely and routing
147
+ * through the SAME shared loader `chroxy start`/`chroxy resume` use:
148
+ * `mergeConfig` (config.js) resolves CLI > ENV > file > default — including
149
+ * the `legacyCli` → `claude-cli` mapping — via its own
150
+ * `parseEnvValue`/`CONFIG_SCHEMA`-aware coercion (so `CHROXY_PROVIDERS`' object
151
+ * form is parsed as JSON, never comma-split, and is correctly ignored here
152
+ * since it feeds `merged.providers`, a field `resolveDaemonDefaultProvider`
153
+ * never reads). `resolveDaemonDefaultProvider` (providers.js) then reads
154
+ * `merged.provider` — the one function both doctor and the real daemon
155
+ * startup path share, so this can't drift from `chroxy start`'s own
156
+ * resolution again without touching shared code both paths run.
157
+ *
115
158
  * Precedence:
116
- * 1. Explicit `providers` option (array of provider names)
117
- * 2. `provider` field from loaded config file
118
- * 3. DEFAULT_PROVIDER (see providers.js)
159
+ * 1. Explicit `providers` option (array of provider names — doctor's own
160
+ * `--provider a,b` flag; unrelated to config.js's `providers` key)
161
+ * 2. Everything `mergeConfig` resolves for `provider` (ENV > file >
162
+ * default) — exactly one name, the one `chroxy start` would run.
119
163
  *
120
164
  * Returns an array of provider name strings.
165
+ *
166
+ * @param {object} args
167
+ * @param {string[]} [args.providers] - doctor's own explicit `--provider a,b`
168
+ * flag; still the highest-precedence override when present.
169
+ * @param {object|null} [args.parsedConfig] - the raw parsed config.json (or
170
+ * null/absent), fed to mergeConfig as the file tier.
121
171
  */
122
- function resolveProviders({ providers, configProvider }) {
172
+ function resolveProviders({ providers, parsedConfig }) {
123
173
  if (Array.isArray(providers) && providers.length > 0) return providers
124
- if (typeof configProvider === 'string' && configProvider.length > 0) return [configProvider]
125
- return [DEFAULT_PROVIDER]
174
+ const merged = mergeConfig({
175
+ fileConfig: parsedConfig && typeof parsedConfig === 'object' ? parsedConfig : {},
176
+ })
177
+ return [resolveDaemonDefaultProvider(merged)]
126
178
  }
127
179
 
128
180
  /**
@@ -141,6 +193,97 @@ function claudeTuiBinaryCandidates() {
141
193
  }
142
194
  }
143
195
 
196
+ /**
197
+ * Build a doctor `fail` check for a binary the opt-in provenance gate refused
198
+ * (#8041) — a `block`-mode hash mismatch or a failed signature-gate
199
+ * assessment. Doctor checks report status objects rather than throwing, so
200
+ * this is the doctor-shaped equivalent of `ProviderBinaryProvenanceError` /
201
+ * `TunnelBinaryProvenanceError`: same message shape (path, verdict status,
202
+ * message, remediation), returned instead of thrown. Always a hard `fail`
203
+ * regardless of whether the binary itself is `required` — a provenance
204
+ * refusal is a security decision (the daemon never downgrades it), not an
205
+ * advisory floor like a missing optional binary.
206
+ *
207
+ * @param {string} name - the doctor check's display name
208
+ * @param {string} resolved - the resolved absolute path that was refused
209
+ * @param {{ status: string, message?: string, remediation?: string }} verdict
210
+ * - the blocked verdict returned by `verifyProvenance`
211
+ * @returns {{ name: string, status: 'fail', message: string }}
212
+ */
213
+ function provenanceBlockedCheck(name, resolved, verdict) {
214
+ return {
215
+ name,
216
+ status: 'fail',
217
+ message: `${resolved} — provenance ${verdict.status}: ${verdict.message || 'failed provenance verification'}`
218
+ + `${verdict.remediation ? ` — ${verdict.remediation}` : ''}`,
219
+ }
220
+ }
221
+
222
+ /**
223
+ * #8223: the resolve -> health-check -> provenance-gate prelude shared by every
224
+ * doctor probe that EXECS `claude` (the claude-tui version pin and the login
225
+ * check), lifted out of `checkClaudeTuiCliVersion` unchanged so the two cannot
226
+ * drift on how the binary is vetted before it runs. Returns the path to exec and
227
+ * any pending warn-mode provenance advisory, or null when `claude` cannot be run
228
+ * (missing / quarantined / provenance-blocked) — the provider binary check
229
+ * already reports those, so a probe adds no second row for them.
230
+ *
231
+ * @param {object} deps - same shape as `checkClaudeTuiCliVersion`'s
232
+ * @param {string} probeLabel - names the probe in the provenance warn log
233
+ * @returns {{ execPath: string, provenanceAdvisory: string|null } | null}
234
+ */
235
+ function resolveClaudeProbeBinary({ candidates, resolveBinary: resolveClaudeBinary, verify, provenance, verifyProvenance }, probeLabel) {
236
+ const resolved = resolveClaudeBinary('claude', candidates)
237
+ // #8074 review C2: `verifyProvenance` must never run on an unresolved/
238
+ // not-found path — a bare, unresolved name (`resolveBinary` returns the
239
+ // bare name itself when nothing matched) would get hashed relative to the
240
+ // CURRENT WORKING DIRECTORY, mislabeling a missing `claude` as a
241
+ // provenance failure. So the #6708 health check gates the probe too, but —
242
+ // "at minimum when a gate is on" — ONLY when `provenance` is supplied: this
243
+ // function had NO health check at all before #8041 (unlike checkBinary),
244
+ // and every existing caller with the gate off relies on `exec` alone
245
+ // deciding pass/fail/missing, exactly as it always has. `null` here (not a
246
+ // fail row) matches this function's own documented contract: the provider
247
+ // binary check already surfaces a missing/quarantined claude.
248
+ let execPath = resolved
249
+ let provenanceAdvisory = null
250
+ if (provenance) {
251
+ const health = verify(resolved)
252
+ if (!health.ok) {
253
+ return null
254
+ }
255
+ execPath = health.path
256
+ // #8041: route the probe through the opt-in provenance gate — a
257
+ // `block`-mode hash mismatch or failed signature gate refuses the probe
258
+ // outright, and the binary at `execPath` is NEVER exec'd.
259
+ const verdict = verifyProvenance({
260
+ resolvedPath: health.path,
261
+ mode: provenance.mode,
262
+ signatureGate: provenance.signatureGate === true,
263
+ ledger: provenance.ledger || null,
264
+ })
265
+ if (verdict.blocked) {
266
+ // #8074 review S3: return null, not a second `fail` row — the SAME
267
+ // `claude` binary's own provider-preflight row (checkProvider, via
268
+ // checkBinary against the identical provenance options) already
269
+ // reports this exact refusal. Two rows for one blocked binary is
270
+ // confusing, not informative, and this function's docblock already
271
+ // promises "null when claude can't be run".
272
+ return null
273
+ }
274
+ if (
275
+ verdict.status === PROVENANCE_STATUS.HASH_MISMATCH
276
+ || verdict.status === PROVENANCE_STATUS.SIGNATURE_INVALID
277
+ || verdict.status === PROVENANCE_STATUS.UNREADABLE
278
+ ) {
279
+ log.warn(`Binary "claude" (${probeLabel} probe) provenance ${verdict.status}: ${verdict.message || ''} (allowed — mode=${provenance.mode})`)
280
+ provenanceAdvisory = `provenance ${verdict.status}: ${verdict.message || 'unverifiable'}`
281
+ + `${verdict.remediation ? ` — ${verdict.remediation}` : ''} (allowed — mode=${provenance.mode})`
282
+ }
283
+ }
284
+ return { execPath, provenanceAdvisory }
285
+ }
286
+
144
287
  /**
145
288
  * audit P1-3 / #5821: compare the installed claude CLI version against the
146
289
  * version chroxy's claude-tui form-driving was validated against
@@ -154,6 +297,14 @@ function claudeTuiBinaryCandidates() {
154
297
  * @param {(bin: string, args: string[]) => string} [deps.exec]
155
298
  * @param {string} [deps.tested]
156
299
  * @param {string[]} [deps.candidates] - fallback absolute paths for resolveBinary
300
+ * @param {(name: string, candidates: string[]) => string} [deps.resolveBinary] -
301
+ * injectable resolver (test seam; defaults to the real PATH/candidate resolve)
302
+ * @param {Function} [deps.verify] - binary health checker (injected in tests;
303
+ * #8074 review C2 — defaults to the real #6708 `verifyBinary`)
304
+ * @param {{ mode: string, signatureGate: boolean, ledger: object|null }|null} [deps.provenance]
305
+ * - #8041: opt-in provenance options bag (`buildBinaryProvenanceOptions`); null
306
+ * (the default) skips the gate entirely, matching pre-#8041 behaviour.
307
+ * @param {Function} [deps.verifyProvenance] - provenance checker (injected in tests)
157
308
  * @returns {{ name: string, status: 'pass'|'warn', message: string } | null}
158
309
  */
159
310
  export function checkClaudeTuiCliVersion(deps = {}) {
@@ -164,7 +315,7 @@ export function checkClaudeTuiCliVersion(deps = {}) {
164
315
  // win32-routing test exercises this default path directly.
165
316
  exec = (bin, args) => {
166
317
  const s = prepareSpawn(bin, args)
167
- return execFileSync(s.command, s.args, { encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], ...s.options })
318
+ return execFileSync(s.command, s.args, { encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], env: buildClaudeLaunchEnv(), ...s.options })
168
319
  },
169
320
  tested = TESTED_CLAUDE_TUI_CLI_VERSION,
170
321
  // #5871: resolve against the SAME candidate paths the claude-tui provider
@@ -173,10 +324,21 @@ export function checkClaudeTuiCliVersion(deps = {}) {
173
324
  // claude via its candidate list — exactly the bundled context where a
174
325
  // silent mis-drive would otherwise go unnoticed.
175
326
  candidates = claudeTuiBinaryCandidates(),
327
+ resolveBinary: resolveClaudeBinary = resolveBinary,
328
+ verify = defaultVerifyBinary,
329
+ provenance = null,
330
+ verifyProvenance = defaultVerifyProvenance,
176
331
  } = deps
332
+ const probe = resolveClaudeProbeBinary({ candidates, resolveBinary: resolveClaudeBinary, verify, provenance, verifyProvenance }, 'claude-tui driving')
333
+ if (!probe) return null
334
+ const { execPath, provenanceAdvisory } = probe
335
+ // #8074 round-2 review: EVERY row this probe returns carries a pending
336
+ // warn-mode advisory, not only the clean-baseline one — an earlier warn
337
+ // (unparseable version, baseline drift) must not swallow it.
338
+ const withAdvisory = (msg) => (provenanceAdvisory ? `${msg} — ${provenanceAdvisory}` : msg)
177
339
  let output
178
340
  try {
179
- output = exec(resolveBinary('claude', candidates), ['--version'])
341
+ output = exec(execPath, ['--version'])
180
342
  } catch {
181
343
  return null // claude missing/hung — the provider binary check surfaces that
182
344
  }
@@ -184,17 +346,105 @@ export function checkClaudeTuiCliVersion(deps = {}) {
184
346
  const found = parseLeadingSemver(output)
185
347
  const testedSemver = parseLeadingSemver(tested)
186
348
  if (found === null) {
187
- return { name: NAME, status: 'warn', message: `Could not parse 'claude --version'; TUI form-driving is validated against ${tested}` }
349
+ return { name: NAME, status: 'warn', message: withAdvisory(`Could not parse 'claude --version'; TUI form-driving is validated against ${tested}`) }
188
350
  }
189
351
  const foundStr = `${found[0]}.${found[1]}.${found[2]}`
190
352
  if (testedSemver && found[0] === testedSemver[0] && found[1] === testedSemver[1]) {
353
+ // #8074 review S1: a pending provenance advisory (warn mode) must not be
354
+ // silently absorbed into an otherwise-clean `pass` row.
355
+ if (provenanceAdvisory) {
356
+ return { name: NAME, status: 'warn', message: withAdvisory(`claude ${foundStr} matches the tested TUI-driving baseline (${tested})`) }
357
+ }
191
358
  return { name: NAME, status: 'pass', message: `claude ${foundStr} matches the tested TUI-driving baseline (${tested})` }
192
359
  }
193
360
  return {
194
361
  name: NAME,
195
362
  status: 'warn',
196
- message: `claude ${foundStr} differs from the tested TUI-driving baseline (${tested}) — chroxy drives the TUI by screen-scraping pinned keystrokes, so a CLI UI change can mis-drive AskUserQuestion forms silently. If question prompts misbehave, report it; re-validation will bump the baseline.`,
363
+ message: withAdvisory(`claude ${foundStr} differs from the tested TUI-driving baseline (${tested}) — chroxy drives the TUI by screen-scraping pinned keystrokes, so a CLI UI change can mis-drive AskUserQuestion forms silently. If question prompts misbehave, report it; re-validation will bump the baseline.`),
364
+ }
365
+ }
366
+
367
+ const CLAUDE_LOGIN_UNREADABLE_MESSAGE = `Could not read the login state from \`claude auth status --json\` — if a claude-tui session reports AUTH_REQUIRED, run \`${CLAUDE_LOGIN_COMMAND}\` on this host.`
368
+
369
+ /**
370
+ * #8223: report whether the `claude` on this host is logged in, from
371
+ * `claude auth status --json` — the same question claude-tui asks before it
372
+ * spawns a PTY. A logged-out host is otherwise discovered only when a session
373
+ * fails to start. Never `fail`s: a doctor failure blocks `chroxy start`, and
374
+ * "not logged in" is a state the operator fixes in a terminal, not a broken
375
+ * install.
376
+ *
377
+ * Rows: `pass` "Logged in (<authMethod>[, <subscriptionType>])" for an explicit
378
+ * `loggedIn: true`; `warn` for an explicit `loggedIn: false`, and `warn` when
379
+ * the status cannot be read (timeout, unparseable output, no `loggedIn` field).
380
+ * Returns null — no row — when `claude` cannot be run at all (missing,
381
+ * quarantined, provenance-blocked): the provider binary row already says so.
382
+ *
383
+ * `claude auth status` exits 1 when logged out but still prints its JSON, so a
384
+ * non-zero exit that carries stdout is read, not treated as unreadable. The
385
+ * probe runs with ANTHROPIC_API_KEY removed from its env the way claude-tui
386
+ * removes it from the PTY's, so it reports the subscription login rather than
387
+ * an API key that claude-tui would never use. An EXPIRED oauth token still
388
+ * reports `loggedIn: true`; only a live session's PTY scan sees expiry.
389
+ *
390
+ * @param {object} [deps] - same seams as `checkClaudeTuiCliVersion`, plus:
391
+ * @param {(bin: string, args: string[], opts: { env: object }) => string} [deps.exec]
392
+ * returns stdout; may throw an error carrying `status` + `stdout` (non-zero exit)
393
+ * @param {object} [deps.env] - environment the probe is derived from (default process.env)
394
+ * @returns {{ name: string, status: 'pass'|'warn', message: string } | null}
395
+ */
396
+ export function checkClaudeLogin(deps = {}) {
397
+ const {
398
+ // Same prepareSpawn routing as the version probe's default (#6484). The args
399
+ // are always the literal ['auth', 'status', '--json'] from the one call below.
400
+ exec = (bin, args, { env }) => {
401
+ const s = prepareSpawn(bin, args)
402
+ return execFileSync(s.command, s.args, { encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], env, ...s.options })
403
+ },
404
+ candidates = claudeTuiBinaryCandidates(),
405
+ resolveBinary: resolveClaudeBinary = resolveBinary,
406
+ verify = defaultVerifyBinary,
407
+ provenance = null,
408
+ verifyProvenance = defaultVerifyProvenance,
409
+ env = process.env,
410
+ } = deps
411
+ const probe = resolveClaudeProbeBinary({ candidates, resolveBinary: resolveClaudeBinary, verify, provenance, verifyProvenance }, 'claude login')
412
+ if (!probe) return null
413
+
414
+ const NAME = 'Claude login'
415
+ const probeEnv = buildClaudeLaunchEnv(env)
416
+ delete probeEnv.ANTHROPIC_API_KEY
417
+
418
+ let stdout
419
+ try {
420
+ stdout = exec(probe.execPath, ['auth', 'status', '--json'], { env: probeEnv })
421
+ } catch (err) {
422
+ if (err?.code === 'ENOENT') return null // claude missing — the binary row says so
423
+ if (typeof err?.status === 'number' && typeof err.stdout === 'string') {
424
+ stdout = err.stdout // exit 1 = logged out, JSON still on stdout
425
+ } else {
426
+ return { name: NAME, status: 'warn', message: CLAUDE_LOGIN_UNREADABLE_MESSAGE }
427
+ }
428
+ }
429
+
430
+ let status
431
+ try {
432
+ status = JSON.parse(String(stdout || ''))
433
+ } catch {
434
+ return { name: NAME, status: 'warn', message: CLAUDE_LOGIN_UNREADABLE_MESSAGE }
197
435
  }
436
+ if (status?.loggedIn === true) {
437
+ const how = [status.authMethod, status.subscriptionType].filter((v) => typeof v === 'string' && v.length > 0)
438
+ return { name: NAME, status: 'pass', message: how.length > 0 ? `Logged in (${how.join(', ')})` : 'Logged in' }
439
+ }
440
+ if (status?.loggedIn === false) {
441
+ return {
442
+ name: NAME,
443
+ status: 'warn',
444
+ message: `Not logged in — run \`${CLAUDE_LOGIN_COMMAND}\` on this host. claude-tui needs it; claude-sdk needs it unless ANTHROPIC_API_KEY is set.`,
445
+ }
446
+ }
447
+ return { name: NAME, status: 'warn', message: CLAUDE_LOGIN_UNREADABLE_MESSAGE }
198
448
  }
199
449
 
200
450
  /**
@@ -274,6 +524,64 @@ export async function checkTunnelRoutability(deps = {}) {
274
524
  }
275
525
  }
276
526
 
527
+ /**
528
+ * #8263: warn about a chroxy permission-hook entry in the USER-LEVEL Claude
529
+ * settings. claude-tui children load that file as well as their per-session
530
+ * settings, so a stranded entry used to double every permission prompt. The
531
+ * hook script now stays inert for it inside a TUI child, so this is a hygiene
532
+ * warning, not a live fault. Read-only: the daemon does not sweep or clean the
533
+ * user-level file, because the entry may belong to a live claude-cli session of
534
+ * another daemon (#8350) — the operator removes it.
535
+ *
536
+ * A file that exists but cannot be read or parsed is reported too: "could not
537
+ * look" must not read the same as "nothing there" (a missing file is not an
538
+ * error, and still yields null).
539
+ *
540
+ * @param {{settingsPath?: string}} [deps]
541
+ * @returns {{ name: string, status: 'warn', message: string } | null} null when none found
542
+ */
543
+ export function checkUserLevelChroxyHook({ settingsPath } = {}) {
544
+ const { found, settingsPath: target, error } = countUserLevelChroxyHooks({ settingsPath })
545
+ const NAME = 'User-level permission hook'
546
+ if (error) {
547
+ return {
548
+ name: NAME,
549
+ status: 'warn',
550
+ message: `could not read user-level settings: ${error} (${target}) — a chroxy permission-hook entry there, if any, was not checked`,
551
+ }
552
+ }
553
+ if (found === 0) return null
554
+ return {
555
+ name: NAME,
556
+ status: 'warn',
557
+ message: `${found} chroxy permission-hook entr${found === 1 ? 'y' : 'ies'} in ${target} — fix: remove the hooks.PreToolUse entry that runs permission-hook.sh from that file by hand (only when no claude-cli session is running; it is ignored inside claude-tui sessions)`,
558
+ }
559
+ }
560
+
561
+ /**
562
+ * #8974: when a CLAUDE_CONFIG_DIR override is active, a chroxy permission-hook
563
+ * entry left in the DEFAULT `~/.claude/settings.json` (registered before the
564
+ * override was set, or by another daemon) is stranded: claude no longer loads
565
+ * that file for this profile. Report only; it is never removed here because
566
+ * another daemon may own it.
567
+ *
568
+ * @param {{activePath?: string, defaultPath?: string}} [deps]
569
+ * @returns {{ name: string, status: 'warn', message: string } | null}
570
+ */
571
+ export function checkStrandedDefaultHook({ activePath, defaultPath } = {}) {
572
+ const active = activePath ?? userSettingsPath()
573
+ const fallback = defaultPath ?? join(defaultClaudeConfigDir(), 'settings.json')
574
+ const canon = (p) => { try { return realpathSync(p) } catch { return resolve(p) } }
575
+ if (canon(active) === canon(fallback)) return null
576
+ const { found, error } = countUserLevelChroxyHooks({ settingsPath: fallback })
577
+ if (error || found === 0) return null
578
+ return {
579
+ name: 'Stranded permission hook',
580
+ status: 'warn',
581
+ message: `${found} chroxy permission-hook entr${found === 1 ? 'y' : 'ies'} in ${fallback}, which is not the active settings file (${active}) for this daemon's claude — fix: remove the hooks.PreToolUse entry that runs permission-hook.sh from that file by hand (only when no claude-cli session of another daemon is using it)`,
582
+ }
583
+ }
584
+
277
585
  /**
278
586
  * Run all preflight dependency checks and return results.
279
587
  *
@@ -290,9 +598,76 @@ export async function checkTunnelRoutability(deps = {}) {
290
598
  * Dependencies check. Defaults to the server package root. Relative paths are resolved to
291
599
  * absolute at call time so the check is fully decoupled from process.cwd(). Exposed so
292
600
  * tests can point the check at a temp directory without mutating process.cwd().
601
+ * @param {string|null} [options.tunnelMode] - #8116: override the named-tunnel mode used by
602
+ * the routability probe (step 5.6, #5328 WP-5.6). `undefined` (the default) reads it from
603
+ * doctor's own default config file, unchanged — `chroxy doctor` never passes this. Supplied
604
+ * (including `null`, meaning "no tunnel") it REPLACES the file-derived value entirely —
605
+ * `chroxy start` passes the MERGED config's own resolved tunnel mode (same seam shape as
606
+ * `binaryProvenanceMode`, #8074).
607
+ * @param {string|null} [options.tunnelHostname] - Same override shape as `tunnelMode`, for the
608
+ * named-tunnel hostname.
293
609
  * @returns {{ checks: Array<{ name: string, status: 'pass'|'warn'|'fail', message: string, provider?: string }>, passed: boolean, providers: string[] }}
294
610
  */
295
- export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgDir = SERVER_PKG_DIR, now = Date.now(), tunnelProbe } = {}) {
611
+ export async function runDoctorChecks({
612
+ port, portProblem, configFilePath, providers, verbose: _verbose, pkgDir = SERVER_PKG_DIR, now = Date.now(),
613
+ tunnelProbe, detectStranded = detectStrandedState, platform = process.platform,
614
+ // #8116 — same seam shape as #8074's binaryProvenanceMode / #8115's
615
+ // providers: `undefined` (the default) means "read the named-tunnel
616
+ // coordinates for the routability probe (step 5.6 below) from doctor's own
617
+ // default config file", exactly as before — `chroxy doctor` (doctor-cmd.js)
618
+ // never passes these and is therefore unaffected. Supplied (even `null`,
619
+ // meaning "no tunnel"), they REPLACE the file-derived value entirely —
620
+ // `chroxy start` (server-cmd.js) passes both from the MERGED config it
621
+ // already resolved (-c <path> / --tunnel / --tunnel-hostname /
622
+ // CHROXY_TUNNEL* env), so the probe always targets the tunnel the daemon
623
+ // it's about to start actually uses, not whichever tunnel the default file
624
+ // happens to name.
625
+ tunnelMode: tunnelModeOverride,
626
+ tunnelHostname: tunnelHostnameOverride,
627
+ // #8041 — test seams for the opt-in binary-provenance gate applied to the
628
+ // cloudflared / provider-binary / claude-tui version probes below. All
629
+ // default to the real production resolution so `chroxy doctor` / `chroxy
630
+ // start` are unaffected:
631
+ // - `binaryProvenanceMode` / `binarySignatureGate` override the config +
632
+ // env resolution (`resolveBinaryProvenanceMode` / `isBinarySignatureGateEnabled`)
633
+ // entirely when supplied — a plain function-argument seam so a test can
634
+ // set the gate's mode WITHOUT resolving it from a real config file or
635
+ // `process.env`, exercising the gate logic directly. (#8074 review N4:
636
+ // this is not about test concurrency — this test runner's default is
637
+ // to run sibling `it()`s within one file SEQUENTIALLY; the seam exists
638
+ // so tests don't need a real config file at all, not to avoid a race.)
639
+ // - `binaryProvenanceLedger` overrides the lazily-constructed default-path
640
+ // ledger (undefined ⇒ construct one only when the gate resolves on,
641
+ // same as `resolveVerifiedClaudeBinary` in cli/session-cmd.js).
642
+ verifyProvenance = defaultVerifyProvenance,
643
+ binaryProvenanceLedger: binaryProvenanceLedgerOverride,
644
+ binaryProvenanceMode: binaryProvenanceModeOverride,
645
+ binarySignatureGate: binarySignatureGateOverride,
646
+ // #8074 review C3(c): test-only resolver override for the claude-tui
647
+ // version-pin probe specifically (see the call site below) — undefined in
648
+ // production, so `checkClaudeTuiCliVersion` uses its own real resolver.
649
+ claudeTuiResolveBinary,
650
+ // #8223 test seam: overrides for the claude login probe (step 5.7) — `exec`,
651
+ // `resolveBinary`, `verify`, `env`. Undefined in production, which uses the real
652
+ // ones; without it a test would resolve and exec a REAL `claude` on the host.
653
+ claudeLoginDeps = {},
654
+ // #8041 test seam: cloudflared's fallback candidate paths, so a test can
655
+ // point resolution at a fixture without depending on whether a REAL
656
+ // cloudflared happens to be installed at one of the fixed production
657
+ // candidates on the machine running the suite. Defaults to
658
+ // `CLOUDFLARED_CANDIDATES`, imported from `tunnel/cloudflare.js` (#8074
659
+ // review S2) rather than a second hand-kept copy — that module's own
660
+ // `_verifyCloudflaredProvenance` gates the daemon's tunnel spawn against
661
+ // this EXACT list, so doctor's pre-flight check and the daemon's real gate
662
+ // can never silently diverge on which paths count as "cloudflared".
663
+ cloudflaredCandidates = CLOUDFLARED_CANDIDATES,
664
+ // #8263: opt-in (`chroxy doctor` passes true) so `chroxy start`'s preflight and
665
+ // the unit tests never read the operator's real ~/.claude/settings.json.
666
+ // `userHookSettingsPath` is the test seam for that read.
667
+ checkUserLevelHook = false,
668
+ userHookSettingsPath,
669
+ strandedHookSettingsPath,
670
+ } = {}) {
296
671
  const checks = []
297
672
 
298
673
  // 1. Node.js version
@@ -306,28 +681,31 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
306
681
  checks.push({ name: 'Node.js', status: 'fail', message: `v${nodeVersion} — Node 22 required` })
307
682
  }
308
683
 
309
- // 2. cloudflared
310
- checks.push(checkBinary('cloudflared', ['--version'], {
311
- parseVersion: (out) => out.trim().split('\n')[0],
312
- required: true,
313
- candidates: [
314
- '/opt/homebrew/bin/cloudflared',
315
- '/usr/local/bin/cloudflared',
316
- join(homedir(), '.local/bin/cloudflared'),
317
- ],
318
- installHint: cloudflaredInstallHint(),
319
- }))
320
-
321
- // 3. Load config (once) — used for both the Config check and provider resolution.
322
- let configProvider = null
684
+ // 2. Load config (once) — used for the Config check, provider resolution,
685
+ // AND (#8041) the binary-provenance gate below. Moved ahead of the
686
+ // cloudflared check (previously step 2) because that check now needs the
687
+ // gate's resolved mode/signatureGate before it can run.
323
688
  let configCheck = null
324
689
  // #5328 (WP-5.6): named-tunnel coordinates for the routability probe (step 5.6).
325
690
  let tunnelMode = null
326
691
  let tunnelHostname = null
327
- if (existsSync(CONFIG_FILE)) {
692
+ // #8041: the raw parsed config object, kept around (in addition to the
693
+ // narrower locals above) so resolveBinaryProvenanceMode /
694
+ // isBinarySignatureGateEnabled can read config.binaryProvenance the same
695
+ // way chroxy start / chroxy resume do. Stays null when the file is
696
+ // missing or fails to parse — both resolvers treat a missing
697
+ // `binaryProvenance` key as gate-off, matching every other check in this
698
+ // function's existing "a corrupt config degrades gracefully" behaviour
699
+ // rather than hard-failing doctor itself.
700
+ // #8233: `-c <path>` (configFilePath) replaces the default config.json for every
701
+ // check below that reads config.
702
+ const explicitConfig = typeof configFilePath === 'string' && configFilePath !== ''
703
+ const cfgFile = explicitConfig ? configFilePath : configFile()
704
+ let parsedConfig = null
705
+ if (existsSync(cfgFile)) {
328
706
  try {
329
- const config = JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'))
330
- if (typeof config.provider === 'string') configProvider = config.provider
707
+ const config = JSON.parse(readFileSync(cfgFile, 'utf-8'))
708
+ parsedConfig = config
331
709
  // Normalize the tunnel mode through parseTunnelArg so aliases resolve —
332
710
  // e.g. `cloudflare:named` (a documented --tunnel form persisted verbatim)
333
711
  // maps to mode 'named' and isn't silently skipped by the routability
@@ -353,34 +731,162 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
353
731
  registerOpenAiCompatibleProviders(config)
354
732
  const { valid, warnings } = validateConfig(config)
355
733
  if (valid) {
356
- configCheck = { name: 'Config', status: 'pass', message: CONFIG_FILE }
734
+ configCheck = { name: 'Config', status: 'pass', message: cfgFile }
357
735
  } else {
358
- configCheck = { name: 'Config', status: 'warn', message: `${CONFIG_FILE} — ${warnings.join('; ')}` }
736
+ configCheck = { name: 'Config', status: 'warn', message: `${cfgFile} — ${warnings.join('; ')}` }
359
737
  }
360
738
  } catch (err) {
361
739
  if (err instanceof SyntaxError) {
362
- configCheck = { name: 'Config', status: 'fail', message: `${CONFIG_FILE} — invalid JSON: ${err.message}` }
740
+ configCheck = { name: 'Config', status: 'fail', message: `${cfgFile} — invalid JSON: ${err.message}` }
363
741
  } else {
364
- configCheck = { name: 'Config', status: 'fail', message: `${CONFIG_FILE} — ${err.message}` }
742
+ configCheck = { name: 'Config', status: 'fail', message: `${cfgFile} — ${err.message}` }
365
743
  }
366
744
  }
745
+ } else if (explicitConfig) {
746
+ // `-c <path>` named a file that does not exist: fail naming THAT path, as `start` does.
747
+ configCheck = { name: 'Config', status: 'fail', message: `${cfgFile} — config file not found` }
367
748
  } else {
368
749
  configCheck = { name: 'Config', status: 'warn', message: `Not found — run 'chroxy init' to create` }
369
750
  }
370
751
 
371
- // 4. Provider-specific checks. Each configured provider contributes its
752
+ // #8116: an explicit override REPLACES the file-derived coordinates above,
753
+ // independently for mode and hostname (mirrors binaryProvenanceMode /
754
+ // binarySignatureGate's independent-override shape below) — `undefined`
755
+ // leaves the file-derived value in place, so `chroxy doctor` (which never
756
+ // supplies either) is byte-identical to before this issue.
757
+ if (tunnelModeOverride !== undefined) tunnelMode = tunnelModeOverride
758
+ if (tunnelHostnameOverride !== undefined) tunnelHostname = tunnelHostnameOverride
759
+
760
+ // 3. #8041 — resolve the opt-in binary-provenance gate ONCE, from the SAME
761
+ // config + env precedence `chroxy start` / `chroxy resume` use
762
+ // (resolveBinaryProvenanceMode / isBinarySignatureGateEnabled — env vars
763
+ // CHROXY_BINARY_PROVENANCE / CHROXY_BINARY_SIGNATURE_GATE outrank the
764
+ // config file), normalized through the SAME `buildBinaryProvenanceOptions`
765
+ // helper #8065 added (utils/preflight.js) so "the gate is off" is defined
766
+ // in exactly one place, not a second copy for doctor. The resolved bag is
767
+ // shared by the cloudflared check below, every provider's binary check
768
+ // (step 5), and the claude-tui version-pin probe (step 5.6) — one gate
769
+ // resolution, one ledger instance, not three.
770
+ //
771
+ // The ledger is opened lazily, and only when a gate is actually ON
772
+ // (#8065 review nitpick 3's rationale, reapplied here): a default
773
+ // `chroxy doctor` / `chroxy start` run with gates off must never touch —
774
+ // or warn about — the real `binary-trust.json`, since `buildBinaryProvenanceOptions`
775
+ // is about to discard it anyway (returns null when the gate is off).
776
+ const provenanceMode = binaryProvenanceModeOverride !== undefined
777
+ ? binaryProvenanceModeOverride
778
+ : resolveBinaryProvenanceMode(parsedConfig || {})
779
+ const provenanceSignatureGate = binarySignatureGateOverride !== undefined
780
+ ? binarySignatureGateOverride
781
+ : isBinarySignatureGateEnabled(parsedConfig || {})
782
+ const provenanceGateOn = provenanceMode !== 'off' || provenanceSignatureGate === true
783
+ const binaryProvenanceLedger = binaryProvenanceLedgerOverride !== undefined
784
+ ? binaryProvenanceLedgerOverride
785
+ : (provenanceGateOn ? new BinaryProvenanceLedger() : null)
786
+ const provenanceOptions = buildBinaryProvenanceOptions({
787
+ mode: provenanceMode,
788
+ signatureGate: provenanceSignatureGate,
789
+ ledger: binaryProvenanceLedger,
790
+ })
791
+
792
+ // 4. cloudflared. #8041: gated through the SAME opt-in provenance options
793
+ // the daemon's tunnel adapter uses (`_verifyCloudflaredProvenance`,
794
+ // tunnel/cloudflare.js) — a block-mode hash mismatch or failed signature
795
+ // gate now reports `fail` here WITHOUT ever exec'ing `cloudflared --version`.
796
+ checks.push(checkBinary('cloudflared', ['--version'], {
797
+ parseVersion: (out) => out.trim().split('\n')[0],
798
+ required: true,
799
+ candidates: cloudflaredCandidates,
800
+ installHint: cloudflaredInstallHint(),
801
+ provenance: provenanceOptions,
802
+ verifyProvenance,
803
+ }))
804
+
805
+ // #7240 — state stranded at ~/.chroxy by a CHROXY_CONFIG_DIR relocation.
806
+ // Computed before the Config check is pushed so the "Not found" branch above
807
+ // can be corrected: recommending `chroxy init` when the real cause is an
808
+ // unmoved config.json mints a fresh token and forces every device to re-pair,
809
+ // which is strictly worse than the problem it purports to fix.
810
+ let strandedCheck = null
811
+ try {
812
+ const raw = detectStranded()
813
+ // #7244 — entries the operator acknowledged with `chroxy config-dir ack`
814
+ // are dropped here; one that appeared afterwards is not, and still warns.
815
+ // The same helper the startup warning uses, so the two cannot disagree.
816
+ const stranded = applyStrandedAck(raw)
817
+ if (stranded.unreadable) {
818
+ strandedCheck = {
819
+ name: 'Config/state root',
820
+ status: 'warn',
821
+ message: `${stranded.target} — could not check ${stranded.source} for stranded state: ${stranded.unreadable}`,
822
+ }
823
+ } else if (stranded.stranded.length > 0) {
824
+ const sharp = stranded.highConsequence.length > 0
825
+ ? ` (including ${stranded.highConsequence.join(', ')})`
826
+ : ''
827
+ // Bounded: a relocated root can strand an arbitrary number of entries and
828
+ // doctor output is a single line per check. The high-consequence ones are
829
+ // named separately above, so the truncated tail never hides the sharp cases.
830
+ const MAX_NAMED = 8
831
+ const named = stranded.stranded.slice(0, MAX_NAMED).join(', ')
832
+ const rest = stranded.stranded.length - MAX_NAMED
833
+ strandedCheck = {
834
+ name: 'Config/state root',
835
+ status: 'warn',
836
+ message: `${stranded.target} (from CHROXY_CONFIG_DIR) — ${stranded.stranded.length} `
837
+ + `state ${stranded.stranded.length === 1 ? 'entry is' : 'entries are'} still at `
838
+ + `${stranded.source}${sharp}: ${named}${rest > 0 ? `, and ${rest} more` : ''}`
839
+ + (stranded.acknowledged.length > 0 ? ` (${stranded.acknowledged.length} more acknowledged earlier)` : '')
840
+ + ` — fix: chroxy config-dir migrate (or chroxy config-dir ack to keep this root on purpose)`,
841
+ }
842
+ } else {
843
+ // Read the root off the detection, NOT from configDir()/process.env
844
+ // directly: the detection is injectable, and a branch that bypasses the
845
+ // seam reports something the caller did not ask about — which also makes
846
+ // this message the one branch a test cannot pin.
847
+ const acked = stranded.acknowledged.length
848
+ strandedCheck = {
849
+ name: 'Config/state root',
850
+ status: 'pass',
851
+ message: `${stranded.target}${stranded.relocated ? ' (from CHROXY_CONFIG_DIR)' : ''}`
852
+ + (acked > 0
853
+ ? ` — ${acked} state ${acked === 1 ? 'entry' : 'entries'} at ${stranded.source} acknowledged (chroxy config-dir ack)`
854
+ : ''),
855
+ }
856
+ }
857
+ // Judged on the RAW detection, not the acknowledgement-filtered one: an
858
+ // acknowledged config.json is still absent from the root the daemon reads,
859
+ // so "run 'chroxy init'" would still be the wrong advice for a missing
860
+ // Config (#7244 — an acknowledgement quiets a warning, not a diagnosis).
861
+ if (raw.relocated && !raw.unreadable && raw.highConsequence.includes('config.json')) {
862
+ configCheck = {
863
+ name: 'Config',
864
+ status: 'fail',
865
+ message: `Not found at ${configPath('config.json')} — it is still at `
866
+ + `${join(raw.source, 'config.json')}. Do NOT run 'chroxy init' `
867
+ + `(it mints a fresh token and forces every device to re-pair) — `
868
+ + `run 'chroxy config-dir migrate' instead`,
869
+ }
870
+ }
871
+ } catch (err) {
872
+ strandedCheck = { name: 'Config/state root', status: 'warn', message: `Check failed: ${err.message}` }
873
+ }
874
+
875
+ // 5. Provider-specific checks. Each configured provider contributes its
372
876
  // own binary and credential checks. Providers not in the user's config
373
877
  // are skipped entirely — a Gemini-only install does NOT fail because
374
878
  // `claude` is missing (#2951).
375
- const resolvedProviders = resolveProviders({ providers, configProvider })
879
+ const resolvedProviders = resolveProviders({ providers, parsedConfig })
376
880
  for (const providerName of resolvedProviders) {
377
- const providerChecks = checkProvider(providerName)
881
+ const providerChecks = checkProvider(providerName, { platform, provenance: provenanceOptions, verifyProvenance })
378
882
  for (const c of providerChecks) checks.push(c)
379
883
  }
380
884
 
381
885
  // 5. Config check — appended after provider checks so per-provider
382
886
  // sections group together in the output report.
383
887
  checks.push(configCheck)
888
+ // #7240 — immediately after Config: the root is the context that explains it.
889
+ if (strandedCheck) checks.push(strandedCheck)
384
890
 
385
891
  // Credential storage (#6236). Surface WHERE the API token + credentials
386
892
  // actually live and whether the OS keychain is healthy — the #6235 fallback to
@@ -400,6 +906,16 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
400
906
  : `file fallback — ${kh.detail}`,
401
907
  })
402
908
 
909
+ if (checkUserLevelHook) {
910
+ const hookCheck = checkUserLevelChroxyHook({ settingsPath: userHookSettingsPath })
911
+ if (hookCheck) checks.push(hookCheck)
912
+ // With a test-seamed user settings path and no stranded seam, skip: the
913
+ // fallback would read the developer's real ~/.claude.
914
+ const strandedCheck = (userHookSettingsPath === undefined || strandedHookSettingsPath !== undefined)
915
+ && checkStrandedDefaultHook({ activePath: userHookSettingsPath, defaultPath: strandedHookSettingsPath })
916
+ if (strandedCheck) checks.push(strandedCheck)
917
+ }
918
+
403
919
  // 5.6 Tunnel routability (#5328 WP-5.6). For a configured NAMED tunnel, probe
404
920
  // the hostname end-to-end so a broken DNS route / down tunnel is visible here
405
921
  // rather than only as a failed remote connection later. Skipped for quick /
@@ -458,10 +974,37 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
458
974
  // version as a measured warning instead. Only meaningful when the default
459
975
  // provider actually drives the TUI.
460
976
  if (effectiveDefault === 'claude-tui') {
461
- const tuiCheck = checkClaudeTuiCliVersion()
977
+ // #8074 review C3(c): `claudeTuiResolveBinary` is a test-only seam
978
+ // (undefined in production, so `checkClaudeTuiCliVersion` falls back to
979
+ // its own real `resolveBinary`) — it lets a test point this probe's
980
+ // resolution at a fixture, so the provenance-gate WIRING between
981
+ // `runDoctorChecks` and `checkClaudeTuiCliVersion` (mutant R2: the probe
982
+ // called with `provenance` dropped) is testable hermetically, without
983
+ // depending on whether a real `claude` binary happens to resolve on the
984
+ // machine running the suite.
985
+ const tuiCheck = checkClaudeTuiCliVersion({
986
+ provenance: provenanceOptions,
987
+ verifyProvenance,
988
+ ...(claudeTuiResolveBinary ? { resolveBinary: claudeTuiResolveBinary } : {}),
989
+ })
462
990
  if (tuiCheck) checks.push(tuiCheck)
463
991
  }
464
992
 
993
+ // 5.7 Claude login (#8223). claude-tui always needs the subscription login;
994
+ // claude-sdk needs it unless ANTHROPIC_API_KEY supplies the credential, so a
995
+ // BYOK-key host is not warned about a login it does not use. `claudeLoginDeps`
996
+ // is the test seam (exec / resolver / env); production passes nothing.
997
+ const needsClaudeLogin = resolvedProviders.includes('claude-tui')
998
+ || (resolvedProviders.includes('claude-sdk') && !process.env.ANTHROPIC_API_KEY)
999
+ if (needsClaudeLogin) {
1000
+ const loginCheck = checkClaudeLogin({
1001
+ provenance: provenanceOptions,
1002
+ verifyProvenance,
1003
+ ...claudeLoginDeps,
1004
+ })
1005
+ if (loginCheck) checks.push(loginCheck)
1006
+ }
1007
+
465
1008
  // 6. Dependencies
466
1009
  // Resolve deps relative to the server package, not process.cwd() — Tauri
467
1010
  // launches the server with cwd='/' under launchd, which would always
@@ -508,7 +1051,10 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
508
1051
 
509
1052
  // 7. Port availability
510
1053
  const checkPort = port || 8765
511
- try {
1054
+ if (portProblem) {
1055
+ // A non-integer / out-of-range port must not reach listen(), which treats a string as a pipe path.
1056
+ checks.push({ name: 'Port', status: 'fail', message: portProblem })
1057
+ } else try {
512
1058
  await checkPortAvailable(checkPort)
513
1059
  checks.push({ name: 'Port', status: 'pass', message: `${checkPort} is available` })
514
1060
  } catch {
@@ -527,9 +1073,16 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
527
1073
  * bad config is reported rather than silently ignored.
528
1074
  *
529
1075
  * @param {string} providerName
1076
+ * @param {object} [opts]
1077
+ * @param {string} [opts.platform] - defaults to `process.platform`; injectable
1078
+ * for tests exercising the `requiresDirectExec` shim refusal (#7986 review S2)
1079
+ * @param {{ mode: string, signatureGate: boolean, ledger: object|null }|null} [opts.provenance]
1080
+ * - #8041: opt-in provenance options (`buildBinaryProvenanceOptions`); forwarded
1081
+ * to `checkBinary`. null (the default) skips the gate entirely.
1082
+ * @param {Function} [opts.verifyProvenance] - provenance checker (injected in tests)
530
1083
  * @returns {Array<{ name: string, status: 'pass'|'warn'|'fail', message: string, provider: string }>}
531
1084
  */
532
- function checkProvider(providerName) {
1085
+ function checkProvider(providerName, { platform = process.platform, provenance = null, verifyProvenance = defaultVerifyProvenance } = {}) {
533
1086
  let ProviderClass
534
1087
  try {
535
1088
  ProviderClass = getProvider(providerName)
@@ -552,19 +1105,59 @@ function checkProvider(providerName) {
552
1105
 
553
1106
  const out = []
554
1107
  if (spec.binary) {
555
- const bin = checkBinary(spec.binary.name, spec.binary.args || ['--version'], {
556
- parseVersion: spec.binary.parseVersion || ((out) => out.trim().split('\n')[0]),
557
- required: true,
558
- candidates: spec.binary.candidates || [],
559
- installHint: spec.binary.installHint || `install ${spec.binary.name}`,
560
- // #3953: providers may declare a minimum binary version (e.g.
561
- // claude-channel needs `claude` ≥ 2.1.80 for the --channels MCP
562
- // transport). checkBinary parses the leading semver out of the
563
- // version output and fails when it's below the floor.
564
- minVersion: spec.binary.minVersion || null,
565
- })
566
- bin.provider = providerName
567
- out.push(bin)
1108
+ // #7986 review S2: a provider that declares `requiresDirectExec: true`
1109
+ // (the Agent SDK spawns its binary with no shell) can never run a
1110
+ // Windows npm shim (`claude.cmd`/`claude.bat`) — `chroxy start`'s own
1111
+ // preflight refuses it via ProviderBinaryUnsupportedError, but `doctor`
1112
+ // runs its OWN binary check (checkBinary, below) rather than
1113
+ // runProviderPreflight, so it needs the same refusal or it would report
1114
+ // a shim as a healthy "pass". Checked BEFORE the exec-for-version probe:
1115
+ // resolve the exact path the real spawn would use (the provider's live
1116
+ // `resolvedBinary` when it exposes one, else a fresh candidate resolve —
1117
+ // same preference order runProviderPreflight uses) and fail the row
1118
+ // outright when that path is a shell shim, without ever exec'ing it.
1119
+ let shimResolvedPath = null
1120
+ if (spec.binary.requiresDirectExec === true) {
1121
+ // Same guard runProviderPreflight uses: a subclass getter may throw.
1122
+ try {
1123
+ shimResolvedPath = ProviderClass.resolvedBinary
1124
+ } catch { /* fall through to a fresh candidate resolve */ }
1125
+ if (typeof shimResolvedPath !== 'string' || shimResolvedPath.length === 0) {
1126
+ shimResolvedPath = resolveBinary(spec.binary.name, spec.binary.candidates || [])
1127
+ }
1128
+ }
1129
+ if (shimResolvedPath !== null && isShellShim(shimResolvedPath, platform)) {
1130
+ out.push({
1131
+ name: spec.binary.name,
1132
+ status: 'fail',
1133
+ message: `${shimResolvedPath} — the ${spec.label || providerName} provider spawns ${spec.binary.name} directly without a shell, so it needs the native executable (for claude, \`claude.exe\` from the native installer), not an npm shim`,
1134
+ provider: providerName,
1135
+ })
1136
+ } else {
1137
+ const bin = checkBinary(spec.binary.name, spec.binary.args || ['--version'], {
1138
+ parseVersion: spec.binary.parseVersion || ((out) => out.trim().split('\n')[0]),
1139
+ required: true,
1140
+ candidates: spec.binary.candidates || [],
1141
+ installHint: spec.binary.installHint || `install ${spec.binary.name}`,
1142
+ // #3953: providers may declare a minimum binary version (e.g.
1143
+ // claude-channel needs `claude` ≥ 2.1.80 for the --channels MCP
1144
+ // transport). checkBinary parses the leading semver out of the
1145
+ // version output and fails when it's below the floor. The field may be
1146
+ // a thunk (claude-sdk derives its floor from the SDK, #7986), so it is
1147
+ // resolved through the same helper preflight uses, never read raw.
1148
+ minVersion: resolveDeclaredMinVersion(spec.binary.minVersion),
1149
+ // #8031: a soft, advisory floor — below it downgrades to `warn`
1150
+ // (never blocks server startup), same resolve helper as minVersion.
1151
+ recommendedVersion: resolveDeclaredMinVersion(spec.binary.recommendedVersion),
1152
+ updateHint: spec.binary.updateHint,
1153
+ // #8041: opt-in provenance gate, forwarded straight through to
1154
+ // checkBinary — see its docblock for the gate's shape.
1155
+ provenance,
1156
+ verifyProvenance,
1157
+ })
1158
+ bin.provider = providerName
1159
+ out.push(bin)
1160
+ }
568
1161
  }
569
1162
 
570
1163
  if (spec.credentials && Array.isArray(spec.credentials.envVars) && spec.credentials.envVars.length > 0) {
@@ -598,9 +1191,36 @@ function checkProvider(providerName) {
598
1191
  * on PATH — important for GUI-launched processes (e.g. Tauri) whose
599
1192
  * inherited PATH excludes user-local install dirs.
600
1193
  *
1194
+ * #8041: `provenance` is the opt-in provenance options bag
1195
+ * (`buildBinaryProvenanceOptions`, utils/preflight.js) — null (the default)
1196
+ * skips the gate entirely, byte-identical to pre-#8041 behaviour. When
1197
+ * supplied and enabled, the SAME `verifyProvenance` (utils/verify-provenance.js)
1198
+ * the daemon's `runProviderPreflight` and the tunnel adapter's
1199
+ * `_verifyCloudflaredProvenance` both call is run against `resolved`, BEFORE
1200
+ * the version-probe exec below: a `block`-mode hash mismatch or failed
1201
+ * signature gate returns a `fail` check and the binary is NEVER exec'd. A
1202
+ * `warn`-mode (or unverifiable-but-allowed) issue is logged and the check
1203
+ * proceeds to exec as normal.
1204
+ *
601
1205
  * Exported for tests — callers in production should use `runDoctorChecks`.
602
1206
  */
603
- export function checkBinary(name, args, { parseVersion, required, installHint, candidates = [], minVersion = null, verify = defaultVerifyBinary }) {
1207
+ export function checkBinary(name, args, {
1208
+ parseVersion, required, installHint, candidates = [], minVersion = null,
1209
+ recommendedVersion = null, updateHint = null, verify = defaultVerifyBinary,
1210
+ provenance = null, verifyProvenance = defaultVerifyProvenance,
1211
+ }) {
1212
+ // #8074 review N3: this re-resolves via `resolveBinary(name, candidates)`
1213
+ // rather than preferring `ProviderClass.resolvedBinary` the way
1214
+ // `runProviderPreflight` (and `checkProvider`'s own shim check, just above
1215
+ // in this file) do. That is a live parity ASSUMPTION, not a proof: every
1216
+ // provider's `resolvedBinary` getter today is `resolveBinary(spec.binary.name,
1217
+ // spec.binary.candidates)` — the identical call — so the two can't diverge
1218
+ // currently. If a provider ever overrides `resolvedBinary` with something
1219
+ // that does NOT reduce to that same call (e.g. a live, already-spawned
1220
+ // process's actual path), this check and the real spawn could gate/probe
1221
+ // different paths. Passing the pre-resolved path through would make that
1222
+ // parity structural instead of assumed; left as a comment (optional per
1223
+ // review) since no current provider does this.
604
1224
  const resolved = resolveBinary(name, candidates)
605
1225
  // #6708 — integrity gate BEFORE we try to exec for a version. A macOS
606
1226
  // Gatekeeper-quarantined binary keeps its X bit, and a present-but-non-
@@ -615,13 +1235,73 @@ export function checkBinary(name, args, { parseVersion, required, installHint, c
615
1235
  const { message } = describeBinaryHealth(health, { binary: name, installHint })
616
1236
  return { name, status: required ? 'fail' : 'warn', message }
617
1237
  }
1238
+ // #8041 — opt-in provenance gate, on the SAME healthy `resolved` path,
1239
+ // BEFORE the version-probe exec below. Fail-safe: a `block`-mode hash
1240
+ // mismatch or a failed signature gate reports `fail` here and returns
1241
+ // immediately — the try block below (the only exec in this function) never
1242
+ // runs. Always a hard `fail` (never downgraded by `required`) — see
1243
+ // `provenanceBlockedCheck`'s docblock.
1244
+ //
1245
+ // #8074 review C2: the gate must never run on a path `verify()` didn't
1246
+ // confirm healthy (i.e. `!health.ok` — NOT_FOUND, since QUARANTINED/
1247
+ // NOT_EXECUTABLE already returned above). `verifyProvenance`'s contract
1248
+ // assumes an otherwise-healthy, absolute, resolved path — the SAME
1249
+ // precondition `runProviderPreflight` and the tunnel adapter's
1250
+ // `_verifyCloudflaredProvenance` already honor ("provenance must not mask
1251
+ // 'cloudflared not installed'"). Skipping this check meant a bare,
1252
+ // unresolved name (`resolveBinary` returns the bare `name` itself when
1253
+ // nothing matched) got hashed relative to the CURRENT WORKING DIRECTORY —
1254
+ // mislabeling a genuinely missing binary as a provenance failure in block
1255
+ // mode ("provenance unreadable" instead of "Not found"), and in warn mode
1256
+ // could TOFU-pin a same-named file that happens to sit in cwd under that
1257
+ // bare, relative key — a path the real exec never runs, since its OWN
1258
+ // PATH lookup resolves independently. So: report the ordinary "Not found"
1259
+ // failure immediately, exactly as the exec's own catch block would below,
1260
+ // without ever calling `verifyProvenance` or attempting the exec.
1261
+ if (provenance && !health.ok) {
1262
+ return { name, status: required ? 'fail' : 'warn', message: `Not found — ${installHint}` }
1263
+ }
1264
+ // #8074 review S1: a warn-mode (or unverifiable-but-allowed) provenance
1265
+ // issue used to ONLY log — the doctor row itself stayed `pass`, so `chroxy
1266
+ // doctor`/`chroxy start` printed a clean "[ OK ]" for a binary whose
1267
+ // provenance just flagged an issue. `provenanceAdvisory` carries that note
1268
+ // through to the row built below (the check still execs normally and
1269
+ // reports the real version — warn mode is "surfaced but allowed", not
1270
+ // "skip the probe", matching every other warn-mode consumer of this gate)
1271
+ // rather than short-circuiting before the exec. `server-cmd.js` only
1272
+ // filters on `status === 'fail'`, so `chroxy start` still only stops on a
1273
+ // `block`-mode refusal above — this never blocks startup.
1274
+ let provenanceAdvisory = null
1275
+ if (provenance) {
1276
+ const verdict = verifyProvenance({
1277
+ resolvedPath: health.path,
1278
+ mode: provenance.mode,
1279
+ signatureGate: provenance.signatureGate === true,
1280
+ ledger: provenance.ledger || null,
1281
+ })
1282
+ if (verdict.blocked) {
1283
+ return provenanceBlockedCheck(name, health.path, verdict)
1284
+ }
1285
+ if (
1286
+ verdict.status === PROVENANCE_STATUS.HASH_MISMATCH
1287
+ || verdict.status === PROVENANCE_STATUS.SIGNATURE_INVALID
1288
+ || verdict.status === PROVENANCE_STATUS.UNREADABLE
1289
+ ) {
1290
+ log.warn(`Binary "${name}" provenance ${verdict.status}: ${verdict.message || ''} (allowed — mode=${provenance.mode})`)
1291
+ provenanceAdvisory = `provenance ${verdict.status}: ${verdict.message || 'unverifiable'}`
1292
+ + `${verdict.remediation ? ` — ${verdict.remediation}` : ''} (allowed — mode=${provenance.mode})`
1293
+ }
1294
+ }
1295
+ // #8074 round-2 review: every version row below carries the advisory — a
1296
+ // min/recommended-version warn or fail returning first must not drop it.
1297
+ const withAdvisory = (msg) => (provenanceAdvisory ? `${msg} — ${provenanceAdvisory}` : msg)
618
1298
  try {
619
1299
  // #6484 — a resolved `.cmd` shim (npm-only Windows host) can't be spawned
620
1300
  // directly on Node 24; route it through cmd.exe via prepareSpawn. No-op for
621
1301
  // a `.exe` and on POSIX, so non-Windows binary checks are unchanged.
622
1302
  const spawnSpec = prepareSpawn(resolved, args)
623
1303
  const output = execFileSync(spawnSpec.command, spawnSpec.args, {
624
- encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], ...spawnSpec.options,
1304
+ encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], env: buildClaudeLaunchEnv(), ...spawnSpec.options,
625
1305
  })
626
1306
  const message = parseVersion(output)
627
1307
  // #3953: when the provider declares a minimum version, parse the
@@ -629,23 +1309,49 @@ export function checkBinary(name, args, { parseVersion, required, installHint, c
629
1309
  // and fail the check below the floor. If the version can't be parsed
630
1310
  // we don't block the user — we surface a warn so a format change in
631
1311
  // the upstream CLI doesn't hard-fail an otherwise-working install.
1312
+ // #8031: `recommendedVersion` is a SOFT floor, checked with the same
1313
+ // parsed `found` — below it downgrades to `warn` regardless of
1314
+ // `required` (a soft check never aborts `chroxy start`), never `fail`.
1315
+ let found = null
1316
+ if (minVersion || recommendedVersion) {
1317
+ found = parseLeadingSemver(message)
1318
+ }
632
1319
  if (minVersion) {
633
- const found = parseLeadingSemver(message)
634
1320
  if (found === null) {
635
1321
  return {
636
1322
  name,
637
1323
  status: 'warn',
638
- message: `${message} — could not parse version to verify ≥ ${minVersion}`,
1324
+ message: withAdvisory(`${message} — could not parse version to verify ≥ ${minVersion}`),
639
1325
  }
640
1326
  }
641
1327
  if (compareSemver(found, minVersion) < 0) {
642
1328
  return {
643
1329
  name,
644
1330
  status: required ? 'fail' : 'warn',
645
- message: `${message} — requires ${name} ≥ ${minVersion}; ${installHint}`,
1331
+ message: withAdvisory(`${message} — requires ${name} ≥ ${minVersion}; ${installHint}`),
646
1332
  }
647
1333
  }
648
1334
  }
1335
+ // Only reached once the hard floor (if any) is satisfied. When ONLY
1336
+ // `recommendedVersion` is declared and `found` couldn't be parsed, this
1337
+ // is silently skipped — an unparseable version is not itself a defect
1338
+ // for a soft, advisory check (the hard-floor branch above already owns
1339
+ // the "could not parse" warning when a min is also declared). A
1340
+ // `recommendedVersion` that is itself unparseable is ignored the same
1341
+ // way: compareSemver fails CLOSED on a malformed floor, which is right
1342
+ // for minVersion but would turn a bad advisory into a spurious warn —
1343
+ // preflight gates this check on a parsed recommended version too.
1344
+ if (recommendedVersion && found !== null && parseLeadingSemver(recommendedVersion) !== null
1345
+ && compareSemver(found, recommendedVersion) < 0) {
1346
+ return {
1347
+ name,
1348
+ status: 'warn',
1349
+ message: withAdvisory(`${message} — older than the recommended ${name} ${recommendedVersion}; ${updateHint || installHint}`),
1350
+ }
1351
+ }
1352
+ if (provenanceAdvisory) {
1353
+ return { name, status: 'warn', message: withAdvisory(message) }
1354
+ }
649
1355
  return { name, status: 'pass', message }
650
1356
  } catch (err) {
651
1357
  if (err.killed || err.signal === 'SIGTERM') {