AI coding agents can edit files, run shell commands, and touch infrastructure. One bad rm -rf, force-push, or docker compose down -v can wipe hours of work or production data.
| 1 | # SPDX-License-Identifier: MIT |
| 2 | """Input normalization helpers.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | import re |
| 7 | import unicodedata |
| 8 | from pathlib import PurePosixPath, PureWindowsPath |
| 9 | |
| 10 | _ANSI_RE = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]|\x1b\].*?\x07|\x1b\[.*?[\x40-\x7e]") |
| 11 | _CTRL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]") |
| 12 | |
| 13 | |
| 14 | def strip_ansi(text: str) -> str: |
| 15 | return _ANSI_RE.sub("", text) |
| 16 | |
| 17 | |
| 18 | def strip_control_chars(text: str) -> str: |
| 19 | """Remove control characters except newline/tab.""" |
| 20 | return _CTRL_RE.sub("", text) |
| 21 | |
| 22 | |
| 23 | def normalize_whitespace(text: str) -> str: |
| 24 | return " ".join(text.split()) |
| 25 | |
| 26 | |
| 27 | def normalize_command(text: str | None) -> str: |
| 28 | """Normalize a command string for analysis (does not execute).""" |
| 29 | if text is None: |
| 30 | return "" |
| 31 | cleaned = text.replace("\x00", "") |
| 32 | cleaned = strip_ansi(cleaned) |
| 33 | cleaned = strip_control_chars(cleaned) |
| 34 | cleaned = unicodedata.normalize("NFC", cleaned) |
| 35 | return cleaned.strip() |
| 36 | |
| 37 | |
| 38 | def _collapse_parts(parts: list[str], *, keep_root_dotdot: bool) -> list[str]: |
| 39 | stack: list[str] = [] |
| 40 | for part in parts: |
| 41 | if part in {".", ""}: |
| 42 | continue |
| 43 | if part == "..": |
| 44 | if stack and stack[-1] not in {"/", ".."} and not ( |
| 45 | len(stack[-1]) == 2 and stack[-1][1] == ":" |
| 46 | ): |
| 47 | stack.pop() |
| 48 | elif keep_root_dotdot and (not stack or stack == [".."] or stack[-1] == ".."): |
| 49 | stack.append("..") |
| 50 | continue |
| 51 | stack.append(part) |
| 52 | return stack |
| 53 | |
| 54 | |
| 55 | def normalize_path_text(path: str) -> str: |
| 56 | """ |
| 57 | Normalize a path string for matching without escaping project semantics. |
| 58 | |
| 59 | Uses Pure paths (no filesystem access / no symlink following). |
| 60 | """ |
| 61 | if not path: |
| 62 | return "" |
| 63 | text = path.strip().replace("\x00", "") |
| 64 | text = strip_ansi(text) |
| 65 | |
| 66 | if text.startswith("~/") or text.startswith("~\\"): |
| 67 | rest = text[2:].replace("\\", "/") |
| 68 | return str(PurePosixPath("~", *PurePosixPath(rest).parts)) |
| 69 | |
| 70 | if re.match(r"^[A-Za-z]:[/\\]", text): |
| 71 | win = PureWindowsPath(text) |
| 72 | collapsed = _collapse_parts(list(win.parts), keep_root_dotdot=False) |
| 73 | if not collapsed: |
| 74 | return win.anchor.replace("\\", "/") |
| 75 | anchor = collapsed[0].replace("\\", "/") |
| 76 | if len(anchor) >= 2 and anchor[1] == ":" and not anchor.endswith("/"): |
| 77 | # Keep drive root style C:/ |
| 78 | body = "/".join(collapsed[1:]) |
| 79 | return f"{anchor}/{body}" if body else f"{anchor}/" |
| 80 | return "/".join(p.replace("\\", "/") for p in collapsed).replace("//", "/") |
| 81 | |
| 82 | text = text.replace("\\", "/") |
| 83 | posix = PurePosixPath(text) |
| 84 | collapsed = _collapse_parts(list(posix.parts), keep_root_dotdot=True) |
| 85 | if not collapsed: |
| 86 | return "." |
| 87 | if collapsed[0] == "/": |
| 88 | return "/" + "/".join(collapsed[1:]) if len(collapsed) > 1 else "/" |
| 89 | return "/".join(collapsed) |
| 90 | |
| 91 | |
| 92 | def is_path_traversal(path: str) -> bool: |
| 93 | """Return True if path attempts to leave a relative project tree.""" |
| 94 | norm = normalize_path_text(path) |
| 95 | if norm.startswith("/") or re.match(r"^[A-Za-z]:/", norm): |
| 96 | return False |
| 97 | return ".." in PurePosixPath(norm.replace("\\", "/")).parts or norm.startswith("..") |