Stealth browser automation for AI agents over MCP and the Chrome DevTools Protocol: navigation, network hooks, DOM extraction, and pixel-accurate UI cloning.
Python ai-agent-toolsai-toolsanthropicanti-bot-bypassautomation-toolsbrowser-automationchrome-devtoolsclaude-mcpcloudflare-bypassdeveloper-toolsfastmcpmcp-servermodel-context-protocolnetwork-interceptionnodriverpythonstealth-browserundetectable-browserweb-automationweb-scraping
fix(file-upload): validate allowed upload paths
Vibhek Soni0f5c0bbb0c36
diff --git a/README.md b/README.mdindex 170bf59..06fd43f 100644--- a/README.md+++ b/README.md@@ -53,8 +53,8 @@ Bypass Cloudflare, antibot systems, and social media blocks with real browser in## Features- **Antibot bypass** — Works on Cloudflare, Queue-It, and other protection systems that block traditional automation-- **90 tools across 11 sections** — From basic navigation to advanced CDP function execution-- **Modular loading** — Run the full 90-tool arsenal or a minimal 22-tool core; disable what you don't need+- **96 tools across 11 sections** — From basic navigation to advanced CDP function execution+- **Modular loading** — Run the full 96-tool arsenal or a minimal 20-tool core; disable what you don't need- **Pixel-accurate element cloning** — Extract complete elements with all CSS, DOM structure, events, and assets via CDP- **Network interception** — Inspect every request, response, header, and payload through your AI agent- **Dynamic hook system** — AI-generated Python functions that intercept and modify network traffic in real-time@@ -158,12 +158,12 @@ Restart your MCP client and ask your agent:## Modular Architecture-Choose exactly what functionality you need. Run the full 90-tool suite or strip it down to 22 core tools.+Choose exactly what functionality you need. Run the full 96-tool suite or strip it down to 20 core tools.| Mode | Tools | Use Case ||------|-------|----------|-| **Full** (default) | 90 | Complete browser automation and debugging |-| **Minimal** (`--minimal`) | 22 | Core browser automation only |+| **Full** (default) | 96 | Complete browser automation and debugging |+| **Minimal** (`--minimal`) | 20 | Core browser automation only || **Custom** (`--disable-*`) | Your choice | Disable specific sections |```bash@@ -181,6 +181,7 @@ Use `--debug` or set `STEALTH_BROWSER_DEBUG=1` to enable verbose server diagnost- Disable idle reaping globally with `BROWSER_IDLE_TIMEOUT=0`.- Tune the background reaper cadence with `BROWSER_IDLE_REAPER_INTERVAL`.- Tune startup cleanup of abandoned temp profiles with `BROWSER_ORPHAN_PROFILE_MAX_AGE` (seconds).+- Restrict local file uploads with `BROWSER_FILE_UPLOAD_ALLOWED_DIRS`.### Browser Lifecycle Environment Variables@@ -191,6 +192,7 @@ These are regular environment variables for the MCP server process itself. Set t| `BROWSER_IDLE_TIMEOUT` | `600` | Global idle timeout in seconds before an unused browser instance is auto-closed. Set `0` to disable idle reaping globally. || `BROWSER_IDLE_REAPER_INTERVAL` | `60` | Background reaper check interval in seconds. || `BROWSER_ORPHAN_PROFILE_MAX_AGE` | `21600` | Startup cleanup threshold in seconds for stale `uc_*` temp profiles that are not in use by live browser processes. Set `0` to disable this startup sweep. |+| `BROWSER_FILE_UPLOAD_ALLOWED_DIRS` | repo root | Directories that `file_upload()` may read from. Separate multiple roots with `;` on Windows or `:` on macOS/Linux. || `STEALTH_BROWSER_DEBUG` | `0` | Enable verbose debug logging to `stderr` when set to `1`. |**Where to set them**@@ -201,6 +203,7 @@ These are regular environment variables for the MCP server process itself. Set texport BROWSER_IDLE_TIMEOUT=900export BROWSER_IDLE_REAPER_INTERVAL=30export BROWSER_ORPHAN_PROFILE_MAX_AGE=43200+export BROWSER_FILE_UPLOAD_ALLOWED_DIRS="/Users/me/uploads:/Users/me/Documents"python src/server.py```@@ -209,6 +212,7 @@ python src/server.py$env:BROWSER_IDLE_TIMEOUT='900'$env:BROWSER_IDLE_REAPER_INTERVAL='30'$env:BROWSER_ORPHAN_PROFILE_MAX_AGE='43200'+$env:BROWSER_FILE_UPLOAD_ALLOWED_DIRS='C:\Users\me\uploads;C:\Users\me\Documents'python src/server.py```@@ -224,7 +228,8 @@ python src/server.py"env": {"BROWSER_IDLE_TIMEOUT": "900","BROWSER_IDLE_REAPER_INTERVAL": "30",- "BROWSER_ORPHAN_PROFILE_MAX_AGE": "43200"+ "BROWSER_ORPHAN_PROFILE_MAX_AGE": "43200",+ "BROWSER_FILE_UPLOAD_ALLOWED_DIRS": "C:\\Users\\me\\uploads;C:\\Users\\me\\Documents"}}}@@ -237,6 +242,7 @@ python src/server.pyEnvironment="BROWSER_IDLE_TIMEOUT=900"Environment="BROWSER_IDLE_REAPER_INTERVAL=30"Environment="BROWSER_ORPHAN_PROFILE_MAX_AGE=43200"+Environment="BROWSER_FILE_UPLOAD_ALLOWED_DIRS=/srv/stealth-browser/uploads:/srv/stealth-browser/shared"ExecStart=/path/to/venv/bin/python /path/to/stealth-browser-mcp/src/server.py --transport http```@@ -252,16 +258,16 @@ Examples:| Section | Tools | Description ||---------|-------|-------------|-| `browser-management` | 11 | Core browser operations |-| `element-interaction` | 11 | Page interaction and manipulation |+| `browser-management` | 8 | Core browser operations |+| `element-interaction` | 12 | Page interaction and manipulation || `element-extraction` | 9 | Element cloning and extraction || `file-extraction` | 9 | File-based extraction tools |-| `network-debugging` | 5 | Network monitoring and interception |+| `network-debugging` | 10 | Network monitoring and interception || `cdp-functions` | 13 | Chrome DevTools Protocol execution || `progressive-cloning` | 10 | Advanced element cloning || `cookies-storage` | 3 | Cookie and storage management || `tabs` | 5 | Tab management |-| `debugging` | 6 | Debug and system tools |+| `debugging` | 7 | Debug and system tools || `dynamic-hooks` | 10 | AI-powered network hooks |---@@ -281,9 +287,6 @@ Examples:| `go_back()` | Navigate back in history || `go_forward()` | Navigate forward in history || `reload_page()` | Reload current page |-| `hot_reload()` | Reload modules without restart |-| `reload_status()` | Check module reload status |-</details><details>@@ -295,11 +298,14 @@ Examples:| `click_element()` | Natural clicking || `type_text()` | Human-like typing with newline support || `paste_text()` | Instant text pasting via CDP |+| `file_upload()` | Upload allowlisted local files to file inputs || `scroll_page()` | Natural scrolling || `wait_for_element()` | Smart waiting || `execute_script()` | Run JavaScript || `select_option()` | Dropdown selection || `get_element_state()` | Element properties |+| `get_page_content()` | Full page HTML and text |+| `take_screenshot()` | Optimized page screenshots |</details>@@ -436,6 +442,8 @@ Examples:| `clear_debug_view()` | Clear debug logs || `export_debug_logs()` | Export logs (JSON/pickle/gzip) || `get_debug_lock_status()` | Debug lock status |+| `hot_reload()` | Reload modules without restart |+| `reload_status()` | Check module reload status || `validate_browser_environment_tool()` | Diagnose platform issues and browser compatibility |</details>@@ -453,8 +461,8 @@ Examples:| Network debugging | Full request/response inspection via AI | Basic || API reverse engineering | Payload inspection through chat | Manual tools only || Dynamic hook system | AI-generated Python functions for real-time interception | Not available |-| Modular architecture | 11 sections, 22–90 tools | Fixed ~20 tools |-| Total tools | 90 (customizable) | ~20 |+| Modular architecture | 11 sections, 20–96 tools | Fixed ~20 tools |+| Total tools | 96 (customizable) | ~20 |Tested on: LinkedIn, Instagram, Twitter/X, Amazon, banking portals, government sites, Cloudflare-protected APIs, Nike SNKRS, Ticketmaster, Supreme.@@ -478,7 +486,7 @@ Run with `--sandbox=false` or ensure your environment supports sandboxing. The sThe server now reaps idle browser instances automatically and performs startup cleanup of tracked orphan browser processes plus stale `uc_*` temp profiles. Set `BROWSER_IDLE_TIMEOUT=0` to disable idle reaping if you want fully manual browser lifetime management.**Too many tools cluttering the AI chat**-Use `--minimal` for 22 core tools, or selectively disable sections:+Use `--minimal` for 20 core tools, or selectively disable sections:```bashpython src/server.py --disable-cdp-functions --disable-dynamic-hooks --disable-progressive-cloning```diff --git a/src/dom_handler.py b/src/dom_handler.pyindex f09b1ae..bb83d93 100644--- a/src/dom_handler.py+++ b/src/dom_handler.py@@ -2,13 +2,14 @@import asyncioimport json-import osimport time-from typing import List, Optional, Dict, Any+from pathlib import Path+from typing import Any, Dict, List, Optionalfrom nodriver import Tab, Element-from models import ElementInfo, ElementActionfrom debug_logger import debug_logger+from file_upload_security import validate_upload_paths+from models import ElementInfo, ElementAction@@ -364,7 +365,7 @@ class DOMHandler:paths: List[str],) -> Dict[str, Any]:"""- Upload local files to a <input type="file"> element via CDP DOM.setFileInputFiles.+ Upload allowed local files to a <input type="file"> element via CDP DOM.setFileInputFiles.Resolves the actual file input even when the selector matches a wrapper(Workday, Ashby, LinkedIn often hide the real input behind a styled button).@@ -374,19 +375,13 @@ class DOMHandler:Args:tab (Tab): The browser tab object.selector (str): CSS selector for the file input or any ancestor that contains it.- paths (List[str]): Absolute local file paths to upload (single or multiple).+ paths (List[str]): Absolute allowlisted local file paths to upload.Returns:Dict[str, Any]: { success: True, count: N, files: [basename, ...] }"""try:- if not paths:- raise Exception("paths must contain at least one file")- for p in paths:- if not os.path.isabs(p):- raise Exception(f"Path must be absolute: {p}")- if not os.path.exists(p):- raise Exception(f"File does not exist: {p}")+ resolved_paths = validate_upload_paths(paths)element = await tab.select(selector)if not element:@@ -406,18 +401,18 @@ class DOMHandler:f"or one of its ancestors.")- if len(paths) > 1 and 'multiple' not in element.attrs:+ if len(resolved_paths) > 1 and 'multiple' not in element.attrs:raise Exception(f"File input does not accept multiple files "- f"(no 'multiple' attribute), but {len(paths)} paths were "+ f"(no 'multiple' attribute), but {len(resolved_paths)} paths were "f"provided. Pass one path or upload sequentially.")- await element.send_file(*paths)+ await element.send_file(*resolved_paths)return {"success": True,- "count": len(paths),- "files": [os.path.basename(p) for p in paths],+ "count": len(resolved_paths),+ "files": [Path(p).name for p in resolved_paths],}except Exception as e:@@ -711,4 +706,4 @@ class DOMHandler:return Trueexcept Exception as e:- raise Exception(f"Failed to scroll page: {str(e)}")\ No newline at end of file+ raise Exception(f"Failed to scroll page: {str(e)}")diff --git a/src/file_upload_security.py b/src/file_upload_security.pynew file mode 100644index 0000000..bcd26b1--- /dev/null+++ b/src/file_upload_security.py@@ -0,0 +1,133 @@+"""File upload path validation for browser form automation."""++import os+from pathlib import Path+from typing import List, Optional, Sequence+++FILE_UPLOAD_ALLOWED_DIRS_ENV = "BROWSER_FILE_UPLOAD_ALLOWED_DIRS"+DEFAULT_FILE_UPLOAD_ROOT = Path(__file__).resolve().parent.parent+++def _split_configured_roots(config_value: Optional[str]) -> Optional[List[str]]:+ """+ Split configured upload roots from the environment value.++ Args:+ config_value (Optional[str]): Raw environment variable value.++ Returns:+ Optional[List[str]]: Configured path strings, or None when the default should be used.+ """+ if config_value is None or not config_value.strip():+ return None+ return [item.strip().strip('"') for item in config_value.split(os.pathsep) if item.strip()]+++def _resolve_upload_root(root_value: str) -> Path:+ """+ Resolve and validate one upload root directory.++ Args:+ root_value (str): Configured upload root path.++ Returns:+ Path: Resolved upload root path.+ """+ root = Path(root_value).expanduser()+ if not root.is_absolute():+ raise ValueError(f"Upload root must be absolute: {root_value}")+ resolved_root = root.resolve(strict=True)+ if not resolved_root.is_dir():+ raise ValueError(f"Upload root is not a directory: {root_value}")+ return resolved_root+++def get_allowed_upload_roots() -> List[Path]:+ """+ Return upload roots allowed for local file uploads.++ Returns:+ List[Path]: Resolved directories that file_upload may read from.+ """+ configured_roots = _split_configured_roots(os.getenv(FILE_UPLOAD_ALLOWED_DIRS_ENV))+ root_values = configured_roots if configured_roots is not None else [str(DEFAULT_FILE_UPLOAD_ROOT)]+ return [_resolve_upload_root(root_value) for root_value in root_values]+++def _is_relative_to(path: Path, root: Path) -> bool:+ """+ Check whether a path is contained inside a root directory.++ Args:+ path (Path): Resolved file path.+ root (Path): Resolved root directory.++ Returns:+ bool: True when the file is inside the root.+ """+ try:+ path.relative_to(root)+ return True+ except ValueError:+ return False+++def _format_allowed_roots(roots: Sequence[Path]) -> str:+ """+ Format upload roots for validation error messages.++ Args:+ roots (Sequence[Path]): Resolved upload root paths.++ Returns:+ str: Human-readable list of roots.+ """+ return ", ".join(str(root) for root in roots)+++def validate_upload_paths(paths: Sequence[str]) -> List[str]:+ """+ Validate local files before passing them to nodriver send_file.++ Args:+ paths (Sequence[str]): Absolute local file paths requested for upload.++ Returns:+ List[str]: Resolved file paths safe to pass to nodriver.+ """+ if not paths or isinstance(paths, (str, bytes)):+ raise ValueError("paths must contain at least one file")++ allowed_roots = get_allowed_upload_roots()+ if not allowed_roots:+ raise ValueError(f"No upload roots configured in {FILE_UPLOAD_ALLOWED_DIRS_ENV}")++ resolved_paths = []+ for path_value in paths:+ if not isinstance(path_value, str) or not path_value.strip():+ raise ValueError(f"Upload path must be a non-empty string: {path_value!r}")++ path = Path(path_value).expanduser()+ if not path.is_absolute():+ raise ValueError(f"Path must be absolute: {path_value}")++ try:+ resolved_path = path.resolve(strict=True)+ except FileNotFoundError as exc:+ raise ValueError(f"File does not exist: {path_value}") from exc++ if not resolved_path.is_file():+ raise ValueError(f"Upload path is not a regular file: {path_value}")++ if not any(_is_relative_to(resolved_path, root) for root in allowed_roots):+ roots = _format_allowed_roots(allowed_roots)+ raise ValueError(+ f"Upload path is outside allowed roots: {resolved_path}. "+ f"Set {FILE_UPLOAD_ALLOWED_DIRS_ENV} to include its directory. "+ f"Allowed roots: {roots}"+ )++ resolved_paths.append(str(resolved_path))++ return resolved_pathsdiff --git a/src/server.py b/src/server.pyindex ec71071..4cd5046 100644--- a/src/server.py+++ b/src/server.py@@ -43,6 +43,19 @@ from process_cleanup import process_cleanupDISABLED_SECTIONS = set()SECTION_TOOLS: Dict[str, List[str]] = defaultdict(list)+SECTION_DESCRIPTIONS = {+ "browser-management": "Core browser operations",+ "element-interaction": "Page interaction and element manipulation",+ "element-extraction": "Element cloning and extraction",+ "file-extraction": "File-based extraction tools",+ "network-debugging": "Network monitoring and interception",+ "cdp-functions": "Chrome DevTools Protocol function execution",+ "progressive-cloning": "Advanced element cloning system",+ "cookies-storage": "Cookie and storage management",+ "tabs": "Tab management",+ "debugging": "Debug and system tools",+ "dynamic-hooks": "AI-powered network hook system",+}def parse_bool_env(name: str, default: bool = False) -> bool:@@ -504,7 +517,7 @@ async def file_upload(paths: List[str]) -> Dict[str, Any]:"""- Upload local files to a <input type="file"> element via CDP DOM.setFileInputFiles.+ Upload allowed local files to a <input type="file"> element via CDP DOM.setFileInputFiles.Resolves the actual file input even if the selector matches a wrapper element(Workday/Ashby/LinkedIn often hide the real input behind a styled button).@@ -513,7 +526,7 @@ async def file_upload(Args:instance_id (str): Browser instance ID.selector (str): CSS selector for the file input or any ancestor that contains it.- paths (List[str]): Absolute local file paths to upload (single or multiple).+ paths (List[str]): Absolute allowlisted local file paths to upload.Returns:Dict[str, Any]: { success: True, count: N, files: [basename, ...] }@@ -2791,7 +2804,9 @@ if parse_bool_env("XPOOL_SAFE_MODE", default=False):if __name__ == "__main__":import argparse- parser = argparse.ArgumentParser(description="Stealth Browser MCP Server with 90 tools")+ parser = argparse.ArgumentParser(+ description=f"Stealth Browser MCP Server with {sum(len(tools) for tools in SECTION_TOOLS.values())} tools"+ )parser.add_argument("--transport", choices=["stdio", "http"], default="stdio",help="Transport protocol to use")parser.add_argument("--port", type=int, default=int(os.getenv("PORT", 8000)),@@ -2846,17 +2861,8 @@ if __name__ == "__main__":if args.list_sections:print("Available tool sections:")- print(" browser-management: Core browser operations (11 tools)")- print(" element-interaction: Page interaction and element manipulation (8 tools)")- print(" element-extraction: Element cloning and extraction (10 tools)")- print(" file-extraction: File-based extraction tools (9 tools)")- print(" network-debugging: Network monitoring and interception (10 tools)")- print(" cdp-functions: Chrome DevTools Protocol function execution (15 tools)")- print(" progressive-cloning: Advanced element cloning system (10 tools)")- print(" cookies-storage: Cookie and storage management (3 tools)")- print(" tabs: Tab management (5 tools)")- print(" debugging: Debug and system tools (6 tools)")- print(" dynamic-hooks: AI-powered network hook system (12 tools)")+ for section, description in SECTION_DESCRIPTIONS.items():+ print(f" {section}: {description} ({len(SECTION_TOOLS.get(section, []))} tools)")print("\nUse --disable-<section-name> to disable specific sections")print("Use --minimal to enable only core functionality")sys.exit(0)