@dreb/coding-agent 2.7.0 → 2.9.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.
@@ -28,4 +28,29 @@
28
28
  * @returns The first matching pattern, or `undefined` if the command is allowed.
29
29
  */
30
30
  export declare function isForbiddenCommand(command: string, extraPatterns?: string[]): string | undefined;
31
+ /**
32
+ * Extract file paths from a command that executes a script file.
33
+ * Detects: `bash file`, `sh file`, `source file`, `. file`, and input
34
+ * redirects like `bash < file`.
35
+ *
36
+ * Returns an array of file paths (usually 0 or 1). Does not check whether
37
+ * the files exist — the caller handles that.
38
+ *
39
+ * @returns Array of script file paths referenced by the command.
40
+ */
41
+ export declare function extractScriptPaths(command: string): string[];
42
+ /**
43
+ * Check file content line-by-line for forbidden commands.
44
+ * Each non-empty, non-comment line is passed through `isForbiddenCommand`.
45
+ *
46
+ * This is a pure function — the caller is responsible for reading the file
47
+ * and passing the content string.
48
+ *
49
+ * @returns The first match with pattern, line number, and line text, or undefined.
50
+ */
51
+ export declare function checkScriptContent(content: string, extraPatterns?: string[]): {
52
+ pattern: string;
53
+ line: number;
54
+ text: string;
55
+ } | undefined;
31
56
  //# sourceMappingURL=forbidden-commands.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"forbidden-commands.d.ts","sourceRoot":"","sources":["../../src/core/forbidden-commands.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AA0IH;;;;;;;;;;GAUG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,SAAS,CA0BhG","sourcesContent":["/**\n * Forbidden-commands guard — blocks bash commands matching dangerous patterns\n * before they reach the shell.\n *\n * Hardcoded default patterns are ALWAYS active regardless of settings.\n * Users can add additional patterns via settings.forbiddenCommands.\n *\n * Commands are split on shell operators (&&, ||, ;, |, &) and each segment\n * is checked independently. Default patterns are anchored to the start of\n * each segment (^) so they only match commands that *begin with* the dangerous\n * command, not commands that merely *mention* the pattern in string literals\n * or arguments.\n *\n * To avoid false positives from operators inside quoted strings, content\n * within single/double quotes is masked before splitting. To catch subshell\n * wrappers like $(cmd) and (cmd), leading wrapper characters are stripped\n * from each segment before pattern matching.\n */\n\n/** Hardcoded patterns that are always active. Always anchored with ^. */\nconst DEFAULT_FORBIDDEN_PATTERNS: string[] = [\n\t\"^gh pr merge.*--admin\", // bypass branch protection\n\t\"^git push.*(-f\\\\b|--force)\", // force push (includes --force-with-lease)\n\t\"^gh api.*bypass\", // API calls with bypass flag\n\t\"^(?:export\\\\s+)?HUSKY=0\", // bypass pre-commit hooks (anchored with optional export prefix)\n\t\"^git\\\\s+commit.*--no-verify\", // bypass pre-commit hooks via --no-verify flag\n\t\"^(?:export\\\\s+)?SKIP_?VALIDATION=1\", // bypass pre-commit hooks via SKIP_VALIDATION env var\n];\n\n/**\n * Mask content inside single and double-quoted strings by replacing\n * characters within quotes with underscores. This prevents shell operators\n * inside quoted strings from causing false splits.\n *\n * Handles escaped quotes (\\\", \\') within strings. Correctly counts\n * consecutive backslashes before a quote — an even count means the quote\n * is real (e.g. `\\\\\"` is escaped-backslash + closing quote).\n */\nfunction maskQuotedContent(command: string): string {\n\tlet result = \"\";\n\tlet inSingle = false;\n\tlet inDouble = false;\n\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\n\t\tif (ch === \"'\" && !inDouble) {\n\t\t\tif (!isEscaped(command, i)) {\n\t\t\t\tinSingle = !inSingle;\n\t\t\t}\n\t\t\tresult += ch;\n\t\t} else if (ch === '\"' && !inSingle) {\n\t\t\tif (!isEscaped(command, i)) {\n\t\t\t\tinDouble = !inDouble;\n\t\t\t}\n\t\t\tresult += ch;\n\t\t} else if (inSingle || inDouble) {\n\t\t\t// Replace content inside quotes with a safe character\n\t\t\t// that won't match shell operators\n\t\t\tresult += ch === \"\\n\" ? \"\\n\" : \"_\";\n\t\t} else {\n\t\t\tresult += ch;\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Check if the character at position `i` is escaped by counting consecutive\n * trailing backslashes. If the count is odd, the character is escaped.\n * If even (including zero), it is not escaped.\n *\n * e.g. `\\\\\"` → 2 backslashes → even → `\"` is NOT escaped (real quote)\n * `\\\\\\\"` → 3 backslashes → odd → `\"` IS escaped (literal quote)\n */\nfunction isEscaped(str: string, i: number): boolean {\n\tlet count = 0;\n\tlet j = i - 1;\n\twhile (j >= 0 && str[j] === \"\\\\\") {\n\t\tcount++;\n\t\tj--;\n\t}\n\treturn count % 2 === 1;\n}\n\n/**\n * Split a command string into individual segments on shell operators.\n *\n * Handles: &&, ||, ;, |, & (background), and newlines.\n * Content inside single/double quotes is masked before splitting so that\n * operators inside quoted strings don't cause false splits.\n * Each segment is trimmed of leading whitespace.\n */\nfunction splitCommandSegments(command: string): string[] {\n\t// Mask quoted content to avoid splitting on operators inside strings\n\tconst masked = maskQuotedContent(command);\n\n\t// Split on shell operators: &&, ||, ;, |, &, and newlines\n\tconst splits = masked.split(/\\s*(?:&&|\\|\\||[;&|]|\\n)\\s*/);\n\n\t// Map split positions back to original command segments.\n\t// We split the masked string to find operator positions, but return\n\t// the original (unmasked) segments so pattern matching sees real text.\n\tconst originalSegments: string[] = [];\n\tlet maskedIdx = 0;\n\n\tfor (const part of splits) {\n\t\t// Find the start of this part in the masked string\n\t\tconst startInMasked = masked.indexOf(part, maskedIdx);\n\t\tif (startInMasked === -1) {\n\t\t\t// Fallback: use the part as-is (shouldn't happen)\n\t\t\toriginalSegments.push(command.substring(maskedIdx, maskedIdx + part.length).trim());\n\t\t} else {\n\t\t\toriginalSegments.push(command.substring(startInMasked, startInMasked + part.length).trim());\n\t\t}\n\t\tmaskedIdx = startInMasked + part.length;\n\t}\n\n\treturn originalSegments.filter((s) => s.length > 0);\n}\n\n/**\n * Strip leading subshell/command-substitution wrappers from a segment\n * so that $(cmd), (cmd), and `cmd` are checked against patterns too.\n *\n * Handles both full-segment wrappers ($(cmd)) and inline substitutions\n * (result=$(cmd)) by extracting inner commands.\n */\nfunction stripSubshellWrapper(segment: string): string {\n\t// Strip $(...) wrapper when it's the whole segment\n\tif (/^\\$\\(/.test(segment) && segment.endsWith(\")\")) {\n\t\treturn segment.slice(2, -1).trim();\n\t}\n\t// Strip (...) wrapper (subshell) when it's the whole segment\n\tif (/^\\(/.test(segment) && segment.endsWith(\")\")) {\n\t\treturn segment.slice(1, -1).trim();\n\t}\n\t// Strip backtick wrapper when it's the whole segment\n\tif (/^`/.test(segment) && segment.endsWith(\"`\")) {\n\t\treturn segment.slice(1, -1).trim();\n\t}\n\t// Extract inner command from inline $() or backtick substitutions\n\t// e.g., \"result=$(git push --force)\" → \"git push --force\"\n\tconst inlineMatch = segment.match(/\\$\\(([^)]+)\\)/);\n\tif (inlineMatch) {\n\t\treturn inlineMatch[1].trim();\n\t}\n\tconst backtickMatch = segment.match(/`([^`]+)`/);\n\tif (backtickMatch) {\n\t\treturn backtickMatch[1].trim();\n\t}\n\treturn segment;\n}\n\n/**\n * Check whether a command matches any forbidden pattern.\n *\n * The command is split on shell operators (&&, ||, ;, |) with quoted content\n * masked to avoid false splits. Each segment is then stripped of subshell\n * wrappers ($(...), (...), `...`) and checked against patterns. Default\n * patterns are ^-anchored so they only match commands that start with the\n * dangerous command prefix.\n *\n * @returns The first matching pattern, or `undefined` if the command is allowed.\n */\nexport function isForbiddenCommand(command: string, extraPatterns?: string[]): string | undefined {\n\t// Guard against misconfigured settings (string instead of array)\n\tconst validatedExtras = Array.isArray(extraPatterns) ? extraPatterns : undefined;\n\tconst allPatterns = validatedExtras\n\t\t? [...DEFAULT_FORBIDDEN_PATTERNS, ...validatedExtras]\n\t\t: DEFAULT_FORBIDDEN_PATTERNS;\n\tconst segments = splitCommandSegments(command);\n\n\tfor (const segment of segments) {\n\t\t// Check both the raw segment and the subshell-unwrapped version\n\t\tconst toCheck = [segment, stripSubshellWrapper(segment)];\n\t\tfor (const text of toCheck) {\n\t\t\tfor (const pattern of allPatterns) {\n\t\t\t\ttry {\n\t\t\t\t\tconst re = new RegExp(pattern);\n\t\t\t\t\tif (re.test(text)) {\n\t\t\t\t\t\treturn pattern;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Invalid regex in user settings — skip it\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn undefined;\n}\n"]}
1
+ {"version":3,"file":"forbidden-commands.d.ts","sourceRoot":"","sources":["../../src/core/forbidden-commands.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAkOH;;;;;;;;;;GAUG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,SAAS,CAgEhG;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,CAqC5D;AAED;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CACjC,OAAO,EAAE,MAAM,EACf,aAAa,CAAC,EAAE,MAAM,EAAE,GACtB;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAgB7D","sourcesContent":["/**\n * Forbidden-commands guard — blocks bash commands matching dangerous patterns\n * before they reach the shell.\n *\n * Hardcoded default patterns are ALWAYS active regardless of settings.\n * Users can add additional patterns via settings.forbiddenCommands.\n *\n * Commands are split on shell operators (&&, ||, ;, |, &) and each segment\n * is checked independently. Default patterns are anchored to the start of\n * each segment (^) so they only match commands that *begin with* the dangerous\n * command, not commands that merely *mention* the pattern in string literals\n * or arguments.\n *\n * To avoid false positives from operators inside quoted strings, content\n * within single/double quotes is masked before splitting. To catch subshell\n * wrappers like $(cmd) and (cmd), leading wrapper characters are stripped\n * from each segment before pattern matching.\n */\n\n/** Hardcoded patterns that are always active. Always anchored with ^. */\nconst DEFAULT_FORBIDDEN_PATTERNS: string[] = [\n\t\"^gh pr merge.*--admin\", // bypass branch protection\n\t\"^git push.*(-f\\\\b|--force)\", // force push (includes --force-with-lease)\n\t\"^gh api.*bypass\", // API calls with bypass flag\n\t\"^(?:export\\\\s+)?HUSKY=0\", // bypass pre-commit hooks (anchored with optional export prefix)\n\t\"^git\\\\s+commit.*--no-verify\", // bypass pre-commit hooks via --no-verify flag\n\t\"^(?:export\\\\s+)?SKIP_?VALIDATION=1\", // bypass pre-commit hooks via SKIP_VALIDATION env var\n\t\"^rm\\\\s+.*--no-preserve-root\", // rm with explicit safety override\n\t\"^rm\\\\s+.*\\\\s[\\\"']?/(\\\\*|[\\\\w.-]+/?)?[\\\"']?(\\\\s|$)\", // rm targeting root or top-level dirs (/, /*, /home, /etc)\n\t\"^dd\\\\s+.*of=/dev/(sd|hd|vd|nvme|xvd|loop|mmcblk|disk)\", // dd writing to block devices\n\t\"^mkfs\", // format filesystem (mkfs.ext4, mkfs.xfs, etc.)\n\t\"^>>?\\\\s*/dev/(sd|hd|vd|nvme|xvd|loop|mmcblk|disk)\", // redirect to block device (> and >>)\n\t// Sensitive file access — block reading credential files via bash\n\t// Matches bare commands AND absolute-path invocations (/bin/cat, /usr/bin/cat, etc.)\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*(?:~|\\\\.ssh)/id_(?!.*\\\\.pub\\\\b)\", // SSH private keys (not .pub)\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.dreb/secrets/\", // dreb credential store\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.dreb/agent/auth\\\\.json\", // dreb auth storage\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.aws/credentials\", // AWS credentials\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.gnupg/private-keys\", // GPG private keys\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.config/gcloud/credentials\\\\.db\", // GCloud credentials\n];\n\n/**\n * Patterns checked against the full (quote-masked) command string before\n * splitting into segments. These catch dangerous constructs that span\n * shell operators and would be fragmented by the segment splitter.\n *\n * Matched against the masked string so quoted content doesn't trigger\n * false positives (e.g., `echo \":(){ :|:& };:\"` is safe).\n */\nconst FULL_COMMAND_PATTERNS: string[] = [\n\t\":\\\\(\\\\)\\\\s*\\\\{\", // fork bomb :(){ :|:& };:\n];\n\n/**\n * Patterns also checked against content extracted from within quoted strings.\n * Catches commands like `echo \"rm -rf /\"` where the quoted content is a\n * destructive command that could be piped to execution via `| bash`.\n *\n * These are intentionally limited to destructive/dangerous patterns — env var\n * patterns like HUSKY=0 are excluded because they appear legitimately in\n * contexts like `git log --grep=\"HUSKY=0\"`.\n *\n * The fork bomb pattern from FULL_COMMAND_PATTERNS is included here because\n * it also needs to be caught when quoted (e.g., `echo \":(){ :|:& };:\"`).\n */\nconst QUOTED_CONTENT_PATTERNS: string[] = [\n\t\"^rm\\\\s+.*--no-preserve-root\",\n\t\"^rm\\\\s+.*\\\\s/(\\\\*|[\\\\w.-]+/?)?(\\\\s|$)\",\n\t\"^dd\\\\s+.*of=/dev/(sd|hd|vd|nvme|xvd|loop|mmcblk|disk)\",\n\t\"^mkfs\",\n\t\"^>>?\\\\s*/dev/(sd|hd|vd|nvme|xvd|loop|mmcblk|disk)\",\n\t\"^gh pr merge.*--admin\",\n\t\"^git push.*(-f\\\\b|--force)\",\n\t\"^gh api.*bypass\",\n\t\"^git\\\\s+commit.*--no-verify\",\n\t\":\\\\(\\\\)\\\\s*\\\\{\", // fork bomb\n\t// Sensitive file access in quoted content\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*(?:~|\\\\.ssh)/id_(?!.*\\\\.pub\\\\b)\",\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.dreb/secrets/\",\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.dreb/agent/auth\\\\.json\",\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.aws/credentials\",\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.gnupg/private-keys\",\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.config/gcloud/credentials\\\\.db\",\n];\n\n/**\n * Mask content inside single and double-quoted strings by replacing\n * characters within quotes with underscores. This prevents shell operators\n * inside quoted strings from causing false splits.\n *\n * Handles escaped quotes (\\\", \\') within strings. Correctly counts\n * consecutive backslashes before a quote — an even count means the quote\n * is real (e.g. `\\\\\"` is escaped-backslash + closing quote).\n */\nfunction maskQuotedContent(command: string): string {\n\tlet result = \"\";\n\tlet inSingle = false;\n\tlet inDouble = false;\n\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\n\t\tif (ch === \"'\" && !inDouble) {\n\t\t\t// In bash, single-quoted strings are completely literal — backslashes\n\t\t\t// have no escape function inside single quotes. Always toggle.\n\t\t\tinSingle = !inSingle;\n\t\t\tresult += ch;\n\t\t} else if (ch === '\"' && !inSingle) {\n\t\t\tif (!isEscaped(command, i)) {\n\t\t\t\tinDouble = !inDouble;\n\t\t\t}\n\t\t\tresult += ch;\n\t\t} else if (inSingle || inDouble) {\n\t\t\t// Replace content inside quotes with a safe character\n\t\t\t// that won't match shell operators\n\t\t\tresult += ch === \"\\n\" ? \"\\n\" : \"_\";\n\t\t} else {\n\t\t\tresult += ch;\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Check if the character at position `i` is escaped by counting consecutive\n * trailing backslashes. If the count is odd, the character is escaped.\n * If even (including zero), it is not escaped.\n *\n * e.g. `\\\\\"` → 2 backslashes → even → `\"` is NOT escaped (real quote)\n * `\\\\\\\"` → 3 backslashes → odd → `\"` IS escaped (literal quote)\n */\nfunction isEscaped(str: string, i: number): boolean {\n\tlet count = 0;\n\tlet j = i - 1;\n\twhile (j >= 0 && str[j] === \"\\\\\") {\n\t\tcount++;\n\t\tj--;\n\t}\n\treturn count % 2 === 1;\n}\n\n/**\n * Extract text content from within quoted strings in a segment.\n * Used to catch commands like `echo \"rm -rf /\" | bash` where dangerous\n * content is hidden inside quotes. The normal segment check won't catch\n * this because `echo` (not `rm`) starts the segment. By extracting the\n * quoted content and checking it separately, we block segments that\n * contain forbidden commands in their quoted arguments.\n */\nfunction extractQuotedContent(text: string): string[] {\n\tconst results: string[] = [];\n\tlet inQuote: string | null = null;\n\tlet start = -1;\n\n\tfor (let i = 0; i < text.length; i++) {\n\t\tconst ch = text[i];\n\t\tif ((ch === '\"' || ch === \"'\") && (ch === \"'\" || !isEscaped(text, i))) {\n\t\t\tif (inQuote === null) {\n\t\t\t\tinQuote = ch;\n\t\t\t\tstart = i + 1;\n\t\t\t} else if (ch === inQuote) {\n\t\t\t\tconst content = text.substring(start, i).trim();\n\t\t\t\tif (content.length > 0) {\n\t\t\t\t\tresults.push(content);\n\t\t\t\t}\n\t\t\t\tinQuote = null;\n\t\t\t}\n\t\t}\n\t}\n\treturn results;\n}\n\n/**\n * Split a command string into individual segments on shell operators.\n *\n * Handles: &&, ||, ;, |, & (background), and newlines.\n * Content inside single/double quotes is masked before splitting so that\n * operators inside quoted strings don't cause false splits.\n * Each segment is trimmed of leading whitespace.\n */\nfunction splitCommandSegments(command: string): string[] {\n\t// Mask quoted content to avoid splitting on operators inside strings\n\tconst masked = maskQuotedContent(command);\n\n\t// Split on shell operators: &&, ||, ;, |, &, and newlines\n\tconst splits = masked.split(/\\s*(?:&&|\\|\\||[;&|]|\\n)\\s*/);\n\n\t// Map split positions back to original command segments.\n\t// We split the masked string to find operator positions, but return\n\t// the original (unmasked) segments so pattern matching sees real text.\n\tconst originalSegments: string[] = [];\n\tlet maskedIdx = 0;\n\n\tfor (const part of splits) {\n\t\t// Find the start of this part in the masked string\n\t\tconst startInMasked = masked.indexOf(part, maskedIdx);\n\t\tif (startInMasked === -1) {\n\t\t\t// Fallback: use the part as-is (shouldn't happen)\n\t\t\toriginalSegments.push(command.substring(maskedIdx, maskedIdx + part.length).trim());\n\t\t} else {\n\t\t\toriginalSegments.push(command.substring(startInMasked, startInMasked + part.length).trim());\n\t\t}\n\t\tmaskedIdx = startInMasked + part.length;\n\t}\n\n\treturn originalSegments.filter((s) => s.length > 0);\n}\n\n/**\n * Strip leading subshell/command-substitution wrappers from a segment\n * so that $(cmd), (cmd), and `cmd` are checked against patterns too.\n *\n * Handles both full-segment wrappers ($(cmd)) and inline substitutions\n * (result=$(cmd)) by extracting inner commands.\n */\nfunction stripSubshellWrapper(segment: string): string {\n\t// Strip $(...) wrapper when it's the whole segment\n\tif (/^\\$\\(/.test(segment) && segment.endsWith(\")\")) {\n\t\treturn segment.slice(2, -1).trim();\n\t}\n\t// Strip (...) wrapper (subshell) when it's the whole segment\n\tif (/^\\(/.test(segment) && segment.endsWith(\")\")) {\n\t\treturn segment.slice(1, -1).trim();\n\t}\n\t// Strip backtick wrapper when it's the whole segment\n\tif (/^`/.test(segment) && segment.endsWith(\"`\")) {\n\t\treturn segment.slice(1, -1).trim();\n\t}\n\t// Extract inner command from inline $() or backtick substitutions\n\t// e.g., \"result=$(git push --force)\" → \"git push --force\"\n\tconst inlineMatch = segment.match(/\\$\\(([^)]+)\\)/);\n\tif (inlineMatch) {\n\t\treturn inlineMatch[1].trim();\n\t}\n\tconst backtickMatch = segment.match(/`([^`]+)`/);\n\tif (backtickMatch) {\n\t\treturn backtickMatch[1].trim();\n\t}\n\treturn segment;\n}\n\n/**\n * Check whether a command matches any forbidden pattern.\n *\n * The command is split on shell operators (&&, ||, ;, |) with quoted content\n * masked to avoid false splits. Each segment is then stripped of subshell\n * wrappers ($(...), (...), `...`) and checked against patterns. Default\n * patterns are ^-anchored so they only match commands that start with the\n * dangerous command prefix.\n *\n * @returns The first matching pattern, or `undefined` if the command is allowed.\n */\nexport function isForbiddenCommand(command: string, extraPatterns?: string[]): string | undefined {\n\t// Guard against misconfigured settings (string instead of array)\n\tconst validatedExtras = Array.isArray(extraPatterns) ? extraPatterns : undefined;\n\tconst allPatterns = validatedExtras\n\t\t? [...DEFAULT_FORBIDDEN_PATTERNS, ...validatedExtras]\n\t\t: DEFAULT_FORBIDDEN_PATTERNS;\n\n\t// Pre-split check: match full-command patterns against the quote-masked\n\t// string to catch constructs that span shell operators (e.g., fork bombs).\n\t// Using the masked string prevents false positives from quoted content.\n\tconst masked = maskQuotedContent(command);\n\tfor (const pattern of FULL_COMMAND_PATTERNS) {\n\t\ttry {\n\t\t\tconst re = new RegExp(pattern);\n\t\t\tif (re.test(masked)) {\n\t\t\t\treturn pattern;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Invalid regex — skip\n\t\t}\n\t}\n\n\tconst segments = splitCommandSegments(command);\n\n\t// Combine quoted-content patterns with any user extras for quoted checking\n\tconst allQuotedPatterns = validatedExtras\n\t\t? [...QUOTED_CONTENT_PATTERNS, ...validatedExtras]\n\t\t: QUOTED_CONTENT_PATTERNS;\n\n\tfor (const segment of segments) {\n\t\t// Check both the raw segment and the subshell-unwrapped version\n\t\tconst toCheck = [segment, stripSubshellWrapper(segment)];\n\t\tfor (const text of toCheck) {\n\t\t\tfor (const pattern of allPatterns) {\n\t\t\t\ttry {\n\t\t\t\t\tconst re = new RegExp(pattern);\n\t\t\t\t\tif (re.test(text)) {\n\t\t\t\t\t\treturn pattern;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Invalid regex in user settings — skip it\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check content within quotes for embedded dangerous commands.\n\t\t// There is no legitimate reason for an agent to output/echo forbidden\n\t\t// commands, and quoted content could be piped to execution via | bash.\n\t\tconst quotedContent = extractQuotedContent(segment);\n\t\tfor (const content of quotedContent) {\n\t\t\tfor (const pattern of allQuotedPatterns) {\n\t\t\t\ttry {\n\t\t\t\t\tconst re = new RegExp(pattern);\n\t\t\t\t\tif (re.test(content)) {\n\t\t\t\t\t\treturn pattern;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Invalid regex — skip\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Extract file paths from a command that executes a script file.\n * Detects: `bash file`, `sh file`, `source file`, `. file`, and input\n * redirects like `bash < file`.\n *\n * Returns an array of file paths (usually 0 or 1). Does not check whether\n * the files exist — the caller handles that.\n *\n * @returns Array of script file paths referenced by the command.\n */\nexport function extractScriptPaths(command: string): string[] {\n\tconst paths: string[] = [];\n\tconst segments = splitCommandSegments(command);\n\n\tfor (const segment of segments) {\n\t\tconst trimmed = segment.trim();\n\n\t\t// bash < file.sh (input redirect) — check before shell exec to avoid\n\t\t// the shell exec regex matching \"<\" as a filename\n\t\tconst redirectMatch = trimmed.match(/^(?:bash|sh|zsh|ksh)(?:\\s+-\\S+)*\\s+<\\s*(\\S+)/);\n\t\tif (redirectMatch?.[1]) {\n\t\t\tpaths.push(redirectMatch[1]);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// bash [flags] file.sh, sh [flags] file.sh\n\t\t// Flags are short options like -x, -e, -ex, etc.\n\t\t// Exclude -c (inline command — handled by quoted content check)\n\t\tif (/^(?:bash|sh|zsh|ksh)\\s+-c\\b/.test(trimmed)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst shellExecMatch = trimmed.match(/^(?:bash|sh|zsh|ksh)\\s+(?:-\\S+\\s+)*(\\S+)/);\n\t\tif (shellExecMatch) {\n\t\t\tconst filePath = shellExecMatch[1];\n\t\t\tif (filePath && !filePath.startsWith(\"-\")) {\n\t\t\t\tpaths.push(filePath);\n\t\t\t}\n\t\t}\n\n\t\t// source file.sh, . file.sh\n\t\tconst sourceMatch = trimmed.match(/^(?:source|\\.)\\s+(\\S+)/);\n\t\tif (sourceMatch?.[1]) {\n\t\t\tpaths.push(sourceMatch[1]);\n\t\t}\n\t}\n\n\treturn [...new Set(paths)]; // deduplicate\n}\n\n/**\n * Check file content line-by-line for forbidden commands.\n * Each non-empty, non-comment line is passed through `isForbiddenCommand`.\n *\n * This is a pure function — the caller is responsible for reading the file\n * and passing the content string.\n *\n * @returns The first match with pattern, line number, and line text, or undefined.\n */\nexport function checkScriptContent(\n\tcontent: string,\n\textraPatterns?: string[],\n): { pattern: string; line: number; text: string } | undefined {\n\tconst lines = content.split(\"\\n\");\n\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst line = lines[i].trim();\n\n\t\t// Skip empty lines and comments\n\t\tif (!line || line.startsWith(\"#\")) continue;\n\n\t\tconst pattern = isForbiddenCommand(line, extraPatterns);\n\t\tif (pattern) {\n\t\t\treturn { pattern, line: i + 1, text: line };\n\t\t}\n\t}\n\n\treturn undefined;\n}\n"]}
@@ -24,6 +24,61 @@ const DEFAULT_FORBIDDEN_PATTERNS = [
24
24
  "^(?:export\\s+)?HUSKY=0", // bypass pre-commit hooks (anchored with optional export prefix)
25
25
  "^git\\s+commit.*--no-verify", // bypass pre-commit hooks via --no-verify flag
26
26
  "^(?:export\\s+)?SKIP_?VALIDATION=1", // bypass pre-commit hooks via SKIP_VALIDATION env var
27
+ "^rm\\s+.*--no-preserve-root", // rm with explicit safety override
28
+ "^rm\\s+.*\\s[\"']?/(\\*|[\\w.-]+/?)?[\"']?(\\s|$)", // rm targeting root or top-level dirs (/, /*, /home, /etc)
29
+ "^dd\\s+.*of=/dev/(sd|hd|vd|nvme|xvd|loop|mmcblk|disk)", // dd writing to block devices
30
+ "^mkfs", // format filesystem (mkfs.ext4, mkfs.xfs, etc.)
31
+ "^>>?\\s*/dev/(sd|hd|vd|nvme|xvd|loop|mmcblk|disk)", // redirect to block device (> and >>)
32
+ // Sensitive file access — block reading credential files via bash
33
+ // Matches bare commands AND absolute-path invocations (/bin/cat, /usr/bin/cat, etc.)
34
+ "^(?:/\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\s+.*(?:~|\\.ssh)/id_(?!.*\\.pub\\b)", // SSH private keys (not .pub)
35
+ "^(?:/\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\s+.*\\.dreb/secrets/", // dreb credential store
36
+ "^(?:/\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\s+.*\\.dreb/agent/auth\\.json", // dreb auth storage
37
+ "^(?:/\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\s+.*\\.aws/credentials", // AWS credentials
38
+ "^(?:/\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\s+.*\\.gnupg/private-keys", // GPG private keys
39
+ "^(?:/\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\s+.*\\.config/gcloud/credentials\\.db", // GCloud credentials
40
+ ];
41
+ /**
42
+ * Patterns checked against the full (quote-masked) command string before
43
+ * splitting into segments. These catch dangerous constructs that span
44
+ * shell operators and would be fragmented by the segment splitter.
45
+ *
46
+ * Matched against the masked string so quoted content doesn't trigger
47
+ * false positives (e.g., `echo ":(){ :|:& };:"` is safe).
48
+ */
49
+ const FULL_COMMAND_PATTERNS = [
50
+ ":\\(\\)\\s*\\{", // fork bomb :(){ :|:& };:
51
+ ];
52
+ /**
53
+ * Patterns also checked against content extracted from within quoted strings.
54
+ * Catches commands like `echo "rm -rf /"` where the quoted content is a
55
+ * destructive command that could be piped to execution via `| bash`.
56
+ *
57
+ * These are intentionally limited to destructive/dangerous patterns — env var
58
+ * patterns like HUSKY=0 are excluded because they appear legitimately in
59
+ * contexts like `git log --grep="HUSKY=0"`.
60
+ *
61
+ * The fork bomb pattern from FULL_COMMAND_PATTERNS is included here because
62
+ * it also needs to be caught when quoted (e.g., `echo ":(){ :|:& };:"`).
63
+ */
64
+ const QUOTED_CONTENT_PATTERNS = [
65
+ "^rm\\s+.*--no-preserve-root",
66
+ "^rm\\s+.*\\s/(\\*|[\\w.-]+/?)?(\\s|$)",
67
+ "^dd\\s+.*of=/dev/(sd|hd|vd|nvme|xvd|loop|mmcblk|disk)",
68
+ "^mkfs",
69
+ "^>>?\\s*/dev/(sd|hd|vd|nvme|xvd|loop|mmcblk|disk)",
70
+ "^gh pr merge.*--admin",
71
+ "^git push.*(-f\\b|--force)",
72
+ "^gh api.*bypass",
73
+ "^git\\s+commit.*--no-verify",
74
+ ":\\(\\)\\s*\\{", // fork bomb
75
+ // Sensitive file access in quoted content
76
+ "^(?:/\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\s+.*(?:~|\\.ssh)/id_(?!.*\\.pub\\b)",
77
+ "^(?:/\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\s+.*\\.dreb/secrets/",
78
+ "^(?:/\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\s+.*\\.dreb/agent/auth\\.json",
79
+ "^(?:/\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\s+.*\\.aws/credentials",
80
+ "^(?:/\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\s+.*\\.gnupg/private-keys",
81
+ "^(?:/\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\s+.*\\.config/gcloud/credentials\\.db",
27
82
  ];
28
83
  /**
29
84
  * Mask content inside single and double-quoted strings by replacing
@@ -41,9 +96,9 @@ function maskQuotedContent(command) {
41
96
  for (let i = 0; i < command.length; i++) {
42
97
  const ch = command[i];
43
98
  if (ch === "'" && !inDouble) {
44
- if (!isEscaped(command, i)) {
45
- inSingle = !inSingle;
46
- }
99
+ // In bash, single-quoted strings are completely literal — backslashes
100
+ // have no escape function inside single quotes. Always toggle.
101
+ inSingle = !inSingle;
47
102
  result += ch;
48
103
  }
49
104
  else if (ch === '"' && !inSingle) {
@@ -80,6 +135,36 @@ function isEscaped(str, i) {
80
135
  }
81
136
  return count % 2 === 1;
82
137
  }
138
+ /**
139
+ * Extract text content from within quoted strings in a segment.
140
+ * Used to catch commands like `echo "rm -rf /" | bash` where dangerous
141
+ * content is hidden inside quotes. The normal segment check won't catch
142
+ * this because `echo` (not `rm`) starts the segment. By extracting the
143
+ * quoted content and checking it separately, we block segments that
144
+ * contain forbidden commands in their quoted arguments.
145
+ */
146
+ function extractQuotedContent(text) {
147
+ const results = [];
148
+ let inQuote = null;
149
+ let start = -1;
150
+ for (let i = 0; i < text.length; i++) {
151
+ const ch = text[i];
152
+ if ((ch === '"' || ch === "'") && (ch === "'" || !isEscaped(text, i))) {
153
+ if (inQuote === null) {
154
+ inQuote = ch;
155
+ start = i + 1;
156
+ }
157
+ else if (ch === inQuote) {
158
+ const content = text.substring(start, i).trim();
159
+ if (content.length > 0) {
160
+ results.push(content);
161
+ }
162
+ inQuote = null;
163
+ }
164
+ }
165
+ }
166
+ return results;
167
+ }
83
168
  /**
84
169
  * Split a command string into individual segments on shell operators.
85
170
  *
@@ -161,7 +246,26 @@ export function isForbiddenCommand(command, extraPatterns) {
161
246
  const allPatterns = validatedExtras
162
247
  ? [...DEFAULT_FORBIDDEN_PATTERNS, ...validatedExtras]
163
248
  : DEFAULT_FORBIDDEN_PATTERNS;
249
+ // Pre-split check: match full-command patterns against the quote-masked
250
+ // string to catch constructs that span shell operators (e.g., fork bombs).
251
+ // Using the masked string prevents false positives from quoted content.
252
+ const masked = maskQuotedContent(command);
253
+ for (const pattern of FULL_COMMAND_PATTERNS) {
254
+ try {
255
+ const re = new RegExp(pattern);
256
+ if (re.test(masked)) {
257
+ return pattern;
258
+ }
259
+ }
260
+ catch {
261
+ // Invalid regex — skip
262
+ }
263
+ }
164
264
  const segments = splitCommandSegments(command);
265
+ // Combine quoted-content patterns with any user extras for quoted checking
266
+ const allQuotedPatterns = validatedExtras
267
+ ? [...QUOTED_CONTENT_PATTERNS, ...validatedExtras]
268
+ : QUOTED_CONTENT_PATTERNS;
165
269
  for (const segment of segments) {
166
270
  // Check both the raw segment and the subshell-unwrapped version
167
271
  const toCheck = [segment, stripSubshellWrapper(segment)];
@@ -178,6 +282,89 @@ export function isForbiddenCommand(command, extraPatterns) {
178
282
  }
179
283
  }
180
284
  }
285
+ // Check content within quotes for embedded dangerous commands.
286
+ // There is no legitimate reason for an agent to output/echo forbidden
287
+ // commands, and quoted content could be piped to execution via | bash.
288
+ const quotedContent = extractQuotedContent(segment);
289
+ for (const content of quotedContent) {
290
+ for (const pattern of allQuotedPatterns) {
291
+ try {
292
+ const re = new RegExp(pattern);
293
+ if (re.test(content)) {
294
+ return pattern;
295
+ }
296
+ }
297
+ catch {
298
+ // Invalid regex — skip
299
+ }
300
+ }
301
+ }
302
+ }
303
+ return undefined;
304
+ }
305
+ /**
306
+ * Extract file paths from a command that executes a script file.
307
+ * Detects: `bash file`, `sh file`, `source file`, `. file`, and input
308
+ * redirects like `bash < file`.
309
+ *
310
+ * Returns an array of file paths (usually 0 or 1). Does not check whether
311
+ * the files exist — the caller handles that.
312
+ *
313
+ * @returns Array of script file paths referenced by the command.
314
+ */
315
+ export function extractScriptPaths(command) {
316
+ const paths = [];
317
+ const segments = splitCommandSegments(command);
318
+ for (const segment of segments) {
319
+ const trimmed = segment.trim();
320
+ // bash < file.sh (input redirect) — check before shell exec to avoid
321
+ // the shell exec regex matching "<" as a filename
322
+ const redirectMatch = trimmed.match(/^(?:bash|sh|zsh|ksh)(?:\s+-\S+)*\s+<\s*(\S+)/);
323
+ if (redirectMatch?.[1]) {
324
+ paths.push(redirectMatch[1]);
325
+ continue;
326
+ }
327
+ // bash [flags] file.sh, sh [flags] file.sh
328
+ // Flags are short options like -x, -e, -ex, etc.
329
+ // Exclude -c (inline command — handled by quoted content check)
330
+ if (/^(?:bash|sh|zsh|ksh)\s+-c\b/.test(trimmed)) {
331
+ continue;
332
+ }
333
+ const shellExecMatch = trimmed.match(/^(?:bash|sh|zsh|ksh)\s+(?:-\S+\s+)*(\S+)/);
334
+ if (shellExecMatch) {
335
+ const filePath = shellExecMatch[1];
336
+ if (filePath && !filePath.startsWith("-")) {
337
+ paths.push(filePath);
338
+ }
339
+ }
340
+ // source file.sh, . file.sh
341
+ const sourceMatch = trimmed.match(/^(?:source|\.)\s+(\S+)/);
342
+ if (sourceMatch?.[1]) {
343
+ paths.push(sourceMatch[1]);
344
+ }
345
+ }
346
+ return [...new Set(paths)]; // deduplicate
347
+ }
348
+ /**
349
+ * Check file content line-by-line for forbidden commands.
350
+ * Each non-empty, non-comment line is passed through `isForbiddenCommand`.
351
+ *
352
+ * This is a pure function — the caller is responsible for reading the file
353
+ * and passing the content string.
354
+ *
355
+ * @returns The first match with pattern, line number, and line text, or undefined.
356
+ */
357
+ export function checkScriptContent(content, extraPatterns) {
358
+ const lines = content.split("\n");
359
+ for (let i = 0; i < lines.length; i++) {
360
+ const line = lines[i].trim();
361
+ // Skip empty lines and comments
362
+ if (!line || line.startsWith("#"))
363
+ continue;
364
+ const pattern = isForbiddenCommand(line, extraPatterns);
365
+ if (pattern) {
366
+ return { pattern, line: i + 1, text: line };
367
+ }
181
368
  }
182
369
  return undefined;
183
370
  }
@@ -1 +1 @@
1
- {"version":3,"file":"forbidden-commands.js","sourceRoot":"","sources":["../../src/core/forbidden-commands.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,yEAAyE;AACzE,MAAM,0BAA0B,GAAa;IAC5C,uBAAuB,EAAE,2BAA2B;IACpD,4BAA4B,EAAE,2CAA2C;IACzE,iBAAiB,EAAE,6BAA6B;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aAAwB,EAAsB;IACjG,iEAAiE;IACjE,MAAM,eAAe,GAAG,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC;IACjF,MAAM,WAAW,GAAG,eAAe;QAClC,CAAC,CAAC,CAAC,GAAG,0BAA0B,EAAE,GAAG,eAAe,CAAC;QACrD,CAAC,CAAC,0BAA0B,CAAC;IAC9B,MAAM,QAAQ,GAAG,oBAAoB,CAAC,OAAO,CAAC,CAAC;IAE/C,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAChC,gEAAgE;QAChE,MAAM,OAAO,GAAG,CAAC,OAAO,EAAE,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC;QACzD,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE,CAAC;YAC5B,KAAK,MAAM,OAAO,IAAI,WAAW,EAAE,CAAC;gBACnC,IAAI,CAAC;oBACJ,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;oBAC/B,IAAI,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;wBACnB,OAAO,OAAO,CAAC;oBAChB,CAAC;gBACF,CAAC;gBAAC,MAAM,CAAC;oBACR,6CAA2C;gBAC5C,CAAC;YACF,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,SAAS,CAAC;AAAA,CACjB","sourcesContent":["/**\n * Forbidden-commands guard — blocks bash commands matching dangerous patterns\n * before they reach the shell.\n *\n * Hardcoded default patterns are ALWAYS active regardless of settings.\n * Users can add additional patterns via settings.forbiddenCommands.\n *\n * Commands are split on shell operators (&&, ||, ;, |, &) and each segment\n * is checked independently. Default patterns are anchored to the start of\n * each segment (^) so they only match commands that *begin with* the dangerous\n * command, not commands that merely *mention* the pattern in string literals\n * or arguments.\n *\n * To avoid false positives from operators inside quoted strings, content\n * within single/double quotes is masked before splitting. To catch subshell\n * wrappers like $(cmd) and (cmd), leading wrapper characters are stripped\n * from each segment before pattern matching.\n */\n\n/** Hardcoded patterns that are always active. Always anchored with ^. */\nconst DEFAULT_FORBIDDEN_PATTERNS: string[] = [\n\t\"^gh pr merge.*--admin\", // bypass branch protection\n\t\"^git push.*(-f\\\\b|--force)\", // force push (includes --force-with-lease)\n\t\"^gh api.*bypass\", // API calls with bypass flag\n\t\"^(?:export\\\\s+)?HUSKY=0\", // bypass pre-commit hooks (anchored with optional export prefix)\n\t\"^git\\\\s+commit.*--no-verify\", // bypass pre-commit hooks via --no-verify flag\n\t\"^(?:export\\\\s+)?SKIP_?VALIDATION=1\", // bypass pre-commit hooks via SKIP_VALIDATION env var\n];\n\n/**\n * Mask content inside single and double-quoted strings by replacing\n * characters within quotes with underscores. This prevents shell operators\n * inside quoted strings from causing false splits.\n *\n * Handles escaped quotes (\\\", \\') within strings. Correctly counts\n * consecutive backslashes before a quote — an even count means the quote\n * is real (e.g. `\\\\\"` is escaped-backslash + closing quote).\n */\nfunction maskQuotedContent(command: string): string {\n\tlet result = \"\";\n\tlet inSingle = false;\n\tlet inDouble = false;\n\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\n\t\tif (ch === \"'\" && !inDouble) {\n\t\t\tif (!isEscaped(command, i)) {\n\t\t\t\tinSingle = !inSingle;\n\t\t\t}\n\t\t\tresult += ch;\n\t\t} else if (ch === '\"' && !inSingle) {\n\t\t\tif (!isEscaped(command, i)) {\n\t\t\t\tinDouble = !inDouble;\n\t\t\t}\n\t\t\tresult += ch;\n\t\t} else if (inSingle || inDouble) {\n\t\t\t// Replace content inside quotes with a safe character\n\t\t\t// that won't match shell operators\n\t\t\tresult += ch === \"\\n\" ? \"\\n\" : \"_\";\n\t\t} else {\n\t\t\tresult += ch;\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Check if the character at position `i` is escaped by counting consecutive\n * trailing backslashes. If the count is odd, the character is escaped.\n * If even (including zero), it is not escaped.\n *\n * e.g. `\\\\\"` → 2 backslashes → even → `\"` is NOT escaped (real quote)\n * `\\\\\\\"` → 3 backslashes → odd → `\"` IS escaped (literal quote)\n */\nfunction isEscaped(str: string, i: number): boolean {\n\tlet count = 0;\n\tlet j = i - 1;\n\twhile (j >= 0 && str[j] === \"\\\\\") {\n\t\tcount++;\n\t\tj--;\n\t}\n\treturn count % 2 === 1;\n}\n\n/**\n * Split a command string into individual segments on shell operators.\n *\n * Handles: &&, ||, ;, |, & (background), and newlines.\n * Content inside single/double quotes is masked before splitting so that\n * operators inside quoted strings don't cause false splits.\n * Each segment is trimmed of leading whitespace.\n */\nfunction splitCommandSegments(command: string): string[] {\n\t// Mask quoted content to avoid splitting on operators inside strings\n\tconst masked = maskQuotedContent(command);\n\n\t// Split on shell operators: &&, ||, ;, |, &, and newlines\n\tconst splits = masked.split(/\\s*(?:&&|\\|\\||[;&|]|\\n)\\s*/);\n\n\t// Map split positions back to original command segments.\n\t// We split the masked string to find operator positions, but return\n\t// the original (unmasked) segments so pattern matching sees real text.\n\tconst originalSegments: string[] = [];\n\tlet maskedIdx = 0;\n\n\tfor (const part of splits) {\n\t\t// Find the start of this part in the masked string\n\t\tconst startInMasked = masked.indexOf(part, maskedIdx);\n\t\tif (startInMasked === -1) {\n\t\t\t// Fallback: use the part as-is (shouldn't happen)\n\t\t\toriginalSegments.push(command.substring(maskedIdx, maskedIdx + part.length).trim());\n\t\t} else {\n\t\t\toriginalSegments.push(command.substring(startInMasked, startInMasked + part.length).trim());\n\t\t}\n\t\tmaskedIdx = startInMasked + part.length;\n\t}\n\n\treturn originalSegments.filter((s) => s.length > 0);\n}\n\n/**\n * Strip leading subshell/command-substitution wrappers from a segment\n * so that $(cmd), (cmd), and `cmd` are checked against patterns too.\n *\n * Handles both full-segment wrappers ($(cmd)) and inline substitutions\n * (result=$(cmd)) by extracting inner commands.\n */\nfunction stripSubshellWrapper(segment: string): string {\n\t// Strip $(...) wrapper when it's the whole segment\n\tif (/^\\$\\(/.test(segment) && segment.endsWith(\")\")) {\n\t\treturn segment.slice(2, -1).trim();\n\t}\n\t// Strip (...) wrapper (subshell) when it's the whole segment\n\tif (/^\\(/.test(segment) && segment.endsWith(\")\")) {\n\t\treturn segment.slice(1, -1).trim();\n\t}\n\t// Strip backtick wrapper when it's the whole segment\n\tif (/^`/.test(segment) && segment.endsWith(\"`\")) {\n\t\treturn segment.slice(1, -1).trim();\n\t}\n\t// Extract inner command from inline $() or backtick substitutions\n\t// e.g., \"result=$(git push --force)\" → \"git push --force\"\n\tconst inlineMatch = segment.match(/\\$\\(([^)]+)\\)/);\n\tif (inlineMatch) {\n\t\treturn inlineMatch[1].trim();\n\t}\n\tconst backtickMatch = segment.match(/`([^`]+)`/);\n\tif (backtickMatch) {\n\t\treturn backtickMatch[1].trim();\n\t}\n\treturn segment;\n}\n\n/**\n * Check whether a command matches any forbidden pattern.\n *\n * The command is split on shell operators (&&, ||, ;, |) with quoted content\n * masked to avoid false splits. Each segment is then stripped of subshell\n * wrappers ($(...), (...), `...`) and checked against patterns. Default\n * patterns are ^-anchored so they only match commands that start with the\n * dangerous command prefix.\n *\n * @returns The first matching pattern, or `undefined` if the command is allowed.\n */\nexport function isForbiddenCommand(command: string, extraPatterns?: string[]): string | undefined {\n\t// Guard against misconfigured settings (string instead of array)\n\tconst validatedExtras = Array.isArray(extraPatterns) ? extraPatterns : undefined;\n\tconst allPatterns = validatedExtras\n\t\t? [...DEFAULT_FORBIDDEN_PATTERNS, ...validatedExtras]\n\t\t: DEFAULT_FORBIDDEN_PATTERNS;\n\tconst segments = splitCommandSegments(command);\n\n\tfor (const segment of segments) {\n\t\t// Check both the raw segment and the subshell-unwrapped version\n\t\tconst toCheck = [segment, stripSubshellWrapper(segment)];\n\t\tfor (const text of toCheck) {\n\t\t\tfor (const pattern of allPatterns) {\n\t\t\t\ttry {\n\t\t\t\t\tconst re = new RegExp(pattern);\n\t\t\t\t\tif (re.test(text)) {\n\t\t\t\t\t\treturn pattern;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Invalid regex in user settings — skip it\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn undefined;\n}\n"]}
1
+ {"version":3,"file":"forbidden-commands.js","sourceRoot":"","sources":["../../src/core/forbidden-commands.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,yEAAyE;AACzE,MAAM,0BAA0B,GAAa;IAC5C,uBAAuB,EAAE,2BAA2B;IACpD,4BAA4B,EAAE,2CAA2C;IACzE,iBAAiB,EAAE,6BAA6B;IAChD,yBAAyB,EAAE,iEAAiE;IAC5F,6BAA6B,EAAE,+CAA+C;IAC9E,oCAAoC,EAAE,sDAAsD;IAC5F,6BAA6B,EAAE,mCAAmC;IAClE,mDAAmD,EAAE,2DAA2D;IAChH,uDAAuD,EAAE,8BAA8B;IACvF,OAAO,EAAE,gDAAgD;IACzD,mDAAmD,EAAE,sCAAsC;IAC3F,oEAAkE;IAClE,qFAAqF;IACrF,8GAA8G,EAAE,8BAA8B;IAC9I,+FAA+F,EAAE,wBAAwB;IACzH,wGAAwG,EAAE,oBAAoB;IAC9H,iGAAiG,EAAE,kBAAkB;IACrH,oGAAoG,EAAE,mBAAmB;IACzH,gHAAgH,EAAE,qBAAqB;CACvI,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,qBAAqB,GAAa;IACvC,gBAAgB,EAAE,0BAA0B;CAC5C,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,uBAAuB,GAAa;IACzC,6BAA6B;IAC7B,uCAAuC;IACvC,uDAAuD;IACvD,OAAO;IACP,mDAAmD;IACnD,uBAAuB;IACvB,4BAA4B;IAC5B,iBAAiB;IACjB,6BAA6B;IAC7B,gBAAgB,EAAE,YAAY;IAC9B,0CAA0C;IAC1C,8GAA8G;IAC9G,+FAA+F;IAC/F,wGAAwG;IACxG,iGAAiG;IACjG,oGAAoG;IACpG,gHAAgH;CAChH,CAAC;AAEF;;;;;;;;GAQG;AACH,SAAS,iBAAiB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,IAAI,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACtB,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;QAC5B,CAAC;IACF,CAAC;IAED,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,cAAc;AAAf,CAC3B;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,kBAAkB,CACjC,OAAe,EACf,aAAwB,EACsC;IAC9D,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAElC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACvC,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QAE7B,gCAAgC;QAChC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;YAAE,SAAS;QAE5C,MAAM,OAAO,GAAG,kBAAkB,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;QACxD,IAAI,OAAO,EAAE,CAAC;YACb,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QAC7C,CAAC;IACF,CAAC;IAED,OAAO,SAAS,CAAC;AAAA,CACjB","sourcesContent":["/**\n * Forbidden-commands guard — blocks bash commands matching dangerous patterns\n * before they reach the shell.\n *\n * Hardcoded default patterns are ALWAYS active regardless of settings.\n * Users can add additional patterns via settings.forbiddenCommands.\n *\n * Commands are split on shell operators (&&, ||, ;, |, &) and each segment\n * is checked independently. Default patterns are anchored to the start of\n * each segment (^) so they only match commands that *begin with* the dangerous\n * command, not commands that merely *mention* the pattern in string literals\n * or arguments.\n *\n * To avoid false positives from operators inside quoted strings, content\n * within single/double quotes is masked before splitting. To catch subshell\n * wrappers like $(cmd) and (cmd), leading wrapper characters are stripped\n * from each segment before pattern matching.\n */\n\n/** Hardcoded patterns that are always active. Always anchored with ^. */\nconst DEFAULT_FORBIDDEN_PATTERNS: string[] = [\n\t\"^gh pr merge.*--admin\", // bypass branch protection\n\t\"^git push.*(-f\\\\b|--force)\", // force push (includes --force-with-lease)\n\t\"^gh api.*bypass\", // API calls with bypass flag\n\t\"^(?:export\\\\s+)?HUSKY=0\", // bypass pre-commit hooks (anchored with optional export prefix)\n\t\"^git\\\\s+commit.*--no-verify\", // bypass pre-commit hooks via --no-verify flag\n\t\"^(?:export\\\\s+)?SKIP_?VALIDATION=1\", // bypass pre-commit hooks via SKIP_VALIDATION env var\n\t\"^rm\\\\s+.*--no-preserve-root\", // rm with explicit safety override\n\t\"^rm\\\\s+.*\\\\s[\\\"']?/(\\\\*|[\\\\w.-]+/?)?[\\\"']?(\\\\s|$)\", // rm targeting root or top-level dirs (/, /*, /home, /etc)\n\t\"^dd\\\\s+.*of=/dev/(sd|hd|vd|nvme|xvd|loop|mmcblk|disk)\", // dd writing to block devices\n\t\"^mkfs\", // format filesystem (mkfs.ext4, mkfs.xfs, etc.)\n\t\"^>>?\\\\s*/dev/(sd|hd|vd|nvme|xvd|loop|mmcblk|disk)\", // redirect to block device (> and >>)\n\t// Sensitive file access — block reading credential files via bash\n\t// Matches bare commands AND absolute-path invocations (/bin/cat, /usr/bin/cat, etc.)\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*(?:~|\\\\.ssh)/id_(?!.*\\\\.pub\\\\b)\", // SSH private keys (not .pub)\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.dreb/secrets/\", // dreb credential store\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.dreb/agent/auth\\\\.json\", // dreb auth storage\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.aws/credentials\", // AWS credentials\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.gnupg/private-keys\", // GPG private keys\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.config/gcloud/credentials\\\\.db\", // GCloud credentials\n];\n\n/**\n * Patterns checked against the full (quote-masked) command string before\n * splitting into segments. These catch dangerous constructs that span\n * shell operators and would be fragmented by the segment splitter.\n *\n * Matched against the masked string so quoted content doesn't trigger\n * false positives (e.g., `echo \":(){ :|:& };:\"` is safe).\n */\nconst FULL_COMMAND_PATTERNS: string[] = [\n\t\":\\\\(\\\\)\\\\s*\\\\{\", // fork bomb :(){ :|:& };:\n];\n\n/**\n * Patterns also checked against content extracted from within quoted strings.\n * Catches commands like `echo \"rm -rf /\"` where the quoted content is a\n * destructive command that could be piped to execution via `| bash`.\n *\n * These are intentionally limited to destructive/dangerous patterns — env var\n * patterns like HUSKY=0 are excluded because they appear legitimately in\n * contexts like `git log --grep=\"HUSKY=0\"`.\n *\n * The fork bomb pattern from FULL_COMMAND_PATTERNS is included here because\n * it also needs to be caught when quoted (e.g., `echo \":(){ :|:& };:\"`).\n */\nconst QUOTED_CONTENT_PATTERNS: string[] = [\n\t\"^rm\\\\s+.*--no-preserve-root\",\n\t\"^rm\\\\s+.*\\\\s/(\\\\*|[\\\\w.-]+/?)?(\\\\s|$)\",\n\t\"^dd\\\\s+.*of=/dev/(sd|hd|vd|nvme|xvd|loop|mmcblk|disk)\",\n\t\"^mkfs\",\n\t\"^>>?\\\\s*/dev/(sd|hd|vd|nvme|xvd|loop|mmcblk|disk)\",\n\t\"^gh pr merge.*--admin\",\n\t\"^git push.*(-f\\\\b|--force)\",\n\t\"^gh api.*bypass\",\n\t\"^git\\\\s+commit.*--no-verify\",\n\t\":\\\\(\\\\)\\\\s*\\\\{\", // fork bomb\n\t// Sensitive file access in quoted content\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*(?:~|\\\\.ssh)/id_(?!.*\\\\.pub\\\\b)\",\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.dreb/secrets/\",\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.dreb/agent/auth\\\\.json\",\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.aws/credentials\",\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.gnupg/private-keys\",\n\t\"^(?:/\\\\S+/)?(?:cat|head|tail|less|more|strings|grep|sed|awk|base64|xxd)\\\\s+.*\\\\.config/gcloud/credentials\\\\.db\",\n];\n\n/**\n * Mask content inside single and double-quoted strings by replacing\n * characters within quotes with underscores. This prevents shell operators\n * inside quoted strings from causing false splits.\n *\n * Handles escaped quotes (\\\", \\') within strings. Correctly counts\n * consecutive backslashes before a quote — an even count means the quote\n * is real (e.g. `\\\\\"` is escaped-backslash + closing quote).\n */\nfunction maskQuotedContent(command: string): string {\n\tlet result = \"\";\n\tlet inSingle = false;\n\tlet inDouble = false;\n\n\tfor (let i = 0; i < command.length; i++) {\n\t\tconst ch = command[i];\n\n\t\tif (ch === \"'\" && !inDouble) {\n\t\t\t// In bash, single-quoted strings are completely literal — backslashes\n\t\t\t// have no escape function inside single quotes. Always toggle.\n\t\t\tinSingle = !inSingle;\n\t\t\tresult += ch;\n\t\t} else if (ch === '\"' && !inSingle) {\n\t\t\tif (!isEscaped(command, i)) {\n\t\t\t\tinDouble = !inDouble;\n\t\t\t}\n\t\t\tresult += ch;\n\t\t} else if (inSingle || inDouble) {\n\t\t\t// Replace content inside quotes with a safe character\n\t\t\t// that won't match shell operators\n\t\t\tresult += ch === \"\\n\" ? \"\\n\" : \"_\";\n\t\t} else {\n\t\t\tresult += ch;\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Check if the character at position `i` is escaped by counting consecutive\n * trailing backslashes. If the count is odd, the character is escaped.\n * If even (including zero), it is not escaped.\n *\n * e.g. `\\\\\"` → 2 backslashes → even → `\"` is NOT escaped (real quote)\n * `\\\\\\\"` → 3 backslashes → odd → `\"` IS escaped (literal quote)\n */\nfunction isEscaped(str: string, i: number): boolean {\n\tlet count = 0;\n\tlet j = i - 1;\n\twhile (j >= 0 && str[j] === \"\\\\\") {\n\t\tcount++;\n\t\tj--;\n\t}\n\treturn count % 2 === 1;\n}\n\n/**\n * Extract text content from within quoted strings in a segment.\n * Used to catch commands like `echo \"rm -rf /\" | bash` where dangerous\n * content is hidden inside quotes. The normal segment check won't catch\n * this because `echo` (not `rm`) starts the segment. By extracting the\n * quoted content and checking it separately, we block segments that\n * contain forbidden commands in their quoted arguments.\n */\nfunction extractQuotedContent(text: string): string[] {\n\tconst results: string[] = [];\n\tlet inQuote: string | null = null;\n\tlet start = -1;\n\n\tfor (let i = 0; i < text.length; i++) {\n\t\tconst ch = text[i];\n\t\tif ((ch === '\"' || ch === \"'\") && (ch === \"'\" || !isEscaped(text, i))) {\n\t\t\tif (inQuote === null) {\n\t\t\t\tinQuote = ch;\n\t\t\t\tstart = i + 1;\n\t\t\t} else if (ch === inQuote) {\n\t\t\t\tconst content = text.substring(start, i).trim();\n\t\t\t\tif (content.length > 0) {\n\t\t\t\t\tresults.push(content);\n\t\t\t\t}\n\t\t\t\tinQuote = null;\n\t\t\t}\n\t\t}\n\t}\n\treturn results;\n}\n\n/**\n * Split a command string into individual segments on shell operators.\n *\n * Handles: &&, ||, ;, |, & (background), and newlines.\n * Content inside single/double quotes is masked before splitting so that\n * operators inside quoted strings don't cause false splits.\n * Each segment is trimmed of leading whitespace.\n */\nfunction splitCommandSegments(command: string): string[] {\n\t// Mask quoted content to avoid splitting on operators inside strings\n\tconst masked = maskQuotedContent(command);\n\n\t// Split on shell operators: &&, ||, ;, |, &, and newlines\n\tconst splits = masked.split(/\\s*(?:&&|\\|\\||[;&|]|\\n)\\s*/);\n\n\t// Map split positions back to original command segments.\n\t// We split the masked string to find operator positions, but return\n\t// the original (unmasked) segments so pattern matching sees real text.\n\tconst originalSegments: string[] = [];\n\tlet maskedIdx = 0;\n\n\tfor (const part of splits) {\n\t\t// Find the start of this part in the masked string\n\t\tconst startInMasked = masked.indexOf(part, maskedIdx);\n\t\tif (startInMasked === -1) {\n\t\t\t// Fallback: use the part as-is (shouldn't happen)\n\t\t\toriginalSegments.push(command.substring(maskedIdx, maskedIdx + part.length).trim());\n\t\t} else {\n\t\t\toriginalSegments.push(command.substring(startInMasked, startInMasked + part.length).trim());\n\t\t}\n\t\tmaskedIdx = startInMasked + part.length;\n\t}\n\n\treturn originalSegments.filter((s) => s.length > 0);\n}\n\n/**\n * Strip leading subshell/command-substitution wrappers from a segment\n * so that $(cmd), (cmd), and `cmd` are checked against patterns too.\n *\n * Handles both full-segment wrappers ($(cmd)) and inline substitutions\n * (result=$(cmd)) by extracting inner commands.\n */\nfunction stripSubshellWrapper(segment: string): string {\n\t// Strip $(...) wrapper when it's the whole segment\n\tif (/^\\$\\(/.test(segment) && segment.endsWith(\")\")) {\n\t\treturn segment.slice(2, -1).trim();\n\t}\n\t// Strip (...) wrapper (subshell) when it's the whole segment\n\tif (/^\\(/.test(segment) && segment.endsWith(\")\")) {\n\t\treturn segment.slice(1, -1).trim();\n\t}\n\t// Strip backtick wrapper when it's the whole segment\n\tif (/^`/.test(segment) && segment.endsWith(\"`\")) {\n\t\treturn segment.slice(1, -1).trim();\n\t}\n\t// Extract inner command from inline $() or backtick substitutions\n\t// e.g., \"result=$(git push --force)\" → \"git push --force\"\n\tconst inlineMatch = segment.match(/\\$\\(([^)]+)\\)/);\n\tif (inlineMatch) {\n\t\treturn inlineMatch[1].trim();\n\t}\n\tconst backtickMatch = segment.match(/`([^`]+)`/);\n\tif (backtickMatch) {\n\t\treturn backtickMatch[1].trim();\n\t}\n\treturn segment;\n}\n\n/**\n * Check whether a command matches any forbidden pattern.\n *\n * The command is split on shell operators (&&, ||, ;, |) with quoted content\n * masked to avoid false splits. Each segment is then stripped of subshell\n * wrappers ($(...), (...), `...`) and checked against patterns. Default\n * patterns are ^-anchored so they only match commands that start with the\n * dangerous command prefix.\n *\n * @returns The first matching pattern, or `undefined` if the command is allowed.\n */\nexport function isForbiddenCommand(command: string, extraPatterns?: string[]): string | undefined {\n\t// Guard against misconfigured settings (string instead of array)\n\tconst validatedExtras = Array.isArray(extraPatterns) ? extraPatterns : undefined;\n\tconst allPatterns = validatedExtras\n\t\t? [...DEFAULT_FORBIDDEN_PATTERNS, ...validatedExtras]\n\t\t: DEFAULT_FORBIDDEN_PATTERNS;\n\n\t// Pre-split check: match full-command patterns against the quote-masked\n\t// string to catch constructs that span shell operators (e.g., fork bombs).\n\t// Using the masked string prevents false positives from quoted content.\n\tconst masked = maskQuotedContent(command);\n\tfor (const pattern of FULL_COMMAND_PATTERNS) {\n\t\ttry {\n\t\t\tconst re = new RegExp(pattern);\n\t\t\tif (re.test(masked)) {\n\t\t\t\treturn pattern;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Invalid regex — skip\n\t\t}\n\t}\n\n\tconst segments = splitCommandSegments(command);\n\n\t// Combine quoted-content patterns with any user extras for quoted checking\n\tconst allQuotedPatterns = validatedExtras\n\t\t? [...QUOTED_CONTENT_PATTERNS, ...validatedExtras]\n\t\t: QUOTED_CONTENT_PATTERNS;\n\n\tfor (const segment of segments) {\n\t\t// Check both the raw segment and the subshell-unwrapped version\n\t\tconst toCheck = [segment, stripSubshellWrapper(segment)];\n\t\tfor (const text of toCheck) {\n\t\t\tfor (const pattern of allPatterns) {\n\t\t\t\ttry {\n\t\t\t\t\tconst re = new RegExp(pattern);\n\t\t\t\t\tif (re.test(text)) {\n\t\t\t\t\t\treturn pattern;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Invalid regex in user settings — skip it\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check content within quotes for embedded dangerous commands.\n\t\t// There is no legitimate reason for an agent to output/echo forbidden\n\t\t// commands, and quoted content could be piped to execution via | bash.\n\t\tconst quotedContent = extractQuotedContent(segment);\n\t\tfor (const content of quotedContent) {\n\t\t\tfor (const pattern of allQuotedPatterns) {\n\t\t\t\ttry {\n\t\t\t\t\tconst re = new RegExp(pattern);\n\t\t\t\t\tif (re.test(content)) {\n\t\t\t\t\t\treturn pattern;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Invalid regex — skip\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Extract file paths from a command that executes a script file.\n * Detects: `bash file`, `sh file`, `source file`, `. file`, and input\n * redirects like `bash < file`.\n *\n * Returns an array of file paths (usually 0 or 1). Does not check whether\n * the files exist — the caller handles that.\n *\n * @returns Array of script file paths referenced by the command.\n */\nexport function extractScriptPaths(command: string): string[] {\n\tconst paths: string[] = [];\n\tconst segments = splitCommandSegments(command);\n\n\tfor (const segment of segments) {\n\t\tconst trimmed = segment.trim();\n\n\t\t// bash < file.sh (input redirect) — check before shell exec to avoid\n\t\t// the shell exec regex matching \"<\" as a filename\n\t\tconst redirectMatch = trimmed.match(/^(?:bash|sh|zsh|ksh)(?:\\s+-\\S+)*\\s+<\\s*(\\S+)/);\n\t\tif (redirectMatch?.[1]) {\n\t\t\tpaths.push(redirectMatch[1]);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// bash [flags] file.sh, sh [flags] file.sh\n\t\t// Flags are short options like -x, -e, -ex, etc.\n\t\t// Exclude -c (inline command — handled by quoted content check)\n\t\tif (/^(?:bash|sh|zsh|ksh)\\s+-c\\b/.test(trimmed)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst shellExecMatch = trimmed.match(/^(?:bash|sh|zsh|ksh)\\s+(?:-\\S+\\s+)*(\\S+)/);\n\t\tif (shellExecMatch) {\n\t\t\tconst filePath = shellExecMatch[1];\n\t\t\tif (filePath && !filePath.startsWith(\"-\")) {\n\t\t\t\tpaths.push(filePath);\n\t\t\t}\n\t\t}\n\n\t\t// source file.sh, . file.sh\n\t\tconst sourceMatch = trimmed.match(/^(?:source|\\.)\\s+(\\S+)/);\n\t\tif (sourceMatch?.[1]) {\n\t\t\tpaths.push(sourceMatch[1]);\n\t\t}\n\t}\n\n\treturn [...new Set(paths)]; // deduplicate\n}\n\n/**\n * Check file content line-by-line for forbidden commands.\n * Each non-empty, non-comment line is passed through `isForbiddenCommand`.\n *\n * This is a pure function — the caller is responsible for reading the file\n * and passing the content string.\n *\n * @returns The first match with pattern, line number, and line text, or undefined.\n */\nexport function checkScriptContent(\n\tcontent: string,\n\textraPatterns?: string[],\n): { pattern: string; line: number; text: string } | undefined {\n\tconst lines = content.split(\"\\n\");\n\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst line = lines[i].trim();\n\n\t\t// Skip empty lines and comments\n\t\tif (!line || line.startsWith(\"#\")) continue;\n\n\t\tconst pattern = isForbiddenCommand(line, extraPatterns);\n\t\tif (pattern) {\n\t\t\treturn { pattern, line: i + 1, text: line };\n\t\t}\n\t}\n\n\treturn undefined;\n}\n"]}
@@ -0,0 +1,11 @@
1
+ export interface SecretPattern {
2
+ name: string;
3
+ pattern: RegExp;
4
+ }
5
+ export interface ScrubResult {
6
+ scrubbed: string;
7
+ redactionCount: number;
8
+ }
9
+ export declare const DEFAULT_SECRET_PATTERNS: SecretPattern[];
10
+ export declare function scrubSecrets(text: string, extraPatterns?: SecretPattern[]): ScrubResult;
11
+ //# sourceMappingURL=secret-scrubber.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret-scrubber.d.ts","sourceRoot":"","sources":["../../src/core/secret-scrubber.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,aAAa;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,WAAW;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,MAAM,CAAC;CACvB;AAkCD,eAAO,MAAM,uBAAuB,EAAE,aAAa,EAAoD,CAAC;AAExG,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,aAAa,EAAE,GAAG,WAAW,CAuCvF","sourcesContent":["export interface SecretPattern {\n\tname: string;\n\tpattern: RegExp;\n}\n\nexport interface ScrubResult {\n\tscrubbed: string;\n\tredactionCount: number;\n}\n\n// Multi-line patterns (processed first)\nconst pemPrivateKey =\n\t/-----BEGIN (?:RSA |EC |DSA |ENCRYPTED )?PRIVATE KEY-----[\\s\\S]*?-----END (?:RSA |EC |DSA |ENCRYPTED )?PRIVATE KEY-----/g;\nconst opensshPrivateKey = /-----BEGIN OPENSSH PRIVATE KEY-----[\\s\\S]*?-----END OPENSSH PRIVATE KEY-----/g;\n\n// Single-line patterns\nconst awsAccessKey = /\\bAKIA[0-9A-Z]{16}\\b/g;\nconst githubToken =\n\t/ghp_[A-Za-z0-9_]{36,}|gho_[A-Za-z0-9_]{36,}|ghu_[A-Za-z0-9_]{36,}|ghs_[A-Za-z0-9_]{36,}|ghr_[A-Za-z0-9_]{36,}|github_pat_[A-Za-z0-9_]{22,}/g;\nconst gitlabToken = /glpat-[0-9a-zA-Z_-]{20,}/g;\nconst anthropicKey = /sk-ant-[a-zA-Z0-9_-]{90,}/g;\nconst openaiKey = /sk-(?!ant-)[a-zA-Z0-9_-]{20,}/g;\nconst slackToken = /xox[baprs]-[0-9a-zA-Z-]{10,}/g;\nconst stripeKey = /[sr]k_(?:test|live)_[0-9a-zA-Z]{24,}/g;\nconst urlCredentials = /(https?:\\/\\/)([^\\s:]+):([^\\s@]+)@/g;\n\nconst MULTILINE_PATTERNS: SecretPattern[] = [\n\t{ name: \"pem_private_key\", pattern: pemPrivateKey },\n\t{ name: \"openssh_private_key\", pattern: opensshPrivateKey },\n];\n\nconst SINGLELINE_PATTERNS: SecretPattern[] = [\n\t{ name: \"aws_access_key\", pattern: awsAccessKey },\n\t{ name: \"github_token\", pattern: githubToken },\n\t{ name: \"gitlab_token\", pattern: gitlabToken },\n\t{ name: \"anthropic_key\", pattern: anthropicKey },\n\t{ name: \"openai_key\", pattern: openaiKey },\n\t{ name: \"slack_token\", pattern: slackToken },\n\t{ name: \"stripe_key\", pattern: stripeKey },\n\t{ name: \"url_credentials\", pattern: urlCredentials },\n];\n\nexport const DEFAULT_SECRET_PATTERNS: SecretPattern[] = [...MULTILINE_PATTERNS, ...SINGLELINE_PATTERNS];\n\nexport function scrubSecrets(text: string, extraPatterns?: SecretPattern[]): ScrubResult {\n\tlet scrubbed = text;\n\tlet redactionCount = 0;\n\n\tfunction applyPattern(sp: SecretPattern): void {\n\t\t// Reset lastIndex since we reuse compiled regexes\n\t\tsp.pattern.lastIndex = 0;\n\n\t\tif (sp.name === \"url_credentials\") {\n\t\t\tscrubbed = scrubbed.replace(sp.pattern, (_match, protocol, user, _password) => {\n\t\t\t\tredactionCount++;\n\t\t\t\treturn `${protocol}${user}:<REDACTED:url_credentials>@`;\n\t\t\t});\n\t\t} else {\n\t\t\tscrubbed = scrubbed.replace(sp.pattern, () => {\n\t\t\t\tredactionCount++;\n\t\t\t\treturn `<REDACTED:${sp.name}>`;\n\t\t\t});\n\t\t}\n\t}\n\n\t// Multi-line patterns first\n\tfor (const sp of MULTILINE_PATTERNS) {\n\t\tapplyPattern(sp);\n\t}\n\n\t// Single-line patterns\n\tfor (const sp of SINGLELINE_PATTERNS) {\n\t\tapplyPattern(sp);\n\t}\n\n\t// Extra patterns last\n\tif (extraPatterns) {\n\t\tfor (const sp of extraPatterns) {\n\t\t\tapplyPattern(sp);\n\t\t}\n\t}\n\n\treturn { scrubbed, redactionCount };\n}\n"]}
@@ -0,0 +1,63 @@
1
+ // Multi-line patterns (processed first)
2
+ const pemPrivateKey = /-----BEGIN (?:RSA |EC |DSA |ENCRYPTED )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |DSA |ENCRYPTED )?PRIVATE KEY-----/g;
3
+ const opensshPrivateKey = /-----BEGIN OPENSSH PRIVATE KEY-----[\s\S]*?-----END OPENSSH PRIVATE KEY-----/g;
4
+ // Single-line patterns
5
+ const awsAccessKey = /\bAKIA[0-9A-Z]{16}\b/g;
6
+ const githubToken = /ghp_[A-Za-z0-9_]{36,}|gho_[A-Za-z0-9_]{36,}|ghu_[A-Za-z0-9_]{36,}|ghs_[A-Za-z0-9_]{36,}|ghr_[A-Za-z0-9_]{36,}|github_pat_[A-Za-z0-9_]{22,}/g;
7
+ const gitlabToken = /glpat-[0-9a-zA-Z_-]{20,}/g;
8
+ const anthropicKey = /sk-ant-[a-zA-Z0-9_-]{90,}/g;
9
+ const openaiKey = /sk-(?!ant-)[a-zA-Z0-9_-]{20,}/g;
10
+ const slackToken = /xox[baprs]-[0-9a-zA-Z-]{10,}/g;
11
+ const stripeKey = /[sr]k_(?:test|live)_[0-9a-zA-Z]{24,}/g;
12
+ const urlCredentials = /(https?:\/\/)([^\s:]+):([^\s@]+)@/g;
13
+ const MULTILINE_PATTERNS = [
14
+ { name: "pem_private_key", pattern: pemPrivateKey },
15
+ { name: "openssh_private_key", pattern: opensshPrivateKey },
16
+ ];
17
+ const SINGLELINE_PATTERNS = [
18
+ { name: "aws_access_key", pattern: awsAccessKey },
19
+ { name: "github_token", pattern: githubToken },
20
+ { name: "gitlab_token", pattern: gitlabToken },
21
+ { name: "anthropic_key", pattern: anthropicKey },
22
+ { name: "openai_key", pattern: openaiKey },
23
+ { name: "slack_token", pattern: slackToken },
24
+ { name: "stripe_key", pattern: stripeKey },
25
+ { name: "url_credentials", pattern: urlCredentials },
26
+ ];
27
+ export const DEFAULT_SECRET_PATTERNS = [...MULTILINE_PATTERNS, ...SINGLELINE_PATTERNS];
28
+ export function scrubSecrets(text, extraPatterns) {
29
+ let scrubbed = text;
30
+ let redactionCount = 0;
31
+ function applyPattern(sp) {
32
+ // Reset lastIndex since we reuse compiled regexes
33
+ sp.pattern.lastIndex = 0;
34
+ if (sp.name === "url_credentials") {
35
+ scrubbed = scrubbed.replace(sp.pattern, (_match, protocol, user, _password) => {
36
+ redactionCount++;
37
+ return `${protocol}${user}:<REDACTED:url_credentials>@`;
38
+ });
39
+ }
40
+ else {
41
+ scrubbed = scrubbed.replace(sp.pattern, () => {
42
+ redactionCount++;
43
+ return `<REDACTED:${sp.name}>`;
44
+ });
45
+ }
46
+ }
47
+ // Multi-line patterns first
48
+ for (const sp of MULTILINE_PATTERNS) {
49
+ applyPattern(sp);
50
+ }
51
+ // Single-line patterns
52
+ for (const sp of SINGLELINE_PATTERNS) {
53
+ applyPattern(sp);
54
+ }
55
+ // Extra patterns last
56
+ if (extraPatterns) {
57
+ for (const sp of extraPatterns) {
58
+ applyPattern(sp);
59
+ }
60
+ }
61
+ return { scrubbed, redactionCount };
62
+ }
63
+ //# sourceMappingURL=secret-scrubber.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret-scrubber.js","sourceRoot":"","sources":["../../src/core/secret-scrubber.ts"],"names":[],"mappings":"AAUA,wCAAwC;AACxC,MAAM,aAAa,GAClB,yHAAyH,CAAC;AAC3H,MAAM,iBAAiB,GAAG,+EAA+E,CAAC;AAE1G,uBAAuB;AACvB,MAAM,YAAY,GAAG,uBAAuB,CAAC;AAC7C,MAAM,WAAW,GAChB,6IAA6I,CAAC;AAC/I,MAAM,WAAW,GAAG,2BAA2B,CAAC;AAChD,MAAM,YAAY,GAAG,4BAA4B,CAAC;AAClD,MAAM,SAAS,GAAG,gCAAgC,CAAC;AACnD,MAAM,UAAU,GAAG,+BAA+B,CAAC;AACnD,MAAM,SAAS,GAAG,uCAAuC,CAAC;AAC1D,MAAM,cAAc,GAAG,oCAAoC,CAAC;AAE5D,MA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,EAAE,CAAC;gBACjB,OAAO,GAAG,QAAQ,GAAG,IAAI,8BAA8B,CAAC;YAAA,CACxD,CAAC,CAAC;QACJ,CAAC;aAAM,CAAC;YACP,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC;gBAC7C,cAAc,EAAE,CAAC;gBACjB,OAAO,aAAa,EAAE,CAAC,IAAI,GAAG,CAAC;YAAA,CAC/B,CAAC,CAAC;QACJ,CAAC;IAAA,CACD;IAED,4BAA4B;IAC5B,KAAK,MAAM,EAAE,IAAI,kBAAkB,EAAE,CAAC;QACrC,YAAY,CAAC,EAAE,CAAC,CAAC;IAClB,CAAC;IAED,uBAAuB;IACvB,KAAK,MAAM,EAAE,IAAI,mBAAmB,EAAE,CAAC;QACtC,YAAY,CAAC,EAAE,CAAC,CAAC;IAClB,CAAC;IAED,sBAAsB;IACtB,IAAI,aAAa,EAAE,CAAC;QACnB,KAAK,MAAM,EAAE,IAAI,aAAa,EAAE,CAAC;YAChC,YAAY,CAAC,EAAE,CAAC,CAAC;QAClB,CAAC;IACF,CAAC;IAED,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,CAAC;AAAA,CACpC","sourcesContent":["export interface SecretPattern {\n\tname: string;\n\tpattern: RegExp;\n}\n\nexport interface ScrubResult {\n\tscrubbed: string;\n\tredactionCount: number;\n}\n\n// Multi-line patterns (processed first)\nconst pemPrivateKey =\n\t/-----BEGIN (?:RSA |EC |DSA |ENCRYPTED )?PRIVATE KEY-----[\\s\\S]*?-----END (?:RSA |EC |DSA |ENCRYPTED )?PRIVATE KEY-----/g;\nconst opensshPrivateKey = /-----BEGIN OPENSSH PRIVATE KEY-----[\\s\\S]*?-----END OPENSSH PRIVATE KEY-----/g;\n\n// Single-line patterns\nconst awsAccessKey = /\\bAKIA[0-9A-Z]{16}\\b/g;\nconst githubToken =\n\t/ghp_[A-Za-z0-9_]{36,}|gho_[A-Za-z0-9_]{36,}|ghu_[A-Za-z0-9_]{36,}|ghs_[A-Za-z0-9_]{36,}|ghr_[A-Za-z0-9_]{36,}|github_pat_[A-Za-z0-9_]{22,}/g;\nconst gitlabToken = /glpat-[0-9a-zA-Z_-]{20,}/g;\nconst anthropicKey = /sk-ant-[a-zA-Z0-9_-]{90,}/g;\nconst openaiKey = /sk-(?!ant-)[a-zA-Z0-9_-]{20,}/g;\nconst slackToken = /xox[baprs]-[0-9a-zA-Z-]{10,}/g;\nconst stripeKey = /[sr]k_(?:test|live)_[0-9a-zA-Z]{24,}/g;\nconst urlCredentials = /(https?:\\/\\/)([^\\s:]+):([^\\s@]+)@/g;\n\nconst MULTILINE_PATTERNS: SecretPattern[] = [\n\t{ name: \"pem_private_key\", pattern: pemPrivateKey },\n\t{ name: \"openssh_private_key\", pattern: opensshPrivateKey },\n];\n\nconst SINGLELINE_PATTERNS: SecretPattern[] = [\n\t{ name: \"aws_access_key\", pattern: awsAccessKey },\n\t{ name: \"github_token\", pattern: githubToken },\n\t{ name: \"gitlab_token\", pattern: gitlabToken },\n\t{ name: \"anthropic_key\", pattern: anthropicKey },\n\t{ name: \"openai_key\", pattern: openaiKey },\n\t{ name: \"slack_token\", pattern: slackToken },\n\t{ name: \"stripe_key\", pattern: stripeKey },\n\t{ name: \"url_credentials\", pattern: urlCredentials },\n];\n\nexport const DEFAULT_SECRET_PATTERNS: SecretPattern[] = [...MULTILINE_PATTERNS, ...SINGLELINE_PATTERNS];\n\nexport function scrubSecrets(text: string, extraPatterns?: SecretPattern[]): ScrubResult {\n\tlet scrubbed = text;\n\tlet redactionCount = 0;\n\n\tfunction applyPattern(sp: SecretPattern): void {\n\t\t// Reset lastIndex since we reuse compiled regexes\n\t\tsp.pattern.lastIndex = 0;\n\n\t\tif (sp.name === \"url_credentials\") {\n\t\t\tscrubbed = scrubbed.replace(sp.pattern, (_match, protocol, user, _password) => {\n\t\t\t\tredactionCount++;\n\t\t\t\treturn `${protocol}${user}:<REDACTED:url_credentials>@`;\n\t\t\t});\n\t\t} else {\n\t\t\tscrubbed = scrubbed.replace(sp.pattern, () => {\n\t\t\t\tredactionCount++;\n\t\t\t\treturn `<REDACTED:${sp.name}>`;\n\t\t\t});\n\t\t}\n\t}\n\n\t// Multi-line patterns first\n\tfor (const sp of MULTILINE_PATTERNS) {\n\t\tapplyPattern(sp);\n\t}\n\n\t// Single-line patterns\n\tfor (const sp of SINGLELINE_PATTERNS) {\n\t\tapplyPattern(sp);\n\t}\n\n\t// Extra patterns last\n\tif (extraPatterns) {\n\t\tfor (const sp of extraPatterns) {\n\t\t\tapplyPattern(sp);\n\t\t}\n\t}\n\n\treturn { scrubbed, redactionCount };\n}\n"]}
@@ -0,0 +1,16 @@
1
+ export interface SensitivePathResult {
2
+ blocked: boolean;
3
+ pattern?: string;
4
+ }
5
+ export declare const DEFAULT_SENSITIVE_PATTERNS: string[];
6
+ /**
7
+ * Check whether a file path points to a sensitive credential file.
8
+ *
9
+ * Resolves the input to an absolute, normalized path (expanding `~`),
10
+ * then checks against built-in and optional extra patterns.
11
+ *
12
+ * SSH public keys (`*.pub`) are explicitly allowlisted even though
13
+ * they match the `~/.ssh/id_*` pattern.
14
+ */
15
+ export declare function isSensitivePath(filepath: string, extraPatterns?: string[]): SensitivePathResult;
16
+ //# sourceMappingURL=sensitive-paths.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sensitive-paths.d.ts","sourceRoot":"","sources":["../../src/core/sensitive-paths.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,mBAAmB;IACnC,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,eAAO,MAAM,0BAA0B,EAAE,MAAM,EAO9C,CAAC;AA8DF;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,EAAE,GAAG,mBAAmB,CAgC/F","sourcesContent":["import { homedir } from \"node:os\";\nimport { normalize, resolve } from \"node:path\";\n\nexport interface SensitivePathResult {\n\tblocked: boolean;\n\tpattern?: string;\n}\n\nexport const DEFAULT_SENSITIVE_PATTERNS: string[] = [\n\t\"~/.ssh/id_*\",\n\t\"~/.gnupg/private-keys-v1.d/*\",\n\t\"~/.dreb/secrets/*\",\n\t\"~/.dreb/agent/auth.json\",\n\t\"~/.aws/credentials\",\n\t\"~/.config/gcloud/credentials.db\",\n];\n\nconst SSH_PUB_SUFFIX = \".pub\";\n\n/**\n * Expand `~` or `~/` prefix to the user's home directory.\n */\nfunction expandHome(filepath: string): string {\n\tif (filepath === \"~\") return homedir();\n\tif (filepath.startsWith(\"~/\")) return `${homedir()}/${filepath.slice(2)}`;\n\treturn filepath;\n}\n\n/**\n * Resolve and normalize a path, expanding `~` to the real home directory.\n * This defeats traversal attacks like `../../.ssh/id_rsa`.\n */\nfunction resolvePath(filepath: string): string {\n\treturn normalize(resolve(expandHome(filepath)));\n}\n\n/**\n * Check whether a pattern contains unsupported mid-path wildcards.\n * Only trailing wildcards are supported. Mid-path wildcards silently fail.\n */\nfunction hasMidPathWildcard(pattern: string): boolean {\n\t// Strip trailing wildcard(s), then check if any wildcards remain\n\tconst withoutTrailing = pattern.replace(/\\/?\\*{1,2}$/, \"\");\n\treturn withoutTrailing.includes(\"*\");\n}\n\n/**\n * Check whether a single pattern matches a resolved absolute path.\n * Returns true if the path matches the pattern.\n *\n * Pattern types:\n * - Ends with `/*` or `/**` → directory prefix match\n * - Ends with `*` (but not `/*`) → prefix match on the literal prefix\n * - Otherwise → exact match\n *\n * Mid-path wildcards are NOT supported and will not match anything.\n * Use hasMidPathWildcard() to detect and warn about these before calling.\n */\nfunction matchesPattern(resolvedPath: string, pattern: string): boolean {\n\tconst expandedPattern = resolvePath(pattern.replace(/\\/?\\*{1,2}$/, \"\"));\n\n\t// Directory match: pattern ends with /* or /**\n\tif (pattern.endsWith(\"/**\") || pattern.endsWith(\"/*\")) {\n\t\tconst dirPrefix = expandedPattern.endsWith(\"/\") ? expandedPattern : `${expandedPattern}/`;\n\t\t// Match the directory itself or anything under it\n\t\treturn resolvedPath === expandedPattern || resolvedPath.startsWith(dirPrefix);\n\t}\n\n\t// Prefix match: pattern ends with * (e.g. ~/.ssh/id_*)\n\tif (pattern.endsWith(\"*\")) {\n\t\treturn resolvedPath.startsWith(expandedPattern);\n\t}\n\n\t// Exact match\n\treturn resolvedPath === resolvePath(pattern);\n}\n\n/**\n * Check whether a file path points to a sensitive credential file.\n *\n * Resolves the input to an absolute, normalized path (expanding `~`),\n * then checks against built-in and optional extra patterns.\n *\n * SSH public keys (`*.pub`) are explicitly allowlisted even though\n * they match the `~/.ssh/id_*` pattern.\n */\nexport function isSensitivePath(filepath: string, extraPatterns?: string[]): SensitivePathResult {\n\tconst resolved = resolvePath(filepath);\n\n\t// Check default patterns\n\tfor (const pattern of DEFAULT_SENSITIVE_PATTERNS) {\n\t\tif (matchesPattern(resolved, pattern)) {\n\t\t\t// Special case: SSH id_* pattern — allowlist .pub files\n\t\t\tif (pattern === \"~/.ssh/id_*\" && resolved.endsWith(SSH_PUB_SUFFIX)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn { blocked: true, pattern };\n\t\t}\n\t}\n\n\t// Check extra patterns\n\tif (extraPatterns) {\n\t\tfor (const pattern of extraPatterns) {\n\t\t\tif (hasMidPathWildcard(pattern)) {\n\t\t\t\t// Mid-path wildcards like ~/vaults/*/key.pem are not supported.\n\t\t\t\t// Skip with a console warning so misconfigurations are visible.\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[sensitive-paths] Skipping unsupported mid-path wildcard pattern: \"${pattern}\". Only trailing wildcards (e.g. \"~/.ssh/id_*\", \"~/.secrets/*\") are supported.`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (matchesPattern(resolved, pattern)) {\n\t\t\t\treturn { blocked: true, pattern };\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { blocked: false };\n}\n"]}