@dreb/coding-agent 2.8.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.
- package/CHANGELOG.md +2 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +52 -4
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/forbidden-commands.d.ts.map +1 -1
- package/dist/core/forbidden-commands.js +15 -0
- package/dist/core/forbidden-commands.js.map +1 -1
- package/dist/core/secret-scrubber.d.ts +11 -0
- package/dist/core/secret-scrubber.d.ts.map +1 -0
- package/dist/core/secret-scrubber.js +63 -0
- package/dist/core/secret-scrubber.js.map +1 -0
- package/dist/core/sensitive-paths.d.ts +16 -0
- package/dist/core/sensitive-paths.d.ts.map +1 -0
- package/dist/core/sensitive-paths.js +102 -0
- package/dist/core/sensitive-paths.js.map +1 -0
- package/dist/core/settings-manager.d.ts +10 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +6 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/docs/settings.md +30 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"forbidden-commands.d.ts","sourceRoot":"","sources":["../../src/core/forbidden-commands.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAmNH;;;;;;;;;;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];\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];\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"]}
|
|
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"]}
|
|
@@ -29,6 +29,14 @@ const DEFAULT_FORBIDDEN_PATTERNS = [
|
|
|
29
29
|
"^dd\\s+.*of=/dev/(sd|hd|vd|nvme|xvd|loop|mmcblk|disk)", // dd writing to block devices
|
|
30
30
|
"^mkfs", // format filesystem (mkfs.ext4, mkfs.xfs, etc.)
|
|
31
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
|
|
32
40
|
];
|
|
33
41
|
/**
|
|
34
42
|
* Patterns checked against the full (quote-masked) command string before
|
|
@@ -64,6 +72,13 @@ const QUOTED_CONTENT_PATTERNS = [
|
|
|
64
72
|
"^gh api.*bypass",
|
|
65
73
|
"^git\\s+commit.*--no-verify",
|
|
66
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",
|
|
67
82
|
];
|
|
68
83
|
/**
|
|
69
84
|
* Mask content inside single and double-quoted strings by replacing
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"forbidden-commands.js","sourceRoot":"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AM,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];\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];\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"]}
|
|
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;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Q,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;gBAC3C,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YACtB,CAAC;QACF,CAAC;QAED,4BAA4B;QAC5B,MAAM,WAAW,GAAG,OAAO,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC5D,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,MAAM,kBAAkB,GAAoB;IAC3C,EAAE,IAAI,EAAE,iBAAiB,EAAE,OAAO,EAAE,aAAa,EAAE;IACnD,EAAE,IAAI,EAAE,qBAAqB,EAAE,OAAO,EAAE,iBAAiB,EAAE;CAC3D,CAAC;AAEF,MAAM,mBAAmB,GAAoB;IAC5C,EAAE,IAAI,EAAE,gBAAgB,EAAE,OAAO,EAAE,YAAY,EAAE;IACjD,EAAE,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,WAAW,EAAE;IAC9C,EAAE,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,WAAW,EAAE;IAC9C,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO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C,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"]}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { normalize, resolve } from "node:path";
|
|
3
|
+
export const DEFAULT_SENSITIVE_PATTERNS = [
|
|
4
|
+
"~/.ssh/id_*",
|
|
5
|
+
"~/.gnupg/private-keys-v1.d/*",
|
|
6
|
+
"~/.dreb/secrets/*",
|
|
7
|
+
"~/.dreb/agent/auth.json",
|
|
8
|
+
"~/.aws/credentials",
|
|
9
|
+
"~/.config/gcloud/credentials.db",
|
|
10
|
+
];
|
|
11
|
+
const SSH_PUB_SUFFIX = ".pub";
|
|
12
|
+
/**
|
|
13
|
+
* Expand `~` or `~/` prefix to the user's home directory.
|
|
14
|
+
*/
|
|
15
|
+
function expandHome(filepath) {
|
|
16
|
+
if (filepath === "~")
|
|
17
|
+
return homedir();
|
|
18
|
+
if (filepath.startsWith("~/"))
|
|
19
|
+
return `${homedir()}/${filepath.slice(2)}`;
|
|
20
|
+
return filepath;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Resolve and normalize a path, expanding `~` to the real home directory.
|
|
24
|
+
* This defeats traversal attacks like `../../.ssh/id_rsa`.
|
|
25
|
+
*/
|
|
26
|
+
function resolvePath(filepath) {
|
|
27
|
+
return normalize(resolve(expandHome(filepath)));
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Check whether a pattern contains unsupported mid-path wildcards.
|
|
31
|
+
* Only trailing wildcards are supported. Mid-path wildcards silently fail.
|
|
32
|
+
*/
|
|
33
|
+
function hasMidPathWildcard(pattern) {
|
|
34
|
+
// Strip trailing wildcard(s), then check if any wildcards remain
|
|
35
|
+
const withoutTrailing = pattern.replace(/\/?\*{1,2}$/, "");
|
|
36
|
+
return withoutTrailing.includes("*");
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Check whether a single pattern matches a resolved absolute path.
|
|
40
|
+
* Returns true if the path matches the pattern.
|
|
41
|
+
*
|
|
42
|
+
* Pattern types:
|
|
43
|
+
* - Ends with `/*` or `/**` → directory prefix match
|
|
44
|
+
* - Ends with `*` (but not `/*`) → prefix match on the literal prefix
|
|
45
|
+
* - Otherwise → exact match
|
|
46
|
+
*
|
|
47
|
+
* Mid-path wildcards are NOT supported and will not match anything.
|
|
48
|
+
* Use hasMidPathWildcard() to detect and warn about these before calling.
|
|
49
|
+
*/
|
|
50
|
+
function matchesPattern(resolvedPath, pattern) {
|
|
51
|
+
const expandedPattern = resolvePath(pattern.replace(/\/?\*{1,2}$/, ""));
|
|
52
|
+
// Directory match: pattern ends with /* or /**
|
|
53
|
+
if (pattern.endsWith("/**") || pattern.endsWith("/*")) {
|
|
54
|
+
const dirPrefix = expandedPattern.endsWith("/") ? expandedPattern : `${expandedPattern}/`;
|
|
55
|
+
// Match the directory itself or anything under it
|
|
56
|
+
return resolvedPath === expandedPattern || resolvedPath.startsWith(dirPrefix);
|
|
57
|
+
}
|
|
58
|
+
// Prefix match: pattern ends with * (e.g. ~/.ssh/id_*)
|
|
59
|
+
if (pattern.endsWith("*")) {
|
|
60
|
+
return resolvedPath.startsWith(expandedPattern);
|
|
61
|
+
}
|
|
62
|
+
// Exact match
|
|
63
|
+
return resolvedPath === resolvePath(pattern);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Check whether a file path points to a sensitive credential file.
|
|
67
|
+
*
|
|
68
|
+
* Resolves the input to an absolute, normalized path (expanding `~`),
|
|
69
|
+
* then checks against built-in and optional extra patterns.
|
|
70
|
+
*
|
|
71
|
+
* SSH public keys (`*.pub`) are explicitly allowlisted even though
|
|
72
|
+
* they match the `~/.ssh/id_*` pattern.
|
|
73
|
+
*/
|
|
74
|
+
export function isSensitivePath(filepath, extraPatterns) {
|
|
75
|
+
const resolved = resolvePath(filepath);
|
|
76
|
+
// Check default patterns
|
|
77
|
+
for (const pattern of DEFAULT_SENSITIVE_PATTERNS) {
|
|
78
|
+
if (matchesPattern(resolved, pattern)) {
|
|
79
|
+
// Special case: SSH id_* pattern — allowlist .pub files
|
|
80
|
+
if (pattern === "~/.ssh/id_*" && resolved.endsWith(SSH_PUB_SUFFIX)) {
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
return { blocked: true, pattern };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// Check extra patterns
|
|
87
|
+
if (extraPatterns) {
|
|
88
|
+
for (const pattern of extraPatterns) {
|
|
89
|
+
if (hasMidPathWildcard(pattern)) {
|
|
90
|
+
// Mid-path wildcards like ~/vaults/*/key.pem are not supported.
|
|
91
|
+
// Skip with a console warning so misconfigurations are visible.
|
|
92
|
+
console.warn(`[sensitive-paths] Skipping unsupported mid-path wildcard pattern: "${pattern}". Only trailing wildcards (e.g. "~/.ssh/id_*", "~/.secrets/*") are supported.`);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (matchesPattern(resolved, pattern)) {
|
|
96
|
+
return { blocked: true, pattern };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return { blocked: false };
|
|
101
|
+
}
|
|
102
|
+
//# sourceMappingURL=sensitive-paths.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sensitive-paths.js","sourceRoot":"","sources":["../../src/core/sensitive-paths.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAO/C,MAAM,CAAC,MAAM,0BAA0B,GAAa;IACnD,aAAa;IACb,8BAA8B;IAC9B,mBAAmB;IACnB,yBAAyB;IACzB,oBAAoB;IACpB,iCAAiC;CACjC,CAAC;AAEF,MAAM,cAAc,GAAG,MAAM,CAAC;AAE9B;;GAEG;AACH,SAAS,UAAU,CAAC,QAAgB,EAAU;IAC7C,IAAI,QAAQ,KAAK,GAAG;QAAE,OAAO,OAAO,EAAE,CAAC;IACvC,IAAI,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC;QAAE,OAAO,GAAG,OAAO,EAAE,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;IAC1E,OAAO,QAAQ,CAAC;AAAA,CAChB;AAED;;;GAGG;AACH,SAAS,WAAW,CAAC,QAAgB,EAAU;IAC9C,OAAO,SAAS,CAAC,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AAAA,CAChD;AAED;;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,OAAO,KAAK,aAAa,IAAI,QAAQ,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE,CAAC;gBACpE,SAAS;YACV,CAAC;YACD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;QACnC,CAAC;IACF,CAAC;IAED,uBAAuB;IACvB,IAAI,aAAa,EAAE,CAAC;QACnB,KAAK,MAAM,OAAO,IAAI,aAAa,EAAE,CAAC;YACrC,IAAI,kBAAkB,CAAC,OAAO,CAAC,EAAE,CAAC;gBACjC,gEAAgE;gBAChE,gEAAgE;gBAChE,OAAO,CAAC,IAAI,CACX,sEAAsE,OAAO,gFAAgF,CAC7J,CAAC;gBACF,SAAS;YACV,CAAC;YACD,IAAI,cAAc,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,CAAC;gBACvC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;YACnC,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,CAC1B","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"]}
|
|
@@ -79,6 +79,11 @@ export interface Settings {
|
|
|
79
79
|
markdown?: MarkdownSettings;
|
|
80
80
|
sessionDir?: string;
|
|
81
81
|
forbiddenCommands?: string[];
|
|
82
|
+
sensitiveFilePaths?: string[];
|
|
83
|
+
secretOutputPatterns?: {
|
|
84
|
+
name: string;
|
|
85
|
+
pattern: string;
|
|
86
|
+
}[];
|
|
82
87
|
dream?: {
|
|
83
88
|
archivePath?: string;
|
|
84
89
|
};
|
|
@@ -235,6 +240,11 @@ export declare class SettingsManager {
|
|
|
235
240
|
setAutocompleteMaxVisible(maxVisible: number): void;
|
|
236
241
|
getCodeBlockIndent(): string;
|
|
237
242
|
getForbiddenCommands(): string[] | undefined;
|
|
243
|
+
getSensitiveFilePaths(): string[] | undefined;
|
|
244
|
+
getSecretOutputPatterns(): {
|
|
245
|
+
name: string;
|
|
246
|
+
pattern: string;
|
|
247
|
+
}[] | undefined;
|
|
238
248
|
getDreamArchivePath(): string;
|
|
239
249
|
setDreamArchivePath(path: string): void;
|
|
240
250
|
}
|