-
Notifications
You must be signed in to change notification settings - Fork 284
Add PreToolUse:Bash hook for OPC script directory guard #160
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
yurukusa
wants to merge
1
commit into
parcadei:main
Choose a base branch
from
yurukusa:fix/opc-directory-guard
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| // src/mcp-directory-guard.ts | ||
| import { readFileSync } from "fs"; | ||
|
|
||
| // src/shared/opc-path.ts | ||
| import { existsSync } from "fs"; | ||
| import { join } from "path"; | ||
| function getOpcDir() { | ||
| const envOpcDir = process.env.CLAUDE_OPC_DIR; | ||
| if (envOpcDir && existsSync(envOpcDir)) { | ||
| return envOpcDir; | ||
| } | ||
| const projectDir = process.env.CLAUDE_PROJECT_DIR || process.cwd(); | ||
| const localOpc = join(projectDir, "opc"); | ||
| if (existsSync(localOpc)) { | ||
| return localOpc; | ||
| } | ||
| const homeDir = process.env.HOME || process.env.USERPROFILE || ""; | ||
| if (homeDir) { | ||
| const globalClaude = join(homeDir, ".claude"); | ||
| const globalScripts = join(globalClaude, "scripts", "core"); | ||
| if (existsSync(globalScripts)) { | ||
| return globalClaude; | ||
| } | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| // src/mcp-directory-guard.ts | ||
| var SCRIPT_PATH_PATTERN = /\bscripts\/(mcp|core)\//; | ||
| function buildCdPrefixPattern(opcDir) { | ||
| const escapedDir = opcDir ? opcDir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") : ""; | ||
| const variants = [ | ||
| "\\$CLAUDE_OPC_DIR", | ||
| "\\$\\{CLAUDE_OPC_DIR\\}" | ||
| ]; | ||
| if (escapedDir) { | ||
| variants.push(escapedDir); | ||
| } | ||
| return new RegExp(`^\\s*cd\\s+(${variants.join("|")})\\s*&&`); | ||
| } | ||
| function main() { | ||
| let input; | ||
| try { | ||
| const stdinContent = readFileSync(0, "utf-8"); | ||
| input = JSON.parse(stdinContent); | ||
| } catch { | ||
| console.log("{}"); | ||
| return; | ||
| } | ||
| if (input.tool_name !== "Bash") { | ||
| console.log("{}"); | ||
| return; | ||
| } | ||
| const command = input.tool_input?.command; | ||
| if (!command) { | ||
| console.log("{}"); | ||
| return; | ||
| } | ||
| if (!SCRIPT_PATH_PATTERN.test(command)) { | ||
| console.log("{}"); | ||
| return; | ||
| } | ||
| const opcDir = getOpcDir(); | ||
| const cdPrefix = buildCdPrefixPattern(opcDir); | ||
| if (cdPrefix.test(command)) { | ||
| console.log("{}"); | ||
| return; | ||
| } | ||
| const dirRef = opcDir || "$CLAUDE_OPC_DIR"; | ||
| const corrected = `cd ${dirRef} && ${command.trimStart()}`; | ||
| const output = { | ||
| hookSpecificOutput: { | ||
| hookEventName: "PreToolUse", | ||
| permissionDecision: "deny", | ||
| permissionDecisionReason: `OPC directory guard: commands referencing scripts/(mcp|core)/ must run from the OPC directory so uv can find pyproject.toml. | ||
|
|
||
| Blocked command: | ||
| ${command.trim()} | ||
|
|
||
| Corrected command: | ||
| ${corrected}` | ||
| } | ||
| }; | ||
| console.log(JSON.stringify(output)); | ||
| } | ||
| main(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| /** | ||
| * PreToolUse:Bash Hook - OPC Script Directory Guard | ||
| * | ||
| * Prevents running scripts from `scripts/(mcp|core)/` without first | ||
| * changing to $CLAUDE_OPC_DIR. When Claude runs these scripts from the | ||
| * wrong directory, `uv run` misses `opc/pyproject.toml` and its | ||
| * dependencies, causing ModuleNotFoundError. | ||
| * | ||
| * Detection: any Bash command referencing `scripts/(mcp|core)/` paths | ||
| * Allowed: commands prefixed with `cd $CLAUDE_OPC_DIR &&` (or resolved path) | ||
| * Denied: returns corrected command in the reason message | ||
| * | ||
| * Fixes: #148 | ||
| */ | ||
|
|
||
| import { readFileSync } from 'fs'; | ||
| import { getOpcDir } from './shared/opc-path.js'; | ||
| import type { PreToolUseInput, PreToolUseHookOutput } from './shared/types.js'; | ||
|
|
||
| /** | ||
| * Pattern matching scripts/(mcp|core)/ references in Bash commands. | ||
| * Captures the path for use in the corrected command suggestion. | ||
| */ | ||
| const SCRIPT_PATH_PATTERN = /\bscripts\/(mcp|core)\//; | ||
|
|
||
| /** | ||
| * Pattern matching a proper cd prefix to OPC dir. | ||
| * Accepts: | ||
| * cd $CLAUDE_OPC_DIR && | ||
| * cd ${CLAUDE_OPC_DIR} && | ||
| * cd /resolved/opc/path && | ||
| */ | ||
| function buildCdPrefixPattern(opcDir: string | null): RegExp { | ||
| const escapedDir = opcDir ? opcDir.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : ''; | ||
| // Match: cd <opc-dir-variant> && (with flexible whitespace) | ||
| const variants = [ | ||
| '\\$CLAUDE_OPC_DIR', | ||
| '\\$\\{CLAUDE_OPC_DIR\\}', | ||
| ]; | ||
| if (escapedDir) { | ||
| variants.push(escapedDir); | ||
| } | ||
| return new RegExp(`^\\s*cd\\s+(${variants.join('|')})\\s*&&`); | ||
| } | ||
|
|
||
| function main(): void { | ||
| let input: PreToolUseInput; | ||
| try { | ||
| const stdinContent = readFileSync(0, 'utf-8'); | ||
| input = JSON.parse(stdinContent) as PreToolUseInput; | ||
| } catch { | ||
| // Can't read input - allow through | ||
| console.log('{}'); | ||
| return; | ||
| } | ||
|
|
||
| // Only process Bash tool | ||
| if (input.tool_name !== 'Bash') { | ||
| console.log('{}'); | ||
| return; | ||
| } | ||
|
|
||
| const command = input.tool_input?.command as string; | ||
| if (!command) { | ||
| console.log('{}'); | ||
| return; | ||
| } | ||
|
|
||
| // Check if command references OPC script paths | ||
| if (!SCRIPT_PATH_PATTERN.test(command)) { | ||
| // No script path reference - allow through | ||
| console.log('{}'); | ||
| return; | ||
| } | ||
|
|
||
| const opcDir = getOpcDir(); | ||
| const cdPrefix = buildCdPrefixPattern(opcDir); | ||
|
|
||
| // Check if command already has the correct cd prefix | ||
| if (cdPrefix.test(command)) { | ||
| console.log('{}'); | ||
| return; | ||
| } | ||
|
|
||
| // Build corrected command suggestion | ||
| const dirRef = opcDir || '$CLAUDE_OPC_DIR'; | ||
| const corrected = `cd ${dirRef} && ${command.trimStart()}`; | ||
|
|
||
| const output: PreToolUseHookOutput = { | ||
| hookSpecificOutput: { | ||
| hookEventName: 'PreToolUse', | ||
| permissionDecision: 'deny', | ||
| permissionDecisionReason: | ||
| `OPC directory guard: commands referencing scripts/(mcp|core)/ must ` + | ||
| `run from the OPC directory so uv can find pyproject.toml.\n\n` + | ||
| `Blocked command:\n ${command.trim()}\n\n` + | ||
| `Corrected command:\n ${corrected}`, | ||
| }, | ||
| }; | ||
|
|
||
| console.log(JSON.stringify(output)); | ||
| } | ||
|
|
||
| main(); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Allow quoted
cdprefixes and quote correctedcdtarget.Line 43 currently rejects valid forms like
cd "$CLAUDE_OPC_DIR" && ..., and Line 87 can emit a broken command when the resolved OPC path contains spaces. This can deny correct commands and suggest unusable retries.🔧 Proposed fix
function buildCdPrefixPattern(opcDir: string | null): RegExp { const escapedDir = opcDir ? opcDir.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : ''; // Match: cd <opc-dir-variant> && (with flexible whitespace) const variants = [ '\\$CLAUDE_OPC_DIR', '\\$\\{CLAUDE_OPC_DIR\\}', ]; if (escapedDir) { variants.push(escapedDir); } - return new RegExp(`^\\s*cd\\s+(${variants.join('|')})\\s*&&`); + const target = `(?:${variants.join('|')})`; + // allow both: cd $CLAUDE_OPC_DIR && ... and cd "$CLAUDE_OPC_DIR" && ... + return new RegExp(`^\\s*cd\\s+(?:(["'])${target}\\1|${target})\\s*&&`); } + +function quoteShellArg(value: string): string { + return "'" + value.replace(/'/g, "'\\''") + "'"; +} @@ - const dirRef = opcDir || '$CLAUDE_OPC_DIR'; + const dirRef = opcDir ? quoteShellArg(opcDir) : '"$CLAUDE_OPC_DIR"'; const corrected = `cd ${dirRef} && ${command.trimStart()}`;Also applies to: 86-87
🧰 Tools
🪛 ast-grep (0.41.1)
[warning] 42-42: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(
^\\s*cd\\s+(${variants.join('|')})\\s*&&)Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html
(regexp-from-variable)
🤖 Prompt for AI Agents