Skip to content

The headless browser for AI agents and web scraping

docs: align guides with current CLI and CDP behavior

SGavrl1693ad537a97
diff --git a/README.md b/README.md
index 15014971..b7645f2b 100644
--- a/README.md
+++ b/README.md
@@ -153,8 +153,9 @@ usable on common LTS servers with glibc 2.35+.
### Docker
```bash
+export OBSCURA_CDP_TOKEN="$(openssl rand -hex 32)"
docker run -d --name obscura -p 127.0.0.1:9222:9222 \
- -e OBSCURA_CDP_TOKEN="$(openssl rand -hex 32)" \
+ -e OBSCURA_CDP_TOKEN \
h4ckf0r0day/obscura
```
@@ -179,7 +180,7 @@ cargo build --release -p obscura-cli --bins --no-default-features
cargo build --release -p obscura-cli --bins --no-default-features --features stealth
```
-Requires Rust 1.75+ ([rustup.rs](https://rustup.rs)). First build takes ~5 min (V8 compiles from source, cached after).
+Requires current stable Rust ([rustup.rs](https://rustup.rs)). First build takes ~5 min (V8 compiles from source, cached after).
The stealth build also compiles BoringSSL and generates bindings, so it needs
CMake, Clang, and the libclang/LLVM development libraries. On Ubuntu/Debian:
@@ -228,6 +229,7 @@ obscura fetch https://example.com --screenshot page.png
# The screenshot flag also has a short form
obscura fetch https://example.com -s page.png
+```
### Testing against localhost / LAN dev servers
@@ -244,7 +246,6 @@ obscura serve --port 9222 --allow-private-network
See [docs/Environment-variables.md](docs/Environment-variables.md) for the
full allow/deny rules (DNS-resolution-time checks included).
-```
## Rendering
@@ -414,7 +415,7 @@ To download a large resource without one giant `Network.getResponseBody` blob, c
Obscura embeds V8 directly. Use `--v8-flags` to pass raw flags through to V8, same syntax as Chromium's `--js-flags` and Node's command-line flags. Most common use is raising the heap cap to fix `JavaScript heap out of memory` on JS-heavy pages:
```bash
-obscura --v8-flags "--max-old-space-size=4096" fetch <url>
+obscura --v8-flags "--max-old-space-size=4096" fetch https://example.com
```
### Heavy SPAs (script execution budget)
diff --git a/docs/Adding-a-CDP-method-or-Web-API.md b/docs/Adding-a-CDP-method-or-Web-API.md
index a805c448..e8d6d60b 100644
--- a/docs/Adding-a-CDP-method-or-Web-API.md
+++ b/docs/Adding-a-CDP-method-or-Web-API.md
@@ -30,10 +30,19 @@ pub async fn do_thing(
### 2. Register in the dispatcher
-In `crates/obscura-cdp/src/dispatch.rs`, add a match arm:
+Export the module in `crates/obscura-cdp/src/domains/mod.rs`:
```rust
-"MyDomain.doThing" => domains::my_domain::do_thing(&req.params, ctx, &req.session_id).await,
+pub mod my_domain;
+```
+
+The dispatcher splits `Domain.method` before matching the domain. In
+`crates/obscura-cdp/src/dispatch.rs`, add a domain arm:
+
+```rust
+"MyDomain" if method == "doThing" => {
+ domains::my_domain::do_thing(&req.params, ctx, &req.session_id).await
+}
```
### 3. Test it
@@ -60,15 +69,18 @@ async fn my_domain_do_thing_returns_ok() {
}
```
-Run:
+Register `cdp_my_domain` in the `integration_tests!` list in
+`crates/obscura-cdp/tests/integration.rs`, then run:
```bash
-cargo nextest run --release --features render -p obscura-cdp my_domain
+cargo nextest run --release --features render -p obscura-cdp --test integration -E 'test(cdp_my_domain::)'
```
## Adding a Web API
-Worked example: `crypto.subtle.digest`, real implementation backed by a Rust hash op.
+`crypto.subtle.digest` is already implemented. The excerpts below show the
+JS-to-Rust flow. Modify the existing op and shim when extending it; do not
+register a duplicate op.
### 1. Add the Rust op
@@ -84,41 +96,46 @@ fn op_subtle_digest(#[string] algorithm: &str, #[buffer] data: &[u8]) -> Vec<u8>
"SHA-256" => sha2::Sha256::digest(data).to_vec(),
"SHA-384" => sha2::Sha384::digest(data).to_vec(),
"SHA-512" => sha2::Sha512::digest(data).to_vec(),
- _ => sha2::Sha256::digest(data).to_vec(),
+ "SHA-512/224" => sha2::Sha512_224::digest(data).to_vec(),
+ "SHA-512/256" => sha2::Sha512_256::digest(data).to_vec(),
+ _ => vec![], // The JS shim rejects unsupported names before this call.
}
}
```
### 2. Register the op
-In the same file, `build_extension()`:
+In the same file, add the op to the vector in `build_extension()`:
```rust
-ops: std::borrow::Cow::Owned(vec![
+let mut ops = vec![
op_dom(),
- op_console_msg(),
- // ...
+ // Other registered ops...
op_subtle_digest(),
-]),
+];
```
### 3. Add the JS shim
-In `crates/obscura-js/js/bootstrap.js`:
+The existing crypto implementation in `crates/obscura-js/js/bootstrap.js`
+validates inputs before calling the private native bridge. Its digest method is:
```js
-globalThis.crypto = globalThis.crypto || {};
-globalThis.crypto.subtle = globalThis.crypto.subtle || {};
-globalThis.crypto.subtle.digest = function digest(algorithm, data) {
- const algName = typeof algorithm === 'string' ? algorithm : algorithm.name;
- const bytes = data instanceof ArrayBuffer
- ? new Uint8Array(data)
- : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
- const out = Deno.core.ops.op_subtle_digest(algName, bytes);
- return Promise.resolve(out.buffer);
-};
+async digest(algorithm, data) {
+ const name = (typeof algorithm === "string" ? algorithm : algorithm && algorithm.name || "")
+ .toUpperCase().replace("_", "-");
+ if (name !== "SHA-1" && name !== "SHA-256" && name !== "SHA-384" &&
+ name !== "SHA-512" && name !== "SHA-512/224" && name !== "SHA-512/256") {
+ throw new DOMException("Unrecognized algorithm name", "NotSupportedError");
+ }
+ return bufferOf(__obscuraCore.ops.op_subtle_digest(name, toBytes(data)));
+}
```
+`toBytes` and `bufferOf` are helpers in the same crypto closure. The async method
+turns validation errors into rejected promises. Do not expose the native bridge
+to page scripts or substitute a different algorithm for unsupported input.
+
### 4. Add a dependency if needed
`crates/obscura-js/Cargo.toml`:
@@ -131,17 +148,20 @@ sha2 = "0.10"
### 5. Smoke test
```bash
-cargo build --release --features render
+cargo build --release -p obscura-cli --bins --features render
./target/release/obscura fetch https://example.com --eval "
crypto.subtle.digest('SHA-256', new TextEncoder().encode('hi'))
- .then(buf => Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join(''))
-"
+ .then(buf => {
+ document.body.textContent = Array.from(new Uint8Array(buf))
+ .map(b => b.toString(16).padStart(2, '0')).join('');
+ })
+" --dump text
```
## Tips
- Keep the JS shim thin. All side effects go through ops.
-- Use `Promise.resolve` to keep async-shaped APIs callable from sync ops.
+- Use async wrappers when validation failures must reject a promise.
- Match the spec: Web API names and shapes are checked by Puppeteer / Playwright wrappers.
- DOM mutations go through `op_dom`, not new ops.
- For events that need to fire across handlers, use the existing `_makeListenerBox` helper in `bootstrap.js`.
diff --git a/docs/Architecture-overview.md b/docs/Architecture-overview.md
index 61b61bb7..8be53852 100644
--- a/docs/Architecture-overview.md
+++ b/docs/Architecture-overview.md
@@ -1,4 +1,4 @@
-Obscura is a workspace of nine crates.
+Obscura is a workspace of ten crates.
```
obscura-cli CLI entry point. fetch, serve, scrape, mcp.
@@ -7,6 +7,7 @@ obscura-browser Page type, navigation, lifecycle events.
obscura-js V8 runtime via deno_core. bootstrap.js + Rust ops.
obscura-dom DOM tree implementation.
obscura-net HTTP client, stealth client, cookie jar, robots cache, tracker blocklist.
+obscura-ssrf Shared URL and IP-address validation for request policies.
obscura-mcp Model Context Protocol server.
obscura-render CSS cascade, retained layout, text shaping, and CPU paint.
obscura Embeddable Rust library API (Browser, Page, Element, CookieStore).
@@ -71,20 +72,20 @@ The relevant paths are `Page::screenshot_with_animation_sample` and
`crates/obscura-js/src/runtime.rs`, and `RenderResourceCache` in
`crates/obscura-render/src/paint.rs`.
-## Single V8 isolate
+## CDP execution
-All pages in a process share one V8 isolate. The isolate is single-threaded by design.
+Each CDP connection runs page work on its own OS thread and current-thread
+Tokio runtime. Socket I/O uses a separate thread. Connections can execute in
+parallel; `--max-connections` bounds live connections per worker process.
-`obscura_js::v8_lock::global()` is a `tokio::sync::Mutex` that serializes V8 work. A handler that wants to run JS must acquire the lock first:
+Each page runtime owns a V8 isolate. `CdpContext::v8_lock` serializes V8 work
+within one connection so handlers do not interleave isolate entry. It is not a
+process-wide lock. Long operations use `process_with_interception` in
+`server.rs` so the connection can keep processing interception messages.
-```rust
-let _guard = obscura_js::v8_lock::global().lock().await;
-page.evaluate(expr).await
-```
-
-The dispatcher routes long-running operations (navigation, eval) through `process_with_interception` in `server.rs`, which spawns the work onto the tokio `LocalSet` and releases the dispatcher to keep handling other CDP messages.
-
-This is why `Target.createTarget` from many concurrent clients works: each `newPage` returns immediately while the actual navigation runs in a spawned task.
+Targets and sessions belong to the connection that created them. A separate
+browser WebSocket does not attach to another connection's pages. Within one
+connection, additional flattened sessions can observe the same target.
## Child frames
@@ -108,7 +109,7 @@ for Playwright frame locators or iframe screenshot fidelity.
## Robustness
-One page cannot hang or crash the process. `obscura-js/runtime.rs` provides a V8 termination watchdog (`arm_watchdog`, `run_event_loop_bounded`) that terminates the isolate from a separate thread when synchronous work overruns a budget, because `tokio::time::timeout` cannot preempt synchronous V8. It bounds the post-load settle, the navigation event-loop pumps, and `--eval`. The complete script phase is bounded by `OBSCURA_SCRIPT_DEADLINE_MS`; enhancement modules have a shorter per-module graph-loading/evaluation budget controlled by `OBSCURA_MODULE_BUDGET_MS`, while modules mounting an empty SPA shell receive the full script deadline. `obscura-js/cdp_watchdog.rs` is a single shared watchdog the dispatcher arms around every CDP command, so a runaway page cannot hold the V8 lock and wedge other sessions (tunable via `OBSCURA_CDP_COMMAND_TIMEOUT_MS`). `op_dom` is wrapped in `catch_unwind` so a DOM-op panic degrades to a null result instead of aborting the process through V8's FFI frame, and `obscura-dom/tree.rs` rejects cyclic reparenting that would make tree walks loop forever. Scripted `fetch()`/XHR and module network requests are timeout-bounded (`OBSCURA_FETCH_TIMEOUT_MS`), and the one-shot `fetch` CLI has a process-level hard deadline as a final backstop.
+`obscura-js/runtime.rs` provides a V8 termination watchdog (`arm_watchdog`, `run_event_loop_bounded`) that terminates the isolate from a separate thread when synchronous work overruns a budget, because `tokio::time::timeout` cannot preempt synchronous V8. It bounds the post-load settle, the navigation event-loop pumps, and `--eval`. The complete script phase is bounded by `OBSCURA_SCRIPT_DEADLINE_MS`; enhancement modules have a shorter per-module graph-loading/evaluation budget controlled by `OBSCURA_MODULE_BUDGET_MS`, while modules mounting an empty SPA shell receive the full script deadline. `obscura-js/cdp_watchdog.rs` is a watchdog the dispatcher arms around CDP commands, to release the connection's V8 lock after an execution timeout (tunable via `OBSCURA_CDP_COMMAND_TIMEOUT_MS`). `op_dom` is wrapped in `catch_unwind` so a DOM-op panic degrades to a null result instead of aborting the process through V8's FFI frame, and `obscura-dom/tree.rs` rejects cyclic reparenting that would make tree walks loop forever. Scripted `fetch()`/XHR and module network requests are timeout-bounded (`OBSCURA_FETCH_TIMEOUT_MS`), and the one-shot `fetch` CLI has a process-level hard deadline as a final backstop.
## JS bridge
@@ -117,7 +118,8 @@ One page cannot hang or crash the process. `obscura-js/runtime.rs` provides a V8
`obscura-js/src/ops.rs` registers Rust ops that the bootstrap calls into:
```js
-Deno.core.ops.op_dom('insert_before', parentNid, refNid, newNid);
+// bootstrap.js helper; the reference node determines the parent.
+_dom('insert_before', newNid, refNid);
```
Adding a Web API usually means:
@@ -141,9 +143,12 @@ OS threads. This is not a complete WorkerGlobalScope implementation.
## CDP session model
Each CDP client connection gets attached to one or more targets.
-Session IDs are `"{targetId}-session"`. The dispatcher routes by `sessionId` in the incoming frame to the right `Page`.
+Managed sessions use `"{targetId}-session"`. Explicit `Target.attachToTarget`
+calls return distinct session IDs. Treat those IDs as opaque and send the
+returned value as `sessionId` on subsequent commands.
-Targets are created by `Target.createTarget`. Closing the WebSocket detaches all sessions but leaves the pages running.
+Targets are created by `Target.createTarget`. Closing the WebSocket ends that connection's sessions and page runtimes.
+The server continues accepting other connections.
## Lifecycle
diff --git a/docs/Build-from-source.md b/docs/Build-from-source.md
index 739edc1a..48db4350 100644
--- a/docs/Build-from-source.md
+++ b/docs/Build-from-source.md
@@ -1,6 +1,6 @@
## Requirements
-- Rust 1.75+ ([rustup.rs](https://rustup.rs))
+- Current stable Rust ([rustup.rs](https://rustup.rs))
- C compiler (gcc or clang)
- ~5 GB free disk space (V8 compiles from source on first build)
@@ -29,7 +29,7 @@ cargo build --release -p obscura-cli --bins --features render,stealth
```
This is the complete rendering build with the stealth wreq/BoringSSL transport,
-TLS fingerprint randomization, browser-identity protections, and tracker
+a consistent browser TLS fingerprint, browser-identity protections, and tracker
blocklist. See [Configure stealth and proxies](Configure-stealth-and-proxies.md).
## Without rendering
@@ -93,11 +93,12 @@ cargo install --path crates/obscura-cli --features render
cargo nextest run --release --features render --no-fail-fast
```
-Integration suite:
+CDP integration tests are registered in `crates/obscura-cdp/tests/integration.rs`.
+Run them with:
```bash
-python3 tests/test_all.py
+cargo nextest run --release --features render -p obscura-cdp --test integration
```
Use `cargo nextest`, not `cargo test`: runtime tests require process isolation
-because the engine owns a single V8 isolate per process.
+to keep V8 runtime state isolated.
diff --git a/docs/CLI-reference.md b/docs/CLI-reference.md
index 5cdf9a9d..11636346 100644
--- a/docs/CLI-reference.md
+++ b/docs/CLI-reference.md
@@ -1,12 +1,17 @@
## `obscura`
-Most top-level flags apply to every subcommand. `--storage-dir` is the
-exception: it is declared on `serve` and `fetch`, and the top-level copy is read
+`--verbose`, `--proxy`, `--stealth`, `--obey-robots`, `--user-agent`, and
+`--allow-private-network` work before or after a subcommand. `--obey-robots`
+applies to `fetch` and `scrape`. Pass `--port` after `serve` or `mcp`; the
+top-level port selects CDP when no subcommand is given.
+
+`--storage-dir` is declared on `serve` and `fetch`. The top-level copy is read
only by `mcp`, which exports it to `OBSCURA_STORAGE_DIR`. Pass it after the
-subcommand to use it with `serve` or `fetch`.
+subcommand to use it with `serve` or `fetch`. Pass `--v8-flags` before the
+subcommand.
```
--v, --verbose Enable info logging
+-v, --verbose Enable debug logging
-p, --port <PORT> CDP port (default 9222)
--proxy <URL> HTTP or SOCKS5 proxy
--stealth Consistent browser fingerprint + tracker blocking
@@ -26,7 +31,10 @@ Load a URL and print its content or an evaluated expression.
```
--dump <FORMAT> html | text | links | markdown | original | assets | cookies
(default html)
- --selector <CSS> Narrow output to a CSS selector
+ --file <PATH> Batch raw fetches from a URL list; - reads stdin
+ --concurrency <N> Parallel batch fetches (default 1; used with --file)
+ --storage-dir <DIR> Persistent cookies and localStorage
+ --selector <CSS> Wait for a CSS selector; output still covers the page
--wait <SECONDS> Fixed post-load delay; omitted uses adaptive settle (5s cap)
--timeout <SECONDS> Navigation timeout (default 30)
--wait-until <LEVEL> domcontentloaded | load | networkidle2 | networkidle0
@@ -37,8 +45,8 @@ Load a URL and print its content or an evaluated expression.
-e, --eval <JS> Evaluate JS, print the result as JSON
-o, --output <FILE> Write to a file instead of stdout
-s, --screenshot <FILE> Capture the settled page as PNG (single URL)
--q, --quiet Suppress info logging
--v, --verbose Enable verbose logging
+-q, --quiet Suppress logs unless overridden by --verbose or RUST_LOG
+-v, --verbose Enable debug logging
```
`--screenshot` requires a render-enabled build. It uses a 1280×720 viewport by
@@ -46,6 +54,10 @@ default and may be combined with `--eval`; the expression runs before capture,
which is useful for scrolling or preparing page state. It is not available in
`--file` batch mode.
+Batch mode (`--file urls.txt`) skips empty lines and lines beginning with `#`,
+fetches raw responses, and emits one JSON status line per URL. Use `scrape`
+for JavaScript evaluation across URLs.
+
When `--wait` is omitted, Obscura drives timers and async work until the page
becomes quiescent, with a five-second ceiling. Supplying `--wait N` instead
requests a fixed `N`-second delay. `--timeout` separately bounds navigation.
@@ -57,7 +69,7 @@ requests a fixed `N`-second delay. `--timeout` separately bounds navigation.
| `html` | Rendered HTML (default) |
| `text` | Plain text |
| `markdown` | Markdown conversion |
-| `links` | Every `<a href>`, one URL per line |
+| `links` | Links as URL and optional tab-separated text, one per line |
| `assets` | Every external resource, one JSON object per line (DOM assets plus `fetch()`/XHR requests) |
| `original` | Raw HTTP response body (binary-safe, bypasses the engine) |
| `cookies` | All cookies in the jar as a JSON array, including HttpOnly cookies invisible to `document.cookie` |
@@ -73,6 +85,8 @@ Run the CDP server. Puppeteer and Playwright connect over WebSocket.
--user-agent <UA> Override the User-Agent
--stealth Consistent browser fingerprint + tracker blocking (global)
--workers <N> Worker processes (default 1)
+ --max-connections <N> Live CDP connections per worker (default 128; 0 refuses connections)
+ --ready-file <PATH> Publish the bound address after startup (--workers 1)
--worker-max-connections <N> Recycle a worker after N CDP connections (--workers > 1)
--worker-max-rss <MB> Recycle a worker above this resident size (Linux)
--worker-max-age <SECS> Recycle a worker after this long
@@ -81,11 +95,15 @@ Run the CDP server. Puppeteer and Playwright connect over WebSocket.
--allow-file-access Permit CDP clients to navigate to file:// URLs
--storage-dir <DIR> Persistent cookies and localStorage
--allow-private-network Permit loopback / RFC1918 / link-local
--q, --quiet Suppress info logging
--v, --verbose Enable info logging
+ --quiet Suppress logs unless overridden by --verbose or RUST_LOG
+-v, --verbose Enable debug logging
```
-Default endpoint is `ws://127.0.0.1:9222`.
+Default endpoint is `ws://127.0.0.1:9222`. `--host` takes an IP address.
+With `--port 0`, the OS chooses a port; `--ready-file` records the bound
+address after V8 initialization. A non-loopback bind requires
+`OBSCURA_CDP_TOKEN` of at least 32 bytes. See
+[CDP authentication](Connect-Puppeteer-or-Playwright.md#authentication).
## `obscura scrape [URLS]...`
@@ -94,13 +112,13 @@ Run a JS expression across many URLs in parallel.
```
-e, --eval <JS> JS to run on each page
--concurrency <N> Parallel pages (default 10)
- --format <FORMAT> Output format (default json)
+ --format <FORMAT> json or tab-separated text (default json)
--timeout <SECONDS> Per-URL timeout (default 60)
--proxy <URL> HTTP or SOCKS5 proxy
--stealth Consistent browser fingerprint + tracker blocking (global)
--allow-private-network Permit loopback / RFC1918 / link-local
--q, --quiet Suppress info logging
--v, --verbose Enable verbose logging
+-q, --quiet Suppress logs unless overridden by --verbose or RUST_LOG
+-v, --verbose Enable debug logging
```
`--stealth`, `--proxy`, and `--allow-private-network` are global flags: they work before or after any subcommand, so each worker in a `scrape` run inherits stealth too.
@@ -111,7 +129,7 @@ Read URLs from stdin with `-`:
cat urls.txt | obscura scrape - --eval "document.title" --concurrency 20
```
-Requires `obscura-worker` next to `obscura` in `PATH`.
+Keep `obscura-worker` in the same directory as the `obscura` executable.
## `obscura mcp`
@@ -126,7 +144,7 @@ Run obscura as an MCP server.
--user-agent <UA> Override the User-Agent
--stealth Consistent browser fingerprint + tracker blocking (global)
--allow-private-network Permit loopback / RFC1918 / link-local
--v, --verbose Enable info logging
+-v, --verbose Enable debug logging
```
`--host` only applies with `--http`. The default `127.0.0.1` keeps the server loopback-only. A non-loopback bind requires `OBSCURA_MCP_TOKEN` (at least 32 bytes); use `OBSCURA_MCP_ALLOWED_ORIGINS` as well when a browser-based client needs access.
diff --git a/docs/Configure-stealth-and-proxies.md b/docs/Configure-stealth-and-proxies.md
index b399a677..527d3aef 100644
--- a/docs/Configure-stealth-and-proxies.md
+++ b/docs/Configure-stealth-and-proxies.md
@@ -43,8 +43,8 @@ Omit rendering with `cargo build --release -p obscura-cli --bins --no-default-fe
(`tcp_options: "M1460,S,T,N,W10"`, window 64240) and macOS
(`tcp_options: "M1460,N,W6,N,N,T,S,E,E"`, window 65535) produces a different
passive fingerprint. Obscura operates in userspace and cannot override these
- kernel defaults. If TCP/IP passive detection is a concern, run Obscura inside
- a container or VM whose kernel matches the target fingerprint, or route
+ kernel defaults. If TCP/IP passive detection is a concern, run Obscura on a host or VM
+ with the required kernel, or route
connections through a proxy whose TCP stack presents the desired profile.
## Proxies
@@ -75,7 +75,8 @@ obscura fetch https://example.com --user-agent "Mozilla/5.0 (...) ..."
obscura serve --user-agent "Mozilla/5.0 (...) ..."
```
-Default UA matches a recent Chrome on the build platform.
+The default profile uses a Windows Chrome identity. `--user-agent` overrides
+the User-Agent; it does not change the host operating system or TLS profile.
## Browser profile, timezone, and geolocation
diff --git a/docs/Connect-Puppeteer-or-Playwright.md b/docs/Connect-Puppeteer-or-Playwright.md
index cafbe882..63825779 100644
--- a/docs/Connect-Puppeteer-or-Playwright.md
+++ b/docs/Connect-Puppeteer-or-Playwright.md
@@ -1,3 +1,5 @@
+Examples use Node.js ES modules. Save scripts with a `.mjs` extension.
+
Obscura speaks the Chrome DevTools Protocol over WebSocket. Puppeteer and
Playwright can connect to its CDP endpoint for the supported workflows below.
@@ -18,7 +20,7 @@ npm install puppeteer-core
```
```js
-const puppeteer = require('puppeteer-core');
+import puppeteer from 'puppeteer-core';
const browser = await puppeteer.connect({
browserWSEndpoint: 'ws://127.0.0.1:9222',
@@ -40,7 +42,7 @@ npm install playwright
```
```js
-const { chromium } = require('playwright');
+import { chromium } from 'playwright';
const browser = await chromium.connectOverCDP('ws://127.0.0.1:9222');
const context = browser.contexts()[0] || await browser.newContext();
@@ -54,9 +56,30 @@ await browser.close();
Use `connectOverCDP`, not `connect`. Playwright's `connect` speaks Playwright's own protocol, which obscura does not implement.
+## Authentication
+
+A non-loopback server bind requires `OBSCURA_CDP_TOKEN` of at least 32 bytes.
+Pass the same token in the client connection headers:
+
+```js
+// Puppeteer
+const browser = await puppeteer.connect({
+ browserWSEndpoint: 'ws://127.0.0.1:9222',
+ headers: { Authorization: `Bearer ${process.env.OBSCURA_CDP_TOKEN}` },
+});
+```
+
+```js
+// Playwright
+const browser = await chromium.connectOverCDP(
+ 'ws://127.0.0.1:9222',
+ { headers: { Authorization: `Bearer ${process.env.OBSCURA_CDP_TOKEN}` } },
+);
+```
+
## `waitUntil`
-Default is `domcontentloaded`. For full subresource load:
+Puppeteer and Playwright default to `load`. Set it explicitly when needed:
```js
await page.goto('https://example.com', { waitUntil: 'load' });
@@ -64,11 +87,16 @@ await page.goto('https://example.com', { waitUntil: 'load' });
| Value | Returns when |
| ------------------ | --------------------------------------- |
-| `domcontentloaded` | HTML parsed, scripts ran (default) |
-| `load` | All subresources finished |
+| `domcontentloaded` | HTML parsed, scripts ran |
+| `load` | All subresources finished (default) |
| `networkidle2` | ≤2 network connections active for 500ms |
| `networkidle0` | 0 network connections active for 500ms |
+The table uses Puppeteer names. Playwright uses `networkidle` for zero active
+connections and also accepts `commit`. Raw CDP `Page.navigate` uses Obscura's
+`domcontentloaded` default when its `waitUntil` parameter is omitted; client
+libraries wait for lifecycle events according to their own options.
+
## Supported
- `page.goto`, `page.reload`, `page.goBack`, `page.goForward`
@@ -143,7 +171,8 @@ their non-table children.
## Current limits
-- Pages share one V8 isolate. CPU-bound JavaScript on one page can delay others.
+- Pages on one CDP connection serialize JavaScript work. Separate connections
+ execute on separate threads.
- PDF output is raster-backed; text is not selectable and tagged PDF,
headers/footers, outlines, and full CSS paged media are not implemented.
- Service workers, native media playback, some Web APIs, and long-tail CSS or
diff --git a/docs/Environment-variables.md b/docs/Environment-variables.md
index d00acfd1..fb0214d7 100644
--- a/docs/Environment-variables.md
+++ b/docs/Environment-variables.md
@@ -54,7 +54,10 @@ This shorter budget applies when the document body already contains more than 50
### `OBSCURA_CDP_COMMAND_TIMEOUT_MS`
-Per-command deadline for the CDP server. A hung page (a runaway `Runtime.evaluate`, a synchronous DOM op) is terminated after this budget so one bad session cannot hold the shared V8 lock and stall the others. Default 60000 (60 seconds); `0` disables it. Navigation self-bounds via `OBSCURA_NAV_TIMEOUT_MS` well under this.
+Per-command V8 deadline for the CDP server. Default 60000 (60 seconds); `0`
+disables it. The watchdog terminates JavaScript that exceeds the budget so it
+can release the connection's V8 lock. It cannot preempt native Rust work. Keep
+this budget above `OBSCURA_NAV_TIMEOUT_MS`.
```bash
OBSCURA_CDP_COMMAND_TIMEOUT_MS=30000 obscura serve
@@ -80,10 +83,51 @@ OBSCURA_FETCH_TIMEOUT_MS=15000 obscura serve
### `OBSCURA_PROXY`
-Default proxy URL used by `obscura-worker` for the parallel `scrape` command when no `--proxy` flag is set.
+Default proxy URL for `serve` and direct `obscura-worker` invocations.
+The `scrape` command passes its `--proxy` value to workers through this variable;
+an unset `--proxy` clears the inherited worker value. Use `--proxy` for `fetch`,
+`scrape`, and `mcp`.
```bash
-OBSCURA_PROXY=http://proxy.example.com:8080 obscura scrape - < urls.txt
+OBSCURA_PROXY=http://proxy.example.com:8080 obscura serve
+```
+
+## Resource limits
+
+Values below are non-negative integers. Byte limits use bytes, not MiB.
+
+| Variable | Default | Effect |
+| --- | --- | --- |
+| `OBSCURA_FETCH_MAX_BODY_BYTES` | 104857600 for JS fetch/XHR; 33554432 for modules | Maximum buffered response size. Setting it overrides both defaults. |
+| `OBSCURA_NETWORK_BODY_BUFFER_ENTRIES` | 128 | Maximum retained response bodies in each page/runtime cache. Zero disables retention. |
+| `OBSCURA_NETWORK_BODY_BUFFER_BYTES` | 2097152 | Largest individual response body retained for CDP retrieval. Zero disables retention; this is not a total-cache byte limit. |
+| `OBSCURA_IO_STREAM_MAX_ENTRIES` | 32 | Maximum open CDP response-body streams per connection. |
+| `OBSCURA_IO_STREAM_MAX_BYTES` | 268435456 | Total bytes retained by those streams. Oldest streams are evicted when a limit is exceeded. |
+| `OBSCURA_MAX_LIVE_FRAMES` | 64 | Maximum live child frames per page, including initial realms awaiting adoption. |
+| `OBSCURA_FRAME_MESSAGE_QUEUE_ENTRIES` | 4096 | Maximum queued cross-frame messages. |
+| `OBSCURA_FRAME_MESSAGE_QUEUE_BYTES` | 8388608 | Maximum bytes in the cross-frame message queue. |
+
+Disabling response-body retention does not disable network events. Reading an
+evicted CDP body or stream returns an error.
+
+## Rendering
+
+These settings require a render-enabled build.
+
+| Variable | Default | Effect |
+| --- | --- | --- |
+| `OBSCURA_SHOT_W` / `OBSCURA_SHOT_H` | 1280 / 720 | CLI screenshot viewport in CSS pixels, set before navigation. |
+| `OBSCURA_SHOT_ANIMATION_TIME_MS` | Live timeline | Sample CSS animations at a finite, non-negative time for a CLI screenshot. |
+| `OBSCURA_RENDER_RESOURCE_DEADLINE_MS` | 3000 | Resource preparation budget before CLI/CDP screenshots, in milliseconds. |
+| `OBSCURA_RENDER_RESOURCE_WARMUP_MS` | 1000 | Resource preparation budget before navigation scripts, in milliseconds. |
+| `OBSCURA_RENDER_RESOURCE_POST_SCRIPT_WARMUP_MS` | 1000 | Resource preparation budget after navigation scripts, in milliseconds. |
+| `OBSCURA_RENDER_RESOURCE_SETTLE_WARMUP_MS` | 1000 | Resource preparation budget after settling, bounded by its remaining time. |
+
+For example:
+
+```bash
+OBSCURA_SHOT_W=1440 OBSCURA_SHOT_H=1000 \
+ obscura fetch https://example.com --screenshot page.png
```
## Stealth and identity
@@ -123,7 +167,7 @@ OBSCURA_GEOLOCATION="40.7128,-74.0060" obscura serve
### `OBSCURA_PROFILE`
-Pin a specific browser profile from the built-in pool by index (`0`-based). Each profile keeps `navigator.platform`, `userAgentData`, the UA string, and the GPU renderer internally consistent. Without it a single stable profile is used.
+Pin a specific browser profile from the built-in pool by index (`0`-based). Each profile keeps `navigator.platform`, `userAgentData`, and the UA string internally consistent. Without it a single stable profile is used.
```bash
OBSCURA_PROFILE=2 obscura serve
@@ -139,12 +183,24 @@ OBSCURA_ROTATE_PROFILE=1 obscura serve
## MCP
+### `OBSCURA_STORAGE_DIR`
+
+Persistent profile directory for MCP. Equivalent to passing `--storage-dir`
+before the `mcp` subcommand. See [Persist cookies and storage](Persist-cookies-and-storage.md).
+
+```bash
+OBSCURA_STORAGE_DIR=./obscura-data obscura mcp
+```
+
### `OBSCURA_MCP_ALLOWED_ORIGINS`
-Comma-separated `Origin` allowlist for the HTTP MCP transport (`obscura mcp --http`). Browser requests are refused by default; when set, only listed origins are accepted. Native, non-browser MCP clients (which send no `Origin`) are always allowed.
+Comma-separated `Origin` allowlist for the HTTP MCP transport (`obscura mcp --http`). Browser requests are refused by default; when set, only listed origins are accepted. Native clients without an `Origin` header pass the origin check.
+If `OBSCURA_MCP_TOKEN` is set, they still need that token.
```bash
-OBSCURA_MCP_ALLOWED_ORIGINS="https://app.example.com" obscura mcp --http --host 0.0.0.0
+OBSCURA_MCP_TOKEN="$(openssl rand -hex 32)" \
+OBSCURA_MCP_ALLOWED_ORIGINS="https://app.example.com" \
+ obscura mcp --http --host 0.0.0.0
```
### `OBSCURA_MCP_TOKEN`
@@ -168,7 +224,8 @@ RUST_LOG=obscura=debug obscura serve
RUST_LOG=obscura_cdp=trace,obscura_browser=debug obscura serve
```
-`--verbose` on the CLI is equivalent to `RUST_LOG=obscura=info`.
+`--verbose` selects debug-level logging unless `RUST_LOG` supplies a filter.
+The default filter is `warn`; `--quiet` selects `off`.
## Build
@@ -177,7 +234,7 @@ RUST_LOG=obscura_cdp=trace,obscura_browser=debug obscura serve
Forces `cargo build` to use the system OpenSSL instead of compiling the vendored copy. Set to `1` on hosts where the vendored OpenSSL fails (older VPS with AVX-512 issues).
```bash
-OPENSSL_NO_VENDOR=1 cargo build --release --features render
+OPENSSL_NO_VENDOR=1 cargo build --release -p obscura-cli --bins --features render
```
## V8
@@ -194,4 +251,5 @@ User flags are appended after the defaults, but V8 applies flag implications aft
## HTTP proxy environment
-Obscura does not honor `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY`. Use `--proxy` or `OBSCURA_PROXY`.
+Obscura does not honor `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY`. Use `--proxy`; `OBSCURA_PROXY` is available for `serve` and direct worker
+invocations as described above.
diff --git a/docs/Extract-data.md b/docs/Extract-data.md
index 4469a1da..e9e24370 100644
--- a/docs/Extract-data.md
+++ b/docs/Extract-data.md
@@ -23,7 +23,7 @@ obscura fetch https://news.ycombinator.com --dump html > hn.html
Plain text. No markup.
```bash
-obscura fetch https://en.wikipedia.org/wiki/Rust_(programming_language) --dump text
+obscura fetch 'https://en.wikipedia.org/wiki/Rust_(programming_language)' --dump text
```
## `markdown`
@@ -36,7 +36,8 @@ obscura fetch https://docs.example.com/page --dump markdown > page.md
## `links`
-Every `<a href>` on the page, one per line.
+Links from the page, one per line. Each line contains the resolved URL and,
+when present, a tab followed by the link text.
```bash
obscura fetch https://example.com --dump links
@@ -52,7 +53,8 @@ obscura fetch https://example.com --dump assets
## `original`
-The raw HTML the server sent, before JavaScript ran.
+The raw HTTP response body, including binary content. This bypasses HTML parsing
+and JavaScript execution.
```bash
obscura fetch https://my-spa.example --dump original > before.html
diff --git a/docs/Installation.md b/docs/Installation.md
index 16c26fe8..592782a3 100644
--- a/docs/Installation.md
+++ b/docs/Installation.md
@@ -45,11 +45,18 @@ yay -S obscura-browser
## Docker
```bash
-docker run -d --name obscura -p 127.0.0.1:9222:9222 h4ckf0r0day/obscura
+export OBSCURA_CDP_TOKEN="$(openssl rand -hex 32)"
+docker run -d --name obscura -p 127.0.0.1:9222:9222 \
+ -e OBSCURA_CDP_TOKEN \
+ h4ckf0r0day/obscura
```
Image: [h4ckf0r0day/obscura](https://hub.docker.com/r/h4ckf0r0day/obscura). Built on `distroless/cc:nonroot`, with no shell or package manager in the runtime image, running as uid 65532. Note the `-p 127.0.0.1:...` above: it publishes the port to host loopback only. A mounted `--storage-dir` must be writable by uid 65532 — see [Run in production at scale](Run-in-production-at-scale.md#the-container-does-not-run-as-root).
+The container requires `OBSCURA_CDP_TOKEN` because it binds all container
+interfaces. Send that token in your CDP client's `Authorization: Bearer <token>`
+header. See [CDP authentication](Connect-Puppeteer-or-Playwright.md#authentication).
+
Official archives and the Docker image include the rendering engine. Source
builders must pass `--features render`; see [Build from source](Build-from-source.md).
diff --git a/docs/Markdown-extraction.md b/docs/Markdown-extraction.md
index 13dfe44c..b3fb188f 100644
--- a/docs/Markdown-extraction.md
+++ b/docs/Markdown-extraction.md
@@ -21,7 +21,9 @@ obscura fetch https://example.com --dump markdown
- `<script>`, `<style>`, `<noscript>`
- Inline styles
- ARIA attributes
-- Tracking pixels and beacons
+
+Images are converted without checking their dimensions or purpose. Tracking
+pixel URLs can remain in the output.
## Save to file
@@ -35,7 +37,8 @@ obscura fetch https://docs.example.com/page --dump markdown -o page.md
obscura fetch https://docs.example.com/page --dump markdown --quiet
```
-`--quiet` strips info logging so the output is just markdown.
+`--quiet` suppresses logs. Progress messages and logs use stderr; Markdown uses
+stdout. `--verbose` or `RUST_LOG` can override the log filter.
## Wait for SPA content
@@ -45,13 +48,15 @@ For pages that render content client-side:
obscura fetch https://my-spa.example --wait-until load --dump markdown
```
-## Narrow to a region
+## Wait for an element
-`--selector` restricts the conversion to a CSS selector:
+`--selector` waits for an element before reading the page. It does not restrict
+Markdown conversion to that element:
```bash
obscura fetch https://example.com --selector "main" --dump markdown
obscura fetch https://example.com --selector "article.post" --dump markdown
```
-Useful for skipping nav, sidebars, and footers.
+To extract a single region, use `--eval` to read its text or HTML, or use the
+[structured extraction tools](Use-the-MCP-server.md#tools-exposed) in MCP.
diff --git a/docs/README.md b/docs/README.md
index 940b096f..33688200 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -2,7 +2,10 @@
Official documentation for Obscura, maintained in this repository.
-Obscura is an open-source headless browser engine written in Rust. It runs JavaScript via V8, speaks the Chrome DevTools Protocol, and works as a drop-in replacement for headless Chrome with Puppeteer and Playwright.
+Obscura is an independent headless browser engine written in Rust. It runs
+JavaScript through V8 and provides a Chrome DevTools Protocol endpoint for
+Puppeteer and Playwright. These docs describe the code on `main`; installed
+release versions may differ.
## Versus headless Chrome
diff --git a/docs/Run-in-production-at-scale.md b/docs/Run-in-production-at-scale.md
index 199828e1..b428b3d8 100644
--- a/docs/Run-in-production-at-scale.md
+++ b/docs/Run-in-production-at-scale.md
@@ -5,14 +5,15 @@
# by it. Without this the cookie jar silently fails to persist.
sudo install -d -o 65532 -g 65532 /srv/obscura/data
+export OBSCURA_CDP_TOKEN="$(openssl rand -hex 32)"
docker run -d \
--name obscura \
--restart unless-stopped \
-p 127.0.0.1:9222:9222 \
- -e OBSCURA_CDP_TOKEN="$(openssl rand -hex 32)" \
+ -e OBSCURA_CDP_TOKEN \
-v /srv/obscura/data:/data \
h4ckf0r0day/obscura \
- serve --host 0.0.0.0 --storage-dir /data --stealth
+ serve --host 0.0.0.0 --storage-dir /data
```
The image runs `obscura serve` by default. Override with arguments after the image name.
@@ -24,7 +25,7 @@ uid/gid **65532**. Obscura executes untrusted page JavaScript in-process through
V8, so a V8 exploit lands with the process's privileges — there is no reason for
those to be root's.
-Two consequences worth knowing:
+Storage and privileges:
- **A mounted `--storage-dir` must be writable by uid 65532**, as above. This is
the one thing that breaks quietly rather than loudly. Verified: with an
@@ -50,7 +51,14 @@ the CDP client and still publish the port to host loopback where possible.
## Systemd
-`/etc/systemd/system/obscura.service`:
+Create a service account if it does not exist:
+
+```bash
+sudo useradd --system --user-group --home-dir /var/lib/obscura --shell /usr/sbin/nologin obscura
+```
+
+Save this unit as `/etc/systemd/system/obscura.service`. `StateDirectory` creates
+`/var/lib/obscura` with the service account as its owner:
```ini
[Unit]
@@ -58,7 +66,8 @@ Description=Obscura headless browser
After=network.target
[Service]
-ExecStart=/usr/local/bin/obscura serve --port 9222 --stealth --storage-dir /var/lib/obscura
+ExecStart=/usr/local/bin/obscura serve --port 9222 --storage-dir /var/lib/obscura
+StateDirectory=obscura
Restart=always
RestartSec=5
User=obscura
@@ -70,8 +79,9 @@ WantedBy=multi-user.target
```
```bash
-systemctl enable --now obscura
-journalctl -fu obscura
+sudo systemctl daemon-reload
+sudo systemctl enable --now obscura
+sudo journalctl -fu obscura
```
## Workers
@@ -82,7 +92,10 @@ journalctl -fu obscura
obscura serve --workers 4
```
-Use one worker per CPU core. Each worker handles its own pool of pages. Sessions are sticky to a worker.
+Each worker accepts multiple CDP connections. Start with a small worker count
+and measure CPU and memory under your workload. Each connection stays on the
+worker that accepted it. `--max-connections` defaults to 128 per worker; excess
+connections receive HTTP 503.
Worker memory can grow over days. Recycle workers with `--worker-max-connections`, `--worker-max-rss` (MB, Linux) or `--worker-max-age` (seconds). A replacement starts first and takes all new connections; the old worker finishes its live connections, then exits. `--worker-drain-timeout` (default 120 s) bounds that wait, after which remaining connections are closed, so set it above your longest session.
@@ -118,7 +131,7 @@ Reads URLs from stdin:
cat urls.txt | obscura scrape --concurrency 20 -
```
-Requires `obscura-worker` next to `obscura` in `PATH`.
+Keep `obscura-worker` in the same directory as the `obscura` executable.
## Resource limits
@@ -182,11 +195,16 @@ obscura serve --verbose
RUST_LOG=obscura=debug obscura serve
```
-`--verbose` enables info-level logs. `RUST_LOG=obscura=debug` enables debug-level. Logs go to stderr.
+`--verbose` selects debug-level logging unless `RUST_LOG` supplies a filter.
+The default filter is `warn`. Logs go to stderr.
## Reliability and timeouts
-The engine is hardened so one page cannot hang, crash, or wedge a worker. A V8 watchdog terminates runaway scripts and microtask storms, DOM ops are panic-safe, cyclic DOM mutations are rejected, and the CDP server terminates any single command that overruns its budget so a hung session cannot stall the others. Scripted `fetch()`/XHR and navigation are timeout-bounded. You can point the server at arbitrary or heavy pages without a stuck worker.
+A V8 watchdog terminates scripts that exceed their execution budget. DOM ops
+catch panics, and the DOM tree rejects cyclic mutations. Navigation and
+scripted network requests have separate timeouts. These controls do not prevent
+every native crash or resource-exhaustion failure; use worker recycling and
+process memory limits for long-running deployments.
Tune the bounds with environment variables (see [Environment variables](Environment-variables.md)):
diff --git a/docs/Testing-and-debugging.md b/docs/Testing-and-debugging.md
index 4a066360..c2c46e47 100644
--- a/docs/Testing-and-debugging.md
+++ b/docs/Testing-and-debugging.md
@@ -16,11 +16,11 @@ cargo nextest run --release --features render -p obscura-browser
By name, also selecting the crate and test target:
```bash
-rtk proxy env CARGO_INCREMENTAL=0 CARGO_BUILD_JOBS=2 cargo nextest run --release --features render -p obscura-js --lib completed_scripts_do_not_wait_for_watchdog_deadline
+env CARGO_INCREMENTAL=0 CARGO_BUILD_JOBS=2 cargo nextest run --release --features render -p obscura-js --lib completed_scripts_do_not_wait_for_watchdog_deadline
```
Use `cargo nextest`, not `cargo test`. Runtime tests require process isolation
-because the engine owns one V8 isolate per process. Render tests must run in
+to keep V8 runtime state isolated. Render tests must run in
release mode; debug builds are not a fidelity or performance gate.
### Fast edit/test loop
@@ -29,7 +29,7 @@ For runtime unit tests, the `test-js` Cargo alias enables incremental compilatio
only for `obscura-js`, retaining release optimization and reusing dependencies:
```bash
-rtk proxy env -u CARGO_INCREMENTAL CARGO_BUILD_JOBS=2 cargo test-js -E 'test(classic_script_url_is_dynamic_import_referrer)'
+env -u CARGO_INCREMENTAL CARGO_BUILD_JOBS=2 cargo test-js -E 'test(classic_script_url_is_dynamic_import_referrer)'
```
The first invocation warms an extra compiler cache. Later source edits reuse it.
@@ -42,7 +42,7 @@ For other crates, select the affected binary before applying a test-name filter.
CDP integration tests share one binary; select a module within it:
```bash
-rtk proxy env CARGO_INCREMENTAL=0 CARGO_BUILD_JOBS=2 cargo nextest run --release --features render -p obscura-cdp --test integration -E 'test(page_frame_contract::)'
+env CARGO_INCREMENTAL=0 CARGO_BUILD_JOBS=2 cargo nextest run --release --features render -p obscura-cdp --test integration -E 'test(page_frame_contract::)'
```
`-p` selects packages; `--lib` or `--test NAME` selects binaries to compile.
@@ -102,7 +102,8 @@ RUST_LOG=obscura_cdp=trace,obscura_browser=debug obscura serve
Logs go to stderr.
-`--verbose` on any subcommand is equivalent to `RUST_LOG=obscura=info`.
+`--verbose` selects debug-level logging unless `RUST_LOG` supplies a filter.
+The default filter is `warn`; `--quiet` selects `off`.
## Driving the CDP server manually
@@ -116,11 +117,12 @@ In another shell:
wscat -c ws://127.0.0.1:9222
> {"id":1,"method":"Target.createTarget","params":{"url":"about:blank"}}
> {"id":2,"method":"Target.attachToTarget","params":{"targetId":"...","flatten":true}}
-> {"id":3,"sessionId":"...-session","method":"Page.navigate","params":{"url":"https://example.com"}}
-> {"id":4,"sessionId":"...-session","method":"Runtime.evaluate","params":{"expression":"document.title"}}
+> {"id":3,"sessionId":"<returned sessionId>","method":"Page.navigate","params":{"url":"https://example.com"}}
+> {"id":4,"sessionId":"<returned sessionId>","method":"Runtime.evaluate","params":{"expression":"document.title"}}
```
-Useful for reproducing what Puppeteer or Playwright is doing without their abstraction.
+Use the `targetId` returned by command 1 and the `sessionId` returned by
+command 2. Send the commands one at a time after receiving each response.
## Common failure modes
@@ -133,8 +135,8 @@ under `target/release/deps/` references before changing engine behavior.
To regenerate the snapshot while retaining dependency caches:
```bash
-rtk proxy touch crates/obscura-js/js/bootstrap.js
-rtk proxy env CARGO_INCREMENTAL=0 CARGO_BUILD_JOBS=2 cargo build --release -p obscura-cli --bins --features render
+touch crates/obscura-js/js/bootstrap.js
+env CARGO_INCREMENTAL=0 CARGO_BUILD_JOBS=2 cargo build --release -p obscura-cli --bins --features render
```
Then rerun the failing nextest command, which rebuilds its own feature-specific
@@ -163,9 +165,11 @@ A handler is awaiting something that never resolves. Run with `RUST_LOG=obscura=
## Reproducing user bug reports
-The integration suite in `tests/test_all.py` is the fastest path from a one-line repro to a regression test. Add the failing case as a new test function, get it failing, then fix.
+Add a regression test to the affected crate. Reproduce the failure before
+changing the implementation, then run the focused release-mode nextest target.
-For Puppeteer / Playwright bug reports, the user's repro script usually drops straight in. Save it as `tests/repro_<issue>.js`, run with `node`, fix until it passes.
+For Puppeteer / Playwright bug reports, the user's repro script usually drops straight in. Save a temporary script outside the repository, run it with `node`, then add
+a regression test under the affected crate's `tests/` directory.
### Rendering regressions
@@ -191,7 +195,7 @@ fixture. Do not add hostname-specific render branches.
CPU with `perf` and a flamegraph:
```bash
-cargo build --release --features render
+cargo build --release -p obscura-cli --bins --features render
perf record -F 99 -g -- ./target/release/obscura fetch https://heavy-spa.example
perf script | flamegraph.pl > flame.svg
```
@@ -202,13 +206,6 @@ Memory with heaptrack:
heaptrack ./target/release/obscura serve
```
-Tokio task inspection:
-
-```bash
-RUSTFLAGS="--cfg tokio_unstable" cargo build --release --features render
-./target/release/obscura serve
-# in another shell
-tokio-console
-```
-
-Requires the workspace `tokio` dependency to be built with the `tracing` feature; not enabled by default, add it in the relevant `Cargo.toml` before profiling.
+Tokio task inspection requires adding both `console-subscriber` initialization
+and Tokio's `tracing` feature to a local profiling build. `tokio-console` cannot
+attach to the default binary.
diff --git a/docs/Use-as-a-Rust-library.md b/docs/Use-as-a-Rust-library.md
index bcd8192c..da437130 100644
--- a/docs/Use-as-a-Rust-library.md
+++ b/docs/Use-as-a-Rust-library.md
@@ -4,15 +4,16 @@ The `obscura` crate embeds the engine in a Rust program with a `Browser` / `Page
```toml
[dependencies]
-obscura = { git = "https://github.com/h4ckf0r0day/obscura" }
+obscura = { git = "https://github.com/h4ckf0r0day/obscura", features = ["stealth"] }
tokio = { version = "1", features = ["rt", "macros"] }
anyhow = "1"
```
-The first build compiles V8 from source, so it is slow and needs the same build tools as [Build from source](Build-from-source.md). Pin a tag for reproducible builds:
+The first build compiles V8 from source, so it is slow and needs the same build tools as [Build from source](Build-from-source.md). Pin the full commit SHA you tested for reproducible builds. Replace the
+placeholder below with that SHA:
```toml
-obscura = { git = "https://github.com/h4ckf0r0day/obscura", tag = "v0.1.7" }
+obscura = { git = "https://github.com/h4ckf0r0day/obscura", rev = "<full commit SHA>", features = ["stealth"] }
```
## Quickstart
@@ -21,7 +22,7 @@ obscura = { git = "https://github.com/h4ckf0r0day/obscura", tag = "v0.1.7" }
use obscura::Browser;
use std::time::Duration;
-#[tokio::main]
+#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
let browser = Browser::builder()
.stealth(true)
@@ -95,7 +96,8 @@ page.settle(2000).await; // let in-page fetch() calls resolve
### Active interception
-`enable_interception()` returns a channel of every JS `fetch()`/XHR request. Resolve each through its `resolver` to pass, block, mock, or rewrite it.
+`enable_interception()` returns a channel of intercepted navigation and JS
+`fetch()`/XHR requests. Resolve each through its `resolver` to pass, block, mock, or rewrite it.
```rust
use obscura::{Browser, InterceptResolution};
diff --git a/docs/Use-the-MCP-server.md b/docs/Use-the-MCP-server.md
index a17af9e5..7f0ca78a 100644
--- a/docs/Use-the-MCP-server.md
+++ b/docs/Use-the-MCP-server.md
@@ -29,7 +29,8 @@ obscura mcp --http --port 3000
The HTTP transport binds `127.0.0.1` by default. Bind all interfaces with `--host` for a container or sidecar deployment:
```bash
-obscura mcp --http --host 0.0.0.0 --port 3000
+OBSCURA_MCP_TOKEN="$(openssl rand -hex 32)" \
+ obscura mcp --http --host 0.0.0.0 --port 3000
```
With stealth and proxy:
@@ -90,7 +91,10 @@ Interact:
Wait and run JS:
-- `browser_wait_for`, `browser_wait_for_text`, `browser_evaluate`
+- `browser_wait_for`, `browser_wait_for_text`, `browser_wait_for_function`, `browser_evaluate`
+
+`browser_wait_for_function` polls the JavaScript expression in `function` until
+it becomes truthy. `timeout` defaults to 30000 ms and `pollIntervalMs` to 100 ms.
`browser_evaluate` accepts JavaScript scripts, executes them once, and waits for
returned promises. `timeoutMs` defaults to 5000 ms and bounds synchronous
diff --git a/docs/Use-with-Playwright.md b/docs/Use-with-Playwright.md
index 237e7d35..77ac6722 100644
--- a/docs/Use-with-Playwright.md
+++ b/docs/Use-with-Playwright.md
@@ -1,3 +1,5 @@
+Examples use Node.js ES modules. Save scripts with a `.mjs` extension.
+
## Setup
```bash
@@ -8,7 +10,7 @@ npm install playwright
## Connect
```js
-const { chromium } = require('playwright');
+import { chromium } from 'playwright';
const browser = await chromium.connectOverCDP('ws://127.0.0.1:9222');
const context = browser.contexts()[0] || await browser.newContext();
@@ -25,7 +27,8 @@ await page.goto('https://example.com', { waitUntil: 'load' });
await page.goto('https://example.com', { waitUntil: 'networkidle' });
```
-Default is `domcontentloaded`. Other values: `load`, `networkidle`.
+Default is `load`. Other values include `domcontentloaded`, `networkidle`, and
+`commit`.
Navigating to `text/plain`, `text/markdown`, or `text/x-markdown` responses
preserves literal markup as text instead of parsing it as HTML.
@@ -145,7 +148,8 @@ await Promise.all([
]);
```
-Pages share one V8 isolate. CPU-bound JS on one page blocks the others.
+Pages on one CDP connection serialize JavaScript work. Separate CDP connections
+run on separate threads and can execute in parallel.
## Screenshots, scrolling, and PDF
diff --git a/docs/Use-with-Puppeteer.md b/docs/Use-with-Puppeteer.md
index a41f0d92..fd591a43 100644
--- a/docs/Use-with-Puppeteer.md
+++ b/docs/Use-with-Puppeteer.md
@@ -1,3 +1,5 @@
+Examples use Node.js ES modules. Save scripts with a `.mjs` extension.
+
## Setup
```bash
@@ -8,7 +10,7 @@ npm install puppeteer-core
## Connect
```js
-const puppeteer = require('puppeteer-core');
+import puppeteer from 'puppeteer-core';
const browser = await puppeteer.connect({
browserWSEndpoint: 'ws://127.0.0.1:9222',
@@ -26,7 +28,7 @@ await page.goto('https://example.com', { waitUntil: 'load' });
await page.goto('https://example.com', { waitUntil: 'networkidle0', timeout: 60000 });
```
-Default `waitUntil` is `domcontentloaded`. Other values: `load`, `networkidle2`, `networkidle0`.
+Default `waitUntil` is `load`. Other values: `domcontentloaded`, `networkidle2`, `networkidle0`.
## Evaluate
@@ -46,7 +48,7 @@ const items = await page.evaluate(() => {
```js
await page.click('#login-button');
await page.type('#username', 'alice');
-await page.fill('#password', 'secret'); // alias of .type for compat
+await page.type('#password', 'secret');
await page.waitForSelector('#dashboard');
await page.waitForFunction(() => window.appReady === true);
@@ -114,7 +116,8 @@ await Promise.all([
]);
```
-Pages share one V8 isolate. Concurrent JS execution serializes through a lock. CPU-bound JS on one page blocks the others.
+Pages on one CDP connection serialize JavaScript work. Separate CDP connections
+run on separate threads and can execute in parallel.
## Screenshots, scrolling, and PDF
@@ -191,7 +194,7 @@ are not implemented by this change.
- Some device emulation, service-worker, native media, long-tail CSS, and
compositor behavior remains incomplete relative to Chromium.
-- Pages share one V8 isolate; CPU-bound JavaScript serializes across pages.
+- CPU-bound JavaScript can delay other pages on the same CDP connection.
- PDF text is not selectable/searchable and tagged PDF is not yet available.
Network events are shared by sessions attached to the same target. An additional
diff --git a/docs/Watch-agent-sessions-live.md b/docs/Watch-agent-sessions-live.md
index aa40ca5b..df3c92d7 100644
--- a/docs/Watch-agent-sessions-live.md
+++ b/docs/Watch-agent-sessions-live.md
@@ -1,177 +1,115 @@
# Watch agent sessions live
-Obscura is headless, so an agent driving it through MCP, Puppeteer, or Playwright works invisibly. The CDP screencast surface lets you stream what the browser sees to a local tab while the agent works, which helps when supervising long tasks or debugging what an agent clicked.
+Capture frames through the same CDP connection that drives the page. Separate
+browser connections have their own targets; opening another connection does
+not let a viewer attach to an existing agent session. CLI `fetch` and stdio MCP
+also run separate browser sessions.
-This guide builds a small live viewer on top of `obscura serve`. It uses only Node's built-in modules and its native WebSocket client (Node 21+).
+## Run a viewer with Puppeteer
-## How it works
-
-1. Start the CDP server:
+Use a render-enabled Obscura build and Node.js 22 or later:
```bash
obscura serve --port 9222
+npm install puppeteer-core
```
-2. Run the viewer script below:
-
-```bash
-node watch.mjs
-```
-
-3. Open http://localhost:8080 in a browser. Every page the agent navigates to appears there, updating as the page paints.
-
-The script attaches to the CDP endpoint, captures the current page twice a second with `Page.captureScreenshot`, and forwards JPEG frames to your browser over Server-Sent Events.
+Save this as `watch.mjs`. Put your automation where the example navigates, using
+the same `page` object. The viewer polls for a JPEG twice a second and sends it
+to local browser tabs over Server-Sent Events.
```js
-// watch.mjs
-// Usage: node watch.mjs [cdpPort] [httpPort]
-import http from "node:http";
-
-const cdpPort = process.argv[2] ?? 9222;
-const httpPort = process.argv[3] ?? 8080;
+import http from 'node:http';
+import puppeteer from 'puppeteer-core';
+const token = process.env.OBSCURA_CDP_TOKEN;
+const browser = await puppeteer.connect({
+ browserWSEndpoint: 'ws://127.0.0.1:9222',
+ headers: token ? { Authorization: `Bearer ${token}` } : {},
+});
+const page = await browser.newPage();
const clients = new Set();
let latest = null;
-let sessionId = null;
-let ws = null;
-
-const page = `
-<!doctype html>
-<html>
-<head><meta charset="utf-8"><title>Obscura live</title>
-<style>body{margin:0;background:#111;display:grid;place-items:center;height:100vh}
-img{max-width:100%;max-height:100%}</style></head>
-<body><img id="s" alt="live page">
+let stopping = false;
+
+const html = `<!doctype html>
+<meta charset="utf-8"><title>Obscura live view</title>
+<style>body{margin:0;background:#111}img{max-width:100%}</style>
+<img id="frame" alt="Current page">
<script>
-const img = document.getElementById("s");
-let old = null;
-const es = new EventSource("/events");
-es.onmessage = (e) => {
- const bytes = Uint8Array.from(atob(e.data), (c) => c.charCodeAt(0));
- const url = URL.createObjectURL(new Blob([bytes], { type: "image/jpeg" }));
- img.src = url;
- if (old) URL.revokeObjectURL(old);
- old = url;
+const image = document.getElementById('frame');
+const events = new EventSource('/events');
+events.onmessage = event => {
+ image.src = 'data:image/jpeg;base64,' + event.data;
};
-</script></body>
-</html>`;
+</script>`;
const server = http.createServer((req, res) => {
- if (req.url === "/events") {
- res.writeHead(200, {
- "Content-Type": "text/event-stream",
- "Cache-Control": "no-store",
- Connection: "keep-alive",
- });
- res.socket.setNoDelay(true);
- if (latest) res.write(`data:${latest}\n\n`);
- clients.add(res);
- req.on("close", () => clients.delete(res));
- } else {
- res.writeHead(200, { "Content-Type": "text/html" });
- res.end(page);
+ if (req.url !== '/events') {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(html);
+ return;
}
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-store',
+ Connection: 'keep-alive',
+ });
+ if (latest) res.write(`data:${latest}\n\n`);
+ clients.add(res);
+ res.on('close', () => clients.delete(res));
});
+server.listen(8080, '127.0.0.1');
+
+async function capture() {
+ try {
+ latest = await page.screenshot({ type: 'jpeg', quality: 70, encoding: 'base64' });
+ for (const client of clients) client.write(`data:${latest}\n\n`);
+ } catch (error) {
+ if (!stopping) console.error('Capture failed:', error.message);
+ }
+ if (!stopping) setTimeout(capture, 500);
+}
-server.listen(httpPort, "127.0.0.1", () => {
- console.log(`live view: http://localhost:${httpPort}`);
+process.once('SIGINT', async () => {
+ stopping = true;
+ for (const client of clients) client.end();
+ server.close();
+ await browser.disconnect();
});
-function broadcast(base64) {
- latest = base64;
- for (const res of clients) {
- if (res.writable) res.write(`data:${base64}\n\n`);
- }
-}
+await page.goto('https://example.com');
+capture();
+// Continue automation here with the same `page` object.
+```
-async function connect() {
- ws = new WebSocket(`ws://127.0.0.1:${cdpPort}/devtools/browser`);
- let id = 0;
- const pending = new Map();
- const call = (method, params = {}, sess) =>
- new Promise((resolve, reject) => {
- const mid = ++id;
- pending.set(mid, { resolve, reject });
- const msg = { id: mid, method, params };
- if (sess) msg.sessionId = sess;
- ws.send(JSON.stringify(msg));
- });
-
- ws.addEventListener("message", (ev) => {
- const msg = JSON.parse(ev.data);
- if (msg.id && pending.has(msg.id)) {
- const p = pending.get(msg.id);
- pending.delete(msg.id);
- msg.error ? p.reject(new Error(msg.error.message)) : p.resolve(msg.result);
- }
- });
- ws.addEventListener("close", () => {
- sessionId = null;
- setTimeout(() => connect().catch(retry), 2000);
- });
- ws.addEventListener("error", () => ws.close());
-
- await new Promise((resolve) => ws.addEventListener("open", resolve));
-
- // reuse the page target an agent session may already have created
- const { targetInfos } = await call("Target.getTargets");
- const existing = targetInfos.find((t) => t.type === "page");
- if (existing) {
- // pre-existing target: attach explicitly and use the returned session id
- const attached = await call("Target.attachToTarget", {
- targetId: existing.targetId,
- flatten: true,
- });
- sessionId = attached.sessionId;
- } else {
- // a freshly created target is auto-attached under a managed session id
- const created = await call("Target.createTarget", { url: "about:blank" });
- sessionId = `${created.targetId}-session`;
- }
- await call("Page.enable", {}, sessionId);
-
- // capture on an interval instead of Page.startScreencast: screencast
- // frames stream to the session that drives the page, so a passive
- // viewer stops receiving them once an agent takes over. An explicit
- // capture always reflects the current page state.
- const capture = async () => {
- if (ws.readyState !== WebSocket.OPEN || !sessionId) return;
- try {
- const shot = await call(
- "Page.captureScreenshot",
- { format: "jpeg", quality: 70 },
- sessionId
- );
- if (shot.data && shot.data.length > 100) broadcast(shot.data);
- } catch {
- // transient failures during navigation are normal, retry next tick
- }
- setTimeout(capture, 500);
- };
- capture();
-}
+Run it, then open http://127.0.0.1:8080:
-function retry(err) {
- console.error(err.message);
- sessionId = null;
- setTimeout(() => connect().catch(retry), 2000);
-}
-connect().catch(retry);
+```bash
+node watch.mjs
```
+The HTTP listener binds only to loopback. If the CDP server requires a token,
+export the same `OBSCURA_CDP_TOKEN` before running the script.
+
+## Other capture paths
-> For a packaged version with adaptive pacing (fast while painting, idle back-off) and multi-page handling, see `tools/live-view.mjs`.
-## Things worth knowing
+Playwright can use the same pattern with its existing `page.screenshot()`;
+convert the returned buffer to base64 before sending it to the viewer.
-- **Why captureScreenshot polling instead of screencast.** `Page.startScreencast` frames stream to the CDP session that drives the page, so once an agent session takes over, a passive viewer session stops receiving frames. It also only produces frames when the page paints something new. An explicit `Page.captureScreenshot` always reflects the current page state regardless of which session navigated, which makes it the reliable choice for watching someone else's session.
-- **Acknowledge every frame.** Without `Page.screencastFrameAck`, frame delivery stops.
-- **One client per page socket.** If an agent's CDP client already holds the page's `webSocketDebuggerUrl`, connecting to it again fails with `503`. Attach through the browser endpoint instead (`ws://127.0.0.1:9222/devtools/browser`) using `Target.attachToTarget` with `flatten: true`, then pass the returned session id as `sessionId` on every command.
-- **Still images vs continuous view.** The MCP server exposes `browser_screenshot` for one-shot captures. Screencast is the right tool when you want to watch continuously; it stays CDP-only by design.
+For CDP screencasting, create an additional session from the existing client
+connection. Handle `Page.screencastFrame`, acknowledge each frame with
+`Page.screencastFrameAck`, and stop with `Page.stopScreencast`. See the
+[Puppeteer](Use-with-Puppeteer.md#screencasting) and
+[Playwright](Use-with-Playwright.md#screencasting) examples. Frames are emitted
+when the page changes, rather than at a fixed rate.
-## Verifying
+MCP offers `browser_screenshot` for individual captures. It does not expose a
+CDP endpoint for a separate viewer to attach to.
-With `obscura serve` running and the viewer open:
+## Verify the viewer
-1. Navigate from another client, for example `obscura fetch https://example.com` through a separate worker, or any Puppeteer/Playwright/MCP session connected to port 9222.
-2. The tab shows the page within a second of it painting.
-3. Closing the viewer tab and reopening it resumes from the most recent frame.
+1. Run `watch.mjs` and open the local viewer.
+2. Navigate or scroll using the script's `page` object. The viewer should update
+ after the next successful capture.
+3. Close and reopen the viewer tab. It should receive the most recent frame.
diff --git a/docs/Your-first-fetch.md b/docs/Your-first-fetch.md
index 47daee01..0715d5e9 100644
--- a/docs/Your-first-fetch.md
+++ b/docs/Your-first-fetch.md
@@ -53,19 +53,20 @@ obscura fetch https://my-spa.example --wait-until domcontentloaded --eval "docum
| `networkidle2` | ≤2 network connections active for 500ms |
| `networkidle0` | 0 network connections active for 500ms |
-(When driving obscura via Puppeteer or Playwright the default is `domcontentloaded` to match client expectations.)
+Puppeteer and Playwright default to `load`. Set `waitUntil` explicitly to choose
+a different readiness condition.
## Common flags
```
--user-agent "..." Override the User-Agent
--timeout 30 Navigation timeout in seconds (default 30)
---wait 5 Extra wait after the page settles, in seconds (default 5)
---selector ".main" CSS selector to narrow output to
+--wait 5 Fixed post-load delay in seconds; omitted uses adaptive settling (5s cap)
+--selector ".main" Wait for a CSS selector; does not filter output
--proxy http://host:port Route through a proxy
--stealth Stealth client (TLS fingerprint, tracker blocking)
-o, --output file.html Write output to a file
--q, --quiet Suppress info logging
+-q, --quiet Suppress logs
```
Full list: [CLI reference](CLI-reference.md).