@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
@@ -4,11 +4,46 @@
4
4
  * Foundation only for #4048/#4076: parse Claude-style mcpServers blocks and
5
5
  * expose safe read-only metadata. This module deliberately does not spawn MCP
6
6
  * children or wire tools.
7
+ *
8
+ * NOT byok-only despite the filename: `resolveClaudeConfigWritePath` +
9
+ * `writeClaudeConfigAtomic` are the SINGLE writer for `~/.claude.json` across the
10
+ * whole server, and `claude-tui/pty-driver.js`'s `ensureCwdTrusted` goes through
11
+ * them too (#7046). A second hand-rolled `writeFileSync(tmp)` → `renameSync(tmp,
12
+ * config)` over this file is how the symlink-destroying / mode-widening defect
13
+ * came to exist in two places at once — add callers here, not copies.
7
14
  */
8
15
 
9
- import { existsSync, readFileSync, statSync } from 'node:fs'
10
- import { homedir } from 'node:os'
11
- import { join } from 'node:path'
16
+ import {
17
+ chmodSync,
18
+ existsSync,
19
+ lstatSync,
20
+ mkdirSync,
21
+ readFileSync,
22
+ realpathSync,
23
+ renameSync,
24
+ statSync,
25
+ unlinkSync,
26
+ writeFileSync,
27
+ } from 'node:fs'
28
+ import { createHash, randomUUID } from 'node:crypto'
29
+ import { dirname, join } from 'node:path'
30
+ import { lookup as dnsLookup } from 'node:dns/promises'
31
+ import { claudeGlobalConfigPath, parseClaudeConfigText } from './utils/claude-config-dir.js'
32
+ import { fsyncForDurability, confirmRenameDurable, stampWindowsAclStrict } from './platform.js'
33
+ import { createLogger } from './logger.js'
34
+ import {
35
+ MCP_SERVER_NAME_RE,
36
+ UNSAFE_MCP_KEYS,
37
+ containsMcpToolNamespaceSeparator,
38
+ isBlockedMetadataHost,
39
+ // #7030 — single-sourced from @chroxy/protocol/mcp-validation (the
40
+ // Zod-free subpath: this file has no other dependency on @chroxy/protocol
41
+ // and must not pull the Zod barrel into the ~/.claude.json parse path).
42
+ // Previously hand-duplicated in packages/dashboard/src/lib/mcp-server-
43
+ // validation.ts; #6986 and #7001 are what one-copy-drifts looks like.
44
+ } from '@chroxy/protocol/mcp-validation'
45
+
46
+ const log = createLogger('claude-config')
12
47
 
13
48
  /**
14
49
  * Defensive upper bound on the size of `~/.claude.json`. Today the file is
@@ -20,7 +55,7 @@ import { join } from 'node:path'
20
55
  export const CLAUDE_CONFIG_MAX_BYTES = 10 * 1024 * 1024
21
56
 
22
57
  export function defaultClaudeConfigPath() {
23
- return process.env.CHROXY_CLAUDE_CONFIG || join(homedir(), '.claude.json')
58
+ return process.env.CHROXY_CLAUDE_CONFIG || claudeGlobalConfigPath()
24
59
  }
25
60
 
26
61
  /**
@@ -51,6 +86,21 @@ function coerceStringArray(value, { warnings, serverName }) {
51
86
  return out
52
87
  }
53
88
 
89
+ /**
90
+ * Keys that must never be assigned into a string→string map we build with `{}`.
91
+ * `map.__proto__ = 'some string'` hits `Object.prototype`'s `__proto__` setter,
92
+ * which ignores non-object values — so the key vanished SILENTLY, and a caller
93
+ * who asked for `env.__proto__` got a server spawned without it and no
94
+ * explanation. `constructor` / `prototype` are plain own-property writes (no
95
+ * setter) but are refused alongside it: a map key that shadows an object internal
96
+ * is never a legitimate environment variable or HTTP header (#7001 review).
97
+ *
98
+ * #7030 — single-sourced as `UNSAFE_MCP_KEYS` from
99
+ * @chroxy/protocol/mcp-validation (imported above). Kept as a local alias so
100
+ * this stays a pure rename at every call site below.
101
+ */
102
+ const UNSAFE_MAP_KEYS = UNSAFE_MCP_KEYS
103
+
54
104
  /**
55
105
  * Coerce an env object to string→string only. Pushes one warning per dropped
56
106
  * key naming the server, the offending field (`env.<KEY>`), and the value's
@@ -67,6 +117,14 @@ function coerceEnv(value, { warnings, serverName }) {
67
117
  const env = {}
68
118
  for (const [key, raw] of Object.entries(value)) {
69
119
  if (typeof key !== 'string' || key.length === 0) continue
120
+ if (UNSAFE_MAP_KEYS.has(key)) {
121
+ // Warn rather than drop silently: on the WRITE path
122
+ // (normalizeMcpServerConfig) any warning is escalated to a rejection, so
123
+ // the caller is told the key is refused instead of receiving an `ok` for a
124
+ // config that quietly lost it.
125
+ warnings.push(`MCP server ${serverName}: refusing env.${key} (reserved object key, never a real environment variable)`)
126
+ continue
127
+ }
70
128
  if (typeof raw === 'string') {
71
129
  env[key] = raw
72
130
  } else {
@@ -78,11 +136,304 @@ function coerceEnv(value, { warnings, serverName }) {
78
136
  return env
79
137
  }
80
138
 
139
+ /**
140
+ * Coerce an HTTP `headers` object to string→string only, for remote (#6821)
141
+ * MCP transports. Same defensive shape as coerceEnv: one warning per dropped
142
+ * key naming the field (`headers.<KEY>`), and the whole field is dropped with
143
+ * a single warning if it is not a plain object. Header VALUES (bearer tokens,
144
+ * api keys) are never logged or surfaced — the warning names only the key.
145
+ */
146
+ function coerceHeaders(value, { warnings, serverName }) {
147
+ if (value == null) return {}
148
+ if (typeof value !== 'object' || Array.isArray(value)) {
149
+ warnings.push(
150
+ `MCP server ${serverName}: ignoring headers (expected object, got ${Array.isArray(value) ? 'array' : typeof value})`,
151
+ )
152
+ return {}
153
+ }
154
+ const headers = {}
155
+ for (const [key, raw] of Object.entries(value)) {
156
+ if (typeof key !== 'string' || key.length === 0) continue
157
+ if (UNSAFE_MAP_KEYS.has(key)) {
158
+ // Same silent-drop hazard as env.__proto__ — refuse explicitly (#7001 review).
159
+ warnings.push(`MCP server ${serverName}: refusing headers.${key} (reserved object key, never a real HTTP header)`)
160
+ continue
161
+ }
162
+ if (typeof raw === 'string') {
163
+ headers[key] = raw
164
+ } else {
165
+ warnings.push(
166
+ `MCP server ${serverName}: dropping headers.${key} (expected string, got ${typeof raw})`,
167
+ )
168
+ }
169
+ }
170
+ return headers
171
+ }
172
+
173
+ // #7030 — `isBlockedMetadataHost` is single-sourced from
174
+ // @chroxy/protocol/mcp-validation (imported above) and re-exported here so
175
+ // existing callers (`byok-mcp-client.js`, `byok-mcp-oauth.js`) are unaffected.
176
+ // See the shared module's doc comment for the full metadata-host rationale
177
+ // (169.254.0.0/16, IPv4-mapped IPv6 forms, the AWS IMDS IPv6 endpoint).
178
+ export { isBlockedMetadataHost }
179
+
180
+ /**
181
+ * Return a credential-stripped form of an MCP server url, safe to log or
182
+ * surface as metadata (#6821). Strips URL userinfo (`user:pass@`), the query
183
+ * string, and the fragment — any of which can carry a token — while keeping
184
+ * the origin + path that identify the endpoint. An unparseable url yields a
185
+ * fixed placeholder so a malformed value can never leak verbatim.
186
+ */
187
+ export function redactMcpUrl(url) {
188
+ if (typeof url !== 'string' || url.length === 0) return ''
189
+ try {
190
+ const u = new URL(url)
191
+ u.username = ''
192
+ u.password = ''
193
+ u.search = ''
194
+ u.hash = ''
195
+ return u.toString()
196
+ } catch {
197
+ return '[unparseable url]'
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Classify a bare IP address for trust-prompt display (#6834). Returns one of
203
+ * 'loopback' | 'private' | 'link-local' | 'public' | 'unknown'. Purely for the
204
+ * human-facing consent string — the cloud-metadata range is hard-BLOCKED
205
+ * upstream (isBlockedMetadataHost, at config-parse and request time) so a
206
+ * metadata address never reaches this classifier.
207
+ *
208
+ * Covers the common private ranges a "remote" MCP server might secretly point
209
+ * at: IPv4 loopback (127/8), RFC1918 (10/8, 172.16/12, 192.168/16), link-local
210
+ * (169.254/16), and their IPv6 equivalents (::1, fc00::/7 ULA, fe80::/10
211
+ * link-local). IPv4-mapped IPv6 (`::ffff:a.b.c.d`) is unwrapped to its v4 form
212
+ * first. Anything else is 'public'. Best-effort — an unrecognisable string maps
213
+ * to 'unknown' (shown as such), never throws.
214
+ */
215
+ export function classifyIpAddress(ip) {
216
+ if (typeof ip !== 'string' || ip.length === 0) return 'unknown'
217
+ let h = ip.toLowerCase().trim()
218
+ if (h.startsWith('[') && h.endsWith(']')) h = h.slice(1, -1)
219
+ const zone = h.indexOf('%') // strip an IPv6 zone id (fe80::1%en0)
220
+ if (zone !== -1) h = h.slice(0, zone)
221
+ // IPv4-mapped IPv6 (::ffff:a.b.c.d) — classify by the embedded v4 address.
222
+ const mapped = h.match(/^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)
223
+ if (mapped) h = mapped[1]
224
+ const v4 = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)
225
+ if (v4) {
226
+ const a = Number(v4[1])
227
+ const b = Number(v4[2])
228
+ if (v4.slice(1).some((o) => Number(o) > 255)) return 'unknown'
229
+ if (a === 127) return 'loopback'
230
+ if (a === 10) return 'private'
231
+ if (a === 172 && b >= 16 && b <= 31) return 'private'
232
+ if (a === 192 && b === 168) return 'private'
233
+ if (a === 169 && b === 254) return 'link-local'
234
+ return 'public'
235
+ }
236
+ // IPv6 literals.
237
+ if (h === '::1') return 'loopback'
238
+ // Link-local is fe80::/10 — the leading hextet spans fe80 through febf (top
239
+ // 10 bits fixed: 1111111010). Match the first two hex digits (fe) plus the
240
+ // third digit constrained to 8..b, not just the `fe80` literal. The trailing
241
+ // `:` covers both `fe80:...` and the compressed `fe80::...` (which begins `:`).
242
+ if (/^fe[89ab][0-9a-f]:/.test(h)) return 'link-local'
243
+ if (/^f[cd][0-9a-f]{2}:/.test(h)) return 'private' // fc00::/7 unique-local
244
+ if (h.includes(':')) return 'public'
245
+ return 'unknown'
246
+ }
247
+
248
+ // Human-readable label per classification, for the trust-prompt string.
249
+ const _CLASSIFICATION_LABELS = {
250
+ loopback: 'loopback',
251
+ private: 'private LAN',
252
+ 'link-local': 'link-local',
253
+ public: 'public',
254
+ unknown: 'unknown',
255
+ }
256
+
257
+ // Order of "notability" when a host resolves to several addresses — the most
258
+ // internal wins the summary label so a remote server that ALSO resolves to an
259
+ // internal address surfaces that fact at consent time.
260
+ const _CLASSIFICATION_PRIORITY = ['loopback', 'private', 'link-local', 'public', 'unknown']
261
+
262
+ // #6852 — cap on the trust-prompt DNS lookup. resolveTrustAddress runs inside
263
+ // the fleet's withTrustStoreLock (byok-mcp-fleet.js), so a slow/hanging
264
+ // resolver would both delay the consent prompt AND hold the lock for every
265
+ // other MCP client. 2s is generous for a real resolver yet bounds the worst
266
+ // case; on timeout we fall back to the same graceful "could not resolve host".
267
+ export const DEFAULT_TRUST_DNS_TIMEOUT_MS = 2000
268
+
269
+ // Resolved by the timeout arm of the lookup race (distinct from any address the
270
+ // resolver could return), so a timeout maps to the graceful fallback.
271
+ const _LOOKUP_TIMEOUT = Symbol('trust-address-lookup-timeout')
272
+
273
+ function _summariseClassification(classifications) {
274
+ for (const c of _CLASSIFICATION_PRIORITY) {
275
+ if (classifications.includes(c)) return c
276
+ }
277
+ return 'unknown'
278
+ }
279
+
280
+ /**
281
+ * Best-effort resolution of a remote MCP server url's host, for the first-use
282
+ * trust prompt (#6834). Returns a small structured record describing WHERE the
283
+ * host actually points so a user approving a 'remote' server can see when it
284
+ * resolves to a loopback / private / internal address and make an informed
285
+ * consent decision (owner decision 2026-07-18: display, don't block).
286
+ *
287
+ * Shape: `{ resolved, hostname, addresses, classification, display }`.
288
+ * - resolved:false + display 'could not resolve host' when the url is
289
+ * unparseable OR DNS lookup fails / returns nothing. NEVER throws.
290
+ * - a literal IP host is classified directly (no DNS round-trip).
291
+ * - a DNS name is resolved via `lookup(..., { all: true })`; the summary
292
+ * classification is the most-internal of the returned addresses.
293
+ *
294
+ * The `lookup` seam is injectable (defaults to node:dns/promises lookup — the
295
+ * same resolver the transport's metadata guard uses) so tests never touch real
296
+ * DNS. Credentials are NOT this function's concern: pass an already-redacted or
297
+ * raw url — only the hostname is read, and only IPs are returned.
298
+ *
299
+ * The lookup is bounded by `timeoutMs` (#6852): resolveTrustAddress runs under
300
+ * the fleet's trust-store lock, so a hanging resolver must not stall the prompt
301
+ * or the lock — a timeout falls back to 'could not resolve host'. The timer
302
+ * itself is injectable via `setTimer`/`clearTimer` (default node globals) so a
303
+ * test can drive the timeout deterministically — firing it by hand instead of
304
+ * waiting on the wall clock (#6908) — with no real DNS and no real timer.
305
+ */
306
+ export async function resolveTrustAddress(
307
+ url,
308
+ {
309
+ lookup = dnsLookup,
310
+ timeoutMs = DEFAULT_TRUST_DNS_TIMEOUT_MS,
311
+ setTimer = setTimeout,
312
+ clearTimer = clearTimeout,
313
+ } = {},
314
+ ) {
315
+ const miss = (hostname = null) => ({
316
+ resolved: false,
317
+ hostname,
318
+ addresses: [],
319
+ classification: 'unknown',
320
+ display: 'could not resolve host',
321
+ })
322
+ let hostname
323
+ try {
324
+ hostname = new URL(url).hostname
325
+ } catch {
326
+ return miss()
327
+ }
328
+ if (!hostname) return miss()
329
+ const bare = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname
330
+ // Short-circuit ONLY for a syntactically-valid IP literal. A dotted-quad-
331
+ // shaped string with an out-of-range octet (e.g. 999.1.1.1) is NOT an IP —
332
+ // classifyIpAddress returns 'unknown' — so it is really a hostname and must
333
+ // go through the DNS path, not be echoed as a misleading "resolves to
334
+ // 999.1.1.1". A bracketed / colon-bearing IPv6 host is always a literal.
335
+ const looksLikeLiteral = /^[\d.]+$/.test(bare) || bare.includes(':')
336
+ const literalClass = looksLikeLiteral ? classifyIpAddress(bare) : 'unknown'
337
+ if (looksLikeLiteral && literalClass !== 'unknown') {
338
+ return {
339
+ resolved: true,
340
+ hostname,
341
+ addresses: [bare],
342
+ classification: literalClass,
343
+ display: `resolves to ${bare} (${_CLASSIFICATION_LABELS[literalClass] || literalClass})`,
344
+ }
345
+ }
346
+ let timer
347
+ try {
348
+ // Bound the lookup: whichever settles first wins. The timeout arm RESOLVES
349
+ // with a sentinel (never rejects) so a slow resolver maps to the graceful
350
+ // fallback, not an error. Promise.race registers a reaction on the lookup
351
+ // promise, so a late rejection from the loser stays handled. The timer is
352
+ // NOT unref'd — it is always cleared in `finally` once the race settles, so
353
+ // it never outlives this (awaited) resolution, and keeping the loop alive
354
+ // while we resolve is the intended behaviour. `setTimer`/`clearTimer` are
355
+ // injectable (default globals) so a test drives the timeout deterministically.
356
+ const timeoutArm = new Promise((resolve) => {
357
+ timer = setTimer(() => resolve(_LOOKUP_TIMEOUT), timeoutMs)
358
+ })
359
+ const addrs = await Promise.race([lookup(bare, { all: true }), timeoutArm])
360
+ if (addrs === _LOOKUP_TIMEOUT) return miss(hostname)
361
+ const addresses = (Array.isArray(addrs) ? addrs : [])
362
+ .map((a) => (a && typeof a.address === 'string' ? a.address : null))
363
+ .filter(Boolean)
364
+ if (addresses.length === 0) return miss(hostname)
365
+ const classifications = addresses.map(classifyIpAddress)
366
+ const classification = _summariseClassification(classifications)
367
+ return {
368
+ resolved: true,
369
+ hostname,
370
+ addresses,
371
+ classification,
372
+ display: `resolves to ${addresses.join(', ')} (${_CLASSIFICATION_LABELS[classification] || classification})`,
373
+ }
374
+ } catch {
375
+ return miss(hostname)
376
+ } finally {
377
+ clearTimer(timer)
378
+ }
379
+ }
380
+
381
+ /**
382
+ * Parse a remote (streamable-HTTP / SSE) MCP server entry (#6821). Claude
383
+ * Code represents these in `~/.claude.json` as `{ "type": "http"|"sse",
384
+ * "url": "https://...", "headers": { ... } }` — no `command`. Returns a
385
+ * normalized `{ name, type, url, headers }` server or null (with a warning)
386
+ * when the entry is unusable. Only http(s) urls are accepted; file:/ws:/etc.
387
+ * are rejected so a config typo can't point the transport at a local socket.
388
+ */
389
+ function parseRemoteEntry(name, entry, { warnings }) {
390
+ const url = typeof entry.url === 'string' ? entry.url.trim() : ''
391
+ if (!url) {
392
+ warnings.push(`Skipping MCP server ${name}: url is required for a remote (http/sse) server`)
393
+ return null
394
+ }
395
+ let parsedUrl
396
+ try {
397
+ parsedUrl = new URL(url)
398
+ } catch {
399
+ warnings.push(`Skipping MCP server ${name}: url is not a valid URL`)
400
+ return null
401
+ }
402
+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
403
+ warnings.push(`Skipping MCP server ${name}: url must be http(s) (got ${parsedUrl.protocol})`)
404
+ return null
405
+ }
406
+ // #6834 sharp edge, folded in pre-merge: the cloud-metadata service /
407
+ // link-local range is never a legitimate MCP server. Refused again at
408
+ // request time in MCPRemoteClient for configs that bypass this parser.
409
+ if (isBlockedMetadataHost(parsedUrl.hostname)) {
410
+ warnings.push(`Skipping MCP server ${name}: url targets a cloud-metadata / link-local address (refused)`)
411
+ return null
412
+ }
413
+ const rawType = typeof entry.type === 'string' ? entry.type.trim().toLowerCase() : ''
414
+ // 'sse' selects the legacy HTTP+SSE two-endpoint transport; everything else
415
+ // ('http', 'streamable-http', or an inferred remote with only a url) maps to
416
+ // the modern Streamable HTTP transport.
417
+ const type = rawType === 'sse' ? 'sse' : 'http'
418
+ return {
419
+ name,
420
+ type,
421
+ url,
422
+ headers: coerceHeaders(entry.headers, { warnings, serverName: name }),
423
+ }
424
+ }
425
+
81
426
  /**
82
427
  * Parse a Claude-style MCP config object.
83
428
  *
429
+ * Handles two server shapes (#6821):
430
+ * - stdio: `{ command, args, env }` — spawned as a local child process.
431
+ * - remote: `{ type: 'http'|'sse', url, headers }` — connected over the
432
+ * network. A remote entry is recognised by an explicit `type` of
433
+ * http/streamable-http/sse, or by carrying a `url` without a `command`.
434
+ *
84
435
  * @param {unknown} raw
85
- * @returns {{ servers: Array<{ name: string, command: string, args: string[], env: Record<string, string> }>, warnings: string[] }}
436
+ * @returns {{ servers: Array<object>, warnings: string[] }}
86
437
  */
87
438
  export function parseClaudeMcpConfig(raw) {
88
439
  const warnings = []
@@ -105,7 +456,29 @@ export function parseClaudeMcpConfig(raw) {
105
456
  warnings.push(`Skipping MCP server ${name}: entry must be an object`)
106
457
  continue
107
458
  }
108
- if (typeof entry.command !== 'string' || entry.command.length === 0) {
459
+ const rawType = typeof entry.type === 'string' ? entry.type.trim().toLowerCase() : ''
460
+ const hasCommand = typeof entry.command === 'string' && entry.command.length > 0
461
+ const hasUrl = typeof entry.url === 'string' && entry.url.trim().length > 0
462
+ const isRemote =
463
+ rawType === 'http' || rawType === 'streamable-http' || rawType === 'sse' || (!hasCommand && hasUrl)
464
+ // #7001 review: an entry carrying BOTH a command and a url is AMBIGUOUS —
465
+ // whichever branch wins, the other field is dropped and the caller is never
466
+ // told which transport it actually got. The read path stays lenient (it warns
467
+ // and still resolves a usable server, so a hand-edited config keeps working),
468
+ // but a WRITE escalates every warning to a rejection, so `add_mcp_server`
469
+ // refuses it rather than silently persisting one of the two shapes.
470
+ if (hasCommand && hasUrl) {
471
+ warnings.push(
472
+ `MCP server ${name}: ambiguous config — carries BOTH command (stdio) and url (remote); ` +
473
+ `resolving as ${isRemote ? 'remote (command ignored)' : 'stdio (url ignored)'}. Specify exactly one transport.`,
474
+ )
475
+ }
476
+ if (isRemote) {
477
+ const remote = parseRemoteEntry(name, entry, { warnings })
478
+ if (remote) servers.push(remote)
479
+ continue
480
+ }
481
+ if (!hasCommand) {
109
482
  warnings.push(`Skipping MCP server ${name}: command is required`)
110
483
  continue
111
484
  }
@@ -135,10 +508,10 @@ export function loadClaudeMcpConfig(filePath = defaultClaudeConfigPath()) {
135
508
  const stat = statSync(filePath)
136
509
  if (stat.size > CLAUDE_CONFIG_MAX_BYTES) {
137
510
  const warning = `MCP config ${filePath} exceeds size cap (${stat.size} bytes > ${CLAUDE_CONFIG_MAX_BYTES} bytes); skipping load`
138
- console.warn(`[byok-mcp-config] ${warning}`)
511
+ log.warn(warning)
139
512
  return { servers: [], warnings: [warning], missing: false }
140
513
  }
141
- const raw = JSON.parse(readFileSync(filePath, 'utf8'))
514
+ const raw = parseClaudeConfigText(readFileSync(filePath, 'utf8'))
142
515
  return { ...parseClaudeMcpConfig(raw), missing: false }
143
516
  } catch (err) {
144
517
  return {
@@ -150,6 +523,17 @@ export function loadClaudeMcpConfig(filePath = defaultClaudeConfigPath()) {
150
523
  }
151
524
 
152
525
  export function toMcpServerMetadata(server) {
526
+ // Remote transport (#6821): expose the transport type + a credential-stripped
527
+ // url + header KEY names only. Header values (bearer tokens, api keys) and any
528
+ // url userinfo/query never appear in metadata that could reach a log or wire.
529
+ if (typeof server.url === 'string' && server.url.length > 0) {
530
+ return Object.freeze({
531
+ name: server.name,
532
+ type: server.type || 'http',
533
+ url: redactMcpUrl(server.url),
534
+ headerKeys: Object.freeze(Object.keys(server.headers || {}).sort()),
535
+ })
536
+ }
153
537
  return Object.freeze({
154
538
  name: server.name,
155
539
  command: server.command,
@@ -157,3 +541,1323 @@ export function toMcpServerMetadata(server) {
157
541
  envKeys: Object.freeze(Object.keys(server.env).sort()),
158
542
  })
159
543
  }
544
+
545
+ /**
546
+ * Collect the NAMES of every configured MCP server in an `mcpServers` block,
547
+ * without the exec-oriented validation `parseClaudeMcpConfig` applies.
548
+ *
549
+ * `parseClaudeMcpConfig` is built for the byok stdio exec path — it requires a
550
+ * `command` and drops any entry without one. For pure VISIBILITY (#6820) we
551
+ * want every declared server by name, including remote/HTTP transports (which
552
+ * carry `url`/`type` instead of `command`). So this is deliberately lenient:
553
+ * any key mapping to a non-null object counts. Malformed entries accumulate a
554
+ * warning rather than throwing.
555
+ *
556
+ * @param {unknown} mcpBlock — the `mcpServers` object from a config source
557
+ * @param {{ warnings: string[], source: string }} ctx
558
+ * @returns {string[]} declared server names (order preserved)
559
+ */
560
+ function collectConfiguredNames(mcpBlock, { warnings, source }) {
561
+ const names = []
562
+ if (mcpBlock == null) return names
563
+ if (typeof mcpBlock !== 'object' || Array.isArray(mcpBlock)) {
564
+ warnings.push(`${source}: mcpServers must be an object`)
565
+ return names
566
+ }
567
+ for (const [name, entry] of Object.entries(mcpBlock)) {
568
+ if (!name) {
569
+ warnings.push(`${source}: skipping MCP server with empty name`)
570
+ continue
571
+ }
572
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
573
+ warnings.push(`${source}: skipping MCP server ${name} (entry must be an object)`)
574
+ continue
575
+ }
576
+ names.push(name)
577
+ }
578
+ return names
579
+ }
580
+
581
+ /**
582
+ * Resolve the project-scoped config block Claude Code stores under
583
+ * `projects[<realpath(cwd)>]` in `~/.claude.json`. Claude keys these by the
584
+ * realpath, so try that first and fall back to the literal `cwd` (a cwd that no
585
+ * longer resolves — e.g. a removed test tmp dir — still matches a literal key).
586
+ *
587
+ * @param {unknown} raw — parsed `~/.claude.json`
588
+ * @param {string} cwd
589
+ * @returns {object|null}
590
+ */
591
+ function resolveProjectBlock(raw, cwd) {
592
+ if (!cwd) return null
593
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
594
+ const projects = raw.projects
595
+ if (!projects || typeof projects !== 'object' || Array.isArray(projects)) return null
596
+ let realCwd = cwd
597
+ try {
598
+ realCwd = realpathSync(cwd)
599
+ } catch {
600
+ // cwd may not exist (tests / stale dir) — fall through to the literal key.
601
+ }
602
+ if (Object.prototype.hasOwnProperty.call(projects, realCwd)) return projects[realCwd]
603
+ if (Object.prototype.hasOwnProperty.call(projects, cwd)) return projects[cwd]
604
+ return null
605
+ }
606
+
607
+ /**
608
+ * #7939: closed vocabulary naming WHICH of the three config sources a
609
+ * discovered (or newly-added) MCP server came from. Threaded onto each spec
610
+ * `discoverMcpServerSpecs` returns and, from there, into the spawn-trust
611
+ * prompt payload (`requestMcpTrust`) — so a user approving a spawn can tell
612
+ * "my own machine-local config" from "a repository I just cloned" instead of
613
+ * every prompt looking identical regardless of provenance.
614
+ *
615
+ * Deliberately three fixed values, never a raw file path: a path is
616
+ * unbounded free-form text (and on the wire schema below is typed as a
617
+ * closed `z.enum`, not `z.string`), and the three values already say
618
+ * everything the prompt needs — "your machine", "this repo", or "your user
619
+ * profile".
620
+ *
621
+ * - LOCAL — `~/.claude.json` → `projects[<cwd>].mcpServers`.
622
+ * Claude Code's "Local" scope: private to this
623
+ * machine + cwd.
624
+ * - PROJECT_MCP_JSON — `<cwd>/.mcp.json`. Claude Code's "Project" scope:
625
+ * checked into the repo and shared with the team —
626
+ * REPO-CONTROLLED, so this is the value the trust
627
+ * prompt flags most visibly.
628
+ * - USER — `~/.claude.json` → root `mcpServers`. Claude Code's
629
+ * "User" scope: available across every project on
630
+ * this machine.
631
+ *
632
+ * Note the naming collision this deliberately avoids: the READ side's
633
+ * internal `source` strings below say "project config mcpServers" for the
634
+ * "Local" scope and "project .mcp.json mcpServers" for the "Project" scope
635
+ * (both use the word "project" for different things), while the WRITE side's
636
+ * `MCP_WRITE_SCOPES` calls the very same "Local" scope `'project'` (see
637
+ * `mcpWriteScopeToSource`). Neither internal vocabulary is fit to show a
638
+ * user — this enum is the one vocabulary both map onto.
639
+ */
640
+ export const MCP_SERVER_SOURCE = Object.freeze({
641
+ LOCAL: 'local',
642
+ PROJECT_MCP_JSON: 'project-mcp-json',
643
+ USER: 'user',
644
+ })
645
+
646
+ /** Ordered value list — for schema/enum construction and validation. */
647
+ export const MCP_SERVER_SOURCE_VALUES = Object.freeze(Object.values(MCP_SERVER_SOURCE))
648
+
649
+ /**
650
+ * Map an `addMcpServer` WRITE scope (`MCP_WRITE_SCOPES`: `'user' | 'project'`)
651
+ * onto the same `MCP_SERVER_SOURCE` vocabulary the READ side uses (#7939), so
652
+ * a spawn-trust prompt for a server the user is actively adding right now
653
+ * names its scope with the identical word a rediscovered one would carry
654
+ * after a restart.
655
+ *
656
+ * Write scope `'project'` targets `projects[<realpath(cwd)>].mcpServers`
657
+ * (see `prepareAddMcpServer` below) — the READ side's "Local" scope, NOT
658
+ * `.mcp.json` (which is not a writable scope at all; see the comment above
659
+ * `MCP_WRITE_SCOPES`). Write scope `'user'` (the default) targets the root
660
+ * `mcpServers` block — the READ side's "User" scope.
661
+ *
662
+ * @param {string} scope — an `MCP_WRITE_SCOPES` value
663
+ * @returns {string} an `MCP_SERVER_SOURCE` value
664
+ */
665
+ export function mcpWriteScopeToSource(scope) {
666
+ return scope === 'project' ? MCP_SERVER_SOURCE.LOCAL : MCP_SERVER_SOURCE.USER
667
+ }
668
+
669
+ /**
670
+ * #7028: the inverse of `mcpWriteScopeToSource` — map a READ-side
671
+ * `MCP_SERVER_SOURCE` onto the `MCP_WRITE_SCOPES` value that REMOVES a server
672
+ * defined there, for the `scope` field on each `mcp_servers` wire entry.
673
+ *
674
+ * The wire vocabulary is the write one on purpose: `remove_mcp_server` is
675
+ * scope-exact (a wrong scope reports `MCP_SERVER_NOT_FOUND`), and the field
676
+ * exists so a client can hand it straight back.
677
+ *
678
+ * - LOCAL → 'project' (`projects[<cwd>].mcpServers`)
679
+ * - USER → 'user' (root `mcpServers`)
680
+ * - PROJECT_MCP_JSON → undefined (`<cwd>/.mcp.json` is not a writable scope,
681
+ * so no remove could name it)
682
+ * - anything else → undefined (an unknown/absent source is never guessed)
683
+ *
684
+ * @param {string | undefined} source — an `MCP_SERVER_SOURCE` value, if known
685
+ * @returns {'user' | 'project' | undefined}
686
+ */
687
+ export function mcpSourceToWriteScope(source) {
688
+ if (source === MCP_SERVER_SOURCE.USER) return 'user'
689
+ if (source === MCP_SERVER_SOURCE.LOCAL) return 'project'
690
+ return undefined
691
+ }
692
+
693
+ /**
694
+ * Read the three MCP config sources Claude Code itself reads, in a single
695
+ * pass, in Claude Code's documented scope-precedence order (highest to
696
+ * lowest), per https://code.claude.com/docs/en/mcp, "Scope Hierarchy and
697
+ * Precedence" (read 2026-09-24): "When the same server is defined in more
698
+ * than one place, Claude Code connects to it once, using the definition
699
+ * from the highest-precedence source."
700
+ *
701
+ * 1. "Local" scope — `projects[<realpath(cwd)>].mcpServers` in
702
+ * `~/.claude.json`. Private to this cwd.
703
+ * 2. "Project" scope — `mcpServers` in `<cwd>/.mcp.json`, checked into the
704
+ * repo and shared with the team.
705
+ * 3. "User" scope — `mcpServers` at the root of `~/.claude.json`,
706
+ * available across every project on this machine.
707
+ *
708
+ * Both `discoverConfiguredMcpServers` (name-only, lenient, for claude-tui's
709
+ * display) and `discoverMcpServerSpecs` (full spec, exec-validated, for the
710
+ * BYOK spawn path) call this ONE function to enumerate sources, so the order
711
+ * a duplicated name resolves in can never drift between "what the user is
712
+ * told is configured" and "what actually spawns" — only the per-entry
713
+ * validation strictness differs between the two callers (#7112 review: a
714
+ * pre-#7112 version of this file had two independently-hand-rolled orderings
715
+ * that had drifted to be exact opposites of each other).
716
+ *
717
+ * Never throws: each read is guarded and a parse failure is reported via
718
+ * `warnings` on the returned object, so a corrupt config can't take down
719
+ * session start.
720
+ *
721
+ * @param {string} cwd — the session's working directory
722
+ * @param {string} configPath — resolved `~/.claude.json` path (or override)
723
+ * @returns {{ sources: Array<{ mcpServers: unknown, source: string }>, warnings: string[] }}
724
+ */
725
+ function readMcpSourcesInPrecedenceOrder(cwd, configPath) {
726
+ const warnings = []
727
+ const sources = []
728
+
729
+ const readJson = (filePath, source) => {
730
+ try {
731
+ // statSync before readFileSync so a pathologically large file (see
732
+ // CLAUDE_CONFIG_MAX_BYTES) doesn't block session start. statSync
733
+ // follows symlinks (as does readFileSync below), consistent with
734
+ // every other read in this file — see writeClaudeConfigAtomic's
735
+ // header comment for why WRITES are guarded but reads are not.
736
+ //
737
+ // isFile() guard: `.mcp.json` is repo-controlled, attacker-influenceable
738
+ // content (a cloned repo can make it a symlink to anything). A symlink
739
+ // to a FIFO or character device (e.g. `/dev/zero`) reports a `size` that
740
+ // is meaningless for this purpose — a FIFO with no writer hangs
741
+ // readFileSync indefinitely (before the trust gate even runs), and a
742
+ // device like `/dev/zero` has no real EOF, so the size cap above never
743
+ // triggers. Only a REGULAR file (following symlinks to their target,
744
+ // same as the size check) is ever read. Mirrors writeClaudeConfigAtomic's
745
+ // `target.isFile()` check on the write side.
746
+ const stat = statSync(filePath)
747
+ if (!stat.isFile()) {
748
+ warnings.push(`MCP config ${filePath} is not a regular file; skipping load`)
749
+ return null
750
+ }
751
+ if (stat.size > CLAUDE_CONFIG_MAX_BYTES) {
752
+ warnings.push(
753
+ `MCP config ${filePath} exceeds size cap (${stat.size} bytes > ${CLAUDE_CONFIG_MAX_BYTES} bytes); skipping load`,
754
+ )
755
+ return null
756
+ }
757
+ return parseClaudeConfigText(readFileSync(filePath, 'utf8'))
758
+ } catch (err) {
759
+ warnings.push(`Failed to parse MCP config ${filePath} (${source}): ${err?.message || String(err)}`)
760
+ return null
761
+ }
762
+ }
763
+
764
+ let userRaw = null
765
+ if (configPath && existsSync(configPath)) {
766
+ userRaw = readJson(configPath, 'user config')
767
+ if (userRaw != null && (typeof userRaw !== 'object' || Array.isArray(userRaw))) {
768
+ userRaw = null
769
+ }
770
+ }
771
+
772
+ // 1 — "Local" scope (highest precedence): projects[<realpath(cwd)>].mcpServers.
773
+ if (userRaw) {
774
+ const projectBlock = resolveProjectBlock(userRaw, cwd)
775
+ if (projectBlock && typeof projectBlock === 'object' && !Array.isArray(projectBlock)) {
776
+ sources.push({
777
+ mcpServers: projectBlock.mcpServers,
778
+ source: 'project config mcpServers',
779
+ sourceKind: MCP_SERVER_SOURCE.LOCAL,
780
+ })
781
+ }
782
+ }
783
+
784
+ // 2 — "Project" scope: <cwd>/.mcp.json, checked into the repo. cwd may not
785
+ // exist (removed tmp dir, stale worktree) — join+existsSync just reports
786
+ // false rather than throwing.
787
+ if (cwd) {
788
+ const mcpJsonPath = join(cwd, '.mcp.json')
789
+ if (existsSync(mcpJsonPath)) {
790
+ const raw = readJson(mcpJsonPath, 'project .mcp.json')
791
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
792
+ sources.push({
793
+ mcpServers: raw.mcpServers,
794
+ source: 'project .mcp.json mcpServers',
795
+ sourceKind: MCP_SERVER_SOURCE.PROJECT_MCP_JSON,
796
+ })
797
+ }
798
+ }
799
+ }
800
+
801
+ // 3 — "User" scope (lowest precedence): root mcpServers in ~/.claude.json.
802
+ if (userRaw) {
803
+ sources.push({
804
+ mcpServers: userRaw.mcpServers,
805
+ source: 'user config mcpServers',
806
+ sourceKind: MCP_SERVER_SOURCE.USER,
807
+ })
808
+ }
809
+
810
+ return { sources, warnings }
811
+ }
812
+
813
+ /**
814
+ * Discover the CONFIGURED (not live-connected) MCP servers a Claude Code
815
+ * session running in `cwd` would load. This is the honest fallback the
816
+ * claude-tui provider uses (#6820): the interactive TUI communicates over a
817
+ * PTY + hook payloads and exposes NO runtime MCP status, unlike the SDK/CLI
818
+ * stream-json `system/init` event that carries live `mcp_servers` with real
819
+ * connection status. So the TUI path can only report what the config DECLARES.
820
+ *
821
+ * Merges the three sources `readMcpSourcesInPrecedenceOrder` enumerates,
822
+ * deduped by name (first source wins on a name collision — see that
823
+ * function for the precedence order and why it is shared with
824
+ * `discoverMcpServerSpecs`). Entry validation here is deliberately LENIENT
825
+ * (any object counts as "configured", even one `discoverMcpServerSpecs`
826
+ * would reject as unspawnable) because this path is display-only visibility,
827
+ * not a spawn decision.
828
+ *
829
+ * Never throws: each read is guarded and failures accumulate as warnings, so a
830
+ * corrupt config can't take down session start.
831
+ *
832
+ * @param {string} cwd — the session's working directory
833
+ * @param {{ configPath?: string }} [opts]
834
+ * @returns {{ servers: Array<{ name: string }>, warnings: string[] }}
835
+ */
836
+ export function discoverConfiguredMcpServers(cwd, { configPath = defaultClaudeConfigPath() } = {}) {
837
+ const { sources, warnings } = readMcpSourcesInPrecedenceOrder(cwd, configPath)
838
+ const byName = new Map()
839
+ for (const { mcpServers, source } of sources) {
840
+ for (const name of collectConfiguredNames(mcpServers, { warnings, source })) {
841
+ if (!byName.has(name)) byName.set(name, { name })
842
+ }
843
+ }
844
+ return { servers: [...byName.values()], warnings }
845
+ }
846
+
847
+ /**
848
+ * #7112: `discoverConfiguredMcpServers` above returns declared NAMES only —
849
+ * built for claude-tui's read-only display, lenient about entry shape (any
850
+ * object counts). The BYOK spawn path (`byok-session.js`) needs full,
851
+ * SPAWNABLE specs: the same exec-oriented validation `parseClaudeMcpConfig`
852
+ * applies (command/url/transport disambiguation, arg/env coercion), resolved
853
+ * across the SAME three config sources, via the SAME
854
+ * `readMcpSourcesInPrecedenceOrder` ordering `discoverConfiguredMcpServers`
855
+ * uses — so the two can never independently drift on WHICH source wins a
856
+ * name collision again.
857
+ *
858
+ * Never throws: each source is read defensively and a parse failure
859
+ * accumulates as a warning, so a corrupt config can't take down session
860
+ * start (mirrors `discoverConfiguredMcpServers` / `loadClaudeMcpConfig`).
861
+ *
862
+ * #7939: every returned spec also carries `source` (an `MCP_SERVER_SOURCE`
863
+ * value) naming which of the three scopes it was resolved from — threaded
864
+ * through to the spawn-trust prompt so an approval can tell "my own config"
865
+ * from "a repository I just cloned" apart. Attached here (not inside
866
+ * `parseClaudeMcpConfig`, which is scope-agnostic and reused by the write
867
+ * path) so the dedup-by-name loop below tags each winning spec with the
868
+ * SAME source its winning `sources` entry carries — a spec picked from the
869
+ * "Local" scope is never mislabeled "User" just because `parseClaudeMcpConfig`
870
+ * doesn't know about scopes.
871
+ *
872
+ * @param {string} cwd — the session's working directory
873
+ * @param {{ configPath?: string }} [opts]
874
+ * @returns {{ servers: Array<object>, warnings: string[] }}
875
+ */
876
+ export function discoverMcpServerSpecs(cwd, { configPath = defaultClaudeConfigPath() } = {}) {
877
+ const { sources, warnings } = readMcpSourcesInPrecedenceOrder(cwd, configPath)
878
+ const byName = new Map()
879
+ for (const { mcpServers, sourceKind } of sources) {
880
+ const parsed = parseClaudeMcpConfig({ mcpServers })
881
+ for (const spec of parsed.servers) {
882
+ if (!byName.has(spec.name)) byName.set(spec.name, { ...spec, source: sourceKind })
883
+ }
884
+ warnings.push(...parsed.warnings)
885
+ }
886
+ return { servers: [...byName.values()], warnings }
887
+ }
888
+
889
+ // ---------------------------------------------------------------------------
890
+ // #6974 — MCP server add/remove (config MUTATION).
891
+ //
892
+ // Everything above this line READS. This section is the only write path into
893
+ // `~/.claude.json`, a file this module's header explicitly calls out as "owned
894
+ // by Claude Code, not by us". We are a guest in someone else's file, so the
895
+ // rules below are deliberately conservative:
896
+ //
897
+ // 1. READ-MODIFY-WRITE, never generate. We parse the whole file, touch only
898
+ // the one `mcpServers` key we were asked to, and write the rest back
899
+ // byte-equivalent. Any key Claude Code owns (projects, history,
900
+ // oauthAccount, …) survives untouched.
901
+ // 2. BAIL on a malformed file — never clobber. If the existing config is
902
+ // unparseable we refuse the mutation with a clear error rather than
903
+ // "recovering" by overwriting it with a fresh object. A user whose config
904
+ // we cannot read is a user whose config we must not destroy.
905
+ // 3. ATOMIC + durable write (temp file + fsync + rename + parent-dir fsync).
906
+ // A crash mid-write leaves the original file intact, never a truncated
907
+ // one. See writeClaudeConfigAtomic for the mode-preservation rationale.
908
+ // 4. Persist only NORMALIZED entries. What lands on disk is rebuilt from
909
+ // `parseClaudeMcpConfig`'s output, not copied from the caller's payload,
910
+ // so a client cannot inject arbitrary keys into the user's config.
911
+ //
912
+ // Note on execution: adding a server does NOT itself execute anything. The
913
+ // live-fleet wiring (byok-mcp-fleet `addServer`) spawns through the SAME
914
+ // first-use trust gate as any other server, so the user still gets the
915
+ // `requestMcpTrust` prompt before a new command runs (#4457).
916
+ // ---------------------------------------------------------------------------
917
+
918
+ /**
919
+ * Charset for a NEWLY ADDED MCP server name: a lowercase identifier — leading
920
+ * lowercase letter, then lowercase letters / digits / dash / underscore, max 64
921
+ * chars. Mirrors the `PROVIDER_ID_RE` "lowercase identifier" rule in
922
+ * anthropic-compatible-config.js, widened by `_` because real MCP server names
923
+ * use it (`ccd_session_mgmt`).
924
+ *
925
+ * Being a strict allow-list, this also forecloses a family of problems for free:
926
+ * no `.` or `/` (so a name can never read as a path or traverse), no uppercase
927
+ * (so two names can't collide case-insensitively), and no whitespace/control
928
+ * characters (so a name can't be visually spoofed in the picker).
929
+ *
930
+ * #7030 — single-sourced from @chroxy/protocol/mcp-validation (imported
931
+ * above); re-exported here since nothing else in this file changes shape.
932
+ */
933
+ export { MCP_SERVER_NAME_RE }
934
+
935
+ /**
936
+ * Names that must never be used as an object key we assign into, regardless of
937
+ * charset — assigning these shadows or mutates object internals. `__proto__` is
938
+ * already refused by MCP_SERVER_NAME_RE (leading `_`), but `constructor` and
939
+ * `prototype` are pure lowercase letters and WOULD pass it, so they are refused
940
+ * explicitly here. Also applied on the removal path, which uses a laxer charset.
941
+ *
942
+ * #7030 — single-sourced as `UNSAFE_MCP_KEYS` (same Set as the env/headers
943
+ * check above); kept as a local alias so the name-specific call sites below
944
+ * read unchanged.
945
+ */
946
+ const UNSAFE_MCP_SERVER_NAMES = UNSAFE_MCP_KEYS
947
+
948
+ /**
949
+ * Upper bound on a removable name. Removal accepts a much laxer charset than
950
+ * `add` (see validateMcpServerNameForRemoval) so a server the `claude` CLI
951
+ * created under a name Chroxy would not have minted is still removable.
952
+ */
953
+ const MCP_SERVER_NAME_MAX = 256
954
+
955
+ /**
956
+ * Validate a name for ADDING a server: the strict lowercase-identifier rule.
957
+ *
958
+ * Beyond the charset there is one non-obvious hard constraint: the name must not
959
+ * contain `__`. MCP tools are namespaced on the wire as `mcp__<server>__<tool>`
960
+ * and `parseMcpToolName` (src/mcp-tools.js) splits on the FIRST `__` after the
961
+ * prefix — so a server named `a__b` would have its tools parsed as server `a`,
962
+ * tool `b__…`, silently routing calls to the wrong (or a nonexistent) server.
963
+ * Refuse it at the door rather than persisting a name that mis-routes.
964
+ *
965
+ * @param {unknown} name
966
+ * @returns {{ ok: true, name: string } | { ok: false, error: string }}
967
+ */
968
+ export function validateNewMcpServerName(name) {
969
+ if (typeof name !== 'string' || name.length === 0) {
970
+ return { ok: false, error: 'MCP server name is required' }
971
+ }
972
+ if (UNSAFE_MCP_SERVER_NAMES.has(name)) {
973
+ return { ok: false, error: `MCP server name '${name}' is reserved` }
974
+ }
975
+ if (!MCP_SERVER_NAME_RE.test(name)) {
976
+ return {
977
+ ok: false,
978
+ error:
979
+ `Invalid MCP server name ${JSON.stringify(name)}: expected a lowercase identifier ` +
980
+ '(letters, digits, dash, underscore; must start with a letter, max 64 chars)',
981
+ }
982
+ }
983
+ if (containsMcpToolNamespaceSeparator(name)) {
984
+ return {
985
+ ok: false,
986
+ error:
987
+ `Invalid MCP server name ${JSON.stringify(name)}: '__' is the MCP tool-namespace ` +
988
+ 'separator (mcp__<server>__<tool>) and would mis-route this server\'s tools',
989
+ }
990
+ }
991
+ return { ok: true, name }
992
+ }
993
+
994
+ /**
995
+ * Validate a name for REMOVING a server. Deliberately laxer than the add rule:
996
+ * a server configured by the `claude` CLI (or hand-edited) may carry a name
997
+ * Chroxy would never mint — uppercase, dots, whatever — and the user must still
998
+ * be able to remove it. So this only refuses what is genuinely unsafe to use as
999
+ * a lookup/delete key: empty, over-long, control characters, or a reserved key.
1000
+ * Removal cannot create anything, so no charset policy is warranted.
1001
+ *
1002
+ * @param {unknown} name
1003
+ * @returns {{ ok: true, name: string } | { ok: false, error: string }}
1004
+ */
1005
+ export function validateMcpServerNameForRemoval(name) {
1006
+ if (typeof name !== 'string' || name.length === 0) {
1007
+ return { ok: false, error: 'MCP server name is required' }
1008
+ }
1009
+ if (name.length > MCP_SERVER_NAME_MAX) {
1010
+ return { ok: false, error: `MCP server name exceeds ${MCP_SERVER_NAME_MAX} characters` }
1011
+ }
1012
+ if (UNSAFE_MCP_SERVER_NAMES.has(name)) {
1013
+ return { ok: false, error: `MCP server name '${name}' is reserved` }
1014
+ }
1015
+ if (/[\x00-\x1f\x7f]/.test(name)) {
1016
+ return { ok: false, error: 'MCP server name must not contain control characters' }
1017
+ }
1018
+ return { ok: true, name }
1019
+ }
1020
+
1021
+ /**
1022
+ * Validate + normalize a proposed server config into the exact object to
1023
+ * persist. Validation is delegated to `parseClaudeMcpConfig` — the SAME parser
1024
+ * the read path uses — by round-tripping a single-entry probe block through it,
1025
+ * so a config we accept for writing is by construction a config we can read
1026
+ * back. Two deliberate tightenings over the read path:
1027
+ *
1028
+ * - the read path is LENIENT (it coerces a bad `args[3]` away with a warning
1029
+ * and carries on, because a partly-usable config beats no session). A WRITE
1030
+ * must not silently persist something other than what the user asked for, so
1031
+ * ANY warning is escalated to a rejection.
1032
+ * - the persisted entry is rebuilt from the parser's normalized output, so
1033
+ * unknown/extra keys in the caller's payload are dropped rather than written
1034
+ * into the user's config.
1035
+ *
1036
+ * @param {string} name — already validated by validateNewMcpServerName
1037
+ * @param {unknown} config
1038
+ * @returns {{ ok: true, entry: object } | { ok: false, error: string }}
1039
+ */
1040
+ export function normalizeMcpServerConfig(name, config) {
1041
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {
1042
+ return { ok: false, error: 'MCP server config must be an object' }
1043
+ }
1044
+ // A computed key always defines an OWN property (unlike a literal
1045
+ // `__proto__:`), and `name` is validated upstream, so this probe cannot be
1046
+ // turned into a prototype write.
1047
+ const { servers, warnings } = parseClaudeMcpConfig({ mcpServers: { [name]: config } })
1048
+ if (servers.length !== 1) {
1049
+ return {
1050
+ ok: false,
1051
+ error: warnings[0] || `config for '${name}' is not a usable MCP server entry`,
1052
+ }
1053
+ }
1054
+ if (warnings.length > 0) return { ok: false, error: warnings[0] }
1055
+
1056
+ const parsed = servers[0]
1057
+ // Remote (http/sse) transport — persist type + url + non-empty headers only.
1058
+ if (typeof parsed.url === 'string' && parsed.url.length > 0) {
1059
+ const entry = { type: parsed.type, url: parsed.url }
1060
+ if (Object.keys(parsed.headers || {}).length > 0) entry.headers = { ...parsed.headers }
1061
+ return { ok: true, entry }
1062
+ }
1063
+ // stdio transport — persist command + non-empty args/env only, so a minimal
1064
+ // add produces a minimal diff in the user's file.
1065
+ const entry = { command: parsed.command }
1066
+ if (parsed.args.length > 0) entry.args = [...parsed.args]
1067
+ if (Object.keys(parsed.env || {}).length > 0) entry.env = { ...parsed.env }
1068
+ return { ok: true, entry }
1069
+ }
1070
+
1071
+ /**
1072
+ * Read `~/.claude.json` for a read-modify-write cycle.
1073
+ *
1074
+ * Unlike `loadClaudeMcpConfig` (which fails OPEN — a corrupt config yields an
1075
+ * empty server list so session start survives), this fails CLOSED: a file we
1076
+ * cannot parse is a file we must not overwrite, so every unreadable/malformed
1077
+ * case returns `ok: false` and the caller aborts the mutation. A MISSING file is
1078
+ * not an error — it is the first-write case and yields an empty object.
1079
+ *
1080
+ * @param {string} filePath
1081
+ * @returns {{ ok: true, raw: object, mode: number|null, existed: boolean, hash: string|null } | { ok: false, error: string }}
1082
+ * `hash` is the sha256 of the bytes parsed (null for a missing file): the snapshot
1083
+ * identity `writeClaudeConfigAtomic`'s `expect` compares against (#8983).
1084
+ */
1085
+ export function readClaudeConfigForMutation(filePath) {
1086
+ if (!filePath) return { ok: false, error: 'No Claude config path resolved' }
1087
+ if (!existsSync(filePath)) {
1088
+ // First write — we create the file. `mode: null` tells the writer to use a
1089
+ // fresh-file default (0600) rather than preserving anything.
1090
+ return { ok: true, raw: {}, mode: null, existed: false, hash: null }
1091
+ }
1092
+ let stat
1093
+ try {
1094
+ stat = statSync(filePath)
1095
+ } catch (err) {
1096
+ return { ok: false, error: `Cannot stat ${filePath}: ${err?.message || String(err)}` }
1097
+ }
1098
+ if (stat.size > CLAUDE_CONFIG_MAX_BYTES) {
1099
+ return {
1100
+ ok: false,
1101
+ error: `Config ${filePath} exceeds the ${CLAUDE_CONFIG_MAX_BYTES}-byte cap (${stat.size} bytes); refusing to rewrite it`,
1102
+ }
1103
+ }
1104
+ let text
1105
+ let hash
1106
+ try {
1107
+ // Read BYTES and hash those, so the pre-rename re-check (which also hashes
1108
+ // bytes) compares like with like even for a file that is not valid UTF-8.
1109
+ const bytes = readFileSync(filePath)
1110
+ hash = hashConfigBytes(bytes)
1111
+ text = bytes.toString('utf8')
1112
+ } catch (err) {
1113
+ return { ok: false, error: `Cannot read ${filePath}: ${err?.message || String(err)}` }
1114
+ }
1115
+ let raw
1116
+ try {
1117
+ raw = parseClaudeConfigText(text)
1118
+ } catch {
1119
+ // The parser's message can quote surrounding bytes (which may include a
1120
+ // token from elsewhere in the file), so it is deliberately NOT echoed.
1121
+ return {
1122
+ ok: false,
1123
+ invalidJson: true,
1124
+ error: `Config ${filePath} is not valid JSON; refusing to overwrite it. Fix or move the file, then retry.`,
1125
+ }
1126
+ }
1127
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
1128
+ return { ok: false, error: `Config ${filePath} root must be a JSON object; refusing to overwrite it` }
1129
+ }
1130
+ return { ok: true, raw, mode: stat.mode & 0o777, existed: true, hash }
1131
+ }
1132
+
1133
+ /**
1134
+ * #7002 — resolve the path the atomic write must actually LAND on.
1135
+ *
1136
+ * The write is `writeFileSync(tmp)` → `renameSync(tmp, dest)`, and `rename(2)`
1137
+ * replaces the FINAL PATH COMPONENT itself. If that component is a symlink — the
1138
+ * common dotfiles-repo arrangement, `~/.claude.json` → `~/dotfiles/claude.json` —
1139
+ * the rename destroys the LINK and leaves a regular file in its place: the user's
1140
+ * dotfiles link silently disappears and their real config stops receiving
1141
+ * updates. (The read path follows the link, so nothing complains.) So a symlinked
1142
+ * destination must be resolved to its target and written THERE.
1143
+ *
1144
+ * TRUST ASSUMPTION, stated plainly: `~/.claude.json` and any link the user has
1145
+ * put in its place are USER-OWNED, USER-AUTHORED configuration. We follow the
1146
+ * link because a user who symlinked their own config meant it. What we do NOT do
1147
+ * is follow it blindly — resolving a symlink and writing to whatever it points at
1148
+ * is precisely how a planted link turns "write my config" into "write an arbitrary
1149
+ * file", so the resolved target must satisfy all of:
1150
+ *
1151
+ * - it resolves at all (a DANGLING link is refused, not materialized — creating
1152
+ * the missing target would be us inventing a file at an attacker-chosen path)
1153
+ * - it is a REGULAR file (no directory, fifo, socket or device)
1154
+ * - it is owned by the uid we run as (a link into another user's file is refused)
1155
+ *
1156
+ * RACE HONESTY: resolution happens ONCE, and the subsequent `rename` re-walks the
1157
+ * path by name, so an attacker who can replace the link between the two syscalls
1158
+ * can still redirect the write (classic TOCTOU). This is NOT closed here — POSIX
1159
+ * offers no "rename onto this exact inode" primitive to close it with. The
1160
+ * residual exposure requires write access to the user's own `$HOME`, which is
1161
+ * already game over for a config the daemon reads and executes commands from;
1162
+ * see the follow-up issue referenced in the PR for a fully race-free design.
1163
+ *
1164
+ * @param {string} filePath
1165
+ * @returns {{ ok: true, path: string, viaSymlink: boolean } | { ok: false, error: string }}
1166
+ */
1167
+ export function resolveClaudeConfigWritePath(filePath) {
1168
+ let link
1169
+ try {
1170
+ link = lstatSync(filePath)
1171
+ } catch {
1172
+ // Missing (the first-write case) or unstattable — write the path as given,
1173
+ // exactly as before this fix.
1174
+ return { ok: true, path: filePath, viaSymlink: false }
1175
+ }
1176
+ if (!link.isSymbolicLink()) return { ok: true, path: filePath, viaSymlink: false }
1177
+
1178
+ let resolved
1179
+ try {
1180
+ resolved = realpathSync(filePath)
1181
+ } catch (err) {
1182
+ return {
1183
+ ok: false,
1184
+ error: `${filePath} is a symlink whose target cannot be resolved (${err?.code || err?.message || String(err)}); refusing to replace the link with a regular file. Fix or remove the link, then retry.`,
1185
+ }
1186
+ }
1187
+ let target
1188
+ try {
1189
+ target = lstatSync(resolved)
1190
+ } catch (err) {
1191
+ return {
1192
+ ok: false,
1193
+ error: `${filePath} is a symlink to ${resolved}, which cannot be stat'd (${err?.code || err?.message || String(err)}); refusing to write through it.`,
1194
+ }
1195
+ }
1196
+ if (!target.isFile()) {
1197
+ return {
1198
+ ok: false,
1199
+ error: `${filePath} is a symlink to ${resolved}, which is not a regular file; refusing to write through it.`,
1200
+ }
1201
+ }
1202
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
1203
+ if (uid !== null && target.uid !== uid) {
1204
+ return {
1205
+ ok: false,
1206
+ error: `${filePath} is a symlink to ${resolved}, which is owned by uid ${target.uid} rather than uid ${uid}; refusing to write through it.`,
1207
+ }
1208
+ }
1209
+ return { ok: true, path: resolved, viaSymlink: true }
1210
+ }
1211
+
1212
+ /**
1213
+ * #7002 — the residual risk of PRESERVING a destination's mode.
1214
+ *
1215
+ * `writeClaudeConfigAtomic` deliberately does not force 0600 on a file the user
1216
+ * (or Claude Code) already owns. That is the right call for permissions, but it
1217
+ * leaves one case where Chroxy is the party making things worse: an existing
1218
+ * config that is group/world-readable, plus a new entry carrying `env` or
1219
+ * `headers` — the two fields that routinely hold API tokens. We do not silently
1220
+ * re-permission the file; we say so loudly instead, naming the file and its mode,
1221
+ * so the user can tighten it themselves.
1222
+ *
1223
+ * Returns `null` when there is nothing to warn about (owner-only mode, no
1224
+ * secret-bearing field, or a file WE created — those get 0600). The message never
1225
+ * echoes a secret VALUE, only the field names.
1226
+ *
1227
+ * @param {{ filePath: string, mode: number|null|undefined, entry: object }} args
1228
+ * @returns {string|null}
1229
+ */
1230
+ export function describeConfigModeSecretWarning({ filePath, mode, entry } = {}) {
1231
+ if (mode === null || mode === undefined) return null
1232
+ // The trigger is the WHOLE `0o077` superset, not just the read bits, and the
1233
+ // wording says "accessible" rather than "readable" to match it (review of
1234
+ // #7040). Group/other WRITE is the sharper edge, not a lesser one: another
1235
+ // local user who can rewrite `~/.claude.json` substitutes MCP server commands
1236
+ // the daemon then spawns. Including the (meaningless-on-a-JSON-file) execute
1237
+ // bit costs at most a harmless false positive on a pathological mode like
1238
+ // 0o611, which is the right side to err on for a security advisory.
1239
+ const otherBits = mode & 0o077
1240
+ if (otherBits === 0) return null
1241
+ const fields = ['env', 'headers'].filter((key) => {
1242
+ const value = entry?.[key]
1243
+ return value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0
1244
+ })
1245
+ if (fields.length === 0) return null
1246
+ const octal = (mode & 0o777).toString(8).padStart(3, '0')
1247
+ return (
1248
+ `${filePath} is mode ${octal} (accessible beyond its owner) and the MCP server entry just added carries ` +
1249
+ `${fields.join(' and ')}, which commonly hold API tokens. Chroxy preserved the file's existing permissions ` +
1250
+ `rather than changing them — tighten it yourself with: chmod 600 ${filePath}`
1251
+ )
1252
+ }
1253
+
1254
+ /**
1255
+ * Atomically write the mutated config back.
1256
+ *
1257
+ * temp file → exact mode → fsync(file) → rename → fsync(parent dir), the same
1258
+ * shape as `writeFileRestricted(..., { durable: true })` in platform.js, with
1259
+ * one deliberate difference: this PRESERVES the destination's existing mode
1260
+ * instead of forcing 0600. `~/.claude.json` belongs to Claude Code; silently
1261
+ * re-permissioning a user's file as a side effect of "add an MCP server" is not
1262
+ * ours to do. A file we CREATE gets 0600 (it can hold OAuth material).
1263
+ *
1264
+ * The write is durable (fsync before rename, dir fsync after) on BOTH add and
1265
+ * remove. Remove is the load-bearing case — it is a capability REDUCTION, and
1266
+ * the #6914/#6927 precedent is that a security-tightening write must survive
1267
+ * power loss rather than silently reappearing after a crash. Add rides the same
1268
+ * path because one code path is cheaper to keep correct than two, and the cost
1269
+ * (one fsync of a few KB, on an operation a user performs rarely) is noise.
1270
+ *
1271
+ * A SYMLINKED destination is written THROUGH (the link survives, its target gets
1272
+ * the bytes) or refused — never replaced. See `resolveClaudeConfigWritePath` for
1273
+ * the trust assumption and the race caveat (#7002).
1274
+ *
1275
+ * SHARED, not byok-local: `claude-tui/pty-driver.js`'s `ensureCwdTrusted` (the
1276
+ * DEFAULT provider's trust pre-write, which runs on far more start()s than any
1277
+ * MCP mutation) commits through this function too (#7046). Callers that need
1278
+ * "best effort" — a refusal must not fail session start — catch and log; callers
1279
+ * that owe the user an answer surface the error.
1280
+ *
1281
+ * #7054: the post-rename directory fsync no longer THROWS. The rename has
1282
+ * already published the file, so a dir-fsync failure means the write LANDED and
1283
+ * only its directory entry's durability is unproven — throwing reported a landed
1284
+ * write as failed (#7067). It is returned instead; callers on a
1285
+ * capability-REDUCTION path propagate it (see `removeMcpServerFromConfig`).
1286
+ *
1287
+ * @param {string} filePath
1288
+ * @param {object} value — the full config object to serialize
1289
+ * @param {{ mode: number|null, expect?: { path?: string, existed: boolean, hash: string|null, mode?: number|null }, _fsync?: Function }} opts — `null` mode = new file, use 0600.
1290
+ * `expect` (#8983) is the snapshot the value was merged from: when given, the destination is re-read just
1291
+ * before the rename and a `ClaudeConfigConflictError` is thrown (temp discarded, file untouched) if it differs.
1292
+ * Production code does not pass it directly — it goes through `updateClaudeConfig`, which owns the retry loop.
1293
+ * `_fsync` is a TEST-ONLY seam (#7070): `(target, { isDir }) => void`, the same
1294
+ * shape as `confirmRenameDurable`'s `fsync`, defaulting to the real
1295
+ * `fsyncForDurability`. BOTH the temp-file fsync and the post-rename directory
1296
+ * fsync (made by `confirmRenameDurable`) go through it, so a test can pin
1297
+ * their order and fail the directory one without a real disk fault. Production
1298
+ * callers never pass it.
1299
+ * @returns {{ durabilityUnconfirmed: string | null }}
1300
+ */
1301
+ export function writeClaudeConfigAtomic(
1302
+ filePath,
1303
+ value,
1304
+ {
1305
+ mode,
1306
+ expect,
1307
+ _fsync = fsyncForDurability,
1308
+ _rename = renameSync,
1309
+ _isWindowsOverride,
1310
+ _sleep = sleepSyncMs,
1311
+ // TEST seam: the exec behind the DEFAULT fail-closed stamper, so a test reaches the
1312
+ // real `stampWindowsAclStrict` (rather than injecting `_stampAcl`) with tools mocked.
1313
+ _aclExec,
1314
+ _stampAcl = (target) => stampWindowsAclStrict(target, { _exec: _aclExec, _onWindows: true }),
1315
+ },
1316
+ ) {
1317
+ const resolved = resolveClaudeConfigWritePath(filePath)
1318
+ if (!resolved.ok) throw new Error(resolved.error)
1319
+ // Everything below targets the RESOLVED path: the sidecar has to live in the
1320
+ // target's directory (rename is only atomic within one filesystem, and a
1321
+ // dotfiles target is frequently on a different one from $HOME), and the
1322
+ // dir-fsync has to be the target's directory too.
1323
+ const destPath = resolved.path
1324
+ const onWindows = _isWindowsOverride ?? process.platform === 'win32'
1325
+ // #8983: a snapshot taken against a different resolved path (the link was
1326
+ // retargeted since the read) is stale by definition — do not even write the temp.
1327
+ if (expect && expect.path !== undefined && expect.path !== destPath) {
1328
+ throw new ClaudeConfigConflictError(destPath, 'its symlink target changed since it was read')
1329
+ }
1330
+ const payload = `${JSON.stringify(value, null, 2)}\n`
1331
+ const targetMode = mode === null || mode === undefined ? 0o600 : mode
1332
+ // Per-call random suffix, NOT process.pid: concurrent sessions in one daemon
1333
+ // share a pid and would race for the same sidecar path (#3922).
1334
+ const tmpPath = `${destPath}.chroxy.${randomUUID()}.tmp`
1335
+ // Cleans up on a THROWN error. A process kill (SIGKILL / OOM / power loss) between
1336
+ // the temp write and the rename can still leave a `.chroxy.<uuid>.tmp` sidecar
1337
+ // beside the config: the destination is never truncated, but the orphan is not
1338
+ // reaped here. Failures other than "already gone" are logged, not swallowed.
1339
+ const discardTmp = () => {
1340
+ try {
1341
+ unlinkSync(tmpPath)
1342
+ } catch (err) {
1343
+ if (err?.code !== 'ENOENT') log.warn(`Failed to remove orphaned ${tmpPath}: ${err?.message || err}`)
1344
+ }
1345
+ }
1346
+ try {
1347
+ // `mode` is only honoured on create, and umask can strip bits from it — so
1348
+ // restate the exact mode afterwards. The intermediate mode can only ever be
1349
+ // TIGHTER than the target (umask removes bits, never adds), so there is no
1350
+ // window in which the temp file is more permissive than the destination
1351
+ // already was.
1352
+ if (onWindows) {
1353
+ // Numeric mode bits are meaningless on NTFS, and a fresh temp would inherit the
1354
+ // parent directory's (possibly broader) ACL. Create it EMPTY, stamp the
1355
+ // owner-only DACL, THEN write — so credentials in the document (env API keys,
1356
+ // OAuth material) never exist in a file readable beyond the owner. The DACL
1357
+ // survives the same-directory rename (same as `writeFileRestricted`). The
1358
+ // stamp is FAIL-CLOSED here (unlike writeFileRestricted's best-effort): a
1359
+ // failed stamp throws, the temp is discarded and the destination — possibly
1360
+ // already restricted — is left untouched rather than replaced by a file
1361
+ // carrying the parent's inherited ACL.
1362
+ writeFileSync(tmpPath, '')
1363
+ _stampAcl(tmpPath)
1364
+ writeFileSync(tmpPath, payload)
1365
+ } else {
1366
+ writeFileSync(tmpPath, payload, { mode: targetMode })
1367
+ chmodSync(tmpPath, targetMode)
1368
+ }
1369
+ _fsync(tmpPath, { isDir: false })
1370
+ } catch (err) {
1371
+ discardTmp()
1372
+ throw err
1373
+ }
1374
+ // A failing rename (EXDEV, FS quota, ACL) would otherwise leave the sidecar
1375
+ // behind — and this sidecar is not inert: it holds the full config, including
1376
+ // any `env` / `headers` the caller just supplied. Unlink it and re-throw the
1377
+ // ORIGINAL rename error, not a cleanup-side ENOENT. Same shape as the #4463 fix
1378
+ // in byok-mcp-trust.js `recordTrust`.
1379
+ //
1380
+ // #8983 — OPTIMISTIC conflict detection (not an atomic compare-and-swap). `claude` (and a second daemon) take no lock of
1381
+ // ours, so the only way to avoid publishing a merge computed from a stale
1382
+ // snapshot is to re-read the destination IMMEDIATELY before the rename and
1383
+ // refuse if it is no longer what the merge started from. The check sits after
1384
+ // the (slow) temp write + fsync so what remains between it and the rename is a
1385
+ // pair of back-to-back syscalls. There is no cross-process lock and POSIX has no
1386
+ // "rename if unchanged", so a write landing in that residual window can still be
1387
+ // lost: this narrows the race to microseconds, it does not eliminate it.
1388
+ for (let attempt = 1; ; attempt++) {
1389
+ try {
1390
+ claudeConfigTestHooks.beforeVerify?.({ path: destPath })
1391
+ // Re-resolve the ORIGINAL path on every attempt (also after a Windows
1392
+ // backoff): a link retargeted, or a regular file swapped for a link with
1393
+ // identical bytes, would otherwise pass the content hash and be clobbered.
1394
+ verifyDestinationUnchanged(filePath, resolved)
1395
+ if (expect) verifyUnchanged(destPath, expect)
1396
+ _rename(tmpPath, destPath)
1397
+ break
1398
+ } catch (err) {
1399
+ // Windows: claude/AV/Windows Search can hold the destination open without
1400
+ // FILE_SHARE_DELETE, failing the replace with a transient EPERM/EACCES/
1401
+ // EBUSY/EEXIST. Bounded retry; the check runs again on the next pass.
1402
+ if (onWindows && err && WIN_RENAME_RETRY_CODES.has(err.code) && attempt < WIN_RENAME_ATTEMPTS) {
1403
+ _sleep(WIN_RENAME_BACKOFF_MS * attempt)
1404
+ continue
1405
+ }
1406
+ discardTmp()
1407
+ throw err
1408
+ }
1409
+ }
1410
+ // Make the rename itself durable, not just the bytes it points at.
1411
+ //
1412
+ // #7054/#7067: this used to be an UNWRAPPED call, so a post-rename
1413
+ // directory-fsync failure THREW — after the rename had already published the
1414
+ // file. The write succeeded; only its directory entry's durability was
1415
+ // unproven. Both callers were harmed by that lie: `ensureCwdTrusted` treats a
1416
+ // throw as "skip the pre-write", so the user got claude's trust dialog for a
1417
+ // trust write that had actually landed; the MCP add/remove paths reported a
1418
+ // failure for a config change that was on disk. Shared verdict now — report,
1419
+ // never throw — via the one implementation in platform.js.
1420
+ return confirmRenameDurable(destPath, { durable: true, fsync: _fsync })
1421
+ }
1422
+
1423
+ const WIN_RENAME_RETRY_CODES = new Set(['EPERM', 'EACCES', 'EBUSY', 'EEXIST'])
1424
+ const WIN_RENAME_ATTEMPTS = 4
1425
+ const WIN_RENAME_BACKOFF_MS = 25
1426
+
1427
+ function sleepSyncMs(ms) {
1428
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
1429
+ }
1430
+
1431
+ /** sha256 (hex) of a config file's raw bytes — the snapshot identity. */
1432
+ function hashConfigBytes(bytes) {
1433
+ return createHash('sha256').update(bytes).digest('hex')
1434
+ }
1435
+
1436
+ /**
1437
+ * TEST-ONLY seam (#8983): `beforeVerify({ path })` runs inside the writer after
1438
+ * the temp file is durable and just before the conflict check, i.e. at
1439
+ * the exact point a concurrent writer's update lands in the bug. A real caller
1440
+ * (register/unregister, trust pre-write, MCP add/remove) reaches the writer only
1441
+ * through `updateClaudeConfig`, so a test sets this to drive THAT caller end to
1442
+ * end rather than testing the helper in isolation. Production leaves it null.
1443
+ */
1444
+ export const claudeConfigTestHooks = { beforeVerify: null }
1445
+
1446
+ /**
1447
+ * Thrown when the destination no longer matches the snapshot a merge was
1448
+ * computed from. `updateClaudeConfig` retries on it; it escapes only once the
1449
+ * retry budget is spent (then as `exhausted: true`).
1450
+ */
1451
+ export class ClaudeConfigConflictError extends Error {
1452
+ constructor(path, why, { exhausted = false } = {}) {
1453
+ super(exhausted
1454
+ ? `${path} kept changing underneath the update (${why}); gave up after retrying so another writer's changes are not overwritten. Nothing was written.`
1455
+ : `${path} changed since it was read (${why})`)
1456
+ this.name = 'ClaudeConfigConflictError'
1457
+ this.code = 'CLAUDE_CONFIG_CONFLICT'
1458
+ this.exhausted = exhausted
1459
+ }
1460
+ }
1461
+
1462
+ // A regular file swapped for a symlink (even to identical bytes) changes the RESOLVED
1463
+ // path (the link's target), so the path comparison below is what catches it; a
1464
+ // separate regular-vs-symlink flag was tried and mutation-tested as redundant.
1465
+ function verifyDestinationUnchanged(filePath, initial) {
1466
+ const now = resolveClaudeConfigWritePath(filePath)
1467
+ if (!now.ok) throw new ClaudeConfigConflictError(filePath, `its symlink state changed and is now refused (${now.error})`)
1468
+ if (now.path !== initial.path) throw new ClaudeConfigConflictError(filePath, 'its symlink target changed since it was read')
1469
+ }
1470
+
1471
+ function verifyUnchanged(destPath, expect) {
1472
+ let bytes = null
1473
+ try {
1474
+ bytes = readFileSync(destPath)
1475
+ } catch (err) {
1476
+ if (err?.code !== 'ENOENT') {
1477
+ // Cannot prove it is unchanged — treat as a conflict, never as "fine".
1478
+ throw new ClaudeConfigConflictError(destPath, `re-read failed: ${err?.code || err?.message}`)
1479
+ }
1480
+ }
1481
+ if (bytes === null) {
1482
+ if (expect.existed) throw new ClaudeConfigConflictError(destPath, 'it was removed')
1483
+ return
1484
+ }
1485
+ if (!expect.existed) throw new ClaudeConfigConflictError(destPath, 'it was created by another writer')
1486
+ if (hashConfigBytes(bytes) !== expect.hash) throw new ClaudeConfigConflictError(destPath, 'its content changed')
1487
+ // A permission change with identical bytes (e.g. a concurrent `chmod 600`) is a
1488
+ // conflict too: the temp carries the snapshot's mode, and publishing it would
1489
+ // silently undo the tightening. The re-merge picks up the CURRENT mode.
1490
+ if (expect.mode !== null && expect.mode !== undefined) {
1491
+ let current = null
1492
+ try { current = statSync(destPath).mode & 0o777 } catch { /* raced away: the next attempt sorts it out */ }
1493
+ if (current !== expect.mode) throw new ClaudeConfigConflictError(destPath, 'its permissions changed')
1494
+ }
1495
+ }
1496
+
1497
+ const TORN_READ_PAUSE_MS = 20
1498
+ const CONFLICT_JITTER_MAX_MS = 8
1499
+
1500
+ /** Retry budget for `updateClaudeConfig` (#8983). Bounded: a file under constant churn must fail loudly, not spin. */
1501
+ export const CLAUDE_CONFIG_MAX_ATTEMPTS = 5
1502
+
1503
+ /**
1504
+ * #8983 — THE read-merge-write for claude's config files (`~/.claude.json`,
1505
+ * `<claude config dir>/settings.json`). Every site that mutates one of them goes
1506
+ * through here: the permission-hook register/unregister, the workspace-trust
1507
+ * pre-write, and MCP add/remove. A second, hand-rolled read-modify-write over
1508
+ * these files is the lost-update bug this exists to prevent (#7262 is the
1509
+ * shape: a guard wired to only some callers).
1510
+ *
1511
+ * Per attempt: resolve the (symlink-aware) destination → read + hash a snapshot
1512
+ * → run `mutate` on a FRESHLY parsed tree → write the temp file → re-read the
1513
+ * destination and refuse to rename if it is not the snapshot any more → rename.
1514
+ * A mismatch discards the temp file and re-runs the WHOLE merge on the new
1515
+ * content, up to `maxAttempts`; running out throws a loud
1516
+ * `ClaudeConfigConflictError` (`exhausted: true`) and leaves the file untouched.
1517
+ *
1518
+ * @param {string} filePath
1519
+ * @param {(raw: object, info: { existed: boolean, mode: number|null, attempt: number }) =>
1520
+ * ({ write?: boolean, value?: object, result?: any } | void)} mutate — mutate `raw` in
1521
+ * place (or return `value`); return `{ write: false, result }` to skip the write
1522
+ * (a no-op must not rewrite a file nor race anyone for nothing). Must be
1523
+ * synchronous and side-effect free apart from `raw`: it re-runs on conflict.
1524
+ * @param {{ maxAttempts?: number, createDir?: boolean, _fsync?: Function,
1525
+ * _rename?: Function, _isWindowsOverride?: boolean, _sleep?: Function }} [opts]
1526
+ * `createDir`: when the file does not exist yet, create its directory (0700) first.
1527
+ * @returns {{ ok: true, wrote: boolean, result: any, attempts: number,
1528
+ * durabilityUnconfirmed: string|null, path: string|null } | { ok: false, error: string }}
1529
+ * `ok: false` is a read/parse refusal (fail-closed, see `readClaudeConfigForMutation`).
1530
+ * A refused symlink, an I/O failure, or exhausted retries THROW.
1531
+ */
1532
+ export function updateClaudeConfig(filePath, mutate, opts = {}) {
1533
+ const { maxAttempts = CLAUDE_CONFIG_MAX_ATTEMPTS, createDir = false, ...writerOpts } = opts
1534
+ const sleep = writerOpts._sleep ?? sleepSyncMs
1535
+ let tornReadRetried = false
1536
+ let lastWhy = 'unknown'
1537
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
1538
+ const resolved = resolveClaudeConfigWritePath(filePath)
1539
+ if (!resolved.ok) throw new Error(resolved.error)
1540
+ let read = readClaudeConfigForMutation(resolved.path)
1541
+ if (!read.ok && read.invalidJson && !tornReadRetried) {
1542
+ // A writer that truncates then writes (rather than rename-replaces) can be
1543
+ // caught mid-write: the file parses as garbage for a moment. Re-read ONCE
1544
+ // after a short pause before treating it as genuinely invalid; if it still
1545
+ // is, fail closed exactly as before.
1546
+ tornReadRetried = true
1547
+ sleep(TORN_READ_PAUSE_MS)
1548
+ read = readClaudeConfigForMutation(resolved.path)
1549
+ }
1550
+ if (!read.ok) return read
1551
+ const out = mutate(read.raw, { existed: read.existed, mode: read.mode, attempt }) ?? {}
1552
+ if (out.write === false) {
1553
+ return { ok: true, wrote: false, result: out.result, attempts: attempt, durabilityUnconfirmed: null, path: null }
1554
+ }
1555
+ if (createDir && !read.existed) mkdirSync(dirname(resolved.path), { recursive: true, mode: 0o700 })
1556
+ try {
1557
+ const { durabilityUnconfirmed } = writeClaudeConfigAtomic(filePath, out.value ?? read.raw, {
1558
+ mode: read.mode,
1559
+ expect: { path: resolved.path, existed: read.existed, hash: read.hash, mode: read.mode },
1560
+ ...writerOpts,
1561
+ })
1562
+ return { ok: true, wrote: true, result: out.result, attempts: attempt, durabilityUnconfirmed, path: resolved.path }
1563
+ } catch (err) {
1564
+ if (!(err instanceof ClaudeConfigConflictError)) throw err
1565
+ lastWhy = err.message
1566
+ log.warn(`${lastWhy}; re-reading and re-merging (attempt ${attempt}/${maxAttempts})`)
1567
+ // Jittered pause so two contending writers do not retry in lockstep.
1568
+ if (attempt < maxAttempts) sleep(1 + Math.floor(Math.random() * CONFLICT_JITTER_MAX_MS))
1569
+ }
1570
+ }
1571
+ log.error(`config update of ${filePath} abandoned after ${maxAttempts} attempts: ${lastWhy}`)
1572
+ throw new ClaudeConfigConflictError(filePath, lastWhy, { exhausted: true })
1573
+ }
1574
+
1575
+ /**
1576
+ * Resolve the `projects` key under which cwd's config block lives, for a WRITE.
1577
+ *
1578
+ * Claude Code keys project blocks by `realpath(cwd)`. Reads tolerate either
1579
+ * spelling (see resolveProjectBlock), so a write must target the key that
1580
+ * ALREADY exists — writing the realpath when a literal-cwd key is present would
1581
+ * create a second, shadowed block that the read path never reaches. Falls back
1582
+ * to the realpath (or literal cwd, if it does not resolve) as the key to create.
1583
+ *
1584
+ * @param {object} raw — parsed config
1585
+ * @param {string} cwd
1586
+ * @returns {string} the projects key to read/write
1587
+ */
1588
+ function resolveProjectKeyForWrite(raw, cwd) {
1589
+ let realCwd = cwd
1590
+ try {
1591
+ realCwd = realpathSync(cwd)
1592
+ } catch {
1593
+ // cwd may not resolve (removed dir) — the literal key is the best we have.
1594
+ }
1595
+ const projects = raw?.projects
1596
+ if (projects && typeof projects === 'object' && !Array.isArray(projects)) {
1597
+ if (Object.prototype.hasOwnProperty.call(projects, realCwd)) return realCwd
1598
+ if (Object.prototype.hasOwnProperty.call(projects, cwd)) return cwd
1599
+ }
1600
+ return realCwd
1601
+ }
1602
+
1603
+ /** The config scopes a mutation may target. */
1604
+ export const MCP_WRITE_SCOPES = Object.freeze(['user', 'project'])
1605
+
1606
+ /**
1607
+ * Why `.mcp.json` is NOT a writable scope: the third read source
1608
+ * (`<cwd>/.mcp.json`) is a project-local file that is normally checked into the
1609
+ * user's git repository. Mutating it from a chat client would dirty their
1610
+ * working tree and could land in a commit unnoticed. Both writable scopes live
1611
+ * in `~/.claude.json`, which is machine-local user state.
1612
+ */
1613
+
1614
+ /**
1615
+ * Everything `addMcpServerToConfig` does EXCEPT the write: validate the name and
1616
+ * scope, normalize the config, read the existing file, locate the target block,
1617
+ * and refuse a duplicate name. Returns the located block + parsed tree so the
1618
+ * caller can either commit (write) or discard (plan).
1619
+ *
1620
+ * Split out for #7001's deny-before-write ordering: the trust prompt has to run
1621
+ * BEFORE anything is persisted, and prompting for an add that was going to fail
1622
+ * validation or EXISTS anyway is both bad UX and a needless prompt. `raw` is a
1623
+ * per-call freshly-parsed tree, so the plan path mutating it (creating an empty
1624
+ * `mcpServers` block) is discarded harmlessly.
1625
+ *
1626
+ * The commit path re-runs this, so the read→check→write critical section stays
1627
+ * synchronous and `await`-free: a plan result is ADVISORY, never the authority.
1628
+ */
1629
+ function prepareAddMcpServer({ name, config, scope = 'user', cwd, configPath = defaultClaudeConfigPath() } = {}) {
1630
+ const validName = validateNewMcpServerName(name)
1631
+ if (!validName.ok) return { ok: false, error: validName.error }
1632
+ if (!MCP_WRITE_SCOPES.includes(scope)) {
1633
+ return { ok: false, error: `Unknown MCP config scope '${scope}' (expected 'user' or 'project')` }
1634
+ }
1635
+ if (scope === 'project' && (typeof cwd !== 'string' || cwd.length === 0)) {
1636
+ return { ok: false, error: 'Project scope requires a session working directory' }
1637
+ }
1638
+ const normalized = normalizeMcpServerConfig(validName.name, config)
1639
+ if (!normalized.ok) return { ok: false, error: normalized.error }
1640
+
1641
+ const shadowed = findShadowingMcpScope({ name: validName.name, scope, cwd, configPath })
1642
+ if (shadowed) {
1643
+ return {
1644
+ ok: false,
1645
+ code: 'EXISTS',
1646
+ error: `An MCP server named '${validName.name}' is already defined in ${MCP_SOURCE_LABELS[shadowed]}, which takes precedence over ${MCP_SOURCE_LABELS[mcpWriteScopeToSource(scope)]}, so a server added here would never be used. ${shadowed === MCP_SERVER_SOURCE.PROJECT_MCP_JSON ? 'Chroxy cannot edit that file, so remove or rename the entry there by hand' : 'Remove or rename it there'}, or use a different name.`,
1647
+ }
1648
+ }
1649
+
1650
+ // DRY-RUN read (the plan path). The COMMIT re-runs `locateAddTarget` on a fresh
1651
+ // read inside `updateClaudeConfig`, which owns the conflict detection (#8983).
1652
+ const read = readClaudeConfigForMutation(configPath)
1653
+ if (!read.ok) return { ok: false, error: read.error }
1654
+ const located = locateAddTarget(read.raw, { scope, cwd, validName, normalized })
1655
+ if (!located.ok) return located
1656
+ return { ...located, mode: read.mode, scope, name: validName.name, configPath }
1657
+ }
1658
+
1659
+ /** Human-readable scope names for add-time errors (#7962). */
1660
+ const MCP_SOURCE_LABELS = Object.freeze({
1661
+ [MCP_SERVER_SOURCE.LOCAL]: 'the local scope of this project',
1662
+ [MCP_SERVER_SOURCE.PROJECT_MCP_JSON]: 'the .mcp.json file in this repository',
1663
+ [MCP_SERVER_SOURCE.USER]: 'user scope',
1664
+ })
1665
+
1666
+ /** Precedence rank, highest first — the same order `readMcpSourcesInPrecedenceOrder` enumerates. */
1667
+ const MCP_SOURCE_RANK = Object.freeze({
1668
+ [MCP_SERVER_SOURCE.LOCAL]: 0,
1669
+ [MCP_SERVER_SOURCE.PROJECT_MCP_JSON]: 1,
1670
+ [MCP_SERVER_SOURCE.USER]: 2,
1671
+ })
1672
+
1673
+ /**
1674
+ * #7962: the scope a server NAMED `name` currently spawns from, when that scope
1675
+ * outranks the write target. Resolved through `discoverMcpServerSpecs` (the spawn
1676
+ * path's own resolver) so "what wins" cannot drift from "what spawns". Returns an
1677
+ * `MCP_SERVER_SOURCE` value, or null when nothing outranks the target.
1678
+ */
1679
+ function findShadowingMcpScope({ name, scope, cwd, configPath }) {
1680
+ const winner = discoverMcpServerSpecs(cwd, { configPath }).servers.find((s) => s.name === name)
1681
+ if (!winner) return null
1682
+ const target = mcpWriteScopeToSource(scope)
1683
+ return MCP_SOURCE_RANK[winner.source] < MCP_SOURCE_RANK[target] ? winner.source : null
1684
+ }
1685
+
1686
+ /** Locate (creating if absent) the block an add targets in `raw`; refuse a duplicate / malformed shape. */
1687
+ function locateAddTarget(raw, { scope, cwd, validName, normalized }) {
1688
+ let block
1689
+ if (scope === 'user') {
1690
+ if (raw.mcpServers != null && (typeof raw.mcpServers !== 'object' || Array.isArray(raw.mcpServers))) {
1691
+ return { ok: false, error: 'Existing user-scope mcpServers is not an object; refusing to replace it' }
1692
+ }
1693
+ if (raw.mcpServers == null) raw.mcpServers = {}
1694
+ block = raw.mcpServers
1695
+ } else {
1696
+ if (raw.projects != null && (typeof raw.projects !== 'object' || Array.isArray(raw.projects))) {
1697
+ return { ok: false, error: 'Existing projects block is not an object; refusing to replace it' }
1698
+ }
1699
+ if (raw.projects == null) raw.projects = {}
1700
+ const key = resolveProjectKeyForWrite(raw, cwd)
1701
+ const existing = raw.projects[key]
1702
+ if (existing != null && (typeof existing !== 'object' || Array.isArray(existing))) {
1703
+ return { ok: false, error: `Existing project block for ${key} is not an object; refusing to replace it` }
1704
+ }
1705
+ // Preserve every other key Claude Code keeps on the project block
1706
+ // (allowedTools, history, …) — only mcpServers is ours to touch.
1707
+ if (existing == null) raw.projects[key] = {}
1708
+ const projectBlock = raw.projects[key]
1709
+ if (projectBlock.mcpServers != null && (typeof projectBlock.mcpServers !== 'object' || Array.isArray(projectBlock.mcpServers))) {
1710
+ return { ok: false, error: `Existing project-scope mcpServers for ${key} is not an object; refusing to replace it` }
1711
+ }
1712
+ if (projectBlock.mcpServers == null) projectBlock.mcpServers = {}
1713
+ block = projectBlock.mcpServers
1714
+ }
1715
+
1716
+ if (Object.prototype.hasOwnProperty.call(block, validName.name)) {
1717
+ return {
1718
+ ok: false,
1719
+ code: 'EXISTS',
1720
+ error: `An MCP server named '${validName.name}' already exists in ${scope} scope. Remove it first to replace it.`,
1721
+ }
1722
+ }
1723
+ return { ok: true, raw, block, entry: normalized.entry }
1724
+ }
1725
+
1726
+ /**
1727
+ * #7001: DRY-RUN of an add — every check `addMcpServerToConfig` performs, with no
1728
+ * write. Returns the exact normalized `entry` that WOULD be persisted, so a caller
1729
+ * can obtain the user's spawn-trust decision for that precise config before
1730
+ * anything reaches disk (a denied add must leave no config entry behind).
1731
+ *
1732
+ * @returns {{ ok: true, entry: object, scope: string } | { ok: false, error: string, code?: string }}
1733
+ */
1734
+ export function planAddMcpServerToConfig(opts = {}) {
1735
+ const prepared = prepareAddMcpServer(opts)
1736
+ if (!prepared.ok) return prepared.code ? { ok: false, error: prepared.error, code: prepared.code } : { ok: false, error: prepared.error }
1737
+ return { ok: true, entry: prepared.entry, scope: prepared.scope }
1738
+ }
1739
+
1740
+ /**
1741
+ * Add (or refuse to overwrite) one MCP server in the user's config.
1742
+ *
1743
+ * Scope selects WHERE: 'user' → the root `mcpServers` block; 'project' →
1744
+ * `projects[<realpath(cwd)>].mcpServers`. There is no "wherever it fits"
1745
+ * fallback — an ambiguous write to a user's config is worse than an error.
1746
+ *
1747
+ * Refuses (rather than overwrites) an existing name in the target scope: an
1748
+ * overwrite would silently replace a command the user trusts with a different
1749
+ * one, which is exactly the substitution the trust store exists to prevent.
1750
+ *
1751
+ * NOTE (#7001): this is the COMMIT. On the WS add path the caller must already
1752
+ * have obtained the user's spawn-trust decision (via `planAddMcpServerToConfig`)
1753
+ * — persisting first and prompting afterwards leaves a denied server configured.
1754
+ *
1755
+ * @param {object} opts
1756
+ * @param {string} opts.name
1757
+ * @param {unknown} opts.config
1758
+ * @param {'user'|'project'} [opts.scope]
1759
+ * @param {string} [opts.cwd] — required for scope 'project'
1760
+ * @param {string} [opts.configPath]
1761
+ * @returns {{ ok: true, entry: object, scope: string, warning?: string } | { ok: false, error: string, code?: string }}
1762
+ */
1763
+ export function addMcpServerToConfig(opts = {}) {
1764
+ const prepared = prepareAddMcpServer(opts)
1765
+ if (!prepared.ok) return prepared.code ? { ok: false, error: prepared.error, code: prepared.code } : { ok: false, error: prepared.error }
1766
+ // The commit re-locates the target on a FRESH read inside the conflict-detection
1767
+ // loop (#8983): the plan's tree is advisory and may be stale by now.
1768
+ const { scope = 'user', cwd } = opts
1769
+ const validName = { name: prepared.name }
1770
+ const normalized = { entry: prepared.entry }
1771
+ const updated = updateClaudeConfig(prepared.configPath, (raw, info) => {
1772
+ const located = locateAddTarget(raw, { scope, cwd, validName, normalized })
1773
+ if (!located.ok) return { write: false, result: located }
1774
+ located.block[prepared.name] = prepared.entry
1775
+ return { result: { mode: info.mode } }
1776
+ })
1777
+ if (!updated.ok) return { ok: false, error: updated.error }
1778
+ if (!updated.wrote) {
1779
+ const refused = updated.result
1780
+ return refused.code ? { ok: false, error: refused.error, code: refused.code } : { ok: false, error: refused.error }
1781
+ }
1782
+ // #7002: computed from the mode we just PRESERVED and the entry we just wrote,
1783
+ // so it only fires when Chroxy is the party that put secret material into a
1784
+ // group/world-readable file. Advisory — we still do not re-permission the file.
1785
+ const warning = describeConfigModeSecretWarning({
1786
+ filePath: prepared.configPath,
1787
+ mode: updated.result.mode,
1788
+ entry: prepared.entry,
1789
+ })
1790
+ const result = { ok: true, entry: prepared.entry, scope: prepared.scope }
1791
+ if (warning) result.warning = warning
1792
+ return result
1793
+ }
1794
+
1795
+ /**
1796
+ * Remove one MCP server from the user's config, in the named scope only.
1797
+ *
1798
+ * Returns `found: false` (no write performed) when the name is absent from the
1799
+ * REQUESTED scope, even if it exists in the other one — a remove that silently
1800
+ * jumped scope could delete a shared user-scope server when the caller meant to
1801
+ * detach a project-scope one. The caller surfaces the scope in its error so a
1802
+ * client can retry against the right one.
1803
+ *
1804
+ * @param {object} opts
1805
+ * @param {string} opts.name
1806
+ * @param {'user'|'project'} [opts.scope]
1807
+ * @param {string} [opts.cwd] — required for scope 'project'
1808
+ * @param {string} [opts.configPath]
1809
+ * @param {Function} [opts._fsync] — TEST-ONLY (#7070): forwarded to
1810
+ * `writeClaudeConfigAtomic`; see its `_fsync` doc. Production never passes it.
1811
+ * @returns {{ ok: true, found: boolean, scope: string, durabilityUnconfirmed?: string } | { ok: false, error: string }}
1812
+ */
1813
+ export function removeMcpServerFromConfig({ name, scope = 'user', cwd, configPath = defaultClaudeConfigPath(), _fsync } = {}) {
1814
+ const validName = validateMcpServerNameForRemoval(name)
1815
+ if (!validName.ok) return { ok: false, error: validName.error }
1816
+ if (!MCP_WRITE_SCOPES.includes(scope)) {
1817
+ return { ok: false, error: `Unknown MCP config scope '${scope}' (expected 'user' or 'project')` }
1818
+ }
1819
+ if (scope === 'project' && (typeof cwd !== 'string' || cwd.length === 0)) {
1820
+ return { ok: false, error: 'Project scope requires a session working directory' }
1821
+ }
1822
+
1823
+ const updated = updateClaudeConfig(configPath, (raw, info) => {
1824
+ if (!info.existed) return { write: false, result: { found: false } }
1825
+ return removeServerFromTree(raw, { name: validName.name, scope, cwd })
1826
+ }, { _fsync })
1827
+ if (!updated.ok) return { ok: false, error: updated.error }
1828
+ if (!updated.wrote) return { ok: true, found: false, scope }
1829
+ const durabilityUnconfirmed = updated.durabilityUnconfirmed ?? undefined
1830
+ // #7054/#7068: REMOVE is the load-bearing durable case — this write is durable
1831
+ // precisely so a capability REDUCTION cannot silently reappear after a power
1832
+ // loss. Dropping the caveat here would sever the only caller-visible signal on
1833
+ // the one path that exists to carry it, which is the same false-green #7068
1834
+ // had to undo on the token revoke. Propagate rather than swallow.
1835
+ return { ok: true, found: true, scope, ...(durabilityUnconfirmed ? { durabilityUnconfirmed } : {}) }
1836
+ }
1837
+
1838
+ /** Delete `name` from the scope's server block in `raw`; `{ write: false }` when it is absent (a no-op remove must not rewrite the file). */
1839
+ function removeServerFromTree(raw, { name, scope, cwd }) {
1840
+ let block = null
1841
+ if (scope === 'user') {
1842
+ if (raw.mcpServers && typeof raw.mcpServers === 'object' && !Array.isArray(raw.mcpServers)) {
1843
+ block = raw.mcpServers
1844
+ }
1845
+ } else {
1846
+ const projects = raw.projects
1847
+ if (projects && typeof projects === 'object' && !Array.isArray(projects)) {
1848
+ const key = resolveProjectKeyForWrite(raw, cwd)
1849
+ const projectBlock = Object.prototype.hasOwnProperty.call(projects, key) ? projects[key] : null
1850
+ if (projectBlock && typeof projectBlock === 'object' && !Array.isArray(projectBlock)) {
1851
+ const servers = projectBlock.mcpServers
1852
+ if (servers && typeof servers === 'object' && !Array.isArray(servers)) block = servers
1853
+ }
1854
+ }
1855
+ }
1856
+ if (!block || !Object.prototype.hasOwnProperty.call(block, name)) {
1857
+ // Nothing to do — and crucially, NO write. A no-op remove must not rewrite
1858
+ // the user's file (nor risk clobbering a concurrent edit for nothing).
1859
+ return { write: false, result: { found: false } }
1860
+ }
1861
+ delete block[name]
1862
+ return { result: { found: true } }
1863
+ }