Skip to content

Stealth browser automation for AI agents over MCP and the Chrome DevTools Protocol: navigation, network hooks, DOM extraction, and pixel-accurate UI cloning.

Add stealth benchmark, trusted input, page bindings, and speed fixes

Vibhek Soni7a06b1459042
diff --git a/.github/workflows/stealth-benchmark.yml b/.github/workflows/stealth-benchmark.yml
new file mode 100644
index 0000000..75df8f4
--- /dev/null
+++ b/.github/workflows/stealth-benchmark.yml
@@ -0,0 +1,139 @@
+name: Stealth benchmark
+
+on:
+ schedule:
+ - cron: "23 5 * * 1"
+ workflow_dispatch:
+ inputs:
+ publish:
+ description: Commit results and open an issue when a target regresses
+ type: boolean
+ default: true
+
+permissions:
+ contents: read
+
+concurrency:
+ group: stealth-benchmark
+ cancel-in-progress: false
+
+jobs:
+ benchmark:
+ name: ${{ matrix.os }} ${{ matrix.mode }} ${{ matrix.chrome }}
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 30
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ mode: [headless, headed]
+ chrome: [stable]
+ include:
+ - os: ubuntu-latest
+ mode: headless
+ chrome: previous
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.11'
+
+ - name: Install dependencies
+ run: |
+ python -m pip install -U pip
+ pip install -r requirements.txt
+
+ - name: Allow the Chrome sandbox on Ubuntu
+ if: runner.os == 'Linux'
+ run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 || true
+
+ - name: Install Chrome ${{ matrix.chrome }}
+ if: matrix.chrome != 'stable'
+ shell: bash
+ run: |
+ executable="$(python -m benchmarks.stealth chrome --milestone '${{ matrix.chrome }}' --dest "$RUNNER_TEMP/chrome")"
+ echo "STEALTH_BROWSER_EXECUTABLE=$executable" >> "$GITHUB_ENV"
+
+ - name: Run benchmark
+ shell: bash
+ run: |
+ command=(python -m benchmarks.stealth run --mode '${{ matrix.mode }}' --channel '${{ matrix.chrome }}' --output-dir bench-out/results --raw-dir bench-out/raw)
+ if [ "$RUNNER_OS" = "Linux" ] && [ '${{ matrix.mode }}' = "headed" ]; then
+ xvfb-run --auto-servernum --server-args="-screen 0 1920x1080x24" "${command[@]}"
+ else
+ "${command[@]}"
+ fi
+
+ - uses: actions/upload-artifact@v4
+ if: always()
+ with:
+ name: stealth-${{ matrix.os }}-${{ matrix.mode }}-${{ matrix.chrome }}
+ path: bench-out
+ if-no-files-found: warn
+ retention-days: 30
+
+ publish:
+ needs: benchmark
+ if: always() && github.ref == 'refs/heads/master' && (github.event_name == 'schedule' || inputs.publish)
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ permissions:
+ contents: write
+ issues: write
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.11'
+
+ - uses: actions/download-artifact@v4
+ with:
+ pattern: stealth-*
+ path: artifacts
+
+ - name: Collect result files
+ run: |
+ mkdir -p incoming
+ find artifacts -path '*/results/*.json' -exec cp {} incoming/ \;
+ ls -l incoming
+
+ - name: Compare with previous results
+ id: compare
+ env:
+ RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
+ run: python -m benchmarks.stealth compare --incoming incoming --issue-file regression.md --run-url "$RUN_URL"
+
+ - name: Store results and render report
+ run: |
+ mkdir -p docs/stealth-results
+ cp incoming/*.json docs/stealth-results/
+ python -m benchmarks.stealth render
+
+ - name: Commit results
+ run: |
+ git config user.name "github-actions[bot]"
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
+ git add docs/stealth-results STEALTH_TESTS.md
+ if git diff --cached --quiet; then
+ echo "No result changes to commit"
+ exit 0
+ fi
+ git commit -m "Update stealth benchmark results"
+ git pull --rebase origin master
+ git push origin HEAD:master
+
+ - name: Report regressions
+ if: steps.compare.outputs.regressions != '0'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ TITLE: ${{ steps.compare.outputs.title }}
+ run: |
+ gh label create stealth-regression --color B60205 --description "Stealth benchmark regression" --force
+ existing="$(gh issue list --label stealth-regression --state open --json number --jq '.[0].number // empty')"
+ if [ -n "$existing" ]; then
+ gh issue comment "$existing" --body-file regression.md
+ else
+ gh issue create --title "$TITLE" --label stealth-regression --body-file regression.md
+ fi
diff --git a/AGENTS.md b/AGENTS.md
index 9f2c675..a226a2d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -35,6 +35,15 @@ For broader syntax validation:
Get-ChildItem src -Filter *.py | ForEach-Object { & .\venv\Scripts\python.exe -m py_compile $_.FullName }
```
+Unit tests and the stealth benchmark:
+
+```powershell
+& .\venv\Scripts\python.exe -m unittest discover -s tests -v
+& .\venv\Scripts\python.exe -m benchmarks.stealth run --mode headed
+```
+
+Set `STEALTH_BROWSER_TESTS=1` to include tests that launch a real browser. Benchmark results go to `.stealth-results/` locally. Only the weekly workflow writes to `docs/stealth-results/` and regenerates the automated section of `STEALTH_TESTS.md`.
+
## Git Rules
- Do not include AI attribution, co-author trailers, or generated-by metadata in commits.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c3cb928..014d1d2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,9 +9,28 @@ The format is based on Keep a Changelog and adheres to Semantic Versioning where
- **`press_key()` tool** - Presses real keys through CDP `Input.dispatchKeyEvent`, producing trusted `keydown`/`keypress`/`keyup` events. Supports named keys (Enter, Tab, Escape, arrows, Backspace, Delete, Home, End, PageUp, PageDown, Space, F1-F12), single printable characters, modifier combinations (Shift, Control/Ctrl, Alt, Meta/Cmd), optional focus selector, repeat count, and inter-press delay.
- **Tests** - `tests/test_press_key.py` covers the key-to-CDP mapping, the modifier bitmask, and the dispatch sequence. A browser-backed test asserting `isTrusted` runs when `STEALTH_BROWSER_TESTS=1` is set.
+- **Stealth benchmark** - `python -m benchmarks.stealth` runs the browser against a bundled local probe, an init script capability check, Sannysoft, Intoli, CreepJS, Cloudflare (nowsecure.nl), and the tls.peet.ws TLS and HTTP/2 fingerprint API. Each target reports PASS, DEGRADED, FAIL, or UNREACHABLE with its individual checks, and each run writes a JSON result file. A weekly GitHub Actions workflow runs it on Linux, Windows, and macOS in headless and headed mode plus the previous Chrome release, commits results to `docs/stealth-results/`, regenerates the automated section of `STEALTH_TESTS.md`, and opens a `stealth-regression` issue when a target gets worse (#25).
+- **`STEALTH_BROWSER_EXECUTABLE`** - Environment variable that selects the browser executable instead of auto-detection.
+- **Page bindings** - `create_page_binding`, `get_page_binding_calls`, `resolve_page_binding_call`, and `remove_page_binding` let page JavaScript call `window.<name>(...args)` and get a Promise that the agent answers. Calls are queued as JSON (64 KB per call, 500 queued per instance), `auto_resolve` answers immediately with a fixed value, and bindings follow every tab and navigation. Nothing runs on the server host. This replaces `create_python_binding`.
+- **`BROWSER_TAB_RECYCLE_NAVIGATIONS`** - Opt-in main tab recycling. It was always on at 25 navigations before.
+- **Input fidelity benchmark target** - Checks that `click_element` and `type_text` produce trusted events in a real order without touching the page DOM.
- **Tests** - `tests/test_js_values.py`, `tests/test_element_cloners.py`, and `tests/test_hooks_and_proxy.py` cover result conversion, template escaping, cloner data paths, hook matching, proxy parsing, and debug log export. CI now runs the unit test suite.
### Fixed
+- **Trusted clicks** - `click_element` scrolls the element into view, moves the mouse along a short path, and presses and releases the button with CDP input events, so pages see trusted `pointerdown`, `mousedown`, `mouseup`, and `click` events. It used to call `el.click()` from JavaScript, which produces an untrusted click with no mouse events, and nodriver's click flashed a highlight element into the page DOM. Covered or hidden elements still fall back to a JavaScript click.
+- **Trusted typing** - `type_text` sends keydown, keypress, input, and keyup for every character, holds Shift for capitals and symbols, and inserts other characters like an input method. It used to send bare `char` events. Clearing a field now selects the content and presses Backspace, so React and other frameworks see the change. `parse_newlines` and `shift_enter` press real Enter and Shift+Enter keys.
+- **Speed** - `navigate` returns in about 30 ms on a simple page instead of about 550 ms, `close_instance` takes about 0.2 s instead of hitting a 5 s timeout every time, `click_element` dropped its fixed 0.5 s wait, `list_tabs` and `new_tab` no longer wait 0.5 s per tab, and `wait_for_element` polls every 100 ms without fetching the whole DOM tree. Element lookups for click, type, paste, and key presses fetch only the document root.
+- **Network hooks** - Fetch interception is enabled only while a hook applies to the instance, so pages without hooks no longer pause every request twice. Hooks created after spawn now update the interception patterns of running instances, and removing the last hook turns interception off.
+- **Network capture memory** - Only text-like response bodies (documents, XHR, fetch, scripts, JSON, text, XML) are stored, up to 2 MB each and 64 MB per instance, oldest dropped first. Images, media, and fonts are fetched on demand instead of copied for every request. Stored bodies also serve `get_response_content` after the page has moved on. Chrome internal URLs are no longer captured.
+- **Tab state** - Timezone override, extra headers, init scripts, network capture, and page bindings are applied to every tab the instance uses, including tabs opened with `new_tab`, switched to, or created to replace a closed or crashed tab. A replaced tab used to silently lose the timezone override and headers. `new_tab` configures the tab before loading the URL.
+- **Closed tab recovery** - Tools recover when the page closes its own tab or the tab crashes, opening a new window when the last one is gone.
+- **Persistent functions** - `create_persistent_function` now really survives reloads and new tabs, validates the name and code, and keeps the function out of `Object.keys(window)`.
+- **Cleanup** - Every close path (tool, idle reaper, shutdown) clears network data, persistent functions, and bindings for the instance. Shutdown and idle reaping close instances in parallel, and nodriver's target refresh tasks no longer error after the browser exits.
+- **Headless detection** - Headless instances no longer report `HeadlessChrome` in `navigator.userAgent`, worker user agents, or the `User-Agent` header. The real headless user agent is read once per browser build and launched with the headless marker removed, unless a custom `user_agent` is set. Headless runs of the stealth benchmark went from 2 of 7 targets passing to 7 of 7, including CreepJS (67% headless to 0%) and the Sannysoft `HEADCHR_UA` and `CHR_MEMORY` checks.
+- **Execution contexts** - `get_execution_contexts` returns the real CDP contexts for every frame and isolated world instead of a single fake entry. `context_id` (numeric id or unique id) is now honored by `discover_global_functions`, `inject_and_execute_script`, and `execute_function_sequence`.
+- **Tabs** - `close_tab` moves the instance to another open tab when the current tab is closed, and closing the last tab leaves a blank tab so the browser stays usable.
+- **Responsiveness** - Browser process and profile cleanup runs in a worker thread, so closing an instance no longer freezes other tool calls for several seconds.
+- **Authenticated proxies** - Plain HTTP requests through an authenticated proxy no longer fail with 407 after the first request on a keep-alive connection. CONNECT responses are checked by status code.
- **Script results** - `execute_script` returns plain JSON values instead of raw CDP deep-serialized nodes, and reports JavaScript exceptions as failures instead of success.
- **Element cloning** - Selectors are JSON-escaped in every extractor, so quotes and backslashes work. Progressive `expand_*` tools, `extract_complete_element_to_file` summaries, CDP matched styles, and `clone_element_to_file` sub-extractors now return real data. File tools no longer save extraction errors as successful files.
- **Broken tools** - `extract_element_assets`, `extract_related_files`, and `discover_object_methods` no longer crash on an invalid `await`. `set_cookie(same_site=...)`, `spawn_browser(extra_headers=...)`, and `navigate(referrer=...)` no longer fail on CDP type errors. Browser state, cookie, and network resources serialize correctly.
@@ -26,13 +45,19 @@ The format is based on Keep a Changelog and adheres to Semantic Versioning where
- `get_instance_state` accepts fractional `devicePixelRatio` values.
### Changed
-- `element-interaction` section now exposes 13 tools; full surface is 98 tools, minimal surface is 21.
+- `STEALTH_TESTS.md` now leads with generated benchmark results. The 2026-02-10 manual snapshot is kept below it, and the X.com section no longer implies an Arkose challenge was solved.
+- `add_script_to_evaluate_on_new_document` logic moved into `BrowserManager.add_init_script` so the benchmark tests the same code path, and installed scripts are re-applied to new and replacement tabs.
+- The MCP server instructions no longer claim instances are undetectable and point to the measured results instead.
+- `element-interaction` section now exposes 13 tools; full surface is 101 tools, minimal surface is 21.
- HTTP transport binds to `127.0.0.1` by default and warns on stderr when bound to another host without an auth token.
- `hot_reload` refuses to run while browser instances are open, so they are not orphaned.
- Removed the unused `response_stage_hooks` module and unused JavaScript templates.
+### Removed
+- **`create_python_binding`** - Removed for security. It ran arbitrary Python from the client on the server host with `exec()`, any website could call the binding it exposed, and the bridge never delivered calls to Python. Use the page binding tools instead.
+
### Notes
-- `type_text(parse_newlines=True)` fakes Enter by writing `\n` into the input value and dispatching an untrusted JavaScript `KeyboardEvent`. React-select and typeahead widgets (Greenhouse, Ashby, Lever, Workday) ignore untrusted events and drop the value on blur. Use `press_key()` for those fields.
+- `type_text(parse_newlines=True)` now presses a real Enter key for each newline. Use `press_key()` for other control keys in React-select and typeahead widgets (Greenhouse, Ashby, Lever, Workday).
## [0.2.5] - 2026-02-10
### Fixed
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0f136e0..8666a7a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -29,6 +29,8 @@ pip install -r requirements.txt
```
3. Run the server: `python src/server.py`
+4. Run the tests: `python -m unittest discover -s tests -v`. Set `STEALTH_BROWSER_TESTS=1` to include tests that launch a real browser.
+5. If your change can affect detection, run the stealth benchmark before and after: `python -m benchmarks.stealth run --mode headed`. See [STEALTH_TESTS.md](STEALTH_TESTS.md) for targets and statuses.
### Pull request guidelines
diff --git a/README.md b/README.md
index 70edd03..828caa1 100644
--- a/README.md
+++ b/README.md
@@ -83,8 +83,8 @@ Navigate Cloudflare challenges, anti-bot checks, and login walls with real Chrom
## Features
- **Anti-bot resistance** - Has passed Cloudflare and Queue-It style challenges in testing; results vary by site, region, browser version, and detector version.
-- **98 tools across 11 sections** - From basic navigation to advanced CDP function execution.
-- **Modular loading** - Run the full 98-tool surface or a minimal 21-tool core; disable sections you do not need.
+- **101 tools across 11 sections** - From basic navigation to advanced CDP function execution.
+- **Modular loading** - Run the full 101-tool surface or a minimal 21-tool core; disable sections you do not need.
- **Pixel-accurate element cloning** - Extract complete elements with CSS, DOM structure, events, animations, and assets via CDP.
- **Network inspection** - Inspect requests, responses, headers, payloads, and captured bodies through your AI agent.
- **Dynamic hook system** - Restricted Python hooks can intercept, block, redirect, fulfill, or modify request/response flows.
@@ -211,11 +211,11 @@ Treat the MCP client or agent as the security principal. The recommended deploym
## Modular Architecture
-Choose exactly what functionality you need. Run the full 98-tool suite or strip it down to the 21-tool core.
+Choose exactly what functionality you need. Run the full 101-tool suite or strip it down to the 21-tool core.
| Mode | Tools | Use Case |
|------|-------|----------|
-| **Full** (default) | 98 | Complete browser automation and debugging |
+| **Full** (default) | 101 | Complete browser automation and debugging |
| **Minimal** (`--minimal`) | 21 | Core browser automation and interaction |
| **Custom** (`--disable-*`) | Your choice | Disable specific sections |
| **Xpool safe** (`--xpool-safe`) | 84 | Disable CDP function tools that trigger `Runtime.enable` |
@@ -239,7 +239,7 @@ Use `--debug` or set `STEALTH_BROWSER_DEBUG=1` to enable verbose server diagnost
| `element-extraction` | 9 | Element cloning and extraction |
| `file-extraction` | 9 | File-based extraction tools |
| `network-debugging` | 10 | Network monitoring and capture |
-| `cdp-functions` | 14 | Chrome DevTools Protocol execution |
+| `cdp-functions` | 17 | Chrome DevTools Protocol execution |
| `progressive-cloning` | 10 | Advanced element cloning |
| `cookies-storage` | 3 | Cookie management |
| `tabs` | 5 | Tab management |
@@ -258,7 +258,9 @@ These are environment variables for the MCP server process. Set them in your she
| `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_TAB_RECYCLE_NAVIGATIONS` | `0` | Replace the main tab with a fresh one after this many navigations. `0` keeps the same tab, which preserves history and session storage. |
| `BROWSER_ORPHAN_PROFILE_MAX_AGE` | `21600` | Startup cleanup threshold in seconds for stale `uc_*` temp profiles. Set `0` to disable this startup sweep. |
+| `STEALTH_BROWSER_EXECUTABLE` | auto-detect | Path to the Chrome, Chromium, or Edge executable to launch instead of the auto-detected one. |
| `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`. |
| `DEBUG` | `0` | Legacy alias for `STEALTH_BROWSER_DEBUG`. |
@@ -476,8 +478,11 @@ client = Client(
| `inspect_function_signature()` | Inspect function details |
| `inject_and_execute_script()` | Inject and run custom JavaScript |
| `create_persistent_function()` | Create functions that survive reloads |
+| `create_page_binding()` | Expose `window.<name>()` so page JavaScript can call back to the agent |
+| `get_page_binding_calls()` | Read queued page binding calls, optionally waiting for one |
+| `resolve_page_binding_call()` | Answer a page binding call with a value or an error |
+| `remove_page_binding()` | Remove a page binding and reject its pending calls |
| `execute_function_sequence()` | Execute ordered function calls |
-| `create_python_binding()` | Create Python-to-JS bindings |
| `execute_python_in_browser()` | Translate Python to JavaScript with py2js and run it |
| `get_function_executor_info()` | Inspect executor state |
@@ -505,7 +510,7 @@ client = Client(
## Stealth vs Playwright MCP
-Detection results are point-in-time and depend on site policy, region, browser version, IP reputation, and detector version. See [STEALTH_TESTS.md](STEALTH_TESTS.md) for the current manual snapshot and [issue #25](https://github.com/vibheksoni/stealth-browser-mcp/issues/25) for the proposed reproducible benchmark harness.
+Detection results are point-in-time and depend on site policy, region, browser version, IP reputation, and detector version. See [STEALTH_TESTS.md](STEALTH_TESTS.md) for weekly automated results from the benchmark in `benchmarks/stealth/`, which runs on Linux, Windows, and macOS in GitHub Actions, plus the earlier manual snapshot.
| Feature | Stealth Browser MCP | Playwright MCP |
|---------|---------------------|----------------|
@@ -516,8 +521,8 @@ Detection results are point-in-time and depend on site policy, region, browser v
| Network debugging | Full request/response inspection through AI tools | Basic |
| API reverse engineering | Payload inspection through chat | Manual tools only |
| Dynamic hook system | Restricted Python hooks for real-time interception | Not available |
-| Modular architecture | 11 sections, 21-98 tools | Fixed tool surface |
-| Total tools | 98 customizable tools | About 20 |
+| Modular architecture | 11 sections, 21-101 tools | Fixed tool surface |
+| Total tools | 101 customizable tools | About 20 |
---
diff --git a/STEALTH_TESTS.md b/STEALTH_TESTS.md
index 5ee039a..adf4b63 100644
--- a/STEALTH_TESTS.md
+++ b/STEALTH_TESTS.md
@@ -1,15 +1,58 @@
# Stealth Detection Test Results
-Verified bypass results for stealth-browser-mcp against major bot detection systems.
+Results for stealth-browser-mcp against public bot detection pages.
+
+There are two parts. The automated results come from the benchmark in `benchmarks/stealth/`, which runs every week in GitHub Actions on Linux, Windows, and macOS, in headless and headed mode, with the current and previous Chrome release. Each run writes a JSON file to `docs/stealth-results/`, and the section below is generated from those files. The manual snapshot further down is a hand-run session from 2026-02-10 and is kept for reference.
+
+Detection results depend on site policy, region, IP reputation, Chrome version, and detector version, so treat them as measurements, not guarantees.
+
+## Running the Benchmark
+
+```bash
+python -m benchmarks.stealth run --mode headed
+python -m benchmarks.stealth run --mode headless --targets local_probe,init_script
+```
+
+Local runs write to `.stealth-results/` and print one line per target. Use `--output-dir` to choose another folder, `--raw-dir` to keep the raw page data, and `STEALTH_BROWSER_EXECUTABLE` to test a specific Chrome build. `python -m benchmarks.stealth chrome --milestone previous --dest .chrome` downloads the previous Chrome release from Chrome for Testing and prints its path.
+
+| Target | What it measures |
+|--------|------------------|
+| Local fingerprint probe | Automation tells read by a bundled page on 127.0.0.1, no network needed |
+| Init script injection | `add_script_to_evaluate_on_new_document` runs before page scripts and survives navigation |
+| Input fidelity | `click_element` and `type_text` produce trusted pointer, mouse, and key events in a real order, with nothing injected into the page |
+| Sannysoft | bot.sannysoft.com headless and fingerprint table |
+| Intoli | Intoli headless Chrome detection table |
+| CreepJS | CreepJS headless and stealth scores |
+| Cloudflare (nowsecure.nl) | Getting through a Cloudflare challenge |
+| TLS and HTTP/2 fingerprint | JA3, JA4, and Akamai HTTP/2 fingerprints seen by tls.peet.ws |
+
+| Status | Meaning |
+|--------|---------|
+| PASS | Every check passed |
+| DEGRADED | Only minor checks failed |
+| FAIL | At least one critical check failed |
+| UNREACHABLE | The page could not be loaded or read, so nothing was measured |
+
+When a target that passed in the previous run of the same runner gets worse, the weekly workflow opens an issue labeled `stealth-regression`. UNREACHABLE results never open issues.
+
+<!-- stealth-benchmark:start -->
+## Automated Results
+
+No automated runs have been recorded yet.
+
+<!-- stealth-benchmark:end -->
+
+---
+
+## Manual Snapshot (2026-02-10)
-**Test Date:** 2026-02-10
**Browser:** Chrome 144 (nodriver)
**Platform:** Windows 10 (Win64)
**Mode:** Non-headless
---
-## 1. Cloudflare Challenge (nowsecure.nl)
+### 1. Cloudflare Challenge (nowsecure.nl)
**Result: PASSED**
@@ -19,7 +62,7 @@ of Cloudflare's JavaScript challenge, TLS fingerprinting, and behavioral analysi
---
-## 2. CreepJS Fingerprint Analysis
+### 2. CreepJS Fingerprint Analysis
**Result: PASSED**
@@ -44,7 +87,7 @@ CreepJS performs deep browser fingerprinting across dozens of vectors. Key findi
---
-## 3. Sannysoft Bot Detection
+### 3. Sannysoft Bot Detection
**Result: 20/20 TESTS PASSED**
@@ -86,7 +129,7 @@ Every single detection vector returned "ok" or consistent values.
---
-## 4. Intoli Headless Detection (Round II)
+### 4. Intoli Headless Detection (Round II)
**Result: ALL TESTS PASSED**
@@ -106,25 +149,26 @@ Every single detection vector returned "ok" or consistent values.
---
-## 5. X.com (Twitter) Login Wall Bypass
+### 5. X.com (Twitter) Login Wall
-**Result: BYPASSED**
+**Result: PROFILE DATA READ BEHIND THE LOGIN WALL**
-Navigated to `x.com/elonmusk` which presents a login modal blocking content.
-The browser loaded the full profile data behind the modal. After removing the
-overlay via DOM manipulation, all profile data was accessible:
+Navigated to `x.com/elonmusk`, which shows a login modal over the content.
+The profile data was already loaded behind the modal. After removing the
+overlay through DOM manipulation, all profile data was readable:
- Display name, handle, bio, join date
- Follower/following counts (234.3M followers)
- Full tweet timeline with engagement metrics
- All data-testid attributes queryable
-This demonstrates real-world scraping capability against a major platform
-with aggressive bot detection (Arkose Labs/FunCaptcha integration).
+This shows logged-out reading of public profile data behind a login wall.
+No Arkose Labs or FunCaptcha challenge appeared in this flow, so this result
+says nothing about solving those challenges.
---
-## Summary
+### Summary
| Detection System | Type | Result |
|-----------------|------|--------|
@@ -132,7 +176,7 @@ with aggressive bot detection (Arkose Labs/FunCaptcha integration).
| CreepJS | Deep Fingerprinting | 0% stealth / 0% headless |
| Sannysoft | Bot Detection Suite | 20/20 tests passed |
| Intoli | Headless Detection | All tests passed |
-| X.com | Login Wall + Arkose | Bypassed, data scraped |
+| X.com | Login Wall | Profile data read behind the modal |
-All tests confirm that stealth-browser-mcp running on nodriver is undetectable
-by current industry-standard bot detection systems.
+In this snapshot, stealth-browser-mcp running on nodriver was not flagged by
+any of the detection systems above. See the automated results for current numbers.
diff --git a/benchmarks/__init__.py b/benchmarks/__init__.py
new file mode 100644
index 0000000..220180b
--- /dev/null
+++ b/benchmarks/__init__.py
@@ -0,0 +1 @@
+"""Benchmarks for stealth-browser-mcp."""
diff --git a/benchmarks/stealth/__init__.py b/benchmarks/stealth/__init__.py
new file mode 100644
index 0000000..7954c4d
--- /dev/null
+++ b/benchmarks/stealth/__init__.py
@@ -0,0 +1,7 @@
+"""
+Reproducible stealth benchmark.
+
+Runs the browser against public bot detection pages and local probes, writes
+machine-readable results to docs/stealth-results, renders STEALTH_TESTS.md
+from them, and reports regressions between runs.
+"""
diff --git a/benchmarks/stealth/__main__.py b/benchmarks/stealth/__main__.py
new file mode 100644
index 0000000..2fb03d7
--- /dev/null
+++ b/benchmarks/stealth/__main__.py
@@ -0,0 +1,209 @@
+"""
+Command line entry point.
+
+ python -m benchmarks.stealth run --mode headless
+ python -m benchmarks.stealth render
+ python -m benchmarks.stealth compare --incoming bench-out
+ python -m benchmarks.stealth chrome --milestone previous --dest .chrome
+"""
+
+import argparse
+import asyncio
+import os
+import sys
+from pathlib import Path
+from typing import List, Optional
+
+from .report import DEFAULT_HISTORY, update_report
+from .regression import ISSUE_TITLE_PREFIX, find_regressions, render_issue
+from .results import TargetResult, load_runs, save_run
+
+ROOT = Path(__file__).resolve().parents[2]
+DEFAULT_RESULTS_DIR = ROOT / "docs" / "stealth-results"
+DEFAULT_REPORT = ROOT / "STEALTH_TESTS.md"
+DEFAULT_LOCAL_OUTPUT = ROOT / ".stealth-results"
+
+
+def print_progress(result: TargetResult) -> None:
+ """
+ Print one line per finished target.
+
+ Args:
+ result (TargetResult): Finished target
+ """
+ line = f"[{result.status.value}] {result.title} ({result.duration_seconds:.1f}s) {result.summary}"
+ if result.error:
+ line += f" | {result.error}"
+ print(line, flush=True)
+
+
+def command_run(args: argparse.Namespace) -> int:
+ """
+ Run the benchmark and save the result file.
+
+ Args:
+ args (argparse.Namespace): Parsed arguments
+
+ Returns:
+ int: Exit code
+ """
+ from .runner import run_benchmark
+ from .targets import select_targets
+
+ names = [name.strip() for name in args.targets.split(",") if name.strip()] if args.targets else None
+ try:
+ targets = select_targets(names)
+ except ValueError as error:
+ print(error, file=sys.stderr)
+ return 2
+ run = asyncio.run(
+ run_benchmark(
+ targets,
+ mode=args.mode,
+ channel=args.channel,
+ label=args.label,
+ raw_dir=Path(args.raw_dir) if args.raw_dir else None,
+ progress=print_progress,
+ )
+ )
+ path = save_run(run, Path(args.output_dir))
+ print(f"{run.runner}: {run.counts} -> {path}", flush=True)
+ return 0
+
+
+def command_render(args: argparse.Namespace) -> int:
+ """
+ Regenerate the automated section of the report.
+
+ Args:
+ args (argparse.Namespace): Parsed arguments
+
+ Returns:
+ int: Exit code
+ """
+ runs = load_runs(Path(args.results_dir))
+ try:
+ changed = update_report(Path(args.report), runs, args.history)
+ except ValueError as error:
+ print(error, file=sys.stderr)
+ return 2
+ print(f"{args.report}: {'updated' if changed else 'unchanged'} ({len(runs)} runs)")
+ return 0
+
+
+def write_github_output(values: dict) -> None:
+ """
+ Append step outputs when running in GitHub Actions.
+
+ Args:
+ values (dict): Output names and values
+ """
+ output = os.environ.get("GITHUB_OUTPUT")
+ if not output:
+ return
+ with open(output, "a", encoding="utf-8") as handle:
+ for key, value in values.items():
+ handle.write(f"{key}={value}\n")
+
+
+def command_compare(args: argparse.Namespace) -> int:
+ """
+ Compare incoming runs with stored history and write an issue body on regressions.
+
+ Args:
+ args (argparse.Namespace): Parsed arguments
+
+ Returns:
+ int: Exit code, 0 even when regressions are found
+ """
+ history = load_runs(Path(args.results_dir))
+ incoming = load_runs(Path(args.incoming))
+ if not incoming:
+ print(f"No result files found in {args.incoming}", file=sys.stderr)
+ return 2
+ regressions = find_regressions(history, incoming)
+ date = max(run.date for run in incoming)
+ title = f"{ISSUE_TITLE_PREFIX} on {date}"
+ for item in regressions:
+ print(f"REGRESSION {item.runner} {item.target}: {item.previous_status.value} -> {item.current_status.value}")
+ if regressions and args.issue_file:
+ Path(args.issue_file).write_text(render_issue(regressions, date, args.run_url), encoding="utf-8")
+ if not regressions:
+ print(f"No regressions across {len(incoming)} run(s)")
+ write_github_output({"regressions": len(regressions), "title": title})
+ return 0
+
+
+def command_chrome(args: argparse.Namespace) -> int:
+ """
+ Install a Chrome for Testing build and print its executable path.
+
+ Args:
+ args (argparse.Namespace): Parsed arguments
+
+ Returns:
+ int: Exit code
+ """
+ from .chrome import install_chrome
+
+ version, executable = install_chrome(args.milestone, Path(args.dest))
+ print(f"Installed Chrome for Testing {version}", file=sys.stderr)
+ print(executable)
+ return 0
+
+
+def build_parser() -> argparse.ArgumentParser:
+ """
+ Build the argument parser.
+
+ Returns:
+ argparse.ArgumentParser: Parser with run, render, compare, and chrome commands
+ """
+ parser = argparse.ArgumentParser(prog="python -m benchmarks.stealth", description="Stealth benchmark harness")
+ commands = parser.add_subparsers(dest="command", required=True)
+
+ run = commands.add_parser("run", help="Run the benchmark and save a result file")
+ run.add_argument("--mode", choices=("headless", "headed"), default="headless")
+ run.add_argument("--channel", default="stable", help="Chrome channel label used in the runner name")
+ run.add_argument("--label", help="Explicit runner label")
+ run.add_argument("--targets", help="Comma separated target names, default all")
+ run.add_argument("--output-dir", default=str(DEFAULT_LOCAL_OUTPUT), help="Directory for the result file")
+ run.add_argument("--raw-dir", help="Directory for raw target payloads")
+ run.set_defaults(handler=command_run)
+
+ render = commands.add_parser("render", help="Regenerate the automated section of STEALTH_TESTS.md")
+ render.add_argument("--results-dir", default=str(DEFAULT_RESULTS_DIR))
+ render.add_argument("--report", default=str(DEFAULT_REPORT))
+ render.add_argument("--history", type=int, default=DEFAULT_HISTORY)
+ render.set_defaults(handler=command_render)
+
+ compare = commands.add_parser("compare", help="Compare new runs with stored results")
+ compare.add_argument("--incoming", required=True, help="Directory with new result files")
+ compare.add_argument("--results-dir", default=str(DEFAULT_RESULTS_DIR))
+ compare.add_argument("--issue-file", help="Write a regression issue body here when regressions are found")
+ compare.add_argument("--run-url", help="Workflow run URL included in the issue body")
+ compare.set_defaults(handler=command_compare)
+
+ chrome = commands.add_parser("chrome", help="Install a Chrome for Testing build")
+ chrome.add_argument("--milestone", default="previous", help="stable, previous, or a milestone number")
+ chrome.add_argument("--dest", required=True, help="Install directory")
+ chrome.set_defaults(handler=command_chrome)
+ return parser
+
+
+def main(argv: Optional[List[str]] = None) -> int:
+ """
+ Parse arguments and dispatch to a command.
+
+ Args:
+ argv (Optional[List[str]]): Arguments, defaults to sys.argv
+
+ Returns:
+ int: Exit code
+ """
+ args = build_parser().parse_args(argv)
+ return args.handler(args)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/benchmarks/stealth/chrome.py b/benchmarks/stealth/chrome.py
new file mode 100644
index 0000000..0fe3bce
--- /dev/null
+++ b/benchmarks/stealth/chrome.py
@@ -0,0 +1,149 @@
+"""Downloads Chrome for Testing builds so runs can target a specific milestone."""
+
+import io
+import os
+import platform
+import stat
+import zipfile
+from pathlib import Path
+from typing import Any, Dict, Tuple
+
+import requests
+
+LAST_KNOWN_GOOD_URL = "https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions.json"
+MILESTONES_URL = (
+ "https://googlechromelabs.github.io/chrome-for-testing/latest-versions-per-milestone-with-downloads.json"
+)
+EXECUTABLES = {
+ "linux64": "chrome-linux64/chrome",
+ "win64": "chrome-win64/chrome.exe",
+ "win32": "chrome-win32/chrome.exe",
+ "mac-arm64": "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
+ "mac-x64": "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
+}
+REQUEST_TIMEOUT = 60
+
+
+def cft_platform() -> str:
+ """
+ Chrome for Testing platform name for this machine.
+
+ Returns:
+ str: linux64, win64, win32, mac-arm64, or mac-x64
+
+ Raises:
+ RuntimeError: When the platform has no Chrome for Testing build
+ """
+ system = platform.system().lower()
+ machine = platform.machine().lower()
+ if system == "linux" and machine in ("x86_64", "amd64"):
+ return "linux64"
+ if system == "windows":
+ return "win64" if machine.endswith("64") else "win32"
+ if system == "darwin":
+ return "mac-arm64" if machine in ("arm64", "aarch64") else "mac-x64"
+ raise RuntimeError(f"No Chrome for Testing build for {system} {machine}")
+
+
+def resolve_milestone(spec: str, stable_version: str) -> int:
+ """
+ Turn a milestone spec into a milestone number.
+
+ Args:
+ spec (str): stable, previous, or a milestone number such as 153
+ stable_version (str): Current stable version such as 154.0.7000.0
+
+ Returns:
+ int: Milestone number
+
+ Raises:
+ ValueError: When the spec is not recognized
+ """
+ stable = int(stable_version.split(".", 1)[0])
+ if spec == "stable":
+ return stable
+ if spec == "previous":
+ return stable - 1
+ if spec.isdigit():
+ return int(spec)
+ raise ValueError(f"Milestone must be stable, previous, or a number, got {spec!r}")
+
+
+def download_url(milestones: Dict[str, Any], milestone: int, platform_name: str) -> Tuple[str, str]:
+ """
+ Find the Chrome download for a milestone and platform.
+
+ Args:
+ milestones (Dict[str, Any]): Parsed latest-versions-per-milestone-with-downloads.json
+ milestone (int): Milestone number
+ platform_name (str): Chrome for Testing platform name
+
+ Returns:
+ Tuple[str, str]: Full version and zip URL
+
+ Raises:
+ LookupError: When the milestone or platform is not published
+ """
+ entry = (milestones.get("milestones") or {}).get(str(milestone))
+ if not entry:
+ raise LookupError(f"Chrome for Testing has no milestone {milestone}")
+ for download in (entry.get("downloads") or {}).get("chrome", []):
+ if download.get("platform") == platform_name:
+ return entry["version"], download["url"]
+ raise LookupError(f"Chrome {milestone} has no {platform_name} download")
+
+
+def extract_zip(data: bytes, destination: Path) -> None:
+ """
+ Extract a zip archive and keep Unix permission bits.
+
+ Args:
+ data (bytes): Zip file content
+ destination (Path): Directory to extract into
+ """
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ for member in archive.infolist():
+ target = destination / member.filename
+ if not target.resolve().is_relative_to(destination.resolve()):
+ raise RuntimeError(f"Refusing to extract {member.filename} outside {destination}")
+ mode = member.external_attr >> 16
+ if stat.S_ISLNK(mode):
+ target.parent.mkdir(parents=True, exist_ok=True)
+ if target.is_symlink() or target.exists():
+ target.unlink()
+ os.symlink(archive.read(member).decode("utf-8"), target)
+ continue
+ archive.extract(member, destination)
+ if mode and not member.is_dir():
+ os.chmod(target, stat.S_IMODE(mode))
+
+
+def install_chrome(spec: str, destination: Path) -> Tuple[str, Path]:
+ """
+ Download and unpack a Chrome for Testing build.
+
+ Args:
+ spec (str): stable, previous, or a milestone number
+ destination (Path): Directory to unpack into
+
+ Returns:
+ Tuple[str, Path]: Installed version and path to the browser executable
+ """
+ session = requests.Session()
+ stable = session.get(LAST_KNOWN_GOOD_URL, timeout=REQUEST_TIMEOUT)
+ stable.raise_for_status()
+ stable_version = stable.json()["channels"]["Stable"]["version"]
+ milestone = resolve_milestone(spec, stable_version)
+ milestones = session.get(MILESTONES_URL, timeout=REQUEST_TIMEOUT)
+ milestones.raise_for_status()
+ platform_name = cft_platform()
+ version, url = download_url(milestones.json(), milestone, platform_name)
+ archive = session.get(url, timeout=REQUEST_TIMEOUT * 5)
+ archive.raise_for_status()
+ install_dir = destination / version
+ install_dir.mkdir(parents=True, exist_ok=True)
+ extract_zip(archive.content, install_dir)
+ executable = install_dir / EXECUTABLES[platform_name]
+ if not executable.is_file():
+ raise RuntimeError(f"Chrome executable missing after extraction: {executable}")
+ return version, executable
diff --git a/benchmarks/stealth/environment.py b/benchmarks/stealth/environment.py
new file mode 100644
index 0000000..369813c
--- /dev/null
+++ b/benchmarks/stealth/environment.py
@@ -0,0 +1,111 @@
+"""Runner labels and environment metadata for benchmark runs."""
+
+import os
+import platform
+import re
+import sys
+from importlib import metadata
+from typing import Any, Dict, Optional
+
+OS_NAMES = {"windows": "windows", "darwin": "macos", "linux": "linux"}
+ARCH_NAMES = {"amd64": "x64", "x86_64": "x64", "arm64": "arm64", "aarch64": "arm64"}
+LABEL_SAFE = re.compile(r"[^a-z0-9.-]+")
+
+
+def os_name() -> str:
+ """
+ Short operating system name.
+
+ Returns:
+ str: windows, macos, linux, or the lowercase platform name
+ """
+ system = platform.system().lower()
+ return OS_NAMES.get(system, system)
+
+
+def arch_name() -> str:
+ """
+ Short CPU architecture name.
+
+ Returns:
+ str: x64, arm64, or the lowercase machine name
+ """
+ machine = platform.machine().lower()
+ return ARCH_NAMES.get(machine, machine)
+
+
+def runner_label(mode: str, channel: str, label: Optional[str] = None) -> str:
+ """
+ Build the runner label used in result file names.
+
+ Args:
+ mode (str): headless or headed
+ channel (str): Chrome channel label, for example stable or previous
+ label (Optional[str]): Explicit label that overrides the generated one
+
+ Returns:
+ str: Lowercase label such as linux-x64-headless-stable
+ """
+ raw = label or f"{os_name()}-{arch_name()}-{mode}-{channel}"
+ return LABEL_SAFE.sub("-", raw.lower()).strip("-")
+
+
+def package_version(name: str) -> Optional[str]:
+ """
+ Installed version of a Python package.
+
+ Args:
+ name (str): Distribution name
+
+ Returns:
+ Optional[str]: Version string, or None when not installed
+ """
+ try:
+ return metadata.version(name)
+ except metadata.PackageNotFoundError:
+ return None
+
+
+def ci_metadata() -> Dict[str, Any]:
+ """
+ GitHub Actions run metadata, when running in Actions.
+
+ Returns:
+ Dict[str, Any]: Run id, URL, and commit, or an empty dict outside Actions
+ """
+ if os.environ.get("GITHUB_ACTIONS") != "true":
+ return {}
+ server = os.environ.get("GITHUB_SERVER_URL", "https://github.com")
+ repository = os.environ.get("GITHUB_REPOSITORY", "")
+ run_id = os.environ.get("GITHUB_RUN_ID", "")
+ return {
+ "provider": "github-actions",
+ "run_id": run_id,
+ "run_url": f"{server}/{repository}/actions/runs/{run_id}" if repository and run_id else None,
+ "commit": os.environ.get("GITHUB_SHA"),
+ "event": os.environ.get("GITHUB_EVENT_NAME"),
+ "runner_image": os.environ.get("ImageOS"),
+ }
+
+
+def base_environment(mode: str, channel: str) -> Dict[str, Any]:
+ """
+ Environment metadata known before the browser starts.
+
+ Args:
+ mode (str): headless or headed
+ channel (str): Chrome channel label
+
+ Returns:
+ Dict[str, Any]: Platform, Python, package, and CI details
+ """
+ return {
+ "os": os_name(),
+ "os_release": platform.platform(),
+ "arch": arch_name(),
+ "python": sys.version.split()[0],
+ "nodriver": package_version("nodriver"),
+ "mode": mode,
+ "chrome_channel": channel,
+ "ci": ci_metadata(),
+ }
diff --git a/benchmarks/stealth/local_server.py b/benchmarks/stealth/local_server.py
new file mode 100644
index 0000000..aa1cc5e
--- /dev/null
+++ b/benchmarks/stealth/local_server.py
@@ -0,0 +1,79 @@
+"""Loopback HTTP server that serves the local probe pages."""
+
+import threading
+from functools import partial
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Optional
+
+PAGES_DIR = Path(__file__).resolve().parent / "pages"
+
+
+class QuietHandler(SimpleHTTPRequestHandler):
+ """Static file handler that keeps request logs off stderr."""
+
+ def log_message(self, format: str, *args) -> None:
+ """
+ Drop access log lines.
+
+ Args:
+ format (str): Log format string
+ *args: Format arguments
+ """
+
+
+class LocalPageServer:
+ """
+ Serves PAGES_DIR on 127.0.0.1 with a random free port.
+
+ Use as a context manager. base_url is valid while the server is running.
+ """
+
+ def __init__(self, directory: Path = PAGES_DIR):
+ """
+ Prepare the server.
+
+ Args:
+ directory (Path): Directory to serve
+ """
+ self.directory = directory
+ self._server: Optional[ThreadingHTTPServer] = None
+ self._thread: Optional[threading.Thread] = None
+
+ @property
+ def base_url(self) -> str:
+ """
+ Root URL of the running server.
+
+ Returns:
+ str: URL such as http://127.0.0.1:54321
+ """
+ if self._server is None:
+ raise RuntimeError("Local page server is not running")
+ host, port = self._server.server_address[:2]
+ return f"http://{host}:{port}"
+
+ def __enter__(self) -> "LocalPageServer":
+ """
+ Start serving in a background thread.
+
+ Returns:
+ LocalPageServer: This server
+ """
+ handler = partial(QuietHandler, directory=str(self.directory))
+ self._server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
+ self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
+ self._thread.start()
+ return self
+
+ def __exit__(self, *exc_info) -> None:
+ """
+ Stop the server.
+
+ Args:
+ *exc_info: Exception information from the with block
+ """
+ if self._server is not None:
+ self._server.shutdown()
+ self._server.server_close()
+ self._server = None
diff --git a/benchmarks/stealth/pages/input.html b/benchmarks/stealth/pages/input.html
new file mode 100644
index 0000000..ff6a631
--- /dev/null
+++ b/benchmarks/stealth/pages/input.html
@@ -0,0 +1,25 @@
+<!doctype html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>input probe</title>
+</head>
+<body>
+<div style="height: 1600px"></div>
+<input id="field" autocomplete="off">
+<button id="target">target</button>
+<script>
+window.__inputProbe = { events: [], added: 0, moves: 0 };
+const probe = window.__inputProbe;
+for (const type of ["pointerdown", "mousedown", "mouseup", "click", "keydown", "keyup", "input"]) {
+ document.addEventListener(type, (event) => {
+ probe.events.push({ type, trusted: event.isTrusted, key: event.key || null, time: performance.now() });
+ }, true);
+}
+document.addEventListener("mousemove", () => { probe.moves += 1; }, true);
+new MutationObserver((records) => {
+ for (const record of records) probe.added += record.addedNodes.length;
+}).observe(document.documentElement, { childList: true, subtree: true });
+</script>
+</body>
+</html>
diff --git a/benchmarks/stealth/pages/probe.html b/benchmarks/stealth/pages/probe.html
new file mode 100644
index 0000000..f694969
--- /dev/null
+++ b/benchmarks/stealth/pages/probe.html
@@ -0,0 +1,63 @@
+<!doctype html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>stealth probe</title>
+<script>
+window.__initMarkerAtParse = typeof window.__sbmInitMarker === "undefined" ? null : window.__sbmInitMarker;
+</script>
+</head>
+<body>
+<p>stealth probe</p>
+<script>
+(async () => {
+ const r = {};
+ r.webdriver = navigator.webdriver;
+ r.userAgent = navigator.userAgent;
+ r.appVersion = navigator.appVersion;
+ r.platform = navigator.platform;
+ r.brands = navigator.userAgentData ? navigator.userAgentData.brands.map(b => b.brand) : null;
+ r.uaPlatform = navigator.userAgentData ? navigator.userAgentData.platform : null;
+ r.hasChrome = typeof window.chrome === "object" && window.chrome !== null;
+ r.plugins = navigator.plugins.length;
+ r.pluginsIsArray = navigator.plugins instanceof PluginArray;
+ r.mimeTypes = navigator.mimeTypes.length;
+ r.languages = Array.from(navigator.languages || []);
+ r.language = navigator.language;
+ r.hardwareConcurrency = navigator.hardwareConcurrency;
+ r.outer = [window.outerWidth, window.outerHeight];
+ r.inner = [window.innerWidth, window.innerHeight];
+ r.screen = [screen.width, screen.height, screen.colorDepth];
+ try {
+ r.notificationPermission = Notification.permission;
+ r.permissionQuery = (await navigator.permissions.query({ name: "notifications" })).state;
+ } catch (e) {
+ r.permissionError = String(e);
+ }
+ try {
+ const gl = document.createElement("canvas").getContext("webgl");
+ const ext = gl && gl.getExtension("WEBGL_debug_renderer_info");
+ r.webgl = !!(gl && ext);
+ r.webglVendor = ext ? gl.getParameter(ext.UNMASKED_VENDOR_WEBGL) : null;
+ r.webglRenderer = ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : null;
+ } catch (e) {
+ r.webglError = String(e);
+ }
+ const iframe = document.createElement("iframe");
+ iframe.srcdoc = "<p>frame</p>";
+ document.body.appendChild(iframe);
+ r.iframeChrome = typeof iframe.contentWindow.chrome === "object" && iframe.contentWindow.chrome !== null;
+ r.iframeWebdriver = iframe.contentWindow.navigator.webdriver;
+ iframe.remove();
+ let stackRead = false;
+ const error = new Error("probe");
+ Object.defineProperty(error, "stack", { configurable: false, get() { stackRead = true; return ""; } });
+ console.debug(error);
+ await new Promise(resolve => setTimeout(resolve, 100));
+ r.consoleStackRead = stackRead;
+ r.initMarkerAtParse = window.__initMarkerAtParse;
+ window.__stealthProbe = r;
+})();
+</script>
+</body>
+</html>
diff --git a/benchmarks/stealth/regression.py b/benchmarks/stealth/regression.py
new file mode 100644
index 0000000..1387341
--- /dev/null
+++ b/benchmarks/stealth/regression.py
@@ -0,0 +1,193 @@
+"""Detects regressions between benchmark runs and renders the issue body."""
+
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional
+
+from .results import RunResult, Status, TargetResult
+
+ISSUE_TITLE_PREFIX = "Stealth benchmark regression"
+
+
+@dataclass
+class Regression:
+ """
+ A target that got worse on one runner.
+
+ Attributes:
+ runner (str): Runner label
+ target (str): Target title
+ previous_status (Status): Status in the previous run
+ current_status (Status): Status in the current run
+ previous_date (str): Date of the previous run
+ new_failed_checks (List[str]): Checks that passed before and fail now
+ changed_details (Dict[str, Dict[str, Any]]): Detail values that changed, keyed by detail name
+ summary (str): Current target summary
+ """
+
+ runner: str
+ target: str
+ previous_status: Status
+ current_status: Status
+ previous_date: str
+ new_failed_checks: List[str] = field(default_factory=list)
+ changed_details: Dict[str, Dict[str, Any]] = field(default_factory=dict)
+ summary: str = ""
+
+
+def is_regression(previous: Status, current: Status) -> bool:
+ """
+ Tell whether a status change is a regression.
+
+ UNREACHABLE on either side is never a regression, network failures are
+ reported in the results but do not open issues.
+
+ Args:
+ previous (Status): Earlier status
+ current (Status): Later status
+
+ Returns:
+ bool: True when the later status is strictly worse
+ """
+ if previous.severity is None or current.severity is None:
+ return False
+ return current.severity > previous.severity
+
+
+def changed_details(previous: TargetResult, current: TargetResult) -> Dict[str, Dict[str, Any]]:
+ """
+ Detail values that differ between two results of the same target.
+
+ Args:
+ previous (TargetResult): Earlier result
+ current (TargetResult): Later result
+
+ Returns:
+ Dict[str, Dict[str, Any]]: {"name": {"before": ..., "after": ...}} for each change
+ """
+ keys = sorted(set(previous.details) | set(current.details))
+ return {
+ key: {"before": previous.details.get(key), "after": current.details.get(key)}
+ for key in keys
+ if previous.details.get(key) != current.details.get(key)
+ }
+
+
+def compare_runs(previous: RunResult, current: RunResult) -> List[Regression]:
+ """
+ Compare two runs from the same runner.
+
+ Args:
+ previous (RunResult): Earlier run
+ current (RunResult): Later run
+
+ Returns:
+ List[Regression]: Targets that got worse, in current run order
+ """
+ regressions = []
+ for target in current.targets:
+ before = previous.target(target.name)
+ if before is None or not is_regression(before.status, target.status):
+ continue
+ previously_passing = {check.name for check in before.checks if check.passed}
+ regressions.append(
+ Regression(
+ runner=current.runner,
+ target=target.title,
+ previous_status=before.status,
+ current_status=target.status,
+ previous_date=previous.date,
+ new_failed_checks=[check.name for check in target.failed_checks if check.name in previously_passing],
+ changed_details=changed_details(before, target),
+ summary=target.summary,
+ )
+ )
+ return regressions
+
+
+def previous_run(history: List[RunResult], current: RunResult) -> Optional[RunResult]:
+ """
+ Find the newest earlier run from the same runner.
+
+ Args:
+ history (List[RunResult]): Stored runs, oldest first
+ current (RunResult): Run being compared
+
+ Returns:
+ Optional[RunResult]: Newest run with the same runner and an earlier date, or None
+ """
+ candidates = [run for run in history if run.runner == current.runner and run.date < current.date]
+ return candidates[-1] if candidates else None
+
+
+def find_regressions(history: List[RunResult], incoming: List[RunResult]) -> List[Regression]:
+ """
+ Compare each incoming run with the previous stored run of its runner.
+
+ Args:
+ history (List[RunResult]): Stored runs, oldest first
+ incoming (List[RunResult]): New runs
+
+ Returns:
+ List[Regression]: Every regression across the incoming runs
+ """
+ regressions: List[Regression] = []
+ for run in incoming:
+ previous = previous_run(history, run)
+ if previous is not None:
+ regressions.extend(compare_runs(previous, run))
+ return regressions
+
+
+def format_value(value: Any, limit: int = 120) -> str:
+ """
+ Render a detail value for a markdown table cell.
+
+ Args:
+ value (Any): Value to render
+ limit (int): Maximum length
+
+ Returns:
+ str: Inline code text with pipes escaped, truncated when long
+ """
+ text = "none" if value is None else str(value)
+ if len(text) > limit:
+ text = text[: limit - 3] + "..."
+ return "`" + text.replace("`", "'").replace("|", "\\|") + "`"
+
+
+def render_issue(regressions: List[Regression], date: str, run_url: Optional[str] = None) -> str:
+ """
+ Render the body of a regression issue.
+
+ Args:
+ regressions (List[Regression]): Regressions to report
+ date (str): Date of the run that regressed
+ run_url (Optional[str]): Link to the workflow run
+
+ Returns:
+ str: Markdown issue body
+ """
+ lines = [f"The stealth benchmark on {date} found {len(regressions)} regression(s).", ""]
+ if run_url:
+ lines += [f"Workflow run and raw payloads: {run_url}", ""]
+ for item in regressions:
+ lines.append(f"### {item.target} on {item.runner}")
+ lines.append("")
+ lines.append(
+ f"Status went from {item.previous_status.value} ({item.previous_date}) to {item.current_status.value}."
+ )
+ if item.summary:
+ lines.append(f"Summary: {item.summary}")
+ if item.new_failed_checks:
+ lines.append("")
+ lines.append("Checks that passed before and fail now:")
+ lines.extend(f"- {name}" for name in item.new_failed_checks)
+ if item.changed_details:
+ lines.append("")
+ lines.append("| Detail | Before | After |")
+ lines.append("|--------|--------|-------|")
+ for key, change in item.changed_details.items():
+ lines.append(f"| {key} | {format_value(change['before'])} | {format_value(change['after'])} |")
+ lines.append("")
+ lines.append("Results are in `docs/stealth-results/` and the summary is in `STEALTH_TESTS.md`.")
+ return "\n".join(lines) + "\n"
diff --git a/benchmarks/stealth/report.py b/benchmarks/stealth/report.py
new file mode 100644
index 0000000..2cfc5ca
--- /dev/null
+++ b/benchmarks/stealth/report.py
@@ -0,0 +1,221 @@
+"""Renders the automated results section of STEALTH_TESTS.md."""
+
+from pathlib import Path
+from typing import Dict, List
+
+from .results import RunResult, Status, latest_by_runner
+
+START_MARKER = "<!-- stealth-benchmark:start -->"
+END_MARKER = "<!-- stealth-benchmark:end -->"
+DEFAULT_HISTORY = 8
+
+
+def escape_cell(text: str) -> str:
+ """
+ Make text safe for a markdown table cell.
+
+ Args:
+ text (str): Raw text
+
+ Returns:
+ str: Text with pipes escaped and newlines flattened
+ """
+ return str(text).replace("|", "\\|").replace("\n", " ")
+
+
+def count_text(run: RunResult) -> str:
+ """
+ Short status count text for a run.
+
+ Args:
+ run (RunResult): Run to describe
+
+ Returns:
+ str: Text such as "5 pass, 1 degraded, 1 unreachable"
+ """
+ parts = [f"{count} {status.lower()}" for status, count in run.counts.items() if count]
+ return ", ".join(parts) or "no targets"
+
+
+def target_matrix(latest: Dict[str, RunResult]) -> List[str]:
+ """
+ Target by runner status table.
+
+ Args:
+ latest (Dict[str, RunResult]): Newest run per runner
+
+ Returns:
+ List[str]: Markdown lines
+ """
+ runners = list(latest)
+ rows: Dict[str, Dict[str, str]] = {}
+ order: List[str] = []
+ meta: Dict[str, str] = {}
+ for runner, run in latest.items():
+ for target in run.targets:
+ if target.name not in rows:
+ rows[target.name] = {}
+ order.append(target.name)
+ meta[target.name] = f"{escape_cell(target.title)} | {escape_cell(target.category)}"
+ rows[target.name][runner] = target.status.value
+ lines = [
+ "| Target | Category | " + " | ".join(runners) + " |",
+ "|--------|----------|" + "|".join("---" for _ in runners) + "|",
+ ]
+ for name in order:
+ cells = [rows[name].get(runner, "not run") for runner in runners]
+ lines.append(f"| {meta[name]} | " + " | ".join(cells) + " |")
+ return lines
+
+
+def runner_table(latest: Dict[str, RunResult]) -> List[str]:
+ """
+ Environment table, one row per runner.
+
+ Args:
+ latest (Dict[str, RunResult]): Newest run per runner
+
+ Returns:
+ List[str]: Markdown lines
+ """
+ lines = [
+ "| Runner | Date | Chrome | nodriver | OS | Result |",
+ "|--------|------|--------|----------|----|--------|",
+ ]
+ for runner, run in latest.items():
+ env = run.environment
+ date = run.date
+ run_url = (env.get("ci") or {}).get("run_url")
+ if run_url:
+ date = f"[{date}]({run_url})"
+ lines.append(
+ "| "
+ + " | ".join(
+ [
+ runner,
+ date,
+ escape_cell(env.get("chrome_version") or "unknown"),
+ escape_cell(env.get("nodriver") or "unknown"),
+ escape_cell(env.get("os_release") or env.get("os") or "unknown"),
+ count_text(run),
+ ]
+ )
+ + " |"
+ )
+ return lines
+
+
+def issue_lines(latest: Dict[str, RunResult]) -> List[str]:
+ """
+ Failing checks and unreachable targets per runner.
+
+ Args:
+ latest (Dict[str, RunResult]): Newest run per runner
+
+ Returns:
+ List[str]: Markdown lines, empty when everything passed
+ """
+ lines: List[str] = []
+ for runner, run in latest.items():
+ entries = []
+ for target in run.targets:
+ if target.status == Status.UNREACHABLE:
+ reason = (target.error or target.summary or "unknown").splitlines()[0][:160]
+ entries.append(f"- {target.title}: not measured, {reason}")
+ continue
+ failed = target.failed_checks
+ if not failed:
+ continue
+ names = ", ".join(
+ f"{check.name}{'' if check.critical else ' (minor)'}" for check in failed
+ )
+ entries.append(f"- {target.title}: {names}")
+ if entries:
+ lines += [f"#### {runner}", ""] + entries + [""]
+ return lines
+
+
+def history_table(runs: List[RunResult], limit: int) -> List[str]:
+ """
+ Passing target counts for the most recent run dates.
+
+ Args:
+ runs (List[RunResult]): All runs, oldest first
+ limit (int): Number of dates to include
+
+ Returns:
+ List[str]: Markdown lines
+ """
+ runners = sorted({run.runner for run in runs})
+ dates = sorted({run.date for run in runs}, reverse=True)[:limit]
+ by_key = {(run.date, run.runner): run for run in runs}
+ lines = [
+ "| Date | " + " | ".join(runners) + " |",
+ "|------|" + "|".join("---" for _ in runners) + "|",
+ ]
+ for date in dates:
+ cells = []
+ for runner in runners:
+ run = by_key.get((date, runner))
+ cells.append(f"{run.counts[Status.PASS.value]}/{len(run.targets)}" if run else "")
+ lines.append(f"| {date} | " + " | ".join(cells) + " |")
+ return lines
+
+
+def render_section(runs: List[RunResult], history: int = DEFAULT_HISTORY) -> str:
+ """
+ Render the generated block, markers included.
+
+ Args:
+ runs (List[RunResult]): All stored runs, oldest first
+ history (int): Number of run dates in the history table
+
+ Returns:
+ str: Markdown block
+ """
+ lines = [START_MARKER, "## Automated Results", ""]
+ if not runs:
+ lines += ["No automated runs have been recorded yet.", "", END_MARKER]
+ return "\n".join(lines)
+ latest = latest_by_runner(runs)
+ newest = max(run.date for run in latest.values())
+ lines += [
+ f"Last updated {newest} from {len(latest)} runner(s). This section is generated by "
+ "`python -m benchmarks.stealth render` from `docs/stealth-results/`, do not edit it by hand.",
+ "",
+ ]
+ lines += target_matrix(latest) + [""]
+ lines += ["### Runners", ""] + runner_table(latest) + [""]
+ problems = issue_lines(latest)
+ if problems:
+ lines += ["### Checks Not Passing", ""] + problems
+ lines += ["### History", "", "Passing targets per run.", ""] + history_table(runs, history) + [""]
+ lines.append(END_MARKER)
+ return "\n".join(lines)
+
+
+def update_report(path: Path, runs: List[RunResult], history: int = DEFAULT_HISTORY) -> bool:
+ """
+ Replace the generated block in a markdown file.
+
+ Args:
+ path (Path): File holding the start and end markers
+ runs (List[RunResult]): All stored runs, oldest first
+ history (int): Number of run dates in the history table
+
+ Returns:
+ bool: True when the file content changed
+
+ Raises:
+ ValueError: When the markers are missing or out of order
+ """
+ text = path.read_text(encoding="utf-8")
+ start = text.find(START_MARKER)
+ end = text.find(END_MARKER)
+ if start == -1 or end == -1 or end < start:
+ raise ValueError(f"{path} must contain {START_MARKER} followed by {END_MARKER}")
+ updated = text[:start] + render_section(runs, history) + text[end + len(END_MARKER):]
+ if updated == text:
+ return False
+ path.write_text(updated, encoding="utf-8")
+ return True
diff --git a/benchmarks/stealth/results.py b/benchmarks/stealth/results.py
new file mode 100644
index 0000000..8f5a85d
--- /dev/null
+++ b/benchmarks/stealth/results.py
@@ -0,0 +1,260 @@
+"""Result models and JSON storage for stealth benchmark runs."""
+
+import json
+import re
+from dataclasses import asdict, dataclass, field
+from enum import Enum
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+SCHEMA_VERSION = 1
+RESULT_FILE_PATTERN = re.compile(r"^(?P<date>\d{4}-\d{2}-\d{2})-(?P<runner>[a-z0-9][a-z0-9.-]*)\.json$")
+
+
+class Status(str, Enum):
+ """Outcome of one benchmark target."""
+
+ PASS = "PASS"
+ DEGRADED = "DEGRADED"
+ FAIL = "FAIL"
+ UNREACHABLE = "UNREACHABLE"
+
+ @property
+ def severity(self) -> Optional[int]:
+ """
+ Rank used to detect regressions.
+
+ Returns:
+ Optional[int]: 0 for PASS, 1 for DEGRADED, 2 for FAIL, None when unreachable
+ """
+ return {Status.PASS: 0, Status.DEGRADED: 1, Status.FAIL: 2}.get(self)
+
+
+@dataclass
+class Check:
+ """
+ Single assertion made against a target.
+
+ Attributes:
+ name (str): Check identifier shown in reports
+ passed (bool): Whether the check passed
+ critical (bool): A failed critical check fails the target, others degrade it
+ value (Any): Observed value that the check was based on
+ """
+
+ name: str
+ passed: bool
+ critical: bool = True
+ value: Any = None
+
+
+@dataclass
+class TargetResult:
+ """
+ Outcome of one target in one run.
+
+ Attributes:
+ name (str): Target identifier
+ title (str): Human readable target name
+ category (str): Detection surface the target covers
+ url (str): Page the target loads
+ status (Status): Overall outcome
+ summary (str): One line description of the outcome
+ checks (List[Check]): Individual assertions
+ details (Dict[str, Any]): Key fingerprint values kept in the committed results
+ duration_seconds (float): Wall time spent on the target
+ error (Optional[str]): Harness or navigation error, when any
+ """
+
+ name: str
+ title: str
+ category: str
+ url: str
+ status: Status
+ summary: str = ""
+ checks: List[Check] = field(default_factory=list)
+ details: Dict[str, Any] = field(default_factory=dict)
+ duration_seconds: float = 0.0
+ error: Optional[str] = None
+
+ @property
+ def failed_checks(self) -> List[Check]:
+ """
+ Checks that did not pass.
+
+ Returns:
+ List[Check]: Failed checks in their original order
+ """
+ return [check for check in self.checks if not check.passed]
+
+
+@dataclass
+class RunResult:
+ """
+ Outcome of one benchmark run on one runner.
+
+ Attributes:
+ runner (str): Runner label, for example linux-x64-headless-stable
+ date (str): Run date in YYYY-MM-DD form (UTC)
+ started_at (str): ISO 8601 start time (UTC)
+ finished_at (str): ISO 8601 finish time (UTC)
+ environment (Dict[str, Any]): Platform, browser, and CI metadata
+ targets (List[TargetResult]): Per-target outcomes
+ schema_version (int): Result file format version
+ """
+
+ runner: str
+ date: str
+ started_at: str
+ finished_at: str
+ environment: Dict[str, Any]
+ targets: List[TargetResult]
+ schema_version: int = SCHEMA_VERSION
+
+ @property
+ def counts(self) -> Dict[str, int]:
+ """
+ Number of targets per status.
+
+ Returns:
+ Dict[str, int]: Count keyed by status value, including zero counts
+ """
+ counts = {status.value: 0 for status in Status}
+ for target in self.targets:
+ counts[target.status.value] += 1
+ return counts
+
+ @property
+ def filename(self) -> str:
+ """
+ File name used when saving this run.
+
+ Returns:
+ str: Name in YYYY-MM-DD-<runner>.json form
+ """
+ return f"{self.date}-{self.runner}.json"
+
+ def target(self, name: str) -> Optional[TargetResult]:
+ """
+ Find a target result by name.
+
+ Args:
+ name (str): Target identifier
+
+ Returns:
+ Optional[TargetResult]: Matching result, or None when the run did not include it
+ """
+ return next((target for target in self.targets if target.name == name), None)
+
+ def to_dict(self) -> Dict[str, Any]:
+ """
+ Convert the run to a JSON-ready dictionary.
+
+ Returns:
+ Dict[str, Any]: Serializable run data
+ """
+ data = asdict(self)
+ data["summary"] = self.counts
+ for target in data["targets"]:
+ target["status"] = Status(target["status"]).value
+ return data
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "RunResult":
+ """
+ Build a run from its JSON dictionary.
+
+ Args:
+ data (Dict[str, Any]): Data produced by to_dict
+
+ Returns:
+ RunResult: Parsed run
+ """
+ targets = []
+ for raw in data.get("targets", []):
+ checks = [Check(**check) for check in raw.get("checks", [])]
+ targets.append(
+ TargetResult(
+ name=raw["name"],
+ title=raw.get("title", raw["name"]),
+ category=raw.get("category", ""),
+ url=raw.get("url", ""),
+ status=Status(raw["status"]),
+ summary=raw.get("summary", ""),
+ checks=checks,
+ details=raw.get("details", {}),
+ duration_seconds=raw.get("duration_seconds", 0.0),
+ error=raw.get("error"),
+ )
+ )
+ return cls(
+ runner=data["runner"],
+ date=data["date"],
+ started_at=data.get("started_at", ""),
+ finished_at=data.get("finished_at", ""),
+ environment=data.get("environment", {}),
+ targets=targets,
+ schema_version=data.get("schema_version", SCHEMA_VERSION),
+ )
+
+
+def save_run(run: RunResult, directory: Path) -> Path:
+ """
+ Write a run to its result file.
+
+ Args:
+ run (RunResult): Run to save
+ directory (Path): Destination directory, created when missing
+
+ Returns:
+ Path: Written file path
+ """
+ directory.mkdir(parents=True, exist_ok=True)
+ path = directory / run.filename
+ path.write_text(json.dumps(run.to_dict(), indent=2, sort_keys=False, default=str) + "\n", encoding="utf-8")
+ return path
+
+
+def load_run(path: Path) -> RunResult:
+ """
+ Read a run from a result file.
+
+ Args:
+ path (Path): Result file path
+
+ Returns:
+ RunResult: Parsed run
+ """
+ return RunResult.from_dict(json.loads(path.read_text(encoding="utf-8")))
+
+
+def load_runs(directory: Path) -> List[RunResult]:
+ """
+ Read every result file in a directory, oldest first.
+
+ Args:
+ directory (Path): Directory holding YYYY-MM-DD-<runner>.json files
+
+ Returns:
+ List[RunResult]: Runs sorted by date, then runner
+ """
+ if not directory.is_dir():
+ return []
+ runs = [load_run(path) for path in directory.iterdir() if RESULT_FILE_PATTERN.match(path.name)]
+ return sorted(runs, key=lambda run: (run.date, run.runner))
+
+
+def latest_by_runner(runs: List[RunResult]) -> Dict[str, RunResult]:
+ """
+ Pick the newest run for each runner label.
+
+ Args:
+ runs (List[RunResult]): Runs sorted oldest first
+
+ Returns:
+ Dict[str, RunResult]: Newest run keyed by runner label, in label order
+ """
+ latest: Dict[str, RunResult] = {}
+ for run in runs:
+ latest[run.runner] = run
+ return dict(sorted(latest.items()))
diff --git a/benchmarks/stealth/runner.py b/benchmarks/stealth/runner.py
new file mode 100644
index 0000000..6d3c9fc
--- /dev/null
+++ b/benchmarks/stealth/runner.py
@@ -0,0 +1,279 @@
+"""Runs benchmark targets against real browsers spawned by BrowserManager."""
+
+import asyncio
+import json
+import sys
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable, Dict, List, Optional
+
+SRC_DIR = Path(__file__).resolve().parents[2] / "src"
+if str(SRC_DIR) not in sys.path:
+ sys.path.insert(0, str(SRC_DIR))
+
+import nodriver as uc
+
+from browser_manager import BrowserManager
+from dom_handler import DOMHandler
+from js_values import evaluate_to_python
+from models import BrowserOptions
+
+from .environment import base_environment, runner_label
+from .local_server import LocalPageServer
+from .results import RunResult, Status, TargetResult
+from .targets.base import Target, Unreachable, status_from_checks
+
+
+class BrowserSession:
+ """
+ Session implementation backed by one BrowserManager instance.
+
+ Attributes:
+ manager (BrowserManager): Manager that owns the browser
+ instance_id (str): Browser instance in use
+ local_base_url (str): Root URL of the local page server
+ """
+
+ def __init__(self, manager: BrowserManager, instance_id: str, local_base_url: str):
+ """
+ Wrap a spawned browser instance.
+
+ Args:
+ manager (BrowserManager): Manager that owns the browser
+ instance_id (str): Browser instance in use
+ local_base_url (str): Root URL of the local page server
+ """
+ self.manager = manager
+ self.instance_id = instance_id
+ self.local_base_url = local_base_url
+
+ async def navigate(self, url: str, timeout: float = 45.0) -> None:
+ """
+ Load a URL through BrowserManager.navigate.
+
+ Args:
+ url (str): Page to load
+ timeout (float): Navigation timeout in seconds
+
+ Raises:
+ Unreachable: When navigation fails or times out
+ """
+ try:
+ await self.manager.navigate(self.instance_id, url, wait_until="load", timeout=int(timeout * 1000))
+ except Exception as error:
+ raise Unreachable(f"Navigation to {url} failed: {error}") from error
+
+ async def evaluate(self, expression: str, await_promise: bool = False) -> Any:
+ """
+ Evaluate JavaScript in the current tab.
+
+ Args:
+ expression (str): JavaScript expression
+ await_promise (bool): Await the result when it is a Promise
+
+ Returns:
+ Any: Plain Python value
+
+ Raises:
+ RuntimeError: When the script throws or the tab is gone
+ """
+ tab = await self.manager.get_tab(self.instance_id)
+ if tab is None:
+ raise RuntimeError(f"Instance not found: {self.instance_id}")
+ value, error = await evaluate_to_python(tab, expression, await_promise=await_promise)
+ if error:
+ raise RuntimeError(error)
+ return value
+
+ async def add_init_script(self, source: str) -> str:
+ """
+ Install an init script through BrowserManager.add_init_script.
+
+ Args:
+ source (str): JavaScript source
+
+ Returns:
+ str: Script identifier
+ """
+ return await self.manager.add_init_script(self.instance_id, source)
+
+ async def click(self, selector: str) -> None:
+ """
+ Click through DOMHandler.click_element.
+
+ Args:
+ selector (str): CSS selector
+ """
+ await DOMHandler.click_element(await self.manager.get_tab(self.instance_id), selector)
+
+ async def type_text(self, selector: str, text: str) -> None:
+ """
+ Type through DOMHandler.type_text with a short keystroke delay.
+
+ Args:
+ selector (str): CSS selector
+ text (str): Text to type
+ """
+ await DOMHandler.type_text(await self.manager.get_tab(self.instance_id), selector, text, delay_ms=20)
+
+
+def utc_now() -> datetime:
+ """
+ Current UTC time.
+
+ Returns:
+ datetime: Timezone-aware UTC timestamp
+ """
+ return datetime.now(timezone.utc)
+
+
+def write_raw_payload(raw_dir: Optional[Path], runner: str, target: str, payload: Any) -> None:
+ """
+ Save a raw payload for later inspection.
+
+ Args:
+ raw_dir (Optional[Path]): Root raw directory, or None to skip
+ runner (str): Runner label
+ target (str): Target name
+ payload (Any): Payload returned by collect()
+ """
+ if raw_dir is None:
+ return
+ directory = raw_dir / runner
+ directory.mkdir(parents=True, exist_ok=True)
+ (directory / f"{target}.json").write_text(json.dumps(payload, indent=2, default=str) + "\n", encoding="utf-8")
+
+
+async def browser_version(manager: BrowserManager, options: BrowserOptions) -> Dict[str, Any]:
+ """
+ Start a browser once to read its product version and default user agent.
+
+ Args:
+ manager (BrowserManager): Browser manager
+ options (BrowserOptions): Spawn options used for the run
+
+ Returns:
+ Dict[str, Any]: chrome_product, chrome_version, user_agent, and protocol_version
+ """
+ instance = await manager.spawn_browser(options)
+ try:
+ tab = await manager.get_tab(instance.instance_id)
+ protocol_version, product, _revision, user_agent, _js_version = await tab.send(uc.cdp.browser.get_version())
+ return {
+ "chrome_product": product,
+ "chrome_version": product.split("/", 1)[-1],
+ "user_agent": user_agent,
+ "protocol_version": protocol_version,
+ }
+ finally:
+ await manager.close_instance(instance.instance_id)
+
+
+async def run_target(
+ target: Target,
+ manager: BrowserManager,
+ options: BrowserOptions,
+ local_base_url: str,
+ runner: str,
+ raw_dir: Optional[Path] = None,
+) -> TargetResult:
+ """
+ Run one target in a fresh browser instance.
+
+ Args:
+ target (Target): Target to run
+ manager (BrowserManager): Browser manager
+ options (BrowserOptions): Spawn options
+ local_base_url (str): Root URL of the local page server
+ runner (str): Runner label, used for raw payload paths
+ raw_dir (Optional[Path]): Directory for raw payloads, or None to skip
+
+ Returns:
+ TargetResult: Outcome, UNREACHABLE when the page could not be measured
+ """
+ result = TargetResult(
+ name=target.name,
+ title=target.title,
+ category=target.category,
+ url=target.url.replace("{local}", "local"),
+ status=Status.UNREACHABLE,
+ )
+ started = time.monotonic()
+ instance_id: Optional[str] = None
+ try:
+ instance = await manager.spawn_browser(options)
+ instance_id = instance.instance_id
+ session = BrowserSession(manager, instance_id, local_base_url)
+ payload = await asyncio.wait_for(target.collect(session), timeout=target.timeout)
+ write_raw_payload(raw_dir, runner, target.name, payload)
+ checks, details, summary = target.evaluate(payload)
+ result.checks = checks
+ result.details = details
+ result.summary = summary
+ result.status = status_from_checks(checks)
+ except asyncio.TimeoutError:
+ result.error = f"Timed out after {target.timeout:.0f}s"
+ result.summary = result.error
+ except Unreachable as error:
+ result.error = str(error)
+ result.summary = "Could not be measured"
+ except Exception as error:
+ result.error = f"{type(error).__name__}: {error}"
+ result.summary = "Harness error"
+ finally:
+ if instance_id is not None:
+ try:
+ await manager.close_instance(instance_id)
+ except Exception:
+ pass
+ result.duration_seconds = round(time.monotonic() - started, 2)
+ return result
+
+
+async def run_benchmark(
+ targets: List[Target],
+ mode: str = "headless",
+ channel: str = "stable",
+ label: Optional[str] = None,
+ raw_dir: Optional[Path] = None,
+ progress: Optional[Callable[[TargetResult], None]] = None,
+) -> RunResult:
+ """
+ Run every target and collect a RunResult.
+
+ Args:
+ targets (List[Target]): Targets to run, in order
+ mode (str): headless or headed
+ channel (str): Chrome channel label recorded in the runner label
+ label (Optional[str]): Explicit runner label
+ raw_dir (Optional[Path]): Directory for raw payloads, or None to skip
+ progress (Optional[Callable[[TargetResult], None]]): Called after each target
+
+ Returns:
+ RunResult: Full run outcome
+ """
+ started = utc_now()
+ runner = runner_label(mode, channel, label)
+ options = BrowserOptions(headless=mode == "headless")
+ manager = BrowserManager()
+ environment = base_environment(mode, channel)
+ try:
+ environment.update(await browser_version(manager, options))
+ results: List[TargetResult] = []
+ with LocalPageServer() as server:
+ for target in targets:
+ result = await run_target(target, manager, options, server.base_url, runner, raw_dir)
+ results.append(result)
+ if progress is not None:
+ progress(result)
+ finally:
+ await manager.close_all()
+ return RunResult(
+ runner=runner,
+ date=started.strftime("%Y-%m-%d"),
+ started_at=started.isoformat(timespec="seconds"),
+ finished_at=utc_now().isoformat(timespec="seconds"),
+ environment=environment,
+ targets=results,
+ )
diff --git a/benchmarks/stealth/targets/__init__.py b/benchmarks/stealth/targets/__init__.py
new file mode 100644
index 0000000..5366b7f
--- /dev/null
+++ b/benchmarks/stealth/targets/__init__.py
@@ -0,0 +1,45 @@
+"""Benchmark target registry."""
+
+from typing import Dict, List, Optional
+
+from .base import Target
+from .cloudflare import CloudflareTarget
+from .creepjs import CreepJSTarget
+from .input_fidelity import InputFidelityTarget
+from .local_probe import InitScriptTarget, LocalProbeTarget
+from .result_tables import IntoliTarget, SannysoftTarget
+from .tls_fingerprint import TLSFingerprintTarget
+
+ALL_TARGETS: List[Target] = [
+ LocalProbeTarget(),
+ InitScriptTarget(),
+ InputFidelityTarget(),
+ SannysoftTarget(),
+ IntoliTarget(),
+ CreepJSTarget(),
+ CloudflareTarget(),
+ TLSFingerprintTarget(),
+]
+TARGETS_BY_NAME: Dict[str, Target] = {target.name: target for target in ALL_TARGETS}
+
+
+def select_targets(names: Optional[List[str]] = None) -> List[Target]:
+ """
+ Resolve target names to target objects.
+
+ Args:
+ names (Optional[List[str]]): Target names, or None for every target
+
+ Returns:
+ List[Target]: Targets in registry order
+
+ Raises:
+ ValueError: When a name is unknown
+ """
+ if not names:
+ return list(ALL_TARGETS)
+ unknown = [name for name in names if name not in TARGETS_BY_NAME]
+ if unknown:
+ raise ValueError(f"Unknown targets: {', '.join(unknown)}. Known: {', '.join(TARGETS_BY_NAME)}")
+ wanted = set(names)
+ return [target for target in ALL_TARGETS if target.name in wanted]
diff --git a/benchmarks/stealth/targets/base.py b/benchmarks/stealth/targets/base.py
new file mode 100644
index 0000000..705849a
--- /dev/null
+++ b/benchmarks/stealth/targets/base.py
@@ -0,0 +1,183 @@
+"""Base class and shared helpers for benchmark targets."""
+
+import asyncio
+import time
+from typing import Any, Dict, List, Optional, Protocol, Tuple
+
+from ..results import Check, Status
+
+DEFAULT_POLL_INTERVAL = 0.5
+
+
+class Session(Protocol):
+ """Browser access handed to targets by the runner."""
+
+ local_base_url: str
+
+ async def navigate(self, url: str, timeout: float = 45.0) -> None:
+ """
+ Load a URL in the benchmark tab.
+
+ Args:
+ url (str): Page to load
+ timeout (float): Navigation timeout in seconds
+ """
+
+ async def evaluate(self, expression: str, await_promise: bool = False) -> Any:
+ """
+ Evaluate JavaScript in the benchmark tab.
+
+ Args:
+ expression (str): JavaScript expression
+ await_promise (bool): Await the result when it is a Promise
+
+ Returns:
+ Any: Plain Python value
+ """
+
+ async def add_init_script(self, source: str) -> str:
+ """
+ Install a script that runs before page scripts on new documents.
+
+ Args:
+ source (str): JavaScript source
+
+ Returns:
+ str: Script identifier
+ """
+
+ async def click(self, selector: str) -> None:
+ """
+ Click an element the way the click_element tool does.
+
+ Args:
+ selector (str): CSS selector
+ """
+
+ async def type_text(self, selector: str, text: str) -> None:
+ """
+ Type into an element the way the type_text tool does.
+
+ Args:
+ selector (str): CSS selector
+ text (str): Text to type
+ """
+
+
+class Target:
+ """
+ One detection surface measured by the benchmark.
+
+ Subclasses set the class attributes, gather a raw payload in collect(), and
+ turn that payload into checks in evaluate(). evaluate() must not touch the
+ browser so it can be unit tested with recorded payloads.
+
+ Attributes:
+ name (str): Stable identifier used in result files
+ title (str): Human readable name
+ category (str): Detection surface covered
+ url (str): Page loaded by the target, may use {local} for the local server
+ timeout (float): Overall time budget in seconds
+ """
+
+ name = ""
+ title = ""
+ category = ""
+ url = ""
+ timeout = 90.0
+
+ def resolve_url(self, session: Session) -> str:
+ """
+ Expand the {local} placeholder in the target URL.
+
+ Args:
+ session (Session): Active browser session
+
+ Returns:
+ str: Absolute URL to load
+ """
+ return self.url.format(local=session.local_base_url)
+
+ async def collect(self, session: Session) -> Dict[str, Any]:
+ """
+ Load the target and gather its raw payload.
+
+ Args:
+ session (Session): Active browser session
+
+ Returns:
+ Dict[str, Any]: Raw payload passed to evaluate()
+ """
+ raise NotImplementedError
+
+ def evaluate(self, payload: Dict[str, Any]) -> Tuple[List[Check], Dict[str, Any], str]:
+ """
+ Turn a raw payload into checks.
+
+ Args:
+ payload (Dict[str, Any]): Data returned by collect()
+
+ Returns:
+ Tuple[List[Check], Dict[str, Any], str]: Checks, details to keep, and a one line summary
+ """
+ raise NotImplementedError
+
+
+class Unreachable(Exception):
+ """Raised when a target page could not be loaded or never produced results."""
+
+
+def status_from_checks(checks: List[Check]) -> Status:
+ """
+ Derive a target status from its checks.
+
+ Args:
+ checks (List[Check]): Checks produced by evaluate()
+
+ Returns:
+ Status: FAIL when a critical check failed, DEGRADED when only
+ non-critical checks failed, PASS otherwise, UNREACHABLE when there are no checks
+ """
+ if not checks:
+ return Status.UNREACHABLE
+ if any(not check.passed and check.critical for check in checks):
+ return Status.FAIL
+ if any(not check.passed for check in checks):
+ return Status.DEGRADED
+ return Status.PASS
+
+
+async def wait_for_value(
+ session: Session,
+ expression: str,
+ timeout: float,
+ interval: float = DEFAULT_POLL_INTERVAL,
+) -> Any:
+ """
+ Poll a JavaScript expression until it returns a truthy value.
+
+ Args:
+ session (Session): Active browser session
+ expression (str): Expression to poll
+ timeout (float): Maximum wait in seconds
+ interval (float): Delay between polls in seconds
+
+ Returns:
+ Any: First truthy value
+
+ Raises:
+ Unreachable: When the value stays falsy for the whole timeout
+ """
+ deadline = time.monotonic() + timeout
+ last_error: Optional[Exception] = None
+ while True:
+ try:
+ value = await session.evaluate(expression)
+ if value:
+ return value
+ except Exception as error:
+ last_error = error
+ if time.monotonic() >= deadline:
+ detail = f": {last_error}" if last_error else ""
+ raise Unreachable(f"Timed out after {timeout:.0f}s waiting for results{detail}")
+ await asyncio.sleep(interval)
diff --git a/benchmarks/stealth/targets/cloudflare.py b/benchmarks/stealth/targets/cloudflare.py
new file mode 100644
index 0000000..e2a1c80
--- /dev/null
+++ b/benchmarks/stealth/targets/cloudflare.py
@@ -0,0 +1,87 @@
+"""Cloudflare challenge target backed by nowsecure.nl."""
+
+import asyncio
+import time
+from typing import Any, Dict, List, Tuple
+
+from ..results import Check
+from .base import Session, Target
+
+READ_PAGE_JS = """(() => ({
+ title: document.title,
+ text: (document.body ? document.body.innerText : '').replace(/\\s+/g, ' ').trim().slice(0, 500),
+ challengeFrame: !!document.querySelector('iframe[src*="challenges.cloudflare.com"]')
+}))()"""
+
+CHALLENGE_MARKERS = ("just a moment", "verify you are human", "checking your browser", "attention required")
+SUCCESS_MARKER = "nowsecure"
+CHALLENGE_WAIT_SECONDS = 45.0
+
+
+def is_challenge(page: Dict[str, Any]) -> bool:
+ """
+ Tell whether a page snapshot is still a Cloudflare challenge.
+
+ Args:
+ page (Dict[str, Any]): Snapshot with title, text, and challengeFrame
+
+ Returns:
+ bool: True when challenge markers are present
+ """
+ haystack = f"{page.get('title', '')} {page.get('text', '')}".lower()
+ return bool(page.get("challengeFrame")) or any(marker in haystack for marker in CHALLENGE_MARKERS)
+
+
+class CloudflareTarget(Target):
+ """
+ nowsecure.nl sits behind a Cloudflare challenge and shows a NOWSECURE
+ banner once the browser gets through.
+ """
+
+ name = "cloudflare"
+ title = "Cloudflare (nowsecure.nl)"
+ category = "JS challenge"
+ url = "https://nowsecure.nl/"
+ timeout = 90.0
+
+ async def collect(self, session: Session) -> Dict[str, Any]:
+ """
+ Load the page and wait for the challenge to clear.
+
+ Args:
+ session (Session): Active browser session
+
+ Returns:
+ Dict[str, Any]: Final page snapshot plus seconds spent waiting
+ """
+ await session.navigate(self.resolve_url(session), timeout=40.0)
+ started = time.monotonic()
+ page: Dict[str, Any] = {}
+ while time.monotonic() - started < CHALLENGE_WAIT_SECONDS:
+ page = await session.evaluate(READ_PAGE_JS) or {}
+ if SUCCESS_MARKER in page.get("text", "").lower() and not is_challenge(page):
+ break
+ await asyncio.sleep(1.0)
+ page["waited_seconds"] = round(time.monotonic() - started, 1)
+ return page
+
+ def evaluate(self, payload: Dict[str, Any]) -> Tuple[List[Check], Dict[str, Any], str]:
+ """
+ Decide whether the challenge was passed.
+
+ Args:
+ payload (Dict[str, Any]): Data returned by collect()
+
+ Returns:
+ Tuple[List[Check], Dict[str, Any], str]: Checks, details, and summary
+ """
+ challenged = is_challenge(payload)
+ reached = SUCCESS_MARKER in payload.get("text", "").lower() and not challenged
+ details = {"title": payload.get("title"), "waited_seconds": payload.get("waited_seconds")}
+ if reached:
+ check = Check("challenge cleared", True, True, payload.get("title"))
+ return [check], details, f"Reached protected page after {payload.get('waited_seconds')}s"
+ if challenged:
+ check = Check("challenge cleared", False, True, payload.get("title"))
+ return [check], details, "Stuck on Cloudflare challenge"
+ return [], details, f"Unexpected page: {payload.get('title') or 'no title'}"
diff --git a/benchmarks/stealth/targets/creepjs.py b/benchmarks/stealth/targets/creepjs.py
new file mode 100644
index 0000000..a68c810
--- /dev/null
+++ b/benchmarks/stealth/targets/creepjs.py
@@ -0,0 +1,95 @@
+"""CreepJS headless and stealth scoring target."""
+
+import re
+from typing import Any, Dict, List, Optional, Tuple
+
+from ..results import Check
+from .base import Session, Target, wait_for_value
+
+READ_SCORES_JS = """(() => {
+ const node = document.querySelector('#headless-resistance-detection-results');
+ if (!node) return null;
+ const text = node.innerText;
+ return /\\d+% stealth/.test(text) ? text : null;
+})()"""
+
+SCORE_PATTERNS = {
+ "like_headless": re.compile(r"^\s*(\d+)% like headless", re.IGNORECASE | re.MULTILINE),
+ "headless": re.compile(r"^\s*(\d+)% headless", re.IGNORECASE | re.MULTILINE),
+ "stealth": re.compile(r"^\s*(\d+)% stealth", re.IGNORECASE | re.MULTILINE),
+}
+HEADLESS_FAIL_PERCENT = 50
+
+
+def parse_scores(text: str) -> Dict[str, Optional[int]]:
+ """
+ Extract CreepJS percentages from the headless panel text.
+
+ Args:
+ text (str): innerText of #headless-resistance-detection-results
+
+ Returns:
+ Dict[str, Optional[int]]: like_headless, headless, and stealth percentages, None when missing
+ """
+ scores: Dict[str, Optional[int]] = {}
+ for key, pattern in SCORE_PATTERNS.items():
+ match = pattern.search(text or "")
+ scores[key] = int(match.group(1)) if match else None
+ return scores
+
+
+class CreepJSTarget(Target):
+ """
+ CreepJS fingerprint analysis.
+
+ Any stealth score means CreepJS saw tampered APIs and fails the target. A
+ headless score of 50% or more fails it, a lower nonzero score degrades it.
+ The like headless score is recorded only, real Chrome reports some.
+ """
+
+ name = "creepjs"
+ title = "CreepJS"
+ category = "Deep fingerprinting"
+ url = "https://abrahamjuliot.github.io/creepjs/"
+ timeout = 120.0
+
+ async def collect(self, session: Session) -> Dict[str, Any]:
+ """
+ Load CreepJS and wait for the headless panel to finish scoring.
+
+ Args:
+ session (Session): Active browser session
+
+ Returns:
+ Dict[str, Any]: {"panel_text": str}
+ """
+ await session.navigate(self.resolve_url(session), timeout=60.0)
+ text = await wait_for_value(session, READ_SCORES_JS, timeout=75.0)
+ return {"panel_text": text}
+
+ def evaluate(self, payload: Dict[str, Any]) -> Tuple[List[Check], Dict[str, Any], str]:
+ """
+ Turn CreepJS scores into checks.
+
+ Args:
+ payload (Dict[str, Any]): Data returned by collect()
+
+ Returns:
+ Tuple[List[Check], Dict[str, Any], str]: Checks, details, and summary
+ """
+ scores = parse_scores(payload.get("panel_text", ""))
+ headless = scores["headless"]
+ stealth = scores["stealth"]
+ checks: List[Check] = []
+ if headless is not None:
+ checks.append(Check("headless score below 50%", headless < HEADLESS_FAIL_PERCENT, True, headless))
+ checks.append(Check("headless score is 0%", headless == 0, False, headless))
+ if stealth is not None:
+ checks.append(Check("stealth score is 0%", stealth == 0, True, stealth))
+ details = {f"{key}_percent": value for key, value in scores.items()}
+ summary = ", ".join(
+ f"{value}% {label}"
+ for label, value in (("headless", headless), ("stealth", stealth), ("like headless", scores["like_headless"]))
+ if value is not None
+ )
+ return checks, details, summary or "Scores not found"
diff --git a/benchmarks/stealth/targets/input_fidelity.py b/benchmarks/stealth/targets/input_fidelity.py
new file mode 100644
index 0000000..2a6f1ef
--- /dev/null
+++ b/benchmarks/stealth/targets/input_fidelity.py
@@ -0,0 +1,85 @@
+"""Offline target that checks clicks and typing look like real user input."""
+
+from typing import Any, Dict, List, Tuple
+
+from ..results import Check
+from .base import Session, Target, wait_for_value
+
+TYPED_TEXT = "Probe Text 42!"
+READ_PROBE_JS = "window.__inputProbe ? JSON.parse(JSON.stringify(window.__inputProbe)) : null"
+READ_VALUE_JS = "document.getElementById('field').value"
+RESET_PROBE_JS = "Object.assign(window.__inputProbe, { events: [], added: 0, moves: 0 }) && true"
+CLICK_SEQUENCE = ["pointerdown", "mousedown", "mouseup", "click"]
+
+
+class InputFidelityTarget(Target):
+ """
+ Clicks a button below the fold and types into a field through the same
+ code paths as the click_element and type_text tools, then checks the
+ events the page saw.
+ """
+
+ name = "input_fidelity"
+ title = "Input fidelity"
+ category = "Interaction"
+ url = "{local}/input.html"
+ timeout = 45.0
+
+ async def collect(self, session: Session) -> Dict[str, Any]:
+ """
+ Click and type on the input probe page.
+
+ Args:
+ session (Session): Active browser session
+
+ Returns:
+ Dict[str, Any]: Recorded events, mouse move count, injected node count, and the typed value
+ """
+ await session.navigate(self.resolve_url(session), timeout=20.0)
+ await wait_for_value(session, READ_PROBE_JS, timeout=10.0)
+ await session.evaluate(RESET_PROBE_JS)
+ await session.click("#target")
+ await session.type_text("#field", TYPED_TEXT)
+ probe = await session.evaluate(READ_PROBE_JS)
+ probe["value"] = await session.evaluate(READ_VALUE_JS)
+ return probe
+
+ def evaluate(self, payload: Dict[str, Any]) -> Tuple[List[Check], Dict[str, Any], str]:
+ """
+ Turn recorded input events into checks.
+
+ Args:
+ payload (Dict[str, Any]): Data returned by collect()
+
+ Returns:
+ Tuple[List[Check], Dict[str, Any], str]: Checks, details, and summary
+ """
+ events = payload.get("events") or []
+ mouse = [event for event in events if event["type"] in CLICK_SEQUENCE]
+ keys = [event for event in events if event["type"] in ("keydown", "keyup", "input")]
+ clicks = [event for event in mouse if event["type"] == "click"]
+ downs = [event for event in mouse if event["type"] == "mousedown"]
+ ups = [event for event in mouse if event["type"] == "mouseup"]
+ press_ms = round(ups[0]["time"] - downs[0]["time"], 1) if downs and ups else None
+ printable = list(TYPED_TEXT)
+ keydown_keys = [event["key"] for event in keys if event["type"] == "keydown" and event["key"] != "Shift"]
+ keyup_count = sum(1 for event in keys if event["type"] == "keyup" and event["key"] != "Shift")
+ checks = [
+ Check("click is trusted", bool(clicks) and all(event["trusted"] for event in clicks), True, len(clicks)),
+ Check(
+ "click has pointer and mouse events",
+ [event["type"] for event in mouse] == CLICK_SEQUENCE,
+ True,
+ [event["type"] for event in mouse],
+ ),
+ Check("mouse moved before click", (payload.get("moves") or 0) > 0, False, payload.get("moves")),
+ Check("button held for a moment", press_ms is not None and press_ms > 5, False, press_ms),
+ Check("key events are trusted", bool(keys) and all(event["trusted"] for event in keys), True, len(keys)),
+ Check("every character has keydown", keydown_keys == printable, True, "".join(key or "" for key in keydown_keys)),
+ Check("every keydown has keyup", keyup_count == len(printable), True, keyup_count),
+ Check("typed value is exact", payload.get("value") == TYPED_TEXT, True, payload.get("value")),
+ Check("no nodes injected into the page", (payload.get("added") or 0) == 0, True, payload.get("added")),
+ ]
+ passed = sum(1 for check in checks if check.passed)
+ details = {"press_ms": press_ms, "mouse_moves": payload.get("moves"), "injected_nodes": payload.get("added")}
+ return checks, details, f"{passed}/{len(checks)} checks passed"
diff --git a/benchmarks/stealth/targets/local_probe.py b/benchmarks/stealth/targets/local_probe.py
new file mode 100644
index 0000000..b224227
--- /dev/null
+++ b/benchmarks/stealth/targets/local_probe.py
@@ -0,0 +1,241 @@
+"""Offline targets that load the bundled probe page from the local server."""
+
+import re
+from typing import Any, Dict, List, Tuple
+
+from ..results import Check
+from .base import Session, Target, wait_for_value
+
+READ_PROBE_JS = "window.__stealthProbe || null"
+READ_OUTER_JS = "[window.outerWidth, window.outerHeight]"
+SOFTWARE_RENDERER = re.compile(r"swiftshader|llvmpipe|software", re.IGNORECASE)
+PLATFORM_FAMILIES = {
+ "Windows": ("Win",),
+ "macOS": ("Mac",),
+ "Linux": ("Linux",),
+ "Chrome OS": ("Linux", "CrOS"),
+ "Android": ("Linux",),
+}
+SPOOFED_RENDERER = "Stealth Benchmark Renderer"
+INIT_MARKER = "installed"
+INIT_SCRIPT = f"""
+window.__sbmInitMarker = {INIT_MARKER!r};
+(() => {{
+ const original = WebGLRenderingContext.prototype.getParameter;
+ WebGLRenderingContext.prototype.getParameter = function (parameter) {{
+ if (parameter === 37446) return {SPOOFED_RENDERER!r};
+ return original.call(this, parameter);
+ }};
+}})();
+"""
+
+
+def platform_matches(navigator_platform: str, ua_platform: str) -> bool:
+ """
+ Check that navigator.platform agrees with the client hints platform.
+
+ Args:
+ navigator_platform (str): navigator.platform value
+ ua_platform (str): navigator.userAgentData.platform value
+
+ Returns:
+ bool: True when consistent or when either value is unavailable
+ """
+ if not navigator_platform or not ua_platform:
+ return True
+ prefixes = PLATFORM_FAMILIES.get(ua_platform)
+ if prefixes is None:
+ return True
+ return navigator_platform.startswith(prefixes)
+
+
+class LocalProbeTarget(Target):
+ """
+ Bundled fingerprint probe served from 127.0.0.1.
+
+ It needs no network access, so it is the most stable regression signal in
+ the suite. It covers the classic headless and automation tells.
+ """
+
+ name = "local_probe"
+ title = "Local fingerprint probe"
+ category = "Automation tells"
+ url = "{local}/probe.html"
+ timeout = 45.0
+
+ async def collect(self, session: Session) -> Dict[str, Any]:
+ """
+ Load the probe page and read its findings.
+
+ Args:
+ session (Session): Active browser session
+
+ Returns:
+ Dict[str, Any]: Values recorded by the probe page, plus the outer
+ window size read after load
+ """
+ await session.navigate(self.resolve_url(session), timeout=20.0)
+ payload = await wait_for_value(session, READ_PROBE_JS, timeout=15.0)
+ payload["outerAfterLoad"] = await session.evaluate(READ_OUTER_JS)
+ return payload
+
+ def evaluate(self, payload: Dict[str, Any]) -> Tuple[List[Check], Dict[str, Any], str]:
+ """
+ Turn probe findings into checks.
+
+ Args:
+ payload (Dict[str, Any]): Data returned by collect()
+
+ Returns:
+ Tuple[List[Check], Dict[str, Any], str]: Checks, details, and summary
+ """
+ user_agent = payload.get("userAgent") or ""
+ brands = payload.get("brands") or []
+ languages = payload.get("languages") or []
+ outer = payload.get("outerAfterLoad") or payload.get("outer") or [0, 0]
+ renderer = payload.get("webglRenderer") or ""
+ notification = payload.get("notificationPermission")
+ query = payload.get("permissionQuery")
+ checks = [
+ Check("navigator.webdriver is not true", payload.get("webdriver") is not True, True, payload.get("webdriver")),
+ Check("user agent has no HeadlessChrome", "HeadlessChrome" not in user_agent, True, user_agent),
+ Check(
+ "client hints have no HeadlessChrome",
+ not any("Headless" in brand for brand in brands),
+ True,
+ brands,
+ ),
+ Check("window.chrome present", bool(payload.get("hasChrome")), True, payload.get("hasChrome")),
+ Check(
+ "plugins present",
+ bool(payload.get("pluginsIsArray")) and (payload.get("plugins") or 0) > 0,
+ True,
+ payload.get("plugins"),
+ ),
+ Check(
+ "languages consistent",
+ bool(languages) and payload.get("language") == languages[0],
+ True,
+ languages,
+ ),
+ Check(
+ "notification permission consistent",
+ not (notification == "denied" and query == "prompt"),
+ True,
+ f"{notification}/{query}",
+ ),
+ Check("window has outer size", all(size > 0 for size in outer), True, outer),
+ Check(
+ "iframe navigator.webdriver is not true",
+ payload.get("iframeWebdriver") is not True,
+ True,
+ payload.get("iframeWebdriver"),
+ ),
+ Check(
+ "platform matches client hints",
+ platform_matches(payload.get("platform") or "", payload.get("uaPlatform") or ""),
+ False,
+ f"{payload.get('platform')}/{payload.get('uaPlatform')}",
+ ),
+ Check("iframe window.chrome present", bool(payload.get("iframeChrome")), False, payload.get("iframeChrome")),
+ Check("WebGL renderer is hardware", bool(renderer) and not SOFTWARE_RENDERER.search(renderer), False, renderer),
+ Check(
+ "console does not read Error.stack",
+ not payload.get("consoleStackRead"),
+ False,
+ payload.get("consoleStackRead"),
+ ),
+ ]
+ details = {
+ "user_agent": user_agent,
+ "platform": payload.get("platform"),
+ "brands": brands,
+ "languages": languages,
+ "hardware_concurrency": payload.get("hardwareConcurrency"),
+ "webgl_vendor": payload.get("webglVendor"),
+ "webgl_renderer": renderer or None,
+ "outer_size": outer,
+ "outer_size_at_load": payload.get("outer"),
+ "screen": payload.get("screen"),
+ }
+ passed = sum(1 for check in checks if check.passed)
+ return checks, details, f"{passed}/{len(checks)} checks passed"
+
+
+class InitScriptTarget(Target):
+ """
+ Capability check for add_script_to_evaluate_on_new_document (issue #22).
+
+ Installs a script through BrowserManager.add_init_script that sets a marker
+ and spoofs the WebGL renderer, then verifies it ran before page scripts and
+ survives a second navigation.
+ """
+
+ name = "init_script"
+ title = "Init script injection"
+ category = "Capability"
+ url = "{local}/probe.html"
+ timeout = 45.0
+
+ async def collect(self, session: Session) -> Dict[str, Any]:
+ """
+ Install the init script and load the probe page twice.
+
+ Args:
+ session (Session): Active browser session
+
+ Returns:
+ Dict[str, Any]: Probe findings for the first and second load
+ """
+ identifier = await session.add_init_script(INIT_SCRIPT)
+ loads = []
+ for suffix in ("?load=1", "?load=2"):
+ await session.navigate(self.resolve_url(session) + suffix, timeout=20.0)
+ probe = await wait_for_value(session, READ_PROBE_JS, timeout=15.0)
+ loads.append(
+ {
+ "initMarkerAtParse": probe.get("initMarkerAtParse"),
+ "webgl": probe.get("webgl"),
+ "webglRenderer": probe.get("webglRenderer"),
+ }
+ )
+ return {"identifier": identifier, "loads": loads}
+
+ def evaluate(self, payload: Dict[str, Any]) -> Tuple[List[Check], Dict[str, Any], str]:
+ """
+ Check that the init script ran on both loads.
+
+ Args:
+ payload (Dict[str, Any]): Data returned by collect()
+
+ Returns:
+ Tuple[List[Check], Dict[str, Any], str]: Checks, details, and summary
+ """
+ loads = payload.get("loads") or [{}, {}]
+ first, second = (loads + [{}, {}])[:2]
+ checks = [
+ Check("script installed", bool(payload.get("identifier")), True, payload.get("identifier")),
+ Check(
+ "ran before page scripts",
+ first.get("initMarkerAtParse") == INIT_MARKER,
+ True,
+ first.get("initMarkerAtParse"),
+ ),
+ Check(
+ "persists across navigation",
+ second.get("initMarkerAtParse") == INIT_MARKER,
+ True,
+ second.get("initMarkerAtParse"),
+ ),
+ ]
+ if first.get("webgl"):
+ checks.append(
+ Check(
+ "WebGL renderer override applied",
+ first.get("webglRenderer") == SPOOFED_RENDERER,
+ False,
+ first.get("webglRenderer"),
+ )
+ )
+ passed = sum(1 for check in checks if check.passed)
+ return checks, {"webgl_renderer": first.get("webglRenderer")}, f"{passed}/{len(checks)} checks passed"
diff --git a/benchmarks/stealth/targets/result_tables.py b/benchmarks/stealth/targets/result_tables.py
new file mode 100644
index 0000000..22c5ee2
--- /dev/null
+++ b/benchmarks/stealth/targets/result_tables.py
@@ -0,0 +1,107 @@
+"""Targets for detection pages that report results as passed or failed table cells."""
+
+import asyncio
+from typing import Any, Dict, List, Tuple
+
+from ..results import Check
+from .base import Session, Target, Unreachable, wait_for_value
+
+COLLECT_ROWS_JS = """(() => {
+ const rows = [];
+ for (const row of document.querySelectorAll('table tr')) {
+ const cells = Array.from(row.cells);
+ if (cells.length < 2) continue;
+ const cell = cells.slice(1).find(c => /\\b(passed|failed|warn)\\b/.test(c.className));
+ if (!cell) continue;
+ const verdict = cell.className.match(/\\b(passed|failed|warn)\\b/)[1];
+ rows.push({
+ name: cells[0].innerText.replace(/\\s+/g, ' ').trim(),
+ verdict: verdict,
+ value: cell.innerText.replace(/\\s+/g, ' ').trim().slice(0, 200)
+ });
+ }
+ return rows.length >= MIN_ROWS ? rows : null;
+})()"""
+
+
+class ResultTableTarget(Target):
+ """
+ Detection page where each result cell carries a passed, failed, or warn class.
+
+ A failed cell fails the target and a warn cell degrades it.
+
+ Attributes:
+ min_rows (int): Rows that must be present before results are read
+ settle_seconds (float): Extra wait after the rows appear, for late async tests
+ """
+
+ min_rows = 1
+ settle_seconds = 3.0
+
+ async def collect(self, session: Session) -> Dict[str, Any]:
+ """
+ Load the page and read every verdict cell.
+
+ Args:
+ session (Session): Active browser session
+
+ Returns:
+ Dict[str, Any]: {"rows": [{"name", "verdict", "value"}, ...]}
+ """
+ await session.navigate(self.resolve_url(session))
+ expression = COLLECT_ROWS_JS.replace("MIN_ROWS", str(self.min_rows))
+ await wait_for_value(session, expression, timeout=self.timeout / 2)
+ if self.settle_seconds:
+ await asyncio.sleep(self.settle_seconds)
+ rows = await session.evaluate(expression)
+ if not rows:
+ raise Unreachable("Result table disappeared after loading")
+ return {"rows": rows}
+
+ def evaluate(self, payload: Dict[str, Any]) -> Tuple[List[Check], Dict[str, Any], str]:
+ """
+ Turn verdict cells into checks.
+
+ Args:
+ payload (Dict[str, Any]): Data returned by collect()
+
+ Returns:
+ Tuple[List[Check], Dict[str, Any], str]: Checks, details, and summary
+ """
+ rows = payload.get("rows") or []
+ checks = [
+ Check(
+ name=row["name"],
+ passed=row["verdict"] == "passed",
+ critical=row["verdict"] != "warn",
+ value=row.get("value"),
+ )
+ for row in rows
+ ]
+ passed = sum(1 for check in checks if check.passed)
+ summary = f"{passed}/{len(checks)} checks passed"
+ failed = [check.name for check in checks if not check.passed]
+ if failed:
+ summary += f", failed: {', '.join(failed)}"
+ details = {row["name"]: row.get("value") for row in rows}
+ return checks, details, summary
+
+
+class SannysoftTarget(ResultTableTarget):
+ """bot.sannysoft.com headless and fingerprint table."""
+
+ name = "sannysoft"
+ title = "Sannysoft"
+ category = "Bot detection suite"
+ url = "https://bot.sannysoft.com/"
+ min_rows = 25
+
+
+class IntoliTarget(ResultTableTarget):
+ """Intoli headless Chrome detection page."""
+
+ name = "intoli"
+ title = "Intoli"
+ category = "Headless detection"
+ url = "https://intoli.com/blog/not-possible-to-block-chrome-headless/chrome-headless-test.html"
+ min_rows = 6
diff --git a/benchmarks/stealth/targets/tls_fingerprint.py b/benchmarks/stealth/targets/tls_fingerprint.py
new file mode 100644
index 0000000..ce10a00
--- /dev/null
+++ b/benchmarks/stealth/targets/tls_fingerprint.py
@@ -0,0 +1,98 @@
+"""TLS and HTTP/2 fingerprint target backed by tls.peet.ws."""
+
+import json
+from typing import Any, Dict, List, Tuple
+
+from ..results import Check
+from .base import Session, Target, Unreachable, wait_for_value
+
+READ_JSON_JS = """(() => {
+ const pre = document.querySelector('pre');
+ const text = (pre ? pre.innerText : (document.body ? document.body.innerText : '')).trim();
+ if (!text.startsWith('{')) return null;
+ try {
+ JSON.parse(text);
+ return text;
+ } catch (error) {
+ return null;
+ }
+})()"""
+
+CHROME_AKAMAI_FINGERPRINT = "1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p"
+CHROME_JA4_CIPHER_HASH = "8daaf6152771"
+PRIVATE_KEYS = ("ip",)
+
+
+class TLSFingerprintTarget(Target):
+ """
+ Records the TLS (JA3, JA4, PeetPrint) and HTTP/2 (Akamai) fingerprints the
+ server sees. The header user agent and protocol checks are critical, the
+ match against known Chrome fingerprints only degrades the target because
+ those values shift with Chrome releases.
+ """
+
+ name = "tls"
+ title = "TLS and HTTP/2 fingerprint"
+ category = "Network fingerprinting"
+ url = "https://tls.peet.ws/api/all"
+ timeout = 60.0
+
+ async def collect(self, session: Session) -> Dict[str, Any]:
+ """
+ Load the fingerprint API and parse its JSON.
+
+ Args:
+ session (Session): Active browser session
+
+ Returns:
+ Dict[str, Any]: API response without the client IP address
+ """
+ await session.navigate(self.resolve_url(session), timeout=40.0)
+ text = await wait_for_value(session, READ_JSON_JS, timeout=15.0)
+ try:
+ payload = json.loads(text)
+ except ValueError as error:
+ raise Unreachable(f"Fingerprint API returned invalid JSON: {error}") from error
+ for key in PRIVATE_KEYS:
+ payload.pop(key, None)
+ return payload
+
+ def evaluate(self, payload: Dict[str, Any]) -> Tuple[List[Check], Dict[str, Any], str]:
+ """
+ Turn the fingerprint response into checks.
+
+ Args:
+ payload (Dict[str, Any]): Data returned by collect()
+
+ Returns:
+ Tuple[List[Check], Dict[str, Any], str]: Checks, details, and summary
+ """
+ tls = payload.get("tls") or {}
+ http2 = payload.get("http2") or {}
+ user_agent = payload.get("user_agent") or ""
+ ja4 = tls.get("ja4") or ""
+ ja4_parts = ja4.split("_")
+ akamai = http2.get("akamai_fingerprint") or ""
+ checks = [
+ Check("header user agent has no HeadlessChrome", "HeadlessChrome" not in user_agent, True, user_agent),
+ Check("HTTP/2 negotiated", payload.get("http_version") == "h2", True, payload.get("http_version")),
+ Check("TLS 1.3 negotiated", ja4.startswith("t13"), True, ja4[:10]),
+ Check("Chrome HTTP/2 fingerprint", akamai == CHROME_AKAMAI_FINGERPRINT, False, akamai),
+ Check(
+ "Chrome JA4 cipher hash",
+ len(ja4_parts) > 1 and ja4_parts[1] == CHROME_JA4_CIPHER_HASH,
+ False,
+ ja4_parts[1] if len(ja4_parts) > 1 else None,
+ ),
+ ]
+ details = {
+ "user_agent": user_agent,
+ "http_version": payload.get("http_version"),
+ "ja3_hash": tls.get("ja3_hash"),
+ "ja4": ja4 or None,
+ "peetprint_hash": tls.get("peetprint_hash"),
+ "akamai_fingerprint": akamai or None,
+ "akamai_fingerprint_hash": http2.get("akamai_fingerprint_hash"),
+ }
+ summary = f"JA4 {ja4 or 'unknown'}, HTTP/2 {http2.get('akamai_fingerprint_hash') or 'unknown'}"
+ return checks, details, summary
diff --git a/skills/stealth-browser-mcp/SKILL.md b/skills/stealth-browser-mcp/SKILL.md
index 9df7d88..25b397b 100644
--- a/skills/stealth-browser-mcp/SKILL.md
+++ b/skills/stealth-browser-mcp/SKILL.md
@@ -18,7 +18,8 @@ description: Use this skill when operating stealth-browser-mcp from an AI agent
- Use `--minimal` when an agent only needs browser spawning, navigation, screenshots, page content, and basic interaction.
- Use full mode for CDP execution, network debugging, cookie/storage work, dynamic hooks, and advanced element extraction.
-- Use `press_key` when a widget needs a real key event, such as Enter or arrow keys in a react-select or typeahead field. Those widgets ignore the synthetic events produced by `type_text(parse_newlines=True)` and discard the value on blur.
+- `click_element`, `type_text`, and `press_key` all send trusted input events. Use `press_key` for control keys such as Enter, Tab, Escape, or arrow keys in react-select and typeahead fields, and `paste_text` when speed matters more than per-key events.
+- Use `create_page_binding` when page JavaScript needs to ask the agent for a value. Read calls with `get_page_binding_calls` (it can wait) and answer with `resolve_page_binding_call`.
- Use `execute_script` for normal page JavaScript.
- Use `execute_cdp_command` only when a CDP primitive is required or when page JavaScript cannot access the needed browser state.
- Use network tools after navigation starts: `list_network_requests`, `search_network_requests`, `get_request_details`, `get_response_details`, and `get_response_content`.
diff --git a/src/browser_manager.py b/src/browser_manager.py
index 6ee02b3..52ef31d 100644
--- a/src/browser_manager.py
+++ b/src/browser_manager.py
@@ -5,7 +5,7 @@ import asyncio
import os
import time
import uuid
-from typing import Any, Dict, Optional, List
+from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple
from datetime import datetime
import nodriver as uc
@@ -27,6 +27,17 @@ from proxy_utils import (
redact_launch_arg,
)
+HEADLESS_UA_TOKEN = "HeadlessChrome/"
+HEADLESS_UA_PROBE_TIMEOUT = 20.0
+CLOSE_STEP_TIMEOUT = 2.0
+TARGET_UPDATE_EVENTS = (
+ uc.cdp.target.TargetInfoChanged,
+ uc.cdp.target.TargetCreated,
+ uc.cdp.target.TargetDestroyed,
+ uc.cdp.target.TargetCrashed,
+)
+PROCESS_EXIT_TIMEOUT = 3.0
+
def _parse_nonnegative_int_env(
name: str,
@@ -59,7 +70,6 @@ def _parse_nonnegative_int_env(
class BrowserManager:
"""Manages multiple browser instances."""
- NAVIGATION_RECYCLE_THRESHOLD = 25
DEFAULT_IDLE_TIMEOUT_SECONDS = 600
DEFAULT_IDLE_REAPER_INTERVAL_SECONDS = 60
@@ -78,6 +88,13 @@ class BrowserManager:
minimum=1,
)
self._idle_reaper_task: Optional[asyncio.Task] = None
+ self._headless_user_agents: Dict[Tuple[str, int], Optional[str]] = {}
+ self._close_listeners: List[Callable[[str], Awaitable[Any]]] = []
+ self._tab_listeners: List[Callable[[Tab, str, BrowserOptions], Awaitable[Any]]] = []
+ self._tab_recycle_navigations = _parse_nonnegative_int_env(
+ "BROWSER_TAB_RECYCLE_NAVIGATIONS",
+ 0,
+ )
@staticmethod
def _append_user_agent_arg(args: List[str], user_agent: Optional[str]) -> List[str]:
@@ -89,6 +106,109 @@ class BrowserManager:
filtered.append(f"{ua_prefix}{user_agent}")
return filtered
+ @staticmethod
+ def _has_user_agent_arg(args: List[str]) -> bool:
+ """
+ Check whether launch arguments already set a user agent.
+
+ Args:
+ args (List[str]): Browser launch arguments.
+
+ Returns:
+ bool: True when a --user-agent argument is present.
+ """
+ return any(arg.startswith("--user-agent=") for arg in args)
+
+ @staticmethod
+ def _headful_user_agent(user_agent: str) -> Optional[str]:
+ """
+ Remove the headless marker from a Chrome user agent.
+
+ Args:
+ user_agent (str): User agent reported by the browser.
+
+ Returns:
+ Optional[str]: User agent with HeadlessChrome replaced by Chrome, or None when no marker is present.
+ """
+ if HEADLESS_UA_TOKEN not in user_agent:
+ return None
+ return user_agent.replace(HEADLESS_UA_TOKEN, "Chrome/")
+
+ async def _resolve_headless_user_agent(
+ self,
+ browser_executable: str,
+ sandbox: bool,
+ launch_args: List[str],
+ ) -> Optional[str]:
+ """
+ Find the user agent a headless browser should launch with.
+
+ Headless Chrome reports HeadlessChrome in navigator.userAgent, workers,
+ and the User-Agent header. A short probe launch reads the real string,
+ and the cleaned value is cached per executable build so later spawns
+ skip the probe.
+
+ Args:
+ browser_executable (str): Browser executable path.
+ sandbox (bool): Whether the sandbox is enabled.
+ launch_args (List[str]): Launch arguments for the real spawn.
+
+ Returns:
+ Optional[str]: Cleaned user agent, or None when the probe fails or no marker is present.
+ """
+ try:
+ build = os.stat(browser_executable).st_mtime_ns
+ except OSError:
+ build = 0
+ cache_key = (browser_executable, build)
+ if cache_key in self._headless_user_agents:
+ return self._headless_user_agents[cache_key]
+
+ probe: Optional[Browser] = None
+ probe_id = f"ua-probe-{uuid.uuid4()}"
+ user_agent: Optional[str] = None
+ try:
+ probe = await asyncio.wait_for(
+ uc.start(config=uc.Config(
+ headless=True,
+ sandbox=sandbox,
+ browser_executable_path=browser_executable,
+ browser_args=list(launch_args),
+ )),
+ timeout=HEADLESS_UA_PROBE_TIMEOUT,
+ )
+ if getattr(probe, "_process", None):
+ process_cleanup.track_browser_process(
+ probe_id,
+ probe._process,
+ user_data_dir=getattr(probe.config, "user_data_dir", None),
+ uses_custom_data_dir=False,
+ )
+ version = await asyncio.wait_for(
+ probe.main_tab.send(uc.cdp.browser.get_version()),
+ timeout=HEADLESS_UA_PROBE_TIMEOUT,
+ )
+ user_agent = self._headful_user_agent(version[3])
+ except Exception as error:
+ debug_logger.log_warning(
+ "browser_manager",
+ "resolve_headless_user_agent",
+ f"Could not read the headless user agent: {error}",
+ )
+ return None
+ finally:
+ if probe is not None:
+ try:
+ await self._shutdown_browser(probe)
+ except Exception:
+ pass
+ try:
+ await asyncio.to_thread(process_cleanup.kill_browser_process, probe_id)
+ except Exception:
+ pass
+ self._headless_user_agents[cache_key] = user_agent
+ return user_agent
+
@staticmethod
def _build_spawn_diagnostics(
*,
@@ -131,11 +251,23 @@ class BrowserManager:
return trimmed_timezone
@staticmethod
- async def _stop_browser(browser: Browser) -> None:
- """Stop a nodriver browser regardless of sync or async stop semantics."""
- stop_result = browser.stop()
- if asyncio.iscoroutine(stop_result):
- await stop_result
+ def _finalize_process_cleanup(instance_id: str, kill_first: bool = False) -> None:
+ """
+ Finish process and profile cleanup for a closed instance.
+
+ Blocking, meant to run in a worker thread.
+
+ Args:
+ instance_id (str): Browser instance ID.
+ kill_first (bool): Kill the tracked process before finalizing.
+
+ Returns:
+ None
+ """
+ if kill_first:
+ process_cleanup.kill_browser_process(instance_id)
+ process_cleanup.finalize_browser_process(instance_id)
+ process_cleanup.cleanup_deferred_profiles()
async def _close_proxy_forwarder(self, instance_id: str) -> None:
"""Close and forget any authenticated proxy forwarder for an instance."""
@@ -186,7 +318,7 @@ class BrowserManager:
await asyncio.sleep(self._idle_reaper_interval_seconds)
try:
closed_count = await self.cleanup_inactive()
- finalized_profiles = process_cleanup.cleanup_deferred_profiles()
+ finalized_profiles = await asyncio.to_thread(process_cleanup.cleanup_deferred_profiles)
if closed_count:
debug_logger.log_info(
"browser_manager",
@@ -322,7 +454,14 @@ class BrowserManager:
launch_proxy_server,
)
launch_args = merge_browser_args(caller_args)
-
+ if options.headless and not self._has_user_agent_arg(launch_args):
+ headful_user_agent = await self._resolve_headless_user_agent(
+ browser_executable,
+ options.sandbox,
+ launch_args,
+ )
+ launch_args = self._append_user_agent_arg(launch_args, headful_user_agent)
+
config = uc.Config(
headless=options.headless,
user_data_dir=options.user_data_dir,
@@ -352,11 +491,6 @@ class BrowserManager:
debug_logger.log_warning("browser_manager", "spawn_browser",
f"Browser {instance_id} has no process to track")
- if options.extra_headers:
- await tab.send(uc.cdp.network.set_extra_http_headers(
- headers=uc.cdp.network.Headers(options.extra_headers)
- ))
-
await tab.set_window_size(
left=0,
top=0,
@@ -369,11 +503,15 @@ class BrowserManager:
f"Set viewport to {options.viewport_width}x{options.viewport_height}",
)
- applied_timezone_id = await self._apply_timezone_override(
- tab=tab,
- timezone_id=options.timezone_id,
+ init_scripts: List[Dict[str, Any]] = []
+ configured_tabs: set = set()
+ applied_timezone_id = await self._configure_tab(
+ tab,
+ instance_id,
+ options,
+ init_scripts,
+ configured_tabs,
)
-
await self._setup_dynamic_hooks(tab, instance_id)
spawn_diagnostics = self._build_spawn_diagnostics(
@@ -397,6 +535,8 @@ class BrowserManager:
'instance': instance,
'options': options,
'navigation_count': 0,
+ 'init_scripts': init_scripts,
+ 'configured_tabs': configured_tabs,
'idle_timeout_seconds': idle_timeout_seconds,
'spawn_diagnostics': spawn_diagnostics,
'network_data': []
@@ -419,7 +559,7 @@ class BrowserManager:
pass
if browser is not None:
try:
- await self._stop_browser(browser)
+ await self._shutdown_browser(browser)
except Exception:
pass
if proxy_forwarder is not None:
@@ -428,7 +568,7 @@ class BrowserManager:
except Exception:
pass
try:
- process_cleanup.kill_browser_process(instance_id)
+ await asyncio.to_thread(process_cleanup.kill_browser_process, instance_id)
except Exception:
pass
instance.state = BrowserState.ERROR
@@ -488,154 +628,132 @@ class BrowserManager:
"""
Close and remove a browser instance.
+ The instance is removed first so other calls stop using it, then
+ Chrome is asked to exit over CDP, the connections are dropped, the
+ process is waited on (and killed if it lingers), and process, profile,
+ proxy, and listener cleanup runs.
+
Args:
instance_id (str): The ID of the browser instance to close.
Returns:
- bool: True if closed successfully, False otherwise.
+ bool: True if the instance existed and was closed, False otherwise.
"""
- import asyncio
-
- async def _do_close():
- async with self._lock:
- if instance_id not in self._instances:
- return False
+ async with self._lock:
+ data = self._instances.pop(instance_id, None)
+ if data is None:
+ return False
- data = self._instances[instance_id]
- browser = data['browser']
- instance = data['instance']
+ browser: Browser = data["browser"]
+ data["instance"].state = BrowserState.CLOSED
+ self._spawn_diagnostics.pop(instance_id, None)
+ persistent_storage.remove_instance(instance_id)
- await dynamic_hook_system.cleanup_instance(instance_id)
+ try:
+ await asyncio.wait_for(dynamic_hook_system.cleanup_instance(instance_id), CLOSE_STEP_TIMEOUT)
+ except Exception:
+ dynamic_hook_system.cancel_instance(instance_id)
- try:
- if hasattr(browser, 'tabs') and browser.tabs:
- for tab in browser.tabs[:]:
- try:
- await tab.close()
- except Exception:
- pass
- except Exception:
- pass
+ await self._shutdown_browser(browser)
- try:
- import asyncio
- if hasattr(browser, 'connection') and browser.connection:
- asyncio.get_event_loop().create_task(browser.connection.disconnect())
- debug_logger.log_info("browser_manager", "close_connection", "closed connection using get_event_loop().create_task()")
- except RuntimeError:
- try:
- import asyncio
- if hasattr(browser, 'connection') and browser.connection:
- await asyncio.wait_for(browser.connection.disconnect(), timeout=2.0)
- debug_logger.log_info("browser_manager", "close_connection", "closed connection with direct await and timeout")
- except (asyncio.TimeoutError, Exception) as e:
- debug_logger.log_info("browser_manager", "close_connection", f"connection disconnect failed or timed out: {e}")
- pass
- except Exception as e:
- debug_logger.log_info("browser_manager", "close_connection", f"connection disconnect failed: {e}")
- pass
+ try:
+ await asyncio.to_thread(self._finalize_process_cleanup, instance_id, True)
+ except Exception as error:
+ debug_logger.log_warning(
+ "browser_manager",
+ "close_instance",
+ f"Process cleanup failed for {instance_id}: {error}",
+ )
- try:
- import nodriver.cdp.browser as cdp_browser
- if hasattr(browser, 'connection') and browser.connection:
- await browser.connection.send(cdp_browser.close())
- except Exception:
- pass
+ try:
+ await self._close_proxy_forwarder(instance_id)
+ except Exception:
+ pass
- try:
- process_cleanup.kill_browser_process(instance_id)
- except Exception as e:
- debug_logger.log_warning("browser_manager", "close_instance",
- f"Process cleanup failed for {instance_id}: {e}")
+ await self._notify_close_listeners(instance_id)
+ return True
- try:
- await self._stop_browser(browser)
- except Exception:
- pass
+ async def _shutdown_browser(self, browser: Browser) -> None:
+ """
+ Stop a browser process and its CDP connections without hanging.
- try:
- await self._close_proxy_forwarder(instance_id)
- except Exception:
- pass
+ Args:
+ browser (Browser): Browser to stop.
+
+ Returns:
+ None
+ """
+ connection = getattr(browser, "connection", None)
+ if connection is not None:
+ handlers = getattr(connection, "handlers", {})
+ for event_type in TARGET_UPDATE_EVENTS:
+ handlers.pop(event_type, None)
+ try:
+ await asyncio.wait_for(connection.send(uc.cdp.browser.close()), CLOSE_STEP_TIMEOUT)
+ except Exception:
+ pass
- if hasattr(browser, '_process') and browser._process and browser._process.returncode is None:
- import os
-
- for attempt in range(3):
- try:
- browser._process.terminate()
- debug_logger.log_info("browser_manager", "terminate_process", f"terminated browser with pid {browser._process.pid} successfully on attempt {attempt + 1}")
- break
- except Exception:
- try:
- browser._process.kill()
- debug_logger.log_info("browser_manager", "kill_process", f"killed browser with pid {browser._process.pid} successfully on attempt {attempt + 1}")
- break
- except Exception:
- try:
- if hasattr(browser, '_process_pid') and browser._process_pid:
- os.kill(browser._process_pid, 15)
- debug_logger.log_info("browser_manager", "kill_process", f"killed browser with pid {browser._process_pid} using signal 15 successfully on attempt {attempt + 1}")
- break
- except (PermissionError, ProcessLookupError) as e:
- debug_logger.log_info("browser_manager", "kill_process", f"browser already stopped or no permission to kill: {e}")
- break
- except Exception as e:
- if attempt == 2:
- debug_logger.log_error("browser_manager", "kill_process", e)
+ process = getattr(browser, "_process", None)
+ if process is not None and process.returncode is None:
+ try:
+ await asyncio.wait_for(process.wait(), PROCESS_EXIT_TIMEOUT)
+ except Exception:
+ for signal_process in (process.terminate, process.kill):
+ try:
+ signal_process()
+ await asyncio.wait_for(process.wait(), PROCESS_EXIT_TIMEOUT)
+ break
+ except ProcessLookupError:
+ break
+ except Exception:
+ continue
+
+ connections = [getattr(tab, "disconnect", None) for tab in list(getattr(browser, "targets", []) or [])]
+ if connection is not None:
+ connections.append(connection.disconnect)
+ disconnects = [disconnect() for disconnect in connections if disconnect is not None]
+ if disconnects:
+ await asyncio.wait(
+ [asyncio.ensure_future(item) for item in disconnects],
+ timeout=CLOSE_STEP_TIMEOUT,
+ )
+ browser._process = None
+ browser._process_pid = None
- try:
- if hasattr(browser, '_process'):
- browser._process = None
- if hasattr(browser, '_process_pid'):
- browser._process_pid = None
+ def add_close_listener(self, listener: Callable[[str], Awaitable[Any]]) -> None:
+ """
+ Register a coroutine called with the instance id after an instance closes.
- instance.state = BrowserState.CLOSED
- except Exception:
- pass
+ Covers every close path: the close tool, idle reaping, and shutdown.
- try:
- process_cleanup.finalize_browser_process(instance_id)
- process_cleanup.cleanup_deferred_profiles()
- except Exception as e:
- debug_logger.log_warning(
- "browser_manager",
- "close_instance",
- f"Post-stop cleanup failed for {instance_id}: {e}",
- )
+ Args:
+ listener (Callable[[str], Awaitable[Any]]): Cleanup coroutine function.
+
+ Returns:
+ None
+ """
+ if listener not in self._close_listeners:
+ self._close_listeners.append(listener)
- del self._instances[instance_id]
- self._spawn_diagnostics.pop(instance_id, None)
+ async def _notify_close_listeners(self, instance_id: str) -> None:
+ """
+ Run close listeners, logging failures instead of raising.
- persistent_storage.remove_instance(instance_id)
+ Args:
+ instance_id (str): Closed instance ID.
- return True
-
- try:
- return await asyncio.wait_for(_do_close(), timeout=5.0)
- except asyncio.TimeoutError:
- debug_logger.log_info("browser_manager", "close_instance", f"Close timeout for {instance_id}, forcing cleanup")
+ Returns:
+ None
+ """
+ for listener in list(self._close_listeners):
try:
- async with self._lock:
- if instance_id in self._instances:
- data = self._instances[instance_id]
- data['instance'].state = BrowserState.CLOSED
- dynamic_hook_system.cancel_instance(instance_id)
- process_cleanup.kill_browser_process(instance_id)
- process_cleanup.finalize_browser_process(instance_id)
- process_cleanup.cleanup_deferred_profiles()
- del self._instances[instance_id]
- self._spawn_diagnostics.pop(instance_id, None)
- proxy_forwarder = self._proxy_forwarders.pop(instance_id, None)
- if proxy_forwarder is not None:
- asyncio.create_task(proxy_forwarder.close())
- persistent_storage.remove_instance(instance_id)
- except Exception:
- pass
- return True
- except Exception as e:
- debug_logger.log_error("browser_manager", "close_instance", e)
- return False
+ await asyncio.wait_for(listener(instance_id), CLOSE_STEP_TIMEOUT)
+ except Exception as error:
+ debug_logger.log_warning(
+ "browser_manager",
+ "close_listener",
+ f"Close listener failed for {instance_id}: {error}",
+ )
async def get_spawn_diagnostics(self, instance_id: str) -> Optional[Dict[str, Any]]:
"""Get spawn diagnostics for an instance."""
@@ -695,8 +813,20 @@ class BrowserManager:
browser = data["browser"]
previous_tab = data.get("tab")
- new_tab = await browser.get("about:blank", new_tab=True)
- await new_tab
+ try:
+ new_tab = await browser.get("about:blank", new_tab=True)
+ except Exception:
+ new_tab = await browser.get("about:blank", new_window=True)
+ options: BrowserOptions = data["options"]
+ try:
+ await new_tab.set_window_size(
+ left=0,
+ top=0,
+ width=options.viewport_width,
+ height=options.viewport_height,
+ )
+ except Exception:
+ pass
if close_existing and previous_tab:
previous_target_id = self._get_tab_target_id(previous_tab)
@@ -707,9 +837,9 @@ class BrowserManager:
except Exception:
pass
+ await self._set_current_tab(instance_id, new_tab)
async with self._lock:
if instance_id in self._instances:
- self._instances[instance_id]["tab"] = new_tab
self._instances[instance_id]["navigation_count"] = 0
debug_logger.log_info(
@@ -738,12 +868,12 @@ class BrowserManager:
navigation_count = data.get("navigation_count", 0)
if (
- self.NAVIGATION_RECYCLE_THRESHOLD > 0
- and navigation_count >= self.NAVIGATION_RECYCLE_THRESHOLD
+ self._tab_recycle_navigations > 0
+ and navigation_count >= self._tab_recycle_navigations
):
return await self._replace_main_tab(
instance_id,
- reason=f"navigation recycle threshold {self.NAVIGATION_RECYCLE_THRESHOLD} reached",
+ reason=f"navigation recycle threshold {self._tab_recycle_navigations} reached",
)
try:
@@ -752,15 +882,11 @@ class BrowserManager:
if tracked_target_id:
for candidate_tab in browser.tabs:
if self._get_tab_target_id(candidate_tab) == tracked_target_id:
- await candidate_tab
return candidate_tab
if browser.tabs:
fallback_tab = browser.tabs[0]
- await fallback_tab
- async with self._lock:
- if instance_id in self._instances:
- self._instances[instance_id]["tab"] = fallback_tab
+ await self._set_current_tab(instance_id, fallback_tab)
return fallback_tab
except Exception as error:
debug_logger.log_warning(
@@ -954,15 +1080,41 @@ class BrowserManager:
instance_id (str): The ID of the browser instance.
touch_activity (bool): Whether retrieving the tab should refresh last activity.
+ If the tracked tab was closed or crashed, another open tab (or a fresh
+ configured tab) takes its place.
+
Returns:
Optional[Tab]: The main tab if found, else None.
"""
data = await self.get_instance(instance_id)
- if data:
- if touch_activity:
- await self.touch_instance(instance_id)
- return data['tab']
- return None
+ if not data:
+ return None
+ if touch_activity:
+ await self.touch_instance(instance_id)
+ tab = data['tab']
+ if not self._tab_is_open(data['browser'], tab):
+ return await self.get_navigation_tab(instance_id) or tab
+ return tab
+
+ def _tab_is_open(self, browser: Browser, tab: Optional[Tab]) -> bool:
+ """
+ Check whether a tab is still among the browser's live targets.
+
+ nodriver removes targets from browser.targets when Chrome reports them
+ destroyed, so this needs no CDP round trip.
+
+ Args:
+ browser (Browser): Owning browser.
+ tab (Optional[Tab]): Tab to check.
+
+ Returns:
+ bool: False only when the browser knows its targets and the tab is not among them.
+ """
+ targets = getattr(browser, "targets", None)
+ target_id = self._get_tab_target_id(tab)
+ if not targets or target_id is None:
+ return True
+ return any(self._get_tab_target_id(target) == target_id for target in targets)
async def get_browser(
self,
@@ -986,6 +1138,208 @@ class BrowserManager:
return data['browser']
return None
+ def add_tab_listener(self, listener: Callable[[Tab, str, BrowserOptions], Awaitable[Any]]) -> None:
+ """
+ Register a coroutine that prepares every tab an instance uses.
+
+ Listeners run once per tab, on spawn and whenever a tab is opened,
+ switched to, or replaced, so per-tab CDP state is never lost.
+
+ Args:
+ listener (Callable[[Tab, str, BrowserOptions], Awaitable[Any]]): Coroutine taking (tab, instance_id, options).
+
+ Returns:
+ None
+ """
+ if listener not in self._tab_listeners:
+ self._tab_listeners.append(listener)
+
+ async def _configure_tab(
+ self,
+ tab: Tab,
+ instance_id: str,
+ options: BrowserOptions,
+ init_scripts: List[Dict[str, Any]],
+ configured_tabs: set,
+ ) -> Optional[str]:
+ """
+ Apply per-tab state: extra headers, timezone, init scripts, and tab listeners.
+
+ Each tab is configured once. CDP overrides such as the timezone and
+ extra headers belong to a tab session, so a tab that skipped this
+ would leak the real timezone or miss headers.
+
+ Args:
+ tab (Tab): Tab to configure.
+ instance_id (str): Owning instance ID.
+ options (BrowserOptions): Spawn options.
+ init_scripts (List[Dict[str, Any]]): Init scripts installed for the instance.
+ configured_tabs (set): Target ids already configured for the instance.
+
+ Returns:
+ Optional[str]: Applied timezone id, or None when no timezone override is set.
+ """
+ target_id = self._get_tab_target_id(tab)
+ if target_id and target_id in configured_tabs:
+ return options.timezone_id
+ if options.extra_headers:
+ await tab.send(uc.cdp.network.set_extra_http_headers(
+ headers=uc.cdp.network.Headers(options.extra_headers)
+ ))
+ applied_timezone_id = await self._apply_timezone_override(
+ tab=tab,
+ timezone_id=options.timezone_id,
+ )
+ for script in init_scripts:
+ await self._install_init_script(tab, **script)
+ for listener in list(self._tab_listeners):
+ try:
+ await listener(tab, instance_id, options)
+ except Exception as error:
+ debug_logger.log_warning(
+ "browser_manager",
+ "configure_tab",
+ f"Tab listener failed for {instance_id}: {error}",
+ )
+ if target_id:
+ configured_tabs.add(target_id)
+ return applied_timezone_id
+
+ async def _ensure_tab_configured(self, instance_id: str, tab: Tab) -> None:
+ """
+ Configure a tab of a registered instance if it has not been configured.
+
+ Args:
+ instance_id (str): Browser instance ID.
+ tab (Tab): Tab to configure.
+
+ Returns:
+ None
+ """
+ data = self._instances.get(instance_id)
+ if data is None:
+ return
+ await self._configure_tab(
+ tab,
+ instance_id,
+ data["options"],
+ data.setdefault("init_scripts", []),
+ data.setdefault("configured_tabs", set()),
+ )
+
+ async def _set_current_tab(self, instance_id: str, tab: Tab) -> None:
+ """
+ Make a tab the instance's current tab.
+
+ The tab is configured if needed and dynamic hook interception moves to it.
+
+ Args:
+ instance_id (str): Browser instance ID.
+ tab (Tab): New current tab.
+
+ Returns:
+ None
+ """
+ await self._ensure_tab_configured(instance_id, tab)
+ await self._setup_dynamic_hooks(tab, instance_id)
+ async with self._lock:
+ if instance_id in self._instances:
+ self._instances[instance_id]["tab"] = tab
+
+ async def open_tab(self, instance_id: str, url: str = "about:blank") -> Tab:
+ """
+ Open a configured tab and load a URL in it.
+
+ The tab starts blank and is configured before the URL loads, so the
+ first page already sees the timezone, headers, and init scripts.
+
+ Args:
+ instance_id (str): Browser instance ID.
+ url (str): URL to load.
+
+ Returns:
+ Tab: The new tab.
+ """
+ data = await self.get_instance(instance_id)
+ if not data:
+ raise Exception(f"Instance not found: {instance_id}")
+ tab = await data["browser"].get("about:blank", new_tab=True)
+ await self._ensure_tab_configured(instance_id, tab)
+ if url and url != "about:blank":
+ await tab.send(uc.cdp.page.navigate(url))
+ return tab
+
+ @staticmethod
+ async def _install_init_script(
+ tab: Tab,
+ source: str,
+ world_name: Optional[str] = None,
+ include_command_line_api: Optional[bool] = None,
+ run_immediately: bool = True,
+ ) -> str:
+ """
+ Install an init script on one tab.
+
+ Page.enable is sent first because Chrome silently ignores
+ Page.addScriptToEvaluateOnNewDocument without it.
+
+ Args:
+ tab (Tab): Target tab.
+ source (str): JavaScript source.
+ world_name (Optional[str]): Isolated world name, or None for the main world.
+ include_command_line_api (Optional[bool]): Whether command line API is available.
+ run_immediately (bool): Whether to run the script in existing contexts too.
+
+ Returns:
+ str: Script identifier.
+ """
+ await tab.send(uc.cdp.page.enable())
+ identifier = await tab.send(uc.cdp.page.add_script_to_evaluate_on_new_document(
+ source=source,
+ world_name=world_name,
+ include_command_line_api=include_command_line_api,
+ run_immediately=run_immediately,
+ ))
+ return str(identifier)
+
+ async def add_init_script(
+ self,
+ instance_id: str,
+ source: str,
+ world_name: Optional[str] = None,
+ include_command_line_api: Optional[bool] = None,
+ run_immediately: bool = True,
+ ) -> str:
+ """
+ Install JavaScript that runs before page scripts on each new document.
+
+ The script is remembered and installed on every tab the instance
+ uses later, including replacement and newly opened tabs.
+
+ Args:
+ instance_id (str): Browser instance ID.
+ source (str): JavaScript source to evaluate before page scripts.
+ world_name (Optional[str]): Isolated world name, or None for the main world.
+ include_command_line_api (Optional[bool]): Whether command line API is available.
+ run_immediately (bool): Whether to run the script in existing contexts too.
+
+ Returns:
+ str: Identifier of the installed script.
+ """
+ data = await self.get_instance(instance_id)
+ if not data:
+ raise Exception(f"Instance not found: {instance_id}")
+ await self.touch_instance(instance_id)
+ script = {
+ "source": source,
+ "world_name": world_name,
+ "include_command_line_api": include_command_line_api,
+ "run_immediately": run_immediately,
+ }
+ identifier = await self._install_init_script(data["tab"], **script)
+ data.setdefault("init_scripts", []).append(script)
+ return identifier
+
async def list_tabs(self, instance_id: str) -> List[Dict[str, str]]:
"""
List all tabs for a browser instance.
@@ -1004,7 +1358,6 @@ class BrowserManager:
tabs = []
for tab in browser.tabs:
- await tab
tabs.append({
'tab_id': str(tab.target.target_id),
'url': getattr(tab, 'url', '') or '',
@@ -1042,9 +1395,7 @@ class BrowserManager:
try:
await target_tab.bring_to_front()
- async with self._lock:
- if instance_id in self._instances:
- self._instances[instance_id]['tab'] = target_tab
+ await self._set_current_tab(instance_id, target_tab)
return True
except Exception:
@@ -1066,6 +1417,10 @@ class BrowserManager:
"""
Close a specific tab.
+ When the closed tab is the instance's current tab, another open tab
+ becomes current. Closing the last tab opens a blank tab first so the
+ browser stays alive.
+
Args:
instance_id (str): The ID of the browser instance.
tab_id (str): The target ID of the tab to close.
@@ -1073,25 +1428,43 @@ class BrowserManager:
Returns:
bool: True if closed successfully, False otherwise.
"""
- browser = await self.get_browser(instance_id)
- if not browser:
+ data = await self.get_instance(instance_id)
+ if not data:
return False
+ browser = data["browser"]
+ try:
+ await browser.update_targets()
+ except Exception:
+ pass
- target_tab = None
- for tab in browser.tabs:
- if str(tab.target.target_id) == tab_id:
- target_tab = tab
- break
-
+ target_tab = next(
+ (tab for tab in browser.tabs if self._get_tab_target_id(tab) == tab_id),
+ None,
+ )
if not target_tab:
return False
+ is_current = self._get_tab_target_id(data.get("tab")) == tab_id
+ remaining = [tab for tab in browser.tabs if self._get_tab_target_id(tab) != tab_id]
+ if not remaining:
+ await self._replace_main_tab(
+ instance_id,
+ reason="closing the last open tab",
+ close_existing=False,
+ )
+
try:
await target_tab.close()
- return True
except Exception:
return False
+ configured_tabs = data.get("configured_tabs")
+ if configured_tabs is not None:
+ configured_tabs.discard(tab_id)
+ if is_current and remaining:
+ await self._set_current_tab(instance_id, remaining[0])
+ return True
+
async def update_instance_state(self, instance_id: str, url: Optional[str] = None, title: Optional[str] = None):
"""
Update instance state after navigation or action.
@@ -1250,8 +1623,11 @@ class BrowserManager:
if (now - instance.last_activity).total_seconds() > effective_timeout:
to_close.append(instance_id)
- for instance_id in to_close:
- await self.close_instance(instance_id)
+ if to_close:
+ await asyncio.gather(
+ *(self.close_instance(instance_id) for instance_id in to_close),
+ return_exceptions=True,
+ )
return len(to_close)
@@ -1262,5 +1638,8 @@ class BrowserManager:
Closes all currently managed browser instances.
"""
instance_ids = list(self._instances.keys())
- for instance_id in instance_ids:
- await self.close_instance(instance_id)
+ if instance_ids:
+ await asyncio.gather(
+ *(self.close_instance(instance_id) for instance_id in instance_ids),
+ return_exceptions=True,
+ )
diff --git a/src/cdp_function_executor.py b/src/cdp_function_executor.py
index 8cf57c4..90bf75f 100644
--- a/src/cdp_function_executor.py
+++ b/src/cdp_function_executor.py
@@ -5,19 +5,23 @@ This module provides comprehensive function execution capabilities using nodrive
1. Direct CDP command execution
2. JavaScript function discovery and execution
3. Dynamic script injection and execution
-4. Python-JavaScript bridge functionality
+4. Python to JavaScript translation
"""
import ast
import asyncio
import json
-from typing import Any, Callable, Dict, List, Optional
+import re
+from typing import Any, Dict, List, Optional
import nodriver as uc
from nodriver import Tab
from debug_logger import debug_logger
+CONTEXT_COLLECT_SECONDS = 0.3
+JS_IDENTIFIER = re.compile(r"^[A-Za-z_$][A-Za-z0-9_$]{0,63}$")
+
class ExecutionContext:
"""Represents a JavaScript execution context."""
@@ -77,7 +81,6 @@ class CDPFunctionExecutor:
"""
Initializes the CDPFunctionExecutor instance.
"""
- self._python_bindings: Dict[str, Callable] = {}
self._persistent_functions: Dict[str, Dict[str, str]] = {}
async def enable_runtime(self, tab: Tab) -> bool:
@@ -214,48 +217,69 @@ class CDPFunctionExecutor:
"""
Gets all available execution contexts.
+ Re-enables the Runtime domain so Chrome reports every live context
+ (main frame, iframes, isolated worlds), then collects the events.
+
Args:
tab (Tab): The browser tab.
Returns:
- List[ExecutionContext]: List of execution contexts.
+ List[ExecutionContext]: Execution contexts ordered by id.
"""
+ collected: Dict[int, Any] = {}
+
+ def on_created(event: uc.cdp.runtime.ExecutionContextCreated) -> None:
+ collected[int(event.context.id_)] = event.context
+
+ def on_destroyed(event: uc.cdp.runtime.ExecutionContextDestroyed) -> None:
+ collected.pop(int(event.execution_context_id), None)
+
+ handlers = (
+ (uc.cdp.runtime.ExecutionContextCreated, on_created),
+ (uc.cdp.runtime.ExecutionContextDestroyed, on_destroyed),
+ )
try:
- await self.enable_runtime(tab)
- script = """
- (function() {
- return {
- location: window.location.href,
- title: document.title,
- readyState: document.readyState,
- contexts: [{
- name: 'main',
- origin: window.location.origin,
- url: window.location.href
- }]
- };
- })()
- """
- result = await tab.send(uc.cdp.runtime.evaluate(
- expression=script,
- return_by_value=True,
- await_promise=True
- ))
- if result and result[0] and result[0].value:
- context_data = result[0].value
- contexts = []
- for i, ctx in enumerate(context_data.get('contexts', [])):
- contexts.append(ExecutionContext(
- id=str(i),
- name=ctx['name'],
- origin=ctx['origin'],
- unique_id=f"{ctx['origin']}_{i}"
- ))
- return contexts
- return []
+ for event_type, handler in handlers:
+ tab.add_handler(event_type, handler)
+ await tab.send(uc.cdp.runtime.disable())
+ await tab.send(uc.cdp.runtime.enable())
+ await asyncio.sleep(CONTEXT_COLLECT_SECONDS)
+ return [
+ ExecutionContext(
+ id=str(int(ctx.id_)),
+ name=ctx.name,
+ origin=ctx.origin,
+ unique_id=ctx.unique_id,
+ aux_data=ctx.aux_data,
+ )
+ for _, ctx in sorted(collected.items())
+ ]
except Exception as e:
debug_logger.log_error("cdp_function_executor", "get_execution_contexts", e)
return []
+ finally:
+ for event_type, handler in handlers:
+ callbacks = tab.handlers.get(event_type)
+ if callbacks and handler in callbacks:
+ callbacks.remove(handler)
+
+ @staticmethod
+ def _context_kwargs(context_id: Optional[str]) -> Dict[str, Any]:
+ """
+ Build Runtime.evaluate arguments that target an execution context.
+
+ Args:
+ context_id (Optional[str]): Numeric context id or unique id from get_execution_contexts.
+
+ Returns:
+ Dict[str, Any]: context_id or unique_context_id keyword, empty for the default context.
+ """
+ if context_id is None or str(context_id).strip() == "":
+ return {}
+ value = str(context_id).strip()
+ if value.isdigit():
+ return {"context_id": uc.cdp.runtime.ExecutionContextId(int(value))}
+ return {"unique_context_id": value}
async def discover_global_functions(self, tab: Tab, context_id: Optional[str] = None) -> List[FunctionInfo]:
"""
@@ -321,7 +345,8 @@ class CDPFunctionExecutor:
result = await tab.send(uc.cdp.runtime.evaluate(
expression=discovery_script,
return_by_value=True,
- await_promise=True
+ await_promise=True,
+ **self._context_kwargs(context_id)
))
if result and result[0] and result[0].value:
functions_data = result[0].value
@@ -396,7 +421,13 @@ class CDPFunctionExecutor:
debug_logger.log_error("cdp_function_executor", "discover_object_methods", e)
return []
- async def call_discovered_function(self, tab: Tab, function_path: str, args: List[Any]) -> Dict[str, Any]:
+ async def call_discovered_function(
+ self,
+ tab: Tab,
+ function_path: str,
+ args: List[Any],
+ context_id: Optional[str] = None,
+ ) -> Dict[str, Any]:
"""
Calls a discovered JavaScript function with arguments.
@@ -404,6 +435,7 @@ class CDPFunctionExecutor:
tab (Tab): The browser tab.
function_path (str): Path to the function.
args (List[Any]): Arguments to pass.
+ context_id (str, optional): Execution context identifier.
Returns:
Dict[str, Any]: Result of the function call.
@@ -453,7 +485,8 @@ class CDPFunctionExecutor:
result = await tab.send(uc.cdp.runtime.evaluate(
expression=call_script,
return_by_value=True,
- await_promise=True
+ await_promise=True,
+ **self._context_kwargs(context_id)
))
if result and result[0] and result[0].value:
return result[0].value
@@ -571,7 +604,8 @@ class CDPFunctionExecutor:
expression=wrapped_script,
return_by_value=True,
await_promise=True,
- allow_unsafe_eval_blocked_by_csp=True
+ allow_unsafe_eval_blocked_by_csp=True,
+ **self._context_kwargs(context_id)
))
if result and result[0] and result[0].value:
return result[0].value
@@ -587,54 +621,53 @@ class CDPFunctionExecutor:
debug_logger.log_error("cdp_function_executor", "inject_and_execute_script", e)
return {"success": False, "error": str(e)}
- async def create_persistent_function(self, tab: Tab, function_name: str, function_code: str, instance_id: str) -> Dict[str, Any]:
+ async def prepare_persistent_function(
+ self,
+ tab: Tab,
+ function_name: str,
+ function_code: str,
+ instance_id: str,
+ ) -> str:
"""
- Creates a persistent JavaScript function that survives page reloads.
+ Validate a persistent function and build its init script.
Args:
- tab (Tab): The browser tab.
- function_name (str): Name of the function.
- function_code (str): JavaScript code for the function.
+ tab (Tab): The browser tab used to check that the code is a function.
+ function_name (str): JavaScript identifier to expose on window.
+ function_code (str): JavaScript function expression.
instance_id (str): Instance identifier.
Returns:
- Dict[str, Any]: Result of function creation.
+ str: Init script source that defines the function on every new document.
+
+ Raises:
+ ValueError: When the name is not an identifier or the code is not a function expression.
+ """
+ if not JS_IDENTIFIER.match(function_name or ""):
+ raise ValueError(f"Invalid function name: {function_name!r}")
+ result, exception = await tab.send(uc.cdp.runtime.evaluate(
+ expression=f"(() => typeof ({function_code}))()",
+ return_by_value=True,
+ ))
+ if exception:
+ raise ValueError(f"Function code does not compile: {exception.text}")
+ if result.value != "function":
+ raise ValueError(f"Function code must evaluate to a function, got {result.value}")
+ self._persistent_functions.setdefault(instance_id, {})[function_name] = function_code
+ return (
+ "(() => { try { Object.defineProperty(window, "
+ f"{json.dumps(function_name)}, {{ value: ({function_code}), writable: true, configurable: true, enumerable: false }}"
+ "); } catch (error) {} })();"
+ )
+
+ def forget_instance(self, instance_id: str) -> None:
+ """
+ Drop state kept for a closed instance.
+
+ Args:
+ instance_id (str): Closed instance identifier.
"""
- try:
- await self.enable_runtime(tab)
- if instance_id not in self._persistent_functions:
- self._persistent_functions[instance_id] = {}
- self._persistent_functions[instance_id][function_name] = function_code
- create_script = f"""
- (function() {{
- try {{
- window.{function_name} = {function_code};
- return {{
- success: true,
- function_name: '{function_name}',
- created_at: new Date().toISOString(),
- available_as: 'window.{function_name}'
- }};
- }} catch (error) {{
- return {{
- success: false,
- error: error.message,
- function_name: '{function_name}'
- }};
- }}
- }})()
- """
- result = await tab.send(uc.cdp.runtime.evaluate(
- expression=create_script,
- return_by_value=True,
- await_promise=True
- ))
- if result and result[0] and result[0].value:
- return result[0].value
- return {"success": False, "error": "Failed to create function"}
- except Exception as e:
- debug_logger.log_error("cdp_function_executor", "create_persistent_function", e)
- return {"success": False, "error": str(e)}
+ self._persistent_functions.pop(instance_id, None)
async def execute_function_sequence(self, tab: Tab, function_calls: List[FunctionCall]) -> List[Dict[str, Any]]:
"""
@@ -654,7 +687,8 @@ class CDPFunctionExecutor:
result = await self.call_discovered_function(
tab,
func_call.function_path,
- func_call.args
+ func_call.args,
+ func_call.context_id,
)
results.append({
"sequence_index": i,
@@ -681,62 +715,6 @@ class CDPFunctionExecutor:
})
return results
- async def create_python_binding(self, tab: Tab, binding_name: str, python_function: Callable) -> Dict[str, Any]:
- """
- Creates a binding that allows JavaScript to call Python functions.
-
- Args:
- tab (Tab): The browser tab.
- binding_name (str): Name of the binding.
- python_function (Callable): Python function to bind.
-
- Returns:
- Dict[str, Any]: Result of binding creation.
- """
- try:
- await self.enable_runtime(tab)
- self._python_bindings[binding_name] = python_function
- await tab.send(uc.cdp.runtime.add_binding(name=binding_name))
- wrapper_script = f"""
- (function() {{
- if (!window.{binding_name}) {{
- window.{binding_name} = function(...args) {{
- return new Promise((resolve, reject) => {{
- const callId = Math.random().toString(36).substr(2, 9);
- window.addEventListener(`{binding_name}_response_${{callId}}`, function(event) {{
- if (event.detail.success) {{
- resolve(event.detail.result);
- }} else {{
- reject(new Error(event.detail.error));
- }}
- }}, {{ once: true }});
- window.chrome.runtime.sendMessage({{
- binding: '{binding_name}',
- args: args,
- callId: callId
- }});
- }});
- }};
- }}
- return {{
- success: true,
- binding_name: '{binding_name}',
- available_as: 'window.{binding_name}'
- }};
- }})()
- """
- result = await tab.send(uc.cdp.runtime.evaluate(
- expression=wrapper_script,
- return_by_value=True,
- await_promise=True
- ))
- if result and result[0] and result[0].value:
- return result[0].value
- return {"success": False, "error": "Failed to create binding"}
- except Exception as e:
- debug_logger.log_error("cdp_function_executor", "create_python_binding", e)
- return {"success": False, "error": str(e)}
-
async def execute_python_in_browser(self, tab: Tab, python_code: str) -> Dict[str, Any]:
"""
Executes Python code by translating it to JavaScript with timeout protection.
@@ -839,40 +817,6 @@ class CDPFunctionExecutor:
return wrapped_code
- async def call_python_from_js(self, binding_name: str, args: List[Any]) -> Dict[str, Any]:
- """
- Handles JavaScript calls to Python functions.
-
- Args:
- binding_name (str): Name of the Python binding.
- args (List[Any]): Arguments to pass to the Python function.
-
- Returns:
- Dict[str, Any]: Result of the Python function call.
- """
- try:
- if binding_name not in self._python_bindings:
- return {"success": False, "error": f"Unknown binding: {binding_name}"}
- python_function = self._python_bindings[binding_name]
- if asyncio.iscoroutinefunction(python_function):
- result = await python_function(*args)
- else:
- result = python_function(*args)
- return {
- "success": True,
- "result": result,
- "binding_name": binding_name,
- "args": args
- }
- except Exception as e:
- debug_logger.log_error("cdp_function_executor", "call_python_from_js", e)
- return {
- "success": False,
- "error": str(e),
- "binding_name": binding_name,
- "args": args
- }
-
async def get_function_executor_info(self, instance_id: Optional[str] = None) -> Dict[str, Any]:
"""
Gets information about the function executor state.
@@ -884,7 +828,6 @@ class CDPFunctionExecutor:
Dict[str, Any]: Information about the executor.
"""
return {
- "python_bindings": list(self._python_bindings.keys()),
"persistent_functions": self._persistent_functions.get(instance_id, {}) if instance_id else self._persistent_functions,
"available_commands": await self.list_cdp_commands(),
"executor_version": "1.0.0",
@@ -892,6 +835,6 @@ class CDPFunctionExecutor:
"direct_cdp_execution",
"function_discovery",
"dynamic_script_injection",
- "python_js_bridge"
+ "python_to_js_translation"
]
}
diff --git a/src/dom_handler.py b/src/dom_handler.py
index a05d9e7..662e046 100644
--- a/src/dom_handler.py
+++ b/src/dom_handler.py
@@ -7,11 +7,24 @@ from pathlib import Path
from typing import Any, Dict, List, Optional
from nodriver import Tab
+
+import input_actions
from debug_logger import debug_logger
from file_upload_security import validate_upload_paths
from js_values import evaluate_to_python
+from key_definitions import MODIFIER_SHIFT, resolve_key_descriptor, resolve_modifiers
from models import ElementInfo
+DEFAULT_ELEMENT_TIMEOUT = 10.0
+WAIT_POLL_INTERVAL = 0.1
+ELEMENT_READY_JS = """function (visible, text) {
+ if (visible) {
+ const style = window.getComputedStyle(this);
+ if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') return false;
+ }
+ return !text || (this.innerText || this.textContent || '').includes(text);
+}"""
+
async def evaluate_or_raise(tab: Tab, expression: str, await_promise: bool = False) -> Any:
"""
@@ -31,138 +44,6 @@ async def evaluate_or_raise(tab: Tab, expression: str, await_promise: bool = Fal
return value
-MODIFIER_ALT = 1
-MODIFIER_CONTROL = 2
-MODIFIER_META = 4
-MODIFIER_SHIFT = 8
-
-MODIFIER_ALIASES: Dict[str, tuple] = {
- "alt": ("Alt", MODIFIER_ALT),
- "option": ("Alt", MODIFIER_ALT),
- "control": ("Control", MODIFIER_CONTROL),
- "ctrl": ("Control", MODIFIER_CONTROL),
- "meta": ("Meta", MODIFIER_META),
- "cmd": ("Meta", MODIFIER_META),
- "command": ("Meta", MODIFIER_META),
- "shift": ("Shift", MODIFIER_SHIFT),
-}
-
-NAMED_KEYS: Dict[str, tuple] = {
- "enter": ("Enter", "Enter", 13, "\r"),
- "tab": ("Tab", "Tab", 9, None),
- "escape": ("Escape", "Escape", 27, None),
- "arrowdown": ("ArrowDown", "ArrowDown", 40, None),
- "arrowup": ("ArrowUp", "ArrowUp", 38, None),
- "arrowleft": ("ArrowLeft", "ArrowLeft", 37, None),
- "arrowright": ("ArrowRight", "ArrowRight", 39, None),
- "backspace": ("Backspace", "Backspace", 8, None),
- "delete": ("Delete", "Delete", 46, None),
- "home": ("Home", "Home", 36, None),
- "end": ("End", "End", 35, None),
- "pageup": ("PageUp", "PageUp", 33, None),
- "pagedown": ("PageDown", "PageDown", 34, None),
- "space": (" ", "Space", 32, " "),
-}
-
-NAMED_KEYS.update({
- f"f{n}": (f"F{n}", f"F{n}", 111 + n, None) for n in range(1, 13)
-})
-
-PRINTABLE_KEY_CODES: Dict[str, tuple] = {
- " ": ("Space", 32),
- "-": ("Minus", 189), "_": ("Minus", 189),
- "=": ("Equal", 187), "+": ("Equal", 187),
- "[": ("BracketLeft", 219), "{": ("BracketLeft", 219),
- "]": ("BracketRight", 221), "}": ("BracketRight", 221),
- "\\": ("Backslash", 220), "|": ("Backslash", 220),
- ";": ("Semicolon", 186), ":": ("Semicolon", 186),
- "'": ("Quote", 222), '"': ("Quote", 222),
- ",": ("Comma", 188), "<": ("Comma", 188),
- ".": ("Period", 190), ">": ("Period", 190),
- "/": ("Slash", 191), "?": ("Slash", 191),
- "`": ("Backquote", 192), "~": ("Backquote", 192),
- "!": ("Digit1", 49), "@": ("Digit2", 50), "#": ("Digit3", 51),
- "$": ("Digit4", 52), "%": ("Digit5", 53), "^": ("Digit6", 54),
- "&": ("Digit7", 55), "*": ("Digit8", 56), "(": ("Digit9", 57),
- ")": ("Digit0", 48),
-}
-
-
-def supported_key_names() -> List[str]:
- """List the named keys accepted by press_key, for error messages."""
- named = [
- "Enter", "Tab", "Escape", "ArrowDown", "ArrowUp", "ArrowLeft", "ArrowRight",
- "Backspace", "Delete", "Home", "End", "PageUp", "PageDown", "Space",
- ]
- return named + [f"F{n}" for n in range(1, 13)]
-
-
-def resolve_key_descriptor(key: str) -> Dict[str, Any]:
- """Map a named key or supported ASCII printable character to CDP fields."""
- if not isinstance(key, str) or key == "":
- raise Exception(
- "Invalid key. Use a supported named key or one ASCII printable character."
- )
-
- if len(key) == 1 and key != " ":
- code, virtual_key_code = PRINTABLE_KEY_CODES.get(key, ("", 0))
- if not code and "a" <= key.lower() <= "z":
- code = f"Key{key.upper()}"
- virtual_key_code = ord(key.upper())
- elif not code and "0" <= key <= "9":
- code = f"Digit{key}"
- virtual_key_code = ord(key)
- if not code or not key.isascii() or not key.isprintable():
- raise Exception(
- f"Unsupported key {key!r}. Use a supported named key or one ASCII printable character."
- )
- return {"key": key, "code": code, "virtual_key_code": virtual_key_code, "text": key}
-
- lookup = "space" if key == " " else key.strip().lower()
- named = NAMED_KEYS.get(lookup)
- if named is None:
- raise Exception(
- f"Unsupported key {key!r}. Supported named keys: {', '.join(supported_key_names())}."
- )
-
- dom_key, code, virtual_key_code, text = named
- return {"key": dom_key, "code": code, "virtual_key_code": virtual_key_code, "text": text}
-
-
-def resolve_modifiers(modifiers: Optional[List[str]]) -> tuple:
- """
- Combine modifier names into the CDP modifiers bitmask.
-
- Args:
- modifiers (Optional[List[str]]): Any of Shift, Control/Ctrl, Alt, Meta/Cmd.
-
- Returns:
- tuple: (bitmask int, canonical modifier names list).
- """
- if not modifiers:
- return 0, []
-
- if isinstance(modifiers, str):
- modifiers = [modifiers]
-
- mask = 0
- canonical: List[str] = []
- for modifier in modifiers:
- entry = MODIFIER_ALIASES.get(str(modifier).strip().lower())
- if entry is None:
- raise Exception(
- f"Unsupported modifier: {modifier!r}. "
- "Supported modifiers: Shift, Control (Ctrl), Alt, Meta (Cmd)."
- )
- name, bit = entry
- mask |= bit
- if name not in canonical:
- canonical.append(name)
-
- return mask, canonical
-
-
-
class DOMHandler:
"""Handles DOM queries and element interactions."""
@@ -304,6 +185,24 @@ class DOMHandler:
{'selector': selector, 'tab': str(tab)})
return []
+ @staticmethod
+ async def _resolve_target(tab: Tab, selector: str, timeout: float) -> int:
+ """
+ Resolve a selector to a backend node id or raise.
+
+ Args:
+ tab (Tab): The browser tab object.
+ selector (str): CSS selector.
+ timeout (float): Seconds to wait for the element.
+
+ Returns:
+ int: Backend node id.
+ """
+ backend_node_id = await input_actions.find_node(tab, selector, timeout)
+ if backend_node_id is None:
+ raise Exception(f"Element not found: {selector}")
+ return backend_node_id
+
@staticmethod
async def click_element(
tab: Tab,
@@ -312,7 +211,12 @@ class DOMHandler:
timeout: int = 10000
) -> bool:
"""
- Click an element with smart retry logic.
+ Click an element with trusted mouse events.
+
+ The element is scrolled into view, the mouse moves to its center, and
+ the left button is pressed and released, producing the same pointer,
+ mouse, and click events a user would. Elements without a layout box or
+ covered by another element are clicked through JavaScript instead.
Args:
tab (Tab): The browser tab object.
@@ -321,29 +225,18 @@ class DOMHandler:
timeout (int): Timeout in milliseconds.
Returns:
- bool: True if click succeeded, False otherwise.
+ bool: True if click succeeded.
"""
try:
- element = None
-
if text_match:
- element = await tab.find(text_match, best_match=True)
+ element = await tab.find(text_match, best_match=True, timeout=timeout / 1000)
+ if not element:
+ raise Exception(f"Element not found with text: {text_match}")
+ backend_node_id = int(element.backend_node_id)
else:
- element = await tab.select(selector, timeout=timeout/1000)
-
- if not element:
- raise Exception(f"Element not found: {selector}")
-
- await element.scroll_into_view()
- await asyncio.sleep(0.5)
-
- try:
- await element.click()
- except Exception:
- await element.mouse_click()
-
+ backend_node_id = await DOMHandler._resolve_target(tab, selector, timeout / 1000)
+ await input_actions.click_node(tab, backend_node_id)
return True
-
except Exception as e:
raise Exception(f"Failed to click element: {str(e)}")
@@ -358,7 +251,11 @@ class DOMHandler:
shift_enter: bool = False
) -> bool:
"""
- Type text with human-like delays and optional newline parsing.
+ Type text with trusted keyboard events and human-like delays.
+
+ Each ASCII character produces keydown, keypress, input, and keyup
+ events, with Shift held for capitals and shifted symbols. Other
+ characters are inserted like an input method would.
Args:
tab (Tab): The browser tab object.
@@ -366,75 +263,23 @@ class DOMHandler:
text (str): Text to type.
clear_first (bool): Clear input before typing.
delay_ms (int): Delay between keystrokes in milliseconds.
- parse_newlines (bool): If True, parse \n as Enter key presses.
- shift_enter (bool): If True, use Shift+Enter instead of Enter (for chat apps).
+ parse_newlines (bool): If True, press Enter for each \n instead of inserting a line break.
+ shift_enter (bool): If True, press Shift+Enter for each \n (for chat apps).
Returns:
- bool: True if typing succeeded, False otherwise.
+ bool: True if typing succeeded.
"""
try:
- element = await tab.select(selector)
- if not element:
- raise Exception(f"Element not found: {selector}")
-
- await element.focus()
- await asyncio.sleep(0.1)
-
+ backend_node_id = await DOMHandler._resolve_target(tab, selector, DEFAULT_ELEMENT_TIMEOUT)
+ await input_actions.focus_node(tab, backend_node_id)
if clear_first:
- try:
- await element.apply("(elem) => { elem.value = ''; }")
- except:
- await element.send_keys('\ue009' + 'a')
- await element.send_keys('\ue017')
- await asyncio.sleep(0.1)
-
- if parse_newlines:
- lines = text.split('\n')
- for i, line in enumerate(lines):
- for char in line:
- await element.send_keys(char)
- await asyncio.sleep(delay_ms / 1000)
-
- if i < len(lines) - 1:
- if shift_enter:
- await element.apply('''(elem) => {
- const start = elem.selectionStart;
- const end = elem.selectionEnd;
- const value = elem.value;
- elem.value = value.substring(0, start) + '\\n' + value.substring(end);
- elem.selectionStart = elem.selectionEnd = start + 1;
-
- elem.dispatchEvent(new KeyboardEvent('keydown', {
- key: 'Enter',
- code: 'Enter',
- shiftKey: true,
- bubbles: true
- }));
- elem.dispatchEvent(new Event('input', { bubbles: true }));
- }''')
- else:
- await element.apply('''(elem) => {
- const start = elem.selectionStart;
- const end = elem.selectionEnd;
- const value = elem.value;
- elem.value = value.substring(0, start) + '\\n' + value.substring(end);
- elem.selectionStart = elem.selectionEnd = start + 1;
-
- elem.dispatchEvent(new KeyboardEvent('keydown', {
- key: 'Enter',
- code: 'Enter',
- bubbles: true
- }));
- elem.dispatchEvent(new Event('input', { bubbles: true }));
- }''')
- await asyncio.sleep(delay_ms / 1000)
- else:
- for char in text:
- await element.send_keys(char)
- await asyncio.sleep(delay_ms / 1000)
-
+ await input_actions.clear_field(tab, backend_node_id)
+ delay = max(delay_ms, 0) / 1000
+ for index, char in enumerate(text):
+ await input_actions.type_character(tab, char, parse_newlines or shift_enter, shift_enter)
+ if delay and index < len(text) - 1:
+ await asyncio.sleep(delay)
return True
-
except Exception as e:
raise Exception(f"Failed to type text: {str(e)}")
@@ -446,8 +291,10 @@ class DOMHandler:
clear_first: bool = True
) -> bool:
"""
- Paste text instantly using nodriver's insert_text method.
- This is much faster than typing character by character.
+ Insert text in one step, like a paste.
+
+ Much faster than typing character by character. The page receives
+ beforeinput and input events but no key events.
Args:
tab (Tab): The browser tab object.
@@ -456,54 +303,17 @@ class DOMHandler:
clear_first (bool): Clear input before pasting.
Returns:
- bool: True if pasting succeeded, False otherwise.
+ bool: True if pasting succeeded.
"""
from nodriver import cdp
-
- try:
- element = await tab.select(selector)
- if not element:
- raise Exception(f"Element not found: {selector}")
-
- await element.focus()
- await asyncio.sleep(0.1)
+ try:
+ backend_node_id = await DOMHandler._resolve_target(tab, selector, DEFAULT_ELEMENT_TIMEOUT)
+ await input_actions.focus_node(tab, backend_node_id)
if clear_first:
- try:
- await element.apply("(elem) => { elem.value = ''; }")
- except:
- await tab.send(cdp.input_.dispatch_key_event(
- "rawKeyDown",
- modifiers=2, # Ctrl
- key="a",
- code="KeyA",
- windows_virtual_key_code=65
- ))
- await tab.send(cdp.input_.dispatch_key_event(
- "keyUp",
- modifiers=2, # Ctrl
- key="a",
- code="KeyA",
- windows_virtual_key_code=65
- ))
- await tab.send(cdp.input_.dispatch_key_event(
- "rawKeyDown",
- key="Delete",
- code="Delete",
- windows_virtual_key_code=46
- ))
- await tab.send(cdp.input_.dispatch_key_event(
- "keyUp",
- key="Delete",
- code="Delete",
- windows_virtual_key_code=46
- ))
- await asyncio.sleep(0.1)
-
+ await input_actions.clear_field(tab, backend_node_id)
await tab.send(cdp.input_.insert_text(text))
-
return True
-
except Exception as e:
raise Exception(f"Failed to paste text: {str(e)}")
@@ -544,11 +354,8 @@ class DOMHandler:
modifier_mask, canonical_modifiers = resolve_modifiers(modifiers)
if selector:
- element = await tab.select(selector)
- if not element:
- raise Exception(f"Element not found: {selector}")
- await element.focus()
- await asyncio.sleep(0.1)
+ backend_node_id = await DOMHandler._resolve_target(tab, selector, DEFAULT_ELEMENT_TIMEOUT)
+ await input_actions.focus_node(tab, backend_node_id)
text = descriptor["text"]
unmodified_text = text
@@ -768,6 +575,9 @@ class DOMHandler:
"""
Wait for element to appear and match conditions.
+ Polls every 100 ms with a root-only DOM lookup, so it reacts quickly
+ without fetching the whole DOM tree on each poll.
+
Args:
tab (Tab): The browser tab object.
selector (str): CSS selector for the element.
@@ -778,44 +588,23 @@ class DOMHandler:
Returns:
bool: True if element matches conditions, False otherwise.
"""
- start_time = time.time()
- timeout_seconds = timeout / 1000
-
- while time.time() - start_time < timeout_seconds:
+ deadline = time.monotonic() + max(timeout, 0) / 1000
+ while True:
try:
- element = await tab.query_selector(selector)
-
- if element:
- if visible:
- try:
- is_visible = await element.apply(
- """(elem) => {
- var style = window.getComputedStyle(elem);
- return style.display !== 'none' &&
- style.visibility !== 'hidden' &&
- style.opacity !== '0';
- }"""
- )
- if not is_visible:
- await asyncio.sleep(0.5)
- continue
- except:
- pass
-
- if text_content:
- text = element.text_all
- if text_content not in text:
- await asyncio.sleep(0.5)
- continue
-
+ backend_node_id = await input_actions.find_node(tab, selector)
+ if backend_node_id is not None and await input_actions.call_on_node(
+ tab,
+ backend_node_id,
+ ELEMENT_READY_JS,
+ visible,
+ text_content,
+ ):
return True
-
except Exception:
pass
-
- await asyncio.sleep(0.5)
-
- return False
+ if time.monotonic() >= deadline:
+ return False
+ await asyncio.sleep(WAIT_POLL_INTERVAL)
@staticmethod
async def execute_script(
diff --git a/src/dynamic_hook_system.py b/src/dynamic_hook_system.py
index 01ef0e5..9b7cb26 100644
--- a/src/dynamic_hook_system.py
+++ b/src/dynamic_hook_system.py
@@ -192,75 +192,146 @@ class DynamicHookSystem:
self._lock = asyncio.Lock()
self._request_tasks: Dict[str, set[asyncio.Task]] = {}
self._interception_handlers: Dict[str, tuple[Any, Callable]] = {}
+ self._instance_tabs: Dict[str, Any] = {}
+ self._fetch_enabled: set[str] = set()
- async def setup_interception(self, tab, instance_id: str):
- """Set up request and response interception for a browser tab."""
- try:
- all_hooks = []
+ def _hooks_for_instance(self, instance_id: str) -> List[DynamicHook]:
+ """
+ Active hooks that apply to an instance.
- instance_hook_ids = self.instance_hooks.get(instance_id, [])
- for hook_id in instance_hook_ids:
- hook = self.hooks.get(hook_id)
- if hook and hook.status == "active":
- all_hooks.append(hook)
-
- for hook_id, hook in self.hooks.items():
- if hook.status == "active" and hook_id not in instance_hook_ids:
- if not hasattr(hook, 'instance_ids') or not hook.instance_ids:
- all_hooks.append(hook)
-
- request_patterns = []
- response_patterns = []
-
- for hook in all_hooks:
- resource_type = hook.requirements.get('resource_type')
- cdp_resource_type = getattr(uc.cdp.network.ResourceType, resource_type.upper()) if resource_type else None
- is_response = hook.request_stage == 'response'
- stage = uc.cdp.fetch.RequestStage.RESPONSE if is_response else uc.cdp.fetch.RequestStage.REQUEST
- target = response_patterns if is_response else request_patterns
- for url_pattern in split_alternatives(hook.requirements.get('url_pattern', '*')) or ['*']:
- target.append(uc.cdp.fetch.RequestPattern(
- url_pattern=url_pattern,
- resource_type=cdp_resource_type,
- request_stage=stage
- ))
+ Args:
+ instance_id (str): Browser instance ID.
- all_patterns = request_patterns + response_patterns
+ Returns:
+ List[DynamicHook]: Instance-specific hooks followed by global hooks.
+ """
+ instance_hook_ids = self.instance_hooks.get(instance_id, [])
+ hooks = [
+ self.hooks[hook_id]
+ for hook_id in instance_hook_ids
+ if hook_id in self.hooks and self.hooks[hook_id].status == "active"
+ ]
+ hooks.extend(
+ hook
+ for hook_id, hook in self.hooks.items()
+ if hook.status == "active" and hook_id not in instance_hook_ids and not hook.instance_ids
+ )
+ return hooks
+
+ @staticmethod
+ def _request_patterns(hooks: List[DynamicHook]) -> List[Any]:
+ """
+ Build Fetch request patterns for a set of hooks.
- if not all_patterns:
- all_patterns = [
- uc.cdp.fetch.RequestPattern(url_pattern='*', request_stage=uc.cdp.fetch.RequestStage.REQUEST),
- uc.cdp.fetch.RequestPattern(url_pattern='*', request_stage=uc.cdp.fetch.RequestStage.RESPONSE)
- ]
+ Args:
+ hooks (List[DynamicHook]): Hooks to intercept for.
- await tab.send(uc.cdp.fetch.enable(patterns=all_patterns))
+ Returns:
+ List[Any]: Fetch.RequestPattern objects, request stage first.
+ """
+ request_patterns = []
+ response_patterns = []
+ for hook in hooks:
+ resource_type = hook.requirements.get('resource_type')
+ cdp_resource_type = getattr(uc.cdp.network.ResourceType, resource_type.upper()) if resource_type else None
+ is_response = hook.request_stage == 'response'
+ stage = uc.cdp.fetch.RequestStage.RESPONSE if is_response else uc.cdp.fetch.RequestStage.REQUEST
+ target = response_patterns if is_response else request_patterns
+ for url_pattern in split_alternatives(hook.requirements.get('url_pattern', '*')) or ['*']:
+ target.append(uc.cdp.fetch.RequestPattern(
+ url_pattern=url_pattern,
+ resource_type=cdp_resource_type,
+ request_stage=stage
+ ))
+ return request_patterns + response_patterns
- def schedule_request(event):
- task = asyncio.create_task(
- self._on_request_paused(tab, event, instance_id)
- )
- tasks = self._request_tasks.setdefault(instance_id, set())
- tasks.add(task)
- task.add_done_callback(tasks.discard)
+ async def setup_interception(self, tab, instance_id: str):
+ """
+ Attach an instance tab to the hook system.
- previous = self._interception_handlers.pop(instance_id, None)
- if previous:
- previous_tab, previous_handler = previous
- try:
- previous_tab.remove_handler(
- uc.cdp.fetch.RequestPaused,
- previous_handler,
- )
- except Exception:
- pass
+ Interception is enabled only while at least one active hook applies to
+ the instance, so pages without hooks load without a Fetch round trip
+ per request.
- tab.add_handler(uc.cdp.fetch.RequestPaused, schedule_request)
- self._interception_handlers[instance_id] = (tab, schedule_request)
+ Args:
+ tab (Any): Browser tab for the instance.
+ instance_id (str): Browser instance ID.
+ """
+ previous_tab = self._instance_tabs.get(instance_id)
+ if previous_tab is not None and previous_tab is not tab:
+ self._remove_request_handler(instance_id)
+ self._fetch_enabled.discard(instance_id)
+ self._instance_tabs[instance_id] = tab
+ await self.refresh_interception(instance_id)
+
+ async def refresh_interception(self, instance_id: str) -> None:
+ """
+ Enable, update, or disable Fetch interception to match the current hooks.
- debug_logger.log_info("dynamic_hook_system", "setup_interception", f"Set up interception for instance {instance_id} with {len(all_patterns)} patterns ({len(request_patterns)} request, {len(response_patterns)} response)")
+ Args:
+ instance_id (str): Browser instance ID.
+ """
+ tab = self._instance_tabs.get(instance_id)
+ if tab is None:
+ return
+ try:
+ patterns = self._request_patterns(self._hooks_for_instance(instance_id))
+ if not patterns:
+ self._remove_request_handler(instance_id)
+ if instance_id in self._fetch_enabled:
+ self._fetch_enabled.discard(instance_id)
+ await tab.send(uc.cdp.fetch.disable())
+ return
+
+ await tab.send(uc.cdp.fetch.enable(patterns=patterns))
+ self._fetch_enabled.add(instance_id)
+ if instance_id not in self._interception_handlers:
+ def schedule_request(event):
+ task = asyncio.create_task(
+ self._on_request_paused(tab, event, instance_id)
+ )
+ tasks = self._request_tasks.setdefault(instance_id, set())
+ tasks.add(task)
+ task.add_done_callback(tasks.discard)
+ tab.add_handler(uc.cdp.fetch.RequestPaused, schedule_request)
+ self._interception_handlers[instance_id] = (tab, schedule_request)
+
+ debug_logger.log_info("dynamic_hook_system", "refresh_interception", f"Intercepting {len(patterns)} patterns for instance {instance_id}")
except Exception as e:
- debug_logger.log_error("dynamic_hook_system", "setup_interception", f"Failed to setup interception: {e}")
+ debug_logger.log_error("dynamic_hook_system", "refresh_interception", f"Failed to update interception: {e}")
+
+ async def _refresh_instances(self, instance_ids: Optional[List[str]] = None) -> None:
+ """
+ Refresh interception for several instances.
+
+ Args:
+ instance_ids (Optional[List[str]]): Instances to refresh, or None for all attached instances.
+ """
+ targets = list(instance_ids) if instance_ids else list(self._instance_tabs)
+ for instance_id in targets:
+ await self.refresh_interception(instance_id)
+
+ def _remove_request_handler(self, instance_id: str) -> None:
+ """
+ Remove the RequestPaused handler for an instance.
+
+ Removes only this handler, because nodriver's remove_handler drops
+ every handler registered for the event type.
+
+ Args:
+ instance_id (str): Browser instance ID.
+ """
+ handler_entry = self._interception_handlers.pop(instance_id, None)
+ if not handler_entry:
+ return
+ tab, handler = handler_entry
+ handlers = getattr(tab, "handlers", {})
+ callbacks = handlers.get(uc.cdp.fetch.RequestPaused)
+ if callbacks and handler in callbacks:
+ callbacks.remove(handler)
+ if not callbacks:
+ handlers.pop(uc.cdp.fetch.RequestPaused, None)
async def _on_request_paused(self, tab, event, instance_id: str):
"""Handle intercepted requests and responses - process hooks immediately."""
@@ -370,13 +441,9 @@ class DynamicHookSystem:
def _detach_instance(self, instance_id: str) -> List[asyncio.Task]:
"""Detach interception and cancel pending request tasks for an instance."""
- handler_entry = self._interception_handlers.pop(instance_id, None)
- if handler_entry:
- tab, handler = handler_entry
- try:
- tab.remove_handler(uc.cdp.fetch.RequestPaused, handler)
- except Exception:
- pass
+ self._remove_request_handler(instance_id)
+ self._instance_tabs.pop(instance_id, None)
+ self._fetch_enabled.discard(instance_id)
tasks = list(self._request_tasks.pop(instance_id, set()))
for task in tasks:
@@ -416,6 +483,7 @@ class DynamicHookSystem:
for instance_id in self.instance_hooks:
self.instance_hooks[instance_id].append(hook_id)
+ await self._refresh_instances(hook.instance_ids or None)
debug_logger.log_info("dynamic_hook_system", "create_hook", f"Created hook {name} with ID {hook_id}")
return hook_id
@@ -469,9 +537,13 @@ class DynamicHookSystem:
self.instance_hooks[instance_id].remove(hook_id)
debug_logger.log_info("dynamic_hook_system", "remove_hook", f"Removed hook {hook_id}")
- return True
+ removed = True
+ else:
+ removed = False
- return False
+ if removed:
+ await self._refresh_instances()
+ return removed
except Exception as e:
debug_logger.log_error("dynamic_hook_system", "remove_hook", f"Failed to remove hook {hook_id}: {e}")
diff --git a/src/input_actions.py b/src/input_actions.py
new file mode 100644
index 0000000..6fcad23
--- /dev/null
+++ b/src/input_actions.py
@@ -0,0 +1,324 @@
+"""Trusted mouse and keyboard input through CDP Input events."""
+
+import asyncio
+import random
+import time
+from typing import Any, Dict, Optional, Tuple
+
+from nodriver import Tab, cdp
+
+from key_definitions import resolve_key_descriptor
+
+SHIFTED_SYMBOLS = set('~!@#$%^&*()_+{}|:"<>?')
+SHIFT_KEY = {"key": "Shift", "code": "ShiftLeft", "virtual_key_code": 16}
+BACKSPACE_KEY = {"key": "Backspace", "code": "Backspace", "virtual_key_code": 8}
+ENTER_KEY = {"key": "Enter", "code": "Enter", "virtual_key_code": 13}
+MODIFIER_SHIFT = 8
+NODE_POLL_INTERVAL = 0.1
+SCROLL_SETTLE_INTERVAL = 0.03
+SCROLL_SETTLE_ATTEMPTS = 10
+MOUSE_MOVE_STEPS = 6
+PRESS_DURATION_RANGE = (0.04, 0.09)
+MAX_TRACKED_TABS = 64
+
+HIT_TEST_JS = """function (x, y) {
+ const hit = document.elementFromPoint(x, y);
+ return !!hit && (hit === this || this.contains(hit) || (hit.shadowRoot && hit.shadowRoot.contains(this)));
+}"""
+JS_CLICK = "function () { this.click(); }"
+FOCUS_JS = "function () { if (typeof this.focus === 'function') this.focus(); }"
+SELECT_CONTENTS_JS = """function () {
+ if (typeof this.select === 'function' && 'value' in this) {
+ if (!this.value) return false;
+ this.select();
+ return true;
+ }
+ if (!this.isContentEditable || !this.textContent) return false;
+ const range = document.createRange();
+ range.selectNodeContents(this);
+ const selection = window.getSelection();
+ selection.removeAllRanges();
+ selection.addRange(range);
+ return true;
+}"""
+
+_last_mouse_positions: Dict[int, Tuple[float, float]] = {}
+
+
+async def find_node(tab: Tab, selector: str, timeout: float = 0.0) -> Optional[int]:
+ """
+ Resolve a CSS selector to a backend node id.
+
+ Only the document root is fetched, so lookups stay fast on large pages.
+
+ Args:
+ tab (Tab): Browser tab.
+ selector (str): CSS selector.
+ timeout (float): Seconds to keep polling while the element is missing.
+
+ Returns:
+ Optional[int]: Backend node id, or None when nothing matched in time.
+ """
+ deadline = time.monotonic() + max(timeout, 0.0)
+ while True:
+ document = await tab.send(cdp.dom.get_document(depth=0))
+ node_id = await tab.send(cdp.dom.query_selector(document.node_id, selector))
+ if node_id:
+ node = await tab.send(cdp.dom.describe_node(node_id=node_id))
+ return int(node.backend_node_id)
+ if time.monotonic() >= deadline:
+ return None
+ await asyncio.sleep(NODE_POLL_INTERVAL)
+
+
+async def call_on_node(tab: Tab, backend_node_id: int, function: str, *args: Any) -> Any:
+ """
+ Call a JavaScript function with the node as `this`.
+
+ Args:
+ tab (Tab): Browser tab.
+ backend_node_id (int): Target node.
+ function (str): Function declaration using `this` for the node.
+ *args (Any): JSON-serializable arguments.
+
+ Returns:
+ Any: Returned value, by value.
+ """
+ remote = await tab.send(cdp.dom.resolve_node(backend_node_id=cdp.dom.BackendNodeId(backend_node_id)))
+ result, exception = await tab.send(cdp.runtime.call_function_on(
+ function,
+ object_id=remote.object_id,
+ arguments=[cdp.runtime.CallArgument(value=arg) for arg in args],
+ return_by_value=True,
+ await_promise=True,
+ ))
+ if exception:
+ raise RuntimeError(exception.text)
+ return result.value
+
+
+async def node_center(tab: Tab, backend_node_id: int) -> Optional[Tuple[float, float]]:
+ """
+ Center of the first content quad of a node, in viewport CSS pixels.
+
+ Args:
+ tab (Tab): Browser tab.
+ backend_node_id (int): Target node.
+
+ Returns:
+ Optional[Tuple[float, float]]: (x, y), or None when the node has no layout box.
+ """
+ try:
+ quads = await tab.send(cdp.dom.get_content_quads(backend_node_id=cdp.dom.BackendNodeId(backend_node_id)))
+ except Exception:
+ return None
+ if not quads:
+ return None
+ quad = quads[0]
+ return sum(quad[0::2]) / 4, sum(quad[1::2]) / 4
+
+
+async def scroll_into_view(tab: Tab, backend_node_id: int) -> Optional[Tuple[float, float]]:
+ """
+ Scroll a node into view and wait until its position stops moving.
+
+ Args:
+ tab (Tab): Browser tab.
+ backend_node_id (int): Target node.
+
+ Returns:
+ Optional[Tuple[float, float]]: Settled center point, or None when the node has no layout box.
+ """
+ try:
+ await tab.send(cdp.dom.scroll_into_view_if_needed(backend_node_id=cdp.dom.BackendNodeId(backend_node_id)))
+ except Exception:
+ pass
+ previous = await node_center(tab, backend_node_id)
+ for _ in range(SCROLL_SETTLE_ATTEMPTS):
+ if previous is None:
+ return None
+ await asyncio.sleep(SCROLL_SETTLE_INTERVAL)
+ current = await node_center(tab, backend_node_id)
+ if current == previous:
+ return current
+ previous = current
+ return previous
+
+
+async def move_mouse(tab: Tab, x: float, y: float) -> None:
+ """
+ Move the mouse to a point along a short path from its last position.
+
+ Args:
+ tab (Tab): Browser tab.
+ x (float): Target x in viewport CSS pixels.
+ y (float): Target y in viewport CSS pixels.
+ """
+ start_x, start_y = _last_mouse_positions.get(id(tab), (x + random.uniform(-120, 120), y + random.uniform(-80, 80)))
+ for step in range(1, MOUSE_MOVE_STEPS + 1):
+ progress = step / MOUSE_MOVE_STEPS
+ eased = progress * progress * (3 - 2 * progress)
+ jitter = 0 if step == MOUSE_MOVE_STEPS else random.uniform(-1.5, 1.5)
+ await tab.send(cdp.input_.dispatch_mouse_event(
+ "mouseMoved",
+ x=start_x + (x - start_x) * eased + jitter,
+ y=start_y + (y - start_y) * eased + jitter,
+ ))
+ _last_mouse_positions.pop(id(tab), None)
+ _last_mouse_positions[id(tab)] = (x, y)
+ while len(_last_mouse_positions) > MAX_TRACKED_TABS:
+ _last_mouse_positions.pop(next(iter(_last_mouse_positions)))
+
+
+async def click_node(tab: Tab, backend_node_id: int) -> bool:
+ """
+ Click a node with trusted mouse events.
+
+ Scrolls the node into view, moves the mouse to its center, and presses
+ and releases the left button. Falls back to a JavaScript click when the
+ node has no layout box or is covered by another element.
+
+ Args:
+ tab (Tab): Browser tab.
+ backend_node_id (int): Target node.
+
+ Returns:
+ bool: True when trusted mouse events were used, False for the JavaScript fallback.
+ """
+ point = await scroll_into_view(tab, backend_node_id)
+ if point is not None and await call_on_node(tab, backend_node_id, HIT_TEST_JS, point[0], point[1]):
+ x, y = point
+ await move_mouse(tab, x, y)
+ await tab.send(cdp.input_.dispatch_mouse_event(
+ "mousePressed", x=x, y=y, button=cdp.input_.MouseButton.LEFT, buttons=1, click_count=1,
+ ))
+ await asyncio.sleep(random.uniform(*PRESS_DURATION_RANGE))
+ await tab.send(cdp.input_.dispatch_mouse_event(
+ "mouseReleased", x=x, y=y, button=cdp.input_.MouseButton.LEFT, buttons=0, click_count=1,
+ ))
+ return True
+ await call_on_node(tab, backend_node_id, JS_CLICK)
+ return False
+
+
+async def focus_node(tab: Tab, backend_node_id: int) -> None:
+ """
+ Focus a node.
+
+ Nodes Chrome considers unfocusable get a JavaScript focus() call
+ instead, which leaves focus unchanged rather than failing.
+
+ Args:
+ tab (Tab): Browser tab.
+ backend_node_id (int): Target node.
+ """
+ try:
+ await tab.send(cdp.dom.focus(backend_node_id=cdp.dom.BackendNodeId(backend_node_id)))
+ except Exception:
+ await call_on_node(tab, backend_node_id, FOCUS_JS)
+
+
+async def press(tab: Tab, key: Dict[str, Any], text: Optional[str] = None, modifiers: int = 0) -> None:
+ """
+ Press and release one key with trusted key events.
+
+ Args:
+ tab (Tab): Browser tab.
+ key (Dict[str, Any]): key, code, and virtual_key_code fields.
+ text (Optional[str]): Text the key produces, or None for non-printing keys.
+ modifiers (int): CDP modifier bitmask held during the press.
+ """
+ await tab.send(cdp.input_.dispatch_key_event(
+ "keyDown" if text else "rawKeyDown",
+ modifiers=modifiers,
+ key=key["key"],
+ code=key["code"],
+ windows_virtual_key_code=key["virtual_key_code"],
+ text=text,
+ unmodified_text=text,
+ ))
+ await tab.send(cdp.input_.dispatch_key_event(
+ "keyUp",
+ modifiers=modifiers,
+ key=key["key"],
+ code=key["code"],
+ windows_virtual_key_code=key["virtual_key_code"],
+ ))
+
+
+def character_key(char: str) -> Optional[Dict[str, Any]]:
+ """
+ Keyboard fields for an ASCII printable character on a US layout.
+
+ Args:
+ char (str): Single character.
+
+ Returns:
+ Optional[Dict[str, Any]]: key, code, and virtual_key_code, or None when the character has no key.
+ """
+ if len(char) != 1 or not char.isascii() or not char.isprintable():
+ return None
+ try:
+ descriptor = resolve_key_descriptor(char)
+ except Exception:
+ return None
+ return {key: descriptor[key] for key in ("key", "code", "virtual_key_code")}
+
+
+async def type_character(tab: Tab, char: str, newline_as_enter: bool = False, shift_enter: bool = False) -> None:
+ """
+ Type one character the way a keyboard would.
+
+ ASCII characters produce keydown, keypress, input, and keyup events, with
+ Shift held for capitals and shifted symbols. Other characters are
+ inserted as text, like an input method would.
+
+ Args:
+ tab (Tab): Browser tab.
+ char (str): Character to type.
+ newline_as_enter (bool): Press Enter for newline characters instead of inserting a line break.
+ shift_enter (bool): Hold Shift when pressing Enter for newlines.
+ """
+ if char == "\n":
+ if newline_as_enter:
+ await press(tab, ENTER_KEY, "\r", MODIFIER_SHIFT if shift_enter else 0)
+ else:
+ await tab.send(cdp.input_.insert_text("\n"))
+ return
+ key = character_key(char)
+ if key is None:
+ await tab.send(cdp.input_.insert_text(char))
+ return
+ shifted = char in SHIFTED_SYMBOLS or char.isupper()
+ if shifted:
+ await tab.send(cdp.input_.dispatch_key_event(
+ "rawKeyDown", modifiers=MODIFIER_SHIFT, key=SHIFT_KEY["key"], code=SHIFT_KEY["code"],
+ windows_virtual_key_code=SHIFT_KEY["virtual_key_code"],
+ ))
+ await press(tab, key, char, MODIFIER_SHIFT if shifted else 0)
+ if shifted:
+ await tab.send(cdp.input_.dispatch_key_event(
+ "keyUp", key=SHIFT_KEY["key"], code=SHIFT_KEY["code"],
+ windows_virtual_key_code=SHIFT_KEY["virtual_key_code"],
+ ))
+
+
+async def clear_field(tab: Tab, backend_node_id: int) -> bool:
+ """
+ Clear an input, textarea, or contenteditable element like a user would.
+
+ Selects the current contents and presses Backspace, so frameworks that
+ listen for input events see the change.
+
+ Args:
+ tab (Tab): Browser tab.
+ backend_node_id (int): Focused target node.
+
+ Returns:
+ bool: True when there was content to clear.
+ """
+ if not await call_on_node(tab, backend_node_id, SELECT_CONTENTS_JS):
+ return False
+ await press(tab, BACKSPACE_KEY)
+ return True
+
diff --git a/src/key_definitions.py b/src/key_definitions.py
new file mode 100644
index 0000000..0c76679
--- /dev/null
+++ b/src/key_definitions.py
@@ -0,0 +1,133 @@
+"""Keyboard key tables and CDP key event field resolution."""
+
+from typing import Any, Dict, List, Optional
+
+MODIFIER_ALT = 1
+MODIFIER_CONTROL = 2
+MODIFIER_META = 4
+MODIFIER_SHIFT = 8
+
+MODIFIER_ALIASES: Dict[str, tuple] = {
+ "alt": ("Alt", MODIFIER_ALT),
+ "option": ("Alt", MODIFIER_ALT),
+ "control": ("Control", MODIFIER_CONTROL),
+ "ctrl": ("Control", MODIFIER_CONTROL),
+ "meta": ("Meta", MODIFIER_META),
+ "cmd": ("Meta", MODIFIER_META),
+ "command": ("Meta", MODIFIER_META),
+ "shift": ("Shift", MODIFIER_SHIFT),
+}
+
+NAMED_KEYS: Dict[str, tuple] = {
+ "enter": ("Enter", "Enter", 13, "\r"),
+ "tab": ("Tab", "Tab", 9, None),
+ "escape": ("Escape", "Escape", 27, None),
+ "arrowdown": ("ArrowDown", "ArrowDown", 40, None),
+ "arrowup": ("ArrowUp", "ArrowUp", 38, None),
+ "arrowleft": ("ArrowLeft", "ArrowLeft", 37, None),
+ "arrowright": ("ArrowRight", "ArrowRight", 39, None),
+ "backspace": ("Backspace", "Backspace", 8, None),
+ "delete": ("Delete", "Delete", 46, None),
+ "home": ("Home", "Home", 36, None),
+ "end": ("End", "End", 35, None),
+ "pageup": ("PageUp", "PageUp", 33, None),
+ "pagedown": ("PageDown", "PageDown", 34, None),
+ "space": (" ", "Space", 32, " "),
+}
+
+NAMED_KEYS.update({
+ f"f{n}": (f"F{n}", f"F{n}", 111 + n, None) for n in range(1, 13)
+})
+
+PRINTABLE_KEY_CODES: Dict[str, tuple] = {
+ " ": ("Space", 32),
+ "-": ("Minus", 189), "_": ("Minus", 189),
+ "=": ("Equal", 187), "+": ("Equal", 187),
+ "[": ("BracketLeft", 219), "{": ("BracketLeft", 219),
+ "]": ("BracketRight", 221), "}": ("BracketRight", 221),
+ "\\": ("Backslash", 220), "|": ("Backslash", 220),
+ ";": ("Semicolon", 186), ":": ("Semicolon", 186),
+ "'": ("Quote", 222), '"': ("Quote", 222),
+ ",": ("Comma", 188), "<": ("Comma", 188),
+ ".": ("Period", 190), ">": ("Period", 190),
+ "/": ("Slash", 191), "?": ("Slash", 191),
+ "`": ("Backquote", 192), "~": ("Backquote", 192),
+ "!": ("Digit1", 49), "@": ("Digit2", 50), "#": ("Digit3", 51),
+ "$": ("Digit4", 52), "%": ("Digit5", 53), "^": ("Digit6", 54),
+ "&": ("Digit7", 55), "*": ("Digit8", 56), "(": ("Digit9", 57),
+ ")": ("Digit0", 48),
+}
+
+
+def supported_key_names() -> List[str]:
+ """List the named keys accepted by press_key, for error messages."""
+ named = [
+ "Enter", "Tab", "Escape", "ArrowDown", "ArrowUp", "ArrowLeft", "ArrowRight",
+ "Backspace", "Delete", "Home", "End", "PageUp", "PageDown", "Space",
+ ]
+ return named + [f"F{n}" for n in range(1, 13)]
+
+
+def resolve_key_descriptor(key: str) -> Dict[str, Any]:
+ """Map a named key or supported ASCII printable character to CDP fields."""
+ if not isinstance(key, str) or key == "":
+ raise Exception(
+ "Invalid key. Use a supported named key or one ASCII printable character."
+ )
+
+ if len(key) == 1 and key != " ":
+ code, virtual_key_code = PRINTABLE_KEY_CODES.get(key, ("", 0))
+ if not code and "a" <= key.lower() <= "z":
+ code = f"Key{key.upper()}"
+ virtual_key_code = ord(key.upper())
+ elif not code and "0" <= key <= "9":
+ code = f"Digit{key}"
+ virtual_key_code = ord(key)
+ if not code or not key.isascii() or not key.isprintable():
+ raise Exception(
+ f"Unsupported key {key!r}. Use a supported named key or one ASCII printable character."
+ )
+ return {"key": key, "code": code, "virtual_key_code": virtual_key_code, "text": key}
+
+ lookup = "space" if key == " " else key.strip().lower()
+ named = NAMED_KEYS.get(lookup)
+ if named is None:
+ raise Exception(
+ f"Unsupported key {key!r}. Supported named keys: {', '.join(supported_key_names())}."
+ )
+
+ dom_key, code, virtual_key_code, text = named
+ return {"key": dom_key, "code": code, "virtual_key_code": virtual_key_code, "text": text}
+
+
+def resolve_modifiers(modifiers: Optional[List[str]]) -> tuple:
+ """
+ Combine modifier names into the CDP modifiers bitmask.
+
+ Args:
+ modifiers (Optional[List[str]]): Any of Shift, Control/Ctrl, Alt, Meta/Cmd.
+
+ Returns:
+ tuple: (bitmask int, canonical modifier names list).
+ """
+ if not modifiers:
+ return 0, []
+
+ if isinstance(modifiers, str):
+ modifiers = [modifiers]
+
+ mask = 0
+ canonical: List[str] = []
+ for modifier in modifiers:
+ entry = MODIFIER_ALIASES.get(str(modifier).strip().lower())
+ if entry is None:
+ raise Exception(
+ f"Unsupported modifier: {modifier!r}. "
+ "Supported modifiers: Shift, Control (Ctrl), Alt, Meta (Cmd)."
+ )
+ name, bit = entry
+ mask |= bit
+ if name not in canonical:
+ canonical.append(name)
+
+ return mask, canonical
diff --git a/src/network_interceptor.py b/src/network_interceptor.py
index 39c806c..968dcdf 100644
--- a/src/network_interceptor.py
+++ b/src/network_interceptor.py
@@ -3,6 +3,7 @@
import asyncio
import base64
import json
+from collections import OrderedDict
from datetime import datetime
from pathlib import Path
from typing import Any, Coroutine, Dict, List, Optional, Set
@@ -15,7 +16,12 @@ from debug_logger import debug_logger
from models import NetworkRequest, NetworkResponse
MAX_REQUESTS_PER_INSTANCE = 1000
-MAX_CAPTURED_BODY_BYTES = 5 * 1024 * 1024
+MAX_CAPTURED_BODY_BYTES = 2 * 1024 * 1024
+MAX_STORED_BODY_BYTES = 64 * 1024 * 1024
+TEXT_RESOURCE_TYPES = {"document", "xhr", "fetch", "script", "eventsource"}
+BINARY_RESOURCE_TYPES = {"image", "media", "font", "websocket", "manifest"}
+INTERNAL_URL_PREFIXES = ("chrome://", "chrome-untrusted://", "chrome-extension://", "devtools://")
+TEXT_MIME_MARKERS = ("json", "text/", "javascript", "xml", "x-www-form-urlencoded", "graphql")
class NetworkInterceptor:
@@ -27,6 +33,8 @@ class NetworkInterceptor:
self._instance_requests: Dict[str, List[str]] = {}
self._instance_filters: Dict[str, Dict[str, List[str]]] = {}
self._tasks: Set[asyncio.Task] = set()
+ self._body_bytes: Dict[str, int] = {}
+ self._body_order: Dict[str, "OrderedDict[str, None]"] = {}
self._lock = asyncio.Lock()
def _spawn(self, coro: Coroutine[Any, Any, Any]) -> None:
@@ -121,6 +129,8 @@ class NetworkInterceptor:
try:
request_id = event.request_id
request = event.request
+ if request.url.startswith(INTERNAL_URL_PREFIXES):
+ return
resource_type = event.type_.value if getattr(event, "type_", None) else None
async with self._lock:
@@ -158,6 +168,7 @@ class NetworkInterceptor:
request_ids.append(request_id)
while len(request_ids) > MAX_REQUESTS_PER_INSTANCE:
evicted = request_ids.pop(0)
+ self._drop_body(evicted)
self._requests.pop(evicted, None)
self._responses.pop(evicted, None)
except Exception as e:
@@ -184,12 +195,55 @@ class NetworkInterceptor:
except Exception as e:
debug_logger.log_warning("network_interceptor", "on_response", f"Failed to record response: {e}")
+ @staticmethod
+ def _should_capture_body(request: Optional[NetworkRequest], response: NetworkResponse) -> bool:
+ """
+ Decide whether a response body is worth storing eagerly.
+
+ Text-like responses (documents, XHR, fetch, scripts, and JSON, text, or
+ XML mime types) are stored. Images, media, fonts, and other binary
+ payloads are left in the browser and can be fetched on demand.
+
+ Args:
+ request (Optional[NetworkRequest]): Captured request, if known.
+ response (NetworkResponse): Captured response metadata.
+
+ Returns:
+ bool: True when the body should be stored.
+ """
+ resource_type = ((request.resource_type if request else None) or "").lower()
+ if resource_type in BINARY_RESOURCE_TYPES:
+ return False
+ if resource_type in TEXT_RESOURCE_TYPES:
+ return True
+ content_type = (response.content_type or "").lower()
+ return any(marker in content_type for marker in TEXT_MIME_MARKERS)
+
+ def _drop_body(self, request_id: str) -> None:
+ """
+ Forget a stored body and its size accounting. Call with the lock held.
+
+ Args:
+ request_id (str): Request whose body is dropped.
+ """
+ response = self._responses.get(request_id)
+ request = self._requests.get(request_id)
+ if response is None or response.body is None:
+ return
+ if request is not None:
+ instance_id = request.instance_id
+ self._body_bytes[instance_id] = max(0, self._body_bytes.get(instance_id, 0) - len(response.body))
+ self._body_order.get(instance_id, {}).pop(request_id, None)
+ response.body = None
+
async def _on_loading_finished(self, event, tab: Tab):
"""
- Capture the response body once the resource has finished loading.
+ Store a text-like response body once the resource has finished loading.
- Bodies larger than MAX_CAPTURED_BODY_BYTES are skipped and can still be
- fetched on demand with get_response_body.
+ Bodies above MAX_CAPTURED_BODY_BYTES are skipped, and each instance
+ keeps at most MAX_STORED_BODY_BYTES of bodies, dropping the oldest
+ first. Skipped bodies can still be fetched with get_response_body
+ while the page holds them.
event: Any - The LoadingFinished event.
tab: Tab - The browser tab that loaded the resource.
@@ -198,16 +252,26 @@ class NetworkInterceptor:
if (event.encoded_data_length or 0) > MAX_CAPTURED_BODY_BYTES:
return
async with self._lock:
- if request_id not in self._responses:
+ response = self._responses.get(request_id)
+ request = self._requests.get(request_id)
+ if response is None or not self._should_capture_body(request, response):
return
- body = await self.get_response_body(tab, request_id)
+ body = await self._fetch_body(tab, request_id)
if body is None or len(body) > MAX_CAPTURED_BODY_BYTES:
return
async with self._lock:
response = self._responses.get(request_id)
- if response is not None:
- response.body = body
-
+ request = self._requests.get(request_id)
+ if response is None or request is None:
+ return
+ self._drop_body(request_id)
+ instance_id = request.instance_id
+ response.body = body
+ self._body_bytes[instance_id] = self._body_bytes.get(instance_id, 0) + len(body)
+ order = self._body_order.setdefault(instance_id, OrderedDict())
+ order[request_id] = None
+ while self._body_bytes[instance_id] > MAX_STORED_BODY_BYTES and order:
+ self._drop_body(next(iter(order)))
async def set_capture_filters(
self,
@@ -354,22 +418,33 @@ class NetworkInterceptor:
async def get_response_body(self, tab: Tab, request_id: str) -> Optional[bytes]:
"""
- Get response body content.
+ Get response body content, from the capture store or the browser.
tab: Tab - The browser tab.
request_id: str - The request identifier.
Returns: Optional[bytes] - The response body as bytes, or None.
"""
+ async with self._lock:
+ response = self._responses.get(request_id)
+ if response is not None and response.body is not None:
+ return response.body
+ return await self._fetch_body(tab, request_id)
+
+ async def _fetch_body(self, tab: Tab, request_id: str) -> Optional[bytes]:
+ """
+ Read a response body from the browser.
+
+ tab: Tab - The browser tab.
+ request_id: str - The request identifier.
+ Returns: Optional[bytes] - The response body as bytes, or None when the browser no longer has it.
+ """
try:
- # Convert string to RequestId object
- request_id_obj = uc.cdp.network.RequestId(request_id)
- result = await tab.send(uc.cdp.network.get_response_body(request_id=request_id_obj))
+ result = await tab.send(uc.cdp.network.get_response_body(request_id=uc.cdp.network.RequestId(request_id)))
if result:
- body, base64_encoded = result # Result is a tuple (body, base64Encoded)
+ body, base64_encoded = result
if base64_encoded:
return base64.b64decode(body)
- else:
- return body.encode("utf-8")
+ return body.encode("utf-8")
except Exception:
pass
return None
@@ -609,3 +684,6 @@ class NetworkInterceptor:
self._requests.pop(req_id, None)
self._responses.pop(req_id, None)
del self._instance_requests[instance_id]
+ self._body_bytes.pop(instance_id, None)
+ self._body_order.pop(instance_id, None)
+ self._instance_filters.pop(instance_id, None)
diff --git a/src/page_bindings.py b/src/page_bindings.py
new file mode 100644
index 0000000..6b50936
--- /dev/null
+++ b/src/page_bindings.py
@@ -0,0 +1,457 @@
+"""
+Page bindings: page JavaScript calls that are answered by the MCP client.
+
+A binding exposes `window.<name>(...args)` to the page. Each call returns a
+Promise and is queued for the client, which reads it with
+get_page_binding_calls and answers with resolve_page_binding_call. No code
+from the client or the page runs on the server host, arguments must be JSON,
+and payload size and queue length are capped so a page cannot exhaust memory.
+"""
+
+import asyncio
+import itertools
+import json
+import re
+import time
+from collections import OrderedDict
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional, Tuple
+
+import nodriver as uc
+from nodriver import Tab
+
+from debug_logger import debug_logger
+
+BINDING_NAME = re.compile(r"^[A-Za-z_$][A-Za-z0-9_$]{0,63}$")
+MAX_PAYLOAD_BYTES = 64 * 1024
+MAX_QUEUED_CALLS = 500
+MAX_WAIT_SECONDS = 60.0
+SETTLE_SYMBOL = "stealth-browser-binding"
+
+WRAPPER_TEMPLATE = """(() => {
+ const name = NAME;
+ const key = Symbol.for(SYMBOL);
+ const raw = globalThis[name];
+ if (typeof raw !== 'function' || raw[key]) return;
+ const pending = new Map();
+ let sequence = 0;
+ const binding = function (...args) {
+ return new Promise((resolve, reject) => {
+ const id = ++sequence;
+ let payload;
+ try {
+ payload = JSON.stringify({ id, args });
+ } catch (error) {
+ reject(new TypeError('Binding arguments must be JSON serializable'));
+ return;
+ }
+ pending.set(id, { resolve, reject });
+ raw(payload);
+ });
+ };
+ Object.defineProperty(binding, key, {
+ value: (id, ok, value) => {
+ const entry = pending.get(id);
+ if (!entry) return false;
+ pending.delete(id);
+ if (ok) entry.resolve(value); else entry.reject(new Error(String(value)));
+ return true;
+ }
+ });
+ Object.defineProperty(globalThis, name, { value: binding, writable: true, configurable: true, enumerable: false });
+})();"""
+
+
+@dataclass
+class BindingCall:
+ """
+ One call made by page JavaScript.
+
+ Attributes:
+ call_id (str): Server-side call identifier
+ binding (str): Binding name
+ args (List[Any]): Arguments passed by the page
+ received_at (float): Unix timestamp
+ status (str): pending, auto_resolved, or rejected
+ tab (Any): Tab that made the call
+ context_id (int): Execution context of the calling frame
+ page_call_id (int): Call id inside the page wrapper
+ """
+
+ call_id: str
+ binding: str
+ args: List[Any]
+ received_at: float
+ status: str
+ tab: Any = field(repr=False)
+ context_id: int = 0
+ page_call_id: int = 0
+
+ def to_dict(self) -> Dict[str, Any]:
+ """
+ Public view of the call.
+
+ Returns:
+ Dict[str, Any]: call_id, binding, args, received_at, and status
+ """
+ return {
+ "call_id": self.call_id,
+ "binding": self.binding,
+ "args": self.args,
+ "received_at": self.received_at,
+ "status": self.status,
+ }
+
+
+@dataclass
+class BindingConfig:
+ """
+ Settings for one binding.
+
+ Attributes:
+ auto_resolve (bool): Answer every call immediately with auto_response
+ auto_response (Any): JSON value used when auto_resolve is set
+ installs (List[Tuple[Any, str]]): (tab, init script identifier) per tab the binding is installed on
+ """
+
+ auto_resolve: bool = False
+ auto_response: Any = None
+ installs: List[Tuple[Any, str]] = field(default_factory=list)
+
+
+class PageBindingManager:
+ """Tracks page bindings and queued calls per browser instance."""
+
+ def __init__(self):
+ """Create empty binding and call registries."""
+ self._bindings: Dict[str, Dict[str, BindingConfig]] = {}
+ self._calls: Dict[str, "OrderedDict[str, BindingCall]"] = {}
+ self._handlers: Dict[str, List[Tuple[Any, Any]]] = {}
+ self._events: Dict[str, asyncio.Event] = {}
+ self._tasks: set = set()
+ self._ids = itertools.count(1)
+
+ async def create(
+ self,
+ tab: Tab,
+ instance_id: str,
+ name: str,
+ auto_resolve: bool = False,
+ auto_response: Any = None,
+ ) -> Dict[str, Any]:
+ """
+ Create a binding and install it on the instance's current tab.
+
+ Args:
+ tab (Tab): Current tab of the instance.
+ instance_id (str): Browser instance ID.
+ name (str): JavaScript identifier exposed as window.<name>.
+ auto_resolve (bool): Answer every call immediately with auto_response.
+ auto_response (Any): JSON value returned to the page when auto_resolve is set.
+
+ Returns:
+ Dict[str, Any]: Creation result.
+ """
+ if not BINDING_NAME.match(name or ""):
+ raise ValueError(f"Invalid binding name: {name!r}. Use a JavaScript identifier up to 64 characters.")
+ if name in self._bindings.get(instance_id, {}):
+ raise ValueError(f"Binding already exists: {name}")
+ exists, _ = await tab.send(uc.cdp.runtime.evaluate(
+ expression=f"{json.dumps(name)} in globalThis",
+ return_by_value=True,
+ ))
+ if exists.value:
+ raise ValueError(f"window.{name} already exists on the page. Choose another name.")
+ json.dumps(auto_response)
+ config = BindingConfig(auto_resolve=auto_resolve, auto_response=auto_response)
+ self._bindings.setdefault(instance_id, {})[name] = config
+ try:
+ await self._install(tab, instance_id, name, config)
+ except Exception:
+ self._bindings[instance_id].pop(name, None)
+ raise
+ return {
+ "success": True,
+ "binding_name": name,
+ "available_as": f"window.{name}(...args)",
+ "auto_resolve": auto_resolve,
+ }
+
+ async def prepare_tab(self, tab: Tab, instance_id: str, options: Any = None) -> None:
+ """
+ Install every binding of an instance on a tab. Used as a tab listener.
+
+ Args:
+ tab (Tab): Tab being prepared.
+ instance_id (str): Browser instance ID.
+ options (Any): Spawn options, unused.
+ """
+ for name, config in list(self._bindings.get(instance_id, {}).items()):
+ if any(installed_tab is tab for installed_tab, _ in config.installs):
+ continue
+ await self._install(tab, instance_id, name, config)
+
+ async def _install(self, tab: Tab, instance_id: str, name: str, config: BindingConfig) -> None:
+ """
+ Install one binding on one tab.
+
+ Args:
+ tab (Tab): Target tab.
+ instance_id (str): Browser instance ID.
+ name (str): Binding name.
+ config (BindingConfig): Binding settings.
+ """
+ self._attach_handler(tab, instance_id)
+ await tab.send(uc.cdp.runtime.add_binding(name=name))
+ await tab.send(uc.cdp.page.enable())
+ identifier = await tab.send(uc.cdp.page.add_script_to_evaluate_on_new_document(
+ source=WRAPPER_TEMPLATE.replace("NAME", json.dumps(name)).replace("SYMBOL", json.dumps(SETTLE_SYMBOL)),
+ run_immediately=True,
+ ))
+ config.installs.append((tab, str(identifier)))
+
+ def _attach_handler(self, tab: Tab, instance_id: str) -> None:
+ """
+ Listen for binding calls on a tab once.
+
+ Args:
+ tab (Tab): Target tab.
+ instance_id (str): Browser instance ID.
+ """
+ handlers = self._handlers.setdefault(instance_id, [])
+ if any(handled_tab is tab for handled_tab, _ in handlers):
+ return
+
+ def on_binding_called(event: uc.cdp.runtime.BindingCalled) -> None:
+ self._on_binding_called(tab, instance_id, event)
+
+ tab.add_handler(uc.cdp.runtime.BindingCalled, on_binding_called)
+ handlers.append((tab, on_binding_called))
+
+ def _on_binding_called(self, tab: Tab, instance_id: str, event: Any) -> None:
+ """
+ Queue a call from the page, or answer it right away for auto bindings.
+
+ Args:
+ tab (Tab): Tab that made the call.
+ instance_id (str): Browser instance ID.
+ event (Any): Runtime.bindingCalled event.
+ """
+ config = self._bindings.get(instance_id, {}).get(event.name)
+ if config is None:
+ return
+ try:
+ if len(event.payload.encode("utf-8")) > MAX_PAYLOAD_BYTES:
+ raise ValueError("payload too large")
+ payload = json.loads(event.payload)
+ page_call_id = int(payload["id"])
+ args = payload.get("args") or []
+ except Exception as error:
+ debug_logger.log_warning("page_bindings", "binding_called", f"Rejected call to {event.name}: {error}")
+ return
+
+ call = BindingCall(
+ call_id=f"call_{next(self._ids)}",
+ binding=event.name,
+ args=args,
+ received_at=time.time(),
+ status="pending",
+ tab=tab,
+ context_id=int(event.execution_context_id),
+ page_call_id=page_call_id,
+ )
+ if config.auto_resolve:
+ call.status = "auto_resolved"
+ self._spawn(self._settle(call, True, config.auto_response))
+
+ calls = self._calls.setdefault(instance_id, OrderedDict())
+ calls[call.call_id] = call
+ while len(calls) > MAX_QUEUED_CALLS:
+ _, dropped = calls.popitem(last=False)
+ if dropped.status == "pending":
+ self._spawn(self._settle(dropped, False, "Binding call dropped, too many pending calls"))
+ self._events.setdefault(instance_id, asyncio.Event()).set()
+
+ def _spawn(self, coroutine: Any) -> None:
+ """
+ Run a coroutine in the background and keep a reference to it.
+
+ Args:
+ coroutine (Any): Coroutine to run.
+ """
+ task = asyncio.ensure_future(coroutine)
+ self._tasks.add(task)
+ task.add_done_callback(self._tasks.discard)
+
+ async def _settle(self, call: BindingCall, ok: bool, value: Any) -> bool:
+ """
+ Resolve or reject the page Promise for a call.
+
+ Args:
+ call (BindingCall): Call to settle.
+ ok (bool): Resolve when True, reject when False.
+ value (Any): Result value, or error message when rejecting.
+
+ Returns:
+ bool: True when the page still had the call pending.
+ """
+ expression = (
+ "(() => {"
+ f" const binding = globalThis[{json.dumps(call.binding)}];"
+ f" const settle = binding && binding[Symbol.for({json.dumps(SETTLE_SYMBOL)})];"
+ f" return settle ? settle({call.page_call_id}, {json.dumps(ok)}, {json.dumps(value)}) : false;"
+ " })()"
+ )
+ try:
+ result, exception = await call.tab.send(uc.cdp.runtime.evaluate(
+ expression=expression,
+ context_id=uc.cdp.runtime.ExecutionContextId(call.context_id),
+ return_by_value=True,
+ ))
+ except Exception:
+ return False
+ return not exception and bool(result.value)
+
+ async def get_calls(
+ self,
+ instance_id: str,
+ name: Optional[str] = None,
+ wait_seconds: float = 0.0,
+ limit: int = 50,
+ ) -> List[Dict[str, Any]]:
+ """
+ Read queued calls, optionally waiting for the first one.
+
+ Pending calls stay queued until resolved. Auto-resolved calls are
+ removed once they have been read.
+
+ Args:
+ instance_id (str): Browser instance ID.
+ name (Optional[str]): Only return calls to this binding.
+ wait_seconds (float): Wait up to this long when no call is queued, capped at 60.
+ limit (int): Maximum number of calls returned.
+
+ Returns:
+ List[Dict[str, Any]]: Calls, oldest first.
+ """
+ def matching() -> List[BindingCall]:
+ return [
+ call for call in self._calls.get(instance_id, {}).values()
+ if name is None or call.binding == name
+ ]
+
+ if not matching() and wait_seconds > 0:
+ event = self._events.setdefault(instance_id, asyncio.Event())
+ deadline = time.monotonic() + min(wait_seconds, MAX_WAIT_SECONDS)
+ while not matching():
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ event.clear()
+ try:
+ await asyncio.wait_for(event.wait(), remaining)
+ except asyncio.TimeoutError:
+ break
+
+ selected = matching()[:max(limit, 1)]
+ calls = self._calls.get(instance_id, {})
+ for call in selected:
+ if call.status != "pending":
+ calls.pop(call.call_id, None)
+ return [call.to_dict() for call in selected]
+
+ async def resolve(
+ self,
+ instance_id: str,
+ call_id: str,
+ result: Any = None,
+ error: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Answer a pending call.
+
+ Args:
+ instance_id (str): Browser instance ID.
+ call_id (str): Call identifier from get_calls.
+ result (Any): JSON value the page Promise resolves with.
+ error (Optional[str]): Rejects the page Promise with this message instead.
+
+ Returns:
+ Dict[str, Any]: Whether the page received the answer.
+ """
+ call = self._calls.get(instance_id, {}).get(call_id)
+ if call is None or call.status != "pending":
+ raise ValueError(f"No pending call with id {call_id}")
+ json.dumps(result)
+ ok = error is None
+ delivered = await self._settle(call, ok, result if ok else str(error))
+ self._calls[instance_id].pop(call_id, None)
+ response = {"success": True, "call_id": call_id, "delivered": delivered}
+ if not delivered:
+ response["note"] = "The page navigated or closed before the answer arrived."
+ return response
+
+ async def remove(self, instance_id: str, name: str) -> Dict[str, Any]:
+ """
+ Remove a binding from every tab and reject its pending calls.
+
+ Args:
+ instance_id (str): Browser instance ID.
+ name (str): Binding name.
+
+ Returns:
+ Dict[str, Any]: Removal result.
+ """
+ config = self._bindings.get(instance_id, {}).pop(name, None)
+ if config is None:
+ raise ValueError(f"No binding named {name}")
+ calls = self._calls.get(instance_id, {})
+ for call_id, call in list(calls.items()):
+ if call.binding != name:
+ continue
+ calls.pop(call_id, None)
+ if call.status == "pending":
+ await self._settle(call, False, "Binding removed")
+ for tab, identifier in config.installs:
+ for command in (
+ uc.cdp.page.remove_script_to_evaluate_on_new_document(
+ identifier=uc.cdp.page.ScriptIdentifier(identifier)
+ ),
+ uc.cdp.runtime.remove_binding(name=name),
+ uc.cdp.runtime.evaluate(expression=f"delete globalThis[{json.dumps(name)}]"),
+ ):
+ try:
+ await tab.send(command)
+ except Exception:
+ pass
+ return {"success": True, "binding_name": name}
+
+ def list_bindings(self, instance_id: str) -> List[str]:
+ """
+ Names of the bindings defined for an instance.
+
+ Args:
+ instance_id (str): Browser instance ID.
+
+ Returns:
+ List[str]: Binding names.
+ """
+ return list(self._bindings.get(instance_id, {}))
+
+ async def forget_instance(self, instance_id: str) -> None:
+ """
+ Drop all binding state for a closed instance. Used as a close listener.
+
+ Args:
+ instance_id (str): Closed instance ID.
+ """
+ self._bindings.pop(instance_id, None)
+ self._calls.pop(instance_id, None)
+ self._events.pop(instance_id, None)
+ for tab, handler in self._handlers.pop(instance_id, []):
+ callbacks = getattr(tab, "handlers", {}).get(uc.cdp.runtime.BindingCalled)
+ if callbacks and handler in callbacks:
+ callbacks.remove(handler)
+
+
+page_bindings = PageBindingManager()
diff --git a/src/platform_utils.py b/src/platform_utils.py
index f82ef3a..2016b0b 100644
--- a/src/platform_utils.py
+++ b/src/platform_utils.py
@@ -7,6 +7,8 @@ import shutil
import sys
from typing import List, Optional
+BROWSER_EXECUTABLE_ENV = "STEALTH_BROWSER_EXECUTABLE"
+
def is_running_as_root() -> bool:
"""
@@ -152,13 +154,20 @@ def get_platform_info() -> dict:
def check_browser_executable() -> Optional[str]:
"""
Find a compatible browser executable on the system.
- Searches for Chrome, Chromium, and Microsoft Edge in order of preference.
-
+ Uses STEALTH_BROWSER_EXECUTABLE when set, otherwise searches for Chrome,
+ Chromium, and Microsoft Edge in order of preference.
+
Returns:
Optional[str]: Path to browser executable or None if not found
"""
+ override = os.environ.get(BROWSER_EXECUTABLE_ENV, "").strip()
+ if override:
+ if os.path.isfile(override) and os.access(override, os.X_OK):
+ return override
+ return None
+
system = platform.system().lower()
-
+
if system == 'windows':
possible_paths = [
# Chrome paths
diff --git a/src/process_cleanup.py b/src/process_cleanup.py
index 89ee847..90f620f 100644
--- a/src/process_cleanup.py
+++ b/src/process_cleanup.py
@@ -7,14 +7,40 @@ import shutil
import signal
import sys
import tempfile
+import threading
import time
+from functools import wraps
from pathlib import Path
-from typing import Any, Dict, Optional, Set
+from typing import Any, Callable, Dict, Optional, Set, TypeVar
import psutil
from debug_logger import debug_logger
+F = TypeVar("F", bound=Callable[..., Any])
+
+
+def synchronized(method: F) -> F:
+ """
+ Run a ProcessCleanup method while holding the instance lock.
+
+ Cleanup runs in worker threads so it does not block the event loop, and
+ tracking runs on the loop thread, so shared state needs a lock.
+
+ Args:
+ method (F): Method to wrap
+
+ Returns:
+ F: Wrapped method
+ """
+
+ @wraps(method)
+ def wrapper(self, *args, **kwargs):
+ with self._lock:
+ return method(self, *args, **kwargs)
+
+ return wrapper # type: ignore[return-value]
+
class ProcessCleanup:
"""Manage tracked browser process cleanup and orphan profile recovery."""
@@ -29,6 +55,7 @@ class ProcessCleanup:
Returns:
None
"""
+ self._lock = threading.RLock()
self.pid_file = Path(os.path.expanduser("~/.stealth_browser_pids.json"))
self.tracked_pids: Set[int] = set()
self.browser_processes: Dict[str, Dict[str, Any]] = {}
@@ -601,6 +628,7 @@ class ProcessCleanup:
self._write_pid_file(retained)
self._sweep_orphaned_temp_profiles()
+ @synchronized
def track_browser_process(
self,
instance_id: str,
@@ -656,6 +684,7 @@ class ProcessCleanup:
)
return False
+ @synchronized
def untrack_browser_process(self, instance_id: str) -> bool:
"""
Stop tracking a browser process and persist the updated metadata file.
@@ -692,6 +721,7 @@ class ProcessCleanup:
)
return False
+ @synchronized
def kill_browser_process(self, instance_id: str) -> bool:
"""
Kill a specific tracked browser process and clean its temp profile when appropriate.
@@ -726,6 +756,7 @@ class ProcessCleanup:
self._save_tracked_pids()
return success
+ @synchronized
def finalize_browser_process(self, instance_id: str) -> bool:
"""
Finalize tracked metadata after a browser was stopped elsewhere.
@@ -766,6 +797,7 @@ class ProcessCleanup:
self._save_tracked_pids()
return False
+ @synchronized
def cleanup_deferred_profiles(self) -> int:
"""
Retry cleanup for tracked temp profiles whose browser process is already gone.
@@ -903,6 +935,7 @@ class ProcessCleanup:
)
return False
+ @synchronized
def _cleanup_all_tracked(self):
"""
Clean up all tracked browser processes and temp profiles for the current run.
@@ -954,6 +987,7 @@ class ProcessCleanup:
f"Failed to clear PID file: {error}",
)
+ @synchronized
def get_tracked_processes(self) -> Dict[str, int]:
"""
Return currently tracked browser PIDs keyed by instance id.
@@ -967,6 +1001,7 @@ class ProcessCleanup:
if isinstance(metadata.get("pid"), int)
}
+ @synchronized
def is_process_alive(self, instance_id: str) -> bool:
"""
Check whether a tracked process is still alive.
diff --git a/src/proxy_forwarder.py b/src/proxy_forwarder.py
index 0098336..4cd7491 100644
--- a/src/proxy_forwarder.py
+++ b/src/proxy_forwarder.py
@@ -13,6 +13,9 @@ from urllib.parse import unquote, urlparse
from debug_logger import debug_logger
+DROPPED_HEADERS = ("proxy-authorization:",)
+HOP_BY_HOP_HEADERS = ("connection:", "proxy-connection:", "keep-alive:")
+
def _free_port() -> int:
"""Return a free loopback TCP port for the local proxy listener."""
@@ -144,7 +147,12 @@ class AuthenticatedProxyForwarder:
writer: asyncio.StreamWriter,
) -> None:
"""
- Forward an HTTP CONNECT tunnel through an authenticated upstream HTTP proxy.
+ Forward one proxied request through an authenticated upstream HTTP proxy.
+
+ CONNECT requests become a tunnel. Plain HTTP requests are sent with
+ Connection: close, because only the first request on a connection
+ gets the Proxy-Authorization header and later keep-alive requests
+ would reach the upstream proxy without credentials.
Args:
reader (asyncio.StreamReader): Local client reader.
@@ -222,10 +230,11 @@ class AuthenticatedProxyForwarder:
credentials = f"{self.username}:{self.password}"
encoded_credentials = base64.b64encode(credentials.encode()).decode("ascii")
+ dropped_headers = DROPPED_HEADERS if method == "CONNECT" else DROPPED_HEADERS + HOP_BY_HOP_HEADERS
remote_writer.write(request_line)
for header in header_lines:
header_text = header.decode("utf-8", errors="ignore").lower()
- if header_text.startswith("proxy-authorization:"):
+ if header_text.startswith(dropped_headers):
continue
remote_writer.write(header)
remote_writer.write(
@@ -233,6 +242,8 @@ class AuthenticatedProxyForwarder:
)
if method == "CONNECT":
remote_writer.write(b"Proxy-Connection: Keep-Alive\r\n")
+ else:
+ remote_writer.write(b"Connection: close\r\nProxy-Connection: close\r\n")
remote_writer.write(b"\r\n")
await remote_writer.drain()
@@ -256,8 +267,8 @@ class AuthenticatedProxyForwarder:
if not header or header in {b"\r\n", b"\n"}:
break
- response_text = response_line.decode("utf-8", errors="ignore")
- if "200" not in response_text:
+ response_parts = response_line.decode("utf-8", errors="ignore").split()
+ if len(response_parts) < 2 or response_parts[1] != "200":
await self._write_and_close(
writer,
b"HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain\r\n\r\n"
diff --git a/src/server.py b/src/server.py
index 4a6c059..dab1edf 100644
--- a/src/server.py
+++ b/src/server.py
@@ -32,6 +32,7 @@ from http_security import (
)
from models import BrowserOptions
from network_interceptor import NetworkInterceptor
+from page_bindings import page_bindings
from dynamic_hook_ai_interface import dynamic_hook_ai
from persistent_storage import persistent_storage
from progressive_element_cloner import progressive_element_cloner
@@ -162,7 +163,9 @@ mcp = FastMCP(
- Execute JavaScript in page context
- Manage cookies and storage
- All browser instances are undetectable by anti-bot systems.
+ Instances are built to avoid common bot detection, with trusted input
+ events and a clean headless fingerprint. Measured results against public
+ detection pages are published in STEALTH_TESTS.md.
""",
auth=create_http_auth_provider(HTTP_AUTH_TOKEN),
lifespan=app_lifespan,
@@ -173,6 +176,40 @@ network_interceptor = NetworkInterceptor()
dom_handler = DOMHandler()
cdp_function_executor = CDPFunctionExecutor()
+
+async def _prepare_tab(tab, instance_id: str, options: BrowserOptions) -> None:
+ """
+ Attach network capture to a tab an instance uses.
+
+ Args:
+ tab (Any): Browser tab.
+ instance_id (str): Browser instance ID.
+ options (BrowserOptions): Spawn options.
+ """
+ await network_interceptor.setup_interception(tab, instance_id, options.block_resources)
+
+
+async def _forget_instance(instance_id: str) -> None:
+ """
+ Drop per-instance state held outside the browser manager.
+
+ Args:
+ instance_id (str): Closed browser instance ID.
+ """
+ await network_interceptor.clear_instance_data(instance_id)
+ cdp_function_executor.forget_instance(instance_id)
+
+
+def _register_manager_listeners() -> None:
+ """Connect tab preparation and close cleanup to the current browser manager."""
+ browser_manager.add_tab_listener(_prepare_tab)
+ browser_manager.add_tab_listener(page_bindings.prepare_tab)
+ browser_manager.add_close_listener(_forget_instance)
+ browser_manager.add_close_listener(page_bindings.forget_instance)
+
+
+_register_manager_listeners()
+
if DEBUG_LOGGING_ENABLED:
debug_logger.enable()
@@ -238,11 +275,6 @@ async def spawn_browser(
sandbox=sandbox
)
instance = await browser_manager.spawn_browser(options)
- tab = await browser_manager.get_tab(instance.instance_id)
- if tab:
- await network_interceptor.setup_interception(
- tab, instance.instance_id, block_resources
- )
spawn_diagnostics = await browser_manager.get_spawn_diagnostics(instance.instance_id)
return {
"instance_id": instance.instance_id,
@@ -299,10 +331,7 @@ async def close_instance(instance_id: str) -> bool:
Returns:
bool: True if closed successfully.
"""
- success = await browser_manager.close_instance(instance_id)
- if success:
- await network_interceptor.clear_instance_data(instance_id)
- return success
+ return await browser_manager.close_instance(instance_id)
@section_tool("browser-management")
async def get_instance_state(instance_id: str) -> Optional[Dict[str, Any]]:
@@ -483,16 +512,18 @@ async def type_text(
shift_enter: bool = False
) -> bool:
"""
- Type text into an input field.
+ Type text into an input field with trusted keyboard events.
+
+ Every character produces keydown, keypress, input, and keyup events.
Args:
instance_id (str): Browser instance ID.
- selector (str): CSS selector or XPath.
+ selector (str): CSS selector.
text (str): Text to type.
clear_first (bool): Clear field before typing.
delay_ms (int): Delay between keystrokes in milliseconds.
- parse_newlines (bool): If True, parse \n as Enter key presses.
- shift_enter (bool): If True, use Shift+Enter instead of Enter (for chat apps).
+ parse_newlines (bool): If True, press Enter for each \n instead of inserting a line break.
+ shift_enter (bool): If True, press Shift+Enter for each \n (for chat apps).
Returns:
bool: True if typed successfully.
@@ -541,9 +572,8 @@ async def press_key(
Press a real key using trusted CDP key events.
Sends Input.dispatchKeyEvent keyDown/keyUp pairs, so the page sees trusted
- events. Use this instead of type_text(parse_newlines=True) for React-select,
- typeahead and combobox widgets, which discard values set by synthetic
- JavaScript KeyboardEvents.
+ events. Use this for control keys such as Enter, Tab, Escape, and the
+ arrow keys in React-select, typeahead, and combobox widgets.
Args:
instance_id (str): Browser instance ID.
@@ -1419,7 +1449,12 @@ async def get_active_tab(instance_id: str) -> Dict[str, Any]:
tab = await browser_manager.get_active_tab(instance_id)
if not tab:
return {"error": "No active tab found"}
- await tab
+ browser = await browser_manager.get_browser(instance_id, touch_activity=False)
+ if browser:
+ try:
+ await browser.update_targets()
+ except Exception:
+ pass
return {
"tab_id": str(tab.target.target_id),
"url": getattr(tab, 'url', '') or '',
@@ -1443,12 +1478,8 @@ async def new_tab(
Returns:
Dict[str, Any]: New tab information.
"""
- browser = await browser_manager.get_browser(instance_id)
- if not browser:
- raise Exception(f"Instance not found: {instance_id}")
try:
- new_tab_obj = await browser.get(url, new_tab=True)
- await new_tab_obj
+ new_tab_obj = await browser_manager.open_tab(instance_id, url)
return {
"tab_id": str(new_tab_obj.target.target_id),
"url": getattr(new_tab_obj, 'url', '') or url,
@@ -1799,6 +1830,7 @@ async def hot_reload() -> str:
if module_name == 'browser_manager':
await browser_manager.stop_idle_reaper()
browser_manager = sys.modules['browser_manager'].BrowserManager()
+ _register_manager_listeners()
await browser_manager.start_idle_reaper()
elif module_name == 'network_interceptor':
network_interceptor = sys.modules['network_interceptor'].NetworkInterceptor()
@@ -2412,18 +2444,15 @@ async def add_script_to_evaluate_on_new_document(
Returns:
Dict[str, Any]: Result with success state and script identifier.
"""
- tab = await browser_manager.get_tab(instance_id)
- if not tab:
- return {"success": False, "error": f"Instance not found: {instance_id}"}
try:
- await tab.send(uc.cdp.page.enable())
- result = await tab.send(uc.cdp.page.add_script_to_evaluate_on_new_document(
- source=source,
+ identifier = await browser_manager.add_init_script(
+ instance_id,
+ source,
world_name=world_name,
include_command_line_api=include_command_line_api,
run_immediately=run_immediately,
- ))
- return {"success": True, "identifier": str(result)}
+ )
+ return {"success": True, "identifier": identifier}
except Exception as e:
debug_logger.log_error("server", "add_script_to_evaluate_on_new_document", e)
return {"success": False, "error": str(e)}
@@ -2630,7 +2659,17 @@ async def create_persistent_function(
tab = await browser_manager.get_tab(instance_id)
if not tab:
return {"success": False, "error": f"Instance not found: {instance_id}"}
- return await cdp_function_executor.create_persistent_function(tab, function_name, function_code, instance_id)
+ try:
+ source = await cdp_function_executor.prepare_persistent_function(tab, function_name, function_code, instance_id)
+ identifier = await browser_manager.add_init_script(instance_id, source)
+ except Exception as e:
+ return {"success": False, "error": str(e), "function_name": function_name}
+ return {
+ "success": True,
+ "function_name": function_name,
+ "available_as": f"window.{function_name}",
+ "script_identifier": identifier,
+ }
@section_tool("cdp-functions")
@@ -2663,38 +2702,114 @@ async def execute_function_sequence(
@section_tool("cdp-functions")
-async def create_python_binding(
+async def create_page_binding(
instance_id: str,
binding_name: str,
- python_code: str
+ auto_resolve: bool = False,
+ auto_response: Optional[Any] = None
) -> Dict[str, Any]:
"""
- Create a binding that allows JavaScript to call Python functions.
+ Expose window.<binding_name>(...args) so page JavaScript can call back to you.
+
+ Each call returns a Promise in the page and is queued here. Read calls with
+ get_page_binding_calls and answer them with resolve_page_binding_call, or set
+ auto_resolve to answer every call immediately with auto_response. Nothing
+ runs on the server host. Arguments must be JSON, payloads are capped at
+ 64 KB, and at most 500 calls are queued per instance. The binding is
+ installed on every tab of the instance and survives navigation. Calls are
+ delivered through Runtime events.
Args:
instance_id (str): Browser instance ID.
- binding_name (str): Name for the binding.
- python_code (str): Python function code (as string).
+ binding_name (str): JavaScript identifier for the function.
+ auto_resolve (bool): Resolve every call immediately with auto_response.
+ auto_response (Optional[Any]): JSON value returned to the page when auto_resolve is set.
Returns:
- Dict[str, Any]: Binding creation result.
+ Dict[str, Any]: Creation result.
"""
tab = await browser_manager.get_tab(instance_id)
if not tab:
return {"success": False, "error": f"Instance not found: {instance_id}"}
try:
- exec_globals = {}
- exec(python_code, exec_globals)
- python_function = None
- for name, obj in exec_globals.items():
- if callable(obj) and not name.startswith('_'):
- python_function = obj
- break
- if not python_function:
- return {"success": False, "error": "No function found in Python code"}
- return await cdp_function_executor.create_python_binding(tab, binding_name, python_function)
+ return await page_bindings.create(tab, instance_id, binding_name, auto_resolve, auto_response)
except Exception as e:
- return {"success": False, "error": f"Failed to create Python function: {str(e)}"}
+ return {"success": False, "error": str(e)}
+
+
+@section_tool("cdp-functions")
+async def get_page_binding_calls(
+ instance_id: str,
+ binding_name: Optional[str] = None,
+ wait_seconds: float = 0,
+ limit: int = 50
+) -> Dict[str, Any]:
+ """
+ Read calls made by page JavaScript to page bindings.
+
+ Pending calls stay queued until resolved. Auto-resolved calls are returned
+ once and then removed.
+
+ Args:
+ instance_id (str): Browser instance ID.
+ binding_name (Optional[str]): Only return calls to this binding.
+ wait_seconds (float): Wait up to this many seconds (max 60) for a call when none is queued.
+ limit (int): Maximum number of calls to return.
+
+ Returns:
+ Dict[str, Any]: Calls (call_id, binding, args, received_at, status) and binding names.
+ """
+ await browser_manager.touch_instance(instance_id)
+ calls = await page_bindings.get_calls(instance_id, binding_name, wait_seconds, limit)
+ return {"calls": calls, "bindings": page_bindings.list_bindings(instance_id)}
+
+
+@section_tool("cdp-functions")
+async def resolve_page_binding_call(
+ instance_id: str,
+ call_id: str,
+ result: Optional[Any] = None,
+ error: Optional[str] = None
+) -> Dict[str, Any]:
+ """
+ Answer a pending page binding call.
+
+ Args:
+ instance_id (str): Browser instance ID.
+ call_id (str): Call ID from get_page_binding_calls.
+ result (Optional[Any]): JSON value the page Promise resolves with.
+ error (Optional[str]): Reject the page Promise with this message instead.
+
+ Returns:
+ Dict[str, Any]: Whether the answer reached the page.
+ """
+ await browser_manager.touch_instance(instance_id)
+ try:
+ return await page_bindings.resolve(instance_id, call_id, result, error)
+ except Exception as e:
+ return {"success": False, "error": str(e)}
+
+
+@section_tool("cdp-functions")
+async def remove_page_binding(
+ instance_id: str,
+ binding_name: str
+) -> Dict[str, Any]:
+ """
+ Remove a page binding from every tab and reject its pending calls.
+
+ Args:
+ instance_id (str): Browser instance ID.
+ binding_name (str): Binding to remove.
+
+ Returns:
+ Dict[str, Any]: Removal result.
+ """
+ await browser_manager.touch_instance(instance_id)
+ try:
+ return await page_bindings.remove(instance_id, binding_name)
+ except Exception as e:
+ return {"success": False, "error": str(e)}
@section_tool("cdp-functions")
diff --git a/tests/test_dynamic_hook_cleanup.py b/tests/test_dynamic_hook_cleanup.py
index a5b0d8f..f5f26b9 100644
--- a/tests/test_dynamic_hook_cleanup.py
+++ b/tests/test_dynamic_hook_cleanup.py
@@ -14,8 +14,10 @@ from dynamic_hook_system import DynamicHookSystem
class FakeTab:
def __init__(self):
self.handlers = {}
+ self.methods = []
async def send(self, command):
+ self.methods.append(next(command)["method"])
return None
def add_handler(self, event_type, handler):
@@ -36,6 +38,12 @@ class FakeTab:
handler(event)
+ALLOW_HOOK = """
+def process_request(request):
+ return HookAction(action="continue")
+"""
+
+
class DynamicHookCleanupTests(unittest.IsolatedAsyncioTestCase):
async def test_cleanup_cancels_request_tasks_and_removes_handler(self):
system = DynamicHookSystem()
@@ -54,6 +62,7 @@ class DynamicHookCleanupTests(unittest.IsolatedAsyncioTestCase):
system._on_request_paused = pending_request
system.add_instance(instance_id)
await system.setup_interception(tab, instance_id)
+ await system.create_hook("all", {"url_pattern": "*"}, ALLOW_HOOK)
self.assertIn(uc.cdp.fetch.RequestPaused, tab.handlers)
tab.emit(uc.cdp.fetch.RequestPaused, object())
@@ -70,5 +79,50 @@ class DynamicHookCleanupTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn(instance_id, system.instance_hooks)
+class OnDemandInterceptionTests(unittest.IsolatedAsyncioTestCase):
+ async def test_fetch_follows_active_hooks(self):
+ system = DynamicHookSystem()
+ tab = FakeTab()
+ system.add_instance("b")
+ await system.setup_interception(tab, "b")
+ self.assertEqual(tab.methods, [])
+ self.assertNotIn(uc.cdp.fetch.RequestPaused, tab.handlers)
+
+ hook_id = await system.create_hook("api", {"url_pattern": "*api*|*graphql*"}, ALLOW_HOOK)
+ self.assertEqual(tab.methods, ["Fetch.enable"])
+ self.assertEqual(len(tab.handlers[uc.cdp.fetch.RequestPaused]), 1)
+
+ await system.create_hook("img", {"url_pattern": "*.png"}, ALLOW_HOOK, instance_ids=["b"])
+ self.assertEqual(tab.methods, ["Fetch.enable", "Fetch.enable"])
+ self.assertEqual(len(tab.handlers[uc.cdp.fetch.RequestPaused]), 1)
+
+ await system.remove_hook(hook_id)
+ self.assertEqual(tab.methods[-1], "Fetch.enable")
+ self.assertEqual(len(system._request_patterns(system._hooks_for_instance("b"))), 1)
+
+ remaining = next(iter(system.hooks))
+ await system.remove_hook(remaining)
+ self.assertEqual(tab.methods[-1], "Fetch.disable")
+ self.assertNotIn(uc.cdp.fetch.RequestPaused, tab.handlers)
+
+ async def test_hooks_for_other_instances_do_not_intercept(self):
+ system = DynamicHookSystem()
+ tab = FakeTab()
+ system.add_instance("a")
+ await system.setup_interception(tab, "a")
+ await system.create_hook("only-b", {"url_pattern": "*"}, ALLOW_HOOK, instance_ids=["b"])
+ self.assertEqual(tab.methods, [])
+
+ async def test_new_tab_replaces_handler(self):
+ system = DynamicHookSystem()
+ first, second = FakeTab(), FakeTab()
+ system.add_instance("a")
+ await system.create_hook("all", {"url_pattern": "*"}, ALLOW_HOOK)
+ await system.setup_interception(first, "a")
+ await system.setup_interception(second, "a")
+ self.assertNotIn(uc.cdp.fetch.RequestPaused, first.handlers)
+ self.assertIn(uc.cdp.fetch.RequestPaused, second.handlers)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_headless_user_agent.py b/tests/test_headless_user_agent.py
new file mode 100644
index 0000000..b7dd6f0
--- /dev/null
+++ b/tests/test_headless_user_agent.py
@@ -0,0 +1,96 @@
+import asyncio
+import sys
+import unittest
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "src"))
+
+import browser_manager as browser_manager_module
+from browser_manager import BrowserManager
+
+HEADLESS_UA = (
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) HeadlessChrome/154.0.0.0 Safari/537.36"
+)
+CLEAN_UA = HEADLESS_UA.replace("HeadlessChrome/", "Chrome/")
+
+
+class FakeTab:
+ def __init__(self, user_agent):
+ self.user_agent = user_agent
+
+ async def send(self, command):
+ return ("1.3", "HeadlessChrome/154.0.8037.98", "rev", self.user_agent, "js")
+
+
+class FakeBrowser:
+ def __init__(self, user_agent):
+ self.main_tab = FakeTab(user_agent)
+ self.config = mock.Mock(user_data_dir="/tmp/uc_probe")
+ self._process = mock.Mock(pid=4242, returncode=0)
+
+
+class HeadlessUserAgentTests(unittest.TestCase):
+ def test_headful_user_agent(self):
+ self.assertEqual(BrowserManager._headful_user_agent(HEADLESS_UA), CLEAN_UA)
+ self.assertIsNone(BrowserManager._headful_user_agent(CLEAN_UA))
+
+ def test_has_user_agent_arg(self):
+ self.assertTrue(BrowserManager._has_user_agent_arg(["--foo", "--user-agent=x"]))
+ self.assertFalse(BrowserManager._has_user_agent_arg(["--foo"]))
+
+ def test_probe_result_is_cached_and_cleaned_up(self):
+ browsers = []
+
+ async def fake_start(config):
+ browser = FakeBrowser(HEADLESS_UA)
+ browsers.append((config, browser))
+ return browser
+
+ manager = BrowserManager()
+ cleanup = mock.Mock()
+ with mock.patch.object(browser_manager_module.uc, "start", side_effect=fake_start), mock.patch.object(
+ browser_manager_module, "process_cleanup", cleanup
+ ):
+ first = asyncio.run(manager._resolve_headless_user_agent("/missing/chrome", True, ["--lang=en-US"]))
+ second = asyncio.run(manager._resolve_headless_user_agent("/missing/chrome", True, ["--lang=en-US"]))
+
+ self.assertEqual(first, CLEAN_UA)
+ self.assertEqual(second, CLEAN_UA)
+ self.assertEqual(len(browsers), 1)
+ config, browser = browsers[0]
+ self.assertTrue(config.headless)
+ self.assertIsNone(browser._process)
+ cleanup.track_browser_process.assert_called_once()
+ cleanup.kill_browser_process.assert_called_once()
+
+ def test_probe_failure_is_not_cached(self):
+ calls = []
+
+ async def failing_start(config):
+ calls.append(config)
+ raise RuntimeError("no browser")
+
+ manager = BrowserManager()
+ with mock.patch.object(browser_manager_module.uc, "start", side_effect=failing_start):
+ self.assertIsNone(asyncio.run(manager._resolve_headless_user_agent("/missing/chrome", True, [])))
+ self.assertIsNone(asyncio.run(manager._resolve_headless_user_agent("/missing/chrome", True, [])))
+ self.assertEqual(len(calls), 2)
+
+ def test_clean_user_agent_is_cached_as_none(self):
+ async def fake_start(config):
+ return FakeBrowser(CLEAN_UA)
+
+ manager = BrowserManager()
+ with mock.patch.object(browser_manager_module.uc, "start", side_effect=fake_start) as start, mock.patch.object(
+ browser_manager_module, "process_cleanup", mock.Mock()
+ ):
+ self.assertIsNone(asyncio.run(manager._resolve_headless_user_agent("/missing/chrome", True, [])))
+ self.assertIsNone(asyncio.run(manager._resolve_headless_user_agent("/missing/chrome", True, [])))
+ self.assertEqual(start.call_count, 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_input_actions.py b/tests/test_input_actions.py
new file mode 100644
index 0000000..495f4f4
--- /dev/null
+++ b/tests/test_input_actions.py
@@ -0,0 +1,83 @@
+import asyncio
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "src"))
+
+import nodriver as uc
+
+import input_actions
+
+
+class RecordingTab:
+ """Tab that records Input events and answers DOM and Runtime calls."""
+
+ def __init__(self, quads=None, hit=True):
+ self.events = []
+ self.quads = quads if quads is not None else [[10, 20, 30, 20, 30, 40, 10, 40]]
+ self.hit = hit
+
+ async def send(self, command):
+ request = next(command)
+ method, params = request["method"], request.get("params", {})
+ if method.startswith("Input."):
+ self.events.append((method, params.get("type"), params.get("key") or params.get("text"), params.get("modifiers", 0)))
+ return None
+ if method == "DOM.getContentQuads":
+ return self.quads
+ if method == "DOM.resolveNode":
+ return SimpleNamespace(object_id=uc.cdp.runtime.RemoteObjectId("obj"))
+ if method == "Runtime.callFunctionOn":
+ self.events.append(("callFunctionOn", params["functionDeclaration"], None, 0))
+ return SimpleNamespace(value=self.hit), None
+ return None
+
+
+class CharacterKeyTests(unittest.TestCase):
+ def test_character_key(self):
+ self.assertEqual(input_actions.character_key("a")["code"], "KeyA")
+ self.assertEqual(input_actions.character_key("!")["code"], "Digit1")
+ self.assertIsNone(input_actions.character_key("é"))
+ self.assertIsNone(input_actions.character_key("ab"))
+
+ def test_typing_uses_key_events_and_shift(self):
+ tab = RecordingTab()
+
+ async def run():
+ for char in "aB!é\n":
+ await input_actions.type_character(tab, char)
+ await input_actions.type_character(tab, "\n", newline_as_enter=True, shift_enter=True)
+
+ asyncio.run(run())
+ kinds = [(event[0], event[1], event[2]) for event in tab.events]
+ self.assertEqual(kinds[0:2], [("Input.dispatchKeyEvent", "keyDown", "a"), ("Input.dispatchKeyEvent", "keyUp", "a")])
+ self.assertEqual(kinds[2], ("Input.dispatchKeyEvent", "rawKeyDown", "Shift"))
+ self.assertEqual(tab.events[3][3], input_actions.MODIFIER_SHIFT)
+ self.assertIn(("Input.insertText", None, "é"), kinds)
+ self.assertIn(("Input.insertText", None, "\n"), kinds)
+ self.assertEqual(tab.events[-2][2], "Enter")
+ self.assertEqual(tab.events[-2][3], input_actions.MODIFIER_SHIFT)
+
+
+class ClickTests(unittest.TestCase):
+ def test_trusted_click_moves_presses_and_releases(self):
+ tab = RecordingTab()
+ used_mouse = asyncio.run(input_actions.click_node(tab, 5))
+ self.assertTrue(used_mouse)
+ mouse = [event[1] for event in tab.events if event[0] == "Input.dispatchMouseEvent"]
+ self.assertEqual(mouse.count("mouseMoved"), input_actions.MOUSE_MOVE_STEPS)
+ self.assertEqual(mouse[-2:], ["mousePressed", "mouseReleased"])
+
+ def test_covered_or_hidden_falls_back_to_script(self):
+ for tab in (RecordingTab(hit=False), RecordingTab(quads=[])):
+ used_mouse = asyncio.run(input_actions.click_node(tab, 5))
+ self.assertFalse(used_mouse)
+ self.assertFalse(any(event[0] == "Input.dispatchMouseEvent" for event in tab.events))
+ self.assertTrue(any("click()" in (event[1] or "") for event in tab.events))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_network_capture.py b/tests/test_network_capture.py
new file mode 100644
index 0000000..d8ddf34
--- /dev/null
+++ b/tests/test_network_capture.py
@@ -0,0 +1,99 @@
+import asyncio
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "src"))
+
+import network_interceptor as network_module
+from network_interceptor import NetworkInterceptor
+
+
+class FakeTab:
+ def __init__(self, bodies):
+ self.bodies = bodies
+ self.fetched = []
+
+ async def send(self, command):
+ request = next(command)
+ request_id = request["params"]["requestId"]
+ self.fetched.append(request_id)
+ return self.bodies[request_id], False
+
+
+def request_event(request_id, url, resource_type):
+ return SimpleNamespace(
+ request_id=request_id,
+ request=SimpleNamespace(url=url, method="GET", headers={}, post_data=None),
+ type_=SimpleNamespace(value=resource_type),
+ )
+
+
+def response_event(request_id, mime_type):
+ return SimpleNamespace(
+ request_id=request_id,
+ response=SimpleNamespace(status=200, headers={}, mime_type=mime_type),
+ )
+
+
+async def load(interceptor, tab, request_id, url, resource_type, mime_type):
+ await interceptor._on_request(request_event(request_id, url, resource_type), "i")
+ await interceptor._on_response(response_event(request_id, mime_type))
+ await interceptor._on_loading_finished(SimpleNamespace(request_id=request_id, encoded_data_length=10), tab)
+
+
+class BodyCaptureTests(unittest.TestCase):
+ def test_only_text_bodies_are_stored(self):
+ interceptor = NetworkInterceptor()
+ tab = FakeTab({"api": '{"ok": 1}', "img": "binary", "doc": "<html>"})
+
+ async def run():
+ await load(interceptor, tab, "api", "https://x/api", "Fetch", "application/json")
+ await load(interceptor, tab, "img", "https://x/a.png", "Image", "image/png")
+ await load(interceptor, tab, "doc", "https://x/", "Document", "text/html")
+
+ asyncio.run(run())
+ self.assertEqual(tab.fetched, ["api", "doc"])
+ self.assertEqual(interceptor._responses["api"].body, b'{"ok": 1}')
+ self.assertIsNone(interceptor._responses["img"].body)
+
+ def test_stored_bodies_are_capped_and_served(self):
+ interceptor = NetworkInterceptor()
+ tab = FakeTab({f"r{index}": "x" * 40 for index in range(5)})
+ original = network_module.MAX_STORED_BODY_BYTES
+ network_module.MAX_STORED_BODY_BYTES = 100
+
+ async def run():
+ for index in range(5):
+ await load(interceptor, tab, f"r{index}", f"https://x/{index}", "XHR", "application/json")
+ return await interceptor.get_response_body(tab, "r4")
+
+ try:
+ served = asyncio.run(run())
+ finally:
+ network_module.MAX_STORED_BODY_BYTES = original
+ stored = [request_id for request_id in ("r0", "r1", "r2", "r3", "r4") if interceptor._responses[request_id].body]
+ self.assertEqual(stored, ["r3", "r4"])
+ self.assertEqual(interceptor._body_bytes["i"], 80)
+ self.assertEqual(served, b"x" * 40)
+ self.assertEqual(tab.fetched.count("r4"), 1)
+
+ def test_internal_urls_are_ignored_and_clear_resets(self):
+ interceptor = NetworkInterceptor()
+ tab = FakeTab({"api": "{}"})
+
+ async def run():
+ await interceptor._on_request(request_event("ntp", "chrome://new-tab-page/", "Script"), "i")
+ await load(interceptor, tab, "api", "https://x/api", "XHR", "application/json")
+ await interceptor.clear_instance_data("i")
+
+ asyncio.run(run())
+ self.assertNotIn("ntp", interceptor._requests)
+ self.assertNotIn("api", interceptor._requests)
+ self.assertNotIn("i", interceptor._body_bytes)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_page_bindings.py b/tests/test_page_bindings.py
new file mode 100644
index 0000000..532fe44
--- /dev/null
+++ b/tests/test_page_bindings.py
@@ -0,0 +1,147 @@
+import asyncio
+import json
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "src"))
+
+import nodriver as uc
+
+import page_bindings as page_bindings_module
+from page_bindings import MAX_PAYLOAD_BYTES, PageBindingManager
+
+
+class FakeTab:
+ """Tab that records CDP methods and answers evaluate calls."""
+
+ def __init__(self, existing_globals=()):
+ self.handlers = {}
+ self.methods = []
+ self.settled = []
+ self.existing_globals = set(existing_globals)
+
+ def add_handler(self, event_type, handler):
+ self.handlers.setdefault(event_type, []).append(handler)
+
+ async def send(self, command):
+ request = next(command)
+ self.methods.append(request["method"])
+ if request["method"] == "Runtime.evaluate":
+ expression = request["params"]["expression"]
+ if expression.endswith("in globalThis"):
+ name = json.loads(expression.split(" in ")[0])
+ return SimpleNamespace(value=name in self.existing_globals), None
+ if "settle" in expression:
+ self.settled.append(expression)
+ return SimpleNamespace(value=True), None
+ return SimpleNamespace(value=None), None
+ if request["method"] == "Page.addScriptToEvaluateOnNewDocument":
+ return "script-1"
+ return None
+
+ def call(self, name, payload, context_id=7):
+ event = SimpleNamespace(name=name, payload=payload, execution_context_id=context_id)
+ for handler in list(self.handlers.get(uc.cdp.runtime.BindingCalled, [])):
+ handler(event)
+
+
+def payload(call_id, *args):
+ return json.dumps({"id": call_id, "args": list(args)})
+
+
+class PageBindingTests(unittest.IsolatedAsyncioTestCase):
+ async def test_create_validates_names(self):
+ manager = PageBindingManager()
+ tab = FakeTab(existing_globals={"fetch"})
+ with self.assertRaises(ValueError):
+ await manager.create(tab, "i", "bad-name")
+ with self.assertRaises(ValueError):
+ await manager.create(tab, "i", "fetch")
+ result = await manager.create(tab, "i", "askAgent")
+ self.assertTrue(result["success"])
+ self.assertIn("Runtime.addBinding", tab.methods)
+ self.assertIn("Page.addScriptToEvaluateOnNewDocument", tab.methods)
+ with self.assertRaises(ValueError):
+ await manager.create(tab, "i", "askAgent")
+
+ async def test_call_queue_and_resolve(self):
+ manager = PageBindingManager()
+ tab = FakeTab()
+ await manager.create(tab, "i", "askAgent")
+ tab.call("askAgent", payload(1, {"q": "hi"}))
+ calls = await manager.get_calls("i")
+ self.assertEqual(len(calls), 1)
+ self.assertEqual(calls[0]["args"], [{"q": "hi"}])
+ self.assertEqual(calls[0]["status"], "pending")
+ self.assertEqual(len(await manager.get_calls("i")), 1)
+
+ result = await manager.resolve("i", calls[0]["call_id"], {"ok": True})
+ self.assertTrue(result["delivered"])
+ self.assertIn('{"ok": true}', tab.settled[-1])
+ self.assertEqual(await manager.get_calls("i"), [])
+ with self.assertRaises(ValueError):
+ await manager.resolve("i", calls[0]["call_id"], 1)
+
+ async def test_wait_for_call(self):
+ manager = PageBindingManager()
+ tab = FakeTab()
+ await manager.create(tab, "i", "askAgent")
+ asyncio.get_running_loop().call_later(0.05, tab.call, "askAgent", payload(1, "late"))
+ calls = await manager.get_calls("i", wait_seconds=2)
+ self.assertEqual(calls[0]["args"], ["late"])
+
+ async def test_rejects_bad_payloads(self):
+ manager = PageBindingManager()
+ tab = FakeTab()
+ await manager.create(tab, "i", "askAgent")
+ tab.call("askAgent", "not json")
+ tab.call("askAgent", json.dumps({"id": 1, "args": ["x" * MAX_PAYLOAD_BYTES]}))
+ tab.call("unknown", payload(2))
+ self.assertEqual(await manager.get_calls("i"), [])
+
+ async def test_auto_resolve_and_queue_cap(self):
+ manager = PageBindingManager()
+ tab = FakeTab()
+ await manager.create(tab, "i", "ping", auto_resolve=True, auto_response="pong")
+ original = page_bindings_module.MAX_QUEUED_CALLS
+ page_bindings_module.MAX_QUEUED_CALLS = 3
+ try:
+ for index in range(5):
+ tab.call("ping", payload(index))
+ await asyncio.sleep(0)
+ calls = await manager.get_calls("i")
+ finally:
+ page_bindings_module.MAX_QUEUED_CALLS = original
+ self.assertEqual([call["status"] for call in calls], ["auto_resolved"] * 3)
+ self.assertEqual(await manager.get_calls("i"), [])
+ self.assertTrue(any('"pong"' in expression for expression in tab.settled))
+
+ async def test_prepare_tab_installs_once_and_forget(self):
+ manager = PageBindingManager()
+ first, second = FakeTab(), FakeTab()
+ await manager.create(first, "i", "askAgent")
+ await manager.prepare_tab(second, "i")
+ await manager.prepare_tab(second, "i")
+ self.assertEqual(second.methods.count("Runtime.addBinding"), 1)
+ await manager.forget_instance("i")
+ self.assertEqual(manager.list_bindings("i"), [])
+ self.assertFalse(first.handlers.get(uc.cdp.runtime.BindingCalled))
+
+ async def test_remove_rejects_pending(self):
+ manager = PageBindingManager()
+ tab = FakeTab()
+ await manager.create(tab, "i", "askAgent")
+ tab.call("askAgent", payload(1))
+ await manager.remove("i", "askAgent")
+ self.assertIn('"Binding removed"', tab.settled[-1])
+ self.assertIn("Runtime.removeBinding", tab.methods)
+ self.assertEqual(await manager.get_calls("i"), [])
+ with self.assertRaises(ValueError):
+ await manager.remove("i", "askAgent")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_press_key.py b/tests/test_press_key.py
index 6d2c267..3c81906 100644
--- a/tests/test_press_key.py
+++ b/tests/test_press_key.py
@@ -8,12 +8,12 @@ from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
-from dom_handler import (
+from dom_handler import DOMHandler
+from key_definitions import (
MODIFIER_ALT,
MODIFIER_CONTROL,
MODIFIER_META,
MODIFIER_SHIFT,
- DOMHandler,
resolve_key_descriptor,
resolve_modifiers,
)
@@ -31,12 +31,11 @@ RECORDER_PAGE = """<!doctype html>
<html><body><input id="target">
<script>
window.__events = [];
-const input = document.getElementById('target');
for (const type of ['keydown', 'keypress', 'keyup']) {
- input.addEventListener(type, (e) => {
+ document.addEventListener(type, (e) => {
window.__events.push({ type: e.type, key: e.key, isTrusted: e.isTrusted,
shiftKey: e.shiftKey });
- });
+ }, true);
}
</script>
</body></html>"""
diff --git a/tests/test_proxy_forwarder.py b/tests/test_proxy_forwarder.py
new file mode 100644
index 0000000..0404976
--- /dev/null
+++ b/tests/test_proxy_forwarder.py
@@ -0,0 +1,122 @@
+import asyncio
+import base64
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "src"))
+
+from proxy_forwarder import AuthenticatedProxyForwarder
+
+RESPONSE = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"
+
+
+class FakeUpstream:
+ """Upstream proxy that records request heads and answers each once."""
+
+ def __init__(self, connect_status=b"200 Connection established"):
+ self.requests = []
+ self.connect_status = connect_status
+ self.server = None
+
+ async def handle(self, reader, writer):
+ head = await reader.readuntil(b"\r\n\r\n")
+ self.requests.append(head.decode())
+ if head.startswith(b"CONNECT"):
+ writer.write(b"HTTP/1.1 " + self.connect_status + b"\r\n\r\n")
+ await writer.drain()
+ if self.connect_status.startswith(b"200"):
+ data = await reader.read(5)
+ writer.write(data.upper())
+ await writer.drain()
+ else:
+ writer.write(RESPONSE)
+ await writer.drain()
+ writer.close()
+
+ async def __aenter__(self):
+ self.server = await asyncio.start_server(self.handle, "127.0.0.1", 0)
+ return self
+
+ async def __aexit__(self, *exc):
+ self.server.close()
+ await self.server.wait_closed()
+
+ @property
+ def port(self):
+ return self.server.sockets[0].getsockname()[1]
+
+
+async def forward(upstream, payload, read_bytes=1024):
+ forwarder = AuthenticatedProxyForwarder(f"http://user:p%[email protected]:{upstream.port}")
+ await forwarder.start()
+ try:
+ reader, writer = await asyncio.open_connection(forwarder.host, forwarder.port)
+ writer.write(payload)
+ await writer.drain()
+ data = await asyncio.wait_for(reader.read(read_bytes), 5)
+ closed = await asyncio.wait_for(reader.read(), 5) == b""
+ writer.close()
+ return data, closed
+ finally:
+ await forwarder.close()
+
+
+class ProxyForwarderTests(unittest.TestCase):
+ def test_plain_http_sends_credentials_and_closes(self):
+ async def run():
+ async with FakeUpstream() as upstream:
+ request = (
+ b"GET http://example.com/ HTTP/1.1\r\nHost: example.com\r\n"
+ b"Proxy-Connection: keep-alive\r\nConnection: keep-alive\r\n"
+ b"Proxy-Authorization: Basic stale\r\n\r\n"
+ )
+ data, closed = await forward(upstream, request)
+ return upstream.requests, data, closed
+
+ requests, data, closed = asyncio.run(run())
+ expected = base64.b64encode(b"user:p@ss").decode()
+ head = requests[0]
+ self.assertIn(f"Proxy-Authorization: Basic {expected}", head)
+ self.assertNotIn("stale", head)
+ self.assertNotIn("keep-alive", head.lower())
+ self.assertIn("Connection: close", head)
+ self.assertTrue(data.endswith(b"ok"))
+ self.assertTrue(closed)
+
+ def test_connect_tunnel_relays_data(self):
+ async def run():
+ async with FakeUpstream() as upstream:
+ forwarder = AuthenticatedProxyForwarder(f"http://user:[email protected]:{upstream.port}")
+ await forwarder.start()
+ try:
+ reader, writer = await asyncio.open_connection(forwarder.host, forwarder.port)
+ writer.write(b"CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\n\r\n")
+ await writer.drain()
+ status = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), 5)
+ writer.write(b"hello")
+ await writer.drain()
+ echoed = await asyncio.wait_for(reader.read(5), 5)
+ writer.close()
+ return upstream.requests, status, echoed
+ finally:
+ await forwarder.close()
+
+ requests, status, echoed = asyncio.run(run())
+ self.assertIn("Proxy-Authorization: Basic ", requests[0])
+ self.assertTrue(status.startswith(b"HTTP/1.1 200"))
+ self.assertEqual(echoed, b"HELLO")
+
+ def test_connect_rejection_is_reported(self):
+ async def run():
+ async with FakeUpstream(connect_status=b"407 Proxy Authentication Required 200") as upstream:
+ return await forward(upstream, b"CONNECT example.com:443 HTTP/1.1\r\n\r\n")
+
+ data, closed = asyncio.run(run())
+ self.assertTrue(data.startswith(b"HTTP/1.1 502"))
+ self.assertTrue(closed)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_stealth_benchmark.py b/tests/test_stealth_benchmark.py
new file mode 100644
index 0000000..05e6f5f
--- /dev/null
+++ b/tests/test_stealth_benchmark.py
@@ -0,0 +1,500 @@
+import asyncio
+import io
+import json
+import os
+import sys
+import tempfile
+import unittest
+import zipfile
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+from benchmarks.stealth import __main__ as cli
+from benchmarks.stealth.chrome import download_url, extract_zip, resolve_milestone
+from benchmarks.stealth.environment import runner_label
+from benchmarks.stealth.regression import compare_runs, find_regressions, previous_run, render_issue
+from benchmarks.stealth.report import END_MARKER, START_MARKER, render_section, update_report
+from benchmarks.stealth.results import (
+ Check,
+ RunResult,
+ Status,
+ TargetResult,
+ latest_by_runner,
+ load_run,
+ load_runs,
+ save_run,
+)
+from benchmarks.stealth.targets import select_targets
+from benchmarks.stealth.targets.base import status_from_checks
+from benchmarks.stealth.targets.cloudflare import CloudflareTarget
+from benchmarks.stealth.targets.creepjs import CreepJSTarget, parse_scores
+from benchmarks.stealth.targets.local_probe import (
+ INIT_MARKER,
+ SPOOFED_RENDERER,
+ InitScriptTarget,
+ LocalProbeTarget,
+ platform_matches,
+)
+from benchmarks.stealth.targets.input_fidelity import TYPED_TEXT, InputFidelityTarget
+from benchmarks.stealth.targets.result_tables import SannysoftTarget
+from benchmarks.stealth.targets.tls_fingerprint import (
+ CHROME_AKAMAI_FINGERPRINT,
+ TLSFingerprintTarget,
+)
+
+RUN_BROWSER_TESTS = os.getenv("STEALTH_BROWSER_TESTS", "").strip().lower() in {"1", "true", "yes"}
+
+CHROME_UA = (
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36"
+)
+HEADLESS_UA = CHROME_UA.replace("Chrome/", "HeadlessChrome/")
+CREEPJS_PANEL = (
+ "7.30ms\nHeadless1634593a\nchromium: true\n25% like headless: 8d3a3ce5\n"
+ "67% headless: f49f2dad\n0% stealth: 0c019315\nplatform hints:"
+)
+
+
+def probe_payload(**overrides):
+ payload = {
+ "webdriver": False,
+ "userAgent": CHROME_UA,
+ "platform": "Win32",
+ "brands": ["Chromium", "Google Chrome", "Not A(Brand"],
+ "uaPlatform": "Windows",
+ "hasChrome": True,
+ "plugins": 5,
+ "pluginsIsArray": True,
+ "languages": ["en-US", "en"],
+ "language": "en-US",
+ "hardwareConcurrency": 16,
+ "outer": [0, 0],
+ "outerAfterLoad": [1920, 1080],
+ "notificationPermission": "default",
+ "permissionQuery": "prompt",
+ "webgl": True,
+ "webglVendor": "Google Inc. (NVIDIA)",
+ "webglRenderer": "ANGLE (NVIDIA, NVIDIA GeForce RTX 2070 SUPER Direct3D11)",
+ "iframeChrome": True,
+ "iframeWebdriver": False,
+ "consoleStackRead": False,
+ }
+ payload.update(overrides)
+ return payload
+
+
+def tls_payload(**overrides):
+ payload = {
+ "http_version": "h2",
+ "user_agent": CHROME_UA,
+ "tls": {
+ "ja3_hash": "3b9c1f63151fb23feec32294cdd489c7",
+ "ja4": "t13d1517h2_8daaf6152771_cb7bf5808d99",
+ "peetprint_hash": "fc97c1cdfb1409c9a9326c1b726d1dee",
+ },
+ "http2": {
+ "akamai_fingerprint": CHROME_AKAMAI_FINGERPRINT,
+ "akamai_fingerprint_hash": "52d84b11737d980aef856699f885ca86",
+ },
+ }
+ payload.update(overrides)
+ return payload
+
+
+def make_target(name, status, checks=(), details=None, title=None):
+ return TargetResult(
+ name=name,
+ title=title or name.title(),
+ category="test",
+ url="https://example.com/",
+ status=status,
+ summary=f"{name} {status.value}",
+ checks=list(checks),
+ details=details or {},
+ )
+
+
+def make_run(date, runner="linux-x64-headless-stable", targets=None):
+ return RunResult(
+ runner=runner,
+ date=date,
+ started_at=f"{date}T00:00:00+00:00",
+ finished_at=f"{date}T00:05:00+00:00",
+ environment={"chrome_version": "154.0.1.2", "nodriver": "0.47.0", "os_release": "Linux"},
+ targets=targets or [],
+ )
+
+
+class StatusTests(unittest.TestCase):
+ def test_status_from_checks(self):
+ self.assertEqual(status_from_checks([]), Status.UNREACHABLE)
+ self.assertEqual(status_from_checks([Check("a", True)]), Status.PASS)
+ self.assertEqual(status_from_checks([Check("a", True), Check("b", False, critical=False)]), Status.DEGRADED)
+ self.assertEqual(status_from_checks([Check("a", False), Check("b", False, critical=False)]), Status.FAIL)
+
+ def test_severity_order(self):
+ self.assertLess(Status.PASS.severity, Status.DEGRADED.severity)
+ self.assertLess(Status.DEGRADED.severity, Status.FAIL.severity)
+ self.assertIsNone(Status.UNREACHABLE.severity)
+
+
+class TargetEvaluationTests(unittest.TestCase):
+ def test_result_table_verdicts(self):
+ rows = [
+ {"name": "WebDriver (New)", "verdict": "passed", "value": "missing (passed)"},
+ {"name": "CHR_MEMORY", "verdict": "warn", "value": "WARN"},
+ ]
+ checks, details, summary = SannysoftTarget().evaluate({"rows": rows})
+ self.assertEqual(status_from_checks(checks), Status.DEGRADED)
+ self.assertEqual(details["WebDriver (New)"], "missing (passed)")
+ self.assertIn("1/2", summary)
+
+ rows.append({"name": "HEADCHR_UA", "verdict": "failed", "value": "FAIL"})
+ checks, _, summary = SannysoftTarget().evaluate({"rows": rows})
+ self.assertEqual(status_from_checks(checks), Status.FAIL)
+ self.assertIn("HEADCHR_UA", summary)
+
+ def test_creepjs_scores(self):
+ self.assertEqual(parse_scores(CREEPJS_PANEL), {"like_headless": 25, "headless": 67, "stealth": 0})
+ checks, details, _ = CreepJSTarget().evaluate({"panel_text": CREEPJS_PANEL})
+ self.assertEqual(status_from_checks(checks), Status.FAIL)
+ self.assertEqual(details["headless_percent"], 67)
+
+ clean = CREEPJS_PANEL.replace("67% headless", "0% headless")
+ self.assertEqual(status_from_checks(CreepJSTarget().evaluate({"panel_text": clean})[0]), Status.PASS)
+ partial = CREEPJS_PANEL.replace("67% headless", "33% headless")
+ self.assertEqual(status_from_checks(CreepJSTarget().evaluate({"panel_text": partial})[0]), Status.DEGRADED)
+ tampered = clean.replace("0% stealth", "20% stealth")
+ self.assertEqual(status_from_checks(CreepJSTarget().evaluate({"panel_text": tampered})[0]), Status.FAIL)
+ self.assertEqual(CreepJSTarget().evaluate({"panel_text": "nothing"})[0], [])
+
+ def test_cloudflare(self):
+ target = CloudflareTarget()
+ passed = target.evaluate({"title": "nowsecure.nl", "text": "NOWSECURE BY NODRIVER", "waited_seconds": 1.0})
+ self.assertEqual(status_from_checks(passed[0]), Status.PASS)
+ stuck = target.evaluate({"title": "Just a moment...", "text": "Verify you are human", "challengeFrame": True})
+ self.assertEqual(status_from_checks(stuck[0]), Status.FAIL)
+ other = target.evaluate({"title": "502 Bad Gateway", "text": "nginx"})
+ self.assertEqual(status_from_checks(other[0]), Status.UNREACHABLE)
+
+ def test_tls(self):
+ target = TLSFingerprintTarget()
+ checks, details, _ = target.evaluate(tls_payload())
+ self.assertEqual(status_from_checks(checks), Status.PASS)
+ self.assertEqual(details["ja4"], "t13d1517h2_8daaf6152771_cb7bf5808d99")
+ self.assertNotIn("ip", details)
+
+ headless = target.evaluate(tls_payload(user_agent=HEADLESS_UA))[0]
+ self.assertEqual(status_from_checks(headless), Status.FAIL)
+ drifted = tls_payload(http2={"akamai_fingerprint": "1:65536|0|0|m,p,a,s"})
+ self.assertEqual(status_from_checks(target.evaluate(drifted)[0]), Status.DEGRADED)
+
+ def test_local_probe(self):
+ target = LocalProbeTarget()
+ self.assertEqual(status_from_checks(target.evaluate(probe_payload())[0]), Status.PASS)
+ self.assertEqual(status_from_checks(target.evaluate(probe_payload(userAgent=HEADLESS_UA))[0]), Status.FAIL)
+ self.assertEqual(status_from_checks(target.evaluate(probe_payload(webdriver=True))[0]), Status.FAIL)
+ self.assertEqual(status_from_checks(target.evaluate(probe_payload(outerAfterLoad=[0, 0]))[0]), Status.FAIL)
+ software = probe_payload(webglRenderer="ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device))")
+ self.assertEqual(status_from_checks(target.evaluate(software)[0]), Status.DEGRADED)
+ inconsistent = probe_payload(notificationPermission="denied", permissionQuery="prompt")
+ self.assertEqual(status_from_checks(target.evaluate(inconsistent)[0]), Status.FAIL)
+
+ def test_input_fidelity(self):
+ def events(trusted=True):
+ recorded = [
+ {"type": "pointerdown", "trusted": trusted, "key": None, "time": 10.0},
+ {"type": "mousedown", "trusted": trusted, "key": None, "time": 10.0},
+ {"type": "mouseup", "trusted": trusted, "key": None, "time": 80.0},
+ {"type": "click", "trusted": trusted, "key": None, "time": 80.0},
+ ]
+ for char in TYPED_TEXT:
+ recorded.append({"type": "keydown", "trusted": trusted, "key": char, "time": 90.0})
+ recorded.append({"type": "input", "trusted": trusted, "key": None, "time": 90.0})
+ recorded.append({"type": "keyup", "trusted": trusted, "key": char, "time": 95.0})
+ return recorded
+
+ target = InputFidelityTarget()
+ good = {"events": events(), "moves": 4, "added": 0, "value": TYPED_TEXT}
+ self.assertEqual(status_from_checks(target.evaluate(good)[0]), Status.PASS)
+ self.assertEqual(status_from_checks(target.evaluate(dict(good, events=events(False)))[0]), Status.FAIL)
+ self.assertEqual(status_from_checks(target.evaluate(dict(good, added=1))[0]), Status.FAIL)
+ self.assertEqual(status_from_checks(target.evaluate(dict(good, moves=0))[0]), Status.DEGRADED)
+ script_click = [event for event in events() if event["type"] not in ("pointerdown", "mousedown", "mouseup")]
+ self.assertEqual(status_from_checks(target.evaluate(dict(good, events=script_click))[0]), Status.FAIL)
+
+ def test_platform_matches(self):
+ self.assertTrue(platform_matches("Win32", "Windows"))
+ self.assertTrue(platform_matches("MacIntel", "macOS"))
+ self.assertTrue(platform_matches("Linux x86_64", "Linux"))
+ self.assertFalse(platform_matches("Win32", "macOS"))
+ self.assertTrue(platform_matches("", "Windows"))
+
+ def test_init_script(self):
+ target = InitScriptTarget()
+ good = {"webgl": True, "initMarkerAtParse": INIT_MARKER, "webglRenderer": SPOOFED_RENDERER}
+ payload = {"identifier": "1", "loads": [good, good]}
+ self.assertEqual(status_from_checks(target.evaluate(payload)[0]), Status.PASS)
+
+ missing = {"webgl": True, "initMarkerAtParse": None, "webglRenderer": "real"}
+ payload = {"identifier": "1", "loads": [missing, missing]}
+ self.assertEqual(status_from_checks(target.evaluate(payload)[0]), Status.FAIL)
+
+ no_webgl = {"webgl": False, "initMarkerAtParse": INIT_MARKER, "webglRenderer": None}
+ checks = target.evaluate({"identifier": "1", "loads": [no_webgl, no_webgl]})[0]
+ self.assertEqual(status_from_checks(checks), Status.PASS)
+ self.assertEqual(len(checks), 3)
+
+ def test_select_targets(self):
+ self.assertEqual([t.name for t in select_targets(["tls", "local_probe"])], ["local_probe", "tls"])
+ self.assertEqual(len(select_targets()), 8)
+ with self.assertRaises(ValueError):
+ select_targets(["missing"])
+
+
+class ResultStorageTests(unittest.TestCase):
+ def test_round_trip(self):
+ run = make_run("2026-10-10", targets=[make_target("tls", Status.PASS, [Check("a", True, value=[1, 2])])])
+ with tempfile.TemporaryDirectory() as tmp:
+ path = save_run(run, Path(tmp))
+ self.assertEqual(path.name, "2026-10-10-linux-x64-headless-stable.json")
+ data = json.loads(path.read_text(encoding="utf-8"))
+ self.assertEqual(data["summary"]["PASS"], 1)
+ self.assertEqual(data["targets"][0]["status"], "PASS")
+ loaded = load_run(path)
+ self.assertEqual(loaded.target("tls").status, Status.PASS)
+ self.assertEqual(loaded.target("tls").checks[0].value, [1, 2])
+
+ def test_load_runs_and_latest(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ directory = Path(tmp)
+ save_run(make_run("2026-10-03"), directory)
+ save_run(make_run("2026-10-10"), directory)
+ save_run(make_run("2026-10-01", runner="macos-arm64-headed-stable"), directory)
+ (directory / "notes.json").write_text("{}", encoding="utf-8")
+ runs = load_runs(directory)
+ self.assertEqual([run.date for run in runs], ["2026-10-01", "2026-10-03", "2026-10-10"])
+ latest = latest_by_runner(runs)
+ self.assertEqual(list(latest), ["linux-x64-headless-stable", "macos-arm64-headed-stable"])
+ self.assertEqual(latest["linux-x64-headless-stable"].date, "2026-10-10")
+
+ def test_runner_label(self):
+ self.assertEqual(runner_label("headless", "stable", "Linux X64 / Custom"), "linux-x64-custom")
+ self.assertRegex(runner_label("headed", "previous"), r"^[a-z0-9.-]+-headed-previous$")
+
+
+class RegressionTests(unittest.TestCase):
+ def test_pass_to_fail_is_reported(self):
+ before = make_run(
+ "2026-10-03",
+ targets=[
+ make_target(
+ "tls",
+ Status.PASS,
+ [Check("ua", True), Check("h2", True)],
+ {"akamai_fingerprint": "1:65536|15663105|0|m,a,s,p"},
+ ),
+ make_target("cloudflare", Status.PASS),
+ ],
+ )
+ after = make_run(
+ "2026-10-10",
+ targets=[
+ make_target(
+ "tls",
+ Status.FAIL,
+ [Check("ua", False), Check("h2", True)],
+ {"akamai_fingerprint": "changed|value"},
+ ),
+ make_target("cloudflare", Status.UNREACHABLE),
+ ],
+ )
+ regressions = compare_runs(before, after)
+ self.assertEqual(len(regressions), 1)
+ self.assertEqual(regressions[0].new_failed_checks, ["ua"])
+ self.assertIn("akamai_fingerprint", regressions[0].changed_details)
+
+ body = render_issue(regressions, "2026-10-10", "https://example.com/run/1")
+ self.assertIn("PASS (2026-10-03) to FAIL", body)
+ self.assertIn("changed\\|value", body)
+ self.assertNotIn("—", body)
+
+ def test_improvement_and_unreachable_are_ignored(self):
+ before = make_run("2026-10-03", targets=[make_target("a", Status.FAIL), make_target("b", Status.UNREACHABLE)])
+ after = make_run("2026-10-10", targets=[make_target("a", Status.PASS), make_target("b", Status.FAIL)])
+ self.assertEqual(compare_runs(before, after), [])
+
+ def test_previous_run_matches_runner_and_date(self):
+ history = [
+ make_run("2026-09-26"),
+ make_run("2026-10-03"),
+ make_run("2026-10-05", runner="windows-x64-headed-stable"),
+ make_run("2026-10-10"),
+ ]
+ current = make_run("2026-10-10")
+ self.assertEqual(previous_run(history, current).date, "2026-10-03")
+ self.assertIsNone(previous_run(history, make_run("2026-10-10", runner="new-runner")))
+
+ def test_find_regressions_across_runs(self):
+ history = [make_run("2026-10-03", targets=[make_target("a", Status.PASS)])]
+ incoming = [make_run("2026-10-10", targets=[make_target("a", Status.DEGRADED)])]
+ self.assertEqual(len(find_regressions(history, incoming)), 1)
+
+
+class ReportTests(unittest.TestCase):
+ def test_render_section(self):
+ runs = [
+ make_run("2026-10-03", targets=[make_target("tls", Status.PASS, title="TLS")]),
+ make_run(
+ "2026-10-10",
+ targets=[
+ make_target("tls", Status.FAIL, [Check("ua has no | pipe", False)], title="TLS"),
+ make_target("cloudflare", Status.UNREACHABLE, title="Cloudflare"),
+ ],
+ ),
+ ]
+ runs[1].targets[1].error = "Navigation failed\nsecond line"
+ section = render_section(runs)
+ self.assertTrue(section.startswith(START_MARKER))
+ self.assertTrue(section.endswith(END_MARKER))
+ self.assertIn("| TLS | test | FAIL |", section)
+ self.assertIn("Cloudflare: not measured, Navigation failed", section)
+ self.assertNotIn("second line", section)
+ self.assertIn("| 2026-10-10 | 0/2 |", section)
+ self.assertIn("| 2026-10-03 | 1/1 |", section)
+ self.assertNotIn("—", section)
+
+ def test_render_without_runs(self):
+ self.assertIn("No automated runs", render_section([]))
+
+ def test_update_report(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "REPORT.md"
+ path.write_text(f"# Title\n\n{START_MARKER}\nold\n{END_MARKER}\n\n## Manual\n", encoding="utf-8")
+ runs = [make_run("2026-10-10", targets=[make_target("tls", Status.PASS)])]
+ self.assertTrue(update_report(path, runs))
+ self.assertFalse(update_report(path, runs))
+ text = path.read_text(encoding="utf-8")
+ self.assertTrue(text.startswith("# Title\n\n"))
+ self.assertTrue(text.endswith(f"{END_MARKER}\n\n## Manual\n"))
+ self.assertNotIn("old", text)
+
+ path.write_text("# No markers\n", encoding="utf-8")
+ with self.assertRaises(ValueError):
+ update_report(path, runs)
+
+ def test_repository_report_has_markers(self):
+ text = (ROOT / "STEALTH_TESTS.md").read_text(encoding="utf-8")
+ self.assertLess(text.index(START_MARKER), text.index(END_MARKER))
+
+
+class ChromeInstallTests(unittest.TestCase):
+ def test_resolve_milestone(self):
+ self.assertEqual(resolve_milestone("stable", "154.0.8037.98"), 154)
+ self.assertEqual(resolve_milestone("previous", "154.0.8037.98"), 153)
+ self.assertEqual(resolve_milestone("150", "154.0.8037.98"), 150)
+ with self.assertRaises(ValueError):
+ resolve_milestone("beta", "154.0.8037.98")
+
+ def test_download_url(self):
+ milestones = {
+ "milestones": {
+ "153": {
+ "version": "153.0.1.0",
+ "downloads": {"chrome": [{"platform": "linux64", "url": "https://example.com/linux.zip"}]},
+ }
+ }
+ }
+ self.assertEqual(download_url(milestones, 153, "linux64"), ("153.0.1.0", "https://example.com/linux.zip"))
+ with self.assertRaises(LookupError):
+ download_url(milestones, 153, "win64")
+ with self.assertRaises(LookupError):
+ download_url(milestones, 152, "linux64")
+
+ def test_extract_zip_rejects_traversal(self):
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ archive.writestr("../escape.txt", "x")
+ with tempfile.TemporaryDirectory() as tmp:
+ with self.assertRaises(RuntimeError):
+ extract_zip(buffer.getvalue(), Path(tmp) / "out")
+
+ def test_extract_zip_keeps_files(self):
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ info = zipfile.ZipInfo("chrome-linux64/chrome")
+ info.external_attr = 0o755 << 16
+ archive.writestr(info, "binary")
+ with tempfile.TemporaryDirectory() as tmp:
+ extract_zip(buffer.getvalue(), Path(tmp))
+ self.assertEqual((Path(tmp) / "chrome-linux64" / "chrome").read_text(), "binary")
+
+
+class CommandLineTests(unittest.TestCase):
+ def test_compare_writes_issue_and_outputs(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ save_run(make_run("2026-10-03", targets=[make_target("a", Status.PASS)]), root / "history")
+ save_run(make_run("2026-10-10", targets=[make_target("a", Status.FAIL)]), root / "incoming")
+ output = root / "github_output"
+ issue = root / "issue.md"
+ with mock.patch.dict(os.environ, {"GITHUB_OUTPUT": str(output)}), mock.patch("sys.stdout", io.StringIO()):
+ code = cli.main(
+ [
+ "compare",
+ "--incoming",
+ str(root / "incoming"),
+ "--results-dir",
+ str(root / "history"),
+ "--issue-file",
+ str(issue),
+ ]
+ )
+ self.assertEqual(code, 0)
+ self.assertIn("regressions=1", output.read_text(encoding="utf-8"))
+ self.assertIn("title=Stealth benchmark regression on 2026-10-10", output.read_text(encoding="utf-8"))
+ self.assertIn("PASS (2026-10-03) to FAIL", issue.read_text(encoding="utf-8"))
+
+ def test_compare_without_regressions_skips_issue(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ save_run(make_run("2026-10-10", targets=[make_target("a", Status.PASS)]), root / "incoming")
+ issue = root / "issue.md"
+ with mock.patch.dict(os.environ, {"GITHUB_OUTPUT": ""}), mock.patch("sys.stdout", io.StringIO()):
+ code = cli.main(
+ ["compare", "--incoming", str(root / "incoming"), "--results-dir", str(root / "none"), "--issue-file", str(issue)]
+ )
+ self.assertEqual(code, 0)
+ self.assertFalse(issue.exists())
+
+ def test_render_command(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ report = root / "REPORT.md"
+ report.write_text(f"{START_MARKER}\n{END_MARKER}\n", encoding="utf-8")
+ save_run(make_run("2026-10-10", targets=[make_target("a", Status.PASS)]), root / "results")
+ with mock.patch("sys.stdout", io.StringIO()):
+ code = cli.main(["render", "--results-dir", str(root / "results"), "--report", str(report)])
+ self.assertEqual(code, 0)
+ self.assertIn("| A | test | PASS |", report.read_text(encoding="utf-8"))
+
+
+ RUN_BROWSER_TESTS,
+ "Set STEALTH_BROWSER_TESTS=1 to run tests that launch a real browser.",
+)
+class LocalTargetsBrowserTests(unittest.TestCase):
+ def test_local_targets_run(self):
+ from benchmarks.stealth.runner import run_benchmark
+
+ run = asyncio.run(run_benchmark(select_targets(["local_probe", "init_script"]), mode="headless"))
+ self.assertEqual(run.target("init_script").status, Status.PASS)
+ self.assertNotEqual(run.target("local_probe").status, Status.UNREACHABLE)
+ self.assertTrue(run.environment.get("chrome_version"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_tabs_and_contexts.py b/tests/test_tabs_and_contexts.py
new file mode 100644
index 0000000..36df0f4
--- /dev/null
+++ b/tests/test_tabs_and_contexts.py
@@ -0,0 +1,106 @@
+import asyncio
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "src"))
+
+import nodriver as uc
+
+from browser_manager import BrowserManager
+from cdp_function_executor import CDPFunctionExecutor
+from models import BrowserOptions
+
+
+class FakeTab:
+ def __init__(self, browser, target_id):
+ self.browser = browser
+ self.target = SimpleNamespace(target_id=target_id)
+ self.handlers = {}
+
+ def __await__(self):
+ if False:
+ yield
+ return self
+
+ async def close(self):
+ self.browser.tabs.remove(self)
+
+
+class FakeBrowser:
+ def __init__(self, count):
+ self.tabs = [FakeTab(self, f"tab-{i}") for i in range(count)]
+ self.created = 0
+
+ async def update_targets(self):
+ return None
+
+ async def get(self, url, new_tab=False):
+ self.created += 1
+ tab = FakeTab(self, f"new-{self.created}")
+ self.tabs.append(tab)
+ return tab
+
+
+def manager_with(browser, current):
+ manager = BrowserManager()
+ manager._instances["i"] = {
+ "browser": browser,
+ "tab": current,
+ "navigation_count": 0,
+ "options": BrowserOptions(),
+ "init_scripts": [],
+ "configured_tabs": set(),
+ }
+ return manager
+
+
+class CloseTabTests(unittest.TestCase):
+ def test_closing_current_tab_moves_to_remaining(self):
+ browser = FakeBrowser(2)
+ manager = manager_with(browser, browser.tabs[1])
+ self.assertTrue(asyncio.run(manager.close_tab("i", "tab-1")))
+ self.assertEqual(manager._instances["i"]["tab"].target.target_id, "tab-0")
+
+ def test_closing_other_tab_keeps_current(self):
+ browser = FakeBrowser(2)
+ manager = manager_with(browser, browser.tabs[0])
+ self.assertTrue(asyncio.run(manager.close_tab("i", "tab-1")))
+ self.assertEqual(manager._instances["i"]["tab"].target.target_id, "tab-0")
+
+ def test_closing_last_tab_opens_blank_tab(self):
+ browser = FakeBrowser(1)
+ manager = manager_with(browser, browser.tabs[0])
+ self.assertTrue(asyncio.run(manager.close_tab("i", "tab-0")))
+ self.assertEqual([tab.target.target_id for tab in browser.tabs], ["new-1"])
+ self.assertEqual(manager._instances["i"]["tab"].target.target_id, "new-1")
+
+ def test_unknown_tab_and_instance(self):
+ browser = FakeBrowser(1)
+ manager = manager_with(browser, browser.tabs[0])
+ self.assertFalse(asyncio.run(manager.close_tab("i", "missing")))
+ self.assertFalse(asyncio.run(manager.close_tab("other", "tab-0")))
+
+
+class ContextKwargsTests(unittest.TestCase):
+ def test_context_kwargs(self):
+ self.assertEqual(CDPFunctionExecutor._context_kwargs(None), {})
+ self.assertEqual(CDPFunctionExecutor._context_kwargs(" "), {})
+ numeric = CDPFunctionExecutor._context_kwargs("3")
+ self.assertEqual(numeric, {"context_id": uc.cdp.runtime.ExecutionContextId(3)})
+ self.assertEqual(
+ CDPFunctionExecutor._context_kwargs("-123.456"),
+ {"unique_context_id": "-123.456"},
+ )
+
+ def test_evaluate_accepts_context_kwargs(self):
+ command = uc.cdp.runtime.evaluate(expression="1", **CDPFunctionExecutor._context_kwargs("7"))
+ self.assertEqual(next(command)["params"]["contextId"], 7)
+ command = uc.cdp.runtime.evaluate(expression="1", **CDPFunctionExecutor._context_kwargs("abc"))
+ self.assertEqual(next(command)["params"]["uniqueContextId"], "abc")
+
+
+if __name__ == "__main__":
+ unittest.main()