@chroxy/server 0.10.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 (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  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 +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  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 +74 -9
  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 +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
package/src/doctor.js CHANGED
@@ -1,16 +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, platform } 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'
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'
9
12
  import { prepareSpawn } from './utils/win-spawn.js'
10
- import { getProvider, DEFAULT_PROVIDER } from './providers.js'
13
+ import { buildClaudeLaunchEnv } from './utils/spawn-env.js'
14
+ import { cloudflaredInstallHint } from './platform.js'
15
+ import { getProvider, DEFAULT_PROVIDER, resolveDaemonDefaultProvider } from './providers.js'
11
16
  import { registerAnthropicCompatibleProviders } from './anthropic-compatible-session.js'
12
17
  import { registerOpenAiCompatibleProviders } from './openai-compatible-session.js'
13
18
  import { parseTunnelArg } from './tunnel/index.js'
19
+ import { CLOUDFLARED_CANDIDATES } from './tunnel/cloudflare.js'
14
20
  import { TESTED_CLAUDE_TUI_CLI_VERSION } from './claude-tui/tested-cli-version.js'
15
21
  import { detectSilentMeteredDefault } from './doctor-billing.js'
16
22
  import { keychainHealth } from './keychain.js'
@@ -21,6 +27,15 @@ import {
21
27
  PROGRAMMATIC_CREDIT_ERA_START,
22
28
  } from './billing-class.js'
23
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')
24
39
 
25
40
  // Resolve the server package root (the directory containing package.json
26
41
  // and node_modules) so dependency checks work regardless of where the
@@ -36,7 +51,9 @@ const SERVER_PKG_DIR = dirname(dirname(__filename))
36
51
  // tests/_setup.mjs redirecting CHROXY_CONFIG_DIR to a tmp dir — which would let
37
52
  // the named-tunnel routability probe (#5328) fire a live network request from
38
53
  // a maintainer's real config during the suite.
39
- const CONFIG_FILE = join(process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy'), 'config.json')
54
+ function configFile() {
55
+ return configPath('config.json')
56
+ }
40
57
 
41
58
  /**
42
59
  * Parse the leading `major.minor.patch` semver out of an arbitrary version
@@ -110,17 +127,54 @@ export function isBundledOrSupervisedContext() {
110
127
  /**
111
128
  * Resolve the list of providers to preflight check.
112
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
+ *
113
158
  * Precedence:
114
- * 1. Explicit `providers` option (array of provider names)
115
- * 2. `provider` field from loaded config file
116
- * 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.
117
163
  *
118
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.
119
171
  */
120
- function resolveProviders({ providers, configProvider }) {
172
+ function resolveProviders({ providers, parsedConfig }) {
121
173
  if (Array.isArray(providers) && providers.length > 0) return providers
122
- if (typeof configProvider === 'string' && configProvider.length > 0) return [configProvider]
123
- return [DEFAULT_PROVIDER]
174
+ const merged = mergeConfig({
175
+ fileConfig: parsedConfig && typeof parsedConfig === 'object' ? parsedConfig : {},
176
+ })
177
+ return [resolveDaemonDefaultProvider(merged)]
124
178
  }
125
179
 
126
180
  /**
@@ -139,6 +193,97 @@ function claudeTuiBinaryCandidates() {
139
193
  }
140
194
  }
141
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
+
142
287
  /**
143
288
  * audit P1-3 / #5821: compare the installed claude CLI version against the
144
289
  * version chroxy's claude-tui form-driving was validated against
@@ -152,6 +297,14 @@ function claudeTuiBinaryCandidates() {
152
297
  * @param {(bin: string, args: string[]) => string} [deps.exec]
153
298
  * @param {string} [deps.tested]
154
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)
155
308
  * @returns {{ name: string, status: 'pass'|'warn', message: string } | null}
156
309
  */
157
310
  export function checkClaudeTuiCliVersion(deps = {}) {
@@ -162,7 +315,7 @@ export function checkClaudeTuiCliVersion(deps = {}) {
162
315
  // win32-routing test exercises this default path directly.
163
316
  exec = (bin, args) => {
164
317
  const s = prepareSpawn(bin, args)
165
- 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 })
166
319
  },
167
320
  tested = TESTED_CLAUDE_TUI_CLI_VERSION,
168
321
  // #5871: resolve against the SAME candidate paths the claude-tui provider
@@ -171,10 +324,21 @@ export function checkClaudeTuiCliVersion(deps = {}) {
171
324
  // claude via its candidate list — exactly the bundled context where a
172
325
  // silent mis-drive would otherwise go unnoticed.
173
326
  candidates = claudeTuiBinaryCandidates(),
327
+ resolveBinary: resolveClaudeBinary = resolveBinary,
328
+ verify = defaultVerifyBinary,
329
+ provenance = null,
330
+ verifyProvenance = defaultVerifyProvenance,
174
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)
175
339
  let output
176
340
  try {
177
- output = exec(resolveBinary('claude', candidates), ['--version'])
341
+ output = exec(execPath, ['--version'])
178
342
  } catch {
179
343
  return null // claude missing/hung — the provider binary check surfaces that
180
344
  }
@@ -182,17 +346,105 @@ export function checkClaudeTuiCliVersion(deps = {}) {
182
346
  const found = parseLeadingSemver(output)
183
347
  const testedSemver = parseLeadingSemver(tested)
184
348
  if (found === null) {
185
- 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}`) }
186
350
  }
187
351
  const foundStr = `${found[0]}.${found[1]}.${found[2]}`
188
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
+ }
189
358
  return { name: NAME, status: 'pass', message: `claude ${foundStr} matches the tested TUI-driving baseline (${tested})` }
190
359
  }
191
360
  return {
192
361
  name: NAME,
193
362
  status: 'warn',
194
- 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 }
195
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 }
196
448
  }
197
449
 
198
450
  /**
@@ -272,6 +524,64 @@ export async function checkTunnelRoutability(deps = {}) {
272
524
  }
273
525
  }
274
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
+
275
585
  /**
276
586
  * Run all preflight dependency checks and return results.
277
587
  *
@@ -288,12 +598,77 @@ export async function checkTunnelRoutability(deps = {}) {
288
598
  * Dependencies check. Defaults to the server package root. Relative paths are resolved to
289
599
  * absolute at call time so the check is fully decoupled from process.cwd(). Exposed so
290
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.
291
609
  * @returns {{ checks: Array<{ name: string, status: 'pass'|'warn'|'fail', message: string, provider?: string }>, passed: boolean, providers: string[] }}
292
610
  */
293
- 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
+ } = {}) {
294
671
  const checks = []
295
- const isMac = platform() === 'darwin'
296
- const isLinux = platform() === 'linux'
297
672
 
298
673
  // 1. Node.js version
299
674
  const nodeVersion = process.versions.node
@@ -306,30 +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: isMac ? 'brew install cloudflared'
319
- : isLinux ? 'see https://pkg.cloudflare.com/ for installation'
320
- : 'see https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/',
321
- }))
322
-
323
- // 3. Load config (once) — used for both the Config check and provider resolution.
324
- 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.
325
688
  let configCheck = null
326
689
  // #5328 (WP-5.6): named-tunnel coordinates for the routability probe (step 5.6).
327
690
  let tunnelMode = null
328
691
  let tunnelHostname = null
329
- 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)) {
330
706
  try {
331
- const config = JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'))
332
- if (typeof config.provider === 'string') configProvider = config.provider
707
+ const config = JSON.parse(readFileSync(cfgFile, 'utf-8'))
708
+ parsedConfig = config
333
709
  // Normalize the tunnel mode through parseTunnelArg so aliases resolve —
334
710
  // e.g. `cloudflare:named` (a documented --tunnel form persisted verbatim)
335
711
  // maps to mode 'named' and isn't silently skipped by the routability
@@ -355,34 +731,162 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
355
731
  registerOpenAiCompatibleProviders(config)
356
732
  const { valid, warnings } = validateConfig(config)
357
733
  if (valid) {
358
- configCheck = { name: 'Config', status: 'pass', message: CONFIG_FILE }
734
+ configCheck = { name: 'Config', status: 'pass', message: cfgFile }
359
735
  } else {
360
- configCheck = { name: 'Config', status: 'warn', message: `${CONFIG_FILE} — ${warnings.join('; ')}` }
736
+ configCheck = { name: 'Config', status: 'warn', message: `${cfgFile} — ${warnings.join('; ')}` }
361
737
  }
362
738
  } catch (err) {
363
739
  if (err instanceof SyntaxError) {
364
- configCheck = { name: 'Config', status: 'fail', message: `${CONFIG_FILE} — invalid JSON: ${err.message}` }
740
+ configCheck = { name: 'Config', status: 'fail', message: `${cfgFile} — invalid JSON: ${err.message}` }
365
741
  } else {
366
- configCheck = { name: 'Config', status: 'fail', message: `${CONFIG_FILE} — ${err.message}` }
742
+ configCheck = { name: 'Config', status: 'fail', message: `${cfgFile} — ${err.message}` }
367
743
  }
368
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` }
369
748
  } else {
370
- configCheck = { name: 'Config', status: 'warn', message: `Not found — run 'npx chroxy init' to create` }
749
+ configCheck = { name: 'Config', status: 'warn', message: `Not found — run 'chroxy init' to create` }
371
750
  }
372
751
 
373
- // 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
374
876
  // own binary and credential checks. Providers not in the user's config
375
877
  // are skipped entirely — a Gemini-only install does NOT fail because
376
878
  // `claude` is missing (#2951).
377
- const resolvedProviders = resolveProviders({ providers, configProvider })
879
+ const resolvedProviders = resolveProviders({ providers, parsedConfig })
378
880
  for (const providerName of resolvedProviders) {
379
- const providerChecks = checkProvider(providerName)
881
+ const providerChecks = checkProvider(providerName, { platform, provenance: provenanceOptions, verifyProvenance })
380
882
  for (const c of providerChecks) checks.push(c)
381
883
  }
382
884
 
383
885
  // 5. Config check — appended after provider checks so per-provider
384
886
  // sections group together in the output report.
385
887
  checks.push(configCheck)
888
+ // #7240 — immediately after Config: the root is the context that explains it.
889
+ if (strandedCheck) checks.push(strandedCheck)
386
890
 
387
891
  // Credential storage (#6236). Surface WHERE the API token + credentials
388
892
  // actually live and whether the OS keychain is healthy — the #6235 fallback to
@@ -402,6 +906,16 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
402
906
  : `file fallback — ${kh.detail}`,
403
907
  })
404
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
+
405
919
  // 5.6 Tunnel routability (#5328 WP-5.6). For a configured NAMED tunnel, probe
406
920
  // the hostname end-to-end so a broken DNS route / down tunnel is visible here
407
921
  // rather than only as a failed remote connection later. Skipped for quick /
@@ -460,10 +974,37 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
460
974
  // version as a measured warning instead. Only meaningful when the default
461
975
  // provider actually drives the TUI.
462
976
  if (effectiveDefault === 'claude-tui') {
463
- 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
+ })
464
990
  if (tuiCheck) checks.push(tuiCheck)
465
991
  }
466
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
+
467
1008
  // 6. Dependencies
468
1009
  // Resolve deps relative to the server package, not process.cwd() — Tauri
469
1010
  // launches the server with cwd='/' under launchd, which would always
@@ -510,7 +1051,10 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
510
1051
 
511
1052
  // 7. Port availability
512
1053
  const checkPort = port || 8765
513
- 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 {
514
1058
  await checkPortAvailable(checkPort)
515
1059
  checks.push({ name: 'Port', status: 'pass', message: `${checkPort} is available` })
516
1060
  } catch {
@@ -529,9 +1073,16 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
529
1073
  * bad config is reported rather than silently ignored.
530
1074
  *
531
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)
532
1083
  * @returns {Array<{ name: string, status: 'pass'|'warn'|'fail', message: string, provider: string }>}
533
1084
  */
534
- function checkProvider(providerName) {
1085
+ function checkProvider(providerName, { platform = process.platform, provenance = null, verifyProvenance = defaultVerifyProvenance } = {}) {
535
1086
  let ProviderClass
536
1087
  try {
537
1088
  ProviderClass = getProvider(providerName)
@@ -554,19 +1105,59 @@ function checkProvider(providerName) {
554
1105
 
555
1106
  const out = []
556
1107
  if (spec.binary) {
557
- const bin = checkBinary(spec.binary.name, spec.binary.args || ['--version'], {
558
- parseVersion: spec.binary.parseVersion || ((out) => out.trim().split('\n')[0]),
559
- required: true,
560
- candidates: spec.binary.candidates || [],
561
- installHint: spec.binary.installHint || `install ${spec.binary.name}`,
562
- // #3953: providers may declare a minimum binary version (e.g.
563
- // claude-channel needs `claude` ≥ 2.1.80 for the --channels MCP
564
- // transport). checkBinary parses the leading semver out of the
565
- // version output and fails when it's below the floor.
566
- minVersion: spec.binary.minVersion || null,
567
- })
568
- bin.provider = providerName
569
- 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
+ }
570
1161
  }
571
1162
 
572
1163
  if (spec.credentials && Array.isArray(spec.credentials.envVars) && spec.credentials.envVars.length > 0) {
@@ -600,17 +1191,117 @@ function checkProvider(providerName) {
600
1191
  * on PATH — important for GUI-launched processes (e.g. Tauri) whose
601
1192
  * inherited PATH excludes user-local install dirs.
602
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
+ *
603
1205
  * Exported for tests — callers in production should use `runDoctorChecks`.
604
1206
  */
605
- export function checkBinary(name, args, { parseVersion, required, installHint, candidates = [], minVersion = null }) {
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.
606
1224
  const resolved = resolveBinary(name, candidates)
1225
+ // #6708 — integrity gate BEFORE we try to exec for a version. A macOS
1226
+ // Gatekeeper-quarantined binary keeps its X bit, and a present-but-non-
1227
+ // executable binary throws EACCES in the version probe — in both cases the
1228
+ // catch below would mislabel it "Not found — install …". Detect them up front
1229
+ // so doctor reports "quarantined/blocked" and "not executable" distinctly from
1230
+ // "not installed", each with its own fix-it hint. The quarantine step is a
1231
+ // no-op off darwin; NOT_FOUND still falls through to the version probe (whose
1232
+ // catch owns the install message).
1233
+ const health = verify(resolved)
1234
+ if (health.status === BINARY_STATUS.QUARANTINED || health.status === BINARY_STATUS.NOT_EXECUTABLE) {
1235
+ const { message } = describeBinaryHealth(health, { binary: name, installHint })
1236
+ return { name, status: required ? 'fail' : 'warn', message }
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)
607
1298
  try {
608
1299
  // #6484 — a resolved `.cmd` shim (npm-only Windows host) can't be spawned
609
1300
  // directly on Node 24; route it through cmd.exe via prepareSpawn. No-op for
610
1301
  // a `.exe` and on POSIX, so non-Windows binary checks are unchanged.
611
1302
  const spawnSpec = prepareSpawn(resolved, args)
612
1303
  const output = execFileSync(spawnSpec.command, spawnSpec.args, {
613
- 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,
614
1305
  })
615
1306
  const message = parseVersion(output)
616
1307
  // #3953: when the provider declares a minimum version, parse the
@@ -618,23 +1309,49 @@ export function checkBinary(name, args, { parseVersion, required, installHint, c
618
1309
  // and fail the check below the floor. If the version can't be parsed
619
1310
  // we don't block the user — we surface a warn so a format change in
620
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
+ }
621
1319
  if (minVersion) {
622
- const found = parseLeadingSemver(message)
623
1320
  if (found === null) {
624
1321
  return {
625
1322
  name,
626
1323
  status: 'warn',
627
- message: `${message} — could not parse version to verify ≥ ${minVersion}`,
1324
+ message: withAdvisory(`${message} — could not parse version to verify ≥ ${minVersion}`),
628
1325
  }
629
1326
  }
630
1327
  if (compareSemver(found, minVersion) < 0) {
631
1328
  return {
632
1329
  name,
633
1330
  status: required ? 'fail' : 'warn',
634
- message: `${message} — requires ${name} ≥ ${minVersion}; ${installHint}`,
1331
+ message: withAdvisory(`${message} — requires ${name} ≥ ${minVersion}; ${installHint}`),
635
1332
  }
636
1333
  }
637
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
+ }
638
1355
  return { name, status: 'pass', message }
639
1356
  } catch (err) {
640
1357
  if (err.killed || err.signal === 'SIGTERM') {