@mxalbert/context-mode 2.0.0
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/.claude-plugin/marketplace.json +33 -0
- package/.claude-plugin/plugin.json +31 -0
- package/.codex-plugin/hooks.json +65 -0
- package/.codex-plugin/mcp.json +13 -0
- package/.codex-plugin/plugin.json +31 -0
- package/.openclaw-plugin/index.ts +12 -0
- package/.openclaw-plugin/openclaw.plugin.json +38 -0
- package/.openclaw-plugin/package.json +28 -0
- package/LICENSE +94 -0
- package/README.md +1619 -0
- package/bin/statusline.mjs +378 -0
- package/build/adapters/antigravity/index.d.ts +51 -0
- package/build/adapters/antigravity/index.js +169 -0
- package/build/adapters/antigravity-cli/index.d.ts +51 -0
- package/build/adapters/antigravity-cli/index.js +342 -0
- package/build/adapters/base.d.ts +92 -0
- package/build/adapters/base.js +135 -0
- package/build/adapters/claude-code/config.d.ts +8 -0
- package/build/adapters/claude-code/config.js +8 -0
- package/build/adapters/claude-code/hooks.d.ts +106 -0
- package/build/adapters/claude-code/hooks.js +183 -0
- package/build/adapters/claude-code/index.d.ts +80 -0
- package/build/adapters/claude-code/index.js +569 -0
- package/build/adapters/claude-code-base.d.ts +49 -0
- package/build/adapters/claude-code-base.js +113 -0
- package/build/adapters/client-map.d.ts +10 -0
- package/build/adapters/client-map.js +42 -0
- package/build/adapters/codex/config.d.ts +8 -0
- package/build/adapters/codex/config.js +8 -0
- package/build/adapters/codex/hooks.d.ts +55 -0
- package/build/adapters/codex/hooks.js +64 -0
- package/build/adapters/codex/index.d.ts +87 -0
- package/build/adapters/codex/index.js +995 -0
- package/build/adapters/codex/paths.d.ts +1 -0
- package/build/adapters/codex/paths.js +12 -0
- package/build/adapters/codex/usage.d.ts +107 -0
- package/build/adapters/codex/usage.js +227 -0
- package/build/adapters/copilot-base.d.ts +94 -0
- package/build/adapters/copilot-base.js +297 -0
- package/build/adapters/copilot-cli/hooks.d.ts +33 -0
- package/build/adapters/copilot-cli/hooks.js +64 -0
- package/build/adapters/copilot-cli/index.d.ts +48 -0
- package/build/adapters/copilot-cli/index.js +341 -0
- package/build/adapters/cursor/config.d.ts +4 -0
- package/build/adapters/cursor/config.js +4 -0
- package/build/adapters/cursor/hooks.d.ts +55 -0
- package/build/adapters/cursor/hooks.js +82 -0
- package/build/adapters/cursor/index.d.ts +64 -0
- package/build/adapters/cursor/index.js +517 -0
- package/build/adapters/detect.d.ts +136 -0
- package/build/adapters/detect.js +623 -0
- package/build/adapters/gemini-cli/config.d.ts +8 -0
- package/build/adapters/gemini-cli/config.js +8 -0
- package/build/adapters/gemini-cli/hooks.d.ts +83 -0
- package/build/adapters/gemini-cli/hooks.js +115 -0
- package/build/adapters/gemini-cli/index.d.ts +80 -0
- package/build/adapters/gemini-cli/index.js +483 -0
- package/build/adapters/jetbrains-copilot/config.d.ts +8 -0
- package/build/adapters/jetbrains-copilot/config.js +8 -0
- package/build/adapters/jetbrains-copilot/hooks.d.ts +59 -0
- package/build/adapters/jetbrains-copilot/hooks.js +87 -0
- package/build/adapters/jetbrains-copilot/index.d.ts +31 -0
- package/build/adapters/jetbrains-copilot/index.js +131 -0
- package/build/adapters/kimi/config.d.ts +8 -0
- package/build/adapters/kimi/config.js +8 -0
- package/build/adapters/kimi/hooks.d.ts +28 -0
- package/build/adapters/kimi/hooks.js +34 -0
- package/build/adapters/kimi/index.d.ts +66 -0
- package/build/adapters/kimi/index.js +537 -0
- package/build/adapters/kimi/paths.d.ts +21 -0
- package/build/adapters/kimi/paths.js +52 -0
- package/build/adapters/kimi/usage.d.ts +82 -0
- package/build/adapters/kimi/usage.js +217 -0
- package/build/adapters/kiro/hooks.d.ts +61 -0
- package/build/adapters/kiro/hooks.js +94 -0
- package/build/adapters/kiro/index.d.ts +61 -0
- package/build/adapters/kiro/index.js +301 -0
- package/build/adapters/omp/index.d.ts +65 -0
- package/build/adapters/omp/index.js +182 -0
- package/build/adapters/omp/plugin.d.ts +81 -0
- package/build/adapters/omp/plugin.js +331 -0
- package/build/adapters/omp/usage.d.ts +49 -0
- package/build/adapters/omp/usage.js +110 -0
- package/build/adapters/openclaw/config.d.ts +8 -0
- package/build/adapters/openclaw/config.js +8 -0
- package/build/adapters/openclaw/hooks.d.ts +50 -0
- package/build/adapters/openclaw/hooks.js +61 -0
- package/build/adapters/openclaw/index.d.ts +74 -0
- package/build/adapters/openclaw/index.js +439 -0
- package/build/adapters/openclaw/mcp-tools.d.ts +54 -0
- package/build/adapters/openclaw/mcp-tools.js +207 -0
- package/build/adapters/openclaw/plugin.d.ts +141 -0
- package/build/adapters/openclaw/plugin.js +818 -0
- package/build/adapters/openclaw/session-db.d.ts +55 -0
- package/build/adapters/openclaw/session-db.js +88 -0
- package/build/adapters/openclaw/usage.d.ts +34 -0
- package/build/adapters/openclaw/usage.js +52 -0
- package/build/adapters/openclaw/workspace-router.d.ts +29 -0
- package/build/adapters/openclaw/workspace-router.js +64 -0
- package/build/adapters/opencode/config.d.ts +8 -0
- package/build/adapters/opencode/config.js +8 -0
- package/build/adapters/opencode/hooks.d.ts +38 -0
- package/build/adapters/opencode/hooks.js +50 -0
- package/build/adapters/opencode/index.d.ts +144 -0
- package/build/adapters/opencode/index.js +638 -0
- package/build/adapters/opencode/plugin.d.ts +249 -0
- package/build/adapters/opencode/plugin.js +1536 -0
- package/build/adapters/opencode/v2.d.ts +117 -0
- package/build/adapters/opencode/v2.js +224 -0
- package/build/adapters/opencode/zod3tov4.d.ts +1 -0
- package/build/adapters/opencode/zod3tov4.js +132 -0
- package/build/adapters/pi/extension.d.ts +81 -0
- package/build/adapters/pi/extension.js +861 -0
- package/build/adapters/pi/index.d.ts +57 -0
- package/build/adapters/pi/index.js +173 -0
- package/build/adapters/pi/mcp-bridge.d.ts +268 -0
- package/build/adapters/pi/mcp-bridge.js +894 -0
- package/build/adapters/qwen-code/hooks.d.ts +26 -0
- package/build/adapters/qwen-code/hooks.js +29 -0
- package/build/adapters/qwen-code/index.d.ts +40 -0
- package/build/adapters/qwen-code/index.js +361 -0
- package/build/adapters/qwen-code/usage.d.ts +90 -0
- package/build/adapters/qwen-code/usage.js +222 -0
- package/build/adapters/types.d.ts +360 -0
- package/build/adapters/types.js +118 -0
- package/build/adapters/vscode-copilot/config.d.ts +8 -0
- package/build/adapters/vscode-copilot/config.js +8 -0
- package/build/adapters/vscode-copilot/hooks.d.ts +71 -0
- package/build/adapters/vscode-copilot/hooks.js +98 -0
- package/build/adapters/vscode-copilot/index.d.ts +32 -0
- package/build/adapters/vscode-copilot/index.js +222 -0
- package/build/adapters/zed/index.d.ts +40 -0
- package/build/adapters/zed/index.js +163 -0
- package/build/cli.d.ts +34 -0
- package/build/cli.js +1828 -0
- package/build/db-base.d.ts +250 -0
- package/build/db-base.js +756 -0
- package/build/executor.d.ts +72 -0
- package/build/executor.js +678 -0
- package/build/exit-classify.d.ts +19 -0
- package/build/exit-classify.js +12 -0
- package/build/fetch/blocks.d.ts +145 -0
- package/build/fetch/blocks.js +244 -0
- package/build/fetch/extract.d.ts +68 -0
- package/build/fetch/extract.js +123 -0
- package/build/fetch/page-store.d.ts +66 -0
- package/build/fetch/page-store.js +174 -0
- package/build/fetch-cache.d.ts +13 -0
- package/build/fetch-cache.js +15 -0
- package/build/lifecycle.d.ts +124 -0
- package/build/lifecycle.js +278 -0
- package/build/package-identity.d.ts +26 -0
- package/build/package-identity.js +28 -0
- package/build/runPool.d.ts +36 -0
- package/build/runPool.js +51 -0
- package/build/runtime.d.ts +71 -0
- package/build/runtime.js +659 -0
- package/build/search/auto-memory.d.ts +47 -0
- package/build/search/auto-memory.js +170 -0
- package/build/search/ctx-search-schema.d.ts +90 -0
- package/build/search/ctx-search-schema.js +135 -0
- package/build/search/flood-guard.d.ts +57 -0
- package/build/search/flood-guard.js +80 -0
- package/build/search/unified.d.ts +56 -0
- package/build/search/unified.js +104 -0
- package/build/security.d.ts +206 -0
- package/build/security.js +780 -0
- package/build/server.d.ts +240 -0
- package/build/server.js +5034 -0
- package/build/session/analytics.d.ts +773 -0
- package/build/session/analytics.js +2420 -0
- package/build/session/db.d.ts +468 -0
- package/build/session/db.js +1330 -0
- package/build/session/error-classifier.d.ts +87 -0
- package/build/session/error-classifier.js +303 -0
- package/build/session/event-emit.d.ts +48 -0
- package/build/session/event-emit.js +101 -0
- package/build/session/extract.d.ts +333 -0
- package/build/session/extract.js +2688 -0
- package/build/session/model-prices.json +429 -0
- package/build/session/persist-tool-calls.d.ts +54 -0
- package/build/session/persist-tool-calls.js +105 -0
- package/build/session/pricing.d.ts +64 -0
- package/build/session/pricing.js +151 -0
- package/build/session/project-attribution.d.ts +73 -0
- package/build/session/project-attribution.js +245 -0
- package/build/session/purge.d.ts +138 -0
- package/build/session/purge.js +240 -0
- package/build/session/retrieval-marker.d.ts +39 -0
- package/build/session/retrieval-marker.js +65 -0
- package/build/session/snapshot.d.ts +46 -0
- package/build/session/snapshot.js +532 -0
- package/build/store-directory.d.ts +56 -0
- package/build/store-directory.js +254 -0
- package/build/store.d.ts +147 -0
- package/build/store.js +1714 -0
- package/build/truncate.d.ts +57 -0
- package/build/truncate.js +142 -0
- package/build/types.d.ts +117 -0
- package/build/types.js +20 -0
- package/build/util/claude-config.d.ts +32 -0
- package/build/util/claude-config.js +84 -0
- package/build/util/hook-config.d.ts +27 -0
- package/build/util/hook-config.js +76 -0
- package/build/util/jsonc.d.ts +14 -0
- package/build/util/jsonc.js +104 -0
- package/build/util/plugin-cache-integrity.d.ts +51 -0
- package/build/util/plugin-cache-integrity.js +146 -0
- package/build/util/project-dir.d.ts +149 -0
- package/build/util/project-dir.js +340 -0
- package/build/util/sibling-mcp.d.ts +79 -0
- package/build/util/sibling-mcp.js +181 -0
- package/cli.bundle.mjs +1495 -0
- package/configs/antigravity/GEMINI.md +68 -0
- package/configs/antigravity/mcp_config.json +7 -0
- package/configs/antigravity-cli/hooks/hooks.json +37 -0
- package/configs/antigravity-cli/hooks.json +37 -0
- package/configs/antigravity-cli/mcp_config.json +10 -0
- package/configs/antigravity-cli/plugin.json +14 -0
- package/configs/antigravity-cli/rules/context-mode.md +77 -0
- package/configs/antigravity-cli/skills/context-mode/SKILL.md +77 -0
- package/configs/claude-code/CLAUDE.md +91 -0
- package/configs/codex/AGENTS.md +99 -0
- package/configs/codex/config.toml +8 -0
- package/configs/codex/hooks.json +47 -0
- package/configs/copilot-cli/.github/plugin/plugin.json +23 -0
- package/configs/copilot-cli/.mcp.json +12 -0
- package/configs/copilot-cli/README.md +47 -0
- package/configs/copilot-cli/hooks.json +41 -0
- package/configs/copilot-cli/skills/context-mode/SKILL.md +38 -0
- package/configs/cursor/context-mode.mdc +76 -0
- package/configs/cursor/hooks.json +21 -0
- package/configs/cursor/mcp.json +7 -0
- package/configs/gemini-cli/GEMINI.md +88 -0
- package/configs/gemini-cli/mcp.json +7 -0
- package/configs/gemini-cli/settings.json +60 -0
- package/configs/jetbrains-copilot/copilot-instructions.md +80 -0
- package/configs/jetbrains-copilot/hooks.json +16 -0
- package/configs/jetbrains-copilot/mcp.json +7 -0
- package/configs/kilo/AGENTS.md +84 -0
- package/configs/kilo/kilo.json +6 -0
- package/configs/kimi/hooks.json +54 -0
- package/configs/kiro/KIRO.md +84 -0
- package/configs/kiro/agent.json +18 -0
- package/configs/kiro/mcp.json +7 -0
- package/configs/omp/SYSTEM.md +85 -0
- package/configs/omp/mcp.json +7 -0
- package/configs/openclaw/AGENTS.md +87 -0
- package/configs/openclaw/openclaw.json +13 -0
- package/configs/opencode/AGENTS.md +84 -0
- package/configs/opencode/opencode.json +6 -0
- package/configs/pi/AGENTS.md +3 -0
- package/configs/qwen-code/QWEN.md +91 -0
- package/configs/vscode-copilot/copilot-instructions.md +80 -0
- package/configs/vscode-copilot/hooks.json +16 -0
- package/configs/vscode-copilot/mcp.json +7 -0
- package/configs/zed/AGENTS.md +68 -0
- package/hooks/antigravity-cli/payload.mjs +98 -0
- package/hooks/antigravity-cli/posttooluse.mjs +138 -0
- package/hooks/antigravity-cli/pretooluse.mjs +78 -0
- package/hooks/antigravity-cli/stop.mjs +58 -0
- package/hooks/auto-injection.mjs +102 -0
- package/hooks/cache-heal-utils.mjs +379 -0
- package/hooks/codex/platform.mjs +1 -0
- package/hooks/codex/posttooluse.mjs +66 -0
- package/hooks/codex/precompact.mjs +70 -0
- package/hooks/codex/pretooluse.mjs +42 -0
- package/hooks/codex/sessionstart.mjs +121 -0
- package/hooks/codex/stop.mjs +138 -0
- package/hooks/codex/userpromptsubmit.mjs +75 -0
- package/hooks/copilot-cli/posttooluse.mjs +79 -0
- package/hooks/copilot-cli/precompact.mjs +66 -0
- package/hooks/copilot-cli/pretooluse.mjs +41 -0
- package/hooks/copilot-cli/sessionstart.mjs +121 -0
- package/hooks/copilot-cli/stop.mjs +59 -0
- package/hooks/copilot-cli/userpromptsubmit.mjs +77 -0
- package/hooks/core/codex-caps.mjs +112 -0
- package/hooks/core/formatters.mjs +356 -0
- package/hooks/core/mcp-ready.mjs +109 -0
- package/hooks/core/platform-detect.mjs +49 -0
- package/hooks/core/routing.mjs +1050 -0
- package/hooks/core/stdin.mjs +90 -0
- package/hooks/core/tool-naming.mjs +57 -0
- package/hooks/cursor/afteragentresponse.mjs +74 -0
- package/hooks/cursor/hooks.json +31 -0
- package/hooks/cursor/posttooluse.mjs +72 -0
- package/hooks/cursor/pretooluse.mjs +26 -0
- package/hooks/cursor/sessionstart.mjs +97 -0
- package/hooks/cursor/stop.mjs +48 -0
- package/hooks/ensure-deps.mjs +254 -0
- package/hooks/formatters/claude-code.mjs +113 -0
- package/hooks/formatters/cursor.mjs +37 -0
- package/hooks/formatters/gemini-cli.mjs +55 -0
- package/hooks/formatters/vscode-copilot.mjs +55 -0
- package/hooks/gemini-cli/aftermodel.mjs +70 -0
- package/hooks/gemini-cli/aftertool.mjs +61 -0
- package/hooks/gemini-cli/beforeagent.mjs +99 -0
- package/hooks/gemini-cli/beforetool.mjs +27 -0
- package/hooks/gemini-cli/precompress.mjs +55 -0
- package/hooks/gemini-cli/sessionstart.mjs +137 -0
- package/hooks/heal-partial-install.mjs +712 -0
- package/hooks/hooks.json +143 -0
- package/hooks/jetbrains-copilot/posttooluse.mjs +61 -0
- package/hooks/jetbrains-copilot/precompact.mjs +55 -0
- package/hooks/jetbrains-copilot/pretooluse.mjs +27 -0
- package/hooks/jetbrains-copilot/sessionstart.mjs +124 -0
- package/hooks/kimi/platform.mjs +1 -0
- package/hooks/kimi/posttooluse.mjs +72 -0
- package/hooks/kimi/precompact.mjs +80 -0
- package/hooks/kimi/pretooluse.mjs +42 -0
- package/hooks/kimi/sessionend.mjs +61 -0
- package/hooks/kimi/sessionstart.mjs +113 -0
- package/hooks/kimi/stop.mjs +132 -0
- package/hooks/kimi/userpromptsubmit.mjs +90 -0
- package/hooks/kiro/agentspawn.mjs +97 -0
- package/hooks/kiro/posttooluse.mjs +51 -0
- package/hooks/kiro/pretooluse.mjs +64 -0
- package/hooks/kiro/userpromptsubmit.mjs +88 -0
- package/hooks/normalize-hooks.mjs +323 -0
- package/hooks/platform-bridge.mjs +340 -0
- package/hooks/posttooluse.mjs +225 -0
- package/hooks/precompact.mjs +100 -0
- package/hooks/pretooluse.mjs +227 -0
- package/hooks/qwen-code/platform.mjs +1 -0
- package/hooks/qwen-code/stop.mjs +168 -0
- package/hooks/routing-block.mjs +105 -0
- package/hooks/run-hook.mjs +95 -0
- package/hooks/security.bundle.mjs +2 -0
- package/hooks/session-attribution.bundle.mjs +1 -0
- package/hooks/session-db.bundle.mjs +145 -0
- package/hooks/session-directive.mjs +520 -0
- package/hooks/session-extract.bundle.mjs +3 -0
- package/hooks/session-helpers.mjs +428 -0
- package/hooks/session-loaders.mjs +448 -0
- package/hooks/session-snapshot.bundle.mjs +32 -0
- package/hooks/sessionstart.mjs +464 -0
- package/hooks/stop.mjs +82 -0
- package/hooks/suppress-stderr.mjs +25 -0
- package/hooks/userpromptsubmit.mjs +108 -0
- package/hooks/vscode-copilot/posttooluse.mjs +61 -0
- package/hooks/vscode-copilot/precompact.mjs +55 -0
- package/hooks/vscode-copilot/pretooluse.mjs +27 -0
- package/hooks/vscode-copilot/sessionstart.mjs +129 -0
- package/openclaw.plugin.json +38 -0
- package/package.json +132 -0
- package/scripts/heal-better-sqlite3.mjs +430 -0
- package/scripts/heal-installed-plugins.mjs +635 -0
- package/scripts/plugin-cache-integrity.mjs +248 -0
- package/scripts/postinstall.mjs +397 -0
- package/server.bundle.mjs +1421 -0
- package/server.js +5 -0
- package/skills/.ignore +7 -0
- package/skills/context-mode/SKILL.md +300 -0
- package/skills/context-mode/references/anti-patterns.md +283 -0
- package/skills/context-mode/references/patterns-javascript.md +298 -0
- package/skills/context-mode/references/patterns-python.md +304 -0
- package/skills/context-mode/references/patterns-shell.md +277 -0
- package/skills/ctx-doctor/SKILL.md +22 -0
- package/skills/ctx-index/SKILL.md +46 -0
- package/skills/ctx-insight/SKILL.md +24 -0
- package/skills/ctx-purge/SKILL.md +49 -0
- package/skills/ctx-search/SKILL.md +35 -0
- package/skills/ctx-stats/SKILL.md +26 -0
- package/skills/ctx-upgrade/SKILL.md +31 -0
- package/start.mjs +616 -0
|
@@ -0,0 +1,780 @@
|
|
|
1
|
+
import { readFileSync, realpathSync } from "node:fs";
|
|
2
|
+
import { relative, resolve, sep } from "node:path";
|
|
3
|
+
import { resolveAdapterGlobalSettingsPaths } from "./util/claude-config.js";
|
|
4
|
+
// ==============================================================================
|
|
5
|
+
// Pattern Parsing
|
|
6
|
+
// ==============================================================================
|
|
7
|
+
/**
|
|
8
|
+
* Extract the glob from a Bash permission pattern.
|
|
9
|
+
* "Bash(sudo *)" returns "sudo *", "Read(.env)" returns null.
|
|
10
|
+
*/
|
|
11
|
+
export function parseBashPattern(pattern) {
|
|
12
|
+
// .+ is greedy: for "Bash(echo (foo))" it captures "echo (foo)"
|
|
13
|
+
// because $ forces the final \) to match only the last paren.
|
|
14
|
+
const match = pattern.match(/^Bash\((.+)\)$/);
|
|
15
|
+
return match ? match[1] : null;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Parse any tool permission pattern like "ToolName(glob)".
|
|
19
|
+
* Returns { tool, glob } or null if not a valid pattern.
|
|
20
|
+
*/
|
|
21
|
+
export function parseToolPattern(pattern) {
|
|
22
|
+
// .+ is greedy: for "Read(some(path))" it captures "some(path)"
|
|
23
|
+
// because $ forces the final \) to match only the last paren.
|
|
24
|
+
const match = pattern.match(/^(\w+)\((.+)\)$/);
|
|
25
|
+
return match ? { tool: match[1], glob: match[2] } : null;
|
|
26
|
+
}
|
|
27
|
+
// ==============================================================================
|
|
28
|
+
// Glob-to-Regex Conversion
|
|
29
|
+
// ==============================================================================
|
|
30
|
+
/** Escape all regex special characters (including *). */
|
|
31
|
+
function escapeRegex(str) {
|
|
32
|
+
return str.replace(/[.*+?^${}()|[\]\\\/\-]/g, "\\$&");
|
|
33
|
+
}
|
|
34
|
+
/** Escape regex specials except *, then convert * to .* */
|
|
35
|
+
function convertGlobPart(glob) {
|
|
36
|
+
return glob
|
|
37
|
+
.replace(/[.+?^${}()|[\]\\\/\-]/g, "\\$&")
|
|
38
|
+
.replace(/\*/g, ".*");
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Convert a Bash permission glob to a regex.
|
|
42
|
+
*
|
|
43
|
+
* Two formats:
|
|
44
|
+
* - Colon: "tree:*" becomes /^tree(\s.*)?$/ (command with optional args)
|
|
45
|
+
* - Space: "sudo *" becomes /^sudo .*$/ (literal glob match)
|
|
46
|
+
*/
|
|
47
|
+
export function globToRegex(glob, caseInsensitive = false) {
|
|
48
|
+
let regexStr;
|
|
49
|
+
const colonIdx = glob.indexOf(":");
|
|
50
|
+
if (colonIdx !== -1) {
|
|
51
|
+
// Colon format: "command:argsGlob"
|
|
52
|
+
const command = glob.slice(0, colonIdx);
|
|
53
|
+
const argsGlob = glob.slice(colonIdx + 1);
|
|
54
|
+
const escapedCmd = escapeRegex(command);
|
|
55
|
+
const argsRegex = convertGlobPart(argsGlob);
|
|
56
|
+
// Match command alone OR command + space + args
|
|
57
|
+
regexStr = `^${escapedCmd}(\\s${argsRegex})?$`;
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
// Plain glob: "sudo *", "ls*", "* commit *"
|
|
61
|
+
regexStr = `^${convertGlobPart(glob)}$`;
|
|
62
|
+
}
|
|
63
|
+
return new RegExp(regexStr, caseInsensitive ? "i" : "");
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Convert a file path glob to a regex.
|
|
67
|
+
*
|
|
68
|
+
* Unlike `globToRegex` (which handles command patterns with colon and
|
|
69
|
+
* space semantics), this handles file path globs where:
|
|
70
|
+
* - `**` matches any number of path segments (including zero)
|
|
71
|
+
* - `*` matches anything except path separators
|
|
72
|
+
* - Paths are matched with forward slashes (callers normalize first)
|
|
73
|
+
*/
|
|
74
|
+
export function fileGlobToRegex(glob, caseInsensitive = false) {
|
|
75
|
+
let regexStr = "";
|
|
76
|
+
let i = 0;
|
|
77
|
+
while (i < glob.length) {
|
|
78
|
+
// Handle ** (globstar): match any number of directory segments
|
|
79
|
+
if (glob[i] === "*" && glob[i + 1] === "*") {
|
|
80
|
+
// **/ at the start or after a slash means "zero or more directories"
|
|
81
|
+
if (i + 2 < glob.length && glob[i + 2] === "/") {
|
|
82
|
+
regexStr += "(.*/)?";
|
|
83
|
+
i += 3; // skip "*" "*" "/"
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
// Trailing ** matches everything
|
|
87
|
+
regexStr += ".*";
|
|
88
|
+
i += 2;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
else if (glob[i] === "*") {
|
|
92
|
+
// Single * matches anything except /
|
|
93
|
+
regexStr += "[^/]*";
|
|
94
|
+
i++;
|
|
95
|
+
}
|
|
96
|
+
else if (glob[i] === "?") {
|
|
97
|
+
regexStr += "[^/]";
|
|
98
|
+
i++;
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
// Escape regex-special characters
|
|
102
|
+
regexStr += glob[i].replace(/[.+^${}()|[\]\\\/\-]/g, "\\$&");
|
|
103
|
+
i++;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return new RegExp(`^${regexStr}$`, caseInsensitive ? "i" : "");
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Check if a command matches any Bash pattern in the list.
|
|
110
|
+
* Returns the matching pattern string, or null.
|
|
111
|
+
*/
|
|
112
|
+
export function matchesAnyPattern(command, patterns, caseInsensitive = false) {
|
|
113
|
+
for (const pattern of patterns) {
|
|
114
|
+
const glob = parseBashPattern(pattern);
|
|
115
|
+
if (!glob)
|
|
116
|
+
continue;
|
|
117
|
+
if (globToRegex(glob, caseInsensitive).test(command))
|
|
118
|
+
return pattern;
|
|
119
|
+
}
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
// ==============================================================================
|
|
123
|
+
// Chained Command Splitting & Subshell Extraction
|
|
124
|
+
// ==============================================================================
|
|
125
|
+
function isEscaped(command, index) {
|
|
126
|
+
let backslashes = 0;
|
|
127
|
+
for (let i = index - 1; i >= 0 && command[i] === "\\"; i--) {
|
|
128
|
+
backslashes++;
|
|
129
|
+
}
|
|
130
|
+
return backslashes % 2 === 1;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Split a shell command on chain operators (&&, ||, ;, |, \n, \r, &) while
|
|
134
|
+
* respecting single/double quotes, backticks, subshells, and escape backslashes.
|
|
135
|
+
*
|
|
136
|
+
* "echo hello && sudo rm -rf /" → ["echo hello", "sudo rm -rf /"]
|
|
137
|
+
*
|
|
138
|
+
* This prevents bypassing deny patterns by prepending innocent commands.
|
|
139
|
+
*/
|
|
140
|
+
export function splitChainedCommands(command) {
|
|
141
|
+
const parts = [];
|
|
142
|
+
let current = "";
|
|
143
|
+
let inSingle = false;
|
|
144
|
+
let inDouble = false;
|
|
145
|
+
let inBacktick = false;
|
|
146
|
+
let dollarParenDepth = 0;
|
|
147
|
+
for (let i = 0; i < command.length; i++) {
|
|
148
|
+
const ch = command[i];
|
|
149
|
+
const escaped = isEscaped(command, i);
|
|
150
|
+
if (ch === "'" && !inDouble && !inBacktick && !escaped) {
|
|
151
|
+
inSingle = !inSingle;
|
|
152
|
+
current += ch;
|
|
153
|
+
}
|
|
154
|
+
else if (ch === '"' && !inSingle && !inBacktick && !escaped) {
|
|
155
|
+
inDouble = !inDouble;
|
|
156
|
+
current += ch;
|
|
157
|
+
}
|
|
158
|
+
else if (ch === "`" && !inSingle && !inDouble && !escaped) {
|
|
159
|
+
inBacktick = !inBacktick;
|
|
160
|
+
current += ch;
|
|
161
|
+
}
|
|
162
|
+
else if (!inSingle && !inDouble && !inBacktick) {
|
|
163
|
+
if (ch === "$" && command[i + 1] === "(" && !escaped) {
|
|
164
|
+
dollarParenDepth++;
|
|
165
|
+
current += ch + command[i + 1];
|
|
166
|
+
i++;
|
|
167
|
+
}
|
|
168
|
+
else if (dollarParenDepth > 0 && ch === "(" && !escaped) {
|
|
169
|
+
dollarParenDepth++;
|
|
170
|
+
current += ch;
|
|
171
|
+
}
|
|
172
|
+
else if (ch === ")" && dollarParenDepth > 0 && !escaped) {
|
|
173
|
+
dollarParenDepth--;
|
|
174
|
+
current += ch;
|
|
175
|
+
}
|
|
176
|
+
else if (dollarParenDepth === 0 &&
|
|
177
|
+
(ch === ";" || ch === "\n" || ch === "\r") &&
|
|
178
|
+
!escaped) {
|
|
179
|
+
parts.push(current.trim());
|
|
180
|
+
current = "";
|
|
181
|
+
}
|
|
182
|
+
else if (dollarParenDepth === 0 && ch === "|" && command[i + 1] === "|") {
|
|
183
|
+
parts.push(current.trim());
|
|
184
|
+
current = "";
|
|
185
|
+
i++; // skip second |
|
|
186
|
+
}
|
|
187
|
+
else if (dollarParenDepth === 0 && ch === "&" && command[i + 1] === "&") {
|
|
188
|
+
parts.push(current.trim());
|
|
189
|
+
current = "";
|
|
190
|
+
i++; // skip second &
|
|
191
|
+
}
|
|
192
|
+
else if (dollarParenDepth === 0 && ch === "&" && !escaped) {
|
|
193
|
+
parts.push(current.trim());
|
|
194
|
+
current = "";
|
|
195
|
+
}
|
|
196
|
+
else if (dollarParenDepth === 0 && ch === "|") {
|
|
197
|
+
// Single pipe — left side is a command too
|
|
198
|
+
parts.push(current.trim());
|
|
199
|
+
current = "";
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
current += ch;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
else {
|
|
206
|
+
current += ch;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
if (current.trim())
|
|
210
|
+
parts.push(current.trim());
|
|
211
|
+
return parts.filter((p) => p.length > 0);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Recursively extract all nested subshell commands from `$()` and `` `...` ``.
|
|
215
|
+
* Handles escaping and quote contexts to ensure correct command boundary detection.
|
|
216
|
+
*/
|
|
217
|
+
export function extractSubshellCommands(command) {
|
|
218
|
+
const subshells = [];
|
|
219
|
+
let inSingle = false;
|
|
220
|
+
let inDouble = false;
|
|
221
|
+
let backtickStart = -1;
|
|
222
|
+
const dollarParenStarts = [];
|
|
223
|
+
const dollarParenDepths = [];
|
|
224
|
+
let parenDepth = 0;
|
|
225
|
+
for (let i = 0; i < command.length; i++) {
|
|
226
|
+
const ch = command[i];
|
|
227
|
+
const escaped = isEscaped(command, i);
|
|
228
|
+
if (ch === "'" && !inDouble && backtickStart === -1 && !escaped) {
|
|
229
|
+
inSingle = !inSingle;
|
|
230
|
+
}
|
|
231
|
+
else if (ch === '"' && !inSingle && backtickStart === -1 && !escaped) {
|
|
232
|
+
inDouble = !inDouble;
|
|
233
|
+
}
|
|
234
|
+
else if (ch === "`" && !inSingle && !inDouble && !escaped) {
|
|
235
|
+
if (backtickStart === -1) {
|
|
236
|
+
backtickStart = i + 1;
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
const sub = command.slice(backtickStart, i);
|
|
240
|
+
subshells.push(sub);
|
|
241
|
+
subshells.push(...extractSubshellCommands(sub));
|
|
242
|
+
backtickStart = -1;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
else if (!inSingle && backtickStart === -1) {
|
|
246
|
+
if (ch === "$" && command[i + 1] === "(" && !escaped) {
|
|
247
|
+
if (command[i + 2] === "(") {
|
|
248
|
+
// Arithmetic expansion is not command execution, but nested command
|
|
249
|
+
// substitutions inside it still get discovered by the scanner.
|
|
250
|
+
parenDepth += 2;
|
|
251
|
+
i += 2; // skip '(('
|
|
252
|
+
}
|
|
253
|
+
else {
|
|
254
|
+
dollarParenStarts.push(i + 2);
|
|
255
|
+
dollarParenDepths.push(parenDepth);
|
|
256
|
+
parenDepth++;
|
|
257
|
+
i++; // skip '('
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
else if (ch === "(" && !escaped) {
|
|
261
|
+
parenDepth++;
|
|
262
|
+
}
|
|
263
|
+
else if (ch === ")" && !escaped) {
|
|
264
|
+
if (parenDepth > 0) {
|
|
265
|
+
parenDepth--;
|
|
266
|
+
}
|
|
267
|
+
if (dollarParenDepths.length > 0 &&
|
|
268
|
+
parenDepth === dollarParenDepths[dollarParenDepths.length - 1]) {
|
|
269
|
+
dollarParenDepths.pop();
|
|
270
|
+
const start = dollarParenStarts.pop();
|
|
271
|
+
const sub = command.slice(start, i);
|
|
272
|
+
subshells.push(sub);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return subshells;
|
|
278
|
+
}
|
|
279
|
+
function collectCommandElements(command) {
|
|
280
|
+
const elements = [];
|
|
281
|
+
const segments = splitChainedCommands(command);
|
|
282
|
+
for (const segment of segments) {
|
|
283
|
+
elements.push(segment);
|
|
284
|
+
for (const subshell of extractSubshellCommands(segment)) {
|
|
285
|
+
elements.push(...collectCommandElements(subshell));
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return elements;
|
|
289
|
+
}
|
|
290
|
+
// ==============================================================================
|
|
291
|
+
// Settings Reader
|
|
292
|
+
// ==============================================================================
|
|
293
|
+
/** Read one settings file and return a SecurityPolicy with only Bash patterns. */
|
|
294
|
+
function readSingleSettings(path) {
|
|
295
|
+
let raw;
|
|
296
|
+
try {
|
|
297
|
+
raw = readFileSync(path, "utf-8");
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
let parsed;
|
|
303
|
+
try {
|
|
304
|
+
parsed = JSON.parse(raw);
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
const perms = parsed?.permissions;
|
|
310
|
+
if (!perms || typeof perms !== "object")
|
|
311
|
+
return null;
|
|
312
|
+
const filterBash = (arr) => {
|
|
313
|
+
if (!Array.isArray(arr))
|
|
314
|
+
return [];
|
|
315
|
+
return arr.filter((p) => typeof p === "string" && parseBashPattern(p) !== null);
|
|
316
|
+
};
|
|
317
|
+
return {
|
|
318
|
+
allow: filterBash(perms.allow),
|
|
319
|
+
deny: filterBash(perms.deny),
|
|
320
|
+
ask: filterBash(perms.ask),
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Read Bash permission policies from up to 3 settings files.
|
|
325
|
+
*
|
|
326
|
+
* Returns policies in precedence order (most local first):
|
|
327
|
+
* 1. .claude/settings.local.json (project-local)
|
|
328
|
+
* 2. .claude/settings.json (project-shared)
|
|
329
|
+
* 3. ~/.claude/settings.json (global)
|
|
330
|
+
*
|
|
331
|
+
* Missing or invalid files are silently skipped.
|
|
332
|
+
*/
|
|
333
|
+
export function readBashPolicies(projectDir, globalSettingsPath) {
|
|
334
|
+
const policies = [];
|
|
335
|
+
if (projectDir) {
|
|
336
|
+
const localPath = resolve(projectDir, ".claude", "settings.local.json");
|
|
337
|
+
const localPolicy = readSingleSettings(localPath);
|
|
338
|
+
if (localPolicy)
|
|
339
|
+
policies.push(localPolicy);
|
|
340
|
+
const sharedPath = resolve(projectDir, ".claude", "settings.json");
|
|
341
|
+
const sharedPolicy = readSingleSettings(sharedPath);
|
|
342
|
+
if (sharedPolicy)
|
|
343
|
+
policies.push(sharedPolicy);
|
|
344
|
+
}
|
|
345
|
+
// Issue #451 round-3: read settings from EVERY adapter-specific global path
|
|
346
|
+
// PLUS the claude global (defense in depth). When the caller passes an
|
|
347
|
+
// explicit globalSettingsPath we honor it verbatim (back-compat with tests
|
|
348
|
+
// and callers that already know which file to read).
|
|
349
|
+
const globalPaths = globalSettingsPath !== undefined
|
|
350
|
+
? [globalSettingsPath]
|
|
351
|
+
: resolveAdapterGlobalSettingsPaths();
|
|
352
|
+
for (const globalPath of globalPaths) {
|
|
353
|
+
const globalPolicy = readSingleSettings(globalPath);
|
|
354
|
+
if (globalPolicy)
|
|
355
|
+
policies.push(globalPolicy);
|
|
356
|
+
}
|
|
357
|
+
return policies;
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Read deny patterns for a specific tool from settings files.
|
|
361
|
+
*
|
|
362
|
+
* Reads the same 3-tier settings as `readBashPolicies`, but extracts
|
|
363
|
+
* only deny globs for the given tool. Used for Read and Grep enforcement
|
|
364
|
+
* — checks if file paths should be blocked by deny patterns.
|
|
365
|
+
*
|
|
366
|
+
* Returns an array of arrays (one per settings file, in precedence order).
|
|
367
|
+
* Each inner array contains the extracted glob strings.
|
|
368
|
+
*/
|
|
369
|
+
export function readToolDenyPatterns(toolName, projectDir, globalSettingsPath) {
|
|
370
|
+
return readToolPermissionPatterns(toolName, "deny", projectDir, globalSettingsPath);
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Read `permissions.{deny|allow}` globs for a tool from every settings file in
|
|
374
|
+
* precedence order (project local → project shared → adapter globals).
|
|
375
|
+
*
|
|
376
|
+
* Generalizes the original deny-only reader so the project-boundary guard
|
|
377
|
+
* (#852) can consult the SAME `permissions.allow` rules the user already
|
|
378
|
+
* maintains for the host's `Read` tool — instead of inventing a context-mode-
|
|
379
|
+
* specific opt-out env that would rot into dead code. A user who legitimately
|
|
380
|
+
* needs an out-of-project read expresses it once, in the host config, e.g.
|
|
381
|
+
* `"permissions": { "allow": ["Read(/var/log/**)"] }`, and both the host and
|
|
382
|
+
* context-mode honor it.
|
|
383
|
+
*/
|
|
384
|
+
export function readToolPermissionPatterns(toolName, kind, projectDir, globalSettingsPath) {
|
|
385
|
+
const result = [];
|
|
386
|
+
const extractGlobs = (path) => {
|
|
387
|
+
let raw;
|
|
388
|
+
try {
|
|
389
|
+
raw = readFileSync(path, "utf-8");
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
return null;
|
|
393
|
+
}
|
|
394
|
+
let parsed;
|
|
395
|
+
try {
|
|
396
|
+
parsed = JSON.parse(raw);
|
|
397
|
+
}
|
|
398
|
+
catch {
|
|
399
|
+
return null;
|
|
400
|
+
}
|
|
401
|
+
const entries = parsed?.permissions?.[kind];
|
|
402
|
+
if (!Array.isArray(entries))
|
|
403
|
+
return [];
|
|
404
|
+
const globs = [];
|
|
405
|
+
for (const entry of entries) {
|
|
406
|
+
if (typeof entry !== "string")
|
|
407
|
+
continue;
|
|
408
|
+
const tp = parseToolPattern(entry);
|
|
409
|
+
if (tp && tp.tool === toolName) {
|
|
410
|
+
globs.push(tp.glob);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
return globs;
|
|
414
|
+
};
|
|
415
|
+
if (projectDir) {
|
|
416
|
+
const localGlobs = extractGlobs(resolve(projectDir, ".claude", "settings.local.json"));
|
|
417
|
+
if (localGlobs !== null)
|
|
418
|
+
result.push(localGlobs);
|
|
419
|
+
const sharedGlobs = extractGlobs(resolve(projectDir, ".claude", "settings.json"));
|
|
420
|
+
if (sharedGlobs !== null)
|
|
421
|
+
result.push(sharedGlobs);
|
|
422
|
+
}
|
|
423
|
+
// Issue #451 round-3: union over every adapter-specific global path PLUS
|
|
424
|
+
// claude global. Each settings file contributes its own globs array entry
|
|
425
|
+
// so the precedence ordering downstream remains per-file rather than
|
|
426
|
+
// collapsed.
|
|
427
|
+
const globalPaths = globalSettingsPath !== undefined
|
|
428
|
+
? [globalSettingsPath]
|
|
429
|
+
: resolveAdapterGlobalSettingsPaths();
|
|
430
|
+
for (const globalPath of globalPaths) {
|
|
431
|
+
const globalGlobs = extractGlobs(globalPath);
|
|
432
|
+
if (globalGlobs !== null)
|
|
433
|
+
result.push(globalGlobs);
|
|
434
|
+
}
|
|
435
|
+
return result;
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Evaluate a command against policies in precedence order.
|
|
439
|
+
*
|
|
440
|
+
* Splits chained commands (&&, ||, ;, |) and checks each segment
|
|
441
|
+
* against deny patterns — prevents bypassing deny by prepending
|
|
442
|
+
* innocent commands like "echo ok && sudo rm -rf /".
|
|
443
|
+
*
|
|
444
|
+
* Within each policy: deny > ask > allow (most restrictive wins).
|
|
445
|
+
* First definitive match across policies wins.
|
|
446
|
+
* Default (no match in any policy): "ask".
|
|
447
|
+
*/
|
|
448
|
+
export function evaluateCommand(command, policies, caseInsensitive = process.platform === "win32" || process.platform === "darwin") {
|
|
449
|
+
// Extract all main segments and nested subshell commands
|
|
450
|
+
const allCommands = collectCommandElements(command);
|
|
451
|
+
// 1. Deny check: If ANY segment or subshell command is denied, block the entire command
|
|
452
|
+
for (const cmdElement of allCommands) {
|
|
453
|
+
for (const policy of policies) {
|
|
454
|
+
const denyMatch = matchesAnyPattern(cmdElement, policy.deny, caseInsensitive);
|
|
455
|
+
if (denyMatch)
|
|
456
|
+
return { decision: "deny", matchedPattern: denyMatch };
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
// 2. Allow/Ask check: Evaluate segment-by-segment in precedence order.
|
|
460
|
+
// The command is allowed if and only if EVERY segment and subshell is explicitly allowed.
|
|
461
|
+
// If any element matches an ask pattern or matches no allow pattern, it defaults to ask.
|
|
462
|
+
for (const policy of policies) {
|
|
463
|
+
let allAllowed = true;
|
|
464
|
+
let anyAsk = false;
|
|
465
|
+
let matchedAskPattern;
|
|
466
|
+
let matchedAllowPattern;
|
|
467
|
+
for (const cmdElement of allCommands) {
|
|
468
|
+
const askMatch = matchesAnyPattern(cmdElement, policy.ask, caseInsensitive);
|
|
469
|
+
if (askMatch) {
|
|
470
|
+
anyAsk = true;
|
|
471
|
+
matchedAskPattern = askMatch;
|
|
472
|
+
break; // Ask wins immediately within this policy
|
|
473
|
+
}
|
|
474
|
+
const allowMatch = matchesAnyPattern(cmdElement, policy.allow, caseInsensitive);
|
|
475
|
+
if (!allowMatch) {
|
|
476
|
+
allAllowed = false;
|
|
477
|
+
}
|
|
478
|
+
else {
|
|
479
|
+
matchedAllowPattern = allowMatch;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
if (anyAsk) {
|
|
483
|
+
return { decision: "ask", matchedPattern: matchedAskPattern };
|
|
484
|
+
}
|
|
485
|
+
if (allAllowed && allCommands.length > 0) {
|
|
486
|
+
return { decision: "allow", matchedPattern: matchedAllowPattern };
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
return { decision: "ask" };
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Server-side variant: only enforce deny patterns.
|
|
493
|
+
*
|
|
494
|
+
* The server has no UI for "ask" prompts, so allow/ask patterns are
|
|
495
|
+
* irrelevant. Returns "deny" if any deny pattern matches, otherwise "allow".
|
|
496
|
+
*
|
|
497
|
+
* Also splits chained commands and nested subshells to prevent bypass.
|
|
498
|
+
*/
|
|
499
|
+
export function evaluateCommandDenyOnly(command, policies, caseInsensitive = process.platform === "win32" || process.platform === "darwin") {
|
|
500
|
+
const allCommands = collectCommandElements(command);
|
|
501
|
+
for (const cmdElement of allCommands) {
|
|
502
|
+
for (const policy of policies) {
|
|
503
|
+
const denyMatch = matchesAnyPattern(cmdElement, policy.deny, caseInsensitive);
|
|
504
|
+
if (denyMatch)
|
|
505
|
+
return { decision: "deny", matchedPattern: denyMatch };
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
return { decision: "allow" };
|
|
509
|
+
}
|
|
510
|
+
// ==============================================================================
|
|
511
|
+
// File Path Evaluation
|
|
512
|
+
// ==============================================================================
|
|
513
|
+
/**
|
|
514
|
+
* Check if a file path should be denied based on deny globs.
|
|
515
|
+
*
|
|
516
|
+
* Normalizes backslashes to forward slashes before matching so that
|
|
517
|
+
* Windows paths work with Unix-style glob patterns.
|
|
518
|
+
*
|
|
519
|
+
* When `projectRoot` is supplied, the path is also matched in its
|
|
520
|
+
* fully-resolved absolute form **and** — when the file exists — in
|
|
521
|
+
* its canonical form (`fs.realpathSync`). This prevents two classes
|
|
522
|
+
* of bypass:
|
|
523
|
+
*
|
|
524
|
+
* 1. `..` traversal: a relative path like `../../.ssh/id_rsa` no
|
|
525
|
+
* longer evades absolute-path deny rules.
|
|
526
|
+
* 2. Symlink escape: a project-local path whose realpath points
|
|
527
|
+
* outside the project (e.g. `safe.log -> ~/.ssh/id_rsa`) no
|
|
528
|
+
* longer evades absolute-path deny rules.
|
|
529
|
+
*
|
|
530
|
+
* realpath is best-effort: if the file does not exist yet (ENOENT)
|
|
531
|
+
* or the syscall fails for any reason, the lexical resolved form is
|
|
532
|
+
* still checked. This keeps the function usable for paths that will
|
|
533
|
+
* be created during execution.
|
|
534
|
+
*/
|
|
535
|
+
export function evaluateFilePath(filePath, denyGlobs, caseInsensitive = process.platform === "win32" || process.platform === "darwin", projectRoot) {
|
|
536
|
+
const toForward = (path) => path.replace(/\\/g, "/");
|
|
537
|
+
// Match against the raw input, the lexically-resolved absolute path,
|
|
538
|
+
// and the canonical (symlink-resolved) path when the file exists.
|
|
539
|
+
// Deduplicated so absolute inputs and paths that don't cross symlinks
|
|
540
|
+
// don't pay the matching cost multiple times.
|
|
541
|
+
const candidates = new Set();
|
|
542
|
+
candidates.add(toForward(filePath));
|
|
543
|
+
if (projectRoot) {
|
|
544
|
+
const lexical = resolve(projectRoot, filePath);
|
|
545
|
+
candidates.add(toForward(lexical));
|
|
546
|
+
try {
|
|
547
|
+
candidates.add(toForward(realpathSync(lexical)));
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
// File does not exist yet, or realpath failed — rely on lexical form.
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
for (const globs of denyGlobs) {
|
|
554
|
+
for (const glob of globs) {
|
|
555
|
+
// Normalize the glob's path separators the same way candidates were
|
|
556
|
+
// normalized — otherwise a Windows absolute deny rule like
|
|
557
|
+
// `Read(C:\Users\...\secret.env)` parses with literal backslashes that
|
|
558
|
+
// never match a forward-slash candidate.
|
|
559
|
+
const regex = fileGlobToRegex(toForward(glob), caseInsensitive);
|
|
560
|
+
for (const candidate of candidates) {
|
|
561
|
+
if (regex.test(candidate)) {
|
|
562
|
+
return { denied: true, matchedPattern: glob };
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
return { denied: false };
|
|
568
|
+
}
|
|
569
|
+
// ==============================================================================
|
|
570
|
+
// Project-Boundary Containment (Issue #852)
|
|
571
|
+
// ==============================================================================
|
|
572
|
+
/**
|
|
573
|
+
* Pure, algorithmic (no-regex) test: does `filePath` resolve to a location
|
|
574
|
+
* inside `projectRoot`?
|
|
575
|
+
*
|
|
576
|
+
* Issue #852 — `ctx_execute_file` previously fed its `path` argument straight
|
|
577
|
+
* into `resolve(projectRoot, path)`. Because `path.resolve` lets an *absolute*
|
|
578
|
+
* argument win outright, an agent could read any file on the host
|
|
579
|
+
* (`/home/user/secret`, `/etc/passwd`) regardless of the project root, and
|
|
580
|
+
* `../` traversal escaped just as easily. Claude Code's harness sandbox cannot
|
|
581
|
+
* inspect MCP input params, so the user approving the MCP call could not see
|
|
582
|
+
* that the path escaped the workspace. This guard re-anchors the path to the
|
|
583
|
+
* project boundary.
|
|
584
|
+
*
|
|
585
|
+
* Containment is decided on the *resolved* form. When the file (or its parent
|
|
586
|
+
* chain) exists, the symlink-canonical form is ALSO required to stay inside —
|
|
587
|
+
* this closes the symlink-escape class (a project-local `safe.log` whose
|
|
588
|
+
* realpath points at `~/.ssh/id_rsa`), mirroring `evaluateFilePath`.
|
|
589
|
+
*
|
|
590
|
+
* A path equal to the project root itself counts as inside. Comparison is
|
|
591
|
+
* case-insensitive on Windows/macOS to match those filesystems' semantics.
|
|
592
|
+
*
|
|
593
|
+
* Returns `true` when `projectRoot` is falsy (no boundary to enforce) so the
|
|
594
|
+
* caller's fail-open posture is preserved when the root cannot be resolved.
|
|
595
|
+
*/
|
|
596
|
+
export function isPathInsideProject(filePath, projectRoot, caseInsensitive = process.platform === "win32" || process.platform === "darwin") {
|
|
597
|
+
if (!projectRoot)
|
|
598
|
+
return true;
|
|
599
|
+
const root = resolve(projectRoot);
|
|
600
|
+
const lexical = resolve(projectRoot, filePath);
|
|
601
|
+
const within = (root, candidate) => {
|
|
602
|
+
let a = root;
|
|
603
|
+
let b = candidate;
|
|
604
|
+
if (caseInsensitive) {
|
|
605
|
+
a = a.toLowerCase();
|
|
606
|
+
b = b.toLowerCase();
|
|
607
|
+
}
|
|
608
|
+
if (a === b)
|
|
609
|
+
return true;
|
|
610
|
+
// `path.relative` is pure string arithmetic — no regex. A candidate inside
|
|
611
|
+
// the root yields a relative path that neither starts with `..` (escapes
|
|
612
|
+
// upward) nor is absolute (a different drive/root on Windows that cannot be
|
|
613
|
+
// expressed relatively).
|
|
614
|
+
const rel = relative(a, b);
|
|
615
|
+
if (rel === "")
|
|
616
|
+
return true;
|
|
617
|
+
if (rel === ".." || rel.startsWith(".." + sep))
|
|
618
|
+
return false;
|
|
619
|
+
if (isAbsoluteRel(rel))
|
|
620
|
+
return false;
|
|
621
|
+
return true;
|
|
622
|
+
};
|
|
623
|
+
// Lexical containment is the primary gate.
|
|
624
|
+
if (!within(root, lexical))
|
|
625
|
+
return false;
|
|
626
|
+
// Defense-in-depth: when the path (or a parent) is a symlink that points
|
|
627
|
+
// outside the project, the canonical form must ALSO stay inside. Best-effort
|
|
628
|
+
// — a not-yet-created file (ENOENT) falls back to the lexical decision above.
|
|
629
|
+
try {
|
|
630
|
+
const canonicalRoot = realpathSync(root);
|
|
631
|
+
const canonical = realpathSync(lexical);
|
|
632
|
+
if (!within(canonicalRoot, canonical))
|
|
633
|
+
return false;
|
|
634
|
+
}
|
|
635
|
+
catch {
|
|
636
|
+
/* file does not exist yet / realpath failed — lexical decision stands */
|
|
637
|
+
}
|
|
638
|
+
return true;
|
|
639
|
+
}
|
|
640
|
+
/** Pure helper: is a `path.relative` result an absolute path? (no regex) */
|
|
641
|
+
function isAbsoluteRel(rel) {
|
|
642
|
+
if (rel.startsWith("/"))
|
|
643
|
+
return true; // POSIX absolute
|
|
644
|
+
// Windows drive-absolute: "C:\..." or "C:/..."
|
|
645
|
+
if (rel.length >= 3 && rel[1] === ":" && (rel[2] === "\\" || rel[2] === "/")) {
|
|
646
|
+
const c = rel.charCodeAt(0);
|
|
647
|
+
return (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
|
|
648
|
+
}
|
|
649
|
+
return false;
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* Decide whether `filePath` may be processed, given the project boundary AND
|
|
653
|
+
* the user's existing host `Read(...)` allow rules.
|
|
654
|
+
*
|
|
655
|
+
* Decision order:
|
|
656
|
+
* 1. Inside the project root → allowed (the common case; no config needed).
|
|
657
|
+
* 2. Outside the project, but matching a `permissions.allow` `Read(...)` glob
|
|
658
|
+
* the user already configured for the host → allowed. This is the
|
|
659
|
+
* principled escape hatch: a deliberate out-of-project read is expressed
|
|
660
|
+
* ONCE in the host config the user already maintains, reusing the same
|
|
661
|
+
* mechanism Claude Code itself uses to whitelist a path outside the
|
|
662
|
+
* sandbox — no context-mode-specific opt-out env that would rot into
|
|
663
|
+
* dead code.
|
|
664
|
+
* 3. Outside the project, no allow match → denied (closes the #852 escape).
|
|
665
|
+
*
|
|
666
|
+
* `allowGlobs` has the same per-settings-file shape as the deny globs returned
|
|
667
|
+
* by `readToolPermissionPatterns(toolName, "allow", …)`. Allow-matching reuses
|
|
668
|
+
* `evaluateFilePath` so absolute/`..`/symlink-canonical candidate resolution is
|
|
669
|
+
* identical to the deny path — one matcher, no divergence.
|
|
670
|
+
*
|
|
671
|
+
* Fail-open on an unknown project root (boundary cannot be computed) so the
|
|
672
|
+
* guard never blocks legitimate in-project work when resolution fails.
|
|
673
|
+
*/
|
|
674
|
+
export function evaluateProjectContainment(filePath, projectRoot, allowGlobs = [], caseInsensitive = process.platform === "win32" || process.platform === "darwin") {
|
|
675
|
+
if (isPathInsideProject(filePath, projectRoot, caseInsensitive)) {
|
|
676
|
+
return { allowed: true, reason: "inside" };
|
|
677
|
+
}
|
|
678
|
+
// Outside the project — permit only if the user explicitly allowed this path
|
|
679
|
+
// for the host Read tool. `evaluateFilePath` returns `denied:true` when a glob
|
|
680
|
+
// MATCHES, so a match here means "explicitly allowed".
|
|
681
|
+
if (allowGlobs.some((g) => g.length > 0)) {
|
|
682
|
+
const matched = evaluateFilePath(filePath, allowGlobs, caseInsensitive, projectRoot);
|
|
683
|
+
if (matched.denied)
|
|
684
|
+
return { allowed: true, reason: "allow-rule" };
|
|
685
|
+
}
|
|
686
|
+
return { allowed: false, reason: "outside" };
|
|
687
|
+
}
|
|
688
|
+
// ==============================================================================
|
|
689
|
+
// Shell-Escape Scanner
|
|
690
|
+
// ==============================================================================
|
|
691
|
+
// Regex patterns that detect shell-escape calls in non-shell languages.
|
|
692
|
+
// Each pattern uses capture groups so that the embedded command string
|
|
693
|
+
// can be extracted from the last non-quote group.
|
|
694
|
+
//
|
|
695
|
+
// NOTE: These regexes contain literal strings like "execSync" — they are
|
|
696
|
+
// patterns for *detecting* shell escapes in user code, not actual usage.
|
|
697
|
+
const SHELL_ESCAPE_PATTERNS = {
|
|
698
|
+
python: [
|
|
699
|
+
/os\.system\(\s*(['"])(.*?)\1\s*\)/g,
|
|
700
|
+
/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*(['"])(.*?)\1/g,
|
|
701
|
+
],
|
|
702
|
+
javascript: [
|
|
703
|
+
/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,
|
|
704
|
+
/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g,
|
|
705
|
+
],
|
|
706
|
+
typescript: [
|
|
707
|
+
/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,
|
|
708
|
+
/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g,
|
|
709
|
+
],
|
|
710
|
+
ruby: [
|
|
711
|
+
/system\(\s*(['"])(.*?)\1/g,
|
|
712
|
+
/`(.*?)`/g,
|
|
713
|
+
],
|
|
714
|
+
go: [
|
|
715
|
+
/exec\.Command\(\s*(['"`])(.*?)\1/g,
|
|
716
|
+
],
|
|
717
|
+
php: [
|
|
718
|
+
/shell_exec\(\s*(['"`])(.*?)\1/g,
|
|
719
|
+
/(?:^|[^.])exec\(\s*(['"`])(.*?)\1/g,
|
|
720
|
+
/(?:^|[^.])system\(\s*(['"`])(.*?)\1/g,
|
|
721
|
+
/passthru\(\s*(['"`])(.*?)\1/g,
|
|
722
|
+
/proc_open\(\s*(['"`])(.*?)\1/g,
|
|
723
|
+
],
|
|
724
|
+
rust: [
|
|
725
|
+
/Command::new\(\s*(['"`])(.*?)\1/g,
|
|
726
|
+
],
|
|
727
|
+
};
|
|
728
|
+
/**
|
|
729
|
+
* Extract all string elements from a Python subprocess list call.
|
|
730
|
+
*
|
|
731
|
+
* subprocess.run(["rm", "-rf", "/"]) → "rm -rf /"
|
|
732
|
+
*
|
|
733
|
+
* This catches the list-of-strings form that the single-string regex misses.
|
|
734
|
+
*/
|
|
735
|
+
function extractPythonSubprocessListArgs(code) {
|
|
736
|
+
const commands = [];
|
|
737
|
+
const pattern = /subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g;
|
|
738
|
+
let match;
|
|
739
|
+
while ((match = pattern.exec(code)) !== null) {
|
|
740
|
+
const listContent = match[1];
|
|
741
|
+
const args = [...listContent.matchAll(/(['"])(.*?)\1/g)].map((m) => m[2]);
|
|
742
|
+
if (args.length > 0) {
|
|
743
|
+
commands.push(args.join(" "));
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
return commands;
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* Scan non-shell code for shell-escape calls and extract the embedded
|
|
750
|
+
* command strings.
|
|
751
|
+
*
|
|
752
|
+
* Returns an array of command strings found in the code. For unknown
|
|
753
|
+
* languages or code without shell-escape calls, returns an empty array.
|
|
754
|
+
*/
|
|
755
|
+
export function extractShellCommands(code, language) {
|
|
756
|
+
const patterns = SHELL_ESCAPE_PATTERNS[language];
|
|
757
|
+
if (!patterns && language !== "python")
|
|
758
|
+
return [];
|
|
759
|
+
const commands = [];
|
|
760
|
+
if (patterns) {
|
|
761
|
+
for (const pattern of patterns) {
|
|
762
|
+
// Reset lastIndex since we reuse the global regex
|
|
763
|
+
pattern.lastIndex = 0;
|
|
764
|
+
let match;
|
|
765
|
+
while ((match = pattern.exec(code)) !== null) {
|
|
766
|
+
// The command string is in the last capture group that isn't the
|
|
767
|
+
// quote delimiter. For patterns with 2 groups (quote + content),
|
|
768
|
+
// it's group 2. For Ruby backticks with 1 group, it's group 1.
|
|
769
|
+
const command = match[match.length - 1];
|
|
770
|
+
if (command)
|
|
771
|
+
commands.push(command);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
// Python: also extract subprocess list-form args
|
|
776
|
+
if (language === "python") {
|
|
777
|
+
commands.push(...extractPythonSubprocessListArgs(code));
|
|
778
|
+
}
|
|
779
|
+
return commands;
|
|
780
|
+
}
|