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(http): support optional bearer auth
Vibhek Soni6e4bddb35dea
diff --git a/Dockerfile b/Dockerfileindex 3eb5057..100ff8b 100644--- a/Dockerfile+++ b/Dockerfile@@ -41,9 +41,13 @@ USER mcpuserEXPOSE 8000ENV PORT=8000-# Health check for FastMCP HTTP server (uses PORT env var)+# Health check for FastMCP HTTP serverHEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \- CMD curl -s http://localhost:$PORT/mcp -o /dev/null || exit 1+ CMD if [ -n "$STEALTH_BROWSER_MCP_AUTH_TOKEN" ]; then \+ curl -fsS -H "Authorization: Bearer $STEALTH_BROWSER_MCP_AUTH_TOKEN" http://localhost:$PORT/mcp -o /dev/null || exit 1; \+ else \+ curl -fsS http://localhost:$PORT/mcp -o /dev/null || exit 1; \+ fi-# Start the MCP server with HTTP transport (reads PORT env var automatically)+# Start HTTP transport. Set STEALTH_BROWSER_MCP_AUTH_TOKEN to enable bearer auth.CMD ["python", "src/server.py", "--transport", "http", "--host", "0.0.0.0"]diff --git a/README.md b/README.mdindex 06fd43f..370d12e 100644--- a/README.md+++ b/README.md@@ -175,6 +175,13 @@ python src/server.py --debugUse `--debug` or set `STEALTH_BROWSER_DEBUG=1` to enable verbose server diagnostics on `stderr`. In normal MCP `stdio` usage, debug logging stays quiet by default to avoid noisy transport output.+**HTTP transport security**+- `stdio` transport is recommended for local MCP clients and does not require HTTP auth.+- HTTP transport remains unauthenticated by default for backward compatibility.+- Do not expose unauthenticated HTTP transport outside trusted local or private networks.+- Set `STEALTH_BROWSER_MCP_AUTH_TOKEN` to enable bearer-token auth for HTTP transport.+- Clients must send `Authorization: Bearer <token>` after HTTP auth is enabled.+**Browser lifecycle defaults**- Idle browser instances are reaped automatically after 10 minutes by default.- Override per instance with `spawn_browser(idle_timeout_seconds=...)`.@@ -183,12 +190,14 @@ Use `--debug` or set `STEALTH_BROWSER_DEBUG=1` to enable verbose server diagnost- 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+### Server Environment VariablesThese are regular environment variables for the MCP server process itself. Set them wherever you launch `src/server.py`:| Variable | Default | Meaning ||----------|---------|---------|+| `STEALTH_BROWSER_MCP_AUTH_TOKEN` | unset | Optional bearer token for HTTP transport. When set, HTTP clients must send `Authorization: Bearer <token>`. |+| `MCP_AUTH_TOKEN` | unset | Backward-compatible alias for `STEALTH_BROWSER_MCP_AUTH_TOKEN`. || `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. |@@ -200,6 +209,7 @@ These are regular environment variables for the MCP server process itself. Set t- **Shell / local terminal**```bash# macOS / Linux+export STEALTH_BROWSER_MCP_AUTH_TOKEN="replace-with-a-long-random-token"export BROWSER_IDLE_TIMEOUT=900export BROWSER_IDLE_REAPER_INTERVAL=30export BROWSER_ORPHAN_PROFILE_MAX_AGE=43200@@ -209,6 +219,7 @@ python src/server.py```powershell# Windows PowerShell+$env:STEALTH_BROWSER_MCP_AUTH_TOKEN='replace-with-a-long-random-token'$env:BROWSER_IDLE_TIMEOUT='900'$env:BROWSER_IDLE_REAPER_INTERVAL='30'$env:BROWSER_ORPHAN_PROFILE_MAX_AGE='43200'@@ -226,6 +237,7 @@ python src/server.py"command": "C:\\path\\to\\stealth-browser-mcp\\venv\\Scripts\\python.exe","args": ["C:\\path\\to\\stealth-browser-mcp\\src\\server.py"],"env": {+ "STEALTH_BROWSER_MCP_AUTH_TOKEN": "replace-with-a-long-random-token","BROWSER_IDLE_TIMEOUT": "900","BROWSER_IDLE_REAPER_INTERVAL": "30","BROWSER_ORPHAN_PROFILE_MAX_AGE": "43200",@@ -239,11 +251,29 @@ python src/server.py- **systemd / long-running service**```ini[Service]+Environment="STEALTH_BROWSER_MCP_AUTH_TOKEN=replace-with-a-long-random-token"Environment="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+ExecStart=/path/to/venv/bin/python /path/to/stealth-browser-mcp/src/server.py --transport http --host 0.0.0.0+```++- **Docker / container HTTP**+```bash+docker run --rm -p 8000:8000 \+ -e STEALTH_BROWSER_MCP_AUTH_TOKEN="replace-with-a-long-random-token" \+ stealth-browser-mcp+```++```python+from fastmcp import Client+from fastmcp.client.auth import BearerAuth++client = Client(+ "http://localhost:8000/mcp/",+ auth=BearerAuth("replace-with-a-long-random-token"),+)```**Per-instance override**diff --git a/SECURITY.md b/SECURITY.mdindex 06182a5..50575bd 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -6,6 +6,8 @@ We support the latest release and the current `master` branch.### Reporting a vulnerability-Please do not open public issues for security problems. Instead, create a private security report using GitHub Security Advisories if available for this repo, or email the maintainers via the contact information on the repository profile. We will acknowledge receipt within 72 hours.+Please do not open public issues for security problems.+Use GitHub private vulnerability reporting from the repository Security tab when possible. If GitHub private reporting is unavailable, email `[email protected]`.+We will acknowledge receipt within 72 hours.diff --git a/src/http_security.py b/src/http_security.pynew file mode 100644index 0000000..f90f276--- /dev/null+++ b/src/http_security.py@@ -0,0 +1,75 @@+"""HTTP transport security helpers."""++from __future__ import annotations++import hmac+import os+from typing import Optional++from fastmcp.server.auth import TokenVerifier+from fastmcp.server.auth.auth import AccessToken++HTTP_AUTH_TOKEN_ENV = "STEALTH_BROWSER_MCP_AUTH_TOKEN"+LEGACY_HTTP_AUTH_TOKEN_ENV = "MCP_AUTH_TOKEN"+HTTP_CONTROL_SCOPE = "browser:control"+++class EnvironmentBearerTokenVerifier(TokenVerifier):+ """Validate HTTP bearer tokens against a server-side environment token."""++ def __init__(self, token: str):+ """+ Initialize the verifier.++ Args:+ token (str): Bearer token expected in incoming HTTP requests.+ """+ super().__init__(required_scopes=[HTTP_CONTROL_SCOPE])+ self._token = token++ async def verify_token(self, token: str) -> Optional[AccessToken]:+ """+ Verify an incoming bearer token.++ Args:+ token (str): Bearer token extracted from the Authorization header.++ Returns:+ Optional[AccessToken]: Access token metadata when valid, otherwise None.+ """+ if not hmac.compare_digest(token, self._token):+ return None+ return AccessToken(+ token=token,+ client_id="environment-token",+ scopes=[HTTP_CONTROL_SCOPE],+ )+++def get_http_auth_token() -> Optional[str]:+ """+ Read the configured HTTP bearer token.++ Returns:+ Optional[str]: Configured token, or None when no token is set.+ """+ for env_name in (HTTP_AUTH_TOKEN_ENV, LEGACY_HTTP_AUTH_TOKEN_ENV):+ token = os.getenv(env_name, "").strip()+ if token:+ return token+ return None+++def create_http_auth_provider(token: Optional[str]) -> Optional[TokenVerifier]:+ """+ Create the FastMCP auth provider for HTTP transports.++ Args:+ token (Optional[str]): Configured bearer token.++ Returns:+ Optional[TokenVerifier]: FastMCP token verifier, or None when auth is disabled.+ """+ if token is None:+ return None+ return EnvironmentBearerTokenVerifier(token)diff --git a/src/server.py b/src/server.pyindex 4cd5046..478830f 100644--- a/src/server.py+++ b/src/server.py@@ -25,6 +25,10 @@ from debug_logger import debug_loggerfrom dom_handler import DOMHandlerfrom element_cloner import element_clonerfrom file_based_element_cloner import file_based_element_cloner+from http_security import (+ create_http_auth_provider,+ get_http_auth_token,+)from models import (BrowserOptions,NavigationOptions,@@ -69,6 +73,7 @@ DEBUG_LOGGING_ENABLED = (parse_bool_env("STEALTH_BROWSER_DEBUG", default=False)or parse_bool_env("DEBUG", default=False))+HTTP_AUTH_TOKEN = get_http_auth_token()def is_section_enabled(section: str) -> bool:"""Check if a tool section is enabled."""@@ -150,6 +155,7 @@ mcp = FastMCP(All browser instances are undetectable by anti-bot systems.""",+ auth=create_http_auth_provider(HTTP_AUTH_TOKEN),lifespan=app_lifespan,)