Compare commits
59
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0cf7de2dd6 | ||
|
|
658bf4226f | ||
|
|
37cd9b91e1 | ||
|
|
b2c4aa0004 | ||
|
|
ec8d01ef4c | ||
|
|
0e5409a81e | ||
|
|
3ded30c210 | ||
|
|
6e50f0ecab | ||
|
|
6f71f4e1ff | ||
|
|
31ef0d7e6a | ||
|
|
42560b56fc | ||
|
|
0c7534d9b2 | ||
|
|
ad4fb14ed9 | ||
|
|
a976287f03 | ||
|
|
649fa4ce94 | ||
|
|
3ac69e822a | ||
|
|
d7a0ed85f9 | ||
|
|
9eaa5495ae | ||
|
|
68734fcb36 | ||
|
|
4b33dbadb4 | ||
|
|
fc73ee6c90 | ||
|
|
28d3748c06 | ||
|
|
fa47a0b8e5 | ||
|
|
36c593631c | ||
|
|
b92757412d | ||
|
|
6ecda4d706 | ||
|
|
123510db2b | ||
|
|
abb65c632b | ||
|
|
e803bffbbb | ||
|
|
96ee2f9758 | ||
|
|
0a3d2a91a6 | ||
|
|
1e5dfd35cb | ||
|
|
b6b2ca56ca | ||
|
|
6d740093dc | ||
|
|
c884fb4f57 | ||
|
|
57ef011817 | ||
|
|
2c3bcb8f3d | ||
|
|
5a61a64559 | ||
|
|
1c2e594003 | ||
|
|
9bd6587278 | ||
|
|
df53b1a70e | ||
|
|
a6f0193779 | ||
|
|
bab58991fe | ||
|
|
c5d4c8908d | ||
|
|
9ac8bae981 | ||
|
|
3302762a32 | ||
|
|
73cf32edc8 | ||
|
|
85fd019f62 | ||
|
|
9b4d924e48 | ||
|
|
9ad011d93c | ||
|
|
ebd220274b | ||
|
|
7a4559ac96 | ||
|
|
bc9622994e | ||
|
|
5d202c06a6 | ||
|
|
0966c630a7 | ||
|
|
d1f574013d | ||
|
|
c3b8855252 | ||
|
|
a9ff0a3fea | ||
|
|
af50605a3b |
@@ -53,6 +53,8 @@ jobs:
|
||||
name: Rust (${{ matrix.os }} - ${{ matrix.target }})
|
||||
if: github.event_name != 'pull_request'
|
||||
runs-on: ${{ matrix.os }}
|
||||
# Fail fast on a hung test instead of running to GitHub's 6h default.
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
@@ -85,6 +87,8 @@ jobs:
|
||||
if: github.event_name != 'pull_request'
|
||||
runs-on: ubuntu-latest
|
||||
needs: rust
|
||||
# Fail fast on a hung e2e test instead of GitHub's 6h default.
|
||||
timeout-minutes: 30
|
||||
# This fork forbids headless by default (always-headed for stealth), but CI
|
||||
# runners have no display. Opt into the documented display-less escape so
|
||||
# launched Chrome can start; e2e tests exercise functionality, not stealth.
|
||||
@@ -160,7 +164,10 @@ jobs:
|
||||
run: |
|
||||
$env:PATH = "$pwd\bin;$env:PATH"
|
||||
Write-Host "--- Opening page ---"
|
||||
bin/agent-browser-win32-x64.exe open https://example.com
|
||||
# --launch: spawn a standalone browser. Without it, `open` defaults to
|
||||
# auto-connect and looks for an existing Chrome on a debug port — which
|
||||
# a fresh CI runner doesn't have, so it errors "Could not connect".
|
||||
bin/agent-browser-win32-x64.exe --launch open https://example.com
|
||||
if ($LASTEXITCODE -ne 0) { Write-Error "open failed"; exit 1 }
|
||||
Write-Host "--- Taking snapshot ---"
|
||||
$snapshot = bin/agent-browser-win32-x64.exe snapshot
|
||||
@@ -242,17 +249,23 @@ jobs:
|
||||
echo "Symlink correctly points to native binary"
|
||||
shell: bash
|
||||
|
||||
- name: Verify shim points to native binary (Windows)
|
||||
- name: Verify CLI works (and prefers the native shim) (Windows)
|
||||
if: runner.os == 'Windows'
|
||||
run: |
|
||||
$shimPath = "$(npm prefix -g)\agent-browser.cmd"
|
||||
$content = Get-Content $shimPath -Raw
|
||||
echo "Shim path: $shimPath"
|
||||
# The CLI must work. The native-shim rewrite is a best-effort speedup
|
||||
# (npm often creates the .cmd AFTER postinstall runs, so the rewrite
|
||||
# can't happen and the JS wrapper — which spawns the native binary — is
|
||||
# the valid fallback). Require functionality; prefer, but don't require,
|
||||
# the native shim.
|
||||
$ver = agent-browser --version
|
||||
if ($LASTEXITCODE -ne 0) { Write-Error "agent-browser --version failed"; exit 1 }
|
||||
echo "CLI version: $ver"
|
||||
$content = Get-Content "$(npm prefix -g)\agent-browser.cmd" -Raw
|
||||
echo "Shim content:"
|
||||
echo $content
|
||||
if ($content -notmatch "agent-browser-win32-x64\.exe") {
|
||||
echo "ERROR: Shim should point to native .exe, not JS wrapper"
|
||||
exit 1
|
||||
if ($content -match "agent-browser-win32-x64\.exe") {
|
||||
echo "OK: shim points directly to the native binary (zero overhead)"
|
||||
} else {
|
||||
echo "INFO: shim uses the JS wrapper fallback (functional; native-shim optimization not applied)"
|
||||
}
|
||||
echo "Shim correctly points to native binary"
|
||||
shell: pwsh
|
||||
|
||||
@@ -1,11 +1,42 @@
|
||||
# agent-browser-stealth
|
||||
|
||||
**English** · [简体中文](README.zh.md)
|
||||
|
||||

|
||||
|
||||
Stealth fork of [agent-browser](https://github.com/vercel-labs/agent-browser) — connects to your real Chrome, shares your login sessions, and is undetectable by anti-bot systems.
|
||||
|
||||
For basic usage, commands, and API reference, see the [upstream documentation](https://github.com/vercel-labs/agent-browser).
|
||||
|
||||
## Give your AI agent the browser you already live in
|
||||
|
||||
**No fresh Chrome. No re-login. No "are you a robot?" walls.**
|
||||
|
||||
agent-browser-stealth points **any** agent — Claude Code, Cursor, Codex, your own scripts — at the **Chrome you're already signed into everything on**. It clicks in *your* window, so you watch it work and grab the wheel the moment it hits a 2FA prompt or captcha. And because it's literally your real browser (over a one-click extension, native messaging — no debug port), sites read it as 100% human: **[CreepJS scores it 0% bot](#anti-detection).**
|
||||
|
||||
**Why not just use…**
|
||||
|
||||
- **Playwright / Puppeteer / browser-use?** They boot an *empty* browser — so you redo every login, fight every captcha, and still get flagged as automation. We use the session you already have.
|
||||
- **Claude's Chrome extension?** Great, but it only drives Claude. This drives *any* agent or CLI.
|
||||
- **A raw `--remote-debugging-port`** (web-access, etc.)? Chrome 136+ pops **"Allow remote debugging?"** on *every* connect. This never does — one-click Store extension, native messaging.
|
||||
|
||||
<details>
|
||||
<summary><b>Full feature comparison</b> (the receipts)</summary>
|
||||
|
||||
| | [Claude in Chrome](https://www.anthropic.com/claude/chrome) | web-access / raw CDP port | Playwright · Puppeteer · browser-use | **agent-browser-stealth** |
|
||||
|---|:---:|:---:|:---:|:---:|
|
||||
| Works with **any** agent / CLI (not one app) | ❌ Claude only | ✅ | ✅ | ✅ |
|
||||
| Drives your **real, logged-in** Chrome | ✅ | ✅ | ❌ fresh empty profile | ✅ |
|
||||
| **No "Allow remote debugging?" popup** | ✅ | ❌ every connect | — (own browser) | ✅ native messaging |
|
||||
| Real-browser fingerprint (CreepJS ~0%)¹ | ✅ | ✅ | ❌ automation markers / headless | ✅ **verified 0%** |
|
||||
| **No `Runtime.enable` CDP leak** (rebrowser)² | — | ❌ leaks | ❌ leaks | ✅ **off by default** |
|
||||
| Many agents on **one** real Chrome, isolated tab groups³ | ❌ single app | ⚠️ shared tabs, no isolation | ❌ separate browsers | ✅ |
|
||||
| Permissions footprint | 16 incl. `<all_urls>` | full CDP | full control | **7, no `<all_urls>`** |
|
||||
|
||||
<sub>¹ All three real-Chrome tools score ~0% on CreepJS (it's a real browser); we've measured ours. ² rebrowser's `runtimeEnableLeak` — verified clean on our relay path; Claude in Chrome not independently tested (—). ³ web-access can run parallel sub-agents on one browser, but without per-session isolation; each `--session` here gets its own colored, command-isolated tab group. See [Anti-detection](#anti-detection) for the measured numbers.</sub>
|
||||
|
||||
</details>
|
||||
|
||||
## Why this fork?
|
||||
|
||||
<img src="assets/fingerprint.png" alt="real but undetectable fingerprint" width="300" align="right" />
|
||||
@@ -100,12 +131,26 @@ fresh one.
|
||||
|
||||
## Setup: connect to your Chrome
|
||||
|
||||
Attaching uses the Chrome DevTools Protocol, which Chrome only exposes when it is
|
||||
**launched with a remote-debugging port**. This is a startup flag, not a setting
|
||||
— the `chrome://inspect` toggle alone is **not** enough (it only enables target
|
||||
discovery, not the CDP attach).
|
||||
**Recommended — the browser extension (one click, no popups).** Install the
|
||||
[**agent-browser-stealth** extension from the Chrome Web Store](https://chromewebstore.google.com/detail/agent-browser-stealth/knfcmbamhjmaonkfnjhldjedeobeafmk),
|
||||
then register the local bridge once:
|
||||
|
||||
**Recommended — fully quit Chrome, then relaunch with the port:**
|
||||
```bash
|
||||
agent-browser extension install # register the native-messaging host (one-time)
|
||||
agent-browser open https://x.com/home
|
||||
```
|
||||
|
||||
`agent-browser open` then drives your real, logged-in Chrome over **native
|
||||
messaging** — no debug port, no token, and **no "Allow remote debugging?" dialog,
|
||||
ever**. The extension auto-updates and survives Chrome restarts, so it stays
|
||||
connected with zero per-use confirmation (ideal for unattended/agent use).
|
||||
|
||||
<details>
|
||||
<summary>Alternative — raw remote-debugging port (pops a consent dialog)</summary>
|
||||
|
||||
Without the extension, agent-browser attaches over the Chrome DevTools Protocol,
|
||||
which Chrome only exposes when **launched with a remote-debugging port** (a
|
||||
startup flag — the `chrome://inspect` toggle alone is not enough):
|
||||
|
||||
```bash
|
||||
# macOS
|
||||
@@ -115,9 +160,10 @@ google-chrome --remote-debugging-port=9222
|
||||
# Windows: add --remote-debugging-port=9222 to your Chrome shortcut's target
|
||||
```
|
||||
|
||||
Then run `agent-browser open <url>` — it auto-discovers the port and attaches.
|
||||
On first attach, **Chrome 136+ shows an "Allow remote debugging?" dialog — click
|
||||
Allow once** (it persists for that Chrome session).
|
||||
Then `agent-browser open <url>` auto-discovers the port. On first attach,
|
||||
**Chrome 136+ shows an "Allow remote debugging?" dialog** — click Allow once (it
|
||||
persists for that Chrome session). The extension above avoids this entirely.
|
||||
</details>
|
||||
|
||||
**No setup / don't want to touch your real Chrome?** Use
|
||||
`agent-browser --launch open <url>` to spawn a fresh isolated stealth browser
|
||||
@@ -179,7 +225,26 @@ When connected to your real Chrome, we inject **zero** JavaScript patches. Your
|
||||
|
||||
`0% stealth` on CreepJS is the key number: because the connect path patches **nothing**, there is no override for a lie-detector to catch. (Dashboards that read `navigator.languages` order or IP geolocation may show a soft "navigator"/"location" flag — that tracks *your real Chrome's* language list and network, not an automation tell.)
|
||||
|
||||
When using `--launch` mode (standalone browser), a full suite of stealth patches is applied instead, and it still passes the suite above.
|
||||
When using `--launch` mode (standalone browser), a full suite of stealth patches is applied instead, and it passes the suite above — with one caveat: CreepJS reports **~20% stealth** because the srcdoc-iframe `contentWindow` patch trips its `hasIframeProxy` probe (the proxy that hides automation is itself a tell). Everything else is clean (`0% headless`, sannysoft/browserscan green, Cloudflare passed). Set **`AGENT_BROWSER_DISABLE_IFRAME_PROXY=1`** to drop that patch for a clean **0% stealth** (trades the niche srcdoc-iframe masking). The **extension-connect path** (your real Chrome) injects zero JS and is unaffected — it's the genuine 0% path.
|
||||
|
||||
### Human-like input (behavioural stealth)
|
||||
|
||||
Fingerprint stealth isn't the whole story — the strongest anti-bot vendors (Akamai, PerimeterX, DataDome) also score *behaviour*. A click that teleports the cursor to an element's exact centre with no approach path and zero press delay is a tell, **even though our CDP events are `isTrusted`**.
|
||||
|
||||
With humanize on, the cursor moves like a hand: clicks follow a curved, decelerating Bézier path and land on a jittered point *inside* the element (never the dead centre); typing uses variable inter-keystroke timing; scrolling eases in segments; drags follow a curve. It's **adaptive** — every navigation is probed for known anti-bot vendors (cookies / scripts / globals) and a guarded page auto-escalates to full human motion, while ordinary sites stay instant (zero overhead).
|
||||
|
||||
What the page's own `mousemove` stream sees (this *is* what a behavioural detector analyses):
|
||||
|
||||
| | trajectory |
|
||||
|---|---|
|
||||
| **off** (default) | straight lines · dead-centre · instant |
|
||||
| **human** | curved trails · slow-in/slow-out · off-centre landings |
|
||||
|
||||
Control with `--humanize off\|fast\|human` or `AGENT_BROWSER_HUMANIZE`. Default `off`; the adaptive detector escalates per page.
|
||||
|
||||
### Silent operation
|
||||
|
||||
Driving your real Chrome should never interrupt your work. The agent operates **entirely in the background**: new tabs open un-focused (in their own colored per-session tab group), the agent **never force-fronts a tab**, and `Emulation.setFocusEmulationEnabled` keeps each agent tab rendering and reporting `document.hasFocus()` / `visibilityState: 'visible'`. So screenshots still work, pages aren't render-throttled, and "the tab was hidden the whole session" never becomes its own bot tell. You keep working in your active tab; the agent works alongside you, silently. (Surfacing a tab stays available as an explicit command.)
|
||||
|
||||
### Verify it yourself
|
||||
|
||||
@@ -198,6 +263,7 @@ We deliberately **don't ship our own bot detector** — the strongest, most hone
|
||||
| Variable | Default | Effect |
|
||||
|---|---|---|
|
||||
| `AGENT_BROWSER_CAPTURE_CONSOLE` | off | Enable `Runtime` domain so `console` / `errors` capture page output. Off keeps the stealthiest profile. |
|
||||
| `AGENT_BROWSER_HUMANIZE` | off | Human-like input motion: `off` (instant), `fast` (light eased trajectory), `human` (full curved trajectory + landing jitter + typing cadence + eased scroll/drag). Also `--humanize`. Default `off`; the adaptive detector auto-escalates pages guarded by Akamai/PerimeterX/DataDome to `human`. |
|
||||
| `AGENT_BROWSER_TIMEZONE` | unset | `--launch` only. An IANA id (e.g. `Asia/Tokyo`) sets the timezone natively (Intl + Date follow, no JS lie) to match a proxy; `auto` derives one from the locale. |
|
||||
| `AGENT_BROWSER_BLOCK_WEBRTC` | auto | `--launch` only. Auto-forces WebRTC through the proxy when one is set (no real-IP leak). `1` hides the local IP without a proxy; `0` opts out. |
|
||||
| `AGENT_BROWSER_HIDE_CANVAS` | off | `--launch` only. Adds session-stable canvas/audio fingerprint noise. Off by default (noise is itself a "lie"). |
|
||||
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
# agent-browser-stealth
|
||||
|
||||
[English](README.md) · **简体中文**
|
||||
|
||||

|
||||
|
||||
[agent-browser](https://github.com/vercel-labs/agent-browser) 的隐身分支 —— 直接连接**你自己**正在用的、已登录的 Chrome,复用你的登录态,对反爬/反自动化系统**完全不可检测**。
|
||||
|
||||
基础用法、命令与 API 参考见[上游文档](https://github.com/vercel-labs/agent-browser)。
|
||||
|
||||
## 把你**已经登录好**的浏览器,交给你的 AI agent
|
||||
|
||||
**不用开新 Chrome。不用重新登录。不用跟"你是不是机器人"较劲。**
|
||||
|
||||
agent-browser-stealth 让**任意** agent(Claude Code、Cursor、Codex、你自己的脚本)直接操作你**已经登录了所有网站**的那个 Chrome。它在**你的窗口里**点击,你看着它干活,撞到 2FA / 验证码的瞬间你接管一下,它接着跑。因为它**就是你的真实浏览器**(一键装的扩展、原生消息、无调试端口),网站眼里它 100% 是人:**[CreepJS 实测 0% 机器人](#反检测)。**
|
||||
|
||||
**为什么不用……**
|
||||
|
||||
- **Playwright / Puppeteer / browser-use?** 它们开的是**空**浏览器 —— 每个登录你重做、每个验证码你硬扛、最后还被标成自动化。我们直接用你**现成的**会话。
|
||||
- **Claude 的 Chrome 插件?** 很好,但**只能给 Claude 用**。我们给**任意** agent / CLI 用。
|
||||
- **裸 `--remote-debugging-port`**(web-access 等)? Chrome 136+ **每次连都弹** "Allow remote debugging?"。我们**永不弹** —— 商店一键装,原生消息。
|
||||
|
||||
<details>
|
||||
<summary><b>完整对比矩阵</b>(要细节的看这里)</summary>
|
||||
|
||||
| | [Claude in Chrome](https://www.anthropic.com/claude/chrome) | web-access / 裸 CDP 端口 | Playwright · Puppeteer · browser-use | **agent-browser-stealth** |
|
||||
|---|:---:|:---:|:---:|:---:|
|
||||
| **任意** agent / CLI 都能用(不绑单一 app) | ❌ 仅 Claude | ✅ | ✅ | ✅ |
|
||||
| 驱动你**真实、已登录**的 Chrome | ✅ | ✅ | ❌ 全新空 profile | ✅ |
|
||||
| **不弹 "Allow remote debugging?"** | ✅ | ❌ 每次连都弹 | —(自带浏览器) | ✅ 原生消息 |
|
||||
| 真实浏览器指纹(CreepJS ~0%)¹ | ✅ | ✅ | ❌ 自动化特征 / headless | ✅ **已实测 0%** |
|
||||
| **无 `Runtime.enable` CDP 泄漏**(rebrowser)² | — | ❌ 泄漏 | ❌ 泄漏 | ✅ **默认关闭** |
|
||||
| 多 agent 共用**同一个**真实 Chrome、标签组隔离³ | ❌ 单 app | ⚠️ 共享 tab、无隔离 | ❌ 各开各的浏览器 | ✅ |
|
||||
| 权限面 | 16 个,含 `<all_urls>` | 完整 CDP | 完全控制 | **7 个,无 `<all_urls>`** |
|
||||
|
||||
<sub>¹ 三家"真实 Chrome"工具在 CreepJS 上都 ~0%(毕竟是真浏览器),我们的是实测过的。² rebrowser `runtimeEnableLeak` —— 我们的中继路径实测无泄漏;Claude in Chrome 未独立测试(—)。³ web-access 也能跑并行子 agent,但无每会话隔离;本工具每个 `--session` 拿到自己彩色、命令隔离的标签组。实测数字见 [反检测](#反检测)。</sub>
|
||||
|
||||
</details>
|
||||
|
||||
## 为什么要 fork
|
||||
|
||||
<img src="assets/fingerprint.png" alt="真实但不可检测的指纹" width="300" align="right" />
|
||||
|
||||
**agent-browser**(上游)启动的是空 profile 的全新浏览器:你得重新登录,网站也能看出是自动化。
|
||||
|
||||
**agent-browser-stealth** 连接你**现有**的 Chrome —— cookies、会话、浏览器指纹全是真的,因为它**就是**你的真实浏览器。
|
||||
|
||||
| | agent-browser | agent-browser-stealth |
|
||||
|---|---|---|
|
||||
| 浏览器 | 启动新 Chrome | 连接你的 Chrome |
|
||||
| 登录态 | 空,要重新登 | 你现有的会话 |
|
||||
| 指纹 | 带自动化标记 | 你的真实指纹 |
|
||||
| 协作 | 独立窗口 | 同一窗口,随时接管 |
|
||||
| 验证码 | Agent 卡住 | 你点一下,Agent 继续 |
|
||||
|
||||
## 工作原理
|
||||
|
||||

|
||||
|
||||
你的 **agent-browser CLI** 通过 Chrome **原生消息(native messaging)** 和一个小**浏览器扩展**通信 —— 这是本机进程间通道,**无网络端口、无 token、无远程服务器**。扩展用 `chrome.debugger` 驱动你指定的标签页(在你**已登录**的 Chrome 里),再把结果交还给 CLI。全程都在你本机。
|
||||
|
||||

|
||||
|
||||
每个 `--session` 拿到**自己的彩色标签组**,多个 agent 共用同一个真实浏览器、互不干扰,也不动你自己的标签页。
|
||||
|
||||
## 安装
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/leeguooooo/agent-browser-stealth/main/install.sh | sh
|
||||
```
|
||||
|
||||
从最新的 [GitHub Release](https://github.com/leeguooooo/agent-browser-stealth/releases) 下载对应平台的预编译二进制,安装 `agent-browser`(以及 `abs` 别名)。无需 npm,无需 token。
|
||||
|
||||
### 安装 AI agent skills
|
||||
|
||||
```bash
|
||||
npx skills add leeguooooo/agent-browser-stealth
|
||||
```
|
||||
|
||||
把 `skills/agent-browser` 拉进当前项目,让你的 AI agent 拿到正确的用法和预授权的 bash 权限。
|
||||
|
||||
## 连接你的 Chrome
|
||||
|
||||
**推荐 —— 浏览器扩展(一键,无弹窗)。** 从 Chrome 应用商店安装 [**agent-browser-stealth** 扩展](https://chromewebstore.google.com/detail/agent-browser-stealth/knfcmbamhjmaonkfnjhldjedeobeafmk),再注册一次本地桥:
|
||||
|
||||
```bash
|
||||
agent-browser extension install # 注册原生消息 host(一次性)
|
||||
agent-browser open https://x.com/home
|
||||
```
|
||||
|
||||
之后 `agent-browser open` 就通过**原生消息**驱动你真实、已登录的 Chrome —— 无调试端口、无 token、**永远不弹 "Allow remote debugging?"**。扩展自动更新、重启不掉,零确认(适合无人值守 / agent 场景)。
|
||||
|
||||
<details>
|
||||
<summary>备选 —— 裸 remote-debugging 端口(会弹同意框)</summary>
|
||||
|
||||
不装扩展时,agent-browser 退回用 CDP 连接,而 Chrome 只在带 remote-debugging 端口启动时才暴露它:
|
||||
|
||||
```bash
|
||||
# macOS
|
||||
open -a "Google Chrome" --args --remote-debugging-port=9222
|
||||
# Linux
|
||||
google-chrome --remote-debugging-port=9222
|
||||
# Windows: 给 Chrome 快捷方式 target 加 --remote-debugging-port=9222
|
||||
```
|
||||
|
||||
然后 `agent-browser open <url>` 自动发现端口。首次连接 **Chrome 136+ 会弹 "Allow remote debugging?"** —— 点一次 Allow(该 Chrome 会话内持续有效)。上面的扩展则完全避开这个框。
|
||||
</details>
|
||||
|
||||
## 用法
|
||||
|
||||
```bash
|
||||
# 连接你的 Chrome 并导航
|
||||
agent-browser open https://example.com
|
||||
|
||||
# 一切都在你已登录的浏览器里进行
|
||||
agent-browser click "Post"
|
||||
agent-browser fill "Title" "Hello World"
|
||||
agent-browser screenshot ./page.png
|
||||
```
|
||||
|
||||
Agent 在你的 Chrome 里操作 —— 你能实时看到开标签、加载、点击。任意时刻都能接管(比如手动过验证码),然后让 agent 继续。
|
||||
|
||||
### 独立模式(`--launch`)
|
||||
|
||||
```bash
|
||||
# 临时:全新空 profile —— 无 cookie 无登录(适合 CI / 测试)
|
||||
agent-browser --launch open https://example.com
|
||||
|
||||
# 保留登录:用你真实的 Chrome profile 启动
|
||||
agent-browser --launch --profile auto open https://x.com/home
|
||||
```
|
||||
|
||||
## 反检测
|
||||
|
||||
连接你真实 Chrome 时,我们**零** JS 注入 —— 浏览器指纹完全是真的。指导原则是 **native CDP/Chrome 覆盖优先于 JS 谎言**:被重定义的 getter 本身可被检测,原生覆盖则不会。
|
||||
|
||||
- `navigator.webdriver = false` 走 `Emulation.setAutomationOverride`(原生,CreepJS 类说谎检测查不出)。
|
||||
- **`Runtime.enable` 默认关闭** —— 活着的 `Runtime` 域是可被检测的 CDP 信号(patchright/rebrowser 的 "runtime leak"),即便连的是你真实 Chrome。只在你主动开启 console/错误捕获时才启用。
|
||||
|
||||
**实测结果(连接真实 Chrome,中继路径):**
|
||||
|
||||
| 检测站 | 结果 |
|
||||
|---|---|
|
||||
| [CreepJS](https://abrahamjuliot.github.io/creepjs/) | **0% stealth · 0% headless**(零 override 痕迹) |
|
||||
| [bot.incolumitas.com](https://bot.incolumitas.com/) | 全部 OK(overflowTest / overrideTest / puppeteerExtraStealth / worker 一致性) |
|
||||
| [rebrowser-bot-detector](https://bot-detector.rebrowser.net/) | `runtimeEnableLeak` 🟢 · `pwInitScripts` 🟢 |
|
||||
| [bot.sannysoft.com](https://bot.sannysoft.com) | 全绿 |
|
||||
|
||||
`--launch` 独立模式下会改用一整套隐身补丁,同样过上述检测。
|
||||
|
||||
### 类人输入(行为隐身)
|
||||
|
||||
指纹隐身只是一半——最强的反爬厂商(Akamai、PerimeterX、DataDome)还会给**行为**打分。点击时光标瞬移到元素正中心、没有接近轨迹、按下即抬起,这本身就是破绽,**哪怕我们的 CDP 事件是 `isTrusted`**。
|
||||
|
||||
开启 humanize 后,光标像手在动:点击走带减速的贝塞尔曲线、落在元素内**偏离正中心**的抖动点;打字用变速的击键间隔;滚动分段缓动;拖拽走曲线。而且**自适应**——每次导航探测页面是否有已知反爬厂商(cookie/脚本/全局变量),命中就自动升到全套类人动作,普通站点保持瞬时(零开销)。
|
||||
|
||||
页面自己的 `mousemove` 流看到的(行为检测器分析的正是这个):
|
||||
|
||||
| | 轨迹 |
|
||||
|---|---|
|
||||
| **off**(默认) | 直线 · 死磕正中心 · 瞬时 |
|
||||
| **human** | 曲线 · 先慢后快再慢 · 落点偏移 |
|
||||
|
||||
用 `--humanize off\|fast\|human` 或 `AGENT_BROWSER_HUMANIZE` 控制。默认 `off`,自适应检测器按页面自动升档。
|
||||
|
||||
### 静默操作
|
||||
|
||||
操作你的真实 Chrome 不该打断你的工作。agent **全程在后台操作**:新标签后台打开(在自己的彩色会话标签组里),**从不强制把标签拽到前台**,并用 `Emulation.setFocusEmulationEnabled` 让每个 agent 标签照常渲染、`document.hasFocus()` / `visibilityState` 仍报 `visible`。于是截图正常、页面不被降频,"标签全程隐藏"也不会变成新的机器人信号。你在自己的标签里照常工作,agent 在旁边默默干活。(想置顶某个标签仍可显式调用命令。)
|
||||
|
||||
## 与上游的差异
|
||||
|
||||
基于 [agent-browser v0.27.0](https://github.com/vercel-labs/agent-browser):
|
||||
|
||||
- **默认 auto-connect** —— `agent-browser open` 连你的 Chrome 而非启新的
|
||||
- **CDP 原生隐身** —— `Emulation.setAutomationOverride` 而非 JS 补丁
|
||||
- **双隐身模式** —— 真实 Chrome 零补丁,`--launch` 全补丁
|
||||
- **`--launch` / `--new`** —— 显式启动独立浏览器
|
||||
- **CI 自动检测** —— 设了 `CI` 环境变量时走独立模式
|
||||
|
||||
所有上游功能(命令、快照、截图、录制、标签、会话等)保持一致。
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0(与上游一致)
|
||||
Generated
+1
-1
@@ -45,7 +45,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "agent-browser-stealth"
|
||||
version = "0.27.0-fork.33"
|
||||
version = "0.27.0-fork.51"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"async-trait",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "agent-browser-stealth"
|
||||
version = "0.27.0-fork.33"
|
||||
version = "0.27.0-fork.51"
|
||||
edition = "2021"
|
||||
description = "Fast browser automation CLI for AI agents"
|
||||
license = "Apache-2.0"
|
||||
|
||||
+272
-26
@@ -101,7 +101,62 @@ pub fn parse_curl_cookies(raw: &str) -> Result<Vec<Value>, String> {
|
||||
.get("value")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| format!("cookies[{}] missing string value", i))?;
|
||||
out.push(json!({ "name": name, "value": value }));
|
||||
let mut cookie = json!({ "name": name, "value": value });
|
||||
let obj = cookie.as_object_mut().unwrap();
|
||||
// Preserve any CDP Network.setCookie attributes present on the
|
||||
// source object so a full auth state round-trips: httpOnly session
|
||||
// tokens, per-domain cookies (a single export spans .chatgpt.com,
|
||||
// .openai.com, ...), and secure/sameSite/expiry. A bare
|
||||
// {name,value} export is unchanged. Common aliases from DevTools /
|
||||
// EditThisCookie / extension exports are accepted.
|
||||
if let Some(v) = c.get("url").and_then(|v| v.as_str()) {
|
||||
obj.insert("url".into(), json!(v));
|
||||
}
|
||||
if let Some(v) = c.get("domain").and_then(|v| v.as_str()) {
|
||||
obj.insert("domain".into(), json!(v));
|
||||
}
|
||||
if let Some(v) = c.get("path").and_then(|v| v.as_str()) {
|
||||
obj.insert("path".into(), json!(v));
|
||||
}
|
||||
if let Some(v) = c.get("secure").and_then(|v| v.as_bool()) {
|
||||
obj.insert("secure".into(), json!(v));
|
||||
}
|
||||
if let Some(v) = c
|
||||
.get("httpOnly")
|
||||
.or_else(|| c.get("httponly"))
|
||||
.or_else(|| c.get("http_only"))
|
||||
.and_then(|v| v.as_bool())
|
||||
{
|
||||
obj.insert("httpOnly".into(), json!(v));
|
||||
}
|
||||
if let Some(v) = c
|
||||
.get("sameSite")
|
||||
.or_else(|| c.get("samesite"))
|
||||
.or_else(|| c.get("same_site"))
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
let norm = match v.to_lowercase().as_str() {
|
||||
"strict" => "Strict",
|
||||
"lax" => "Lax",
|
||||
"none" | "no_restriction" => "None",
|
||||
_ => "",
|
||||
};
|
||||
if !norm.is_empty() {
|
||||
obj.insert("sameSite".into(), json!(norm));
|
||||
}
|
||||
}
|
||||
// CDP `expires` is seconds since the Unix epoch (f64). Accept
|
||||
// `expires` or EditThisCookie's `expirationDate`.
|
||||
if let Some(v) = c
|
||||
.get("expires")
|
||||
.or_else(|| c.get("expirationDate"))
|
||||
.and_then(|v| v.as_f64())
|
||||
{
|
||||
if v > 0.0 {
|
||||
obj.insert("expires".into(), json!(v));
|
||||
}
|
||||
}
|
||||
out.push(cookie);
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
@@ -320,12 +375,25 @@ fn parse_command_inner(args: &[String], flags: &Flags) -> Result<Value, ParseErr
|
||||
// === Core Actions ===
|
||||
"click" => {
|
||||
let new_tab = rest.contains(&"--new-tab");
|
||||
// Coordinate click as a first-class form (issue #8.4): when the only
|
||||
// handle is a pixel position, no element/selector is needed.
|
||||
// click <x> <y> e.g. click 449 320
|
||||
// click <x>,<y> e.g. click 449,320
|
||||
// click --coords <x>,<y> | --coords <x> <y>
|
||||
let coord_args: Vec<&str> = rest
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|a| *a != "--new-tab" && *a != "--coords")
|
||||
.collect();
|
||||
if let Some((x, y)) = parse_coords(&coord_args) {
|
||||
return Ok(json!({ "id": id, "action": "click", "x": x, "y": y }));
|
||||
}
|
||||
let sel = rest
|
||||
.iter()
|
||||
.find(|arg| **arg != "--new-tab")
|
||||
.ok_or_else(|| ParseError::MissingArguments {
|
||||
context: "click".to_string(),
|
||||
usage: "click <selector> [--new-tab]",
|
||||
usage: "click <selector> | click <x> <y> | click --coords <x>,<y> [--new-tab]",
|
||||
})?;
|
||||
if new_tab {
|
||||
Ok(json!({ "id": id, "action": "click", "selector": sel, "newTab": true }))
|
||||
@@ -348,12 +416,48 @@ fn parse_command_inner(args: &[String], flags: &Flags) -> Result<Value, ParseErr
|
||||
Ok(json!({ "id": id, "action": "fill", "selector": sel, "value": rest[1..].join(" ") }))
|
||||
}
|
||||
"type" => {
|
||||
// `type --focused <text>` types into whatever element currently has
|
||||
// focus (no selector) — for custom widgets that move focus to a hidden
|
||||
// input after you open them.
|
||||
if rest.first() == Some(&"--focused") {
|
||||
return Ok(json!({
|
||||
"id": id, "action": "type", "focused": true,
|
||||
"text": rest[1..].join(" "),
|
||||
}));
|
||||
}
|
||||
let sel = rest.first().ok_or_else(|| ParseError::MissingArguments {
|
||||
context: "type".to_string(),
|
||||
usage: "type <selector> <text>",
|
||||
usage: "type <selector> <text> (or: type --focused <text>)",
|
||||
})?;
|
||||
Ok(json!({ "id": id, "action": "type", "selector": sel, "text": rest[1..].join(" ") }))
|
||||
}
|
||||
"pick" => {
|
||||
// pick <selector|@ref> --option "<text>" — atomic combobox select:
|
||||
// open the control, wait for options (incl. portal menus), match by
|
||||
// text, fire the right event sequence, verify. Covers native <select>,
|
||||
// ARIA combobox/listbox, and react-select.
|
||||
let sel = rest.first().ok_or_else(|| ParseError::MissingArguments {
|
||||
context: "pick".to_string(),
|
||||
usage: "pick <selector> --option \"<text>\"",
|
||||
})?;
|
||||
let opt_pos = rest.iter().position(|a| *a == "--option" || *a == "-o");
|
||||
let option = match opt_pos {
|
||||
Some(p) => rest[p + 1..].join(" "),
|
||||
None => {
|
||||
return Err(ParseError::MissingArguments {
|
||||
context: "pick".to_string(),
|
||||
usage: "pick <selector> --option \"<text>\"",
|
||||
})
|
||||
}
|
||||
};
|
||||
if option.is_empty() {
|
||||
return Err(ParseError::MissingArguments {
|
||||
context: "pick".to_string(),
|
||||
usage: "pick <selector> --option \"<text>\"",
|
||||
});
|
||||
}
|
||||
Ok(json!({ "id": id, "action": "pick", "selector": sel, "option": option }))
|
||||
}
|
||||
"hover" => {
|
||||
let sel = rest.first().ok_or_else(|| ParseError::MissingArguments {
|
||||
context: "hover".to_string(),
|
||||
@@ -786,17 +890,31 @@ fn parse_command_inner(args: &[String], flags: &Flags) -> Result<Value, ParseErr
|
||||
|
||||
// === Eval ===
|
||||
"eval" => {
|
||||
// Check for flags: -b/--base64 or --stdin
|
||||
let (is_base64, is_stdin, script_parts): (bool, bool, &[&str]) =
|
||||
// Check for flags: -b/--base64, --stdin, or --file <path>
|
||||
let (is_base64, is_stdin, is_file, script_parts): (bool, bool, bool, &[&str]) =
|
||||
if rest.first() == Some(&"-b") || rest.first() == Some(&"--base64") {
|
||||
(true, false, &rest[1..])
|
||||
(true, false, false, &rest[1..])
|
||||
} else if rest.first() == Some(&"--stdin") {
|
||||
(false, true, &rest[1..])
|
||||
(false, true, false, &rest[1..])
|
||||
} else if rest.first() == Some(&"--file") {
|
||||
(false, false, true, &rest[1..])
|
||||
} else {
|
||||
(false, false, rest.as_slice())
|
||||
(false, false, false, rest.as_slice())
|
||||
};
|
||||
|
||||
let script = if is_stdin {
|
||||
let script = if is_file {
|
||||
// Read the script from a file. Avoids shell-mangling of inline JS
|
||||
// (non-ASCII identifiers/strings, quotes, large scripts) — the file
|
||||
// is read as UTF-8 and sent verbatim.
|
||||
let path = script_parts.first().ok_or(ParseError::InvalidValue {
|
||||
message: "eval --file requires a path".to_string(),
|
||||
usage: "eval --file <path>",
|
||||
})?;
|
||||
std::fs::read_to_string(path).map_err(|e| ParseError::InvalidValue {
|
||||
message: format!("eval --file: cannot read {path}: {e}"),
|
||||
usage: "eval --file <path>",
|
||||
})?
|
||||
} else if is_stdin {
|
||||
// Read script from stdin
|
||||
let stdin = io::stdin();
|
||||
let lines: Vec<String> = stdin
|
||||
@@ -826,6 +944,15 @@ fn parse_command_inner(args: &[String], flags: &Flags) -> Result<Value, ParseErr
|
||||
Ok(json!({ "id": id, "action": "evaluate", "script": script }))
|
||||
}
|
||||
|
||||
// === Stealth self-check ===
|
||||
"stealth" => {
|
||||
// `stealth [status]` — local stealth self-check: mode, live probes
|
||||
// (navigator.webdriver, window.chrome, plugins, UA), and the list of
|
||||
// active overrides. --json for a stable machine-readable shape.
|
||||
// (Distinct from `doctor`, which checks install/env/Chrome health.)
|
||||
Ok(json!({ "id": id, "action": "stealth_status" }))
|
||||
}
|
||||
|
||||
// === Close ===
|
||||
"close" | "quit" | "exit" => Ok(json!({ "id": id, "action": "close" })),
|
||||
|
||||
@@ -1094,6 +1221,15 @@ fn parse_command_inner(args: &[String], flags: &Flags) -> Result<Value, ParseErr
|
||||
parse_get(&get_args, &id)
|
||||
}
|
||||
|
||||
// Hyphen/underscore aliases for `get text <selector>` — agents naturally
|
||||
// guess `get-text` / `get_text` (issue #8.4).
|
||||
"get-text" | "get_text" => {
|
||||
let mut get_args: Vec<&str> = Vec::with_capacity(rest.len() + 1);
|
||||
get_args.push("text");
|
||||
get_args.extend_from_slice(&rest);
|
||||
parse_get(&get_args, &id)
|
||||
}
|
||||
|
||||
// === Is (state checks) ===
|
||||
"is" => parse_is(&rest, &id),
|
||||
|
||||
@@ -1275,7 +1411,9 @@ fn parse_command_inner(args: &[String], flags: &Flags) -> Result<Value, ParseErr
|
||||
}
|
||||
|
||||
// === Tabs ===
|
||||
"tab" => {
|
||||
// `tabs` (plural) is a natural guess for the `tab` subcommand tree —
|
||||
// alias it so `tabs` / `tabs list` / `tabs new` all work (issue #8.4).
|
||||
"tab" | "tabs" => {
|
||||
match rest.first().copied() {
|
||||
Some("new") => {
|
||||
// Accepted forms:
|
||||
@@ -2199,19 +2337,6 @@ fn parse_is(rest: &[&str], id: &str) -> Result<Value, ParseError> {
|
||||
}
|
||||
|
||||
fn parse_find(rest: &[&str], id: &str) -> Result<Value, ParseError> {
|
||||
const VALID: &[&str] = &[
|
||||
"role",
|
||||
"text",
|
||||
"label",
|
||||
"placeholder",
|
||||
"alt",
|
||||
"title",
|
||||
"testid",
|
||||
"first",
|
||||
"last",
|
||||
"nth",
|
||||
];
|
||||
|
||||
let locator = rest.first().ok_or_else(|| ParseError::MissingArguments {
|
||||
context: "find".to_string(),
|
||||
usage: "find <locator> <value> [action] [text]",
|
||||
@@ -2381,13 +2506,37 @@ fn parse_find(rest: &[&str], id: &str) -> Result<Value, ParseError> {
|
||||
}
|
||||
Ok(cmd)
|
||||
}
|
||||
_ => Err(ParseError::UnknownSubcommand {
|
||||
subcommand: locator.to_string(),
|
||||
valid_options: VALID,
|
||||
_ => Err(ParseError::InvalidValue {
|
||||
// The user passed a value where a locator keyword was expected — the
|
||||
// classic `find "I'm not a robot" click` mistake (issue #8.4). Lead
|
||||
// with the corrected command using their own value, then the menu.
|
||||
message: format!(
|
||||
"`{loc}` is not a find locator. To match by visible text, name the locator:\n \
|
||||
agent-browser find text \"{loc}\" click\n\n\
|
||||
Locators: role, text, label, placeholder, alt, title, testid, first, last, nth\n\
|
||||
Examples:\n \
|
||||
agent-browser find text \"Sign in\" click\n \
|
||||
agent-browser find role button --name \"Submit\" click\n \
|
||||
agent-browser find label \"Email\" fill you@example.com",
|
||||
loc = locator,
|
||||
),
|
||||
usage: "find <locator> <value> [action] [text]",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a coordinate pair from `["449","320"]`, `["449,320"]`, or `["449, 320"]`.
|
||||
/// Returns None if the args aren't a clean numeric pair (so callers fall back to
|
||||
/// treating the argument as a selector). Used by first-class coordinate `click`.
|
||||
fn parse_coords(args: &[&str]) -> Option<(f64, f64)> {
|
||||
let (a, b) = match args {
|
||||
[one] => one.split_once(',')?,
|
||||
[a, b] => (*a, *b),
|
||||
_ => return None,
|
||||
};
|
||||
Some((a.trim().parse().ok()?, b.trim().parse().ok()?))
|
||||
}
|
||||
|
||||
fn parse_mouse(rest: &[&str], id: &str) -> Result<Value, ParseError> {
|
||||
const VALID: &[&str] = &["move", "down", "up", "wheel"];
|
||||
|
||||
@@ -2859,6 +3008,27 @@ mod tests {
|
||||
assert_eq!(cmd["action"], "cookies_clear");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_curl_cookies_json_preserves_attributes() {
|
||||
// A full cookie export (httpOnly session token, per-domain, secure,
|
||||
// sameSite, expiry) must round-trip — not get flattened to name/value.
|
||||
let input = r#"[
|
||||
{"name":"__Secure-next-auth.session-token","value":"eyJ.tok","domain":".chatgpt.com","path":"/","secure":true,"httpOnly":true,"sameSite":"Lax","expires":1893456000},
|
||||
{"name":"cf_clearance","value":"abc","domain":".openai.com","path":"/","secure":true,"http_only":true,"same_site":"no_restriction"}
|
||||
]"#;
|
||||
let out = parse_curl_cookies(input).unwrap();
|
||||
assert_eq!(out.len(), 2);
|
||||
assert_eq!(out[0]["domain"], ".chatgpt.com");
|
||||
assert_eq!(out[0]["secure"], true);
|
||||
assert_eq!(out[0]["httpOnly"], true);
|
||||
assert_eq!(out[0]["sameSite"], "Lax");
|
||||
assert_eq!(out[0]["expires"], 1893456000.0);
|
||||
// alias keys (http_only, same_site=no_restriction) normalize to CDP shape
|
||||
assert_eq!(out[1]["domain"], ".openai.com");
|
||||
assert_eq!(out[1]["httpOnly"], true);
|
||||
assert_eq!(out[1]["sameSite"], "None");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_curl_cookies_json_array() {
|
||||
let input = r#"[{"name":"a","value":"1"},{"name":"b","value":"2"}]"#;
|
||||
@@ -2866,6 +3036,9 @@ mod tests {
|
||||
assert_eq!(out.len(), 2);
|
||||
assert_eq!(out[0]["name"], "a");
|
||||
assert_eq!(out[0]["value"], "1");
|
||||
// bare {name,value} stays minimal — no spurious attribute keys
|
||||
assert!(out[0].get("domain").is_none());
|
||||
assert!(out[0].get("secure").is_none());
|
||||
assert_eq!(out[1]["name"], "b");
|
||||
assert_eq!(out[1]["value"], "2");
|
||||
}
|
||||
@@ -3412,6 +3585,79 @@ mod tests {
|
||||
assert_eq!(cmd["action"], "reload");
|
||||
}
|
||||
|
||||
// === issue #8.4: CLI ergonomics ===
|
||||
|
||||
#[test]
|
||||
fn test_click_coords_two_args() {
|
||||
let cmd = parse_command(&args("click 449 320"), &default_flags()).unwrap();
|
||||
assert_eq!(cmd["action"], "click");
|
||||
assert_eq!(cmd["x"], 449.0);
|
||||
assert_eq!(cmd["y"], 320.0);
|
||||
assert!(cmd.get("selector").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_click_coords_comma() {
|
||||
let cmd = parse_command(&args("click 449,320"), &default_flags()).unwrap();
|
||||
assert_eq!(cmd["x"], 449.0);
|
||||
assert_eq!(cmd["y"], 320.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_click_coords_flag() {
|
||||
let cmd = parse_command(&args("click --coords 449,320"), &default_flags()).unwrap();
|
||||
assert_eq!(cmd["x"], 449.0);
|
||||
assert_eq!(cmd["y"], 320.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_click_selector_not_coords() {
|
||||
let cmd = parse_command(&args("click button.submit"), &default_flags()).unwrap();
|
||||
assert_eq!(cmd["action"], "click");
|
||||
assert_eq!(cmd["selector"], "button.submit");
|
||||
assert!(cmd.get("x").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tabs_alias_lists() {
|
||||
assert_eq!(
|
||||
parse_command(&args("tabs"), &default_flags()).unwrap()["action"],
|
||||
"tab_list"
|
||||
);
|
||||
assert_eq!(
|
||||
parse_command(&args("tabs list"), &default_flags()).unwrap()["action"],
|
||||
"tab_list"
|
||||
);
|
||||
assert_eq!(
|
||||
parse_command(&args("tabs new"), &default_flags()).unwrap()["action"],
|
||||
"tab_new"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_text_hyphen_and_underscore_aliases() {
|
||||
for verb in ["get-text", "get_text"] {
|
||||
let cmd = parse_command(&args(&format!("{verb} .price")), &default_flags()).unwrap();
|
||||
assert_eq!(cmd["action"], "gettext", "{verb}");
|
||||
assert_eq!(cmd["selector"], ".price", "{verb}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_find_bare_value_suggests_text_locator() {
|
||||
// `find "I'm not a robot" click` — value where a locator keyword was
|
||||
// expected. Error must steer to the corrected `find text ...` form.
|
||||
let input: Vec<String> = vec![
|
||||
"find".to_string(),
|
||||
"I'm not a robot".to_string(),
|
||||
"click".to_string(),
|
||||
];
|
||||
let err = parse_command(&input, &default_flags()).unwrap_err();
|
||||
let msg = err.format();
|
||||
assert!(msg.contains("find text"), "got: {msg}");
|
||||
assert!(msg.contains("I'm not a robot"), "got: {msg}");
|
||||
}
|
||||
|
||||
// === Core Actions ===
|
||||
|
||||
#[test]
|
||||
|
||||
+18
-3
@@ -235,10 +235,12 @@ fn install_force_install_profile(no_open: bool) -> Result<PathBuf, String> {
|
||||
}
|
||||
|
||||
/// The `.mobileconfig` payload: a user-scope Chrome policy that force-installs
|
||||
/// the extension by id from our hosted update manifest. User scope installs
|
||||
/// without admin — just a one-time approval click.
|
||||
/// the extension from the Chrome Web Store. User scope installs without admin —
|
||||
/// just a one-time approval click. Must use the STORE id (the Web Store update
|
||||
/// server serves the published extension under the id it assigned, not the local
|
||||
/// Load-unpacked id).
|
||||
fn force_install_mobileconfig() -> String {
|
||||
let forcelist = format!("{EXTENSION_ID};{UPDATE_URL}");
|
||||
let forcelist = format!("{STORE_EXTENSION_ID};{UPDATE_URL}");
|
||||
format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
@@ -342,6 +344,19 @@ fn host_manifest_path_for_chrome() -> Option<PathBuf> {
|
||||
})
|
||||
}
|
||||
|
||||
/// True if the ab-connect native-messaging host manifest is present — i.e. the
|
||||
/// user has set up the extension path. When installed, auto-connect treats the
|
||||
/// dialog-free extension relay as the *intended* transport and refuses to fall
|
||||
/// back to a raw debug port (which would pop Chrome 136+'s "Allow remote
|
||||
/// debugging?" consent modal). The relay-url file comes and goes with the
|
||||
/// service worker; this manifest is the durable signal that the extension is
|
||||
/// the chosen path.
|
||||
pub fn host_installed() -> bool {
|
||||
native_messaging_dirs()
|
||||
.into_iter()
|
||||
.any(|d| d.join(format!("{HOST_NAME}.json")).exists())
|
||||
}
|
||||
|
||||
fn report(json: bool, ok: bool, msg: &str) {
|
||||
if json {
|
||||
println!(
|
||||
|
||||
+31
-2
@@ -625,7 +625,10 @@ pub fn ensure_daemon(session: &str, opts: &DaemonOptions) -> Result<DaemonResult
|
||||
// version (e.g. after an upgrade), kill it and start a fresh one.
|
||||
if !daemon_version_matches(session) {
|
||||
eprintln!(
|
||||
"{} Daemon version mismatch detected, restarting...",
|
||||
"{} Daemon version mismatch detected, restarting... \
|
||||
In-memory context (active tab, refs, captured requests) is reset. \
|
||||
If the next read looks blank or lands on the wrong page, re-open \
|
||||
your target URL before retrying (issue #8.2).",
|
||||
crate::color::warning_indicator()
|
||||
);
|
||||
// Best-effort: ask the old daemon for its current URL so the
|
||||
@@ -821,7 +824,33 @@ fn connect(session: &str) -> Result<Connection, String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_command(cmd: Value, session: &str) -> Result<Response, String> {
|
||||
pub fn send_command(mut cmd: Value, session: &str) -> Result<Response, String> {
|
||||
// Forward per-invocation env to the daemon. The daemon's environment is
|
||||
// frozen at spawn, so settings like AGENT_BROWSER_CLICK_MODE /
|
||||
// AGENT_BROWSER_HUMANIZE (incl. the --humanize flag, which sets the latter)
|
||||
// are otherwise silently ignored on an already-running daemon. Carry them in
|
||||
// the envelope so they apply to THIS command.
|
||||
if let Some(obj) = cmd.as_object_mut() {
|
||||
if let Ok(m) = std::env::var("AGENT_BROWSER_CLICK_MODE") {
|
||||
obj.insert("_clickMode".to_string(), Value::String(m));
|
||||
}
|
||||
if let Ok(h) = std::env::var("AGENT_BROWSER_HUMANIZE") {
|
||||
// Only forward a recognized level; warn once (like the --humanize flag
|
||||
// does) when the env var is set to garbage, instead of silently
|
||||
// ignoring it.
|
||||
if crate::native::humanize::HumanizeLevel::parse(&h).is_some() {
|
||||
obj.insert("_humanize".to_string(), Value::String(h));
|
||||
} else {
|
||||
static WARNED: std::sync::Once = std::sync::Once::new();
|
||||
WARNED.call_once(|| {
|
||||
eprintln!(
|
||||
"warning: AGENT_BROWSER_HUMANIZE must be off|fast|human, got {h:?} (ignored)"
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Retry logic for transient errors (EAGAIN/EWOULDBLOCK/connection issues)
|
||||
const MAX_RETRIES: u32 = 5;
|
||||
const RETRY_DELAY_MS: u64 = 200;
|
||||
|
||||
@@ -248,6 +248,7 @@ fn extract_config_path(args: &[String]) -> Option<Option<String>> {
|
||||
"--screenshot-format",
|
||||
"--idle-timeout",
|
||||
"--model",
|
||||
"--humanize",
|
||||
];
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
@@ -796,6 +797,21 @@ pub fn parse_flags(args: &[String]) -> Flags {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
"--humanize" => {
|
||||
// Human-like input motion level (off|fast|human). Surface it as
|
||||
// AGENT_BROWSER_HUMANIZE so the daemon — spawned as a child that
|
||||
// inherits this process's env — picks it up and it overrides the
|
||||
// adaptive detector. Applies when the session's daemon launches.
|
||||
if let Some(s) = args.get(i + 1) {
|
||||
match crate::native::humanize::HumanizeLevel::parse(s) {
|
||||
Some(_) => std::env::set_var("AGENT_BROWSER_HUMANIZE", s),
|
||||
None => eprintln!(
|
||||
"warning: --humanize must be off|fast|human, got {s:?} (ignored)"
|
||||
),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
"--screenshot-dir" => {
|
||||
if let Some(s) = args.get(i + 1) {
|
||||
flags.screenshot_dir = Some(s.clone());
|
||||
@@ -922,6 +938,7 @@ pub fn clean_args(args: &[String]) -> Vec<String> {
|
||||
"--screenshot-format",
|
||||
"--idle-timeout",
|
||||
"--model",
|
||||
"--humanize",
|
||||
];
|
||||
|
||||
let mut i = 0;
|
||||
|
||||
+367
-39
@@ -23,6 +23,7 @@ use super::cdp::types::{
|
||||
use super::cookies;
|
||||
use super::diff;
|
||||
use super::element::RefMap;
|
||||
use super::humanize;
|
||||
use super::inspect_server::InspectServer;
|
||||
use super::interaction;
|
||||
use super::network::{self, DomainFilter, EventTracker};
|
||||
@@ -1159,6 +1160,23 @@ impl Drop for DaemonState {
|
||||
|
||||
pub async fn execute_command(cmd: &Value, state: &mut DaemonState) -> Value {
|
||||
let action = cmd.get("action").and_then(|v| v.as_str()).unwrap_or("");
|
||||
|
||||
// Apply per-invocation overrides the client forwarded (the daemon's own env
|
||||
// is frozen at spawn). CLICK_MODE is read fresh from the process env by
|
||||
// interaction::click, so mirror it here — set when this command provided it,
|
||||
// clear otherwise, so a value from an earlier command never leaks forward.
|
||||
match cmd.get("_clickMode").and_then(|v| v.as_str()) {
|
||||
Some(m) if !m.is_empty() => std::env::set_var("AGENT_BROWSER_CLICK_MODE", m),
|
||||
_ => std::env::remove_var("AGENT_BROWSER_CLICK_MODE"),
|
||||
}
|
||||
// Humanize: set the session level from the client's --humanize / env. Only
|
||||
// set when provided (don't clear — the adaptive per-navigation detector also
|
||||
// owns this level between explicit overrides).
|
||||
if let Some(h) = cmd.get("_humanize").and_then(|v| v.as_str()) {
|
||||
if let Some(level) = super::humanize::HumanizeLevel::parse(h) {
|
||||
super::humanize::set_detected_level(level);
|
||||
}
|
||||
}
|
||||
let id = cmd
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -1298,6 +1316,7 @@ pub async fn execute_command(cmd: &Value, state: &mut DaemonState) -> Value {
|
||||
"content" => handle_content(state).await,
|
||||
"evaluate" => handle_evaluate(cmd, state).await,
|
||||
"close" => handle_close(state).await,
|
||||
"stealth_status" => handle_stealth_status(state).await,
|
||||
"snapshot" => handle_snapshot(cmd, state).await,
|
||||
"screenshot" => handle_screenshot(cmd, state).await,
|
||||
"click" => handle_click(cmd, state).await,
|
||||
@@ -1305,6 +1324,7 @@ pub async fn execute_command(cmd: &Value, state: &mut DaemonState) -> Value {
|
||||
"fill" => handle_fill(cmd, state).await,
|
||||
"type" => handle_type(cmd, state).await,
|
||||
"press" => handle_press(cmd, state).await,
|
||||
"pick" => handle_pick(cmd, state).await,
|
||||
"hover" => handle_hover(cmd, state).await,
|
||||
"scroll" => handle_scroll(cmd, state).await,
|
||||
"select" => handle_select(cmd, state).await,
|
||||
@@ -1510,12 +1530,11 @@ pub async fn execute_command(cmd: &Value, state: &mut DaemonState) -> Value {
|
||||
/// subsequent navigations don't hijack the user's existing tabs.
|
||||
async fn connect_auto_with_fresh_tab() -> Result<BrowserManager, String> {
|
||||
let mut mgr = BrowserManager::connect_auto().await?;
|
||||
// tab_new creates the tab in the background (CreateTargetParams.background),
|
||||
// so attaching to the user's Chrome never steals their foreground tab. We
|
||||
// deliberately do NOT bring it to front — silent operation.
|
||||
mgr.tab_new(None, None).await?;
|
||||
let session_id = mgr.active_session_id()?.to_string();
|
||||
let _ = mgr
|
||||
.client
|
||||
.send_command("Page.bringToFront", None, Some(&session_id))
|
||||
.await;
|
||||
|
||||
// Liveness probe: confirm the CDP session can actually round-trip
|
||||
// before returning success. Without this, a zombie CDP socket (process
|
||||
@@ -2512,7 +2531,49 @@ async fn handle_navigate(cmd: &Value, state: &mut DaemonState) -> Result<Value,
|
||||
state.ref_map.clear();
|
||||
state.iframe_sessions.clear();
|
||||
state.active_frame_id = None;
|
||||
mgr.navigate(url, wait_until).await
|
||||
let result = mgr.navigate(url, wait_until).await?;
|
||||
// Adaptive humanize: sample the freshly loaded page for known behavioural
|
||||
// anti-bot vendors and escalate this session to Human if any are present.
|
||||
detect_and_set_humanize(mgr).await;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// After navigation, probe the page for known anti-bot vendor fingerprints
|
||||
/// (cookies / script URLs / `window` globals) and set this session's humanize
|
||||
/// level accordingly — `Human` when a vendor is detected, else the `Off`
|
||||
/// baseline. Best-effort: any failure leaves the level unchanged. Skipped when
|
||||
/// `AGENT_BROWSER_HUMANIZE` is set, since the override always wins and the probe
|
||||
/// would be wasted work.
|
||||
async fn detect_and_set_humanize(mgr: &BrowserManager) {
|
||||
if std::env::var("AGENT_BROWSER_HUMANIZE").is_ok() {
|
||||
return;
|
||||
}
|
||||
let js = r#"(() => { try {
|
||||
const cookies = document.cookie.split(';').map(c => c.trim().split('=')[0]).filter(Boolean);
|
||||
const scripts = Array.from(document.scripts, s => s.src || '').filter(Boolean);
|
||||
const re = /_px|bmak|_abck|datadome|reese84|kpsdk|incap_ses|visid_incap|akam/i;
|
||||
const globals = Object.getOwnPropertyNames(window).filter(k => re.test(k));
|
||||
return { cookies, scripts, globals };
|
||||
} catch (e) { return {}; } })()"#;
|
||||
let Ok(val) = mgr.evaluate(js, None).await else {
|
||||
return;
|
||||
};
|
||||
let to_strings = |v: Option<&Value>| -> Vec<String> {
|
||||
v.and_then(|v| v.as_array())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|x| x.as_str().map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let signals = humanize::DetectSignals {
|
||||
cookie_names: to_strings(val.get("cookies")),
|
||||
script_urls: to_strings(val.get("scripts")),
|
||||
window_globals: to_strings(val.get("globals")),
|
||||
};
|
||||
let level = humanize::detect_level(&signals, humanize::HumanizeLevel::Off);
|
||||
humanize::set_detected_level(level);
|
||||
}
|
||||
|
||||
async fn handle_url(state: &DaemonState) -> Result<Value, String> {
|
||||
@@ -2620,6 +2681,89 @@ async fn handle_evaluate(cmd: &Value, state: &DaemonState) -> Result<Value, Stri
|
||||
Ok(json!({ "result": result, "origin": url }))
|
||||
}
|
||||
|
||||
/// Local stealth self-check: reports the active mode, live fingerprint probes,
|
||||
/// and the list of applied overrides — so an agent (or human) can confirm
|
||||
/// stealth is working without driving an external detector, and audit exactly
|
||||
/// what's patched on this path (issue #5).
|
||||
async fn handle_stealth_status(state: &DaemonState) -> Result<Value, String> {
|
||||
let mgr = state.browser.as_ref().ok_or("Browser not launched")?;
|
||||
let connect = mgr.is_cdp_connection();
|
||||
|
||||
let probe_js = r#"(() => {
|
||||
const ua = navigator.userAgent || '';
|
||||
return {
|
||||
webdriver: navigator.webdriver === true,
|
||||
hasWindowChrome: typeof window.chrome === 'object' && window.chrome !== null,
|
||||
plugins: navigator.plugins ? navigator.plugins.length : 0,
|
||||
languages: navigator.languages || [],
|
||||
platform: navigator.platform || '',
|
||||
headlessUA: /Headless/i.test(ua),
|
||||
};
|
||||
})()"#;
|
||||
let p = mgr.evaluate(probe_js, None).await.unwrap_or(Value::Null);
|
||||
let webdriver = p.get("webdriver").and_then(|v| v.as_bool()).unwrap_or(true);
|
||||
let has_chrome = p
|
||||
.get("hasWindowChrome")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
let plugins = p.get("plugins").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let headless_ua = p
|
||||
.get("headlessUA")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
|
||||
let checks = json!([
|
||||
{ "name": "navigator.webdriver is false", "pass": !webdriver },
|
||||
{ "name": "window.chrome present", "pass": has_chrome },
|
||||
{ "name": "navigator.plugins non-empty", "pass": plugins > 0, "value": plugins },
|
||||
{ "name": "userAgent has no 'Headless'", "pass": !headless_ua },
|
||||
]);
|
||||
let ok = !webdriver && has_chrome && plugins > 0 && !headless_ua;
|
||||
|
||||
let overrides = if connect {
|
||||
json!([
|
||||
"navigator.webdriver=false via Emulation.setAutomationOverride (native CDP — no JS lie)",
|
||||
"Runtime.enable OFF unless console/error capture is opted in (no rebrowser runtime leak)",
|
||||
"zero JS patches injected — the browser's real fingerprint is used as-is",
|
||||
])
|
||||
} else {
|
||||
let iframe_proxy =
|
||||
std::env::var("AGENT_BROWSER_DISABLE_IFRAME_PROXY").as_deref() != Ok("1");
|
||||
json!([
|
||||
"navigator.webdriver removed; navigator.languages/locale normalized",
|
||||
"window.chrome / chrome.runtime shimmed; navigator.platform fixed",
|
||||
"WebGL vendor/renderer, plugins, permissions normalized",
|
||||
format!(
|
||||
"srcdoc-iframe contentWindow proxy: {} (CreepJS hasIframeProxy)",
|
||||
if iframe_proxy {
|
||||
"ON — set AGENT_BROWSER_DISABLE_IFRAME_PROXY=1 for clean 0%"
|
||||
} else {
|
||||
"off"
|
||||
}
|
||||
),
|
||||
format!(
|
||||
"canvas/audio noise: {} (AGENT_BROWSER_HIDE_CANVAS)",
|
||||
if std::env::var("AGENT_BROWSER_HIDE_CANVAS").as_deref() == Ok("1") {
|
||||
"on"
|
||||
} else {
|
||||
"off (opt-in)"
|
||||
}
|
||||
),
|
||||
"Chrome flags: --disable-blink-features=AutomationControlled, ANGLE GL",
|
||||
])
|
||||
};
|
||||
|
||||
Ok(json!({
|
||||
"stealthStatus": {
|
||||
"mode": if connect { "connect (your real Chrome — strongest)" } else { "launch (standalone)" },
|
||||
"ok": ok,
|
||||
"checks": checks,
|
||||
"overrides": overrides,
|
||||
"probe": p,
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
async fn handle_close(state: &mut DaemonState) -> Result<Value, String> {
|
||||
if let Some(ref mgr) = state.browser {
|
||||
if let Some(ref session_name) = state.session_name {
|
||||
@@ -2837,11 +2981,32 @@ async fn handle_screenshot(cmd: &Value, state: &mut DaemonState) -> Result<Value
|
||||
response["annotations"] = serde_json::to_value(&result.annotations)
|
||||
.map_err(|e| format!("Failed to serialize annotations: {}", e))?;
|
||||
}
|
||||
// Stamp which page was captured so a screenshot of the wrong tab is obvious
|
||||
// (issue #8.1: relay sessions can drift to whatever tab the user activated).
|
||||
if let Ok(url) = mgr.get_url().await {
|
||||
if !url.is_empty() {
|
||||
response["origin"] = json!(url);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn handle_click(cmd: &Value, state: &mut DaemonState) -> Result<Value, String> {
|
||||
// First-class coordinate click (issue #8.4): click a raw viewport point with
|
||||
// no element resolution. Parsed from `click <x> <y>` / `click --coords x,y`.
|
||||
if let (Some(x), Some(y)) = (
|
||||
cmd.get("x").and_then(|v| v.as_f64()),
|
||||
cmd.get("y").and_then(|v| v.as_f64()),
|
||||
) {
|
||||
let mgr = state.browser.as_ref().ok_or("Browser not launched")?;
|
||||
let session_id = mgr.active_session_id()?.to_string();
|
||||
let button = cmd.get("button").and_then(|v| v.as_str()).unwrap_or("left");
|
||||
let click_count = cmd.get("clickCount").and_then(|v| v.as_i64()).unwrap_or(1) as i32;
|
||||
interaction::click_at_point(&mgr.client, &session_id, x, y, button, click_count).await?;
|
||||
return Ok(json!({ "clicked": { "x": x, "y": y } }));
|
||||
}
|
||||
|
||||
let selector = cmd
|
||||
.get("selector")
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -2972,6 +3137,22 @@ async fn handle_fill(cmd: &Value, state: &mut DaemonState) -> Result<Value, Stri
|
||||
async fn handle_type(cmd: &Value, state: &mut DaemonState) -> Result<Value, String> {
|
||||
let mgr = state.browser.as_ref().ok_or("Browser not launched")?;
|
||||
let session_id = mgr.active_session_id()?.to_string();
|
||||
|
||||
// `type --focused <text>`: type into the currently-focused element without a
|
||||
// selector (custom widgets that move focus to a hidden input on open).
|
||||
if cmd
|
||||
.get("focused")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
let text = cmd
|
||||
.get("text")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or("Missing 'text' parameter")?;
|
||||
interaction::type_text_into_active_context(&mgr.client, &session_id, text, None).await?;
|
||||
return Ok(json!({ "typed": text, "focused": true }));
|
||||
}
|
||||
|
||||
let selector = cmd
|
||||
.get("selector")
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -2997,6 +3178,103 @@ async fn handle_type(cmd: &Value, state: &mut DaemonState) -> Result<Value, Stri
|
||||
Ok(json!({ "typed": text }))
|
||||
}
|
||||
|
||||
/// Atomic combobox select: `pick <selector> --option "<text>"`. Opens the control
|
||||
/// (so a portal-rendered menu mounts), polls for the option by visible text, then
|
||||
/// fires the full pointer/mouse event sequence on it — covering native `<select>`,
|
||||
/// ARIA combobox/listbox, and react-select, which a bare `click`+`press Enter`
|
||||
/// can't do reliably. Runs as one in-page async routine so the open→render→pick
|
||||
/// dance happens without round-trips that let the menu collapse between commands.
|
||||
async fn handle_pick(cmd: &Value, state: &mut DaemonState) -> Result<Value, String> {
|
||||
let mgr = state.browser.as_ref().ok_or("Browser not launched")?;
|
||||
let session_id = mgr.active_session_id()?.to_string();
|
||||
let selector = cmd
|
||||
.get("selector")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or("Missing 'selector' parameter")?;
|
||||
let option = cmd
|
||||
.get("option")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or("Missing 'option' parameter")?;
|
||||
|
||||
let (object_id, effective_session_id) = super::element::resolve_element_object_id(
|
||||
&mgr.client,
|
||||
&session_id,
|
||||
&state.ref_map,
|
||||
selector,
|
||||
&state.iframe_sessions,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let func = format!(
|
||||
r#"async function() {{
|
||||
const want = {opt};
|
||||
const norm = s => (s || '').replace(/\s+/g, ' ').trim();
|
||||
const matches = el => norm(el.textContent).toLowerCase().includes(want.toLowerCase());
|
||||
const el = this;
|
||||
const fire = (n, t) => n.dispatchEvent(new MouseEvent(t, {{ bubbles: true, cancelable: true, view: window }}));
|
||||
|
||||
// Native <select>: set the matching option and dispatch input/change.
|
||||
if (el.tagName === 'SELECT') {{
|
||||
const opt = [...el.options].find(matches);
|
||||
if (!opt) return {{ ok: false, error: 'no <option> matched ' + JSON.stringify(want) }};
|
||||
el.value = opt.value;
|
||||
el.dispatchEvent(new Event('input', {{ bubbles: true }}));
|
||||
el.dispatchEvent(new Event('change', {{ bubbles: true }}));
|
||||
return {{ ok: true, picked: norm(opt.textContent), value: el.value, kind: 'select' }};
|
||||
}}
|
||||
|
||||
// Custom widget: open it.
|
||||
(el.focus && el.focus());
|
||||
['pointerdown', 'mousedown', 'mouseup', 'click'].forEach(t => fire(el, t));
|
||||
|
||||
// Poll for the option to render anywhere in the document (portals
|
||||
// mount the menu outside the trigger), then click it.
|
||||
const sel = '[role=option], [role=listbox] [role=option], li[role=option], [class*=option], [class*=item]';
|
||||
const find = () => [...document.querySelectorAll(sel)].find(o => o.offsetParent !== null && matches(o));
|
||||
const deadline = Date.now() + 2500;
|
||||
let opt = find();
|
||||
while (!opt && Date.now() < deadline) {{
|
||||
await new Promise(r => setTimeout(r, 80));
|
||||
opt = find();
|
||||
}}
|
||||
if (!opt) return {{ ok: false, error: 'option ' + JSON.stringify(want) + ' did not appear after opening the control' }};
|
||||
(opt.scrollIntoView && opt.scrollIntoView({{ block: 'center' }}));
|
||||
['pointermove', 'pointerover', 'mouseover', 'pointerdown', 'mousedown', 'mouseup', 'click'].forEach(t => fire(opt, t));
|
||||
return {{ ok: true, picked: norm(opt.textContent), kind: 'custom' }};
|
||||
}}"#,
|
||||
opt = serde_json::to_string(option).unwrap_or_default(),
|
||||
);
|
||||
|
||||
let result: super::cdp::types::EvaluateResult = mgr
|
||||
.client
|
||||
.send_command_typed(
|
||||
"Runtime.callFunctionOn",
|
||||
&super::cdp::types::CallFunctionOnParams {
|
||||
function_declaration: func,
|
||||
object_id: Some(object_id),
|
||||
arguments: None,
|
||||
return_by_value: Some(true),
|
||||
await_promise: Some(true),
|
||||
},
|
||||
Some(&effective_session_id),
|
||||
)
|
||||
.await?;
|
||||
|
||||
if let Some(ref ex) = result.exception_details {
|
||||
return Err(format!("pick failed: {}", ex.text));
|
||||
}
|
||||
let val = result.result.value.unwrap_or(Value::Null);
|
||||
if val.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||
Ok(json!({ "picked": val.get("picked"), "selector": selector }))
|
||||
} else {
|
||||
Err(val
|
||||
.get("error")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("pick failed")
|
||||
.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_press(cmd: &Value, state: &mut DaemonState) -> Result<Value, String> {
|
||||
let mgr = state.browser.as_ref().ok_or("Browser not launched")?;
|
||||
let session_id = mgr.active_session_id()?.to_string();
|
||||
@@ -5470,19 +5748,29 @@ async fn handle_wheel(cmd: &Value, state: &DaemonState) -> Result<Value, String>
|
||||
let delta_x = cmd.get("deltaX").and_then(|v| v.as_f64()).unwrap_or(0.0);
|
||||
let delta_y = cmd.get("deltaY").and_then(|v| v.as_f64()).unwrap_or(0.0);
|
||||
|
||||
mgr.client
|
||||
.send_command(
|
||||
"Input.dispatchMouseEvent",
|
||||
Some(json!({
|
||||
"type": "mouseWheel",
|
||||
"x": x,
|
||||
"y": y,
|
||||
"deltaX": delta_x,
|
||||
"deltaY": delta_y,
|
||||
})),
|
||||
Some(&session_id),
|
||||
)
|
||||
.await?;
|
||||
// Humanize: at Off this is one instant wheel event (unchanged); at
|
||||
// Fast/Human the scroll is split into eased, slightly-jittered segments so
|
||||
// it ramps and settles like a real wheel/trackpad flick.
|
||||
let level = humanize::active_level();
|
||||
let seed = humanize::next_seed();
|
||||
for (dx, dy, delay) in humanize::scroll_segments(delta_x, delta_y, level, seed) {
|
||||
mgr.client
|
||||
.send_command(
|
||||
"Input.dispatchMouseEvent",
|
||||
Some(json!({
|
||||
"type": "mouseWheel",
|
||||
"x": x,
|
||||
"y": y,
|
||||
"deltaX": dx,
|
||||
"deltaY": dy,
|
||||
})),
|
||||
Some(&session_id),
|
||||
)
|
||||
.await?;
|
||||
if !delay.is_zero() {
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(json!({ "scrolled": true, "deltaX": delta_x, "deltaY": delta_y }))
|
||||
}
|
||||
@@ -6479,7 +6767,7 @@ async fn handle_drag(cmd: &Value, state: &mut DaemonState) -> Result<Value, Stri
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or("Missing 'target' parameter")?;
|
||||
|
||||
let (sx, sy, source_session_id) = super::element::resolve_element_center(
|
||||
let (sx, sy, _, _, source_session_id) = super::element::resolve_element_center(
|
||||
&mgr.client,
|
||||
&session_id,
|
||||
&state.ref_map,
|
||||
@@ -6487,7 +6775,7 @@ async fn handle_drag(cmd: &Value, state: &mut DaemonState) -> Result<Value, Stri
|
||||
&state.iframe_sessions,
|
||||
)
|
||||
.await?;
|
||||
let (tx, ty, target_session_id) = super::element::resolve_element_center(
|
||||
let (tx, ty, _, _, target_session_id) = super::element::resolve_element_center(
|
||||
&mgr.client,
|
||||
&session_id,
|
||||
&state.ref_map,
|
||||
@@ -6512,12 +6800,26 @@ async fn handle_drag(cmd: &Value, state: &mut DaemonState) -> Result<Value, Stri
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Move in steps to target, keeping the left button held (buttons: 1) so
|
||||
// that the browser sees a drag rather than a plain pointer move.
|
||||
let steps = 10;
|
||||
for i in 1..=steps {
|
||||
let cx = sx + (tx - sx) * (i as f64) / (steps as f64);
|
||||
let cy = sy + (ty - sy) * (i as f64) / (steps as f64);
|
||||
// Move to the target with the left button held (buttons: 1) so the browser
|
||||
// sees a drag. At Off this is the original linear 10-step path; at
|
||||
// Fast/Human it follows humanize's curved, decelerating trajectory.
|
||||
let level = humanize::active_level();
|
||||
let drag_path: Vec<(f64, f64, std::time::Duration)> =
|
||||
if matches!(level, humanize::HumanizeLevel::Off) {
|
||||
(1..=10)
|
||||
.map(|i| {
|
||||
let cx = sx + (tx - sx) * (i as f64) / 10.0;
|
||||
let cy = sy + (ty - sy) * (i as f64) / 10.0;
|
||||
(cx, cy, std::time::Duration::from_millis(10))
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
humanize::move_path((sx, sy), (tx, ty), level, humanize::next_seed())
|
||||
.into_iter()
|
||||
.map(|s| (s.x, s.y, s.delay))
|
||||
.collect()
|
||||
};
|
||||
for (cx, cy, delay) in drag_path {
|
||||
mgr.client
|
||||
.send_command(
|
||||
"Input.dispatchMouseEvent",
|
||||
@@ -6525,7 +6827,9 @@ async fn handle_drag(cmd: &Value, state: &mut DaemonState) -> Result<Value, Stri
|
||||
Some(&target_session_id),
|
||||
)
|
||||
.await?;
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
|
||||
if !delay.is_zero() {
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Mouse up at target
|
||||
@@ -7617,23 +7921,40 @@ pub fn matches_status_filter(status: Option<i64>, filter: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
async fn enable_request_tracking(state: &mut DaemonState) {
|
||||
if state.request_tracking {
|
||||
return;
|
||||
}
|
||||
state.request_tracking = true;
|
||||
if let Some(ref mgr) = state.browser {
|
||||
if let Ok(session_id) = mgr.active_session_id() {
|
||||
let _ = mgr
|
||||
.client
|
||||
.send_command_no_params("Network.enable", Some(session_id))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_requests(cmd: &Value, state: &mut DaemonState) -> Result<Value, String> {
|
||||
if cmd.get("clear").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||
state.tracked_requests.clear();
|
||||
// Enable Network capture NOW, on `--clear`, not lazily on the next read.
|
||||
// `--clear` is the canonical "start capturing fresh" call, so requests
|
||||
// fired between it and the following `requests` read must be tracked.
|
||||
// Lazy-enabling only on read missed exactly those → intermittent
|
||||
// "No requests captured" on the first try, fine on retry (issue #8.3).
|
||||
enable_request_tracking(state).await;
|
||||
return Ok(json!({ "cleared": true }));
|
||||
}
|
||||
|
||||
if !state.request_tracking {
|
||||
state.request_tracking = true;
|
||||
if let Some(ref mgr) = state.browser {
|
||||
if let Ok(session_id) = mgr.active_session_id() {
|
||||
let _ = mgr
|
||||
.client
|
||||
.send_command_no_params("Network.enable", Some(session_id))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
enable_request_tracking(state).await;
|
||||
// Current page URL, so a `requests` read on a drifted/wrong tab is obvious
|
||||
// and "0 captured" can't be confused with "wrong page" (issues #8.1/#8.3).
|
||||
let origin = match state.browser.as_ref() {
|
||||
Some(mgr) => mgr.get_url().await.ok().filter(|u| !u.is_empty()),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let filter = cmd.get("filter").and_then(|v| v.as_str());
|
||||
let type_filter = cmd.get("type").and_then(|v| v.as_str());
|
||||
@@ -7670,7 +7991,14 @@ async fn handle_requests(cmd: &Value, state: &mut DaemonState) -> Result<Value,
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(json!({ "requests": requests }))
|
||||
// NB: do NOT add a top-level `count` field here — the human formatter treats
|
||||
// any `{count}` as a `get count` result and prints just the number, which
|
||||
// would swallow the request list. The list length is self-evident.
|
||||
let mut response = json!({ "requests": requests });
|
||||
if let Some(o) = origin {
|
||||
response["origin"] = json!(o);
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn handle_request_detail(cmd: &Value, state: &mut DaemonState) -> Result<Value, String> {
|
||||
|
||||
+170
-7
@@ -309,6 +309,19 @@ pub struct BrowserManager {
|
||||
pub ignore_https_errors: bool,
|
||||
/// Origins visited during this session, used by save_state to collect cross-origin localStorage.
|
||||
visited_origins: HashSet<String>,
|
||||
/// Target IDs of tabs THIS session created via `Target.createTarget`. When
|
||||
/// connected to the user's real Chrome (not a launched browser), these are
|
||||
/// closed on `close()` so the session's tabs don't pile up in the user's
|
||||
/// browser after it ends. Only ever holds tabs we created — never the user's
|
||||
/// existing tabs or other sessions' tabs — so closing them is always safe.
|
||||
created_targets: HashSet<String>,
|
||||
/// The session's *intended* active tab, pinned by stable target_id rather
|
||||
/// than the fragile `active_page_index`. Set on every explicit open / tab new
|
||||
/// / tab switch. `active_session_id` resolves through this so a foreign tab
|
||||
/// opening (passive discovery), a tab closing, or list reordering can't drift
|
||||
/// the session's commands onto the wrong page — the wrong-origin-fetch hazard
|
||||
/// in the dogfood reports. Falls back to the index if the pinned tab is gone.
|
||||
active_target_id: Option<String>,
|
||||
next_tab_id: u32,
|
||||
/// Whether to enable the CDP `Runtime` domain (console / error / exception capture).
|
||||
/// OFF by default for stealth: a live `Runtime.enable` is a detectable CDP signal
|
||||
@@ -433,6 +446,8 @@ impl BrowserManager {
|
||||
download_path: download_path.clone(),
|
||||
ignore_https_errors,
|
||||
visited_origins: HashSet::new(),
|
||||
created_targets: HashSet::new(),
|
||||
active_target_id: None,
|
||||
next_tab_id: 1,
|
||||
capture_console: console_capture_enabled(),
|
||||
};
|
||||
@@ -523,6 +538,8 @@ impl BrowserManager {
|
||||
download_path: None,
|
||||
ignore_https_errors: false,
|
||||
visited_origins: HashSet::new(),
|
||||
created_targets: HashSet::new(),
|
||||
active_target_id: None,
|
||||
next_tab_id: 1,
|
||||
capture_console: console_capture_enabled(),
|
||||
};
|
||||
@@ -539,6 +556,7 @@ impl BrowserManager {
|
||||
target_type: "page".to_string(),
|
||||
});
|
||||
manager.active_page_index = 0;
|
||||
manager.pin_active_target();
|
||||
manager.enable_domains_direct().await?;
|
||||
} else {
|
||||
manager.discover_and_attach_targets().await?;
|
||||
@@ -581,10 +599,13 @@ impl BrowserManager {
|
||||
&CreateTargetParams {
|
||||
url: "about:blank".to_string(),
|
||||
agent_group,
|
||||
background: None,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
// We created this tab — own it so close() can clean it up.
|
||||
self.created_targets.insert(result.target_id.clone());
|
||||
|
||||
let attach_result: AttachToTargetResult = self
|
||||
.client
|
||||
@@ -610,6 +631,7 @@ impl BrowserManager {
|
||||
target_type: "page".to_string(),
|
||||
});
|
||||
self.active_page_index = 0;
|
||||
self.pin_active_target();
|
||||
self.enable_domains(&attach_result.session_id).await?;
|
||||
} else {
|
||||
for target in &page_targets {
|
||||
@@ -639,6 +661,7 @@ impl BrowserManager {
|
||||
}
|
||||
|
||||
self.active_page_index = 0;
|
||||
self.pin_active_target();
|
||||
let session_id = self.pages[0].session_id.clone();
|
||||
self.enable_domains(&session_id).await?;
|
||||
}
|
||||
@@ -687,6 +710,20 @@ impl BrowserManager {
|
||||
Some(session_id),
|
||||
)
|
||||
.await;
|
||||
// Silent operation: agent tabs are driven in the background (we never
|
||||
// force them to the foreground), so emulate focus. Without this a
|
||||
// backgrounded tab is render-throttled and reports `document.hidden` /
|
||||
// `!document.hasFocus()` — which both breaks timing-sensitive pages and
|
||||
// is itself a bot signal (a real user looks at the page). Best-effort;
|
||||
// ignored on engines without Emulation support.
|
||||
let _ = self
|
||||
.client
|
||||
.send_command(
|
||||
"Emulation.setFocusEmulationEnabled",
|
||||
Some(json!({ "enabled": true })),
|
||||
Some(session_id),
|
||||
)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -711,9 +748,31 @@ impl BrowserManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Index of the session's active page, resolved through the pinned
|
||||
/// `active_target_id` (stable across reorder/removal/passive discovery) and
|
||||
/// falling back to `active_page_index` when nothing is pinned or the pin is
|
||||
/// gone. This is what keeps commands on the tab the agent actually opened.
|
||||
fn resolved_active_index(&self) -> usize {
|
||||
if let Some(tid) = &self.active_target_id {
|
||||
if let Some(i) = self.pages.iter().position(|p| &p.target_id == tid) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
self.active_page_index
|
||||
}
|
||||
|
||||
/// Pin the current active page by target_id so later commands stick to it.
|
||||
/// Call after any explicit open / tab new / tab switch.
|
||||
fn pin_active_target(&mut self) {
|
||||
self.active_target_id = self
|
||||
.pages
|
||||
.get(self.active_page_index)
|
||||
.map(|p| p.target_id.clone());
|
||||
}
|
||||
|
||||
pub fn active_session_id(&self) -> Result<&str, String> {
|
||||
self.pages
|
||||
.get(self.active_page_index)
|
||||
.get(self.resolved_active_index())
|
||||
.map(|p| p.session_id.as_str())
|
||||
.ok_or_else(|| "No active page".to_string())
|
||||
}
|
||||
@@ -877,6 +936,24 @@ impl BrowserManager {
|
||||
.client
|
||||
.send_command_no_params("Browser.close", None)
|
||||
.await;
|
||||
} else {
|
||||
// Connected to the user's real Chrome: we must NOT close their
|
||||
// browser, but we DO own the tabs this session created. Close them so
|
||||
// they don't pile up in the user's window (in their per-session tab
|
||||
// group) every time a session ends, idles out, or the daemon shuts
|
||||
// down. `created_targets` only holds tabs we made via
|
||||
// Target.createTarget — never the user's existing tabs or other
|
||||
// sessions' — so this is always safe. Best-effort per tab.
|
||||
for target_id in self.created_targets.drain() {
|
||||
let _ = self
|
||||
.client
|
||||
.send_command_typed::<_, Value>(
|
||||
"Target.closeTarget",
|
||||
&CloseTargetParams { target_id },
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(mut process) = self.browser_process.take() {
|
||||
@@ -948,7 +1025,7 @@ impl BrowserManager {
|
||||
|
||||
pub fn active_target_id(&self) -> Result<&str, String> {
|
||||
self.pages
|
||||
.get(self.active_page_index)
|
||||
.get(self.resolved_active_index())
|
||||
.map(|p| p.target_id.as_str())
|
||||
.ok_or_else(|| "No active page".to_string())
|
||||
}
|
||||
@@ -973,10 +1050,13 @@ impl BrowserManager {
|
||||
&CreateTargetParams {
|
||||
url: "about:blank".to_string(),
|
||||
agent_group,
|
||||
background: None,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
// We created this tab — own it so close() can clean it up.
|
||||
self.created_targets.insert(result.target_id.clone());
|
||||
|
||||
let attach_result: AttachToTargetResult = self
|
||||
.client
|
||||
@@ -1137,10 +1217,13 @@ impl BrowserManager {
|
||||
&CreateTargetParams {
|
||||
url: target_url.to_string(),
|
||||
agent_group,
|
||||
background: Some(true),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
// We created this tab — own it so close() can clean it up.
|
||||
self.created_targets.insert(result.target_id.clone());
|
||||
|
||||
let attach: AttachToTargetResult = self
|
||||
.client
|
||||
@@ -1170,6 +1253,7 @@ impl BrowserManager {
|
||||
target_type: "page".to_string(),
|
||||
});
|
||||
self.active_page_index = index;
|
||||
self.pin_active_target();
|
||||
|
||||
Ok(json!({
|
||||
"tabId": format_tab_id(tab_id),
|
||||
@@ -1189,14 +1273,14 @@ impl BrowserManager {
|
||||
}
|
||||
|
||||
self.active_page_index = index;
|
||||
self.pin_active_target();
|
||||
let session_id = self.pages[index].session_id.clone();
|
||||
self.enable_domains(&session_id).await?;
|
||||
|
||||
// Bring tab to front
|
||||
let _ = self
|
||||
.client
|
||||
.send_command("Page.bringToFront", None, Some(&session_id))
|
||||
.await;
|
||||
// Silent: switching the agent's *internal* active page must not yank the
|
||||
// user's foreground tab. The page is driven in the background (focus is
|
||||
// emulated in enable_domains); the explicit `bringToFront` command is the
|
||||
// only way a tab is deliberately surfaced.
|
||||
|
||||
let url = self.get_url().await.unwrap_or_default();
|
||||
let title = self.get_title().await.unwrap_or_default();
|
||||
@@ -1533,6 +1617,7 @@ impl BrowserManager {
|
||||
let index = self.pages.len();
|
||||
self.pages.push(page);
|
||||
self.active_page_index = index;
|
||||
self.pin_active_target();
|
||||
}
|
||||
|
||||
/// Add a passively-discovered page WITHOUT changing the active tab.
|
||||
@@ -1556,8 +1641,18 @@ impl BrowserManager {
|
||||
|
||||
pub fn remove_page_by_target_id(&mut self, target_id: &str) {
|
||||
if let Some(pos) = self.pages.iter().position(|p| p.target_id == target_id) {
|
||||
let removed_was_pinned = self.active_target_id.as_deref() == Some(target_id);
|
||||
self.pages.remove(pos);
|
||||
self.update_active_page_after_removal(pos);
|
||||
// If we just removed the pinned active target, the pin now dangles and
|
||||
// `resolved_active_index` silently falls back to `active_page_index`.
|
||||
// After a passive about:blank discovery that index can point at a blank
|
||||
// tab, so `wait` → eval/snapshot lands on about:blank (issue #7). Re-pin
|
||||
// to the surviving active page so the pin is never left pointing at a
|
||||
// target that no longer exists.
|
||||
if removed_was_pinned {
|
||||
self.pin_active_target();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1734,6 +1829,8 @@ async fn initialize_lightpanda_manager(
|
||||
download_path: None,
|
||||
ignore_https_errors: false,
|
||||
visited_origins: HashSet::new(),
|
||||
created_targets: HashSet::new(),
|
||||
active_target_id: None,
|
||||
next_tab_id: 1,
|
||||
capture_console: console_capture_enabled(),
|
||||
};
|
||||
@@ -2018,6 +2115,72 @@ mod tests {
|
||||
assert_eq!(active_page_index_after_removal(0, 0, 0), 0);
|
||||
}
|
||||
|
||||
// issue #7: removing the pinned active target must re-anchor the pin to a
|
||||
// surviving page. Models `remove_page_by_target_id`'s index + re-pin steps
|
||||
// purely (BrowserManager needs a live CDP client, so the method itself can't
|
||||
// be unit-constructed). The invariant: after removal the pin never dangles
|
||||
// and never silently resolves to a passively-discovered about:blank tab.
|
||||
fn simulate_remove(
|
||||
target_ids: &[&str],
|
||||
active_index: usize,
|
||||
pinned: &str,
|
||||
remove_id: &str,
|
||||
) -> (Vec<String>, usize, Option<String>) {
|
||||
let pos = target_ids.iter().position(|t| *t == remove_id).unwrap();
|
||||
let removed_was_pinned = pinned == remove_id;
|
||||
let mut pages: Vec<String> = target_ids.iter().map(|s| s.to_string()).collect();
|
||||
pages.remove(pos);
|
||||
let new_active = active_page_index_after_removal(active_index, pos, pages.len());
|
||||
let new_pin = if removed_was_pinned {
|
||||
pages.get(new_active).cloned()
|
||||
} else {
|
||||
Some(pinned.to_string())
|
||||
};
|
||||
(pages, new_active, new_pin)
|
||||
}
|
||||
|
||||
fn resolve_active<'a>(
|
||||
pages: &'a [String],
|
||||
active_index: usize,
|
||||
pin: &Option<String>,
|
||||
) -> &'a str {
|
||||
if let Some(tid) = pin {
|
||||
if let Some(p) = pages.iter().find(|p| *p == tid) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
pages.get(active_index).map(|s| s.as_str()).unwrap_or("")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_removing_unpinned_blank_keeps_pin_on_real_page() {
|
||||
// pages = [creepjs(pinned, active), about:blank]; a passive blank closes.
|
||||
let (pages, active, pin) = simulate_remove(&["creepjs", "blank"], 0, "creepjs", "blank");
|
||||
assert_eq!(resolve_active(&pages, active, &pin), "creepjs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_removing_pinned_page_repins_to_survivor_not_dangling() {
|
||||
// pages = [blank, creepjs(pinned, active)]; the pinned page itself closes.
|
||||
let (pages, active, pin) = simulate_remove(&["blank", "creepjs"], 1, "creepjs", "creepjs");
|
||||
// pin must point at a page that still exists (no dangling fallback).
|
||||
let resolved = resolve_active(&pages, active, &pin);
|
||||
assert!(
|
||||
pages.iter().any(|p| p == resolved),
|
||||
"resolved a dangling target"
|
||||
);
|
||||
assert_eq!(resolved, "blank");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_falls_back_cleanly_when_pin_dangles() {
|
||||
// A stale pin (target already gone) must resolve to a real surviving page,
|
||||
// never panic or return the missing id.
|
||||
let pages = vec!["creepjs".to_string(), "blank".to_string()];
|
||||
let pin = Some("gone".to_string());
|
||||
assert_eq!(resolve_active(&pages, 0, &pin), "creepjs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_launch_options_extensions_and_cdp() {
|
||||
let ext = vec!["/path/to/ext".to_string()];
|
||||
|
||||
@@ -783,14 +783,46 @@ pub async fn auto_connect_cdp() -> Result<String, String> {
|
||||
// / :9222 probes below: if the user's Chrome happens to also be listening on a
|
||||
// debug port, attaching there would pop the consent dialog and defeat the
|
||||
// whole zero-interaction extension path.
|
||||
if let Some(relay) = crate::connect::relay_url() {
|
||||
// The relay is a local CDP-over-WS endpoint we connect to like Chrome.
|
||||
// A bare TCP liveness check (no WS upgrade) confirms it is actually
|
||||
// accepting before we commit, mirroring the consent-free probe used for
|
||||
// DevToolsActivePort.
|
||||
if relay_is_live(&relay).await {
|
||||
return Ok(relay);
|
||||
// If the extension is installed, it is the *intended* transport. The relay
|
||||
// URL file comes and goes with the MV3 service worker (a Chrome restart or an
|
||||
// idle SW briefly drops it), so a single failed probe doesn't mean "no
|
||||
// extension" — retry for a few seconds while it reconnects. Crucially, when
|
||||
// the extension is set up we must NEVER fall through to the raw :9222 path
|
||||
// below: that pops Chrome 136+'s "Allow remote debugging?" dialog, the exact
|
||||
// thing the extension exists to avoid.
|
||||
// ~15s of retries (500ms apart) when the extension is installed: long enough
|
||||
// for the MV3 service worker to wake and reconnect on its own (onStartup
|
||||
// after a Chrome restart, or the keepalive alarm) so the relay self-heals
|
||||
// with NO user action. The loop re-checks the relay file every iteration, so
|
||||
// a recovery mid-wait is picked up immediately — the full window is only ever
|
||||
// spent when the extension is genuinely down.
|
||||
let host_installed = crate::connect::host_installed();
|
||||
let relay_attempts = if host_installed { 30 } else { 1 };
|
||||
for attempt in 0..relay_attempts {
|
||||
if let Some(relay) = crate::connect::relay_url() {
|
||||
// The relay is a local CDP-over-WS endpoint we connect to like Chrome.
|
||||
// A bare TCP liveness check (no WS upgrade) confirms it is actually
|
||||
// accepting before we commit, mirroring the consent-free probe used
|
||||
// for DevToolsActivePort.
|
||||
if relay_is_live(&relay).await {
|
||||
return Ok(relay);
|
||||
}
|
||||
}
|
||||
if host_installed && attempt + 1 < relay_attempts {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
|
||||
if host_installed {
|
||||
return Err(
|
||||
"The agent-browser-stealth extension is installed, but its relay \
|
||||
isn't connected right now. Wake it up — click the extension's \
|
||||
toolbar icon, or reload it at chrome://extensions — then retry. \
|
||||
(agent-browser will not attach to a raw --remote-debugging-port \
|
||||
while the extension is set up, because that pops Chrome's \"Allow \
|
||||
remote debugging?\" dialog. Use --cdp <port> to force the raw path.)"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
let user_data_dirs = get_chrome_user_data_dirs();
|
||||
|
||||
@@ -153,6 +153,12 @@ pub struct CreateTargetParams {
|
||||
/// endpoint never receives an unknown parameter.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub agent_group: Option<String>,
|
||||
/// Create the tab in the background so opening it never steals the user's
|
||||
/// foreground tab (silent operation). Standard CDP param; the ab-connect
|
||||
/// extension creates its tabs `active: false` regardless, so this only
|
||||
/// affects the raw-CDP (no extension) path.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub background: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
|
||||
@@ -2252,9 +2252,13 @@ async fn e2e_save_state_cross_domain() {
|
||||
.await;
|
||||
assert_success(&resp);
|
||||
|
||||
// Navigate to domain A and set cookie + localStorage
|
||||
// Navigate to domain A and set cookie + localStorage. Use example.org (a
|
||||
// stable IANA-reserved domain, like example.com below) rather than an
|
||||
// external service such as httpbin.org — cookie/localStorage are set
|
||||
// client-side via CDP, so the only requirement is that the page loads
|
||||
// reliably. A flaky external domain made this test intermittently fail in CI.
|
||||
let resp = execute_command(
|
||||
&json!({ "id": "2", "action": "navigate", "url": "https://httpbin.org/html" }),
|
||||
&json!({ "id": "2", "action": "navigate", "url": "https://example.org/" }),
|
||||
&mut state,
|
||||
)
|
||||
.await;
|
||||
@@ -2263,7 +2267,7 @@ async fn e2e_save_state_cross_domain() {
|
||||
let resp = execute_command(
|
||||
&json!({
|
||||
"id": "3", "action": "cookies_set",
|
||||
"name": "domainA_cookie", "value": "from_httpbin"
|
||||
"name": "domainA_cookie", "value": "from_example_org"
|
||||
}),
|
||||
&mut state,
|
||||
)
|
||||
@@ -2330,7 +2334,7 @@ async fn e2e_save_state_cross_domain() {
|
||||
let has_domain_b = cookies.iter().any(|c| c["name"] == "domainB_cookie");
|
||||
assert!(
|
||||
has_domain_a,
|
||||
"Should include cross-domain cookie from httpbin.org: {:?}",
|
||||
"Should include cross-domain cookie from example.org: {:?}",
|
||||
cookies
|
||||
);
|
||||
assert!(
|
||||
@@ -2341,21 +2345,26 @@ async fn e2e_save_state_cross_domain() {
|
||||
|
||||
// Verify BOTH origins' localStorage are present
|
||||
let origins = state_data["origins"].as_array().unwrap();
|
||||
// Match full hostnames so the two example.* origins don't alias each other.
|
||||
let has_origin_a = origins.iter().any(|o| {
|
||||
o["origin"].as_str().is_some_and(|s| s.contains("httpbin"))
|
||||
o["origin"]
|
||||
.as_str()
|
||||
.is_some_and(|s| s.contains("example.org"))
|
||||
&& o["localStorage"]
|
||||
.as_array()
|
||||
.is_some_and(|ls| ls.iter().any(|e| e["name"] == "domainA_key"))
|
||||
});
|
||||
let has_origin_b = origins.iter().any(|o| {
|
||||
o["origin"].as_str().is_some_and(|s| s.contains("example"))
|
||||
o["origin"]
|
||||
.as_str()
|
||||
.is_some_and(|s| s.contains("example.com"))
|
||||
&& o["localStorage"]
|
||||
.as_array()
|
||||
.is_some_and(|ls| ls.iter().any(|e| e["name"] == "domainB_key"))
|
||||
});
|
||||
assert!(
|
||||
has_origin_a,
|
||||
"Should include localStorage from httpbin.org origin: {:?}",
|
||||
"Should include localStorage from example.org origin: {:?}",
|
||||
origins
|
||||
);
|
||||
assert!(
|
||||
|
||||
@@ -200,13 +200,17 @@ async fn relocate_stale_ref(
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve a `@ref` or CSS selector to a click point. Returns
|
||||
/// `(centre_x, centre_y, width, height, session_id)`. Width/height come from the
|
||||
/// element's box model and feed humanize's in-bounds landing jitter; the CSS
|
||||
/// selector path returns zero size (→ land on centre, no jitter).
|
||||
pub async fn resolve_element_center(
|
||||
client: &CdpClient,
|
||||
session_id: &str,
|
||||
ref_map: &RefMap,
|
||||
selector_or_ref: &str,
|
||||
iframe_sessions: &HashMap<String, String>,
|
||||
) -> Result<(f64, f64, String), String> {
|
||||
) -> Result<(f64, f64, f64, f64, String), String> {
|
||||
if let Some(ref_id) = parse_ref(selector_or_ref) {
|
||||
let entry = ref_map
|
||||
.get(&ref_id)
|
||||
@@ -263,7 +267,7 @@ pub async fn resolve_element_center(
|
||||
.await;
|
||||
|
||||
if let Ok(r) = result {
|
||||
let (x, y) = box_model_center(&r.model);
|
||||
let (x, y, w, h) = box_model_dims(&r.model);
|
||||
// Occlusion check: a transient overlay (X.com's "click
|
||||
// outside to close" mask, modal backdrop, sticky banner,
|
||||
// etc.) can land on top of our target between snapshot
|
||||
@@ -279,7 +283,7 @@ pub async fn resolve_element_center(
|
||||
verify_click_target(client, effective_session_id, active_id, &ref_id, x, y)
|
||||
.await?;
|
||||
}
|
||||
return Ok((x, y, effective_session_id.to_string()));
|
||||
return Ok((x, y, w, h, effective_session_id.to_string()));
|
||||
}
|
||||
// backend_node_id is stale; re-query the accessibility tree below
|
||||
}
|
||||
@@ -316,13 +320,14 @@ pub async fn resolve_element_center(
|
||||
Some(effective_session_id),
|
||||
)
|
||||
.await?;
|
||||
let (x, y) = box_model_center(&result.model);
|
||||
return Ok((x, y, effective_session_id.to_string()));
|
||||
let (x, y, w, h) = box_model_dims(&result.model);
|
||||
return Ok((x, y, w, h, effective_session_id.to_string()));
|
||||
}
|
||||
|
||||
// CSS selector
|
||||
let (x, y) = resolve_by_selector(client, session_id, selector_or_ref).await?;
|
||||
Ok((x, y, session_id.to_string()))
|
||||
// No box model on the CSS-selector fast path → zero size → land on centre.
|
||||
Ok((x, y, 0.0, 0.0, session_id.to_string()))
|
||||
}
|
||||
|
||||
pub async fn resolve_element_object_id(
|
||||
@@ -551,8 +556,12 @@ async fn verify_ref_identity(
|
||||
Err(format!(
|
||||
"Ref {} no longer matches its snapshot. Was [{} \"{}\"], now [{} \"{}\"].\n\
|
||||
The DOM mutated between snapshot and interaction (typical with React/Vue \
|
||||
reusing nodes during re-render). Take a fresh snapshot, then re-target.\n\
|
||||
To bypass this guard set AGENT_BROWSER_VERIFY_REF=0.",
|
||||
reusing nodes during re-render). Fix: take a fresh `snapshot` and re-target \
|
||||
with the new ref. For SPAs where refs churn every interaction, drive the \
|
||||
element directly with `eval` (e.g. `eval \"document.querySelector(...).click()\"`), \
|
||||
which doesn't depend on refs.\n\
|
||||
(Last resort: AGENT_BROWSER_VERIFY_REF=0 disables this safety check — only \
|
||||
if you accept clicks may land on a re-rendered/wrong node.)",
|
||||
ref_id, expected_role, expected_name, actual_role, actual_name,
|
||||
))
|
||||
}
|
||||
@@ -872,6 +881,35 @@ fn box_model_center(model: &BoxModel) -> (f64, f64) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Centre plus width/height of the content box, derived from the quad's
|
||||
/// bounding extent. Width/height feed humanize's in-bounds landing jitter; a
|
||||
/// degenerate quad yields zero size, which the jitter treats as "land on
|
||||
/// centre" (no jitter).
|
||||
fn box_model_dims(model: &BoxModel) -> (f64, f64, f64, f64) {
|
||||
let (cx, cy) = box_model_center(model);
|
||||
if model.content.len() >= 8 {
|
||||
let xs = [
|
||||
model.content[0],
|
||||
model.content[2],
|
||||
model.content[4],
|
||||
model.content[6],
|
||||
];
|
||||
let ys = [
|
||||
model.content[1],
|
||||
model.content[3],
|
||||
model.content[5],
|
||||
model.content[7],
|
||||
];
|
||||
let w = xs.iter().cloned().fold(f64::MIN, f64::max)
|
||||
- xs.iter().cloned().fold(f64::MAX, f64::min);
|
||||
let h = ys.iter().cloned().fold(f64::MIN, f64::max)
|
||||
- ys.iter().cloned().fold(f64::MAX, f64::min);
|
||||
(cx, cy, w.max(0.0), h.max(0.0))
|
||||
} else {
|
||||
(cx, cy, 0.0, 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_element_text(
|
||||
client: &CdpClient,
|
||||
session_id: &str,
|
||||
|
||||
@@ -0,0 +1,517 @@
|
||||
//! Human-like input behaviour for stealth.
|
||||
//!
|
||||
//! When agent-browser drives a real Chrome over CDP, the input events it
|
||||
//! dispatches are already `isTrusted` — but a click that teleports the cursor
|
||||
//! straight to an element's exact centre, with no approach path and zero delay
|
||||
//! between move/press/release, is a behavioural tell that advanced anti-bot
|
||||
//! vendors (Akamai, PerimeterX, DataDome) look for.
|
||||
//!
|
||||
//! This module produces **human-like motion plans** — curved, eased cursor
|
||||
//! trajectories and variable keystroke timing — as *pure data*. It performs no
|
||||
//! I/O and knows nothing about CDP: callers turn the returned steps into
|
||||
//! `Input.dispatchMouseEvent` / `dispatchKeyEvent` calls. Keeping the maths pure
|
||||
//! makes the easing/jitter/detection logic unit-testable and deterministic
|
||||
//! (every randomised value comes from a caller-supplied seed).
|
||||
//!
|
||||
//! Design (see brainstorm 2026-06-11):
|
||||
//! - Three levels: [`HumanizeLevel::Off`] (instant, today's behaviour),
|
||||
//! `Fast` (a few cheap eased steps), `Human` (full curved trajectory + jitter).
|
||||
//! - Baseline is `Off`; the daemon escalates a session to `Human` when
|
||||
//! [`detect_level`] spots a known anti-bot vendor on the page. `--humanize` /
|
||||
//! `AGENT_BROWSER_HUMANIZE` force a fixed level.
|
||||
//! - Humanization only changes *how* the cursor reaches a target, never *which*
|
||||
//! element is hit: the landing jitter stays inside the caller-provided bounds.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
// ---- daemon-wide runtime state -------------------------------------------
|
||||
//
|
||||
// The pure motion maths above are stateless. The daemon drives one active page
|
||||
// at a time, so we keep the *current* humanize level and last cursor position
|
||||
// in process-global slots rather than threading them through every call site.
|
||||
// (The adaptive detector flips the level per navigation; `dispatch_click` reads
|
||||
// the level + cursor here, so no signature in the click/type call graph has to
|
||||
// change.)
|
||||
|
||||
/// `AGENT_BROWSER_HUMANIZE` forces a fixed level, overriding the adaptive
|
||||
/// detector. Parsed once.
|
||||
fn env_override() -> Option<HumanizeLevel> {
|
||||
static OVERRIDE: OnceLock<Option<HumanizeLevel>> = OnceLock::new();
|
||||
*OVERRIDE.get_or_init(|| {
|
||||
std::env::var("AGENT_BROWSER_HUMANIZE")
|
||||
.ok()
|
||||
.and_then(|s| HumanizeLevel::parse(&s))
|
||||
})
|
||||
}
|
||||
|
||||
fn session_level() -> &'static Mutex<HumanizeLevel> {
|
||||
static LEVEL: OnceLock<Mutex<HumanizeLevel>> = OnceLock::new();
|
||||
LEVEL.get_or_init(|| Mutex::new(HumanizeLevel::Off))
|
||||
}
|
||||
|
||||
fn last_cursor_slot() -> &'static Mutex<(f64, f64)> {
|
||||
static CURSOR: OnceLock<Mutex<(f64, f64)>> = OnceLock::new();
|
||||
CURSOR.get_or_init(|| Mutex::new((0.0, 0.0)))
|
||||
}
|
||||
|
||||
/// The level that should apply right now: the env override if set, else the
|
||||
/// level the detector last chose for the active page.
|
||||
pub fn active_level() -> HumanizeLevel {
|
||||
env_override().unwrap_or_else(|| *session_level().lock().unwrap())
|
||||
}
|
||||
|
||||
/// Set by the adaptive detector after navigation. Ignored while an env override
|
||||
/// is in force (so `--humanize` always wins).
|
||||
pub fn set_detected_level(level: HumanizeLevel) {
|
||||
*session_level().lock().unwrap() = level;
|
||||
}
|
||||
|
||||
/// Where the virtual cursor currently sits, so the next move starts from there
|
||||
/// instead of teleporting.
|
||||
pub fn last_cursor() -> (f64, f64) {
|
||||
*last_cursor_slot().lock().unwrap()
|
||||
}
|
||||
|
||||
/// Record the cursor landing point after a move/click.
|
||||
pub fn set_last_cursor(p: (f64, f64)) {
|
||||
*last_cursor_slot().lock().unwrap() = p;
|
||||
}
|
||||
|
||||
/// A fresh seed per action so repeated clicks on the same point still vary,
|
||||
/// without touching the wall clock or a global RNG (both would break replay).
|
||||
pub fn next_seed() -> u64 {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0x1234_5678);
|
||||
COUNTER
|
||||
.fetch_add(0x9E37_79B9_7F4A_7C15, Ordering::Relaxed)
|
||||
.rotate_left(17)
|
||||
}
|
||||
|
||||
/// How human-like input motion should be.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum HumanizeLevel {
|
||||
/// Instant: a single move to the exact point, no delays. Original behaviour.
|
||||
#[default]
|
||||
Off,
|
||||
/// A few eased steps with small delays — cheap cover for ordinary sites.
|
||||
Fast,
|
||||
/// Full curved, decelerating trajectory with landing jitter and press
|
||||
/// dwell — for pages guarded by behavioural anti-bot systems.
|
||||
Human,
|
||||
}
|
||||
|
||||
impl HumanizeLevel {
|
||||
/// Parse a user-supplied level (`--humanize` / `AGENT_BROWSER_HUMANIZE`).
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"off" | "none" | "instant" | "0" => Some(Self::Off),
|
||||
"fast" | "light" | "low" => Some(Self::Fast),
|
||||
"human" | "full" | "high" | "max" => Some(Self::Human),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_off(self) -> bool {
|
||||
matches!(self, Self::Off)
|
||||
}
|
||||
}
|
||||
|
||||
/// One step of a humanized cursor move: dispatch `mouseMoved` to (`x`, `y`),
|
||||
/// then sleep for `delay` before the next step. The final step's point is where
|
||||
/// the press/release should land.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MoveStep {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub delay: Duration,
|
||||
}
|
||||
|
||||
/// Tiny deterministic PRNG (xorshift64*). Seeded by the caller so trajectories
|
||||
/// are reproducible in tests; we avoid pulling in the `rand` crate and never
|
||||
/// call a wall-clock/global RNG (which would also break workflow replay).
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn new(seed: u64) -> Self {
|
||||
// Avoid the zero state, which xorshift cannot escape.
|
||||
Rng(seed ^ 0x9E37_79B9_7F4A_7C15)
|
||||
}
|
||||
|
||||
fn next_u64(&mut self) -> u64 {
|
||||
let mut x = self.0;
|
||||
x ^= x >> 12;
|
||||
x ^= x << 25;
|
||||
x ^= x >> 27;
|
||||
self.0 = x;
|
||||
x.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
|
||||
/// Uniform in [0, 1).
|
||||
fn unit(&mut self) -> f64 {
|
||||
// Top 53 bits → f64 mantissa.
|
||||
(self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
|
||||
/// Uniform in [-1, 1).
|
||||
fn signed(&mut self) -> f64 {
|
||||
self.unit() * 2.0 - 1.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Smootherstep ease (zero velocity at both ends) — used to bias the per-step
|
||||
/// timing so the cursor accelerates away from the start and decelerates into
|
||||
/// the target, the way a hand does.
|
||||
fn ease(t: f64) -> f64 {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
t * t * t * (t * (t * 6.0 - 15.0) + 10.0)
|
||||
}
|
||||
|
||||
/// Cubic Bézier point at parameter `t`.
|
||||
fn bezier(p0: (f64, f64), p1: (f64, f64), p2: (f64, f64), p3: (f64, f64), t: f64) -> (f64, f64) {
|
||||
let u = 1.0 - t;
|
||||
let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
|
||||
(
|
||||
a * p0.0 + b * p1.0 + c * p2.0 + d * p3.0,
|
||||
a * p0.1 + b * p1.1 + c * p2.1 + d * p3.1,
|
||||
)
|
||||
}
|
||||
|
||||
/// Pick a landing point inside `bbox` (`x`, `y`, `width`, `height`). `Off`
|
||||
/// returns the exact centre; `Fast`/`Human` jitter around the centre but stay
|
||||
/// well inside the element so the click still lands on it.
|
||||
pub fn landing_point(bbox: (f64, f64, f64, f64), level: HumanizeLevel, seed: u64) -> (f64, f64) {
|
||||
let (bx, by, bw, bh) = bbox;
|
||||
let cx = bx + bw / 2.0;
|
||||
let cy = by + bh / 2.0;
|
||||
if level.is_off() || bw <= 1.0 || bh <= 1.0 {
|
||||
return (cx, cy);
|
||||
}
|
||||
// Keep within the inner 60% so jitter never lands on a neighbouring element
|
||||
// or the element's padding/edge.
|
||||
let spread = match level {
|
||||
HumanizeLevel::Human => 0.30,
|
||||
_ => 0.15,
|
||||
};
|
||||
let mut rng = Rng::new(seed);
|
||||
(
|
||||
cx + rng.signed() * bw * spread,
|
||||
cy + rng.signed() * bh * spread,
|
||||
)
|
||||
}
|
||||
|
||||
/// Build the cursor path from `from` to `to`. The last [`MoveStep`] is the
|
||||
/// landing point. `Off` yields a single zero-delay step at `to` (today's
|
||||
/// teleport), so callers can use one code path for every level.
|
||||
pub fn move_path(
|
||||
from: (f64, f64),
|
||||
to: (f64, f64),
|
||||
level: HumanizeLevel,
|
||||
seed: u64,
|
||||
) -> Vec<MoveStep> {
|
||||
if level.is_off() {
|
||||
return vec![MoveStep {
|
||||
x: to.0,
|
||||
y: to.1,
|
||||
delay: Duration::ZERO,
|
||||
}];
|
||||
}
|
||||
|
||||
let dist = (to.0 - from.0).hypot(to.1 - from.1);
|
||||
if dist < 1.0 {
|
||||
return vec![MoveStep {
|
||||
x: to.0,
|
||||
y: to.1,
|
||||
delay: Duration::ZERO,
|
||||
}];
|
||||
}
|
||||
|
||||
let (steps, total_ms, arc) = match level {
|
||||
HumanizeLevel::Fast => {
|
||||
let s = ((dist / 120.0).round() as usize).clamp(3, 6);
|
||||
(s, (dist * 0.35).clamp(40.0, 130.0), 0.06)
|
||||
}
|
||||
// Off handled above.
|
||||
_ => {
|
||||
let s = ((dist / 45.0).round() as usize).clamp(8, 24);
|
||||
(s, (dist * 0.9).clamp(140.0, 650.0), 0.16)
|
||||
}
|
||||
};
|
||||
|
||||
let mut rng = Rng::new(seed);
|
||||
|
||||
// Two control points along the line, pushed perpendicular to it to bow the
|
||||
// path into a gentle, slightly asymmetric arc.
|
||||
let (dx, dy) = (to.0 - from.0, to.1 - from.1);
|
||||
let (nx, ny) = (-dy / dist, dx / dist); // unit normal
|
||||
let bow = dist * arc * rng.signed();
|
||||
let ctrl = |frac: f64, jitter: f64, rng: &mut Rng| {
|
||||
let base = (from.0 + dx * frac, from.1 + dy * frac);
|
||||
let off = bow * (1.0 + jitter * rng.signed());
|
||||
(base.0 + nx * off, base.1 + ny * off)
|
||||
};
|
||||
let p1 = ctrl(0.33, 0.4, &mut rng);
|
||||
let p2 = ctrl(0.66, 0.4, &mut rng);
|
||||
|
||||
let mut out = Vec::with_capacity(steps);
|
||||
let mut prev_ease = 0.0;
|
||||
for i in 1..=steps {
|
||||
let t = i as f64 / steps as f64;
|
||||
// Ease maps wall-time progress so most points cluster near the ends
|
||||
// (slow start, slow finish, fast middle).
|
||||
let te = ease(t);
|
||||
let (x, y) = bezier(from, p1, p2, to, te);
|
||||
let frac = te - prev_ease;
|
||||
prev_ease = te;
|
||||
out.push(MoveStep {
|
||||
x,
|
||||
y,
|
||||
delay: Duration::from_micros((total_ms * frac * 1000.0).max(0.0) as u64),
|
||||
});
|
||||
}
|
||||
// Guarantee the final point is exactly the target.
|
||||
if let Some(last) = out.last_mut() {
|
||||
last.x = to.0;
|
||||
last.y = to.1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Split a wheel scroll of (`total_dx`, `total_dy`) into eased segments. `Off`
|
||||
/// returns a single instant segment (today's one-shot scroll); `Fast`/`Human`
|
||||
/// break it into several accelerate-then-decelerate chunks with small,
|
||||
/// jittered inter-segment delays, the way a trackpad/wheel flick actually
|
||||
/// lands. The segment deltas always sum to the requested total.
|
||||
pub fn scroll_segments(
|
||||
total_dx: f64,
|
||||
total_dy: f64,
|
||||
level: HumanizeLevel,
|
||||
seed: u64,
|
||||
) -> Vec<(f64, f64, Duration)> {
|
||||
if level.is_off() {
|
||||
return vec![(total_dx, total_dy, Duration::ZERO)];
|
||||
}
|
||||
let (segs, base_ms) = match level {
|
||||
HumanizeLevel::Fast => (4usize, 18.0),
|
||||
_ => (9usize, 28.0),
|
||||
};
|
||||
let mut rng = Rng::new(seed);
|
||||
let mut out = Vec::with_capacity(segs);
|
||||
let mut prev = 0.0;
|
||||
for i in 1..=segs {
|
||||
let f = ease(i as f64 / segs as f64);
|
||||
let frac = f - prev;
|
||||
prev = f;
|
||||
let jitter = 1.0 + 0.3 * rng.signed();
|
||||
out.push((
|
||||
total_dx * frac,
|
||||
total_dy * frac,
|
||||
Duration::from_millis((base_ms * jitter).max(4.0) as u64),
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Dwell between `mousePressed` and `mouseReleased` (a real click isn't
|
||||
/// instantaneous). Zero for `Off`.
|
||||
pub fn press_dwell(level: HumanizeLevel, seed: u64) -> Duration {
|
||||
match level {
|
||||
HumanizeLevel::Off => Duration::ZERO,
|
||||
HumanizeLevel::Fast => Duration::from_millis(20 + (seed % 30)),
|
||||
HumanizeLevel::Human => Duration::from_millis(50 + (seed % 90)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-character delays for typing `len` characters. `Off` is all-zero (use a
|
||||
/// single `Input.insertText`); `Fast`/`Human` produce variable inter-keystroke
|
||||
/// gaps with the occasional longer "think" pause, like a real typist.
|
||||
pub fn keystroke_delays(len: usize, level: HumanizeLevel, seed: u64) -> Vec<Duration> {
|
||||
if level.is_off() || len == 0 {
|
||||
return vec![Duration::ZERO; len];
|
||||
}
|
||||
let (mean, jitter, pause_chance, pause_extra) = match level {
|
||||
HumanizeLevel::Fast => (25.0, 15.0, 0.0, 0.0),
|
||||
_ => (95.0, 55.0, 0.06, 220.0),
|
||||
};
|
||||
let mut rng = Rng::new(seed);
|
||||
(0..len)
|
||||
.map(|_| {
|
||||
let mut ms = (mean + rng.signed() * jitter).max(8.0);
|
||||
if pause_chance > 0.0 && rng.unit() < pause_chance {
|
||||
ms += rng.unit() * pause_extra;
|
||||
}
|
||||
Duration::from_millis(ms as u64)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Page signals sampled after navigation, used to decide whether to escalate a
|
||||
/// session to [`HumanizeLevel::Human`]. All strings are matched case-insensitively.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct DetectSignals {
|
||||
/// Cookie names present on the document (e.g. `_abck`, `datadome`).
|
||||
pub cookie_names: Vec<String>,
|
||||
/// `src` of loaded scripts.
|
||||
pub script_urls: Vec<String>,
|
||||
/// Names of suspicious globals on `window` (e.g. `_px`, `bmak`).
|
||||
pub window_globals: Vec<String>,
|
||||
}
|
||||
|
||||
/// Known behavioural anti-bot fingerprints: (substring, vendor). Matched against
|
||||
/// cookie names, script URLs, and window globals.
|
||||
const VENDOR_MARKERS: &[(&str, &str)] = &[
|
||||
("_abck", "akamai"),
|
||||
("bm_sz", "akamai"),
|
||||
("ak_bmsc", "akamai"),
|
||||
("bmak", "akamai"),
|
||||
("_px", "perimeterx"),
|
||||
("perimeterx", "perimeterx"),
|
||||
("px-cloud", "perimeterx"),
|
||||
("datadome", "datadome"),
|
||||
("kpsdk", "kasada"),
|
||||
("incap_ses", "imperva"),
|
||||
("visid_incap", "imperva"),
|
||||
("reese84", "imperva"),
|
||||
("__cf_bm", "cloudflare-bot-mgmt"),
|
||||
];
|
||||
|
||||
/// Decide the level for a page. Returns `Human` if any known anti-bot vendor is
|
||||
/// present, otherwise `baseline`. Misses just stay at baseline and false hits
|
||||
/// only cost a little latency, so matching is deliberately liberal.
|
||||
pub fn detect_level(signals: &DetectSignals, baseline: HumanizeLevel) -> HumanizeLevel {
|
||||
let hay: Vec<String> = signals
|
||||
.cookie_names
|
||||
.iter()
|
||||
.chain(signals.script_urls.iter())
|
||||
.chain(signals.window_globals.iter())
|
||||
.map(|s| s.to_ascii_lowercase())
|
||||
.collect();
|
||||
let matched = VENDOR_MARKERS
|
||||
.iter()
|
||||
.any(|(marker, _)| hay.iter().any(|h| h.contains(marker)));
|
||||
if matched {
|
||||
HumanizeLevel::Human
|
||||
} else {
|
||||
baseline
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_accepts_known_levels_and_rejects_junk() {
|
||||
assert_eq!(HumanizeLevel::parse("off"), Some(HumanizeLevel::Off));
|
||||
assert_eq!(HumanizeLevel::parse(" FAST "), Some(HumanizeLevel::Fast));
|
||||
assert_eq!(HumanizeLevel::parse("Human"), Some(HumanizeLevel::Human));
|
||||
assert_eq!(HumanizeLevel::parse("max"), Some(HumanizeLevel::Human));
|
||||
assert_eq!(HumanizeLevel::parse("wat"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_level_teleports_in_one_step() {
|
||||
let path = move_path((0.0, 0.0), (100.0, 50.0), HumanizeLevel::Off, 1);
|
||||
assert_eq!(path.len(), 1);
|
||||
assert_eq!((path[0].x, path[0].y), (100.0, 50.0));
|
||||
assert_eq!(path[0].delay, Duration::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn humanized_path_is_multi_step_and_lands_exactly_on_target() {
|
||||
let to = (640.0, 480.0);
|
||||
let path = move_path((10.0, 10.0), to, HumanizeLevel::Human, 42);
|
||||
assert!(path.len() >= 8, "human path should have many steps");
|
||||
let last = path.last().unwrap();
|
||||
assert_eq!((last.x, last.y), to, "final point must equal the target");
|
||||
// Path must actually leave the straight line at some point (it's a curve).
|
||||
let straight = path.iter().all(|s| {
|
||||
let t = (s.x - 10.0) / (to.0 - 10.0);
|
||||
(s.y - (10.0 + t * (to.1 - 10.0))).abs() < 0.5
|
||||
});
|
||||
assert!(!straight, "human path should bow off the straight line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_path_is_shorter_than_human() {
|
||||
let fast = move_path((0.0, 0.0), (500.0, 500.0), HumanizeLevel::Fast, 7);
|
||||
let human = move_path((0.0, 0.0), (500.0, 500.0), HumanizeLevel::Human, 7);
|
||||
assert!(fast.len() < human.len());
|
||||
assert!((3..=6).contains(&fast.len()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_path_is_deterministic_for_a_seed() {
|
||||
let a = move_path((1.0, 2.0), (300.0, 400.0), HumanizeLevel::Human, 99);
|
||||
let b = move_path((1.0, 2.0), (300.0, 400.0), HumanizeLevel::Human, 99);
|
||||
assert_eq!(a, b);
|
||||
let c = move_path((1.0, 2.0), (300.0, 400.0), HumanizeLevel::Human, 100);
|
||||
assert_ne!(a, c, "different seeds should differ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn landing_point_stays_inside_bounds_and_centres_when_off() {
|
||||
let bbox = (100.0, 100.0, 40.0, 20.0);
|
||||
assert_eq!(landing_point(bbox, HumanizeLevel::Off, 1), (120.0, 110.0));
|
||||
for seed in 0..200 {
|
||||
let (x, y) = landing_point(bbox, HumanizeLevel::Human, seed);
|
||||
assert!(x > 100.0 && x < 140.0, "x {x} escaped bbox");
|
||||
assert!(y > 100.0 && y < 120.0, "y {y} escaped bbox");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keystroke_delays_zero_when_off_and_positive_otherwise() {
|
||||
assert!(keystroke_delays(5, HumanizeLevel::Off, 1)
|
||||
.iter()
|
||||
.all(|d| *d == Duration::ZERO));
|
||||
let human = keystroke_delays(20, HumanizeLevel::Human, 3);
|
||||
assert_eq!(human.len(), 20);
|
||||
assert!(human.iter().all(|d| *d >= Duration::from_millis(8)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scroll_segments_sum_to_total_and_single_when_off() {
|
||||
let off = scroll_segments(0.0, 600.0, HumanizeLevel::Off, 1);
|
||||
assert_eq!(off.len(), 1);
|
||||
assert_eq!((off[0].0, off[0].1), (0.0, 600.0));
|
||||
assert_eq!(off[0].2, Duration::ZERO);
|
||||
|
||||
let human = scroll_segments(0.0, 600.0, HumanizeLevel::Human, 5);
|
||||
assert!(human.len() >= 5);
|
||||
let total_dy: f64 = human.iter().map(|s| s.1).sum();
|
||||
assert!(
|
||||
(total_dy - 600.0).abs() < 1e-6,
|
||||
"segments must sum to total"
|
||||
);
|
||||
assert!(human.iter().all(|s| s.2 >= Duration::from_millis(4)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detect_escalates_on_known_vendor_else_baseline() {
|
||||
let mut s = DetectSignals::default();
|
||||
assert_eq!(detect_level(&s, HumanizeLevel::Off), HumanizeLevel::Off);
|
||||
|
||||
s.cookie_names = vec!["sessionid".into(), "_abck".into()];
|
||||
assert_eq!(detect_level(&s, HumanizeLevel::Off), HumanizeLevel::Human);
|
||||
|
||||
let s2 = DetectSignals {
|
||||
script_urls: vec!["https://cdn.example.com/DataDome-tags.js".into()],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(detect_level(&s2, HumanizeLevel::Off), HumanizeLevel::Human);
|
||||
|
||||
let s3 = DetectSignals {
|
||||
window_globals: vec!["_pxAppId".into()],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(detect_level(&s3, HumanizeLevel::Fast), HumanizeLevel::Human);
|
||||
|
||||
// Unknown signals keep the baseline.
|
||||
let s4 = DetectSignals {
|
||||
cookie_names: vec!["cart".into(), "theme".into()],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(detect_level(&s4, HumanizeLevel::Fast), HumanizeLevel::Fast);
|
||||
}
|
||||
}
|
||||
+143
-27
@@ -4,7 +4,8 @@ use serde_json::Value;
|
||||
|
||||
use super::cdp::client::CdpClient;
|
||||
use super::cdp::types::*;
|
||||
use super::element::{resolve_element_center, resolve_element_object_id, RefMap};
|
||||
use super::element::{parse_ref, resolve_element_center, resolve_element_object_id, RefMap};
|
||||
use super::humanize;
|
||||
|
||||
pub async fn click(
|
||||
client: &CdpClient,
|
||||
@@ -54,8 +55,42 @@ pub async fn click(
|
||||
.await;
|
||||
|
||||
match resolved {
|
||||
Ok((x, y, effective_session_id)) => {
|
||||
dispatch_click(client, &effective_session_id, x, y, button, click_count).await
|
||||
Ok((cx, cy, w, h, effective_session_id)) => {
|
||||
// Occlusion guard for the CSS-selector path. `@ref` clicks are already
|
||||
// occlusion-checked in resolve_element_center, but a plain selector
|
||||
// resolves to coordinates without that check — so an overlay (modal
|
||||
// backdrop, sticky banner, the getByText located node sitting under a
|
||||
// full-screen layer) would make the coordinate click land on the
|
||||
// overlay and still report success. If the click point doesn't hit the
|
||||
// target, dispatch through the DOM instead (targets the element
|
||||
// directly). Skipped for strict `coord` mode and non-left/multi-clicks.
|
||||
if mode != "coord"
|
||||
&& button == "left"
|
||||
&& click_count == 1
|
||||
&& parse_ref(selector_or_ref).is_none()
|
||||
&& point_misses_element(client, &effective_session_id, selector_or_ref).await
|
||||
{
|
||||
eprintln!(
|
||||
"[click] target occluded at its click point; dispatching through \
|
||||
the DOM (set AGENT_BROWSER_CLICK_MODE=coord to disable)"
|
||||
);
|
||||
return dom_click(
|
||||
client,
|
||||
session_id,
|
||||
ref_map,
|
||||
selector_or_ref,
|
||||
iframe_sessions,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
// Land on a jittered point inside the element rather than its exact
|
||||
// centre (Fast/Human). Zero size or Off → exact centre.
|
||||
let (tx, ty) = humanize::landing_point(
|
||||
(cx - w / 2.0, cy - h / 2.0, w, h),
|
||||
humanize::active_level(),
|
||||
humanize::next_seed(),
|
||||
);
|
||||
dispatch_click(client, &effective_session_id, tx, ty, button, click_count).await
|
||||
}
|
||||
Err(e) => {
|
||||
// (B) The coordinate path failed — typically a persistent overlay
|
||||
@@ -84,6 +119,42 @@ pub async fn click(
|
||||
}
|
||||
}
|
||||
|
||||
/// True if a coordinate click at the selector's centre would land on something
|
||||
/// OTHER than the element (an overlay on top), i.e. the element is occluded.
|
||||
/// `false` when not occluded, the element is missing, or the probe fails (so we
|
||||
/// never block a click on a flaky probe — the normal coordinate path runs).
|
||||
async fn point_misses_element(client: &CdpClient, session_id: &str, selector: &str) -> bool {
|
||||
let js = format!(
|
||||
r#"(() => {{
|
||||
const el = document.querySelector({sel});
|
||||
if (!el) return false;
|
||||
const r = el.getBoundingClientRect();
|
||||
if (r.width === 0 || r.height === 0) return false;
|
||||
const hit = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2);
|
||||
if (!hit) return false;
|
||||
// Not occluded if the hit is the element, a descendant, or an ancestor
|
||||
// wrapper (clicking those still reaches the element's handlers).
|
||||
return !(hit === el || el.contains(hit) || hit.contains(el));
|
||||
}})()"#,
|
||||
sel = serde_json::to_string(selector).unwrap_or_default()
|
||||
);
|
||||
match client
|
||||
.send_command_typed::<_, EvaluateResult>(
|
||||
"Runtime.evaluate",
|
||||
&EvaluateParams {
|
||||
expression: js,
|
||||
return_by_value: Some(true),
|
||||
await_promise: Some(false),
|
||||
},
|
||||
Some(session_id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(r) => r.result.value.and_then(|v| v.as_bool()).unwrap_or(false),
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Best-effort scroll-into-view before a coordinate click. Uses Chrome's
|
||||
/// `scrollIntoViewIfNeeded` (only scrolls when not already fully visible),
|
||||
/// falling back to centered `scrollIntoView`. Resolution failures are ignored —
|
||||
@@ -190,7 +261,7 @@ pub async fn hover(
|
||||
selector_or_ref: &str,
|
||||
iframe_sessions: &HashMap<String, String>,
|
||||
) -> Result<(), String> {
|
||||
let (x, y, effective_session_id) = resolve_element_center(
|
||||
let (x, y, _w, _h, effective_session_id) = resolve_element_center(
|
||||
client,
|
||||
session_id,
|
||||
ref_map,
|
||||
@@ -349,9 +420,18 @@ pub async fn type_text_into_active_context(
|
||||
text: &str,
|
||||
delay_ms: Option<u64>,
|
||||
) -> Result<(), String> {
|
||||
let delay = delay_ms.unwrap_or(0);
|
||||
// Per-character timing: an explicit `delay_ms` wins (caller asked for a
|
||||
// fixed cadence); otherwise fall back to humanize — variable, human-like
|
||||
// inter-keystroke gaps at Fast/Human, all-zero (instant) at Off.
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let cadence: Vec<std::time::Duration> = match delay_ms {
|
||||
Some(d) => vec![std::time::Duration::from_millis(d); chars.len()],
|
||||
None => {
|
||||
humanize::keystroke_delays(chars.len(), humanize::active_level(), humanize::next_seed())
|
||||
}
|
||||
};
|
||||
|
||||
for ch in text.chars() {
|
||||
for (i, ch) in chars.into_iter().enumerate() {
|
||||
if matches!(ch, '\n' | '\r' | '\t') {
|
||||
let (key, code, key_code) = char_to_key_info(ch);
|
||||
let text_str = key_text(&key);
|
||||
@@ -403,8 +483,9 @@ pub async fn type_text_into_active_context(
|
||||
.await?;
|
||||
}
|
||||
|
||||
if delay > 0 {
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(delay)).await;
|
||||
let gap = cadence[i];
|
||||
if !gap.is_zero() {
|
||||
tokio::time::sleep(gap).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -988,7 +1069,7 @@ pub async fn tap_touch(
|
||||
selector_or_ref: &str,
|
||||
iframe_sessions: &HashMap<String, String>,
|
||||
) -> Result<(), String> {
|
||||
let (x, y, effective_session_id) = resolve_element_center(
|
||||
let (x, y, _w, _h, effective_session_id) = resolve_element_center(
|
||||
client,
|
||||
session_id,
|
||||
ref_map,
|
||||
@@ -1062,6 +1143,20 @@ async fn wait_for_paint_settled(client: &CdpClient, session_id: &str) {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Click at a raw viewport coordinate, bypassing element/selector resolution
|
||||
/// (issue #8.4 first-class coordinate click). Honors the humanize trajectory and
|
||||
/// press dwell exactly like a selector click — it shares `dispatch_click`.
|
||||
pub async fn click_at_point(
|
||||
client: &CdpClient,
|
||||
session_id: &str,
|
||||
x: f64,
|
||||
y: f64,
|
||||
button: &str,
|
||||
click_count: i32,
|
||||
) -> Result<(), String> {
|
||||
dispatch_click(client, session_id, x, y, button, click_count).await
|
||||
}
|
||||
|
||||
async fn dispatch_click(
|
||||
client: &CdpClient,
|
||||
session_id: &str,
|
||||
@@ -1070,24 +1165,38 @@ async fn dispatch_click(
|
||||
button: &str,
|
||||
click_count: i32,
|
||||
) -> Result<(), String> {
|
||||
// Move
|
||||
client
|
||||
.send_command_typed::<_, Value>(
|
||||
"Input.dispatchMouseEvent",
|
||||
&DispatchMouseEventParams {
|
||||
event_type: "mouseMoved".to_string(),
|
||||
x,
|
||||
y,
|
||||
button: None,
|
||||
buttons: None,
|
||||
click_count: None,
|
||||
delta_x: None,
|
||||
delta_y: None,
|
||||
modifiers: None,
|
||||
},
|
||||
Some(session_id),
|
||||
)
|
||||
.await?;
|
||||
// Move toward the target along a human-like path. At HumanizeLevel::Off this
|
||||
// is a single zero-delay step to (x, y) — identical to the old teleport — so
|
||||
// the default behaviour is unchanged. At Fast/Human it's a curved,
|
||||
// decelerating trajectory starting from where the cursor last landed, which
|
||||
// removes the "instant jump to exact centre, no prior movement" tell that
|
||||
// behavioural anti-bot systems flag.
|
||||
let level = humanize::active_level();
|
||||
let start = humanize::last_cursor();
|
||||
let seed = humanize::next_seed();
|
||||
for step in humanize::move_path(start, (x, y), level, seed) {
|
||||
client
|
||||
.send_command_typed::<_, Value>(
|
||||
"Input.dispatchMouseEvent",
|
||||
&DispatchMouseEventParams {
|
||||
event_type: "mouseMoved".to_string(),
|
||||
x: step.x,
|
||||
y: step.y,
|
||||
button: None,
|
||||
buttons: None,
|
||||
click_count: None,
|
||||
delta_x: None,
|
||||
delta_y: None,
|
||||
modifiers: None,
|
||||
},
|
||||
Some(session_id),
|
||||
)
|
||||
.await?;
|
||||
if !step.delay.is_zero() {
|
||||
tokio::time::sleep(step.delay).await;
|
||||
}
|
||||
}
|
||||
humanize::set_last_cursor((x, y));
|
||||
|
||||
let button_value = match button {
|
||||
"right" => 2,
|
||||
@@ -1114,6 +1223,13 @@ async fn dispatch_click(
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Hold briefly before releasing — a real click isn't instantaneous. Zero at
|
||||
// HumanizeLevel::Off.
|
||||
let dwell = humanize::press_dwell(level, seed);
|
||||
if !dwell.is_zero() {
|
||||
tokio::time::sleep(dwell).await;
|
||||
}
|
||||
|
||||
// Release
|
||||
client
|
||||
.send_command_typed::<_, Value>(
|
||||
|
||||
@@ -17,6 +17,8 @@ pub mod diff;
|
||||
#[allow(dead_code)]
|
||||
pub mod element;
|
||||
#[allow(dead_code)]
|
||||
pub mod humanize;
|
||||
#[allow(dead_code)]
|
||||
pub mod inspect_server;
|
||||
#[allow(dead_code)]
|
||||
pub mod interaction;
|
||||
|
||||
@@ -1305,6 +1305,39 @@ fn render_tree(
|
||||
}
|
||||
}
|
||||
|
||||
/// True if a snapshot line names an interactive ARIA role. Compaction keeps
|
||||
/// these even without a `ref=`/`": "` marker, so a clickable control never gets
|
||||
/// dropped from `-c` output (the dogfood reports saw a button present in the full
|
||||
/// snapshot vanish from compact, leaving the agent clicking an empty ref).
|
||||
fn is_interactive_line(line: &str) -> bool {
|
||||
const ROLES: &[&str] = &[
|
||||
"button",
|
||||
"link",
|
||||
"textbox",
|
||||
"checkbox",
|
||||
"radio",
|
||||
"combobox",
|
||||
"listbox",
|
||||
"menuitem",
|
||||
"menuitemcheckbox",
|
||||
"menuitemradio",
|
||||
"option",
|
||||
"switch",
|
||||
"slider",
|
||||
"spinbutton",
|
||||
"searchbox",
|
||||
"tab ",
|
||||
"clickable",
|
||||
"focusable",
|
||||
"editable",
|
||||
];
|
||||
let t = line.trim_start();
|
||||
// Lines look like `- button "Label" [ref=e1]`; match the role token after the
|
||||
// leading "- " marker.
|
||||
let t = t.strip_prefix("- ").unwrap_or(t);
|
||||
ROLES.iter().any(|r| t.starts_with(r))
|
||||
}
|
||||
|
||||
fn compact_tree(tree: &str, interactive: bool) -> String {
|
||||
let lines: Vec<&str> = tree.lines().collect();
|
||||
if lines.is_empty() {
|
||||
@@ -1314,7 +1347,7 @@ fn compact_tree(tree: &str, interactive: bool) -> String {
|
||||
let mut keep = vec![false; lines.len()];
|
||||
|
||||
for (i, line) in lines.iter().enumerate() {
|
||||
if line.contains("ref=") || line.contains(": ") {
|
||||
if line.contains("ref=") || line.contains(": ") || is_interactive_line(line) {
|
||||
keep[i] = true;
|
||||
// Mark ancestors
|
||||
let my_indent = count_indent(line);
|
||||
|
||||
@@ -121,6 +121,7 @@ async fn collect_storage_via_temp_target(
|
||||
url: "about:blank".to_string(),
|
||||
// Transient internal target (storage collection) — never grouped.
|
||||
agent_group: None,
|
||||
background: None,
|
||||
},
|
||||
None,
|
||||
)
|
||||
|
||||
@@ -51,18 +51,19 @@ pub fn build_stealth_script(mode: StealthMode, locale: Option<&str>) -> String {
|
||||
vec![locale, base_lang]
|
||||
};
|
||||
let config_line = format!(
|
||||
r#"const __abStealth = {{ locale: "{}", languages: {}, allowWebGLContextFallback: false, hideCanvas: {}, canvasSeed: {} }};"#,
|
||||
r#"const __abStealth = {{ locale: "{}", languages: {}, allowWebGLContextFallback: false, hideCanvas: {}, canvasSeed: {}, disableIframeProxy: {} }};"#,
|
||||
locale,
|
||||
serde_json::to_string(&languages).unwrap_or_else(|_| r#"["en-US","en"]"#.to_string()),
|
||||
hide_canvas_enabled(),
|
||||
canvas_noise_seed(),
|
||||
disable_iframe_proxy_enabled(),
|
||||
);
|
||||
|
||||
// NB: this prefix MUST match the first line of stealth_scripts.js verbatim,
|
||||
// otherwise the fallback below prepends a SECOND `const __abStealth`
|
||||
// declaration and the whole script dies with a redeclaration SyntaxError.
|
||||
if let Some(rest) = STEALTH_SCRIPTS_RAW.strip_prefix(
|
||||
r#"const __abStealth = { locale: "en-US", languages: ["en-US", "en"], allowWebGLContextFallback: false, hideCanvas: false, canvasSeed: 0 };"#,
|
||||
r#"const __abStealth = { locale: "en-US", languages: ["en-US", "en"], allowWebGLContextFallback: false, hideCanvas: false, canvasSeed: 0, disableIframeProxy: false };"#,
|
||||
) {
|
||||
format!("{}{}", config_line, rest)
|
||||
} else {
|
||||
@@ -81,6 +82,18 @@ fn hide_canvas_enabled() -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether to DROP the srcdoc-iframe `contentWindow` Proxy patch (FullLaunch).
|
||||
/// That patch masks automation in srcdoc iframes, but the JS `Proxy` is itself a
|
||||
/// fingerprintable tell (CreepJS `hasIframeProxy` → ~20% stealth). Off by default
|
||||
/// (keep the patch); `AGENT_BROWSER_DISABLE_IFRAME_PROXY=1` drops it for a clean
|
||||
/// 0% CreepJS at the cost of that niche srcdoc-iframe masking.
|
||||
fn disable_iframe_proxy_enabled() -> bool {
|
||||
std::env::var("AGENT_BROWSER_DISABLE_IFRAME_PROXY")
|
||||
.ok()
|
||||
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// A per-process seed so canvas/audio noise is STABLE within a session (a real
|
||||
/// device returns the same hash on repeated reads) but differs from the
|
||||
/// headless-stable default. 0 is avoided so the JS can treat it as "unset".
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
const __abStealth = { locale: "en-US", languages: ["en-US", "en"], allowWebGLContextFallback: false, hideCanvas: false, canvasSeed: 0 };
|
||||
const __abStealth = { locale: "en-US", languages: ["en-US", "en"], allowWebGLContextFallback: false, hideCanvas: false, canvasSeed: 0, disableIframeProxy: false };
|
||||
// Redefine a navigator property on its PROTOTYPE (Navigator / WorkerNavigator),
|
||||
// the way real Chrome exposes these — as prototype getters, NOT instance own
|
||||
// properties. Adding an own property to the `navigator` instance is itself a
|
||||
@@ -289,6 +289,10 @@ const __abRedefineNavProto = (name, getterImpl) => {
|
||||
})();
|
||||
(function(){
|
||||
if (typeof document === 'undefined' || typeof document.createElement !== 'function') return;
|
||||
// The srcdoc-iframe contentWindow Proxy below is itself a fingerprintable tell
|
||||
// (CreepJS `hasIframeProxy`). Honor the opt-out so callers can trade the niche
|
||||
// srcdoc masking for a clean 0% CreepJS fingerprint.
|
||||
if (typeof __abStealth !== 'undefined' && __abStealth.disableIframeProxy) return;
|
||||
const nativeCreateElement = document.createElement.bind(document);
|
||||
const nativeSrcdocDescriptor =
|
||||
typeof HTMLIFrameElement !== 'undefined'
|
||||
@@ -304,12 +308,39 @@ const __abRedefineNavProto = (name, getterImpl) => {
|
||||
try {
|
||||
if (iframe.contentWindow) return;
|
||||
} catch {}
|
||||
// Native window methods are bound to the real Window via an internal slot;
|
||||
// calling them with the Proxy as `this` throws "Illegal invocation". Wrap
|
||||
// each function in an apply/construct trap that swaps the Proxy receiver for
|
||||
// the real window, while passing `.prototype`/`.name`/`.toString`/identity
|
||||
// straight through (a plain `.bind()` would drop `.prototype` and break
|
||||
// `instanceof`). Cached so repeated reads return the same function.
|
||||
const fnProxyCache = new WeakMap();
|
||||
const bindToRealWindow = (fn) => {
|
||||
let wrapped = fnProxyCache.get(fn);
|
||||
if (wrapped) return wrapped;
|
||||
try {
|
||||
wrapped = new Proxy(fn, {
|
||||
apply(target, thisArg, args) {
|
||||
return Reflect.apply(target, thisArg === proxy ? window : thisArg, args);
|
||||
},
|
||||
construct(target, args, newTarget) {
|
||||
return Reflect.construct(target, args, newTarget);
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
wrapped = fn;
|
||||
}
|
||||
fnProxyCache.set(fn, wrapped);
|
||||
return wrapped;
|
||||
};
|
||||
const proxy = new Proxy(window, {
|
||||
get(target, key) {
|
||||
if (key === 'self') return proxy;
|
||||
if (key === 'frameElement') return iframe;
|
||||
if (key === '0') return undefined;
|
||||
return Reflect.get(target, key, target);
|
||||
const value = Reflect.get(target, key, target);
|
||||
if (typeof value === 'function') return bindToRealWindow(value);
|
||||
return value;
|
||||
},
|
||||
});
|
||||
iframeProxyMap.set(iframe, proxy);
|
||||
|
||||
+98
-1
@@ -130,6 +130,20 @@ fn format_stream_status_text(action: Option<&str>, data: &serde_json::Value) ->
|
||||
}
|
||||
}
|
||||
|
||||
/// Shorten an over-long string by keeping its head and tail and eliding the
|
||||
/// middle, with a char count. Used so multi-KB URLs (JWT/OTP login links) don't
|
||||
/// flood `tab list`.
|
||||
fn truncate_middle(s: &str, max: usize) -> String {
|
||||
let n = s.chars().count();
|
||||
if n <= max {
|
||||
return s.to_string();
|
||||
}
|
||||
let keep = max.saturating_sub(1) / 2;
|
||||
let head: String = s.chars().take(keep).collect();
|
||||
let tail: String = s.chars().skip(n - keep).collect();
|
||||
format!("{head}…{tail} [{n} chars]")
|
||||
}
|
||||
|
||||
pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &OutputOptions) {
|
||||
if opts.json {
|
||||
if opts.content_boundaries {
|
||||
@@ -338,12 +352,55 @@ pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &Ou
|
||||
println!("{}", enabled);
|
||||
return;
|
||||
}
|
||||
// Stealth self-check (`stealth status` / `doctor`)
|
||||
if let Some(s) = data.get("stealthStatus") {
|
||||
let ok = s.get("ok").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let mode = s.get("mode").and_then(|v| v.as_str()).unwrap_or("?");
|
||||
println!(
|
||||
"{} stealth: {} · mode: {}",
|
||||
if ok {
|
||||
color::success_indicator().to_string()
|
||||
} else {
|
||||
color::cyan("•")
|
||||
},
|
||||
if ok {
|
||||
"all checks pass"
|
||||
} else {
|
||||
"some checks need attention"
|
||||
},
|
||||
mode
|
||||
);
|
||||
if let Some(checks) = s.get("checks").and_then(|v| v.as_array()) {
|
||||
for c in checks {
|
||||
let pass = c.get("pass").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let name = c.get("name").and_then(|v| v.as_str()).unwrap_or("");
|
||||
println!(" {} {}", if pass { "✓" } else { "✗" }, name);
|
||||
}
|
||||
}
|
||||
if let Some(ovs) = s.get("overrides").and_then(|v| v.as_array()) {
|
||||
println!(" applied overrides:");
|
||||
for o in ovs.iter().filter_map(|v| v.as_str()) {
|
||||
println!(" {}", color::dim(&format!("· {o}")));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(checked) = data.get("checked").and_then(|v| v.as_bool()) {
|
||||
println!("{}", checked);
|
||||
return;
|
||||
}
|
||||
// Eval result
|
||||
if let Some(result) = data.get("result") {
|
||||
// Surface which page the eval actually ran on — to stderr, so it
|
||||
// never corrupts the parsed value on stdout. Lets an agent catch tab
|
||||
// drift (commands landing on the wrong tab) before trusting a result,
|
||||
// e.g. a logged-in `fetch` that hit the wrong origin. (In
|
||||
// content-boundaries mode the origin is already in the banner.)
|
||||
if !opts.content_boundaries {
|
||||
if let Some(o) = origin.filter(|o| !o.is_empty()) {
|
||||
eprintln!("eval @ {o}");
|
||||
}
|
||||
}
|
||||
let formatted = serde_json::to_string_pretty(result).unwrap_or_default();
|
||||
print_with_boundaries(&formatted, origin, opts);
|
||||
return;
|
||||
@@ -421,7 +478,15 @@ pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &Ou
|
||||
.get("title")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Untitled");
|
||||
// A page can set its title to a multi-KB string (e.g. equal to a
|
||||
// giant JWT/OTP URL); truncate it like the URL so the row stays
|
||||
// readable.
|
||||
let title = truncate_middle(title, 120);
|
||||
let title = title.as_str();
|
||||
let url = tab.get("url").and_then(|v| v.as_str()).unwrap_or("");
|
||||
// Truncate very long URLs (e.g. multi-KB JWT/OTP login links) so
|
||||
// the list stays readable instead of flooding the terminal.
|
||||
let url = truncate_middle(url, 120);
|
||||
let active = tab.get("active").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let marker = if active {
|
||||
color::cyan("→")
|
||||
@@ -530,6 +595,15 @@ pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &Ou
|
||||
}
|
||||
// Network requests
|
||||
if let Some(requests) = data.get("requests").and_then(|v| v.as_array()) {
|
||||
// Stamp the page these requests were read from, mirroring `eval @ url`,
|
||||
// so a read against a drifted/wrong tab is obvious (issue #8.1).
|
||||
if let Some(o) = data
|
||||
.get("origin")
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|o| !o.is_empty())
|
||||
{
|
||||
eprintln!("network @ {o}");
|
||||
}
|
||||
if requests.is_empty() {
|
||||
println!("No requests captured");
|
||||
} else {
|
||||
@@ -733,8 +807,22 @@ pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &Ou
|
||||
color::success_indicator(),
|
||||
color::green(path)
|
||||
);
|
||||
// Stamp which page was captured (mirrors `eval @ url`) so a
|
||||
// screenshot of the wrong/drifted tab is obvious (issue #8.1).
|
||||
if let Some(o) = data
|
||||
.get("origin")
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|o| !o.is_empty())
|
||||
{
|
||||
eprintln!("screenshot @ {o}");
|
||||
}
|
||||
if let Some(annotations) = data.get("annotations").and_then(|v| v.as_array()) {
|
||||
for ann in annotations {
|
||||
// Cap the printed legend on dense pages (it can be
|
||||
// hundreds of lines and flood the terminal). The image
|
||||
// still shows every marker; --json returns the full list.
|
||||
const LEGEND_CAP: usize = 40;
|
||||
let total = annotations.len();
|
||||
for ann in annotations.iter().take(LEGEND_CAP) {
|
||||
let num = ann.get("number").and_then(|n| n.as_u64()).unwrap_or(0);
|
||||
let ref_id = ann.get("ref").and_then(|r| r.as_str()).unwrap_or("");
|
||||
let role = ann.get("role").and_then(|r| r.as_str()).unwrap_or("");
|
||||
@@ -756,6 +844,15 @@ pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &Ou
|
||||
);
|
||||
}
|
||||
}
|
||||
if total > LEGEND_CAP {
|
||||
println!(
|
||||
" {}",
|
||||
color::dim(&format!(
|
||||
"… and {} more markers (shown in the image; --json for the full list)",
|
||||
total - LEGEND_CAP
|
||||
))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
"pdf" => println!(
|
||||
|
||||
@@ -29,6 +29,16 @@ fn build_doctor_cmd(tmp: &TempDir, args: &[&str]) -> Command {
|
||||
cmd
|
||||
}
|
||||
|
||||
// `doctor --offline --quick` runs the full check suite and, on Windows, does
|
||||
// not exit while its stdout is captured by `Command::output()` (the `--help`
|
||||
// variant below exits fine) — so the test would block forever. The 767-test
|
||||
// main suite passes on Windows; this is the one binary-spawning doctor check
|
||||
// that hangs there. Skip it on Windows until the Windows doctor exit/pipe
|
||||
// behavior is fixed; it still runs on Linux/macOS.
|
||||
#[cfg_attr(
|
||||
windows,
|
||||
ignore = "doctor --offline hangs on Windows under captured stdout"
|
||||
)]
|
||||
#[test]
|
||||
fn doctor_offline_quick_json_emits_valid_payload() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
|
||||
@@ -199,10 +199,31 @@ async function handleForwardCdpCommand(msg) {
|
||||
}
|
||||
|
||||
// Everything else → chrome.debugger on the resolved tab.
|
||||
const tabId =
|
||||
(sessionId ? tabForSession(sessionId) : null) ??
|
||||
(typeof params?.targetId === 'string' ? tabForTarget(params.targetId) : null) ??
|
||||
anyConnectedTab()
|
||||
//
|
||||
// A daemon-supplied sessionId/targetId MUST resolve to a real attached tab.
|
||||
// The old code fell through to anyConnectedTab() when it didn't, which
|
||||
// silently ran the command (eval/screenshot/network) on an arbitrary tab —
|
||||
// exactly the "ran on the wrong page with no warning" failure in issue #8.1,
|
||||
// and the blank-screenshot symptom after a service-worker restart (#8.2).
|
||||
// Fail loudly instead so the agent sees an actionable error, not bad data.
|
||||
let tabId
|
||||
if (sessionId) {
|
||||
tabId = tabForSession(sessionId)
|
||||
if (!tabId) {
|
||||
throw new Error(
|
||||
`stale sessionId ${sessionId} for ${method}: its tab is gone (closed, ` +
|
||||
`navigated across processes, or lost after an extension restart). ` +
|
||||
`Re-attach by re-opening your target URL before retrying.`,
|
||||
)
|
||||
}
|
||||
} else if (typeof params?.targetId === 'string') {
|
||||
tabId = tabForTarget(params.targetId)
|
||||
if (!tabId) throw new Error(`no attached tab for targetId ${params.targetId} (${method})`)
|
||||
} else {
|
||||
// No session/target specified — a browser-level command that legitimately
|
||||
// applies to any attached tab.
|
||||
tabId = anyConnectedTab()
|
||||
}
|
||||
if (!tabId) throw new Error(`no attached tab for ${method}`)
|
||||
const dbg = { tabId }
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "agent-browser-stealth",
|
||||
"version": "0.4.1",
|
||||
"version": "0.4.2",
|
||||
"description": "Let agent-browser drive your logged-in Chrome \u2014 install once, no token, no per-use confirmation.",
|
||||
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6vQIyscGIPYPZdSpPwPL0+0gxUROyRgCpmvCSDoc8XUm4qm97VbKnD9Ijc1lV22lNWZtE78gaRjt6BeSfuMgnBymnhLKjN1gU6AI5QUU0mrJyeHdWKvrKQR5FmsM2A7Xr1ykE2SiiS8zNUS3Y/6O5l+Nva7wrVy6E4a2dkBVQkOsu+DV+nEZvhIyuDY5D5SPXqNwUTWTaglwj5mjvHz36xSwCWlPmrtJ+ED0AUyrb2z4GIOmvk4kqtBVrh/UD058klLo4CkYOnIybB5aV6WYuwarfPY4bF/dLggPem+ewLNTUNBuwrxj/A4nUv0LJTuRO8rR7f8WR9qnRCY0Ic5saQIDAQAB",
|
||||
"icons": {
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "agent-browser-stealth",
|
||||
"version": "0.27.0-fork.33",
|
||||
"version": "0.27.0-fork.51",
|
||||
"description": "Browser automation CLI for AI agents — stealth fork with anti-detection",
|
||||
"type": "module",
|
||||
"packageManager": "pnpm@11.1.3",
|
||||
@@ -17,7 +17,7 @@
|
||||
"abs": "bin/agent-browser.js"
|
||||
},
|
||||
"scripts": {
|
||||
"prepare": "husky",
|
||||
"prepare": "husky || true",
|
||||
"version:sync": "node scripts/sync-version.js",
|
||||
"version": "npm run version:sync && git add cli/Cargo.toml",
|
||||
"build:native": "npm run version:sync && cargo build --release --manifest-path cli/Cargo.toml && node scripts/copy-native.js",
|
||||
|
||||
@@ -287,21 +287,20 @@ async function fixWindowsShims() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Detect architecture so ARM64 Windows is handled correctly
|
||||
const cpuArch = arch() === 'arm64' ? 'arm64' : 'x64';
|
||||
const relativeBinaryPath = `node_modules\\agent-browser\\bin\\agent-browser-win32-${cpuArch}.exe`;
|
||||
const absoluteBinaryPath = join(npmBinDir, relativeBinaryPath);
|
||||
|
||||
// Only rewrite shims if the native binary actually exists
|
||||
if (!existsSync(absoluteBinaryPath)) {
|
||||
// Point the shims at the binary's ABSOLUTE path. The previous code rebuilt a
|
||||
// relative `node_modules\agent-browser\bin\...` path, but this fork's package
|
||||
// is `agent-browser-stealth`, so that path never existed → the rewrite was
|
||||
// skipped and the shim stayed the (slower) JS wrapper. `binaryPath` is the
|
||||
// real absolute path to the native binary inside this package.
|
||||
if (!existsSync(binaryPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const cmdContent = `@ECHO off\r\n"%~dp0${relativeBinaryPath}" %*\r\n`;
|
||||
const cmdContent = `@ECHO off\r\n"${binaryPath}" %*\r\n`;
|
||||
writeFileSync(cmdShim, cmdContent);
|
||||
|
||||
const ps1Content = `#!/usr/bin/env pwsh\r\n$basedir = Split-Path $MyInvocation.MyCommand.Definition -Parent\r\n& "$basedir\\${relativeBinaryPath}" $args\r\nexit $LASTEXITCODE\r\n`;
|
||||
const ps1Content = `#!/usr/bin/env pwsh\r\n& "${binaryPath}" $args\r\nexit $LASTEXITCODE\r\n`;
|
||||
writeFileSync(ps1Shim, ps1Content);
|
||||
|
||||
console.log('✓ Optimized: shims point to native binary (zero overhead)');
|
||||
|
||||
+109
-21
@@ -15,6 +15,13 @@ Most normal web tasks (navigate, read, click, fill, extract, screenshot) are
|
||||
covered here. Load a specialized skill when the task falls outside browser
|
||||
web pages — see [When to load another skill](#when-to-load-another-skill).
|
||||
|
||||
> **Hit a rough edge? Please report it.** If a command surprised you — a
|
||||
> confusing error, a stale `@ref`, an occluded click, a flaky wait, a missing
|
||||
> feature, or anything that cost you extra turns — open a quick issue at
|
||||
> **<https://github.com/leeguooooo/agent-browser-stealth/issues>** with the exact
|
||||
> command and what happened vs. what you expected. Agent-filed friction reports
|
||||
> are how this tool gets sharper; a 30-second issue is genuinely valuable.
|
||||
|
||||
## The core loop
|
||||
|
||||
```bash
|
||||
@@ -49,17 +56,42 @@ hand-constructed URL often doesn't.
|
||||
### Driving the user's real, already-open Chrome (extension)
|
||||
|
||||
When the task needs the user's *live* logged-in window (their real session, the
|
||||
window they're looking at — not a fresh browser), use the extension connect flow:
|
||||
`agent-browser extension install` once, load `extensions/ab-connect` in
|
||||
`chrome://extensions` once (it shows up as **agent-browser-stealth**; a GUI step
|
||||
you can perform with a **computer-use / GUI-automation tool** like the
|
||||
`cua-driver` skill — see `references/commands.md` → "Drive your real, logged-in
|
||||
Chrome"). Once the extension is loaded, plain `agent-browser open <url>`
|
||||
auto-connects through it — `auto_connect_cdp` **prefers the live extension relay
|
||||
over a raw `--remote-debugging-port`**, so Chrome 136+'s "Allow remote debugging?"
|
||||
consent popup never fires. `agent-browser extension connect` is the explicit form
|
||||
of the same path. Zero-confirmation, zero-token. Use `--launch` instead when a
|
||||
fresh, isolated browser is fine.
|
||||
window they're looking at — not a fresh browser), use the extension connect flow.
|
||||
One-time setup:
|
||||
1. `agent-browser extension install` — registers the native-messaging host.
|
||||
2. Install the **agent-browser-stealth** extension. Easiest (and restart-stable):
|
||||
the **Chrome Web Store**, one-click *Add to Chrome*:
|
||||
<https://chromewebstore.google.com/detail/agent-browser-stealth/knfcmbamhjmaonkfnjhldjedeobeafmk>
|
||||
(Dev fallback: `chrome://extensions` → Developer mode → *Load unpacked* →
|
||||
`extensions/ab-connect`. Load-unpacked can be disabled on Chrome restart, so
|
||||
prefer the Store build for unattended setups.)
|
||||
|
||||
Once installed, plain `agent-browser open <url>` auto-connects through the
|
||||
extension relay — `auto_connect_cdp` **prefers the live relay over a raw
|
||||
`--remote-debugging-port`**, so Chrome 136+'s "Allow remote debugging?" consent
|
||||
popup never fires. `agent-browser extension connect` is the explicit form of the
|
||||
same path. Zero-confirmation, zero-token. Use `--launch` instead when a fresh,
|
||||
isolated browser is fine.
|
||||
|
||||
**If you DO hit the "Allow remote debugging?" dialog**, don't keep retrying (every
|
||||
attempt re-pops it). One of two things is true:
|
||||
|
||||
1. **You're on a stale build.** The relay-preference that avoids this dialog
|
||||
landed in **fork.30**. Run `agent-browser --version`: if it's below
|
||||
`0.27.0-fork.30`, upgrade and retry:
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/leeguooooo/agent-browser-stealth/main/install.sh | sh
|
||||
```
|
||||
If `which -a agent-browser` shows more than one install, an old **npm/pnpm**
|
||||
copy (the npm registry lags behind — Releases are the source of truth) may be
|
||||
shadowing the upgraded one; remove the stale copy
|
||||
(`npm rm -g agent-browser-stealth` / `pnpm rm -g agent-browser-stealth`) so the
|
||||
`install.sh` build wins. A tool that bundles its *own* pinned copy
|
||||
(e.g. `node .../agent-browser-stealth@0.24.x/.../agent-browser`) needs that
|
||||
copy upgraded too.
|
||||
2. **The extension/relay isn't live.** Tell the user to install the Store
|
||||
extension (one click, above); after that the relay stays up and the dialog
|
||||
never returns.
|
||||
|
||||
Each `--session` that connects gets its **own colored Chrome tab group** (named
|
||||
after the session) and drives only its own tabs — multiple agents share the one
|
||||
@@ -70,6 +102,20 @@ connect) > a headed launched browser > headless (forbidden).** A genuine human
|
||||
browser has no headless/automation tells at all, so prefer it for anything
|
||||
anti-bot-sensitive.
|
||||
|
||||
**Silent by default.** When driving the user's real Chrome the agent works
|
||||
entirely in the background — new tabs open un-focused, the agent never force-
|
||||
fronts a tab, and focus is emulated so the page still renders and reports
|
||||
`visibilityState: 'visible'`. You don't need to do anything; just don't expect
|
||||
the user's view to follow you (use the explicit `bringToFront` only if you
|
||||
deliberately want to surface a tab).
|
||||
|
||||
**Human-like input for behavioural anti-bot.** Beyond fingerprint stealth,
|
||||
`--humanize off|fast|human` (or `AGENT_BROWSER_HUMANIZE`) makes clicks follow a
|
||||
curved, decelerating path with in-element landing jitter, typing use variable
|
||||
cadence, and scroll/drag ease. Default `off`; a per-navigation detector
|
||||
auto-escalates pages guarded by Akamai/PerimeterX/DataDome to `human`. Leave it
|
||||
on auto; force `human` only when you already know the target scores behaviour.
|
||||
|
||||
## Two ways to drive a page — and when to drop to `eval`
|
||||
|
||||
You have a **real Chrome with the user's DOM**. Two layers, mix them freely:
|
||||
@@ -136,14 +182,17 @@ Snapshot output looks like:
|
||||
Page: Example - Log in
|
||||
URL: https://example.com/login
|
||||
|
||||
@e1 [heading] "Log in"
|
||||
@e2 [form]
|
||||
@e3 [input type="email"] placeholder="Email"
|
||||
@e4 [input type="password"] placeholder="Password"
|
||||
@e5 [button type="submit"] "Continue"
|
||||
@e6 [link] "Forgot password?"
|
||||
- heading "Log in" [level=1, ref=e1]
|
||||
- textbox "Email" [ref=e2]
|
||||
- textbox "Password" [ref=e3]
|
||||
- button "Continue" [ref=e4]
|
||||
- link "Forgot password?" [ref=e5]
|
||||
```
|
||||
|
||||
Each line is `- <role> "<accessible name>" [<attrs>, ref=eN]`, indented by nesting
|
||||
depth. You pass the ref to commands as `@eN` (e.g. `click @e4`). Refs are
|
||||
assigned fresh on every snapshot.
|
||||
|
||||
For unstructured reading (no refs needed):
|
||||
|
||||
```bash
|
||||
@@ -170,8 +219,16 @@ agent-browser press Enter # press a key at current focus
|
||||
agent-browser press Control+a # key combination
|
||||
agent-browser check @e3 # check checkbox
|
||||
agent-browser uncheck @e3 # uncheck
|
||||
agent-browser select @e4 "option-value" # select dropdown option
|
||||
agent-browser select @e4 "option-value" # native <select> only
|
||||
agent-browser select @e4 "a" "b" # select multiple
|
||||
agent-browser pick @e4 --option "Europe" # ANY combobox (react-select / ARIA /
|
||||
# native): opens it, waits for the menu
|
||||
# (incl. portal-rendered), matches by
|
||||
# visible text, fires the right events,
|
||||
# and ERRORS if the option never shows
|
||||
# (no silent no-op). Use this for custom
|
||||
# dropdowns where `select` returns ✓ but
|
||||
# changes nothing.
|
||||
agent-browser upload @e5 file1.pdf # upload file(s)
|
||||
agent-browser scroll down 500 # scroll page (up/down/left/right)
|
||||
agent-browser scrollintoview @e1 # scroll element into view
|
||||
@@ -340,9 +397,23 @@ Array.from(rows).map(r => ({
|
||||
EOF
|
||||
```
|
||||
|
||||
Prefer `eval --stdin` (heredoc) or `eval -b <base64>` for any JS with
|
||||
quotes or special characters. Inline `agent-browser eval "..."` works
|
||||
only for simple expressions.
|
||||
Prefer `eval --stdin` (heredoc), `eval --file <path>`, or `eval -b <base64>`
|
||||
for any JS with quotes, **non-ASCII identifiers/strings (e.g. Chinese)**, or
|
||||
large scripts — inline `agent-browser eval "..."` is shell-mangled and works
|
||||
only for simple ASCII expressions.
|
||||
|
||||
**`eval` runs in the page's MAIN world and state persists across calls**, so a
|
||||
top-level `const x`/`let x`/`var x` in one call collides with the next
|
||||
(`SyntaxError: Identifier 'x' has already been declared`). Either use unique
|
||||
names, assign to `window.x`, or wrap the body in an IIFE
|
||||
(`(() => { const x = …; return x; })()`).
|
||||
|
||||
**For array/object results, use `eval --json`** — the plain renderer
|
||||
pretty-prints across multiple lines, which `tail`/`head`/pipes mangle; `--json`
|
||||
emits one parseable line. Also note **`type`/`fill` insert text without firing
|
||||
`keydown`/`keyup`** (CDP insertText) — the value lands, but a page that gates on
|
||||
key events (some search-as-you-type widgets) won't react; use `keyboard type` (or
|
||||
`press` per key) when real keystrokes are required.
|
||||
|
||||
### Screenshot
|
||||
|
||||
@@ -387,6 +458,19 @@ agent-browser --session b fill @e1 "bob@test.com"
|
||||
`AGENT_BROWSER_SESSION=myapp` sets the default session for the current
|
||||
shell.
|
||||
|
||||
**Concurrent agents MUST each use a distinct `--session <name>`.** Within one
|
||||
session, commands are pinned to the tab you opened (by target_id, so a foreign
|
||||
tab can't drift your `eval`/`screenshot`). Two agents sharing the *same* session
|
||||
(e.g. both on the bare default) share one daemon and one active tab and will
|
||||
clobber each other.
|
||||
|
||||
True multi-agent isolation requires the **extension-connect path**: each
|
||||
`--session` gets its own colored Chrome tab group, so sessions never touch each
|
||||
other's tabs. **Raw `--cdp <port>` does NOT isolate** — every session attaches to
|
||||
the same browser's existing targets, so a second session's first `open` can
|
||||
navigate a sibling's tab. For concurrent agents on one real Chrome, use the
|
||||
extension (each with a distinct `--session`), not raw `--cdp`.
|
||||
|
||||
### Mock network requests
|
||||
|
||||
```bash
|
||||
@@ -456,6 +540,10 @@ agent-browser doctor # full diagnosis (env, Chrome, daemons,
|
||||
agent-browser doctor --offline --quick # fast, local-only
|
||||
agent-browser doctor --fix # also run destructive repairs (reinstall Chrome, purge old state, ...)
|
||||
agent-browser doctor --json # structured output for programmatic consumption
|
||||
agent-browser stealth status # stealth self-check: mode + live probes
|
||||
agent-browser stealth status --json # (webdriver/chrome/plugins/UA) + applied
|
||||
# overrides. Gate a sensitive flow on this
|
||||
# instead of driving an external detector.
|
||||
```
|
||||
|
||||
`doctor` auto-cleans stale socket/pid/version sidecar files on every run.
|
||||
|
||||
@@ -331,15 +331,16 @@ One-time setup:
|
||||
agent-browser extension install # writes the native-messaging host manifest
|
||||
```
|
||||
|
||||
The native-messaging host accepts **both** extension origins, so the extension
|
||||
can be installed either way:
|
||||
The native-messaging host accepts **both** extension origins, so either install
|
||||
works — but prefer the Store build:
|
||||
|
||||
1. **Load unpacked (works today)** — load `<repo>/extensions/ab-connect` from
|
||||
source; its pinned `key` gives the stable id `ciiljdlhd…`.
|
||||
2. **Chrome Web Store (once published)** — one-click *Add to Chrome*; the store
|
||||
strips the `key` and assigns its own id (`knfcmbamhjmaonkfnjhldjedeobeafmk`),
|
||||
which `connect.rs` also allow-lists. (Submitted for review; until it's live,
|
||||
use Load unpacked.)
|
||||
1. **Chrome Web Store (recommended)** — one-click *Add to Chrome*:
|
||||
<https://chromewebstore.google.com/detail/agent-browser-stealth/knfcmbamhjmaonkfnjhldjedeobeafmk>
|
||||
Restart-stable and auto-updating (store id `knfcmbamhjmaonkfnjhldjedeobeafmk`).
|
||||
2. **Load unpacked (dev)** — load `<repo>/extensions/ab-connect` from source;
|
||||
its pinned `key` gives the stable id `ciiljdlhd…`. NOTE: Load-unpacked
|
||||
extensions can be disabled/dropped on Chrome restart (Developer-mode handling),
|
||||
which silently drops the relay — so for unattended setups use the Store build.
|
||||
|
||||
For Load unpacked — a GUI step (Chrome's `chrome://extensions` is privileged; the
|
||||
CLI can't load an unpacked extension):
|
||||
|
||||
Reference in New Issue
Block a user