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