@chroxy/server 0.11.0 → 0.11.11
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 +206 -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 +958 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +304 -0
- package/src/agent-control/client.js +1645 -0
- package/src/agent-control/events.js +551 -0
- package/src/agent-control/local-connection.js +293 -0
- package/src/agent-control/mcp-server.js +547 -0
- package/src/anthropic-compatible-config.js +30 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- 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 +1520 -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 +291 -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 +633 -122
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +37 -23
- package/src/byok-session.js +707 -179
- package/src/byok-tool-executor.js +2742 -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-setting-sources.js +74 -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 +215 -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 +3563 -284
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-cmd.js +236 -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/connection-state.js +54 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +91 -40
- package/src/cli/server-cmd.js +54 -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/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- 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 +1250 -126
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1517 -81
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-error-text.js +114 -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 +449 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +306 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +78 -23
- 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 +227 -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 +42 -39
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +28 -39
- 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 +170 -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 +294 -11
- package/src/doctor.js +781 -64
- package/src/durable-write.js +35 -0
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +101 -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 +186 -235
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +540 -80
- package/src/handlers/checkpoint-handlers.js +47 -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/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +714 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +92 -18
- package/src/handlers/session-handlers.js +551 -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 +372 -50
- package/src/handlers/skills-handlers.js +20 -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 +112 -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 +378 -91
- package/src/jsonl-subprocess-session.js +96 -9
- package/src/keychain.js +1 -1
- package/src/logger.js +166 -30
- package/src/mailbox-route.js +113 -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 +27 -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 +112 -36
- package/src/orchestration/permission-gate.js +17 -2
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +185 -43
- package/src/orphan-reaper.js +470 -0
- package/src/outgoing-policy.js +189 -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 +1410 -43
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +737 -89
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +126 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +315 -47
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +209 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +531 -20
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +330 -26
- package/src/scheduler.js +368 -11
- package/src/sdk-session.js +2114 -188
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +17 -3
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +553 -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 +1099 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +4062 -312
- package/src/session-message-history.js +841 -16
- package/src/session-name-allocator.js +685 -0
- 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 +100 -29
- package/src/summarize-session.js +53 -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 +140 -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 +770 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +639 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +29 -0
- package/src/utils/bounded-regex.js +162 -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/pid-liveness.js +47 -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 +297 -16
- package/src/worktree-gc.js +202 -6
- package/src/ws-auth.js +163 -31
- package/src/ws-broadcaster.js +49 -5
- package/src/ws-client-manager.js +24 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +363 -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 +349 -39
- package/src/ws-handler-context.js +88 -2
- package/src/ws-history.js +1010 -175
- package/src/ws-message-handlers.js +25 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +885 -98
- 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/permission-floor.js
CHANGED
|
@@ -17,17 +17,18 @@
|
|
|
17
17
|
* so `auto`/`acceptEdits` on claude-tui read `.env` / `id_rsa` ungated. Keep the
|
|
18
18
|
* floor HERE — never reimplement it in the shell hook or a second JS call site
|
|
19
19
|
* (the #6986/#7001 lesson: divergent copies of a security check are how these
|
|
20
|
-
* bugs happen). A leaf module by design (no
|
|
21
|
-
* store) so an HTTP handler can import it without pulling in PermissionManager
|
|
20
|
+
* bugs happen). A leaf module by design (no EventEmitter, no rule
|
|
21
|
+
* store; its one sibling import is the config-dir resolver) so an HTTP handler can import it without pulling in PermissionManager
|
|
22
22
|
* or joining its permission-rule-store import cycle — the same shape as
|
|
23
23
|
* `redaction.js`, the sanitizer both paths already share.
|
|
24
24
|
*
|
|
25
25
|
* Everything here is PURE except the deliberate symlink resolution (realpath /
|
|
26
26
|
* lstat), which FAILS CLOSED — see {@link isProtectedPathValue}.
|
|
27
27
|
*/
|
|
28
|
-
import { realpathSync } from 'node:fs'
|
|
29
|
-
import { resolve, relative, sep, isAbsolute, dirname, basename, join } from 'node:path'
|
|
28
|
+
import { realpathSync, lstatSync, statSync } from 'node:fs'
|
|
29
|
+
import path, { resolve, relative, sep, isAbsolute, dirname, basename, join } from 'node:path'
|
|
30
30
|
import { resolveTargetComponentwiseSync } from './utils/componentwise-resolver.js'
|
|
31
|
+
import { claudeConfigDir, claudeHomeDir } from './utils/claude-config-dir.js'
|
|
31
32
|
|
|
32
33
|
// #6794 — hardcoded protected-path floor. Even under lenient settings (auto /
|
|
33
34
|
// acceptEdits / a broad `allow` rule) Chroxy must not SILENTLY auto-approve a
|
|
@@ -51,7 +52,7 @@ const PROTECTED_DIR_SEGMENTS = new Set(['.git', '.claude', '.vscode'])
|
|
|
51
52
|
// is a common benign operation and must not prompt, but auto-reading a private
|
|
52
53
|
// key or an env file under a broad `allow Read` must not silently succeed.
|
|
53
54
|
//
|
|
54
|
-
// Matched (
|
|
55
|
+
// Matched (as written and in canonical form, see canonicalName) at ANY path segment:
|
|
55
56
|
// - `.env` or `.env.*` → env files (.env / .env.local / …)
|
|
56
57
|
// - one of SECRET_FILE_EXACT → SSH keys, credential dotfiles
|
|
57
58
|
// - a segment ending in an extension in SECRET_FILE_EXTENSIONS → PEM / keys /
|
|
@@ -61,8 +62,17 @@ const PROTECTED_DIR_SEGMENTS = new Set(['.git', '.claude', '.vscode'])
|
|
|
61
62
|
const SECRET_FILE_EXACT = new Set([
|
|
62
63
|
'id_rsa', 'id_dsa', 'id_ecdsa', 'id_ed25519', // SSH private keys
|
|
63
64
|
'.npmrc', '.pgpass', '.netrc', // credential dotfiles
|
|
65
|
+
'.credentials.json', // claude's stored login, wherever its config dir is
|
|
64
66
|
])
|
|
67
|
+
// Files that configure what a session loads and runs. Floored for WRITES only
|
|
68
|
+
// (full floor); reading one is benign, like the other config files above.
|
|
69
|
+
const PROTECTED_WRITE_FILE_NAMES = new Set(['.mcp.json'])
|
|
65
70
|
const SECRET_FILE_EXTENSIONS = ['.pem', '.key', '.p12', '.pfx']
|
|
71
|
+
// The env-file family: exactly `.env`, or `.env.` followed by anything. Named so
|
|
72
|
+
// the #7978 glob analysis below builds its templates from the same two spellings
|
|
73
|
+
// isSecretFileSegment tests, rather than from a second copy of them.
|
|
74
|
+
const ENV_FILE_NAME = '.env'
|
|
75
|
+
const ENV_FILE_PREFIX = '.env.'
|
|
66
76
|
|
|
67
77
|
// Tool-input fields that name a filesystem target. Presence of one is what
|
|
68
78
|
// makes a tool "path-carrying" for the floor (Write/Edit → file_path,
|
|
@@ -73,6 +83,48 @@ const SECRET_FILE_EXTENSIONS = ['.pem', '.key', '.p12', '.pfx']
|
|
|
73
83
|
// path field (a path-redirect would let an edit slip past the protected floor).
|
|
74
84
|
export const PROTECTED_PATH_INPUT_FIELDS = ['file_path', 'path', 'notebook_path']
|
|
75
85
|
|
|
86
|
+
/**
|
|
87
|
+
* The paths a patch-shaped `changes` array names: each member's `path`, and the
|
|
88
|
+
* destination of a rename (`kind.move_path`, the app-server `PatchChangeKind`
|
|
89
|
+
* shape). One extraction, used by the protected-path floor and by path-scoped
|
|
90
|
+
* rules, so both look at the same set of paths.
|
|
91
|
+
*
|
|
92
|
+
* `complete` is false when `changes` is not an array, or any member is not an
|
|
93
|
+
* object with a non-empty string `path` and a supported `kind` (`add`, `update`
|
|
94
|
+
* or `delete`, as a string or as `{ type }`), or carries a `move_path` that is
|
|
95
|
+
* neither absent/null nor a non-empty string. A caller that must see every path
|
|
96
|
+
* (a scoped rule) treats an incomplete list as no match; the floor uses the
|
|
97
|
+
* paths that are present.
|
|
98
|
+
* @param {*} changes
|
|
99
|
+
* @returns {{ complete: boolean, paths: string[] }}
|
|
100
|
+
*/
|
|
101
|
+
// The change kinds the app-server passes, as a bare string (legacy) or as `type`.
|
|
102
|
+
const PATCH_CHANGE_KINDS = new Set(['add', 'update', 'delete'])
|
|
103
|
+
|
|
104
|
+
export function collectChangeTargets(changes) {
|
|
105
|
+
const paths = []
|
|
106
|
+
if (!Array.isArray(changes)) return { complete: false, paths }
|
|
107
|
+
let complete = true
|
|
108
|
+
for (const change of changes) {
|
|
109
|
+
if (!change || typeof change !== 'object') { complete = false; continue }
|
|
110
|
+
if (typeof change.path === 'string' && change.path.length > 0) paths.push(change.path)
|
|
111
|
+
else complete = false
|
|
112
|
+
const kind = change.kind
|
|
113
|
+
if (typeof kind === 'string') {
|
|
114
|
+
// The legacy bare-string form.
|
|
115
|
+
if (!PATCH_CHANGE_KINDS.has(kind)) complete = false
|
|
116
|
+
} else if (kind && typeof kind === 'object' && PATCH_CHANGE_KINDS.has(kind.type)) {
|
|
117
|
+
if (kind.move_path != null) {
|
|
118
|
+
if (typeof kind.move_path === 'string' && kind.move_path.length > 0) paths.push(kind.move_path)
|
|
119
|
+
else complete = false
|
|
120
|
+
}
|
|
121
|
+
} else {
|
|
122
|
+
complete = false
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return { complete, paths }
|
|
126
|
+
}
|
|
127
|
+
|
|
76
128
|
// #6803 — tools whose floor is SECRETS-ONLY (non-mutating reads). handlePermission
|
|
77
129
|
// routes these through isSecretReadTarget (env files + key material) instead of
|
|
78
130
|
// the full config-dir floor. EVERY OTHER path-carrying tool — the mutating ones
|
|
@@ -82,14 +134,14 @@ export const PROTECTED_PATH_INPUT_FIELDS = ['file_path', 'path', 'notebook_path'
|
|
|
82
134
|
export const SECRET_READ_FLOOR_TOOLS = new Set(['Read', 'Glob', 'Grep'])
|
|
83
135
|
|
|
84
136
|
/**
|
|
85
|
-
* #6803 — is a single (
|
|
137
|
+
* #6803 — is a single path segment (lowercased as written, or canonical — see canonicalName) a known secret FILE?
|
|
86
138
|
* Env files, SSH/credential dotfiles, and PEM/key/keystore extensions. Pure
|
|
87
139
|
* string ops (no regex) so it can't be mangled by a later edit.
|
|
88
|
-
* @param {string} seg a lowercased path segment
|
|
140
|
+
* @param {string} seg a lowercased or canonical path segment
|
|
89
141
|
* @returns {boolean}
|
|
90
142
|
*/
|
|
91
143
|
function isSecretFileSegment(seg) {
|
|
92
|
-
if (seg ===
|
|
144
|
+
if (seg === ENV_FILE_NAME || seg.startsWith(ENV_FILE_PREFIX)) return true
|
|
93
145
|
if (SECRET_FILE_EXACT.has(seg)) return true
|
|
94
146
|
for (const ext of SECRET_FILE_EXTENSIONS) {
|
|
95
147
|
if (seg.length > ext.length && seg.endsWith(ext)) return true
|
|
@@ -110,26 +162,238 @@ function isSecretFileSegment(seg) {
|
|
|
110
162
|
* the config dirs (`.claude/skills/*.md`, a secret-free `.vscode/settings.json`)
|
|
111
163
|
* stay un-floored for reads per #6803's intent.
|
|
112
164
|
*
|
|
113
|
-
* Matched as a 2-/3-segment sequence anchored at index `i` of the (lowercased,
|
|
165
|
+
* Matched as a 2-/3-segment sequence anchored at index `i` of the (lowercased or canonical,
|
|
114
166
|
* `..`-stripped) segment array, so any depth prefix (`sub/.git/config`) matches.
|
|
115
167
|
* Pure string ops (no regex) — consistent with the rest of the floor.
|
|
116
|
-
* @param {string[]} segments lowercased path segments
|
|
168
|
+
* @param {string[]} segments lowercased or canonical path segments
|
|
117
169
|
* @param {number} i the current segment index
|
|
118
170
|
* @returns {boolean}
|
|
119
171
|
*/
|
|
120
172
|
function isCredentialConfigSegment(segments, i) {
|
|
121
|
-
|
|
122
|
-
//
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
(segments[i + 2] === 'config' || segments[i + 2] === 'credentials')) return true
|
|
173
|
+
// .git/config (PAT-embedded remote URLs), .git/credentials (git store), and
|
|
174
|
+
// the XDG equivalents under .config/git/.
|
|
175
|
+
for (const sequence of CREDENTIAL_CONFIG_SEQUENCES) {
|
|
176
|
+
if (sequence.every((name, k) => segments[i + k] === name)) return true
|
|
177
|
+
}
|
|
127
178
|
// .claude/settings*.json (settings.json / settings.local.json — may hold keys).
|
|
128
179
|
const child = segments[i + 1]
|
|
129
|
-
if (
|
|
180
|
+
if (segments[i] === CLAUDE_SETTINGS_DIR && typeof child === 'string' &&
|
|
181
|
+
child.startsWith(CLAUDE_SETTINGS_PREFIX) && child.endsWith(CLAUDE_SETTINGS_SUFFIX)) return true
|
|
130
182
|
return false
|
|
131
183
|
}
|
|
132
184
|
|
|
185
|
+
// The credential-dense config files above, as data (#7978) so the Grep glob
|
|
186
|
+
// analysis derives its templates from the same spellings this matcher uses.
|
|
187
|
+
const CREDENTIAL_CONFIG_SEQUENCES = [
|
|
188
|
+
['.git', 'config'], ['.git', 'credentials'],
|
|
189
|
+
['.config', 'git', 'config'], ['.config', 'git', 'credentials'],
|
|
190
|
+
]
|
|
191
|
+
const CLAUDE_DIR = '.claude'
|
|
192
|
+
const CLAUDE_SETTINGS_DIR = CLAUDE_DIR
|
|
193
|
+
const CLAUDE_SETTINGS_PREFIX = 'settings'
|
|
194
|
+
const CLAUDE_SETTINGS_SUFFIX = '.json'
|
|
195
|
+
|
|
196
|
+
// The name a path segment carries: anything from a `:` on, and any trailing
|
|
197
|
+
// dots or spaces, are dropped. The trim is a scan from the end, not a regex,
|
|
198
|
+
// so a long run of dots or spaces costs linear time.
|
|
199
|
+
export function segmentName(seg) {
|
|
200
|
+
const colon = seg.indexOf(':')
|
|
201
|
+
const name = colon === -1 ? seg : seg.slice(0, colon)
|
|
202
|
+
let end = name.length
|
|
203
|
+
while (end > 0 && (name[end - 1] === '.' || name[end - 1] === ' ')) end--
|
|
204
|
+
return name.slice(0, end)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// The canonical form of a segment's name (see segmentName): folded wider than
|
|
208
|
+
// `toLowerCase()`. Compatibility forms are decomposed and combining marks
|
|
209
|
+
// removed, then each character is lower-, upper- and lower-cased again (so a
|
|
210
|
+
// capital or small sharp s becomes `ss`). An ASCII name is only lowercased.
|
|
211
|
+
// Each segment is also checked as written, so this form only adds matches.
|
|
212
|
+
const ASCII_NAME = /^[\x00-\x7f]*$/
|
|
213
|
+
export function canonicalName(name) {
|
|
214
|
+
if (ASCII_NAME.test(name)) return name.toLowerCase()
|
|
215
|
+
return [...name.normalize('NFKD').replace(/\p{M}/gu, '')]
|
|
216
|
+
.map((ch) => ch.toLowerCase().toUpperCase().toLowerCase())
|
|
217
|
+
.join('')
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// canonicalName, computed once per name within one call: every target of a
|
|
221
|
+
// call that resolves through the same directories shares its names. Returns
|
|
222
|
+
// null, and the caller floors, for a name longer than FLOOR_MAX_NAME_LENGTH or
|
|
223
|
+
// once the call's distinct non-ASCII names pass FLOOR_MAX_CALL_CANONICAL
|
|
224
|
+
// characters. A resolved path's names include directory names and symlink
|
|
225
|
+
// text, which the call's byte budget does not count.
|
|
226
|
+
function _canonicalNameIn(name, call) {
|
|
227
|
+
let canonical = call.names.get(name)
|
|
228
|
+
if (canonical !== undefined) return canonical
|
|
229
|
+
if (name.length > FLOOR_MAX_NAME_LENGTH) return null
|
|
230
|
+
if (!ASCII_NAME.test(name)) {
|
|
231
|
+
call.canonical.left -= name.length
|
|
232
|
+
if (call.canonical.left < 0) return null
|
|
233
|
+
}
|
|
234
|
+
canonical = canonicalName(name)
|
|
235
|
+
call.names.set(name, canonical)
|
|
236
|
+
return canonical
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// A segment whose name (see segmentName) is in the 8.3 short-name form
|
|
240
|
+
// (`CLAUDE~1`, `SETTIN~1.JSO`): up to six characters, `~`, digits, and an
|
|
241
|
+
// extension of up to three. It floors without a name comparison, under both floors.
|
|
242
|
+
const SHORT_NAME_SEGMENT = /^[^~.]{1,6}~\d+(\.[^.]{1,3})?$/
|
|
243
|
+
|
|
244
|
+
// #8741 — Claude Code's own worktrees live INSIDE the protected `.claude/` dir:
|
|
245
|
+
// `EnterWorktree` / `claude --worktree <name>` check one out at
|
|
246
|
+
// `<repo>/.claude/worktrees/<name>/`. Flooring `.claude` at any depth forced a
|
|
247
|
+
// prompt on every edit inside one; under Auto nobody answers and each cost the
|
|
248
|
+
// 300 s timeout. A worktree is a workspace like the cwd itself, so a target
|
|
249
|
+
// strictly inside `<cwd>/.claude/worktrees/<name>/` is scanned from `<name>` down:
|
|
250
|
+
// its own `.claude/settings*.json`, `.git`, `.env`, keys and config dirs still floor.
|
|
251
|
+
const CLAUDE_WORKTREES_DIR = 'worktrees'
|
|
252
|
+
// Claude Code accepts `[A-Za-z0-9._-]+` per `/`-separated name segment, refuses
|
|
253
|
+
// `.`, `..` and `.git`, and names the directory with each `/` written as `+`
|
|
254
|
+
// (`feature/auth` -> `feature+auth`). The floor also refuses a leading dot or
|
|
255
|
+
// `+`: a name starts with a letter, digit, `_` or `-`, so one that is itself a
|
|
256
|
+
// dotfile or a protected dir (`.claude`, `.git`, `.vscode`, `.env`) is never a root.
|
|
257
|
+
const CLAUDE_WORKTREE_NAME = /^[a-z0-9_-][a-z0-9._+-]*$/i
|
|
258
|
+
// The carve-out covers PLAIN names only: ASCII letters, digits, space and
|
|
259
|
+
// `._-@+()[]$`, not ending in a dot or a space. A path with any other component
|
|
260
|
+
// keeps the full scan, which costs a prompt, never access.
|
|
261
|
+
const PLAIN_COMPONENT = /^[A-Za-z0-9._@+()[\]$ -]*[A-Za-z0-9_@+()[\]$-]$/
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* #8741 — is `rel` (`relative(base, resolve(base, target))`, the path as
|
|
265
|
+
* written) strictly inside one of Claude Code's worktrees,
|
|
266
|
+
* `<base>/.claude/worktrees/<name>/`, by a path the scan reads as it is?
|
|
267
|
+
* `target` is the raw tool-input value. Decided ONCE, on the path as written,
|
|
268
|
+
* by {@link isProtectedPathValue}; the resolved pass keeps the carve-out only
|
|
269
|
+
* when its resolved path is that same path.
|
|
270
|
+
*
|
|
271
|
+
* Refused (the full scan applies) unless ALL of these hold:
|
|
272
|
+
* - the raw `target` has no `..` component;
|
|
273
|
+
* - split on the PLATFORM separator, every component of `rel` is a
|
|
274
|
+
* {@link PLAIN_COMPONENT}, the first two are exactly `.claude/worktrees`
|
|
275
|
+
* (as Claude Code spells them) and the third is a
|
|
276
|
+
* {@link CLAUDE_WORKTREE_NAME};
|
|
277
|
+
* - there is at least one component below `<name>` — the root itself, and
|
|
278
|
+
* anything directly in `worktrees/`, stays floored;
|
|
279
|
+
* - walking down from `.claude` with `lstat`, `.claude`, `.claude/worktrees`
|
|
280
|
+
* and `<name>` are real directories (`lstat` reports a symlink as not a
|
|
281
|
+
* directory), and no component below them that exists is a symlink. The
|
|
282
|
+
* first part is Claude Code's own condition for creating a worktree (a
|
|
283
|
+
* symlink at any of the three could redirect it); together they keep a path
|
|
284
|
+
* that only LOOKS like a worktree, or leaves one through a link, floored.
|
|
285
|
+
* On POSIX a non-directory among the first three also fails the next
|
|
286
|
+
* `lstat` with `ENOTDIR`, so a test can separate only the symlink half.
|
|
287
|
+
* `ENOENT` below `<name>` ends the walk, since nothing further exists yet; any
|
|
288
|
+
* other error refuses (fail closed). That refusal is also covered by the
|
|
289
|
+
* resolved pass, whose walk fails closed on the same error.
|
|
290
|
+
* @param {string} base
|
|
291
|
+
* @param {string} rel
|
|
292
|
+
* @param {string} target
|
|
293
|
+
* @returns {boolean}
|
|
294
|
+
*/
|
|
295
|
+
function _insideClaudeWorktree(base, rel, target) {
|
|
296
|
+
if (target.split(/[/\\]+/).includes('..')) return false
|
|
297
|
+
const parts = rel.split(sep)
|
|
298
|
+
if (parts.length < 4 || !parts.every((part) => PLAIN_COMPONENT.test(part))) return false
|
|
299
|
+
if (parts[0] !== CLAUDE_DIR || parts[1] !== CLAUDE_WORKTREES_DIR) return false
|
|
300
|
+
if (!CLAUDE_WORKTREE_NAME.test(parts[2])) return false
|
|
301
|
+
let path = base
|
|
302
|
+
for (let k = 0; k < parts.length; k++) {
|
|
303
|
+
path = join(path, parts[k])
|
|
304
|
+
let stat
|
|
305
|
+
try {
|
|
306
|
+
stat = lstatSync(path)
|
|
307
|
+
} catch (err) {
|
|
308
|
+
return err.code === 'ENOENT' && k >= 3
|
|
309
|
+
}
|
|
310
|
+
// A root component must be a directory (a symlink is not one to `lstat`);
|
|
311
|
+
// below the root, no existing component may be a symlink.
|
|
312
|
+
if (k < 3 ? !stat.isDirectory() : stat.isSymbolicLink()) return false
|
|
313
|
+
}
|
|
314
|
+
return true
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Is `path` an existing file with more than one hard link? A missing target is
|
|
319
|
+
* not; any other `lstat` error answers yes (fail closed).
|
|
320
|
+
* @param {string} path
|
|
321
|
+
* @returns {boolean}
|
|
322
|
+
*/
|
|
323
|
+
function _hasOtherHardLinks(path) {
|
|
324
|
+
try {
|
|
325
|
+
const stat = lstatSync(path)
|
|
326
|
+
return stat.isFile() && stat.nlink > 1
|
|
327
|
+
} catch (err) {
|
|
328
|
+
return err.code !== 'ENOENT'
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// The most a single path-tool target may be before the floor decides it
|
|
333
|
+
// without resolving it: longer than FLOOR_MAX_TARGET_BYTES (UTF-8), or with more
|
|
334
|
+
// than FLOOR_MAX_TARGET_COMPONENTS components (`/`- or `\`-separated, `.` and
|
|
335
|
+
// `..` included), it floors. Measured on 573,681 real paths, the deepest had 21
|
|
336
|
+
// components and the longest was 335 bytes; Linux's PATH_MAX is 4096 bytes.
|
|
337
|
+
// Exported so tests derive their inputs from the same numbers.
|
|
338
|
+
export const FLOOR_MAX_TARGET_BYTES = 4096
|
|
339
|
+
export const FLOOR_MAX_TARGET_COMPONENTS = 256
|
|
340
|
+
// And the most one tool call may carry: more than FLOOR_MAX_CALL_TARGETS path
|
|
341
|
+
// targets (path fields and `changes[]` members together), or more than
|
|
342
|
+
// FLOOR_MAX_CALL_COMPONENTS components across them, floors the call before any
|
|
343
|
+
// target is resolved. A patch touching hundreds of files is far below both.
|
|
344
|
+
export const FLOOR_MAX_CALL_TARGETS = 1024
|
|
345
|
+
export const FLOOR_MAX_CALL_COMPONENTS = 16384
|
|
346
|
+
// The call's symlink-resolving walks share one budget too: past
|
|
347
|
+
// FLOOR_MAX_CALL_WALK components walked across all its targets (those a symlink
|
|
348
|
+
// adds included), the call floors.
|
|
349
|
+
export const FLOOR_MAX_CALL_WALK = 16384
|
|
350
|
+
// Filesystem-identity lookups made for the configured Claude config directory in
|
|
351
|
+
// one call; past it the call floors. Separate from the walk so a large patch is
|
|
352
|
+
// not floored by this budget alone.
|
|
353
|
+
export const FLOOR_MAX_CALL_IDENTITY = 16384
|
|
354
|
+
// And more than FLOOR_MAX_CALL_BYTES UTF-8 bytes across one call's targets
|
|
355
|
+
// floors the call. A thousand-file patch of 250-byte absolute paths is about 250 KB.
|
|
356
|
+
export const FLOOR_MAX_CALL_BYTES = 262144
|
|
357
|
+
// A path name longer than FLOOR_MAX_NAME_LENGTH characters floors: no
|
|
358
|
+
// filesystem here accepts one. And more than FLOOR_MAX_CALL_CANONICAL characters
|
|
359
|
+
// of distinct non-ASCII names, from the targets and from what they resolve to,
|
|
360
|
+
// floors the call. Characters here are UTF-16 code units, as `length` counts them.
|
|
361
|
+
export const FLOOR_MAX_NAME_LENGTH = 255
|
|
362
|
+
export const FLOOR_MAX_CALL_CANONICAL = 65536
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* How many `/`- or `\`-separated components `target` has, counting no further
|
|
366
|
+
* than `limit` (so a huge target costs only as much as the bound it is checked
|
|
367
|
+
* against).
|
|
368
|
+
* @param {string} target
|
|
369
|
+
* @param {number} limit
|
|
370
|
+
* @returns {number}
|
|
371
|
+
*/
|
|
372
|
+
function _componentCount(target, limit) {
|
|
373
|
+
let components = 0
|
|
374
|
+
let inName = false
|
|
375
|
+
for (let i = 0; i < target.length && components <= limit; i++) {
|
|
376
|
+
const code = target.charCodeAt(i)
|
|
377
|
+
if (code === 0x2f || code === 0x5c) {
|
|
378
|
+
inName = false
|
|
379
|
+
} else if (!inName) {
|
|
380
|
+
inName = true
|
|
381
|
+
components++
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
return components
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Is `target` over either size bound? Linear in its length.
|
|
389
|
+
* @param {string} target
|
|
390
|
+
* @returns {boolean}
|
|
391
|
+
*/
|
|
392
|
+
function _exceedsTargetBounds(target) {
|
|
393
|
+
if (Buffer.byteLength(target, 'utf8') > FLOOR_MAX_TARGET_BYTES) return true
|
|
394
|
+
return _componentCount(target, FLOOR_MAX_TARGET_COMPONENTS) > FLOOR_MAX_TARGET_COMPONENTS
|
|
395
|
+
}
|
|
396
|
+
|
|
133
397
|
// #6851 — depth ceiling for the sync deepest-ancestor realpath walk. Absolute
|
|
134
398
|
// paths never legitimately nest this deep; the cap only guards a pathological /
|
|
135
399
|
// malicious tail (a to-be-created path with hundreds of nonexistent components
|
|
@@ -198,12 +462,227 @@ function realpathDeepestAncestorSync(absPath) {
|
|
|
198
462
|
// walks is what keeps them from drifting again — #6928 was a bug present in BOTH
|
|
199
463
|
// copies. Imported as `resolveTargetComponentwiseSync` at the top of this file.
|
|
200
464
|
|
|
465
|
+
/**
|
|
466
|
+
* The configured Claude config directory (CLAUDE_CONFIG_DIR, resolved and
|
|
467
|
+
* canonical exactly as `claudeConfigDir` resolves it) treated like `.claude`.
|
|
468
|
+
*
|
|
469
|
+
* A `.claude`-NAMED root needs nothing here: the segment rules already cover it
|
|
470
|
+
* wherever it sits. Any other name is recognised by its resolved location:
|
|
471
|
+
* - a dedicated root (the usual case): the full floor covers everything
|
|
472
|
+
* inside it, and both floors cover `settings*.json` directly inside it, as
|
|
473
|
+
* they do for `.claude/settings*.json`;
|
|
474
|
+
* - a root that is `$HOME` or an ancestor of it (the resolver accepts these):
|
|
475
|
+
* it is NOT floored wholesale, which would prompt for the whole home
|
|
476
|
+
* directory. Only the `settings*.json` files directly inside it floor.
|
|
477
|
+
* A root the resolver rejects (relative, `/`, an alias of `/`) never reaches
|
|
478
|
+
* here: it resolves to `~/.claude`, which the name rules already cover.
|
|
479
|
+
* Resolved once per call. Returns null when no extra rule applies.
|
|
480
|
+
* @param {{ configRoot?: object|null }} call
|
|
481
|
+
* @returns {{ root: string, broad: boolean }|null}
|
|
482
|
+
*/
|
|
483
|
+
function _configRootRule(call) {
|
|
484
|
+
if (call.configRoot !== undefined) return call.configRoot
|
|
485
|
+
let root
|
|
486
|
+
let home
|
|
487
|
+
try {
|
|
488
|
+
root = (call.configDirFn ?? claudeConfigDir)()
|
|
489
|
+
home = claudeHomeDir()
|
|
490
|
+
} catch {
|
|
491
|
+
// The resolver itself failed: nothing can be said about the directory, so floor.
|
|
492
|
+
call.configRoot = { root: null, broad: false, anchor: null, anchorId: null, tail: [], anchorAncestorIds: null, failed: true }
|
|
493
|
+
return call.configRoot
|
|
494
|
+
}
|
|
495
|
+
let rule = null
|
|
496
|
+
if (basename(root).toLowerCase() !== CLAUDE_DIR) {
|
|
497
|
+
try { home = realpathSync.native(home) } catch { /* the raw home still gives a prefix test */ }
|
|
498
|
+
// `anchor` is the root, or its deepest EXISTING ancestor when the root is not
|
|
499
|
+
// created yet; `tail` are the missing pieces between them (lowercased).
|
|
500
|
+
rule = { root, broad: false, anchor: null, anchorId: null, tail: [], anchorAncestorIds: null, failed: false }
|
|
501
|
+
try {
|
|
502
|
+
// The root holds $HOME (is it, or an ancestor of it). Both are canonical
|
|
503
|
+
// (native realpath), so the spelling comparison is enough.
|
|
504
|
+
rule.broad = pathPiecesUnder(root, home, path) !== null
|
|
505
|
+
let anchor = root
|
|
506
|
+
const missing = []
|
|
507
|
+
for (;;) {
|
|
508
|
+
const id = _statId(anchor, call)
|
|
509
|
+
if (id !== undefined) { rule.anchor = anchor; rule.anchorId = id; break }
|
|
510
|
+
const parent = dirname(anchor)
|
|
511
|
+
if (parent === anchor) break
|
|
512
|
+
missing.push(basename(anchor).toLowerCase())
|
|
513
|
+
anchor = parent
|
|
514
|
+
}
|
|
515
|
+
rule.tail = missing.reverse()
|
|
516
|
+
} catch {
|
|
517
|
+
rule.failed = true
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
call.configRoot = rule
|
|
521
|
+
return rule
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** `p` followed by each ancestor, ending at the filesystem root. */
|
|
525
|
+
function _withAncestors(p) {
|
|
526
|
+
const chain = [p]
|
|
527
|
+
for (let parent = dirname(p); parent !== chain[chain.length - 1]; parent = dirname(parent)) chain.push(parent)
|
|
528
|
+
return chain
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* Which filesystem object is at `p`: a `device:inode` id; null when the
|
|
533
|
+
* filesystem reports inode 0 (identifies nothing); undefined when nothing is
|
|
534
|
+
* there (ENOENT / ENOTDIR). Any other error throws, and callers fail closed.
|
|
535
|
+
* Each distinct lookup is charged to the call's own identity budget
|
|
536
|
+
* ({@link FLOOR_MAX_CALL_IDENTITY}, separate from the component walk) and remembered for
|
|
537
|
+
* the rest of the call; running out of budget throws, so the call floors.
|
|
538
|
+
*/
|
|
539
|
+
function _statId(p, call) {
|
|
540
|
+
if (call.ids.has(p)) return call.ids.get(p)
|
|
541
|
+
if (--call.idBudget.left < 0) throw Object.assign(new Error('floor: identity lookups exceed the call budget'), { code: 'EBUDGET' })
|
|
542
|
+
let id
|
|
543
|
+
try {
|
|
544
|
+
const st = (call.statFn ?? statSync)(p, { bigint: true })
|
|
545
|
+
id = st.ino === 0n ? null : `${st.dev}:${st.ino}`
|
|
546
|
+
} catch (err) {
|
|
547
|
+
if (err?.code !== 'ENOENT' && err?.code !== 'ENOTDIR') throw err
|
|
548
|
+
id = undefined
|
|
549
|
+
}
|
|
550
|
+
call.ids.set(p, id)
|
|
551
|
+
return id
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** A name the filesystem might treat as another (case, normalisation). */
|
|
555
|
+
function _sameName(a, b, call) {
|
|
556
|
+
if (a === b) return true
|
|
557
|
+
// Trailing dots and spaces, and a `:` suffix, are not part of a Windows name.
|
|
558
|
+
const ca = _canonicalNameIn(segmentName(a), call)
|
|
559
|
+
const cb = _canonicalNameIn(segmentName(b), call)
|
|
560
|
+
return ca === null || cb === null || ca === cb
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* The path pieces of `target` relative to `root` (both absolute), compared
|
|
565
|
+
* case-insensitively so a differently-cased spelling of one directory matches
|
|
566
|
+
* on a case-insensitive volume; null when `target` is not inside `root`.
|
|
567
|
+
* `[]` means the target is the root itself. `pathImpl` is injectable so the
|
|
568
|
+
* Windows spelling is testable from any host.
|
|
569
|
+
* @param {string} root
|
|
570
|
+
* @param {string} target
|
|
571
|
+
* @param {typeof path} pathImpl
|
|
572
|
+
* @returns {string[]|null}
|
|
573
|
+
*/
|
|
574
|
+
export function pathPiecesUnder(root, target, pathImpl) {
|
|
575
|
+
const rel = pathImpl.relative(root.toLowerCase(), target.toLowerCase())
|
|
576
|
+
if (rel === '') return []
|
|
577
|
+
if (pathImpl.isAbsolute(rel) || rel === '..' || rel.startsWith('..' + pathImpl.sep)) return null
|
|
578
|
+
return rel.split(/[/\\]+/).filter((s) => s.length > 0)
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* How the absolute `real` relates to the configured root, by spelling first and
|
|
583
|
+
* then by filesystem object, so a name the filesystem treats as equivalent (a
|
|
584
|
+
* case or Unicode-normalisation variant, a second path) is recognised too. A
|
|
585
|
+
* root that is not created yet is matched through its deepest existing ancestor
|
|
586
|
+
* (by identity) plus the missing tail (by name).
|
|
587
|
+
* inside: the pieces of `real` below the root, or null when not inside it
|
|
588
|
+
* covers: `real` is the root or an ancestor of it (a search from there
|
|
589
|
+
* reaches the root)
|
|
590
|
+
* Throws on a stat error other than "nothing there", or when the call's budget
|
|
591
|
+
* is spent; callers fail closed.
|
|
592
|
+
*/
|
|
593
|
+
function _rootRelation(rule, real, wantCovers, call) {
|
|
594
|
+
let inside = pathPiecesUnder(rule.root, real, path)
|
|
595
|
+
let covers = wantCovers && pathPiecesUnder(real, rule.root, path) !== null
|
|
596
|
+
if (rule.anchorId === null || rule.anchorId === undefined) return { inside, covers }
|
|
597
|
+
if (inside === null || (wantCovers && !covers)) {
|
|
598
|
+
// Top-down, so the first missing directory ends the walk: nothing below it exists.
|
|
599
|
+
for (const dir of _withAncestors(real).reverse()) {
|
|
600
|
+
const id = _statId(dir, call)
|
|
601
|
+
if (id === undefined) break
|
|
602
|
+
if (id !== rule.anchorId) continue
|
|
603
|
+
const rest = pathPiecesUnder(dir, real, path) ?? []
|
|
604
|
+
let k = 0
|
|
605
|
+
while (k < rest.length && k < rule.tail.length && _sameName(rest[k], rule.tail[k], call)) k++
|
|
606
|
+
if (k === rule.tail.length) {
|
|
607
|
+
if (inside === null) inside = rest.slice(k)
|
|
608
|
+
} else if (k === rest.length) {
|
|
609
|
+
covers = true // `real` is above the root, reached through directories not created yet
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
if (wantCovers && !covers) {
|
|
613
|
+
const realId = _statId(real, call)
|
|
614
|
+
if (realId) {
|
|
615
|
+
if (rule.anchorAncestorIds === null) {
|
|
616
|
+
rule.anchorAncestorIds = new Set()
|
|
617
|
+
for (const dir of _withAncestors(rule.anchor)) {
|
|
618
|
+
const id = _statId(dir, call)
|
|
619
|
+
if (id) rule.anchorAncestorIds.add(id)
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
covers = rule.anchorAncestorIds.has(realId)
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
return { inside, covers }
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* The verdict for a target `inside` the configured root (see
|
|
631
|
+
* {@link _configRootRule}): is it floored? `inside` are its pieces below the
|
|
632
|
+
* root. Dedicated root: everything under the full floor; `settings*.json`
|
|
633
|
+
* directly inside under both. Broad root (holds $HOME): only the latter.
|
|
634
|
+
* Exported so the Windows spelling can be tested from any host.
|
|
635
|
+
* @param {string[]} inside
|
|
636
|
+
* @param {boolean} broad
|
|
637
|
+
* @param {boolean} secretsOnly
|
|
638
|
+
* @param {object} call
|
|
639
|
+
* @returns {boolean}
|
|
640
|
+
*/
|
|
641
|
+
export function configRootVerdict(inside, broad, secretsOnly, call) {
|
|
642
|
+
if (!broad && !secretsOnly) return true
|
|
643
|
+
if (inside.length === 0) return false
|
|
644
|
+
// The first piece sits where `.claude` has `settings*.json`: test it in the
|
|
645
|
+
// same two forms and with the same matcher as the `.claude` rule.
|
|
646
|
+
const first = segmentName(inside[0])
|
|
647
|
+
if (SHORT_NAME_SEGMENT.test(first)) return true
|
|
648
|
+
const canonical = _canonicalNameIn(first, call)
|
|
649
|
+
if (canonical === null) return true
|
|
650
|
+
return isCredentialConfigSegment([CLAUDE_DIR, first], 0) || isCredentialConfigSegment([CLAUDE_DIR, canonical], 0)
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* Does the already-resolved absolute `resolved` hit the configured config
|
|
655
|
+
* directory's rules? Applies whether or not the target sits in a workspace
|
|
656
|
+
* the worktree carve-out admits. Fails closed.
|
|
657
|
+
* @param {string} resolved
|
|
658
|
+
* @param {boolean} secretsOnly
|
|
659
|
+
* @param {object} call
|
|
660
|
+
* @returns {boolean}
|
|
661
|
+
*/
|
|
662
|
+
function _hitsConfigRoot(resolved, secretsOnly, call) {
|
|
663
|
+
const rule = _configRootRule(call)
|
|
664
|
+
if (rule === null) return false
|
|
665
|
+
if (rule.failed) return true
|
|
666
|
+
try {
|
|
667
|
+
const { inside } = _rootRelation(rule, resolved, false, call)
|
|
668
|
+
if (inside === null) return false
|
|
669
|
+
return configRootVerdict(inside, rule.broad, secretsOnly, call)
|
|
670
|
+
} catch {
|
|
671
|
+
return true
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
|
|
201
675
|
/**
|
|
202
676
|
* #6851 — the pure segment scan, factored out of {@link isProtectedPathValue} so
|
|
203
677
|
* the lexical pass and the symlink-resolved pass share ONE matcher. Given a
|
|
204
678
|
* resolution `base` and an already-resolved absolute `resolved` target, applies
|
|
205
|
-
* the #6806 relative-vs-absolute framing (below) and tests each segment.
|
|
206
|
-
*
|
|
679
|
+
* the #6806 relative-vs-absolute framing (below) and tests each segment. String
|
|
680
|
+
* ops only.
|
|
681
|
+
*
|
|
682
|
+
* #8741 — when `carved` (see {@link isProtectedPathValue}), the target is
|
|
683
|
+
* strictly inside `<base>/.claude/worktrees/<name>/` and is scanned from
|
|
684
|
+
* `<name>` down, so the `.claude` and `worktrees` above the worktree are not
|
|
685
|
+
* counted while everything inside it is.
|
|
207
686
|
*
|
|
208
687
|
* #6806 — the discriminator is whether the resolved target stays INSIDE base's
|
|
209
688
|
* own subtree:
|
|
@@ -218,9 +697,12 @@ function realpathDeepestAncestorSync(absPath) {
|
|
|
218
697
|
* @param {string} base
|
|
219
698
|
* @param {string} resolved an absolute path already resolved against base
|
|
220
699
|
* @param {boolean} secretsOnly
|
|
700
|
+
* @param {boolean} carved `resolved` is inside a worktree the carve-out admits
|
|
701
|
+
* @param {{ names: Map<string, string>, canonical: { left: number } }} call
|
|
702
|
+
* the canonical names computed in this call, and the characters left to compute
|
|
221
703
|
* @returns {boolean}
|
|
222
704
|
*/
|
|
223
|
-
function _scanResolvedTarget(base, resolved, secretsOnly) {
|
|
705
|
+
function _scanResolvedTarget(base, resolved, secretsOnly, carved, call) {
|
|
224
706
|
const rel = relative(base, resolved)
|
|
225
707
|
// Target is inside base's own subtree when the relative path neither is nor
|
|
226
708
|
// begins with `..` (and isn't a foreign absolute — a Windows cross-drive
|
|
@@ -232,10 +714,170 @@ function _scanResolvedTarget(base, resolved, secretsOnly) {
|
|
|
232
714
|
// here, but a separator-agnostic split keeps the segment scan robust to any
|
|
233
715
|
// foreign `\`/`/` that survives (and can never wrongly merge two segments — a
|
|
234
716
|
// filename cannot contain a separator on the platform that produced it).
|
|
235
|
-
const
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
717
|
+
const pieces = scanned.split(/[/\\]+/).filter((s) => s.length > 0 && s !== '..')
|
|
718
|
+
const names = pieces.map(segmentName)
|
|
719
|
+
// #8741 — start the scan at `<name>`. `carved` means `rel` is a path
|
|
720
|
+
// `_insideClaudeWorktree` admitted: every native component is a
|
|
721
|
+
// PLAIN_COMPONENT (no separator of either kind, never empty or `..`), so its
|
|
722
|
+
// first three native components are also `pieces[0..2]`.
|
|
723
|
+
const start = carved ? 2 : 0
|
|
724
|
+
for (let i = start; i < names.length; i++) {
|
|
725
|
+
if (SHORT_NAME_SEGMENT.test(names[i])) return true
|
|
726
|
+
}
|
|
727
|
+
// Each segment is checked as written (lowercased) and in canonical form; a
|
|
728
|
+
// match in either floors, and so does a name with no canonical form computed.
|
|
729
|
+
const canonical = []
|
|
730
|
+
for (const name of names) {
|
|
731
|
+
const form = _canonicalNameIn(name, call)
|
|
732
|
+
if (form === null) return true
|
|
733
|
+
canonical.push(form)
|
|
734
|
+
}
|
|
735
|
+
return _matchesProtectedSegments(pieces.map((p) => p.toLowerCase()), start, secretsOnly) ||
|
|
736
|
+
_matchesProtectedSegments(canonical, start, secretsOnly) ||
|
|
737
|
+
_hitsConfigRoot(resolved, secretsOnly, call) ||
|
|
738
|
+
_hitsInboxSocketDir(resolved, call) ||
|
|
739
|
+
_isSessionsDir(resolved, call)
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
// Claude Code's inbox sockets live under this directory. It is matched by its
|
|
743
|
+
// absolute spelling, with and without the macOS `/private` prefix, and as a
|
|
744
|
+
// prefix: every path at or below it floors, under both floors. The real-path
|
|
745
|
+
// pass resolves `/tmp` to `/private/tmp` on macOS, so the second spelling is
|
|
746
|
+
// what a symlinked or relative route arrives as; on other hosts it is a literal.
|
|
747
|
+
const INBOX_SOCKET_DIR = 'cc-socks'
|
|
748
|
+
const INBOX_SOCKET_PREFIXES = [['tmp', INBOX_SOCKET_DIR], ['private', 'tmp', INBOX_SOCKET_DIR]]
|
|
749
|
+
const CLAUDE_SESSIONS_DIR = 'sessions'
|
|
750
|
+
|
|
751
|
+
/**
|
|
752
|
+
* A path resolved through its deepest existing ancestor. A component that is
|
|
753
|
+
* not a directory (ENOTDIR) means the path cannot exist, which is the same
|
|
754
|
+
* answer as a component that is missing: it names only itself.
|
|
755
|
+
* @param {string} p an absolute path
|
|
756
|
+
* @returns {string}
|
|
757
|
+
*/
|
|
758
|
+
function _resolveRoot(p) {
|
|
759
|
+
try {
|
|
760
|
+
return realpathDeepestAncestorSync(p)
|
|
761
|
+
} catch (err) {
|
|
762
|
+
if (err?.code !== 'ENOTDIR') throw err
|
|
763
|
+
const parent = dirname(p)
|
|
764
|
+
if (parent === p) throw err
|
|
765
|
+
return join(_resolveRoot(parent), basename(p))
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* One protected directory set: each written path and its symlink-resolved
|
|
771
|
+
* form, so a root that is itself a link (or reached through one) is recognised
|
|
772
|
+
* from either side. `failed` is set when a path could not be resolved at all
|
|
773
|
+
* (for example EACCES on a parent); the written paths are still listed, and the
|
|
774
|
+
* caller then treats everything at or under them as the directory.
|
|
775
|
+
*/
|
|
776
|
+
function _rootEntry(written, call) {
|
|
777
|
+
const resolveFn = call.resolveRootFn ?? _resolveRoot
|
|
778
|
+
const paths = new Set(written)
|
|
779
|
+
let failed = false
|
|
780
|
+
for (const p of written) {
|
|
781
|
+
try { paths.add(resolveFn(p)) } catch { failed = true }
|
|
782
|
+
}
|
|
783
|
+
return { paths: [...paths], failed }
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* The protected directories, resolved once per call. The sessions directory and
|
|
788
|
+
* the inbox directories are resolved independently, so a failure in one never
|
|
789
|
+
* reaches the other, and a failure affects only targets at or under that
|
|
790
|
+
* directory's written path (or a search reaching it), never an ordinary read.
|
|
791
|
+
* A config directory that cannot be determined at all names no sessions
|
|
792
|
+
* directory: the configured-root rule already decides for that case.
|
|
793
|
+
* @param {object} call
|
|
794
|
+
* @returns {{ sessions: { paths: string[], failed: boolean }, inbox: { paths: string[] } }}
|
|
795
|
+
*/
|
|
796
|
+
function _protectedRoots(call) {
|
|
797
|
+
if (call.protectedRoots !== undefined) return call.protectedRoots
|
|
798
|
+
let sessions = { paths: [], failed: false }
|
|
799
|
+
try {
|
|
800
|
+
sessions = _rootEntry([join((call.configDirFn ?? claudeConfigDir)(), CLAUDE_SESSIONS_DIR)], call)
|
|
801
|
+
} catch { /* see above */ }
|
|
802
|
+
// The inbox roots are POSIX paths; there is nothing to resolve elsewhere.
|
|
803
|
+
const inbox = _rootEntry(call.inboxDirs ?? (sep === '/' ? ['/tmp/' + INBOX_SOCKET_DIR, '/private/tmp/' + INBOX_SOCKET_DIR] : []), call)
|
|
804
|
+
call.protectedRoots = { sessions, inbox: { paths: inbox.paths } }
|
|
805
|
+
return call.protectedRoots
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/**
|
|
809
|
+
* Is the absolute `resolved` at or below an inbox socket directory? Compared
|
|
810
|
+
* case-insensitively, against the resolved form of each directory first (so a
|
|
811
|
+
* target of any depth, such as a root that resolves to `/sockets`, is judged),
|
|
812
|
+
* then in both the lowercased and the canonical spelling of each name. A name
|
|
813
|
+
* that cannot be canonicalised floors.
|
|
814
|
+
* @param {string} resolved
|
|
815
|
+
* @param {object} call
|
|
816
|
+
* @returns {boolean}
|
|
817
|
+
*/
|
|
818
|
+
function _hitsInboxSocketDir(resolved, call) {
|
|
819
|
+
if (_protectedRoots(call).inbox.paths.some((root) => pathPiecesUnder(root, resolved, path) !== null)) return true
|
|
820
|
+
const raw = resolved.split(/[/\\]+/).filter((s) => s.length > 0 && s !== '..')
|
|
821
|
+
// A Windows drive (`C:`) is the root, not a directory name.
|
|
822
|
+
if (sep === '\\' && /^[A-Za-z]:$/.test(raw[0] ?? '')) raw.shift()
|
|
823
|
+
const pieces = raw.map(segmentName)
|
|
824
|
+
if (pieces.length < 2) return false
|
|
825
|
+
const lowered = pieces.map((p) => p.toLowerCase())
|
|
826
|
+
const canonical = []
|
|
827
|
+
for (const name of pieces) {
|
|
828
|
+
const form = _canonicalNameIn(name, call)
|
|
829
|
+
if (form === null) return true
|
|
830
|
+
canonical.push(form)
|
|
831
|
+
}
|
|
832
|
+
return INBOX_SOCKET_PREFIXES.some((prefix) =>
|
|
833
|
+
[lowered, canonical].some((names) => prefix.every((name, i) => names[i] === name)))
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/**
|
|
837
|
+
* Is `resolved` the `sessions` directory of the configured Claude config
|
|
838
|
+
* directory itself, in either spelling? A search rooted there reaches every key
|
|
839
|
+
* file inside it, which the file-name rule alone does not see. A file inside it
|
|
840
|
+
* is judged by its own name, so ordinary files there are unaffected. When the
|
|
841
|
+
* directory could not be resolved, everything at or under its written path
|
|
842
|
+
* counts as it.
|
|
843
|
+
* @param {string} resolved
|
|
844
|
+
* @param {object} call
|
|
845
|
+
* @returns {boolean}
|
|
846
|
+
*/
|
|
847
|
+
function _isSessionsDir(resolved, call) {
|
|
848
|
+
const { paths, failed } = _protectedRoots(call).sessions
|
|
849
|
+
return paths.some((root) => {
|
|
850
|
+
const inside = pathPiecesUnder(root, resolved, path)
|
|
851
|
+
return inside !== null && (failed || inside.length === 0)
|
|
852
|
+
})
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* Does a recursive content search rooted at the absolute `resolved`, strictly
|
|
857
|
+
* above the sessions directory, reach it? Claude Code's Grep passes `--hidden`
|
|
858
|
+
* (see the #7978 section), so a route through a dot-named directory counts:
|
|
859
|
+
* a search from `$HOME` reaches `~/.claude/sessions`.
|
|
860
|
+
* @param {string} resolved
|
|
861
|
+
* @param {object} call
|
|
862
|
+
* @returns {boolean}
|
|
863
|
+
*/
|
|
864
|
+
function _searchReachesSessions(resolved, call) {
|
|
865
|
+
return _protectedRoots(call).sessions.paths.some((root) => {
|
|
866
|
+
const below = pathPiecesUnder(resolved, root, path)
|
|
867
|
+
return below !== null && below.length > 0
|
|
868
|
+
})
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
/**
|
|
872
|
+
* Does any segment from `start` on match the floor's names? `segments` are
|
|
873
|
+
* already in the form to compare (lowercased, or canonical).
|
|
874
|
+
* @param {string[]} segments
|
|
875
|
+
* @param {number} start
|
|
876
|
+
* @param {boolean} secretsOnly
|
|
877
|
+
* @returns {boolean}
|
|
878
|
+
*/
|
|
879
|
+
function _matchesProtectedSegments(segments, start, secretsOnly) {
|
|
880
|
+
for (let i = start; i < segments.length; i++) {
|
|
239
881
|
const seg = segments[i]
|
|
240
882
|
// Secret files, and credential-dense config files, are floored under BOTH
|
|
241
883
|
// the read and the write floor (PR #6873 review — the read floor must not
|
|
@@ -246,6 +888,7 @@ function _scanResolvedTarget(base, resolved, secretsOnly) {
|
|
|
246
888
|
// Config DIRS (any file within them) are floored only under the full (write)
|
|
247
889
|
// floor; a read of a NON-credential config file stays un-prompted.
|
|
248
890
|
if (PROTECTED_DIR_SEGMENTS.has(seg)) return true
|
|
891
|
+
if (PROTECTED_WRITE_FILE_NAMES.has(seg)) return true
|
|
249
892
|
if (seg === '.config' && segments[i + 1] === 'git') return true
|
|
250
893
|
}
|
|
251
894
|
return false
|
|
@@ -258,8 +901,10 @@ function _scanResolvedTarget(base, resolved, secretsOnly) {
|
|
|
258
901
|
* TWO passes, ORed — a hit on EITHER floors the target:
|
|
259
902
|
* (1) LEXICAL (the pre-#6851 floor, unchanged). `resolve()` absorbs absolute
|
|
260
903
|
* paths, a leading `./`, and `..` traversal; the resolved path is scanned
|
|
261
|
-
* segment-by-segment ({@link _scanResolvedTarget}).
|
|
262
|
-
*
|
|
904
|
+
* segment-by-segment ({@link _scanResolvedTarget}). String ops, plus the
|
|
905
|
+
* #8741 worktree lstat walk for a `.claude/worktrees/<name>/…` target —
|
|
906
|
+
* fast, and every input the old floor flagged still flags, except an
|
|
907
|
+
* ordinary file inside one of Claude Code's own worktrees.
|
|
263
908
|
* (2) #6851/#6921 SYMLINK. The lexical pass is symlink-BLIND: because
|
|
264
909
|
* `resolve()` collapses `..` textually, a symlink in cwd's PREFIX (the
|
|
265
910
|
* chroxy agent worktree can live under a *symlink* to a real `.claude/`),
|
|
@@ -301,13 +946,26 @@ function _scanResolvedTarget(base, resolved, secretsOnly) {
|
|
|
301
946
|
* the full (write) floor passes `secretsOnly = false`.
|
|
302
947
|
* @param {string} target a path value from a tool input
|
|
303
948
|
* @param {string} base the resolution base (session cwd)
|
|
304
|
-
* @param {boolean}
|
|
949
|
+
* @param {boolean} secretsOnly match only secret / credential files
|
|
950
|
+
* @param {{ realBase: string|undefined, walk: { left: number }, names: Map<string, string>, canonical: { left: number } }} call
|
|
951
|
+
* state shared by one call's targets: the session cwd's real path once
|
|
952
|
+
* resolved, the walk budget left, the canonical names computed so far, and
|
|
953
|
+
* the characters of non-ASCII names left to compute
|
|
305
954
|
* @returns {boolean}
|
|
306
955
|
*/
|
|
307
|
-
function isProtectedPathValue(target, base, secretsOnly
|
|
956
|
+
function isProtectedPathValue(target, base, secretsOnly, call) {
|
|
957
|
+
// The work spent on one target is bounded before anything else runs.
|
|
958
|
+
if (_exceedsTargetBounds(target)) return true
|
|
959
|
+
// On POSIX `\` is a name character that both passes read as a separator, so
|
|
960
|
+
// a target holding one floors.
|
|
961
|
+
if (sep === '/' && target.includes('\\')) return true
|
|
308
962
|
// (1) LEXICAL floor — pre-#6851 behavior, authoritative on a hit (no fs cost).
|
|
309
963
|
const resolvedLexical = resolve(base, target)
|
|
310
|
-
|
|
964
|
+
// #8741 — the worktree carve-out is decided once, on the path as written. An
|
|
965
|
+
// escaping relative path begins with `..` or is absolute, never `.claude`.
|
|
966
|
+
const lexicalRel = relative(base, resolvedLexical)
|
|
967
|
+
const carved = _insideClaudeWorktree(base, lexicalRel, target)
|
|
968
|
+
if (_scanResolvedTarget(base, resolvedLexical, secretsOnly, carved, call)) return true
|
|
311
969
|
// (2) #6851/#6921 SYMLINK floor — resolve the real base, then walk the RAW
|
|
312
970
|
// target component-by-component (open(2) semantics) and re-scan. A resolution
|
|
313
971
|
// error FAILS CLOSED (return true → force the prompt). Runs only on a
|
|
@@ -324,12 +982,22 @@ function isProtectedPathValue(target, base, secretsOnly = false) {
|
|
|
324
982
|
// (caught below → return true → force the prompt) instead of resolving
|
|
325
983
|
// against process.cwd(). Wrapping in resolve() would defeat BOTH the guard
|
|
326
984
|
// and the wrong-root framing it protects against.
|
|
327
|
-
|
|
985
|
+
// Once per call: every target of one call shares the session cwd.
|
|
986
|
+
if (call.realBase === undefined) call.realBase = realpathDeepestAncestorSync(base)
|
|
987
|
+
const realBase = call.realBase
|
|
328
988
|
// Pass the RAW `target` (its `..` intact) to the component walker, so a `..`
|
|
329
989
|
// after a symlinked component climbs from the symlink's TARGET, not its
|
|
330
990
|
// lexical parent. Do NOT pre-resolve() it — that would collapse the `..`.
|
|
331
|
-
const realTarget = resolveTargetComponentwiseSync(realBase, target)
|
|
332
|
-
|
|
991
|
+
const realTarget = resolveTargetComponentwiseSync(realBase, target, call.walk)
|
|
992
|
+
// The carve-out survives only when the resolved path IS the written one. The
|
|
993
|
+
// written path held no symlink when `_insideClaudeWorktree` walked it, so
|
|
994
|
+
// this differs only if the path changed between the two walks; then the
|
|
995
|
+
// resolved target gets the full scan rather than an offset meant for another
|
|
996
|
+
// path.
|
|
997
|
+
const stillCarved = carved && relative(realBase, realTarget) === lexicalRel
|
|
998
|
+
if (_scanResolvedTarget(realBase, realTarget, secretsOnly, stillCarved, call)) return true
|
|
999
|
+
// Under the full floor, an existing target with more than one hard link floors.
|
|
1000
|
+
return !secretsOnly && _hasOtherHardLinks(realTarget)
|
|
333
1001
|
} catch {
|
|
334
1002
|
return true
|
|
335
1003
|
}
|
|
@@ -362,10 +1030,13 @@ function isProtectedPathValue(target, base, secretsOnly = false) {
|
|
|
362
1030
|
* prefix excluded). But a `..`-traversal back UP into that same `.claude`
|
|
363
1031
|
* (`../../settings.local.json` → the real agent config) IS floored, because an
|
|
364
1032
|
* above-cwd target is scanned as its resolved ABSOLUTE path (#6806). See
|
|
365
|
-
* {@link isProtectedPathValue} for the full reconciliation.
|
|
1033
|
+
* {@link isProtectedPathValue} for the full reconciliation. A Claude Code
|
|
1034
|
+
* worktree BELOW cwd (`.claude/worktrees/<name>/…`) is a workspace too: its
|
|
1035
|
+
* ordinary files are not floored, its own config and secrets are (#8741,
|
|
1036
|
+
* {@link _insideClaudeWorktree}).
|
|
366
1037
|
*
|
|
367
1038
|
* Segment rules (a match on ANY segment floors the write; see
|
|
368
|
-
* {@link
|
|
1039
|
+
* {@link canonicalName} for the forms segments are compared in):
|
|
369
1040
|
* - a segment in {@link PROTECTED_DIR_SEGMENTS} (`.git` / `.claude` / `.vscode`)
|
|
370
1041
|
* - a `.config` segment immediately followed by `git` (the XDG git-config dir)
|
|
371
1042
|
* - a segment that is `.env` or starts with `.env.` (`.env` / `.env.local` / …)
|
|
@@ -404,28 +1075,454 @@ export function isSecretReadTarget(input, cwd) {
|
|
|
404
1075
|
* resolving each against the session cwd, and tests it with {@link isProtectedPathValue}.
|
|
405
1076
|
* `secretsOnly` selects the read floor (secret files) vs the full write floor
|
|
406
1077
|
* (config dirs + secret files). ANY protected field/member floors the input.
|
|
1078
|
+
* The call as a whole is bounded too: more than FLOOR_MAX_CALL_TARGETS targets,
|
|
1079
|
+
* FLOOR_MAX_CALL_COMPONENTS components or FLOOR_MAX_CALL_BYTES bytes across them,
|
|
1080
|
+
* more than FLOOR_MAX_CALL_WALK components walked, or more than
|
|
1081
|
+
* FLOOR_MAX_CALL_CANONICAL characters of distinct non-ASCII names compared,
|
|
1082
|
+
* floors it.
|
|
407
1083
|
* @param {object} input
|
|
408
1084
|
* @param {string} [cwd]
|
|
409
1085
|
* @param {boolean} secretsOnly
|
|
410
1086
|
* @returns {boolean}
|
|
411
1087
|
*/
|
|
1088
|
+
function _newCall(statFn) {
|
|
1089
|
+
return {
|
|
1090
|
+
realBase: undefined,
|
|
1091
|
+
configRoot: undefined,
|
|
1092
|
+
walk: { left: FLOOR_MAX_CALL_WALK },
|
|
1093
|
+
idBudget: { left: FLOOR_MAX_CALL_IDENTITY },
|
|
1094
|
+
names: new Map(),
|
|
1095
|
+
canonical: { left: FLOOR_MAX_CALL_CANONICAL },
|
|
1096
|
+
ids: new Map(),
|
|
1097
|
+
statFn,
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
|
|
412
1101
|
function _matchesFloor(input, cwd, secretsOnly) {
|
|
413
1102
|
if (!input || typeof input !== 'object') return false
|
|
414
1103
|
const base = (typeof cwd === 'string' && cwd.length > 0) ? cwd : process.cwd()
|
|
1104
|
+
const targets = []
|
|
415
1105
|
for (const field of PROTECTED_PATH_INPUT_FIELDS) {
|
|
416
1106
|
if (typeof input[field] !== 'string' || input[field].length === 0) continue
|
|
417
|
-
|
|
1107
|
+
targets.push(input[field])
|
|
418
1108
|
}
|
|
419
|
-
// #6805/#6828 —
|
|
1109
|
+
// #6805/#6828 — the array-shaped per-file targets (codex apply_patch). Every
|
|
1110
|
+
// member counts toward the call's target budget, whatever it holds, so the
|
|
1111
|
+
// array is never enumerated past the budget.
|
|
420
1112
|
if (Array.isArray(input.changes)) {
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
1113
|
+
if (targets.length + input.changes.length > FLOOR_MAX_CALL_TARGETS) return true
|
|
1114
|
+
for (const changePath of collectChangeTargets(input.changes).paths) targets.push(changePath)
|
|
1115
|
+
if (targets.length > FLOOR_MAX_CALL_TARGETS) return true
|
|
1116
|
+
}
|
|
1117
|
+
// The call's component and byte budgets, checked before any target is resolved.
|
|
1118
|
+
let components = 0
|
|
1119
|
+
let bytes = 0
|
|
1120
|
+
for (const target of targets) {
|
|
1121
|
+
components += _componentCount(target, FLOOR_MAX_CALL_COMPONENTS - components)
|
|
1122
|
+
if (components > FLOOR_MAX_CALL_COMPONENTS) return true
|
|
1123
|
+
bytes += Buffer.byteLength(target, 'utf8')
|
|
1124
|
+
if (bytes > FLOOR_MAX_CALL_BYTES) return true
|
|
1125
|
+
}
|
|
1126
|
+
const call = _newCall()
|
|
1127
|
+
for (const target of targets) {
|
|
1128
|
+
if (isProtectedPathValue(target, base, secretsOnly, call)) return true
|
|
1129
|
+
}
|
|
1130
|
+
return false
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
// ---------------------------------------------------------------------------
|
|
1134
|
+
// #7978 — Grep's FILE-SELECTING `glob` field.
|
|
1135
|
+
//
|
|
1136
|
+
// The path fields above say WHERE a Grep searches; `glob` says WHICH FILES in
|
|
1137
|
+
// there it reads, and it is the stronger of the two. Every Grep implementation
|
|
1138
|
+
// Chroxy fronts runs ripgrep, and an include glob OVERRIDES ripgrep's ignore
|
|
1139
|
+
// rules: `rg --glob=.env -e X -- .` reads a gitignored `.env`, and so do `*`,
|
|
1140
|
+
// `**`, `sub/*`, `.e?v` and `*env*`. Claude Code's own Grep always passes
|
|
1141
|
+
// `--hidden`, so ripgrep's hidden-file filter is no barrier there; `.gitignore`
|
|
1142
|
+
// is the only one, and a glob walks straight through it. `*.json` is the
|
|
1143
|
+
// ordinary case, not the exotic one: it reads the `.claude/settings.local.json`
|
|
1144
|
+
// that Claude Code gitignores by default. Measured with ripgrep 15.2.0.
|
|
1145
|
+
//
|
|
1146
|
+
// Scanning only `path` therefore let `Grep({path: '.', glob: '.env'})` read
|
|
1147
|
+
// secrets while the floor answered "not floored", and a lenient mode then
|
|
1148
|
+
// auto-approved it.
|
|
1149
|
+
//
|
|
1150
|
+
// WHAT FLOORS. First, anything outside a small grammar floors unanalyzed:
|
|
1151
|
+
// ASCII letters, digits, `. _ - / !`, whitespace, `*`, `**`, `?`, and `{a,b}`
|
|
1152
|
+
// groups that hold at least one comma. A class, an escape, a single-alternative
|
|
1153
|
+
// or empty brace, or any non-ASCII character floors (GLOB_FLOOR_ANALYZABLE
|
|
1154
|
+
// says why). A glob inside the grammar is taken apart the way ripgrep takes it
|
|
1155
|
+
// (a pattern without a `/` matches a basename at any depth) and intersected with
|
|
1156
|
+
// TEMPLATES built from the floor's own name sets above. It floors when it can
|
|
1157
|
+
// match:
|
|
1158
|
+
// (a) an EXACT secret path, however it gets there: `.env`, SECRET_FILE_EXACT,
|
|
1159
|
+
// the CREDENTIAL_CONFIG_SEQUENCES, `.claude/settings{,.local}.json`, plus
|
|
1160
|
+
// the common real-world names in the two witness lists below. `*`, `**`,
|
|
1161
|
+
// `sub/*`, `*.json` and `*test*` all floor here;
|
|
1162
|
+
// (b) a member of a secret FAMILY — `.env.<tail>`, `<stem><secret ext>`,
|
|
1163
|
+
// `.claude/settings<mid>.json` — PROVIDED at least one character of the
|
|
1164
|
+
// family's defining part (`.env`, the extension, the settings skeleton) is
|
|
1165
|
+
// matched by something other than `*`/`**`. `.e?v.*`, `.env.????`,
|
|
1166
|
+
// `?.pem` and `*v.*` floor here.
|
|
1167
|
+
//
|
|
1168
|
+
// THE ONE ACCEPTED RESIDUAL, stated because (b) is where it lives. `*.ts` can
|
|
1169
|
+
// match `.env.ts`, a name the floor counts as a secret. It does so only by
|
|
1170
|
+
// letting `*` swallow the whole of `.env`, so it does not floor: a strictly
|
|
1171
|
+
// sound rule would floor every extension filter (`*.ts`, `*.py`) and prompt on
|
|
1172
|
+
// nearly every globbed Grep in a lenient mode. What still gets through is an
|
|
1173
|
+
// extension or stem filter aimed at a GITIGNORED secret whose name is none of
|
|
1174
|
+
// the witnesses — `*.ts` reading a gitignored `.env.ts`. The witness lists
|
|
1175
|
+
// exist to keep that set to unusual names. The same mechanism applies to a
|
|
1176
|
+
// DIRECTORY: `{*.d,*.conf}` can re-include a gitignored `.env.d/` and read its
|
|
1177
|
+
// `app.conf`, because `*` swallowed the `.env`.
|
|
1178
|
+
//
|
|
1179
|
+
// NOT COVERED, and not this field's job: a Grep with no glob reads every file
|
|
1180
|
+
// the ignore rules let through, secrets included when they are not gitignored.
|
|
1181
|
+
// That is the directory-grep limit of a path floor, unchanged here. Grep's
|
|
1182
|
+
// `type` field is not inspected because ripgrep's type filters RESPECT
|
|
1183
|
+
// `.gitignore` (measured: `-t sh` does not read a gitignored `.env`, though the
|
|
1184
|
+
// `sh` type lists it), so they select nothing a plain Grep does not. Glob's
|
|
1185
|
+
// `pattern` is not inspected either: it returns names, never contents.
|
|
1186
|
+
|
|
1187
|
+
/**
|
|
1188
|
+
* Tools whose input carries a file-selecting `glob` the floor inspects. The
|
|
1189
|
+
* shell hook's negative pre-filter keys on these NAMES (a `"Grep"` payload must
|
|
1190
|
+
* reach the daemon even with no path field) — tests/permission-hook-floor.test.js
|
|
1191
|
+
* asserts the hook matches every member.
|
|
1192
|
+
*/
|
|
1193
|
+
export const GLOB_SELECTOR_FLOOR_TOOLS = new Set(['Grep'])
|
|
1194
|
+
|
|
1195
|
+
// Common real-world secret names that only a (b)-exempt glob — one that
|
|
1196
|
+
// constrains the tail or the stem, not the defining part — could otherwise
|
|
1197
|
+
// reach. Each must be a secret by the floor's OWN predicate (asserted in
|
|
1198
|
+
// tests/permission-floor-grep-glob.test.js), so this list can only ever add
|
|
1199
|
+
// floors to names the floor already protects; it cannot widen what counts as a
|
|
1200
|
+
// secret. Missing a name here reopens only the residual described above.
|
|
1201
|
+
const ENV_TAIL_WITNESSES = [
|
|
1202
|
+
'local', 'development', 'production', 'test', 'staging', 'dev', 'prod',
|
|
1203
|
+
'example', 'sample', 'ci', 'qa', 'uat', 'preview', 'backup', 'bak', 'old',
|
|
1204
|
+
'secret', 'secrets', 'docker', 'development.local', 'production.local', 'test.local',
|
|
1205
|
+
]
|
|
1206
|
+
const KEY_STEM_WITNESSES = ['server', 'private', 'privkey', 'key', 'cert', 'fullchain', 'tls', 'client', 'ca', 'id']
|
|
1207
|
+
|
|
1208
|
+
/**
|
|
1209
|
+
* The floor's secret-name sets, read-only, so tests can derive their corpus
|
|
1210
|
+
* from the floor instead of restating it (tests/permission-floor-grep-glob.test.js).
|
|
1211
|
+
*/
|
|
1212
|
+
export const FLOOR_SECRET_NAMES = Object.freeze({
|
|
1213
|
+
envName: ENV_FILE_NAME,
|
|
1214
|
+
envPrefix: ENV_FILE_PREFIX,
|
|
1215
|
+
exact: Object.freeze([...SECRET_FILE_EXACT]),
|
|
1216
|
+
extensions: Object.freeze([...SECRET_FILE_EXTENSIONS]),
|
|
1217
|
+
credentialConfigPaths: Object.freeze(CREDENTIAL_CONFIG_SEQUENCES.map((sequence) => sequence.join('/'))),
|
|
1218
|
+
claudeSettings: Object.freeze({ dir: CLAUDE_SETTINGS_DIR, prefix: CLAUDE_SETTINGS_PREFIX, suffix: CLAUDE_SETTINGS_SUFFIX }),
|
|
1219
|
+
envTailWitnesses: Object.freeze([...ENV_TAIL_WITNESSES]),
|
|
1220
|
+
keyStemWitnesses: Object.freeze([...KEY_STEM_WITNESSES]),
|
|
1221
|
+
})
|
|
1222
|
+
|
|
1223
|
+
// Bounds on the analysis. Past any one the glob FLOORS (fail closed): a
|
|
1224
|
+
// pathological glob is not something to analyze at length on the hot path.
|
|
1225
|
+
// An ordinary glob visits ~10K search states (~1ms); the largest legitimate
|
|
1226
|
+
// shapes the caps allow visit ~450K (~9ms). A crafted glob can still multiply
|
|
1227
|
+
// states — `(**q)` repeated 330 times visited 5.8M (71ms, synchronous on the
|
|
1228
|
+
// daemon's event loop) — so one Grep call gets a shared STATE budget, and
|
|
1229
|
+
// running out of it floors (PR #7980 review).
|
|
1230
|
+
const GLOB_FLOOR_MAX_LENGTH = 1024
|
|
1231
|
+
const GLOB_FLOOR_MAX_ALTERNATIVES = 64
|
|
1232
|
+
const GLOB_FLOOR_MAX_EXPANDED_LENGTH = 4096
|
|
1233
|
+
export const GLOB_FLOOR_MAX_STATES = 1_000_000
|
|
1234
|
+
|
|
1235
|
+
let _globFloorTemplates = null
|
|
1236
|
+
let _globFloorTemplatesRootRelative = null
|
|
1237
|
+
|
|
1238
|
+
/**
|
|
1239
|
+
* The templates a Grep glob is intersected with, built once from the floor's
|
|
1240
|
+
* own sets. A template is a list of elements over a lowercased path:
|
|
1241
|
+
* { kind: 'lit', ch, core } one fixed character (`core`: part of a family's
|
|
1242
|
+
* defining text, see (b) above)
|
|
1243
|
+
* { kind: 'one' } exactly one non-`/` character
|
|
1244
|
+
* { kind: 'star', slash } any run of characters (`/` too when `slash`)
|
|
1245
|
+
* Every template also gets an any-directory-prefix variant, because a secret can
|
|
1246
|
+
* sit at any depth under the searched root.
|
|
1247
|
+
* `rootRelative` adds the `settings*.json` names bare (not behind `.claude/`),
|
|
1248
|
+
* for a search that reaches a configured Claude config directory whose name is
|
|
1249
|
+
* not `.claude` (see {@link _configRootRule}).
|
|
1250
|
+
* @param {boolean} [rootRelative]
|
|
1251
|
+
* @returns {{ elems: object[], requireCore: boolean }[]}
|
|
1252
|
+
*/
|
|
1253
|
+
function globFloorTemplates(rootRelative = false) {
|
|
1254
|
+
const cached = rootRelative ? _globFloorTemplatesRootRelative : _globFloorTemplates
|
|
1255
|
+
if (cached) return cached
|
|
1256
|
+
const lit = (text, core) => [...text].map((ch) => ({ kind: 'lit', ch, core }))
|
|
1257
|
+
const oneOrMore = [{ kind: 'one' }, { kind: 'star', slash: false }]
|
|
1258
|
+
const base = []
|
|
1259
|
+
const exact = (path) => base.push({ elems: lit(path, false), requireCore: false })
|
|
1260
|
+
|
|
1261
|
+
exact(ENV_FILE_NAME)
|
|
1262
|
+
for (const name of SECRET_FILE_EXACT) exact(name)
|
|
1263
|
+
for (const sequence of CREDENTIAL_CONFIG_SEQUENCES) exact(sequence.join('/'))
|
|
1264
|
+
for (const name of ['', '.local']) {
|
|
1265
|
+
exact(`${CLAUDE_SETTINGS_DIR}/${CLAUDE_SETTINGS_PREFIX}${name}${CLAUDE_SETTINGS_SUFFIX}`)
|
|
1266
|
+
}
|
|
1267
|
+
for (const tail of ENV_TAIL_WITNESSES) exact(ENV_FILE_PREFIX + tail)
|
|
1268
|
+
for (const stem of KEY_STEM_WITNESSES) {
|
|
1269
|
+
for (const ext of SECRET_FILE_EXTENSIONS) exact(stem + ext)
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
// Families. The `.` that ends ENV_FILE_PREFIX is a separator, not part of the
|
|
1273
|
+
// env-ness, so it is NOT core — otherwise `*.ts` would spell it and floor.
|
|
1274
|
+
base.push({
|
|
1275
|
+
elems: [...lit(ENV_FILE_NAME, true), ...lit('.', false), ...oneOrMore],
|
|
1276
|
+
requireCore: true,
|
|
1277
|
+
})
|
|
1278
|
+
for (const ext of SECRET_FILE_EXTENSIONS) {
|
|
1279
|
+
base.push({ elems: [...oneOrMore, ...lit(ext, true)], requireCore: true })
|
|
1280
|
+
}
|
|
1281
|
+
base.push({
|
|
1282
|
+
elems: [
|
|
1283
|
+
...lit(`${CLAUDE_SETTINGS_DIR}/${CLAUDE_SETTINGS_PREFIX}`, true),
|
|
1284
|
+
{ kind: 'star', slash: false },
|
|
1285
|
+
...lit(CLAUDE_SETTINGS_SUFFIX, true),
|
|
1286
|
+
],
|
|
1287
|
+
requireCore: true,
|
|
1288
|
+
})
|
|
1289
|
+
|
|
1290
|
+
if (rootRelative) {
|
|
1291
|
+
for (const name of ['', '.local']) exact(`${CLAUDE_SETTINGS_PREFIX}${name}${CLAUDE_SETTINGS_SUFFIX}`)
|
|
1292
|
+
base.push({
|
|
1293
|
+
elems: [...lit(CLAUDE_SETTINGS_PREFIX, true), { kind: 'star', slash: false }, ...lit(CLAUDE_SETTINGS_SUFFIX, true)],
|
|
1294
|
+
requireCore: true,
|
|
1295
|
+
})
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
const anyDirectory = [{ kind: 'star', slash: true }, { kind: 'lit', ch: '/', core: false }]
|
|
1299
|
+
const built = base.flatMap((t) => [t, { elems: [...anyDirectory, ...t.elems], requireCore: t.requireCore }])
|
|
1300
|
+
if (rootRelative) _globFloorTemplatesRootRelative = built
|
|
1301
|
+
else _globFloorTemplates = built
|
|
1302
|
+
return built
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
// The only characters the analysis models (PR #7980 review). Anything else in a
|
|
1306
|
+
// glob — a `[...]` class, a `\` escape, any non-ASCII character
|
|
1307
|
+
// (ripgrep trims trailing Unicode whitespace such as U+0085 that `\s` does not
|
|
1308
|
+
// match) — FLOORS without analysis. Four independent mismatches with ripgrep's
|
|
1309
|
+
// globset were found in exactly those constructs (a class matching `/`, `\`
|
|
1310
|
+
// being literal inside a class, chained ranges, a `,` inside a class inside a
|
|
1311
|
+
// brace group), so the parser does not try to be globset: it recognizes a small
|
|
1312
|
+
// grammar and refuses the rest. The ordinary filters (`*.ts`, `*.{ts,tsx}`,
|
|
1313
|
+
// `src/**/*.py`) are all inside it.
|
|
1314
|
+
// A `!` past the first character is a literal to ripgrep (only a LEADING `!`
|
|
1315
|
+
// negates, and classes are excluded), so it is kept.
|
|
1316
|
+
const GLOB_FLOOR_ANALYZABLE = /^[A-Za-z0-9._/*?{},!\- \t\n\r\v\f]*$/
|
|
1317
|
+
// Claude Code passes each whitespace/comma piece as its own --glob; past this
|
|
1318
|
+
// many pieces the call floors rather than analyze each one.
|
|
1319
|
+
const GLOB_FLOOR_MAX_PIECES = 32
|
|
1320
|
+
|
|
1321
|
+
/**
|
|
1322
|
+
* Expand `{a,b}` alternatives (nested too). Every `{` must close and hold at
|
|
1323
|
+
* least one top-level comma: ripgrep treats `{x}` and `{}` as a real
|
|
1324
|
+
* alternation (`{.env}` reads `.env`), so a brace this function cannot expand
|
|
1325
|
+
* is not "literal text" — the caller floors it. Returns null for an unmatched
|
|
1326
|
+
* or comma-less brace, a stray `}`, or past {@link GLOB_FLOOR_MAX_ALTERNATIVES}.
|
|
1327
|
+
* Runs only on {@link GLOB_FLOOR_ANALYZABLE} input, so there is no `[` or `\`
|
|
1328
|
+
* that could hide a brace or a comma.
|
|
1329
|
+
* @param {string} glob
|
|
1330
|
+
* @returns {string[] | null}
|
|
1331
|
+
*/
|
|
1332
|
+
function expandGlobBraces(glob) {
|
|
1333
|
+
const open = glob.indexOf('{')
|
|
1334
|
+
if (open === -1) return glob.includes('}') ? null : [glob]
|
|
1335
|
+
if (glob.slice(0, open).includes('}')) return null
|
|
1336
|
+
let depth = 0
|
|
1337
|
+
const commas = []
|
|
1338
|
+
let close = -1
|
|
1339
|
+
for (let i = open; i < glob.length; i++) {
|
|
1340
|
+
const ch = glob[i]
|
|
1341
|
+
if (ch === '{') depth++
|
|
1342
|
+
else if (ch === '}') {
|
|
1343
|
+
depth--
|
|
1344
|
+
if (depth === 0) { close = i; break }
|
|
1345
|
+
} else if (ch === ',' && depth === 1) commas.push(i)
|
|
1346
|
+
}
|
|
1347
|
+
if (close === -1 || commas.length === 0) return null
|
|
1348
|
+
const head = glob.slice(0, open)
|
|
1349
|
+
const tail = glob.slice(close + 1)
|
|
1350
|
+
const bounds = [open, ...commas, close]
|
|
1351
|
+
const out = []
|
|
1352
|
+
for (let k = 0; k < bounds.length - 1; k++) {
|
|
1353
|
+
const expanded = expandGlobBraces(head + glob.slice(bounds[k] + 1, bounds[k + 1]) + tail)
|
|
1354
|
+
if (expanded === null) return null
|
|
1355
|
+
out.push(...expanded)
|
|
1356
|
+
if (out.length > GLOB_FLOOR_MAX_ALTERNATIVES) return null
|
|
1357
|
+
}
|
|
1358
|
+
return out
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
/**
|
|
1362
|
+
* Tokenize one brace-free alternative of an analyzable glob: `*`, `**`, `?`
|
|
1363
|
+
* and literals. `**` anywhere is a cross-directory wildcard and swallows a
|
|
1364
|
+
* following `/` (so `a/**\/b` still matches `a/b`); treating a non-segment `**`
|
|
1365
|
+
* that way only ever admits more, i.e. floors more.
|
|
1366
|
+
* @param {string} glob
|
|
1367
|
+
* @returns {object[]}
|
|
1368
|
+
*/
|
|
1369
|
+
function tokenizeGlob(glob) {
|
|
1370
|
+
const tokens = []
|
|
1371
|
+
for (let i = 0; i < glob.length; i++) {
|
|
1372
|
+
const ch = glob[i]
|
|
1373
|
+
if (ch === '*') {
|
|
1374
|
+
if (glob[i + 1] === '*') {
|
|
1375
|
+
i++
|
|
1376
|
+
while (glob[i + 1] === '*') i++
|
|
1377
|
+
if (glob[i + 1] === '/') i++
|
|
1378
|
+
// `**/**/` matches exactly what `**/` does; collapsing the run keeps a
|
|
1379
|
+
// 330-deep repetition from costing 20ms of search (PR #7980 review).
|
|
1380
|
+
if (tokens.length === 0 || tokens[tokens.length - 1].kind !== 'globstar') tokens.push({ kind: 'globstar' })
|
|
1381
|
+
} else {
|
|
1382
|
+
tokens.push({ kind: 'star' })
|
|
1383
|
+
}
|
|
1384
|
+
} else if (ch === '?') {
|
|
1385
|
+
tokens.push({ kind: 'any' })
|
|
1386
|
+
} else {
|
|
1387
|
+
tokens.push({ kind: 'lit', ch })
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
return tokens
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
/**
|
|
1394
|
+
* Can glob token `tok` consume the (lowercase) template character `ch`? The
|
|
1395
|
+
* floor lowercases names, so a literal admits `ch` when it lowercases to it.
|
|
1396
|
+
*/
|
|
1397
|
+
function _tokenAdmits(tok, ch) {
|
|
1398
|
+
switch (tok.kind) {
|
|
1399
|
+
case 'lit': return tok.ch.toLowerCase() === ch
|
|
1400
|
+
case 'any': case 'star': return ch !== '/'
|
|
1401
|
+
case 'globstar': return true
|
|
1402
|
+
default: return true
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
/**
|
|
1407
|
+
* Is there a string that both the glob `tokens` and template `t` match — and,
|
|
1408
|
+
* when `t.requireCore`, one where some `core` character is consumed by a token
|
|
1409
|
+
* other than `*`/`**`? A search over (glob position, template position, core
|
|
1410
|
+
* seen) — at most (|tokens|+1) x (|template|+1) x 2 states. Every state visited
|
|
1411
|
+
* is charged to `budget`; past it the answer is null, which the caller floors.
|
|
1412
|
+
* @returns {boolean | null}
|
|
1413
|
+
*/
|
|
1414
|
+
function _globMatchesTemplate(tokens, t, budget) {
|
|
1415
|
+
const elems = t.elems
|
|
1416
|
+
const G = tokens.length
|
|
1417
|
+
const T = elems.length
|
|
1418
|
+
const seen = new Uint8Array((G + 1) * (T + 1) * 2)
|
|
1419
|
+
const stack = [0, 0, 0]
|
|
1420
|
+
while (stack.length > 0) {
|
|
1421
|
+
const core = stack.pop()
|
|
1422
|
+
const ti = stack.pop()
|
|
1423
|
+
const gi = stack.pop()
|
|
1424
|
+
const key = (gi * (T + 1) + ti) * 2 + core
|
|
1425
|
+
if (seen[key]) continue
|
|
1426
|
+
seen[key] = 1
|
|
1427
|
+
if (--budget.left < 0) return null
|
|
1428
|
+
if (gi === G && ti === T && (core === 1 || !t.requireCore)) return true
|
|
1429
|
+
const g = gi < G ? tokens[gi] : null
|
|
1430
|
+
const e = ti < T ? elems[ti] : null
|
|
1431
|
+
const gRepeats = g !== null && (g.kind === 'star' || g.kind === 'globstar')
|
|
1432
|
+
// A wildcard on either side may match nothing.
|
|
1433
|
+
if (gRepeats) stack.push(gi + 1, ti, core)
|
|
1434
|
+
if (e !== null && e.kind === 'star') stack.push(gi, ti + 1, core)
|
|
1435
|
+
if (g === null || e === null) continue
|
|
1436
|
+
// Or both consume one character.
|
|
1437
|
+
let joint
|
|
1438
|
+
if (e.kind === 'lit') joint = _tokenAdmits(g, e.ch)
|
|
1439
|
+
else if (e.kind === 'star' && e.slash) joint = true
|
|
1440
|
+
else joint = g.kind !== 'lit' || g.ch !== '/'
|
|
1441
|
+
if (!joint) continue
|
|
1442
|
+
const nextCore = (core === 1 || (e.kind === 'lit' && e.core && !gRepeats)) ? 1 : 0
|
|
1443
|
+
stack.push(gRepeats ? gi : gi + 1, e.kind === 'star' ? ti : ti + 1, nextCore)
|
|
1444
|
+
}
|
|
1445
|
+
return false
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
/**
|
|
1449
|
+
* #7978 — can a single ripgrep glob select a secret file? See the section
|
|
1450
|
+
* comment above for exactly what floors and the one accepted residual. Trailing
|
|
1451
|
+
* ASCII whitespace is trimmed, as ripgrep trims it; LEADING whitespace is kept,
|
|
1452
|
+
* because ripgrep keeps it (` !x` is a literal include, not an exclusion). A
|
|
1453
|
+
* leading `!` only excludes, so it never floors. Outside
|
|
1454
|
+
* {@link GLOB_FLOOR_ANALYZABLE}, with a brace that does not expand, past a size
|
|
1455
|
+
* cap, or once `budget` runs out, the glob floors without a full analysis.
|
|
1456
|
+
* @param {string} glob
|
|
1457
|
+
* @param {{ left: number }} [budget] search states left; shared across one Grep call
|
|
1458
|
+
* @param {boolean} [rootRelative] also match bare `settings*.json` (see {@link globFloorTemplates})
|
|
1459
|
+
* @returns {boolean}
|
|
1460
|
+
*/
|
|
1461
|
+
export function globSelectsSecret(glob, budget = { left: GLOB_FLOOR_MAX_STATES }, rootRelative = false) {
|
|
1462
|
+
if (typeof glob !== 'string') return true
|
|
1463
|
+
if (glob.length > GLOB_FLOOR_MAX_LENGTH) return true
|
|
1464
|
+
const trimmed = glob.replace(/[ \t\n\r\v\f]+$/, '')
|
|
1465
|
+
if (trimmed.length === 0) return false
|
|
1466
|
+
if (trimmed.startsWith('!')) return false
|
|
1467
|
+
if (!GLOB_FLOOR_ANALYZABLE.test(trimmed)) return true
|
|
1468
|
+
const alternatives = expandGlobBraces(trimmed)
|
|
1469
|
+
if (alternatives === null) return true
|
|
1470
|
+
if (alternatives.reduce((sum, alt) => sum + alt.length, 0) > GLOB_FLOOR_MAX_EXPANDED_LENGTH) return true
|
|
1471
|
+
const templates = globFloorTemplates(rootRelative)
|
|
1472
|
+
for (let alt of alternatives) {
|
|
1473
|
+
// Anchors: ripgrep roots a leading `/` at the search root, and `./` names
|
|
1474
|
+
// the same place. Both only narrow where a match can sit; drop them.
|
|
1475
|
+
while (alt.startsWith('/') || alt.startsWith('./')) alt = alt.startsWith('/') ? alt.slice(1) : alt.slice(2)
|
|
1476
|
+
// A trailing `/` means "directories only", and ripgrep drops it BEFORE it
|
|
1477
|
+
// decides whether the glob is anchored: `.env/` behaves as `**/.env` and
|
|
1478
|
+
// re-includes a gitignored `.env/` directory for another piece to read
|
|
1479
|
+
// from (PR #7980 review). Drop it here too, before the same decision.
|
|
1480
|
+
while (alt.endsWith('/')) alt = alt.slice(0, -1)
|
|
1481
|
+
if (alt.length === 0) continue
|
|
1482
|
+
const tokens = tokenizeGlob(alt)
|
|
1483
|
+
// Without a `/`, ripgrep matches the basename at any depth: try the glob
|
|
1484
|
+
// both against a top-level name and behind an arbitrary directory.
|
|
1485
|
+
const variants = alt.includes('/')
|
|
1486
|
+
? [tokens]
|
|
1487
|
+
: [tokens, [{ kind: 'globstar' }, { kind: 'lit', ch: '/' }, ...tokens]]
|
|
1488
|
+
for (const variant of variants) {
|
|
1489
|
+
for (const t of templates) {
|
|
1490
|
+
const hit = _globMatchesTemplate(variant, t, budget)
|
|
1491
|
+
if (hit !== false) return true
|
|
1492
|
+
}
|
|
424
1493
|
}
|
|
425
1494
|
}
|
|
426
1495
|
return false
|
|
427
1496
|
}
|
|
428
1497
|
|
|
1498
|
+
/**
|
|
1499
|
+
* #7978 — do a Grep input's `glob` values select a secret? Claude Code splits
|
|
1500
|
+
* the field on whitespace and then on commas (unless the piece holds a `{...}`
|
|
1501
|
+
* group) and passes each piece as its own `--glob`; the BYOK executor passes
|
|
1502
|
+
* the whole string as ONE `--glob`. Both readings are checked, and either one
|
|
1503
|
+
* flooring floors the input. A `glob` that is present but not a string floors:
|
|
1504
|
+
* the floor cannot say what an executor would make of it. So does one too long
|
|
1505
|
+
* to split, or one that splits into more than {@link GLOB_FLOOR_MAX_PIECES}.
|
|
1506
|
+
* @param {object} input
|
|
1507
|
+
* @returns {boolean}
|
|
1508
|
+
*/
|
|
1509
|
+
function grepGlobFloored(input, rootRelative) {
|
|
1510
|
+
const glob = input.glob
|
|
1511
|
+
if (glob === undefined || glob === null) return false
|
|
1512
|
+
if (typeof glob !== 'string') return true
|
|
1513
|
+
if (glob.length > GLOB_FLOOR_MAX_LENGTH) return true
|
|
1514
|
+
const readings = new Set([glob])
|
|
1515
|
+
for (const piece of glob.split(/\s+/)) {
|
|
1516
|
+
if (piece.includes('{') && piece.includes('}')) readings.add(piece)
|
|
1517
|
+
else for (const part of piece.split(',')) readings.add(part)
|
|
1518
|
+
if (readings.size > GLOB_FLOOR_MAX_PIECES) return true
|
|
1519
|
+
}
|
|
1520
|
+
const budget = { left: GLOB_FLOOR_MAX_STATES }
|
|
1521
|
+
for (const reading of readings) {
|
|
1522
|
+
if (globSelectsSecret(reading, budget, rootRelative)) return true
|
|
1523
|
+
}
|
|
1524
|
+
return false
|
|
1525
|
+
}
|
|
429
1526
|
/**
|
|
430
1527
|
* #7004 — the floor decision for ONE (tool, input) pair: the tool-aware choice
|
|
431
1528
|
* between the read floor and the full write floor, plus the predicate itself.
|
|
@@ -434,7 +1531,9 @@ function _matchesFloor(input, cwd, secretsOnly) {
|
|
|
434
1531
|
*
|
|
435
1532
|
* - {@link SECRET_READ_FLOOR_TOOLS} (Read / Glob / Grep — non-mutating) are
|
|
436
1533
|
* floored ONLY on secret + credential files ({@link isSecretReadTarget});
|
|
437
|
-
* reading a config dir stays benign and un-prompted.
|
|
1534
|
+
* reading a config dir stays benign and un-prompted. The one addition is a
|
|
1535
|
+
* Grep ROOTED at a directory holding those files, which floors unless an
|
|
1536
|
+
* include glob narrows it (see {@link CREDENTIAL_CONFIG_DIRS}).
|
|
438
1537
|
* - EVERY other tool (the mutating ones, and any future/unknown tool) gets the
|
|
439
1538
|
* full config-dir + secret floor ({@link isProtectedPathTarget}) — defaulting
|
|
440
1539
|
* the unknown case to the STRONGER floor is fail-safe.
|
|
@@ -449,7 +1548,275 @@ function _matchesFloor(input, cwd, secretsOnly) {
|
|
|
449
1548
|
* @returns {boolean} true when the target is floored (prompt required)
|
|
450
1549
|
*/
|
|
451
1550
|
export function isFlooredTarget(toolName, input, cwd) {
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
1551
|
+
// A patch whose change list is missing, malformed or empty names no paths the
|
|
1552
|
+
// floor can judge, so it always prompts.
|
|
1553
|
+
if (toolName === 'apply_patch' && !_hasCompleteChangeList(input)) return true
|
|
1554
|
+
if (!SECRET_READ_FLOOR_TOOLS.has(toolName)) return isProtectedPathTarget(input, cwd)
|
|
1555
|
+
if (isSecretReadTarget(input, cwd)) return true
|
|
1556
|
+
if (SEARCH_ROOT_TOOLS.has(toolName) && _searchRootFloored(toolName, input, cwd)) return true
|
|
1557
|
+
// #7978 — Grep's `glob` picks WHICH files it reads, overriding .gitignore.
|
|
1558
|
+
if (!GLOB_SELECTOR_FLOOR_TOOLS.has(toolName) || input === null || typeof input !== 'object') return false
|
|
1559
|
+
const reach = _searchReachToConfigRoot(input, cwd)
|
|
1560
|
+
if (grepGlobFloored(input, reach.near)) return true
|
|
1561
|
+
// No glob narrowing the search: a recursive Grep from the configured root, or
|
|
1562
|
+
// from a directory above it, reads the settings files inside it.
|
|
1563
|
+
return reach.covers && !globNarrowsSearch(input.glob)
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
/**
|
|
1567
|
+
* Does a patch input carry a non-empty, well-formed `changes` array?
|
|
1568
|
+
* @param {object} input
|
|
1569
|
+
* @returns {boolean}
|
|
1570
|
+
*/
|
|
1571
|
+
function _hasCompleteChangeList(input) {
|
|
1572
|
+
if (input === null || typeof input !== 'object') return false
|
|
1573
|
+
if (!Array.isArray(input.changes) || input.changes.length === 0) return false
|
|
1574
|
+
return collectChangeTargets(input.changes).complete
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
/**
|
|
1578
|
+
* Can the Grep `glob` provably not select a `.key` file? True only when it has
|
|
1579
|
+
* at least one piece and every piece (judged alone, under each reading of the field,
|
|
1580
|
+
* see {@link grepGlobFloored}) is inside the analysable grammar and ends in a fixed
|
|
1581
|
+
* extension other than `key`: `*.js`, `src/**\/*.{js,ts}`. Anything else is
|
|
1582
|
+
* treated as able to select one, including `*`, `**`, `sessions/123*`,
|
|
1583
|
+
* `sessions/**`, `**\/*.key`, a class or escape, a directory (trailing `/`), and
|
|
1584
|
+
* a glob that only excludes. Case-insensitive on the extension.
|
|
1585
|
+
* @param {unknown} glob
|
|
1586
|
+
* @returns {boolean}
|
|
1587
|
+
*/
|
|
1588
|
+
function globAvoidsKeyFiles(glob) {
|
|
1589
|
+
if (typeof glob !== 'string' || glob.length === 0 || glob.length > GLOB_FLOOR_MAX_LENGTH) return false
|
|
1590
|
+
// Any `!` can turn a piece into an exclusion under one reading of the field
|
|
1591
|
+
// and leave it an include under another, so none can be reasoned about.
|
|
1592
|
+
if (glob.includes('!')) return false
|
|
1593
|
+
const readings = new Set([glob])
|
|
1594
|
+
for (const piece of glob.split(/\s+/)) {
|
|
1595
|
+
if (piece.includes('{') && piece.includes('}')) readings.add(piece)
|
|
1596
|
+
else for (const part of piece.split(',')) readings.add(part)
|
|
1597
|
+
if (readings.size > GLOB_FLOOR_MAX_PIECES) return false
|
|
1598
|
+
}
|
|
1599
|
+
let judged = 0
|
|
1600
|
+
for (const reading of readings) {
|
|
1601
|
+
const trimmed = reading.replace(/[ \t\n\r\v\f]+$/, '')
|
|
1602
|
+
// Nothing is passed to ripgrep for an empty piece; each real one is judged alone.
|
|
1603
|
+
if (trimmed.length === 0) continue
|
|
1604
|
+
if (!GLOB_FLOOR_ANALYZABLE.test(trimmed)) return false
|
|
1605
|
+
const alternatives = expandGlobBraces(trimmed)
|
|
1606
|
+
if (alternatives === null) return false
|
|
1607
|
+
if (alternatives.reduce((sum, alt) => sum + alt.length, 0) > GLOB_FLOOR_MAX_EXPANDED_LENGTH) return false
|
|
1608
|
+
for (const alt of alternatives) {
|
|
1609
|
+
const last = alt.slice(alt.lastIndexOf('/') + 1)
|
|
1610
|
+
const dot = last.lastIndexOf('.')
|
|
1611
|
+
const ext = dot === -1 ? '' : last.slice(dot + 1)
|
|
1612
|
+
if (ext.length === 0 || /[*?]/.test(ext) || ext.toLowerCase() === 'key') return false
|
|
1613
|
+
}
|
|
1614
|
+
judged++
|
|
1615
|
+
}
|
|
1616
|
+
return judged > 0
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
export const SEARCH_ROOT_TOOLS = new Set(['Grep', 'Glob'])
|
|
1620
|
+
|
|
1621
|
+
/**
|
|
1622
|
+
* The directory a Grep / Glob call searches from, as the executor reads it: its
|
|
1623
|
+
* `path`, or the session cwd (`'.'`) when `path` is absent, null or empty. Other fields
|
|
1624
|
+
* never stand in for it. Returns null when `path` is present but not a usable
|
|
1625
|
+
* string, so the caller fails closed.
|
|
1626
|
+
* @param {object} input
|
|
1627
|
+
* @returns {string|null}
|
|
1628
|
+
*/
|
|
1629
|
+
export function effectiveSearchRoot(input) {
|
|
1630
|
+
const value = input?.path
|
|
1631
|
+
if (value === undefined || value === null || value === '') return '.'
|
|
1632
|
+
return typeof value === 'string' && value.length > 0 ? value : null
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
/**
|
|
1636
|
+
* The paths to judge for a search call: its effective root, plus any other flat
|
|
1637
|
+
* path field it carries (which may add checks, never replace the root).
|
|
1638
|
+
* Returns null when the root is unusable.
|
|
1639
|
+
* @param {object} input
|
|
1640
|
+
* @returns {string[]|null}
|
|
1641
|
+
*/
|
|
1642
|
+
function _searchTargets(input) {
|
|
1643
|
+
const root = effectiveSearchRoot(input)
|
|
1644
|
+
if (root === null) return null
|
|
1645
|
+
const targets = [root]
|
|
1646
|
+
for (const f of PROTECTED_PATH_INPUT_FIELDS) {
|
|
1647
|
+
if (f !== 'path' && typeof input[f] === 'string' && input[f].length > 0) targets.push(input[f])
|
|
1648
|
+
}
|
|
1649
|
+
return targets
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
// The directories that hold the read-floored credential files, derived from
|
|
1653
|
+
// the same tables the read floor matches: the parent of each
|
|
1654
|
+
// CREDENTIAL_CONFIG_SEQUENCES entry (`.git`, `.config/git`) and the directory
|
|
1655
|
+
// of the `settings*.json` rule (`.claude`). A recursive search rooted at one of
|
|
1656
|
+
// them reads those files. Searches rooted ABOVE one are deliberately not judged
|
|
1657
|
+
// here: an ordinary project-root search is above `.claude`, and a search with
|
|
1658
|
+
// no `glob` already reads whatever the ignore rules let through (the documented
|
|
1659
|
+
// directory-search limit), so judging ancestors would prompt on every search.
|
|
1660
|
+
export const CREDENTIAL_CONFIG_DIRS = Object.freeze([
|
|
1661
|
+
...CREDENTIAL_CONFIG_SEQUENCES.map((sequence) => sequence.slice(0, -1)),
|
|
1662
|
+
[CLAUDE_SETTINGS_DIR],
|
|
1663
|
+
].filter((dir, i, all) => all.findIndex((d) => d.join('/') === dir.join('/')) === i))
|
|
1664
|
+
|
|
1665
|
+
/**
|
|
1666
|
+
* Is the absolute `resolved` itself one of the {@link CREDENTIAL_CONFIG_DIRS}
|
|
1667
|
+
* (its last path names, in the lowercased or canonical spelling)? A name that
|
|
1668
|
+
* cannot be canonicalised floors, and so does an 8.3 short name in the last
|
|
1669
|
+
* positions (a root that is the cwd itself has no relative segments for the
|
|
1670
|
+
* read floor's target scan to see).
|
|
1671
|
+
* @param {string} resolved
|
|
1672
|
+
* @param {object} call
|
|
1673
|
+
* @returns {boolean}
|
|
1674
|
+
*/
|
|
1675
|
+
function _isCredentialConfigDir(resolved, call) {
|
|
1676
|
+
const pieces = resolved.split(/[/\\]+/).filter((s) => s.length > 0 && s !== '..').map(segmentName)
|
|
1677
|
+
const longest = Math.max(...CREDENTIAL_CONFIG_DIRS.map((d) => d.length))
|
|
1678
|
+
const tail = pieces.slice(-longest)
|
|
1679
|
+
if (tail.some((name) => SHORT_NAME_SEGMENT.test(name))) return true
|
|
1680
|
+
const canonical = []
|
|
1681
|
+
for (const name of tail) {
|
|
1682
|
+
const form = _canonicalNameIn(name, call)
|
|
1683
|
+
if (form === null) return true
|
|
1684
|
+
canonical.push(form)
|
|
1685
|
+
}
|
|
1686
|
+
const lowered = tail.map((name) => name.toLowerCase())
|
|
1687
|
+
return CREDENTIAL_CONFIG_DIRS.some((dir) =>
|
|
1688
|
+
[lowered, canonical].some((names) => names.length >= dir.length &&
|
|
1689
|
+
dir.every((name, k) => names[names.length - dir.length + k] === name)))
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
/**
|
|
1693
|
+
* Where a Grep / Glob searches, against the inbox socket, sessions and
|
|
1694
|
+
* credential-config-directory rules.
|
|
1695
|
+
* A call with no path field searches from the session cwd, so the cwd stands
|
|
1696
|
+
* in for the missing root; a supplied root is judged in its written and its
|
|
1697
|
+
* symlink-resolved form. A Grep also floors from the sessions directory's
|
|
1698
|
+
* parent or an ancestor of it when it can reach it (see
|
|
1699
|
+
* {@link _searchReachesSessions}) and no `glob` narrows it. A Glob returns
|
|
1700
|
+
* names only, so it floors only when rooted in the directories themselves.
|
|
1701
|
+
* Fails closed.
|
|
1702
|
+
* @param {string} toolName
|
|
1703
|
+
* @param {object} input
|
|
1704
|
+
* @param {string} [cwd]
|
|
1705
|
+
* @returns {boolean}
|
|
1706
|
+
*/
|
|
1707
|
+
function _searchRootFloored(toolName, input, cwd) {
|
|
1708
|
+
if (input === null || typeof input !== 'object') return false
|
|
1709
|
+
const base = (typeof cwd === 'string' && cwd.length > 0) ? cwd : process.cwd()
|
|
1710
|
+
const targets = _searchTargets(input)
|
|
1711
|
+
if (targets === null) return true
|
|
1712
|
+
const call = _newCall()
|
|
1713
|
+
try {
|
|
1714
|
+
const realBase = realpathDeepestAncestorSync(base)
|
|
1715
|
+
for (const target of targets) {
|
|
1716
|
+
const forms = [resolve(base, target), resolveTargetComponentwiseSync(realBase, target, call.walk)]
|
|
1717
|
+
for (const form of forms) {
|
|
1718
|
+
if (_hitsInboxSocketDir(form, call) || _isSessionsDir(form, call)) return true
|
|
1719
|
+
if (toolName === 'Grep' && !globAvoidsKeyFiles(input.glob) && _searchReachesSessions(form, call)) return true
|
|
1720
|
+
// A Grep rooted at a directory holding read-floored files reads them
|
|
1721
|
+
// unless a `glob` narrows it (the glob analysis floors one that can
|
|
1722
|
+
// select a protected file). A Glob returns names only, so it is not
|
|
1723
|
+
// judged here, as for the sessions directory's parent.
|
|
1724
|
+
if (toolName === 'Grep' && _isCredentialConfigDir(form, call) && !globNarrowsSearch(input.glob)) return true
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
return false
|
|
1728
|
+
} catch {
|
|
1729
|
+
return true
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
/**
|
|
1734
|
+
* Does the Grep `glob` field restrict which files are searched? Absent, empty,
|
|
1735
|
+
* and exclusion-only (`!x`) globs do not.
|
|
1736
|
+
* @param {unknown} glob
|
|
1737
|
+
* @returns {boolean}
|
|
1738
|
+
*/
|
|
1739
|
+
function globNarrowsSearch(glob) {
|
|
1740
|
+
if (glob === undefined || glob === null) return false
|
|
1741
|
+
if (typeof glob !== 'string') return true
|
|
1742
|
+
return glob.split(/[\s,]+/).some((piece) => piece.length > 0 && !piece.startsWith('!'))
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
/**
|
|
1746
|
+
* How a Grep's search location relates to a configured Claude config directory
|
|
1747
|
+
* whose name is not `.claude`: `near` when it is inside it or reaches it, and
|
|
1748
|
+
* `covers` when it is the root or above it (so a recursive search reaches the
|
|
1749
|
+
* files directly inside it). `near` makes its `glob` also be tested against
|
|
1750
|
+
* bare `settings*.json`. Fails closed: a location that cannot be resolved
|
|
1751
|
+
* counts as both.
|
|
1752
|
+
* @param {object} input
|
|
1753
|
+
* @param {string} [cwd]
|
|
1754
|
+
* @param {Function} [statFn] injected `stat`, for tests
|
|
1755
|
+
* @returns {{ near: boolean, covers: boolean }}
|
|
1756
|
+
*/
|
|
1757
|
+
function _searchReachToConfigRoot(input, cwd, statFn) {
|
|
1758
|
+
const call = _newCall(statFn)
|
|
1759
|
+
const rule = _configRootRule(call)
|
|
1760
|
+
if (rule === null) return { near: false, covers: false }
|
|
1761
|
+
if (rule.failed) return { near: true, covers: true }
|
|
1762
|
+
const base = (typeof cwd === 'string' && cwd.length > 0) ? cwd : process.cwd()
|
|
1763
|
+
const targets = _searchTargets(input)
|
|
1764
|
+
if (targets === null) return { near: true, covers: true }
|
|
1765
|
+
const reach = { near: false, covers: false }
|
|
1766
|
+
try {
|
|
1767
|
+
const realBase = realpathDeepestAncestorSync(base)
|
|
1768
|
+
for (const target of targets) {
|
|
1769
|
+
const real = resolveTargetComponentwiseSync(realBase, target, { left: FLOOR_MAX_CALL_WALK })
|
|
1770
|
+
const { inside, covers } = _rootRelation(rule, real, true, call)
|
|
1771
|
+
if (inside !== null || covers) reach.near = true
|
|
1772
|
+
if (covers) reach.covers = true
|
|
1773
|
+
}
|
|
1774
|
+
return reach
|
|
1775
|
+
} catch {
|
|
1776
|
+
return { near: true, covers: true }
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
/**
|
|
1781
|
+
* Internals exposed for tests only: they take an injected `stat` so the
|
|
1782
|
+
* fail-closed paths (a lookup that errors, a spent budget) can be driven
|
|
1783
|
+
* without making a real directory unreadable.
|
|
1784
|
+
*/
|
|
1785
|
+
export const floorInternalsForTest = {
|
|
1786
|
+
sameName(a, b) {
|
|
1787
|
+
return _sameName(a, b, _newCall())
|
|
1788
|
+
},
|
|
1789
|
+
hitsConfigRoot(resolved, secretsOnly, statFn, budget, configDirFn) {
|
|
1790
|
+
const call = _newCall(statFn)
|
|
1791
|
+
call.configDirFn = configDirFn
|
|
1792
|
+
if (budget !== undefined) call.idBudget.left = budget
|
|
1793
|
+
// An array is evaluated within ONE call, sharing its lookups and budget.
|
|
1794
|
+
let hit = false
|
|
1795
|
+
for (const target of Array.isArray(resolved) ? resolved : [resolved]) {
|
|
1796
|
+
if (_hitsConfigRoot(target, secretsOnly, call)) hit = true
|
|
1797
|
+
}
|
|
1798
|
+
return hit
|
|
1799
|
+
},
|
|
1800
|
+
hitsInboxSocketDir(resolved, inboxDirs) {
|
|
1801
|
+
const call = _newCall()
|
|
1802
|
+
call.inboxDirs = inboxDirs
|
|
1803
|
+
return _hitsInboxSocketDir(resolved, call)
|
|
1804
|
+
},
|
|
1805
|
+
protectedRootVerdicts(resolved, { configDirFn, inboxDirs, resolveRootFn } = {}) {
|
|
1806
|
+
const call = _newCall()
|
|
1807
|
+
call.configDirFn = configDirFn
|
|
1808
|
+
call.inboxDirs = inboxDirs
|
|
1809
|
+
call.resolveRootFn = resolveRootFn
|
|
1810
|
+
return {
|
|
1811
|
+
inbox: _hitsInboxSocketDir(resolved, call),
|
|
1812
|
+
sessionsDir: _isSessionsDir(resolved, call),
|
|
1813
|
+
reaches: _searchReachesSessions(resolved, call),
|
|
1814
|
+
}
|
|
1815
|
+
},
|
|
1816
|
+
globAvoidsKeyFiles(glob) {
|
|
1817
|
+
return globAvoidsKeyFiles(glob)
|
|
1818
|
+
},
|
|
1819
|
+
searchReach(input, cwd, statFn) {
|
|
1820
|
+
return _searchReachToConfigRoot(input, cwd, statFn)
|
|
1821
|
+
},
|
|
455
1822
|
}
|