@chroxy/server 0.11.0 → 0.11.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +204 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1203 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +628 -121
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +3 -3
- package/src/byok-session.js +650 -175
- package/src/byok-tool-executor.js +2662 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +211 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3513 -287
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +68 -39
- package/src/cli/server-cmd.js +48 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1066 -121
- package/src/cli.js +4 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1454 -79
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +286 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +284 -10
- package/src/doctor.js +767 -61
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +151 -233
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +535 -68
- package/src/handlers/checkpoint-handlers.js +39 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/input-handlers.js +685 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/scheduler-handlers.js +88 -14
- package/src/handlers/session-handlers.js +542 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +330 -42
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +289 -82
- package/src/jsonl-subprocess-session.js +92 -8
- package/src/keychain.js +1 -1
- package/src/logger.js +63 -17
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +12 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +80 -33
- package/src/orchestration/permission-gate.js +13 -1
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/turn-driver.js +44 -20
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1357 -42
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +712 -83
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +122 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +159 -43
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +207 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +318 -26
- package/src/scheduler.js +73 -3
- package/src/sdk-session.js +2060 -187
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +524 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3491 -312
- package/src/session-message-history.js +722 -16
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +23 -11
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +137 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +7 -2
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +331 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +329 -39
- package/src/ws-handler-context.js +70 -2
- package/src/ws-history.js +940 -172
- package/src/ws-message-handlers.js +17 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +643 -96
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
package/src/byok-mcp-config.js
CHANGED
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
chmodSync,
|
|
18
18
|
existsSync,
|
|
19
19
|
lstatSync,
|
|
20
|
+
mkdirSync,
|
|
20
21
|
readFileSync,
|
|
21
22
|
realpathSync,
|
|
22
23
|
renameSync,
|
|
@@ -24,11 +25,25 @@ import {
|
|
|
24
25
|
unlinkSync,
|
|
25
26
|
writeFileSync,
|
|
26
27
|
} from 'node:fs'
|
|
27
|
-
import { randomUUID } from 'node:crypto'
|
|
28
|
-
import { homedir } from 'node:os'
|
|
28
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
29
29
|
import { dirname, join } from 'node:path'
|
|
30
30
|
import { lookup as dnsLookup } from 'node:dns/promises'
|
|
31
|
-
import {
|
|
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')
|
|
32
47
|
|
|
33
48
|
/**
|
|
34
49
|
* Defensive upper bound on the size of `~/.claude.json`. Today the file is
|
|
@@ -40,7 +55,7 @@ import { fsyncForDurability, confirmRenameDurable } from './platform.js'
|
|
|
40
55
|
export const CLAUDE_CONFIG_MAX_BYTES = 10 * 1024 * 1024
|
|
41
56
|
|
|
42
57
|
export function defaultClaudeConfigPath() {
|
|
43
|
-
return process.env.CHROXY_CLAUDE_CONFIG ||
|
|
58
|
+
return process.env.CHROXY_CLAUDE_CONFIG || claudeGlobalConfigPath()
|
|
44
59
|
}
|
|
45
60
|
|
|
46
61
|
/**
|
|
@@ -79,8 +94,12 @@ function coerceStringArray(value, { warnings, serverName }) {
|
|
|
79
94
|
* explanation. `constructor` / `prototype` are plain own-property writes (no
|
|
80
95
|
* setter) but are refused alongside it: a map key that shadows an object internal
|
|
81
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.
|
|
82
101
|
*/
|
|
83
|
-
const UNSAFE_MAP_KEYS =
|
|
102
|
+
const UNSAFE_MAP_KEYS = UNSAFE_MCP_KEYS
|
|
84
103
|
|
|
85
104
|
/**
|
|
86
105
|
* Coerce an env object to string→string only. Pushes one warning per dropped
|
|
@@ -151,34 +170,12 @@ function coerceHeaders(value, { warnings, serverName }) {
|
|
|
151
170
|
return headers
|
|
152
171
|
}
|
|
153
172
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
* host tricks (0xa9fea9fe, 2852039166) to dotted-quad first, so a
|
|
161
|
-
* literal-host check on the PARSED hostname catches those too.
|
|
162
|
-
* - IPv4-mapped IPv6 forms of the same range: the URL parser serializes
|
|
163
|
-
* them as hex groups (`::ffff:a9fe:xxxx`; a9fe == 169.254), dns.lookup
|
|
164
|
-
* may return the dotted form (`::ffff:169.254.x.x`).
|
|
165
|
-
* - fd00:ec2::254, the AWS IMDS IPv6 endpoint (URL-canonical compressed
|
|
166
|
-
* form plus the expanded spelling).
|
|
167
|
-
* Deliberately does NOT block loopback / RFC1918 generally — localhost MCP
|
|
168
|
-
* servers are legitimate; the broader egress policy is #6834's scope.
|
|
169
|
-
*/
|
|
170
|
-
export function isBlockedMetadataHost(hostname) {
|
|
171
|
-
if (typeof hostname !== 'string' || hostname.length === 0) return false
|
|
172
|
-
let h = hostname.toLowerCase()
|
|
173
|
-
if (h.startsWith('[') && h.endsWith(']')) h = h.slice(1, -1)
|
|
174
|
-
const v4 = h.match(/^(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/)
|
|
175
|
-
if (v4) return Number(v4[1]) === 169 && Number(v4[2]) === 254
|
|
176
|
-
if (/^::ffff:a9fe:[0-9a-f]{1,4}$/.test(h)) return true
|
|
177
|
-
const mapped = h.match(/^::ffff:(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/)
|
|
178
|
-
if (mapped) return Number(mapped[1]) === 169 && Number(mapped[2]) === 254
|
|
179
|
-
if (h === 'fd00:ec2::254' || h === 'fd00:ec2:0:0:0:0:0:254') return true
|
|
180
|
-
return false
|
|
181
|
-
}
|
|
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 }
|
|
182
179
|
|
|
183
180
|
/**
|
|
184
181
|
* Return a credential-stripped form of an MCP server url, safe to log or
|
|
@@ -511,10 +508,10 @@ export function loadClaudeMcpConfig(filePath = defaultClaudeConfigPath()) {
|
|
|
511
508
|
const stat = statSync(filePath)
|
|
512
509
|
if (stat.size > CLAUDE_CONFIG_MAX_BYTES) {
|
|
513
510
|
const warning = `MCP config ${filePath} exceeds size cap (${stat.size} bytes > ${CLAUDE_CONFIG_MAX_BYTES} bytes); skipping load`
|
|
514
|
-
|
|
511
|
+
log.warn(warning)
|
|
515
512
|
return { servers: [], warnings: [warning], missing: false }
|
|
516
513
|
}
|
|
517
|
-
const raw =
|
|
514
|
+
const raw = parseClaudeConfigText(readFileSync(filePath, 'utf8'))
|
|
518
515
|
return { ...parseClaudeMcpConfig(raw), missing: false }
|
|
519
516
|
} catch (err) {
|
|
520
517
|
return {
|
|
@@ -608,82 +605,284 @@ function resolveProjectBlock(raw, cwd) {
|
|
|
608
605
|
}
|
|
609
606
|
|
|
610
607
|
/**
|
|
611
|
-
*
|
|
612
|
-
*
|
|
613
|
-
*
|
|
614
|
-
*
|
|
615
|
-
*
|
|
616
|
-
*
|
|
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.
|
|
617
614
|
*
|
|
618
|
-
*
|
|
619
|
-
*
|
|
620
|
-
*
|
|
621
|
-
*
|
|
622
|
-
*
|
|
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".
|
|
623
620
|
*
|
|
624
|
-
*
|
|
625
|
-
*
|
|
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.
|
|
626
720
|
*
|
|
627
721
|
* @param {string} cwd — the session's working directory
|
|
628
|
-
* @param {
|
|
629
|
-
* @returns {{
|
|
722
|
+
* @param {string} configPath — resolved `~/.claude.json` path (or override)
|
|
723
|
+
* @returns {{ sources: Array<{ mcpServers: unknown, source: string }>, warnings: string[] }}
|
|
630
724
|
*/
|
|
631
|
-
|
|
725
|
+
function readMcpSourcesInPrecedenceOrder(cwd, configPath) {
|
|
632
726
|
const warnings = []
|
|
633
|
-
const
|
|
634
|
-
const add = (names) => {
|
|
635
|
-
for (const name of names) {
|
|
636
|
-
if (!byName.has(name)) byName.set(name, { name })
|
|
637
|
-
}
|
|
638
|
-
}
|
|
727
|
+
const sources = []
|
|
639
728
|
|
|
640
729
|
const readJson = (filePath, source) => {
|
|
641
730
|
try {
|
|
642
731
|
// statSync before readFileSync so a pathologically large file (see
|
|
643
|
-
// CLAUDE_CONFIG_MAX_BYTES) doesn't block session start.
|
|
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.
|
|
644
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
|
+
}
|
|
645
751
|
if (stat.size > CLAUDE_CONFIG_MAX_BYTES) {
|
|
646
752
|
warnings.push(
|
|
647
753
|
`MCP config ${filePath} exceeds size cap (${stat.size} bytes > ${CLAUDE_CONFIG_MAX_BYTES} bytes); skipping load`,
|
|
648
754
|
)
|
|
649
755
|
return null
|
|
650
756
|
}
|
|
651
|
-
return
|
|
757
|
+
return parseClaudeConfigText(readFileSync(filePath, 'utf8'))
|
|
652
758
|
} catch (err) {
|
|
653
|
-
warnings.push(
|
|
759
|
+
warnings.push(`Failed to parse MCP config ${filePath} (${source}): ${err?.message || String(err)}`)
|
|
654
760
|
return null
|
|
655
761
|
}
|
|
656
762
|
}
|
|
657
763
|
|
|
658
|
-
|
|
764
|
+
let userRaw = null
|
|
659
765
|
if (configPath && existsSync(configPath)) {
|
|
660
|
-
|
|
661
|
-
if (
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
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
|
+
})
|
|
670
781
|
}
|
|
671
782
|
}
|
|
672
783
|
|
|
673
|
-
//
|
|
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.
|
|
674
787
|
if (cwd) {
|
|
675
788
|
const mcpJsonPath = join(cwd, '.mcp.json')
|
|
676
789
|
if (existsSync(mcpJsonPath)) {
|
|
677
790
|
const raw = readJson(mcpJsonPath, 'project .mcp.json')
|
|
678
791
|
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
|
679
|
-
|
|
680
|
-
|
|
792
|
+
sources.push({
|
|
793
|
+
mcpServers: raw.mcpServers,
|
|
681
794
|
source: 'project .mcp.json mcpServers',
|
|
682
|
-
|
|
795
|
+
sourceKind: MCP_SERVER_SOURCE.PROJECT_MCP_JSON,
|
|
796
|
+
})
|
|
683
797
|
}
|
|
684
798
|
}
|
|
685
799
|
}
|
|
686
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
|
+
}
|
|
687
886
|
return { servers: [...byName.values()], warnings }
|
|
688
887
|
}
|
|
689
888
|
|
|
@@ -727,8 +926,11 @@ export function discoverConfiguredMcpServers(cwd, { configPath = defaultClaudeCo
|
|
|
727
926
|
* no `.` or `/` (so a name can never read as a path or traverse), no uppercase
|
|
728
927
|
* (so two names can't collide case-insensitively), and no whitespace/control
|
|
729
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.
|
|
730
932
|
*/
|
|
731
|
-
export
|
|
933
|
+
export { MCP_SERVER_NAME_RE }
|
|
732
934
|
|
|
733
935
|
/**
|
|
734
936
|
* Names that must never be used as an object key we assign into, regardless of
|
|
@@ -736,8 +938,12 @@ export const MCP_SERVER_NAME_RE = /^[a-z][a-z0-9_-]{0,63}$/
|
|
|
736
938
|
* already refused by MCP_SERVER_NAME_RE (leading `_`), but `constructor` and
|
|
737
939
|
* `prototype` are pure lowercase letters and WOULD pass it, so they are refused
|
|
738
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.
|
|
739
945
|
*/
|
|
740
|
-
const UNSAFE_MCP_SERVER_NAMES =
|
|
946
|
+
const UNSAFE_MCP_SERVER_NAMES = UNSAFE_MCP_KEYS
|
|
741
947
|
|
|
742
948
|
/**
|
|
743
949
|
* Upper bound on a removable name. Removal accepts a much laxer charset than
|
|
@@ -774,7 +980,7 @@ export function validateNewMcpServerName(name) {
|
|
|
774
980
|
'(letters, digits, dash, underscore; must start with a letter, max 64 chars)',
|
|
775
981
|
}
|
|
776
982
|
}
|
|
777
|
-
if (name
|
|
983
|
+
if (containsMcpToolNamespaceSeparator(name)) {
|
|
778
984
|
return {
|
|
779
985
|
ok: false,
|
|
780
986
|
error:
|
|
@@ -872,14 +1078,16 @@ export function normalizeMcpServerConfig(name, config) {
|
|
|
872
1078
|
* not an error — it is the first-write case and yields an empty object.
|
|
873
1079
|
*
|
|
874
1080
|
* @param {string} filePath
|
|
875
|
-
* @returns {{ ok: true, raw: object, mode: number|null, existed: boolean } | { ok: false, error: string }}
|
|
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).
|
|
876
1084
|
*/
|
|
877
1085
|
export function readClaudeConfigForMutation(filePath) {
|
|
878
1086
|
if (!filePath) return { ok: false, error: 'No Claude config path resolved' }
|
|
879
1087
|
if (!existsSync(filePath)) {
|
|
880
1088
|
// First write — we create the file. `mode: null` tells the writer to use a
|
|
881
1089
|
// fresh-file default (0600) rather than preserving anything.
|
|
882
|
-
return { ok: true, raw: {}, mode: null, existed: false }
|
|
1090
|
+
return { ok: true, raw: {}, mode: null, existed: false, hash: null }
|
|
883
1091
|
}
|
|
884
1092
|
let stat
|
|
885
1093
|
try {
|
|
@@ -894,26 +1102,32 @@ export function readClaudeConfigForMutation(filePath) {
|
|
|
894
1102
|
}
|
|
895
1103
|
}
|
|
896
1104
|
let text
|
|
1105
|
+
let hash
|
|
897
1106
|
try {
|
|
898
|
-
|
|
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')
|
|
899
1112
|
} catch (err) {
|
|
900
1113
|
return { ok: false, error: `Cannot read ${filePath}: ${err?.message || String(err)}` }
|
|
901
1114
|
}
|
|
902
1115
|
let raw
|
|
903
1116
|
try {
|
|
904
|
-
raw =
|
|
1117
|
+
raw = parseClaudeConfigText(text)
|
|
905
1118
|
} catch {
|
|
906
1119
|
// The parser's message can quote surrounding bytes (which may include a
|
|
907
1120
|
// token from elsewhere in the file), so it is deliberately NOT echoed.
|
|
908
1121
|
return {
|
|
909
1122
|
ok: false,
|
|
1123
|
+
invalidJson: true,
|
|
910
1124
|
error: `Config ${filePath} is not valid JSON; refusing to overwrite it. Fix or move the file, then retry.`,
|
|
911
1125
|
}
|
|
912
1126
|
}
|
|
913
1127
|
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
914
1128
|
return { ok: false, error: `Config ${filePath} root must be a JSON object; refusing to overwrite it` }
|
|
915
1129
|
}
|
|
916
|
-
return { ok: true, raw, mode: stat.mode & 0o777, existed: true }
|
|
1130
|
+
return { ok: true, raw, mode: stat.mode & 0o777, existed: true, hash }
|
|
917
1131
|
}
|
|
918
1132
|
|
|
919
1133
|
/**
|
|
@@ -1072,10 +1286,34 @@ export function describeConfigModeSecretWarning({ filePath, mode, entry } = {})
|
|
|
1072
1286
|
*
|
|
1073
1287
|
* @param {string} filePath
|
|
1074
1288
|
* @param {object} value — the full config object to serialize
|
|
1075
|
-
* @param {{ mode: number|null }} opts — `null` mode = new file, use 0600
|
|
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.
|
|
1076
1299
|
* @returns {{ durabilityUnconfirmed: string | null }}
|
|
1077
1300
|
*/
|
|
1078
|
-
export function writeClaudeConfigAtomic(
|
|
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
|
+
) {
|
|
1079
1317
|
const resolved = resolveClaudeConfigWritePath(filePath)
|
|
1080
1318
|
if (!resolved.ok) throw new Error(resolved.error)
|
|
1081
1319
|
// Everything below targets the RESOLVED path: the sidecar has to live in the
|
|
@@ -1083,22 +1321,54 @@ export function writeClaudeConfigAtomic(filePath, value, { mode }) {
|
|
|
1083
1321
|
// dotfiles target is frequently on a different one from $HOME), and the
|
|
1084
1322
|
// dir-fsync has to be the target's directory too.
|
|
1085
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
|
+
}
|
|
1086
1330
|
const payload = `${JSON.stringify(value, null, 2)}\n`
|
|
1087
1331
|
const targetMode = mode === null || mode === undefined ? 0o600 : mode
|
|
1088
1332
|
// Per-call random suffix, NOT process.pid: concurrent sessions in one daemon
|
|
1089
1333
|
// share a pid and would race for the same sidecar path (#3922).
|
|
1090
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
|
+
}
|
|
1091
1346
|
try {
|
|
1092
1347
|
// `mode` is only honoured on create, and umask can strip bits from it — so
|
|
1093
1348
|
// restate the exact mode afterwards. The intermediate mode can only ever be
|
|
1094
1349
|
// TIGHTER than the target (umask removes bits, never adds), so there is no
|
|
1095
1350
|
// window in which the temp file is more permissive than the destination
|
|
1096
1351
|
// already was.
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
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 })
|
|
1100
1370
|
} catch (err) {
|
|
1101
|
-
|
|
1371
|
+
discardTmp()
|
|
1102
1372
|
throw err
|
|
1103
1373
|
}
|
|
1104
1374
|
// A failing rename (EXDEV, FS quota, ACL) would otherwise leave the sidecar
|
|
@@ -1106,11 +1376,36 @@ export function writeClaudeConfigAtomic(filePath, value, { mode }) {
|
|
|
1106
1376
|
// any `env` / `headers` the caller just supplied. Unlink it and re-throw the
|
|
1107
1377
|
// ORIGINAL rename error, not a cleanup-side ENOENT. Same shape as the #4463 fix
|
|
1108
1378
|
// in byok-mcp-trust.js `recordTrust`.
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
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
|
+
}
|
|
1114
1409
|
}
|
|
1115
1410
|
// Make the rename itself durable, not just the bytes it points at.
|
|
1116
1411
|
//
|
|
@@ -1122,7 +1417,159 @@ export function writeClaudeConfigAtomic(filePath, value, { mode }) {
|
|
|
1122
1417
|
// trust write that had actually landed; the MCP add/remove paths reported a
|
|
1123
1418
|
// failure for a config change that was on disk. Shared verdict now — report,
|
|
1124
1419
|
// never throw — via the one implementation in platform.js.
|
|
1125
|
-
return confirmRenameDurable(destPath, { durable: true })
|
|
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 })
|
|
1126
1573
|
}
|
|
1127
1574
|
|
|
1128
1575
|
/**
|
|
@@ -1191,14 +1638,53 @@ function prepareAddMcpServer({ name, config, scope = 'user', cwd, configPath = d
|
|
|
1191
1638
|
const normalized = normalizeMcpServerConfig(validName.name, config)
|
|
1192
1639
|
if (!normalized.ok) return { ok: false, error: normalized.error }
|
|
1193
1640
|
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
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).
|
|
1198
1652
|
const read = readClaudeConfigForMutation(configPath)
|
|
1199
1653
|
if (!read.ok) return { ok: false, error: read.error }
|
|
1200
|
-
const
|
|
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
|
+
})
|
|
1201
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 }) {
|
|
1202
1688
|
let block
|
|
1203
1689
|
if (scope === 'user') {
|
|
1204
1690
|
if (raw.mcpServers != null && (typeof raw.mcpServers !== 'object' || Array.isArray(raw.mcpServers))) {
|
|
@@ -1234,7 +1720,7 @@ function prepareAddMcpServer({ name, config, scope = 'user', cwd, configPath = d
|
|
|
1234
1720
|
error: `An MCP server named '${validName.name}' already exists in ${scope} scope. Remove it first to replace it.`,
|
|
1235
1721
|
}
|
|
1236
1722
|
}
|
|
1237
|
-
return { ok: true, raw, block,
|
|
1723
|
+
return { ok: true, raw, block, entry: normalized.entry }
|
|
1238
1724
|
}
|
|
1239
1725
|
|
|
1240
1726
|
/**
|
|
@@ -1277,14 +1763,28 @@ export function planAddMcpServerToConfig(opts = {}) {
|
|
|
1277
1763
|
export function addMcpServerToConfig(opts = {}) {
|
|
1278
1764
|
const prepared = prepareAddMcpServer(opts)
|
|
1279
1765
|
if (!prepared.ok) return prepared.code ? { ok: false, error: prepared.error, code: prepared.code } : { ok: false, error: prepared.error }
|
|
1280
|
-
|
|
1281
|
-
|
|
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
|
+
}
|
|
1282
1782
|
// #7002: computed from the mode we just PRESERVED and the entry we just wrote,
|
|
1283
1783
|
// so it only fires when Chroxy is the party that put secret material into a
|
|
1284
1784
|
// group/world-readable file. Advisory — we still do not re-permission the file.
|
|
1285
1785
|
const warning = describeConfigModeSecretWarning({
|
|
1286
1786
|
filePath: prepared.configPath,
|
|
1287
|
-
mode:
|
|
1787
|
+
mode: updated.result.mode,
|
|
1288
1788
|
entry: prepared.entry,
|
|
1289
1789
|
})
|
|
1290
1790
|
const result = { ok: true, entry: prepared.entry, scope: prepared.scope }
|
|
@@ -1306,9 +1806,11 @@ export function addMcpServerToConfig(opts = {}) {
|
|
|
1306
1806
|
* @param {'user'|'project'} [opts.scope]
|
|
1307
1807
|
* @param {string} [opts.cwd] — required for scope 'project'
|
|
1308
1808
|
* @param {string} [opts.configPath]
|
|
1309
|
-
* @
|
|
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 }}
|
|
1310
1812
|
*/
|
|
1311
|
-
export function removeMcpServerFromConfig({ name, scope = 'user', cwd, configPath = defaultClaudeConfigPath() } = {}) {
|
|
1813
|
+
export function removeMcpServerFromConfig({ name, scope = 'user', cwd, configPath = defaultClaudeConfigPath(), _fsync } = {}) {
|
|
1312
1814
|
const validName = validateMcpServerNameForRemoval(name)
|
|
1313
1815
|
if (!validName.ok) return { ok: false, error: validName.error }
|
|
1314
1816
|
if (!MCP_WRITE_SCOPES.includes(scope)) {
|
|
@@ -1318,11 +1820,23 @@ export function removeMcpServerFromConfig({ name, scope = 'user', cwd, configPat
|
|
|
1318
1820
|
return { ok: false, error: 'Project scope requires a session working directory' }
|
|
1319
1821
|
}
|
|
1320
1822
|
|
|
1321
|
-
const
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
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
|
+
}
|
|
1325
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 }) {
|
|
1326
1840
|
let block = null
|
|
1327
1841
|
if (scope === 'user') {
|
|
1328
1842
|
if (raw.mcpServers && typeof raw.mcpServers === 'object' && !Array.isArray(raw.mcpServers)) {
|
|
@@ -1339,18 +1853,11 @@ export function removeMcpServerFromConfig({ name, scope = 'user', cwd, configPat
|
|
|
1339
1853
|
}
|
|
1340
1854
|
}
|
|
1341
1855
|
}
|
|
1342
|
-
if (!block || !Object.prototype.hasOwnProperty.call(block,
|
|
1856
|
+
if (!block || !Object.prototype.hasOwnProperty.call(block, name)) {
|
|
1343
1857
|
// Nothing to do — and crucially, NO write. A no-op remove must not rewrite
|
|
1344
1858
|
// the user's file (nor risk clobbering a concurrent edit for nothing).
|
|
1345
|
-
return {
|
|
1859
|
+
return { write: false, result: { found: false } }
|
|
1346
1860
|
}
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
const { durabilityUnconfirmed } = writeClaudeConfigAtomic(configPath, raw, { mode: read.mode }) ?? {}
|
|
1350
|
-
// #7054/#7068: REMOVE is the load-bearing durable case — this write is durable
|
|
1351
|
-
// precisely so a capability REDUCTION cannot silently reappear after a power
|
|
1352
|
-
// loss. Dropping the caveat here would sever the only caller-visible signal on
|
|
1353
|
-
// the one path that exists to carry it, which is the same false-green #7068
|
|
1354
|
-
// had to undo on the token revoke. Propagate rather than swallow.
|
|
1355
|
-
return { ok: true, found: true, scope, ...(durabilityUnconfirmed ? { durabilityUnconfirmed } : {}) }
|
|
1861
|
+
delete block[name]
|
|
1862
|
+
return { result: { found: true } }
|
|
1356
1863
|
}
|