@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.
- package/CONFIG.md +602 -19
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +416 -11
- package/package.json +20 -23
- 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 +1353 -41
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +24 -1
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +101 -0
- 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 +74 -9
- 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 +1153 -20
- package/src/byok-mcp-config.js +1712 -8
- package/src/byok-mcp-fleet.js +416 -29
- package/src/byok-mcp-oauth-store.js +329 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +257 -40
- package/src/byok-session.js +1400 -149
- package/src/byok-tool-executor.js +2681 -38
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +96 -51
- package/src/chroxy-host-metadata.js +122 -0
- 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 +109 -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 +223 -60
- 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 +3611 -286
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +6 -6
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +46 -11
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +16 -17
- package/src/cli/providers-cmd.js +6 -6
- package/src/cli/schedule-cmd.js +804 -0
- package/src/cli/server-cmd.js +64 -2
- package/src/cli/service-cmd.js +70 -27
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +168 -14
- package/src/cli/tokens-cmd.js +212 -0
- package/src/cli/tunnel-cmd.js +256 -25
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1117 -116
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +2108 -101
- 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 +571 -45
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +738 -52
- 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 +23 -30
- package/src/control-room/skills-inventory.js +8 -3
- package/src/control-room/survey.js +32 -0
- 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 +279 -29
- 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/diagnostics.js +3 -0
- 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 +188 -4
- package/src/docker-session.js +293 -10
- package/src/doctor.js +783 -66
- 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 +39 -10
- package/src/environments/backends/k8s.js +58 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +137 -14
- package/src/event-normalizer.js +363 -110
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +100 -7
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +563 -62
- package/src/handlers/checkpoint-handlers.js +162 -20
- package/src/handlers/control-room-handlers.js +99 -29
- package/src/handlers/conversation-handlers.js +563 -25
- package/src/handlers/credential-handlers.js +43 -2
- 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 +101 -13
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +689 -48
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +584 -0
- package/src/handlers/session-handlers.js +546 -16
- 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 +822 -35
- 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/handlers/token-handlers.js +11 -2
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +286 -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 +309 -48
- package/src/jsonl-subprocess-session.js +122 -9
- package/src/keychain.js +160 -13
- package/src/logger.js +240 -31
- 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 +100 -10
- 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 +82 -12
- 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 +63 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +381 -0
- package/src/orchestration/orchestration-manager.js +1342 -0
- package/src/orchestration/permission-gate.js +121 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +206 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +422 -0
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +236 -12
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-audit.js +79 -3
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1770 -0
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +1175 -94
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +174 -12
- package/src/permission-rule-store.js +411 -0
- package/src/permission-scope.js +43 -0
- package/src/platform.js +483 -23
- 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 +228 -6
- 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/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +945 -0
- package/src/scheduler.js +1099 -0
- package/src/sdk-session.js +2374 -168
- 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 +50 -4
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +760 -62
- package/src/server-identity.js +42 -14
- package/src/service.js +682 -53
- 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 +3879 -308
- package/src/session-message-history.js +749 -37
- 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-title.js +168 -0
- package/src/session-token-store.js +70 -36
- 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 +22 -5
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +596 -0
- package/src/subagent-counter.js +9 -1
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +99 -38
- 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/token-manager.js +39 -9
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +413 -31
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +145 -35
- package/src/tunnel/index.js +13 -1
- package/src/tunnel/preview.js +64 -0
- package/src/tunnel-check.js +1 -1
- package/src/turn-outcome.js +137 -0
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +122 -0
- package/src/user-shell-session.js +157 -37
- 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 +301 -0
- package/src/utils/composite-key.js +45 -0
- 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/iso-datetime.js +51 -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 +485 -29
- 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 +196 -5
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +634 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +11 -3
- 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 +370 -66
- package/src/ws-file-ops/common.js +384 -11
- package/src/ws-file-ops/git.js +615 -44
- package/src/ws-file-ops/index.js +7 -0
- package/src/ws-file-ops/memory.js +460 -0
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +676 -94
- package/src/ws-forwarding.js +373 -55
- package/src/ws-handler-context.js +89 -2
- package/src/ws-history.js +1018 -177
- package/src/ws-message-handlers.js +23 -1
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +589 -38
- package/src/ws-schemas.js +6 -0
- package/src/ws-server.js +936 -105
- 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
|
@@ -1,13 +1,145 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { stat, mkdir, realpath } from 'fs/promises'
|
|
2
|
+
import { stillAuthorized } from '../connection-authority.js'
|
|
2
3
|
import { constants as fsConstants } from 'fs'
|
|
3
4
|
import { resolve, normalize, extname } from 'path'
|
|
4
5
|
import { execFile as execFileCb } from 'child_process'
|
|
5
6
|
import { promisify } from 'util'
|
|
6
|
-
import {
|
|
7
|
+
import { GET_DIFF_BASE_MAX_LENGTH } from '@chroxy/protocol'
|
|
8
|
+
import { parseDiff, diffFileHeaderPaths } from '../diff-parser.js'
|
|
7
9
|
import { GIT } from '../git.js'
|
|
10
|
+
import { openNoFollow } from './open-nofollow.js'
|
|
11
|
+
import { createLogger } from '../logger.js'
|
|
12
|
+
import { isSafeArgvValue } from '../utils/argv-safety.js'
|
|
13
|
+
import { isPathWithin } from '../utils/path-containment.js'
|
|
14
|
+
import { readPinnedHandle, readContainedBytes, assertRegularHandle } from '../utils/regular-file.js'
|
|
15
|
+
import { unresolvablePathError, isConfigDirOrDirectChild, fileOpErrorMessage, clientSafeError, CONFIG_DIR_REFUSAL } from './common.js'
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* #7957 — refuse a write target that is not a regular file, on the OPENED
|
|
19
|
+
* handle and before any byte is written. The text reaches the client verbatim,
|
|
20
|
+
* so it carries no path.
|
|
21
|
+
*/
|
|
22
|
+
async function refuseNonRegular(fh) {
|
|
23
|
+
try {
|
|
24
|
+
await assertRegularHandle(fh)
|
|
25
|
+
} catch (err) {
|
|
26
|
+
if (err.code === 'ENOTREG') throw clientSafeError('Not a regular file')
|
|
27
|
+
throw err
|
|
28
|
+
}
|
|
29
|
+
}
|
|
8
30
|
|
|
9
31
|
const execFileAsync = promisify(execFileCb)
|
|
10
32
|
|
|
33
|
+
// #8012 — the message read_file sends when the first `realpath()` failed with
|
|
34
|
+
// one of these codes for a path INSIDE the project. Any other code, or any
|
|
35
|
+
// path outside it, gets the generic denial instead (see unresolvablePathError).
|
|
36
|
+
const READ_UNRESOLVABLE_REASONS = {
|
|
37
|
+
EACCES: 'Permission denied',
|
|
38
|
+
EPERM: 'Permission denied',
|
|
39
|
+
ENOTDIR: 'File not found',
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// #8016 — the same, for write_file and append_memory.
|
|
43
|
+
const WRITE_UNRESOLVABLE_REASONS = {
|
|
44
|
+
EACCES: 'Permission denied',
|
|
45
|
+
EPERM: 'Permission denied',
|
|
46
|
+
ENOTDIR: 'Not a directory',
|
|
47
|
+
}
|
|
48
|
+
const log = createLogger('ws')
|
|
49
|
+
|
|
50
|
+
// getDiff reads paths out of `git diff` output (parseDiff, diffFileHeaderPaths), and
|
|
51
|
+
// the config-directory rule is applied to those paths. A user's or repo's git config
|
|
52
|
+
// can change how a changed file is printed, so every `git diff` call pins what it
|
|
53
|
+
// reads. Settings not named here are not pinned.
|
|
54
|
+
// --src-prefix=a/ --dst-prefix=b/ the `a/` / `b/` header form; beats diff.noprefix,
|
|
55
|
+
// diff.mnemonicPrefix, diff.srcPrefix, diff.dstPrefix
|
|
56
|
+
// -c diff.relative=false paths from the repository root, not the cwd
|
|
57
|
+
// --no-ext-diff an external diff driver (diff.external, or a
|
|
58
|
+
// `diff=` attribute with diff.<name>.command) prints
|
|
59
|
+
// no `diff --git` header, so its output would land in
|
|
60
|
+
// the previous entry
|
|
61
|
+
// --no-color colour escapes start every header line
|
|
62
|
+
// Checked on git 2.55.0: each prefix key alone and all four together still print
|
|
63
|
+
// `a/` / `b/`; diff.relative=true from a subdirectory prints cwd-relative paths and
|
|
64
|
+
// drops files outside it, and `-c diff.relative=false` restores repo-root paths.
|
|
65
|
+
// Relative output is pinned with `-c` rather than `--no-relative` because the repo
|
|
66
|
+
// states no minimum git version and `--no-relative` needs git 2.28; a `-c` setting
|
|
67
|
+
// is accepted by every git (an unknown key is ignored). `-c` must come BEFORE the
|
|
68
|
+
// subcommand, so it is a separate piece of argv from the options after it.
|
|
69
|
+
const DIFF_PIN_CONFIG = ['-c', 'diff.relative=false']
|
|
70
|
+
const DIFF_HEADER_ARGS = ['--src-prefix=a/', '--dst-prefix=b/', '--no-ext-diff', '--no-color']
|
|
71
|
+
// Limits a diff to the directory git runs in (the session cwd). A fixed literal,
|
|
72
|
+
// never client input.
|
|
73
|
+
const DIFF_CWD_PATHSPEC = ['--', '.']
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The supported authored layout has a thin CLAUDE.md importing cwd/AGENTS.md.
|
|
77
|
+
* Recognize only that entire adapter, never turn arbitrary @imports into writes.
|
|
78
|
+
* A bounded, symlink-refusing read cannot follow an external adapter or wait on
|
|
79
|
+
* a special file. Legacy project files (including in-bounds links) retain their
|
|
80
|
+
* existing append destination and the validation below.
|
|
81
|
+
*/
|
|
82
|
+
async function projectMemoryFilename(cwdReal) {
|
|
83
|
+
let fh
|
|
84
|
+
try {
|
|
85
|
+
fh = await openNoFollow(resolve(cwdReal, 'CLAUDE.md'), fsConstants.O_RDONLY)
|
|
86
|
+
const st = await fh.stat()
|
|
87
|
+
if (!st.isFile() || st.size > 64) return 'CLAUDE.md'
|
|
88
|
+
const buffer = Buffer.alloc(65)
|
|
89
|
+
let length = 0
|
|
90
|
+
while (length < buffer.length) {
|
|
91
|
+
const { bytesRead } = await fh.read(buffer, length, buffer.length - length, length)
|
|
92
|
+
if (!bytesRead) break
|
|
93
|
+
length += bytesRead
|
|
94
|
+
}
|
|
95
|
+
const content = buffer.subarray(0, length).toString('utf8').trim()
|
|
96
|
+
return content === '@AGENTS.md' || content === '@./AGENTS.md' ? 'AGENTS.md' : 'CLAUDE.md'
|
|
97
|
+
} catch (err) {
|
|
98
|
+
// Missing legacy files are created by append; existing links are validated
|
|
99
|
+
// by the unchanged realpath/containment pipeline rather than read here.
|
|
100
|
+
if (err.code === 'ENOENT' || err.code === 'ELOOP') return 'CLAUDE.md'
|
|
101
|
+
throw err
|
|
102
|
+
} finally {
|
|
103
|
+
await fh?.close()
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Longest `base` getDiff will hand to git. A revision is short — a full OID is
|
|
109
|
+
* 40 characters and a ref name far less — so this rejects nothing legitimate,
|
|
110
|
+
* and it bounds what could otherwise be spent per request: two `rev-parse`
|
|
111
|
+
* argvs, plus whatever git echoes back into an error message.
|
|
112
|
+
*
|
|
113
|
+
* #7870 — imported rather than redeclared: `GetDiffSchema` (packages/protocol)
|
|
114
|
+
* now rejects a `base` over this same length AT THE WIRE, before getDiff ever
|
|
115
|
+
* runs. This constant is the single source both layers read, so the two
|
|
116
|
+
* cannot drift the way a hand-copied number could. This gate stays anyway —
|
|
117
|
+
* it is the server's OWN, independent defense-in-depth boundary, correct even
|
|
118
|
+
* for a future caller that reaches getDiff by a path that skips schema
|
|
119
|
+
* validation (see packages/server/tests/ws-server-file-ops.test.js's direct
|
|
120
|
+
* `createReaderOps` calls, which exercise it without going over the wire).
|
|
121
|
+
*/
|
|
122
|
+
const MAX_DIFF_BASE_LENGTH = GET_DIFF_BASE_MAX_LENGTH
|
|
123
|
+
|
|
124
|
+
/** Longest error detail written to the server log in one line (#7298). */
|
|
125
|
+
const MAX_LOGGED_ERROR_LENGTH = 500
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Bound one error detail before it reaches the log.
|
|
129
|
+
*
|
|
130
|
+
* An `execFile` rejection's `message` carries the whole command line — which
|
|
131
|
+
* includes the client's own `base` — followed by the child's stderr, and
|
|
132
|
+
* neither is bounded by anything the caller controls. Logging it raw turns an
|
|
133
|
+
* oversized input into log amplification, so the log gets a prefix and the
|
|
134
|
+
* original length instead.
|
|
135
|
+
*/
|
|
136
|
+
export function truncateForLog(message) {
|
|
137
|
+
const text = String(message ?? '')
|
|
138
|
+
return text.length > MAX_LOGGED_ERROR_LENGTH
|
|
139
|
+
? `${text.slice(0, MAX_LOGGED_ERROR_LENGTH)}… (truncated, ${text.length} chars)`
|
|
140
|
+
: text
|
|
141
|
+
}
|
|
142
|
+
|
|
11
143
|
/** Image extensions to MIME type mapping (module-level to avoid per-call allocation) */
|
|
12
144
|
const IMAGE_MIME = {
|
|
13
145
|
png: 'image/png',
|
|
@@ -25,9 +157,15 @@ const IMAGE_MIME = {
|
|
|
25
157
|
* @param {Function} sendFn - (ws, message) => void
|
|
26
158
|
* @param {Function} resolveSessionCwd - shared CWD resolver
|
|
27
159
|
* @param {Function} validatePathWithinCwd - shared path validator
|
|
160
|
+
* @param {Function} [execImpl] - injectable promisified execFile seam (defaults to the
|
|
161
|
+
* real one; matches createGitOps' 5th arg, #7871). Every git invocation inside
|
|
162
|
+
* getDiff routes through this — `rev-parse --git-dir`, both `rev-parse --verify`
|
|
163
|
+
* calls, both `diff` calls, and `ls-files` — so the preflight failure branch
|
|
164
|
+
* (and the exit-128 classification, #7877) can be driven by tests without a
|
|
165
|
+
* real non-repo/permission-denied/timeout condition on the host.
|
|
28
166
|
* @returns {Object} reader operation methods
|
|
29
167
|
*/
|
|
30
|
-
export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd) {
|
|
168
|
+
export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd, execImpl = execFileAsync) {
|
|
31
169
|
|
|
32
170
|
/**
|
|
33
171
|
* Read file content at a given path within the session CWD.
|
|
@@ -84,9 +222,27 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
84
222
|
// Before surfacing "File not found", enforce workspace boundary.
|
|
85
223
|
// A nonexistent path outside the root must return Access denied to
|
|
86
224
|
// avoid leaking filesystem existence information as an oracle.
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
225
|
+
//
|
|
226
|
+
// #8000 — decide it with the SAME canonical check the existing-file
|
|
227
|
+
// path uses below: realpath the deepest existing ancestor, compare
|
|
228
|
+
// against the realpath'd cwd. This used to be a LEXICAL compare of
|
|
229
|
+
// `absPath` (built from the cwd as given) against the realpath'd cwd,
|
|
230
|
+
// which was wrong both ways:
|
|
231
|
+
// - a cwd spelled non-canonically (through a symlink on POSIX, as an
|
|
232
|
+
// 8.3 short name on Windows) made a missing file INSIDE the
|
|
233
|
+
// project answer "Access denied";
|
|
234
|
+
// - `<cwd>/link-to-outside/missing` looked lexically inside and
|
|
235
|
+
// answered "File not found" — an existence oracle for the
|
|
236
|
+
// outside directory, through the link.
|
|
237
|
+
// A check that cannot be answered (ELOOP, EACCES on an ancestor)
|
|
238
|
+
// denies: "could not check" must never read as "not found".
|
|
239
|
+
let withinCwd = false
|
|
240
|
+
try {
|
|
241
|
+
({ valid: withinCwd } = await validatePathWithinCwd(absPath, sessionCwd))
|
|
242
|
+
} catch {
|
|
243
|
+
withinCwd = false
|
|
244
|
+
}
|
|
245
|
+
if (!withinCwd) {
|
|
90
246
|
send({
|
|
91
247
|
type: 'file_content',
|
|
92
248
|
path: absPath,
|
|
@@ -98,6 +254,24 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
98
254
|
})
|
|
99
255
|
return
|
|
100
256
|
}
|
|
257
|
+
// Files directly in the config directory are daemon-managed state, so
|
|
258
|
+
// reads follow the same rule as writes: a missing name there answers
|
|
259
|
+
// the refusal an existing one does, never "File not found". Only
|
|
260
|
+
// reached once the path is known to be inside the project, where the
|
|
261
|
+
// deepest-ancestor walk has already resolved this same path; a check
|
|
262
|
+
// that cannot be answered denies, as it does for writes.
|
|
263
|
+
if (await isConfigDirOrDirectChild(absPath)) {
|
|
264
|
+
send({
|
|
265
|
+
type: 'file_content',
|
|
266
|
+
path: absPath,
|
|
267
|
+
content: null,
|
|
268
|
+
language: null,
|
|
269
|
+
size: null,
|
|
270
|
+
truncated: false,
|
|
271
|
+
error: CONFIG_DIR_REFUSAL,
|
|
272
|
+
})
|
|
273
|
+
return
|
|
274
|
+
}
|
|
101
275
|
send({
|
|
102
276
|
type: 'file_content',
|
|
103
277
|
path: absPath,
|
|
@@ -109,7 +283,26 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
109
283
|
})
|
|
110
284
|
return
|
|
111
285
|
}
|
|
112
|
-
|
|
286
|
+
// #8012 — any OTHER failure (EACCES, EPERM, ENOTDIR, ELOOP, …) used to
|
|
287
|
+
// skip the containment check and reach the outer catch, which sent
|
|
288
|
+
// "Permission denied" for EACCES and Node's raw message — server path
|
|
289
|
+
// included — for the rest. For a path outside the project that told
|
|
290
|
+
// "blocked" apart from "readable" and "missing". Outside, or when the
|
|
291
|
+
// check cannot be answered (a cycle), the answer is now the same denial
|
|
292
|
+
// every outside path gets; only an in-project path keeps a specific
|
|
293
|
+
// message, and never the raw text.
|
|
294
|
+
const cwdReal = await resolveSessionCwd(sessionCwd).catch(() => null)
|
|
295
|
+
send({
|
|
296
|
+
type: 'file_content',
|
|
297
|
+
path: absPath,
|
|
298
|
+
content: null,
|
|
299
|
+
language: null,
|
|
300
|
+
size: null,
|
|
301
|
+
truncated: false,
|
|
302
|
+
error: await unresolvablePathError(err, absPath, cwdReal, READ_UNRESOLVABLE_REASONS,
|
|
303
|
+
'Access denied: file reading is restricted to the project directory'),
|
|
304
|
+
})
|
|
305
|
+
return
|
|
113
306
|
}
|
|
114
307
|
|
|
115
308
|
const { valid } = await validatePathWithinCwd(resolvedAbsPath, sessionCwd)
|
|
@@ -126,6 +319,24 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
126
319
|
return
|
|
127
320
|
}
|
|
128
321
|
|
|
322
|
+
// The config directory itself and any file directly in it are
|
|
323
|
+
// daemon-managed state, so the file viewer treats reads the same way as
|
|
324
|
+
// writes. Checked on the resolved path (a symlink into the config directory
|
|
325
|
+
// is judged by where it lands) and BEFORE `stat`, so no size or type of a
|
|
326
|
+
// refused file is revealed.
|
|
327
|
+
if (await isConfigDirOrDirectChild(resolvedAbsPath)) {
|
|
328
|
+
send({
|
|
329
|
+
type: 'file_content',
|
|
330
|
+
path: absPath,
|
|
331
|
+
content: null,
|
|
332
|
+
language: null,
|
|
333
|
+
size: null,
|
|
334
|
+
truncated: false,
|
|
335
|
+
error: CONFIG_DIR_REFUSAL,
|
|
336
|
+
})
|
|
337
|
+
return
|
|
338
|
+
}
|
|
339
|
+
|
|
129
340
|
const fileStat = await stat(resolvedAbsPath)
|
|
130
341
|
if (fileStat.isDirectory()) {
|
|
131
342
|
send({
|
|
@@ -153,15 +364,36 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
153
364
|
return
|
|
154
365
|
}
|
|
155
366
|
|
|
156
|
-
//
|
|
157
|
-
//
|
|
158
|
-
// validatePathWithinCwd() and this open
|
|
367
|
+
// openNoFollow closes the post-validation TOCTOU window: if the file at
|
|
368
|
+
// resolvedAbsPath was replaced with a symlink between
|
|
369
|
+
// validatePathWithinCwd() and this open, it is rejected with ELOOP — by
|
|
370
|
+
// the kernel on POSIX (O_NOFOLLOW), by an lstat + fd-identity check on
|
|
371
|
+
// win32, where O_NOFOLLOW does not exist and the bare flag silently
|
|
372
|
+
// no-opped until #7280. See open-nofollow.js for the exact per-platform
|
|
373
|
+
// guarantee and the race it cannot close.
|
|
159
374
|
let buf
|
|
160
375
|
{
|
|
161
376
|
let fh
|
|
162
377
|
try {
|
|
163
|
-
fh = await
|
|
164
|
-
|
|
378
|
+
fh = await openNoFollow(resolvedAbsPath, fsConstants.O_RDONLY)
|
|
379
|
+
// #7938 — `fileStat` above was taken BEFORE this open, so it can't
|
|
380
|
+
// see a FIFO/device swapped in during the TOCTOU window between
|
|
381
|
+
// that stat and this open. openNoFollow's O_NONBLOCK keeps the
|
|
382
|
+
// open from hanging on a planted FIFO with no writer, but the
|
|
383
|
+
// content must still not be read from anything but a regular file
|
|
384
|
+
// — re-check on the OPENED fd, which can't be raced the same way.
|
|
385
|
+
// The opened object must be the file this name denotes inside the
|
|
386
|
+
// project (parents included), within the size cap, and is read from
|
|
387
|
+
// the descriptor in bounded steps (utils/regular-file.js).
|
|
388
|
+
try {
|
|
389
|
+
buf = await readPinnedHandle(fh, resolvedAbsPath, await resolveSessionCwd(sessionCwd), 512 * 1024)
|
|
390
|
+
} catch (pinErr) {
|
|
391
|
+
// No path in the text: this reaches the client verbatim.
|
|
392
|
+
if (pinErr.code === 'ENOTREG') throw clientSafeError('Not a regular file')
|
|
393
|
+
if (pinErr.code === 'EFBIG') throw clientSafeError('File too large (max 512KB)')
|
|
394
|
+
if (pinErr.code === 'EACCES') throw Object.assign(new Error('pinned'), { code: 'ELOOP' })
|
|
395
|
+
throw pinErr
|
|
396
|
+
}
|
|
165
397
|
} catch (openErr) {
|
|
166
398
|
if (openErr.code === 'ELOOP') {
|
|
167
399
|
// Symlink appeared at the canonical path after validation — reject
|
|
@@ -233,10 +465,8 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
233
465
|
error: null,
|
|
234
466
|
})
|
|
235
467
|
} catch (err) {
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
else if (err.code === 'EACCES') errorMessage = 'Permission denied'
|
|
239
|
-
else errorMessage = err.message || 'Unknown error'
|
|
468
|
+
log.error(`read_file failed: ${truncateForLog(err.message)}`)
|
|
469
|
+
const errorMessage = fileOpErrorMessage(err, 'Operation failed', { ENOENT: 'File not found' })
|
|
240
470
|
|
|
241
471
|
send({
|
|
242
472
|
type: 'file_content',
|
|
@@ -251,7 +481,7 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
251
481
|
}
|
|
252
482
|
|
|
253
483
|
/** Write file content at a given path within the session CWD */
|
|
254
|
-
async function writeFileContent(ws, requestedPath, content, sessionCwd) {
|
|
484
|
+
async function writeFileContent(ws, requestedPath, content, sessionCwd, isAuthorized) {
|
|
255
485
|
if (!sessionCwd) {
|
|
256
486
|
sendFn(ws, {
|
|
257
487
|
type: 'write_file_result',
|
|
@@ -292,7 +522,8 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
292
522
|
const absInCwd = normalize(resolve(cwdReal, requestedPath.trim()))
|
|
293
523
|
|
|
294
524
|
// Determine whether the target file already exists so we can choose
|
|
295
|
-
// between
|
|
525
|
+
// between a symlink-refusing truncate (existing) and parent-validated
|
|
526
|
+
// creation (new).
|
|
296
527
|
let resolvedTarget
|
|
297
528
|
let fileExists = false
|
|
298
529
|
try {
|
|
@@ -304,49 +535,68 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
304
535
|
// Use the lexical path for the new-file case.
|
|
305
536
|
resolvedTarget = absInCwd
|
|
306
537
|
} else {
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
if (fileExists) {
|
|
312
|
-
// Existing file: validate the resolved (symlink-followed) path
|
|
313
|
-
const { valid: writeValid } = await validatePathWithinCwd(resolvedTarget, sessionCwd)
|
|
314
|
-
if (!writeValid) {
|
|
315
|
-
sendFn(ws, {
|
|
316
|
-
type: 'write_file_result',
|
|
317
|
-
path: requestedPath,
|
|
318
|
-
error: 'Access denied: file writing is restricted to the project directory',
|
|
319
|
-
})
|
|
320
|
-
return
|
|
321
|
-
}
|
|
322
|
-
} else {
|
|
323
|
-
// New file: validate the lexical path is within CWD
|
|
324
|
-
const { valid: writeValid } = await validatePathWithinCwd(absInCwd, sessionCwd)
|
|
325
|
-
if (!writeValid) {
|
|
538
|
+
// #8016 — any other failure used to reach the outer catch, which
|
|
539
|
+
// answered "Permission denied" (EACCES) or the raw Node message,
|
|
540
|
+
// server path included, even for a target outside the project.
|
|
326
541
|
sendFn(ws, {
|
|
327
542
|
type: 'write_file_result',
|
|
328
543
|
path: requestedPath,
|
|
329
|
-
error:
|
|
544
|
+
error: await unresolvablePathError(err, absInCwd, cwdReal, WRITE_UNRESOLVABLE_REASONS,
|
|
545
|
+
'Access denied: file writing is restricted to the project directory'),
|
|
330
546
|
})
|
|
331
547
|
return
|
|
332
548
|
}
|
|
333
549
|
}
|
|
550
|
+
|
|
551
|
+
// Existing file: validate the resolved (symlink-followed) path. New file:
|
|
552
|
+
// validate the lexical path. A check that cannot be answered (a
|
|
553
|
+
// self-referential link's ELOOP, the depth ceiling, a file swapped
|
|
554
|
+
// between the two resolutions) denies rather than sending the helper's
|
|
555
|
+
// own text (#8016).
|
|
556
|
+
let writeValid = false
|
|
557
|
+
try {
|
|
558
|
+
({ valid: writeValid } = await validatePathWithinCwd(fileExists ? resolvedTarget : absInCwd, sessionCwd))
|
|
559
|
+
} catch {
|
|
560
|
+
writeValid = false
|
|
561
|
+
}
|
|
562
|
+
if (!writeValid) {
|
|
563
|
+
sendFn(ws, {
|
|
564
|
+
type: 'write_file_result',
|
|
565
|
+
path: requestedPath,
|
|
566
|
+
error: 'Access denied: file writing is restricted to the project directory',
|
|
567
|
+
})
|
|
568
|
+
return
|
|
569
|
+
}
|
|
334
570
|
absPath = fileExists ? resolvedTarget : absInCwd
|
|
335
571
|
|
|
572
|
+
// Generic file writes refuse the daemon's config directory, so the deploy
|
|
573
|
+
// control files can only be written through `daemon_update_action`. This runs
|
|
574
|
+
// BEFORE the mkdir below: a refused write must not create anything either.
|
|
575
|
+
if (await isConfigDirOrDirectChild(absPath)) {
|
|
576
|
+
sendFn(ws, { type: 'write_file_result', path: requestedPath, error: CONFIG_DIR_REFUSAL })
|
|
577
|
+
return
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// Everything above waited; the requesting connection may have ended.
|
|
581
|
+
if (!stillAuthorized(isAuthorized)) return
|
|
582
|
+
|
|
336
583
|
// Create parent directories if needed
|
|
337
584
|
await mkdir(resolve(absPath, '..'), { recursive: true })
|
|
585
|
+
if (!stillAuthorized(isAuthorized)) return
|
|
338
586
|
|
|
339
|
-
// Write the file
|
|
340
|
-
// window:
|
|
341
|
-
//
|
|
587
|
+
// Write the file through openNoFollow to close the post-validation TOCTOU
|
|
588
|
+
// window: a symlink swapped in at absPath between validation and this
|
|
589
|
+
// open is rejected with ELOOP on every platform (#7280 — the bare
|
|
590
|
+
// O_NOFOLLOW flag this used to pass is undefined on win32 and ORed to 0).
|
|
342
591
|
const data = Buffer.from(content || '', 'utf-8')
|
|
343
592
|
{
|
|
344
593
|
let fh
|
|
345
594
|
try {
|
|
346
595
|
const flags = fileExists
|
|
347
|
-
? fsConstants.O_WRONLY | fsConstants.
|
|
348
|
-
: fsConstants.O_WRONLY | fsConstants.
|
|
349
|
-
fh = await
|
|
596
|
+
? fsConstants.O_WRONLY | fsConstants.O_TRUNC
|
|
597
|
+
: fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL
|
|
598
|
+
fh = await openNoFollow(absPath, flags, 0o666)
|
|
599
|
+
await refuseNonRegular(fh)
|
|
350
600
|
await fh.writeFile(data)
|
|
351
601
|
} catch (openErr) {
|
|
352
602
|
if (openErr.code === 'ELOOP') {
|
|
@@ -362,7 +612,8 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
362
612
|
// Race: file was created between our existence check and O_EXCL open.
|
|
363
613
|
// Retry once using the existing-file path (O_TRUNC without O_EXCL).
|
|
364
614
|
try {
|
|
365
|
-
fh = await
|
|
615
|
+
fh = await openNoFollow(absPath, fsConstants.O_WRONLY | fsConstants.O_TRUNC, 0o666)
|
|
616
|
+
await refuseNonRegular(fh)
|
|
366
617
|
await fh.writeFile(data)
|
|
367
618
|
} catch (retryErr) {
|
|
368
619
|
if (retryErr.code === 'ELOOP') {
|
|
@@ -389,9 +640,8 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
389
640
|
error: null,
|
|
390
641
|
})
|
|
391
642
|
} catch (err) {
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
else errorMessage = err.message || 'Unknown error'
|
|
643
|
+
log.error(`write_file failed: ${truncateForLog(err.message)}`)
|
|
644
|
+
const errorMessage = fileOpErrorMessage(err)
|
|
395
645
|
|
|
396
646
|
sendFn(ws, {
|
|
397
647
|
type: 'write_file_result',
|
|
@@ -401,8 +651,184 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
401
651
|
}
|
|
402
652
|
}
|
|
403
653
|
|
|
404
|
-
/**
|
|
405
|
-
|
|
654
|
+
/**
|
|
655
|
+
* Append a single note line to the session cwd's project memory. Thin Claude
|
|
656
|
+
* adapters route to authored AGENTS.md; legacy CLAUDE.md files are created
|
|
657
|
+
* when absent (#6861, epic #6760).
|
|
658
|
+
*
|
|
659
|
+
* The TARGET is chosen SERVER-side (a fixed cwd filename) — the client sends only
|
|
660
|
+
* the note text, never a path — so the write is path-confined BY CONSTRUCTION.
|
|
661
|
+
* validatePathWithinCwd is still run for symlink-escape defence (a CLAUDE.md
|
|
662
|
+
* symlinked out of the workspace is rejected), and the open goes through
|
|
663
|
+
* openNoFollow to close the post-validation TOCTOU window, matching
|
|
664
|
+
* writeFileContent above.
|
|
665
|
+
*
|
|
666
|
+
* The write uses O_APPEND (+ O_CREAT): each append lands atomically at EOF, so
|
|
667
|
+
* concurrent appends can't lose a line and a crash can't truncate the file —
|
|
668
|
+
* the correct primitive for appending, unlike a read-modify-write O_TRUNC. The
|
|
669
|
+
* only read is a cheap 1-byte tail check to decide whether a separating newline
|
|
670
|
+
* is needed; a race there is benign (a stray/missing separator at worst — the
|
|
671
|
+
* note line itself is always written atomically and in full).
|
|
672
|
+
*/
|
|
673
|
+
async function appendMemory(ws, note, sessionCwd, isAuthorized) {
|
|
674
|
+
if (!sessionCwd) {
|
|
675
|
+
sendFn(ws, { type: 'append_memory_result', path: null, created: false, error: 'Memory is not available in this mode' })
|
|
676
|
+
return
|
|
677
|
+
}
|
|
678
|
+
if (typeof note !== 'string' || !note.trim()) {
|
|
679
|
+
sendFn(ws, { type: 'append_memory_result', path: null, created: false, error: 'No note provided' })
|
|
680
|
+
return
|
|
681
|
+
}
|
|
682
|
+
const MAX_NOTE = 10_000
|
|
683
|
+
if (note.length > MAX_NOTE) {
|
|
684
|
+
sendFn(ws, { type: 'append_memory_result', path: null, created: false, error: `Note too long (max ${MAX_NOTE} characters)` })
|
|
685
|
+
return
|
|
686
|
+
}
|
|
687
|
+
// Collapse to a single line — quick-append is a one-line note by definition.
|
|
688
|
+
const line = note.trim().replace(/\r?\n/g, ' ')
|
|
689
|
+
|
|
690
|
+
let absPath = null
|
|
691
|
+
try {
|
|
692
|
+
const cwdReal = await resolveSessionCwd(sessionCwd)
|
|
693
|
+
const filename = await projectMemoryFilename(cwdReal)
|
|
694
|
+
const target = normalize(resolve(cwdReal, filename))
|
|
695
|
+
|
|
696
|
+
// Resolve symlinks: if CLAUDE.md already exists, validate its real path;
|
|
697
|
+
// if not, validate the lexical target (still inside cwd by construction).
|
|
698
|
+
let resolvedTarget
|
|
699
|
+
let fileExists = false
|
|
700
|
+
try {
|
|
701
|
+
resolvedTarget = await realpath(target)
|
|
702
|
+
fileExists = true
|
|
703
|
+
} catch (err) {
|
|
704
|
+
if (err.code === 'ENOENT') {
|
|
705
|
+
if (filename === 'AGENTS.md') throw clientSafeError('Authored project memory AGENTS.md is missing')
|
|
706
|
+
resolvedTarget = target
|
|
707
|
+
} else {
|
|
708
|
+
// #8016 — a CLAUDE.md link whose target cannot be resolved: same
|
|
709
|
+
// answer as a target outside the project, never the raw text.
|
|
710
|
+
sendFn(ws, {
|
|
711
|
+
type: 'append_memory_result',
|
|
712
|
+
path: null,
|
|
713
|
+
created: false,
|
|
714
|
+
error: await unresolvablePathError(err, target, cwdReal, WRITE_UNRESOLVABLE_REASONS,
|
|
715
|
+
'Access denied: memory is restricted to the project directory'),
|
|
716
|
+
})
|
|
717
|
+
return
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
// A check that cannot be answered denies (#8016).
|
|
722
|
+
let valid = false
|
|
723
|
+
try {
|
|
724
|
+
({ valid } = await validatePathWithinCwd(fileExists ? resolvedTarget : target, sessionCwd))
|
|
725
|
+
} catch {
|
|
726
|
+
valid = false
|
|
727
|
+
}
|
|
728
|
+
if (!valid) {
|
|
729
|
+
sendFn(ws, {
|
|
730
|
+
type: 'append_memory_result',
|
|
731
|
+
path: null,
|
|
732
|
+
created: false,
|
|
733
|
+
error: 'Access denied: memory is restricted to the project directory',
|
|
734
|
+
})
|
|
735
|
+
return
|
|
736
|
+
}
|
|
737
|
+
absPath = fileExists ? resolvedTarget : target
|
|
738
|
+
|
|
739
|
+
// Same rule as write_file: generic writes refuse the config directory.
|
|
740
|
+
if (await isConfigDirOrDirectChild(absPath)) {
|
|
741
|
+
sendFn(ws, { type: 'append_memory_result', path: null, created: false, error: CONFIG_DIR_REFUSAL })
|
|
742
|
+
return
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
// Everything above waited; the requesting connection may have ended.
|
|
746
|
+
if (!stillAuthorized(isAuthorized)) return
|
|
747
|
+
|
|
748
|
+
// Cheap tail check: does the existing file already end with a newline? If
|
|
749
|
+
// not, prepend one so the note lands on its own line. Best-effort (a race
|
|
750
|
+
// only affects the separator, never the note itself).
|
|
751
|
+
let needsLeadingNewline = false
|
|
752
|
+
if (fileExists) {
|
|
753
|
+
try {
|
|
754
|
+
const st = await stat(absPath)
|
|
755
|
+
if (st.size > 0) {
|
|
756
|
+
let rfh
|
|
757
|
+
try {
|
|
758
|
+
// #7938 — openNoFollow's O_NONBLOCK keeps a FIFO raced in at this
|
|
759
|
+
// path from hanging the open. No post-open isFile() check here,
|
|
760
|
+
// deliberately: the read below is a positioned read (pread), and
|
|
761
|
+
// pread on a FIFO fails ESPIPE and on a directory EISDIR, both
|
|
762
|
+
// landing in the advisory catch exactly as a refusal would. A
|
|
763
|
+
// check could not change any outcome (a mutation deleting one
|
|
764
|
+
// survived every test for that reason), and the one byte read is
|
|
765
|
+
// never returned to the client — it only picks the separator.
|
|
766
|
+
rfh = await openNoFollow(absPath, fsConstants.O_RDONLY)
|
|
767
|
+
const tail = Buffer.alloc(1)
|
|
768
|
+
await rfh.read(tail, 0, 1, st.size - 1)
|
|
769
|
+
needsLeadingNewline = tail[0] !== 0x0a
|
|
770
|
+
} finally {
|
|
771
|
+
await rfh?.close()
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
} catch {
|
|
775
|
+
// Tail read is advisory only — fall back to no separator.
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
if (!stillAuthorized(isAuthorized)) return
|
|
780
|
+
const data = Buffer.from((needsLeadingNewline ? '\n' : '') + line + '\n', 'utf-8')
|
|
781
|
+
|
|
782
|
+
// O_APPEND: atomic append at EOF (no lost-update / truncation window).
|
|
783
|
+
// Legacy files use O_CREAT without O_EXCL, so a concurrent creator just
|
|
784
|
+
// means we append instead. Authored rules must still exist at the open:
|
|
785
|
+
// a source removed by another operation must not be recreated as a note.
|
|
786
|
+
// openNoFollow keeps the symlink-escape defence on the final component, on win32 as
|
|
787
|
+
// well as POSIX (#7280).
|
|
788
|
+
{
|
|
789
|
+
let fh
|
|
790
|
+
try {
|
|
791
|
+
let flags = fsConstants.O_WRONLY | fsConstants.O_APPEND
|
|
792
|
+
if (filename !== 'AGENTS.md') flags |= fsConstants.O_CREAT
|
|
793
|
+
fh = await openNoFollow(absPath, flags, 0o666)
|
|
794
|
+
await refuseNonRegular(fh)
|
|
795
|
+
await fh.writeFile(data)
|
|
796
|
+
} catch (openErr) {
|
|
797
|
+
if (openErr.code === 'ENOENT' && filename === 'AGENTS.md') {
|
|
798
|
+
throw clientSafeError('Authored project memory AGENTS.md is missing')
|
|
799
|
+
}
|
|
800
|
+
if (openErr.code === 'ELOOP') {
|
|
801
|
+
sendFn(ws, {
|
|
802
|
+
type: 'append_memory_result',
|
|
803
|
+
path: null,
|
|
804
|
+
created: false,
|
|
805
|
+
error: 'Access denied: memory is restricted to the project directory',
|
|
806
|
+
})
|
|
807
|
+
return
|
|
808
|
+
}
|
|
809
|
+
throw openErr
|
|
810
|
+
} finally {
|
|
811
|
+
await fh?.close()
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
sendFn(ws, { type: 'append_memory_result', path: absPath, created: !fileExists, error: null })
|
|
816
|
+
} catch (err) {
|
|
817
|
+
log.error(`append_memory failed: ${truncateForLog(err.message)}`)
|
|
818
|
+
const errorMessage = fileOpErrorMessage(err)
|
|
819
|
+
sendFn(ws, { type: 'append_memory_result', path: absPath, created: false, error: errorMessage })
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* Get git diff for uncommitted changes in the session CWD.
|
|
825
|
+
*
|
|
826
|
+
* `confineToCwd` (a session-scoped connection) limits the answer to files at or
|
|
827
|
+
* beneath the session's own directory. `git diff` reports the whole
|
|
828
|
+
* repository, and several sessions can share one repository, so without it the
|
|
829
|
+
* diff would include files belonging to a sibling's directory.
|
|
830
|
+
*/
|
|
831
|
+
async function getDiff(ws, base, sessionCwd, { confineToCwd = false } = {}) {
|
|
406
832
|
if (!sessionCwd) {
|
|
407
833
|
sendFn(ws, {
|
|
408
834
|
type: 'diff_result',
|
|
@@ -417,67 +843,173 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
417
843
|
|
|
418
844
|
// Check if the directory is a git repository before running git commands
|
|
419
845
|
try {
|
|
420
|
-
|
|
846
|
+
// #7877 — LC_ALL/LANG=C: the classification below reads git's stderr
|
|
847
|
+
// for an English substring. Left to the daemon host's own locale, a
|
|
848
|
+
// translated "not a git repository" message would silently miss that
|
|
849
|
+
// substring and fall into the "other exit-128" branch on EVERY
|
|
850
|
+
// request from that host — exactly the per-request log spam #7862's
|
|
851
|
+
// review downgrade was trying to avoid. Forcing C here makes the
|
|
852
|
+
// classification locale-independent without touching any other git
|
|
853
|
+
// invocation in this function (none of the others string-match stderr).
|
|
854
|
+
await execImpl(GIT, ['rev-parse', '--git-dir'], {
|
|
421
855
|
cwd: cwdReal,
|
|
422
856
|
timeout: 5000,
|
|
857
|
+
env: { ...process.env, LC_ALL: 'C', LANG: 'C' },
|
|
423
858
|
})
|
|
424
859
|
} catch (revParseErr) {
|
|
425
860
|
const stderr = (revParseErr.stderr || revParseErr.message || '').toLowerCase()
|
|
426
|
-
|
|
427
|
-
|
|
861
|
+
// #7877 — git exits 128 for MANY fatals, not only "not a git
|
|
862
|
+
// repository": `fatal: detected dubious ownership in repository at
|
|
863
|
+
// '<path>'` (mounted volumes, container/worktree setups) is the one
|
|
864
|
+
// chroxy actually hits. The old `stderr.includes(...) || code === 128`
|
|
865
|
+
// OR'd every other 128 into the same bucket, so a dubious-ownership
|
|
866
|
+
// session was misreported to the client AND logged nowhere — the
|
|
867
|
+
// operator had no trace of the real cause.
|
|
868
|
+
//
|
|
869
|
+
// The client-facing contract is UNCHANGED here on purpose (still a
|
|
870
|
+
// fixed 'Not a git repository' for any exit-128, never raw stderr —
|
|
871
|
+
// #7298 must hold): the fix is that an "other 128" is now visible to
|
|
872
|
+
// the operator. `isOtherExit128Fatal` is exactly the case the old
|
|
873
|
+
// predicate swallowed: an exit-128 whose stderr, in the forced C
|
|
874
|
+
// locale above, does NOT actually say "not a git repository".
|
|
875
|
+
const isGenuineNotGitRepo = stderr.includes('not a git repository')
|
|
876
|
+
const isOtherExit128Fatal = !isGenuineNotGitRepo && revParseErr.code === 128
|
|
877
|
+
const isNotGitRepo = isGenuineNotGitRepo || isOtherExit128Fatal
|
|
878
|
+
|
|
879
|
+
if (isOtherExit128Fatal) {
|
|
880
|
+
// Routine-ish (dubious ownership, etc.) but worth an operator's
|
|
881
|
+
// attention — warn, not error, and not silence (#7877).
|
|
882
|
+
log.warn(`git rev-parse --git-dir exited 128 without a "not a git repository" message — classified as non-repo anyway: ${truncateForLog(revParseErr.message)}`)
|
|
883
|
+
} else if (!isNotGitRepo) {
|
|
884
|
+
// Only the genuinely UNEXPECTED failure (git missing, timeout,
|
|
885
|
+
// EACCES) logs at error level. "Not a git repository" is the
|
|
886
|
+
// ordinary state of a session whose cwd is not a checkout, and it
|
|
887
|
+
// arrives on every `get_diff` that session sends — logging it at
|
|
888
|
+
// error level buries the failures worth reading, which is the same
|
|
889
|
+
// defect as not logging at all (Copilot review of #7862).
|
|
890
|
+
log.error(`git rev-parse --git-dir failed: ${truncateForLog(revParseErr.message)}`)
|
|
891
|
+
}
|
|
428
892
|
sendFn(ws, {
|
|
429
893
|
type: 'diff_result',
|
|
430
894
|
files: [],
|
|
431
|
-
error: isNotGitRepo
|
|
432
|
-
? 'Not a git repository'
|
|
433
|
-
: `Git error: ${revParseErr.message || 'unknown failure'}`,
|
|
895
|
+
error: isNotGitRepo ? 'Not a git repository' : 'Failed to run git diff',
|
|
434
896
|
})
|
|
435
897
|
return
|
|
436
898
|
}
|
|
437
899
|
|
|
438
900
|
const rawBase = (typeof base === 'string' && base.trim()) ? base.trim() : 'HEAD'
|
|
439
|
-
//
|
|
440
|
-
|
|
901
|
+
// #7290: `base` is client-controlled and UNVALIDATED on the wire —
|
|
902
|
+
// GetDiffSchema is `z.object({ type }).passthrough()` — and it lands in
|
|
903
|
+
// the REVISION slot of `git diff <base>`. The charset allowlist below
|
|
904
|
+
// used to be the only check, and it put `-` INSIDE its character class,
|
|
905
|
+
// so every single-token option passed it: `--stat`, `-p`, `--exit-code`,
|
|
906
|
+
// `--ext-diff`, and `-O<path>` — which makes git read <path> as a diff
|
|
907
|
+
// orderfile and report whether it could, straight back to the client,
|
|
908
|
+
// which at the time forwarded `err.message` verbatim (see #7298 below).
|
|
909
|
+
//
|
|
910
|
+
// isSafeArgvValue is the load-bearing half (it rejects the leading dash);
|
|
911
|
+
// the allowlist stays as a charset narrowing. A `--` separator canNOT
|
|
912
|
+
// substitute for either — see utils/argv-safety.js for the measurements.
|
|
913
|
+
// A git revision can never legitimately begin with `-`, so REJECTING is
|
|
914
|
+
// correct here; falling back to 'HEAD' preserves the pre-existing
|
|
915
|
+
// contract for any unusable base.
|
|
916
|
+
//
|
|
917
|
+
// #7298 — HALF 1 of 2. The charset above is a NARROWING, never a
|
|
918
|
+
// decision: it cannot tell a revision from a path, and `:` and `/` used
|
|
919
|
+
// to be members, so `HEAD:<path>` and a bare absolute path both reached
|
|
920
|
+
// git as revisions and git answered on the wire (measured, git 2.55.0):
|
|
921
|
+
//
|
|
922
|
+
// base='HEAD:/etc/passwd' -> fatal: path '/etc/passwd' exists on
|
|
923
|
+
// disk, but not in 'HEAD'
|
|
924
|
+
// base='HEAD:absent' -> fatal: path 'absent' does not exist in 'HEAD'
|
|
925
|
+
// base='/etc/passwd' -> fatal: '/etc/passwd' is outside
|
|
926
|
+
// repository at '<cwdReal>'
|
|
927
|
+
//
|
|
928
|
+
// — a filesystem-wide path-existence oracle, as the daemon user,
|
|
929
|
+
// escaping the session cwd, plus the workspace path itself.
|
|
930
|
+
//
|
|
931
|
+
// So RESOLVE the base instead of pattern-matching it: only a revision
|
|
932
|
+
// that names a real commit in THIS repo is ever handed to `git diff`,
|
|
933
|
+
// and everything else falls back to HEAD (the pre-existing contract for
|
|
934
|
+
// an unusable base) without git being asked the client's question at
|
|
935
|
+
// all. `rev-parse --verify --quiet` is silent on failure — it exits 1
|
|
936
|
+
// with empty stderr for every probe above — so the resolution step is
|
|
937
|
+
// not itself an oracle. `:` is dropped from the charset in the same
|
|
938
|
+
// change: `<rev>:<path>` names a BLOB, never a commit.
|
|
939
|
+
//
|
|
940
|
+
// Do NOT "harden" this by appending a `--` to the diff argv instead.
|
|
941
|
+
// That changes an unresolvable base's error to `fatal: bad revision`,
|
|
942
|
+
// which the old `unknown revision` recovery predicate missed — and `--`
|
|
943
|
+
// does not stop option parsing for a token that precedes it anyway
|
|
944
|
+
// (#7290, utils/argv-safety.js).
|
|
945
|
+
// The length bound is the third gate, and it is about COST rather than
|
|
946
|
+
// about the oracle: `base` is unconstrained on the wire (#7870), and
|
|
947
|
+
// every byte of it is spawned twice (both `rev-parse` calls) and can be
|
|
948
|
+
// echoed back into an error message. A revision is short, so nothing
|
|
949
|
+
// legitimate is rejected. Only the LENGTH is logged — never the value,
|
|
950
|
+
// which is the input this whole function exists to distrust.
|
|
951
|
+
if (rawBase.length > MAX_DIFF_BASE_LENGTH) {
|
|
952
|
+
log.warn(`get_diff base rejected: ${rawBase.length} chars exceeds the ${MAX_DIFF_BASE_LENGTH}-char limit`)
|
|
953
|
+
}
|
|
954
|
+
const candidate = (
|
|
955
|
+
rawBase.length <= MAX_DIFF_BASE_LENGTH &&
|
|
956
|
+
isSafeArgvValue(rawBase) &&
|
|
957
|
+
/^[a-zA-Z0-9._\-\/~^@{}]+$/.test(rawBase)
|
|
958
|
+
)
|
|
959
|
+
? rawBase
|
|
960
|
+
: 'HEAD'
|
|
961
|
+
|
|
962
|
+
/** Resolve a revision to a commit OID, or null when it names no commit. */
|
|
963
|
+
const resolveCommit = async (rev) => {
|
|
964
|
+
try {
|
|
965
|
+
const { stdout } = await execImpl(
|
|
966
|
+
GIT, ['rev-parse', '--verify', '--quiet', `${rev}^{commit}`],
|
|
967
|
+
{ cwd: cwdReal, timeout: 5000 }
|
|
968
|
+
)
|
|
969
|
+
return stdout.trim() || null
|
|
970
|
+
} catch {
|
|
971
|
+
return null
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
const headOid = await resolveCommit('HEAD')
|
|
976
|
+
// An unresolvable base is HEAD. HEAD itself is unresolvable only in a
|
|
977
|
+
// repo with no commits, where `git diff HEAD` used to fail into the
|
|
978
|
+
// `unknown revision` recovery — so go straight to the plain `git diff`
|
|
979
|
+
// that recovery ran, and drop the stderr-substring predicate with it.
|
|
980
|
+
const baseOid = candidate === 'HEAD'
|
|
981
|
+
? headOid
|
|
982
|
+
: (await resolveCommit(candidate)) || headOid
|
|
983
|
+
const baseIsHead = baseOid === null || baseOid === headOid
|
|
441
984
|
|
|
442
985
|
let diffOutput = ''
|
|
443
986
|
try {
|
|
444
|
-
const { stdout } = await
|
|
987
|
+
const { stdout } = await execImpl(GIT, [...DIFF_PIN_CONFIG, 'diff', ...DIFF_HEADER_ARGS, ...(baseOid ? [baseOid] : []), ...(confineToCwd ? DIFF_CWD_PATHSPEC : [])], {
|
|
445
988
|
cwd: cwdReal,
|
|
446
989
|
maxBuffer: 2 * 1024 * 1024,
|
|
447
990
|
timeout: 10000,
|
|
448
991
|
})
|
|
449
992
|
diffOutput = stdout
|
|
450
993
|
} catch (err) {
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
})
|
|
465
|
-
return
|
|
466
|
-
}
|
|
467
|
-
} else {
|
|
468
|
-
sendFn(ws, {
|
|
469
|
-
type: 'diff_result',
|
|
470
|
-
files: [],
|
|
471
|
-
error: err.message || 'Failed to run git diff',
|
|
472
|
-
})
|
|
473
|
-
return
|
|
474
|
-
}
|
|
994
|
+
// #7298 — HALF 2 of 2. Raw git stderr used to go to the client
|
|
995
|
+
// verbatim, which is what made every message above readable on the
|
|
996
|
+
// wire. Half 1 keeps the client's own string out of that stderr, but
|
|
997
|
+
// any git failure can name a path (the workspace, an object, a
|
|
998
|
+
// config), so the detail stays server-side and the wire gets a fixed
|
|
999
|
+
// string. Both halves are load-bearing; neither is redundant.
|
|
1000
|
+
log.error(`git diff failed: ${truncateForLog(err.message)}`)
|
|
1001
|
+
sendFn(ws, {
|
|
1002
|
+
type: 'diff_result',
|
|
1003
|
+
files: [],
|
|
1004
|
+
error: 'Failed to run git diff',
|
|
1005
|
+
})
|
|
1006
|
+
return
|
|
475
1007
|
}
|
|
476
1008
|
|
|
477
|
-
// Also get staged changes if
|
|
478
|
-
if (
|
|
1009
|
+
// Also get staged changes if the effective base is HEAD
|
|
1010
|
+
if (baseIsHead) {
|
|
479
1011
|
try {
|
|
480
|
-
const { stdout: stagedOutput } = await
|
|
1012
|
+
const { stdout: stagedOutput } = await execImpl(GIT, [...DIFF_PIN_CONFIG, 'diff', ...DIFF_HEADER_ARGS, '--cached', 'HEAD', ...(confineToCwd ? DIFF_CWD_PATHSPEC : [])], {
|
|
481
1013
|
cwd: cwdReal,
|
|
482
1014
|
maxBuffer: 2 * 1024 * 1024,
|
|
483
1015
|
timeout: 10000,
|
|
@@ -490,7 +1022,39 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
490
1022
|
}
|
|
491
1023
|
}
|
|
492
1024
|
|
|
493
|
-
|
|
1025
|
+
let files = diffOutput.trim() ? parseDiff(diffOutput) : []
|
|
1026
|
+
|
|
1027
|
+
// Files directly in the config directory are daemon-managed state, so the
|
|
1028
|
+
// diff view treats them the way the file viewer and generic writes do: a
|
|
1029
|
+
// changed one is left out of the reply, hunks and all, rather than listed by
|
|
1030
|
+
// name. `git diff` names files from the repository root (not the session
|
|
1031
|
+
// cwd), and an entry can touch more than one path (the source of a rename).
|
|
1032
|
+
// An entry with no placeable path is left out too: "could not check" must
|
|
1033
|
+
// never read as "not in the config directory".
|
|
1034
|
+
if (files.length > 0) {
|
|
1035
|
+
const { stdout: topOut } = await execImpl(GIT, ['rev-parse', '--show-toplevel'], {
|
|
1036
|
+
cwd: cwdReal,
|
|
1037
|
+
timeout: 5000,
|
|
1038
|
+
})
|
|
1039
|
+
const repoRoot = topOut.trim()
|
|
1040
|
+
if (!repoRoot) throw new Error('git rev-parse --show-toplevel printed nothing')
|
|
1041
|
+
const headerPaths = diffFileHeaderPaths(diffOutput)
|
|
1042
|
+
const shown = []
|
|
1043
|
+
for (let i = 0; i < files.length; i++) {
|
|
1044
|
+
const touched = headerPaths[i] ?? []
|
|
1045
|
+
let inConfigDir = touched.length === 0
|
|
1046
|
+
for (const p of touched) {
|
|
1047
|
+
if (await isConfigDirOrDirectChild(resolve(repoRoot, p))) { inConfigDir = true; break }
|
|
1048
|
+
}
|
|
1049
|
+
if (inConfigDir) continue
|
|
1050
|
+
// A confined reader keeps an entry only when EVERY path it touches (a
|
|
1051
|
+
// rename names two) is inside the session directory. The pathspec above
|
|
1052
|
+
// already limits what git reports; this does not trust it to.
|
|
1053
|
+
if (confineToCwd && !touched.every((p) => isPathWithin(resolve(repoRoot, p), cwdReal))) continue
|
|
1054
|
+
shown.push(files[i])
|
|
1055
|
+
}
|
|
1056
|
+
files = shown
|
|
1057
|
+
}
|
|
494
1058
|
|
|
495
1059
|
// Deduplicate files that appear in both unstaged and staged diffs
|
|
496
1060
|
const seen = new Map()
|
|
@@ -507,15 +1071,23 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
507
1071
|
|
|
508
1072
|
// Discover untracked files (new files not yet staged)
|
|
509
1073
|
try {
|
|
510
|
-
const { stdout: untrackedOutput } = await
|
|
1074
|
+
const { stdout: untrackedOutput } = await execImpl(
|
|
511
1075
|
GIT, ['ls-files', '--others', '--exclude-standard'],
|
|
512
1076
|
{ cwd: cwdReal, maxBuffer: 512 * 1024, timeout: 5000 }
|
|
513
1077
|
)
|
|
514
1078
|
if (untrackedOutput.trim()) {
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
1079
|
+
// Files directly in the config directory are daemon-managed state and are left
|
|
1080
|
+
// out (as in the tracked-file filter above, and as a file outside the project
|
|
1081
|
+
// is left out in the loop below). They are dropped BEFORE the cap of ten, so a
|
|
1082
|
+
// config root that holds ten or more of them cannot fill the slots and hide
|
|
1083
|
+
// every ordinary file after them. `isConfigDirOrDirectChild` resolves symlinks,
|
|
1084
|
+
// so a link to such a file is dropped too.
|
|
1085
|
+
const untrackedPaths = []
|
|
1086
|
+
for (const p of untrackedOutput.trim().split('\n').filter(p => p && !seen.has(p)).sort()) {
|
|
1087
|
+
if (untrackedPaths.length >= 10) break
|
|
1088
|
+
if (await isConfigDirOrDirectChild(resolve(cwdReal, p))) continue
|
|
1089
|
+
untrackedPaths.push(p)
|
|
1090
|
+
}
|
|
519
1091
|
|
|
520
1092
|
const MAX_UNTRACKED_SIZE = 50 * 1024
|
|
521
1093
|
for (const filePath of untrackedPaths) {
|
|
@@ -531,7 +1103,8 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
531
1103
|
lines = [{ type: 'context', content: `File too large to preview (${(fileStat.size / 1024).toFixed(1)} KB)` }]
|
|
532
1104
|
additions = 0
|
|
533
1105
|
} else {
|
|
534
|
-
const buf = await
|
|
1106
|
+
const buf = await readContainedBytes(validation.realPath, cwdReal, MAX_UNTRACKED_SIZE)
|
|
1107
|
+
if (buf === null) continue
|
|
535
1108
|
const checkLen = Math.min(buf.length, 8192)
|
|
536
1109
|
let isBinary = false
|
|
537
1110
|
for (let i = 0; i < checkLen; i++) {
|
|
@@ -579,10 +1152,18 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
579
1152
|
error: null,
|
|
580
1153
|
})
|
|
581
1154
|
} catch (err) {
|
|
1155
|
+
// #7298 — the last raw-message branch, and the one that names the
|
|
1156
|
+
// workspace without any help from the client: this catch wraps
|
|
1157
|
+
// `resolveSessionCwd`, whose `realpath()` throws
|
|
1158
|
+
// `ENOENT: no such file or directory, realpath '<cwdReal>'` when the
|
|
1159
|
+
// session cwd is gone (removed worktree, unmounted volume, rename).
|
|
1160
|
+
// That is the same `cwdReal` leak the issue is about, reachable by a
|
|
1161
|
+
// bound client sending a bare `get_diff` with no crafted base at all.
|
|
1162
|
+
log.error(`getDiff failed: ${truncateForLog(err.message)}`)
|
|
582
1163
|
sendFn(ws, {
|
|
583
1164
|
type: 'diff_result',
|
|
584
1165
|
files: [],
|
|
585
|
-
error:
|
|
1166
|
+
error: 'Failed to run git diff',
|
|
586
1167
|
})
|
|
587
1168
|
}
|
|
588
1169
|
}
|
|
@@ -590,6 +1171,7 @@ export function createReaderOps(sendFn, resolveSessionCwd, validatePathWithinCwd
|
|
|
590
1171
|
return {
|
|
591
1172
|
readFile: readFileContent,
|
|
592
1173
|
writeFile: writeFileContent,
|
|
1174
|
+
appendMemory,
|
|
593
1175
|
getDiff,
|
|
594
1176
|
}
|
|
595
1177
|
}
|