Skip to content

The headless browser for AI agents and web scraping

docs: document the interception API and refresh the skill

SGavrl5db0dc0e01c0
diff --git a/AGENTS.md b/AGENTS.md
index def1d045..d358cf41 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -65,13 +65,13 @@ edit instead.
## Architecture
-- **obscura-cli** — CLI: `fetch` (`--dump assets|html|text|links|markdown|original`, `--eval <JS>`), `serve` (CDP server), `scrape`, `mcp`. `--proxy` and `--allow-private-network` are global flags (valid before or after the subcommand); `--stealth` is a per-subcommand flag, available on `fetch`, `serve`, and `mcp` but not `scrape`.
+- **obscura-cli** — CLI: `fetch` (`--dump assets|html|text|links|markdown|original|cookies`, `--eval <JS>`), `serve` (CDP server), `scrape`, `mcp`. `--proxy`, `--stealth`, and `--allow-private-network` are global flags: valid before or after the subcommand and applied to `fetch`, `serve`, `scrape`, and `mcp` (a `scrape` run forwards `--stealth` to each worker via `OBSCURA_STEALTH`).
- **obscura-cdp** — Chrome DevTools Protocol server (WebSocket). Sessions are `"{targetId}-session"`.
- **obscura-js** — V8/`deno_core` runtime. `js/bootstrap.js` is the DOM/browser shim; `src/ops.rs` bridges JS to Rust DOM ops; `src/runtime.rs` owns the isolate and the per-page `ObscuraState`.
- **obscura-dom** — DOM tree (`src/tree.rs`).
- **obscura-net** — HTTP client (`client.rs`), stealth client (`wreq_client.rs`), cookie jar, robots cache, tracker blocklist.
- **obscura-browser** — the `Page` type, navigation, JS evaluation.
-- **obscura** — embeddable Rust library API (git dependency; builds V8 locally, not on crates.io).
+- **obscura** — embeddable Rust library API (git dependency; builds V8 locally, not on crates.io). Public request-interception API on `Page`: `add_preload_script`, `enable_interception` (channel of `InterceptedRequest`, resolved with `InterceptResolution::{Continue, Fulfill, Fail}`), and passive `on_request` / `on_response`. `op_fetch_url` invokes these for JS `fetch()`/XHR, so when touching it keep a `Continue` URL rewrite behind `validate_fetch_url` (the SSRF gate, same as redirects).
## Conventions
diff --git a/docs/Intercept-and-modify-requests.md b/docs/Intercept-and-modify-requests.md
index d3300c38..3e5d7d21 100644
--- a/docs/Intercept-and-modify-requests.md
+++ b/docs/Intercept-and-modify-requests.md
@@ -118,3 +118,7 @@ page.on('request', req => {
```
Built-in: `--stealth` ships with a tracker blocklist that handles most of these without per-script setup. See [Configure stealth and proxies](Configure-stealth-and-proxies.md).
+
+## From the Rust library
+
+The patterns above drive interception over CDP from Puppeteer or Playwright. If you embed the engine with the `obscura` crate, the same capability is a native API on `Page`: `on_request` / `on_response` callbacks, an `enable_interception()` channel that can block, mock, or rewrite requests, and `add_preload_script` to run code before the page's own scripts. See [Use as a Rust library](Use-as-a-Rust-library.md#intercept-requests).
diff --git a/docs/Use-as-a-Rust-library.md b/docs/Use-as-a-Rust-library.md
index 6f9d6145..54017d2c 100644
--- a/docs/Use-as-a-Rust-library.md
+++ b/docs/Use-as-a-Rust-library.md
@@ -55,11 +55,85 @@ async fn main() -> anyhow::Result<()> {
- `query_selector(css)` first match as an `Element`, or `None`
- `wait_for_selector(css, Duration).await` poll until present
- `settle(max_ms).await` drive the event loop so async work (`fetch`, timers) completes
+- `on_request(cb)` / `on_response(cb)` passive callbacks for every request and response
+- `enable_interception()` channel to block, mock, or rewrite requests
+- `add_preload_script(js)` run a script before the page's own scripts
`Element`: `text()`, `attribute(name)`, `click()`.
`CookieStore`: `set`, `get_all`, `get_for_url`, `save_to_file`, `load_from_file`.
+## Intercept requests
+
+The interception API observes, blocks, mocks, and rewrites the requests a page makes, including JavaScript `fetch()` and XHR. Use it to capture API payloads while crawling, block trackers, or mock responses in tests.
+
+### Passive callbacks
+
+`on_request` and `on_response` fire for every request and response (navigation and JS `fetch()`/XHR) and are non-blocking. `on_response` is the main path for capturing the JSON an SPA loads asynchronously.
+
+```rust
+use obscura::{Browser, ResourceType};
+use std::sync::Arc;
+
+let browser = Browser::new()?;
+let mut page = browser.new_page().await?;
+
+page.on_response(Arc::new(|info, resp| {
+ if info.resource_type == ResourceType::Fetch {
+ println!("{} -> {} bytes", info.url, resp.body.len());
+ }
+}));
+
+page.goto("https://example.com").await?;
+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.
+
+```rust
+use obscura::{Browser, InterceptResolution};
+
+let mut page = browser.new_page().await?;
+let mut rx = page.enable_interception();
+
+tokio::spawn(async move {
+ while let Some(req) = rx.recv().await {
+ let action = if req.url.contains("/ads") {
+ InterceptResolution::Fail { reason: "blocked".into() }
+ } else if req.url.ends_with("/api/flags") {
+ InterceptResolution::Fulfill {
+ status: 200,
+ headers: Default::default(),
+ body: r#"{"newDashboard":true}"#.into(),
+ }
+ } else {
+ // Pass through, or rewrite by setting url/method/headers/body.
+ InterceptResolution::Continue { url: None, method: None, headers: None, body: None }
+ };
+ let _ = req.resolver.send(action);
+ }
+});
+
+page.goto("https://example.com").await?;
+page.settle(2000).await;
+```
+
+A `Continue` with `url: Some(...)` rewrites the target. The new URL is re-checked against the SSRF / private-network gate, so a rewrite cannot reach an internal address that would otherwise need `--allow-private-network`.
+
+### Preload scripts
+
+`add_preload_script` runs a script before any of the page's own `<script>` tags (the CDP `Page.addScriptToEvaluateOnNewDocument` contract), so it can install hooks before the page bootstraps. Call it before `goto`.
+
+```rust
+let mut page = browser.new_page().await?;
+page.add_preload_script("window.__patched = true;");
+page.goto("https://example.com").await?;
+```
+
+`resource_type` reports `Fetch` for JS-initiated requests and does not yet split `Xhr` from `Fetch`.
+
## When to use which interface
- Embedding the engine in a Rust service: this crate.
diff --git a/skills/obscura/SKILL.md b/skills/obscura/SKILL.md
index 00834372..fd752821 100644
--- a/skills/obscura/SKILL.md
+++ b/skills/obscura/SKILL.md
@@ -27,12 +27,12 @@ Obscura is roughly as fast as warm Chrome, ~2× faster cold, parallelizes far be
```bash
git clone https://github.com/h4ckf0r0day/obscura.git
cd obscura
-CARGO_TARGET_DIR=/tmp/obscura-target cargo build -p obscura-cli --bin obscura --no-default-features
+CARGO_TARGET_DIR=/tmp/obscura-target cargo build -p obscura-cli --bin obscura
```
Resulting binary: `/tmp/obscura-target/debug/obscura`
-`--no-default-features` skips the stealth build. Stealth needs `cmake` locally because it pulls `wreq` / BoringSSL.
+The default build has no stealth and needs no extra tools. Stealth is opt-in (see below) and pulls `wreq` / BoringSSL, so it needs `cmake` locally.
### Stealth build
@@ -42,12 +42,18 @@ CARGO_TARGET_DIR=/tmp/obscura-target cargo build -p obscura-cli --bin obscura --
What stealth gives you:
-- **Per-session randomized fingerprints** — GPU, canvas, audio, battery
+- **Consistent browser fingerprint** so cross-layer checks pass: the TLS ClientHello, User-Agent, `navigator` surfaces, and WebGL renderer all agree on one Chrome identity rather than contradicting each other
- **3,520 tracker domains blocked** (built-in blocklist)
- **`navigator.webdriver` masked**
- **Native functions patched** so common automation detectors can't unmask them via `Function.prototype.toString` inspection
- **TLS / HTTP-2 fingerprint** matching real Chromium (defeats most JA3/JA4 + ALPN-ordering bot management)
+Enable it at runtime with the global `--stealth` flag (works on `fetch`, `serve`, `scrape`, and `mcp`, before or after the subcommand). The flag needs a stealth-feature build for the TLS layer; without it `--stealth` still does tracker blocking.
+
+```bash
+/tmp/obscura-target/debug/obscura fetch https://example.com/ --stealth --dump text
+```
+
Use stealth against: Cloudflare Turnstile non-interactive, Akamai BMP, PerimeterX, DataDome.
Stealth still won't clear: hard interactive CAPTCHAs (Turnstile interactive, hCaptcha challenge), and fingerprinters using WebGPU/WebAssembly quirks not yet patched.
@@ -58,10 +64,12 @@ Stealth still won't clear: hard interactive CAPTCHAs (Turnstile interactive, hCa
```
Useful flags:
-- `--dump text` — visible text only
-- `--dump html` — full rendered DOM
-- `--quiet` — suppress progress logs
-- `--timeout <ms>` — per-page timeout
+- `--dump text`: visible text only
+- `--dump html`: full rendered DOM
+- `--dump assets`: every external resource plus `fetch()`/XHR URLs, one JSON object per line
+- `--dump cookies`: all cookies as JSON, including HttpOnly
+- `--quiet`: suppress progress logs
+- `--timeout <ms>`: per-page timeout
## CDP server (Puppeteer / Playwright)
@@ -95,6 +103,10 @@ console.log(await page.title());
await browser.disconnect();
```
+## Request interception
+
+Over CDP, `page.setRequestInterception(true)` (Puppeteer) or `page.route` (Playwright) block, modify, or mock requests as usual. Embedding the engine with the `obscura` Rust crate gives the same thing as a native `Page` API: `on_request` / `on_response` callbacks (capture SPA API payloads without reverse-engineering the bundle), an `enable_interception()` channel to block, mock, or rewrite, and `add_preload_script` to run code before the page's own scripts.
+
## Scaling profile
- ✅ **High concurrency, low resource:** static + lightly-dynamic pages — hundreds of parallel fetches per box.