Skip to content

The headless browser for AI agents and web scraping

fix(network): preserve destinations for dynamic resources

SGavrl359362f0a76f
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index e6c64cea..80a77691 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -4260,7 +4260,7 @@ impl Page {
intercepted: ev.intercepted,
url: ev.url,
method: ev.method,
- resource_type: "Fetch".to_string(),
+ resource_type: ev.resource_type,
status: ev.status,
headers: std::collections::HashMap::new(),
response_headers: Arc::new(ev.response_headers),
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 0a815d4e..b2ffd015 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -380,7 +380,7 @@ async function __fetchDynClassicScript(task) {
body = _decodeDataScriptUrl(task.url);
} else {
const raw = await __obscuraCore.ops.op_fetch_url(
- task.url, "GET", "{}", new Uint8Array(0), task.pageOrigin, "no-cors", "same-origin", true
+ task.url, "GET", "{}", new Uint8Array(0), task.pageOrigin, "no-cors", "same-origin", "Script"
);
const parsed = JSON.parse(raw);
// The HTML script-fetch algorithm treats an unsuccessful HTTP response
@@ -616,7 +616,7 @@ async function _fetchLinkedCss(url, pageOrigin, depth = 0, seen = new Set()) {
}
seen.add(url);
const raw = await __obscuraCore.ops.op_fetch_url(
- url, "GET", "{}", new Uint8Array(0), pageOrigin, "no-cors", "same-origin", true
+ url, "GET", "{}", new Uint8Array(0), pageOrigin, "no-cors", "same-origin", "Stylesheet"
);
const parsed = JSON.parse(raw);
if (parsed.blocked || parsed.status >= 400 || parsed.status === 0) {
@@ -4620,7 +4620,7 @@ class Element extends Node {
try { pageOrigin = new URL(_domParse('document_url') || 'about:blank').origin; } catch (_) {}
__obscuraCore.ops.op_fetch_url(
fullUrl, 'GET', '{}', new Uint8Array(0), pageOrigin,
- 'no-cors', 'same-origin', true
+ 'no-cors', 'same-origin', 'Document'
).then(raw => {
if (el._iframeLoadingUrl !== fullUrl) return;
const response = JSON.parse(raw);
@@ -7732,7 +7732,7 @@ function _serializeBody(initBody, headers, synthesizeContentType = true) {
return new TextEncoder().encode(typeof initBody === 'string' ? initBody : String(initBody));
}
-globalThis.fetch = async (input, init = {}) => {
+async function _fetch(input, init = {}, resourceType = "Fetch") {
init = init || {};
const request = input instanceof Request ? input : null;
let url = typeof input === "string"
@@ -7766,7 +7766,7 @@ globalThis.fetch = async (input, init = {}) => {
throw new TypeError("Failed to execute 'fetch': '" + fetchCredentials + "' is not a valid RequestCredentials value");
}
const pageOrigin = (function() { try { const u = new URL(_domParse("document_url") || "about:blank"); return u.origin; } catch(e) { return ""; } })();
- const raw = await __obscuraCore.ops.op_fetch_url(url, method, hdrs, body, pageOrigin, fetchMode, fetchCredentials, false);
+ const raw = await __obscuraCore.ops.op_fetch_url(url, method, hdrs, body, pageOrigin, fetchMode, fetchCredentials, resourceType);
const parsed = JSON.parse(raw);
if (parsed.blocked) {
const err = new TypeError('net::ERR_FAILED');
@@ -7804,7 +7804,8 @@ globalThis.fetch = async (input, init = {}) => {
});
}
return response;
-};
+}
+globalThis.fetch = (input, init = {}) => _fetch(input, init);
if (typeof Headers === "undefined") {
globalThis.Headers = class Headers {
@@ -7935,13 +7936,13 @@ globalThis.XMLHttpRequest = class XMLHttpRequest extends XMLHttpRequestEventTarg
// Same rule as fetch: always resolve through the URL parser.
let url = _resolveUrl(this._url);
- fetch(url, {
+ _fetch(url, {
method: this._method,
headers: this._headers,
body: body || undefined,
mode: 'cors',
credentials: this.withCredentials ? 'include' : 'same-origin',
- }).then(async (resp) => {
+ }, 'XHR').then(async (resp) => {
if (xhr._aborted) return;
xhr.status = resp.status;
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 5123c998..a8401523 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -89,6 +89,7 @@ pub struct JsNetworkEvent {
pub intercepted: bool,
pub url: String,
pub method: String,
+ pub resource_type: String,
pub status: u16,
pub response_headers: HashMap<String, String>,
pub body_size: usize,
@@ -3245,8 +3246,17 @@ async fn op_fetch_url(
#[string] origin: String,
#[string] mode: String,
#[string] credentials: String,
- internal_load: bool,
+ #[string] destination: String,
) -> Result<String, deno_error::JsErrorBox> {
+ let (resource_type, resource_type_name) = match destination.as_str() {
+ "Script" => (ResourceType::Script, "Script"),
+ "Stylesheet" => (ResourceType::Stylesheet, "Stylesheet"),
+ "Document" => (ResourceType::Document, "Document"),
+ "XHR" => (ResourceType::Xhr, "XHR"),
+ _ => (ResourceType::Fetch, "Fetch"),
+ };
+ let internal_load = matches!(resource_type,
+ ResourceType::Script | ResourceType::Stylesheet | ResourceType::Document);
let body = body.to_vec();
tracing::debug!(
"op_fetch_url called: {} {} (intercept check pending)",
@@ -3356,7 +3366,7 @@ async fn op_fetch_url(
url: url.clone(),
method: method.clone(),
headers: custom_headers.clone(),
- resource_type: "Fetch".to_string(),
+ resource_type: resource_type_name.to_string(),
resolver: resolve_tx,
};
if tx.send(intercepted).is_ok() {
@@ -3375,6 +3385,7 @@ async fn op_fetch_url(
record_js_network_completion(&state, JsNetworkEvent {
request_id: request_id.clone(), intercepted: true,
url: url.clone(), method: method.clone(), status,
+ resource_type: resource_type_name.to_string(),
response_headers: h.clone(), body_size,
timestamp: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default().as_secs_f64(),
@@ -3496,7 +3507,7 @@ async fn op_fetch_url(
url: parsed,
method: method.clone(),
headers: custom_headers.clone(),
- resource_type: ResourceType::Fetch,
+ resource_type,
};
cbs.fire_request(&info).await;
}
@@ -3613,6 +3624,10 @@ async fn op_fetch_url(
callbacks.clone(),
allow_private_network,
internal_load,
+ resource_type,
+ resource_type_name,
+ request_id,
+ was_intercepted,
)
.await;
}
@@ -3877,7 +3892,7 @@ async fn op_fetch_url(
);
let info = RequestInfo {
url: resp.url.clone(), method: current_method.as_str().to_string(),
- headers: resp_headers.clone(), resource_type: ResourceType::Fetch,
+ headers: resp_headers.clone(), resource_type,
};
cbs.fire_response(&info, &resp).await;
}
@@ -3886,6 +3901,7 @@ async fn op_fetch_url(
record_js_network_completion(&state, JsNetworkEvent {
request_id, intercepted: was_intercepted,
url: current_url, method: current_method.as_str().to_string(), status,
+ resource_type: resource_type_name.to_string(),
response_headers: resp_headers, body_size: resp_bytes.len(),
timestamp: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default().as_secs_f64(),
@@ -3920,8 +3936,7 @@ fn fetch_response(
/// and CORS semantics but sends every hop through the wreq stealth client so
/// the request carries the Chrome TLS fingerprint and client hints. Cookie
/// handling lives inside StealthHttpClient::send_single, which shares the
-/// context jar. Response bodies are not mirrored into the CDP
-/// Network.getResponseBody buffer here; that is a follow-up for stealth fetches.
+/// context jar. Request identity and destination survive transport selection.
#[cfg(feature = "stealth")]
async fn stealth_fetch_all(
state: Rc<RefCell<OpState>>,
@@ -3937,6 +3952,10 @@ async fn stealth_fetch_all(
callbacks: Option<Arc<CallbackRegistry>>,
allow_private_network: bool,
internal_load: bool,
+ resource_type: ResourceType,
+ resource_type_name: &'static str,
+ request_id: String,
+ was_intercepted: bool,
) -> Result<String, deno_error::JsErrorBox> {
let mut current_url = url.clone();
let mut current_method = method;
@@ -4106,11 +4125,13 @@ async fn stealth_fetch_all(
let metadata = serde_json::json!({
"status": if opaque { 0 } else { status },
+ "requestId": request_id,
"url": current_url,
"redirected": redirects_followed > 0,
"opaque": opaque,
"headers": script_headers,
});
+ let body_state = Rc::downgrade(&state);
let body = Box::pin(async move {
let _page_in_flight = page_in_flight;
let resp_bytes = response.body.await
@@ -4122,12 +4143,22 @@ async fn stealth_fetch_all(
resp_bytes.clone(), redirected_from,
);
let info = RequestInfo {
- url: resp.url.clone(), method: current_method,
- headers: resp_headers, resource_type: ResourceType::Fetch,
+ url: resp.url.clone(), method: current_method.clone(),
+ headers: resp_headers.clone(), resource_type,
};
cbs.fire_response(&info, &resp).await;
}
}
+ if let Some(state) = body_state.upgrade() {
+ record_js_network_completion(&state, JsNetworkEvent {
+ request_id, intercepted: was_intercepted,
+ url: current_url, method: current_method, status,
+ resource_type: resource_type_name.to_string(),
+ response_headers: resp_headers, body_size: resp_bytes.len(),
+ timestamp: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default().as_secs_f64(),
+ }, &String::from_utf8_lossy(&resp_bytes), false);
+ }
Ok(resp_bytes)
});
fetch_body_result(&state, metadata, body, internal_load).await
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index e712c961..15b3934b 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -20125,6 +20125,117 @@ mod tests {
assert_eq!(rt.get_network_response_body(&request_id).unwrap().body, "arrived");
}
+ async fn assert_script_fetch_xhr_destinations(fulfilled: bool, stealth: bool) {
+ const BODY: &str = "globalThis.destinationLoaded = 1;";
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let origin = format!("http://{}", listener.local_addr().unwrap());
+ if fulfilled {
+ drop(listener);
+ } else {
+ std::thread::spawn(move || {
+ use std::io::{Read as _, Write as _};
+ for _ in 0..3 {
+ let (mut stream, _) = listener.accept().unwrap();
+ let mut request = [0u8; 4096];
+ stream.read(&mut request).unwrap();
+ write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: text/javascript\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", BODY.len(), BODY).unwrap();
+ }
+ });
+ }
+ let mut rt = redirect_runtime_for_origin(&origin);
+ #[cfg(feature = "stealth")]
+ if stealth {
+ rt.set_stealth_client(std::sync::Arc::new(obscura_net::StealthHttpClient::new(
+ std::sync::Arc::new(obscura_net::CookieJar::new()),
+ )));
+ }
+ #[cfg(not(feature = "stealth"))]
+ assert!(!stealth);
+ let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let responses = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let callbacks = std::sync::Arc::new(obscura_net::CallbackRegistry::new());
+ let capture = requests.clone();
+ callbacks.add_request(std::sync::Arc::new(move |request| {
+ capture.lock().unwrap().push(request.resource_type);
+ }));
+ let capture = responses.clone();
+ callbacks.add_response(std::sync::Arc::new(move |request, _| {
+ capture.lock().unwrap().push(request.resource_type);
+ }));
+ rt.set_callbacks(callbacks);
+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
+ if fulfilled {
+ rt.set_intercept_tx(tx);
+ rt.set_intercept_enabled(true);
+ }
+ let load = rt.call_function_on_for_cdp(
+ r#"async () => {
+ await new Promise((resolve, reject) => {
+ const script = document.createElement('script');
+ script.src = '/same.js';
+ script.onload = resolve; script.onerror = reject;
+ document.head.append(script);
+ });
+ const fetched = await (await fetch('/same.js', {resourceType: 'Script'})).text();
+ const xhrBody = await new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest(); xhr.open('GET', '/same.js');
+ xhr.onload = () => resolve(xhr.responseText); xhr.onerror = reject; xhr.send();
+ });
+ return [globalThis.destinationLoaded, fetched, xhrBody];
+ }"#, None, &[], true, true,
+ );
+ let resolve = async {
+ let mut types = Vec::new();
+ if fulfilled {
+ for _ in 0..3 {
+ let request = rx.recv().await.unwrap();
+ types.push(request.resource_type);
+ request.resolver.send(crate::ops::InterceptResolution::Fulfill {
+ status: 200, headers: std::collections::HashMap::new(),
+ body: BODY.to_string(), body_base64: String::new(),
+ }).unwrap();
+ }
+ }
+ types
+ };
+ let (result, intercepted) = tokio::time::timeout(
+ std::time::Duration::from_secs(5), async { tokio::join!(load, resolve) },
+ ).await.expect("dynamic resources complete");
+ assert_eq!(result.unwrap().value.unwrap(), serde_json::json!([1, BODY, BODY]));
+ let events = rt.take_js_network_events();
+ assert_eq!(events.iter().map(|event| event.resource_type.as_str()).collect::<Vec<_>>(),
+ vec!["Script", "Fetch", "XHR"]);
+ for event in &events {
+ assert_eq!(rt.get_network_response_body(&event.request_id).unwrap().body, BODY);
+ }
+ if fulfilled {
+ assert_eq!(intercepted, vec!["Script", "Fetch", "XHR"]);
+ assert!(requests.lock().unwrap().is_empty());
+ assert!(responses.lock().unwrap().is_empty());
+ } else {
+ let expected = vec![obscura_net::ResourceType::Script, obscura_net::ResourceType::Fetch,
+ obscura_net::ResourceType::Xhr];
+ assert_eq!(*requests.lock().unwrap(), expected);
+ assert_eq!(*responses.lock().unwrap(), expected);
+ }
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn dynamic_resource_destinations_reach_network_events_and_callbacks() {
+ assert_script_fetch_xhr_destinations(false, false).await;
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn dynamic_resource_destinations_survive_interception_fulfillment() {
+ assert_script_fetch_xhr_destinations(true, false).await;
+ }
+
+ #[cfg(feature = "stealth")]
+ #[tokio::test(flavor = "current_thread")]
+ async fn stealth_dynamic_resource_destinations_reach_network_events_and_callbacks() {
+ assert_script_fetch_xhr_destinations(false, true).await;
+ }
+
#[tokio::test(flavor = "current_thread")]
async fn fetch_response_reports_the_final_redirect_url() {
let mut rt = redirect_chain_runtime(3);