The headless browser for AI agents and web scraping
fix(cdp): emit complete Page.Frame payloads
rubenssotoe19bd434a90d
diff --git a/crates/obscura-cdp/src/domains/input.rs b/crates/obscura-cdp/src/domains/input.rsindex ca8e2f38..49f541f6 100644--- a/crates/obscura-cdp/src/domains/input.rs+++ b/crates/obscura-cdp/src/domains/input.rs@@ -140,7 +140,7 @@ pub async fn handle(page.evaluate(&code);}} else if event_type == "mouseReleased" {- if let Some(page) = ctx.get_session_page_mut(session_id) {+ let moved_frame = if let Some(page) = ctx.get_session_page_mut(session_id) {let code = format!("(function() {{\var target = (document.elementFromPoint && document.elementFromPoint({x},{y})) || globalThis.__obscura_click_target || document.activeElement || document.body;\@@ -226,22 +226,33 @@ pub async fn handle(if moved {let url = page.url_string();let frame_id = page.frame_id.clone();- ctx.pending_events.push(crate::types::CdpEvent {- method: "Page.frameNavigated".into(),- params: json!({- "frame": {- "id": frame_id,- "url": url,- "domainAndRegistry": "",- "securityOrigin": "",- "mimeType": "text/html",- "adFrameStatus": { "adFrameType": "none" },- },- "type": "Navigation",- }),- session_id: Some(session_id.clone().unwrap_or_default()),- });+ Some((page.id.clone(), frame_id, url))+ } else {+ None}+ } else {+ None+ };+ if let Some((page_id, frame_id, url)) = moved_frame {+ let loader_id = ctx+ .current_loader_ids+ .get(&page_id)+ .cloned()+ .unwrap_or_else(|| format!("loader-blank-{page_id}"));+ ctx.pending_events.push(crate::types::CdpEvent {+ method: "Page.frameNavigated".into(),+ params: json!({+ "frame": crate::domains::page::frame_value(+ &frame_id,+ None,+ &loader_id,+ &url,+ "text/html",+ ),+ "type": "Navigation",+ }),+ session_id: Some(session_id.clone().unwrap_or_default()),+ });}} else if event_type == "mouseWheel" {let delta_x = params.get("deltaX").and_then(|v| v.as_f64()).unwrap_or(0.0);diff --git a/crates/obscura-cdp/src/domains/page.rs b/crates/obscura-cdp/src/domains/page.rsindex 5afc539f..7fd05791 100644--- a/crates/obscura-cdp/src/domains/page.rs+++ b/crates/obscura-cdp/src/domains/page.rs@@ -19,6 +19,63 @@ fn child_frame_id(page_frame_id: &str, frame_id: u32) -> String {format!("{page_frame_id}-frame-{frame_id}")}+fn is_localhost(url: &url::Url) -> bool {+ match url.host() {+ Some(url::Host::Domain(host)) => {+ host.eq_ignore_ascii_case("localhost")+ || host.to_ascii_lowercase().ends_with(".localhost")+ }+ Some(url::Host::Ipv4(address)) => address.is_loopback(),+ Some(url::Host::Ipv6(address)) => address.is_loopback(),+ None => false,+ }+}++fn secure_context_type(url: &url::Url) -> &'static str {+ match url.scheme() {+ "https" | "wss" | "file" | "about" => "Secure",+ "http" | "ws" if is_localhost(url) => "SecureLocalhost",+ _ => "InsecureScheme",+ }+}++/// Build the required `Page.Frame` fields in one place. Generated CDP clients+/// deserialize this object before their frame managers see it, so every path+/// that returns or emits a frame must use the same protocol-complete shape.+pub(crate) fn frame_value(+ id: &str,+ parent_id: Option<&str>,+ loader_id: &str,+ url: &str,+ mime_type: &str,+) -> Value {+ let parsed_url = url::Url::parse(url).ok();+ let security_origin = parsed_url+ .as_ref()+ .map(|url| url.origin().ascii_serialization())+ .unwrap_or_else(|| "null".to_string());+ let secure_context = parsed_url+ .as_ref()+ .map(secure_context_type)+ .unwrap_or("InsecureScheme");+ let mut frame = json!({+ "id": id,+ "loaderId": loader_id,+ "url": url,+ "domainAndRegistry": "",+ "securityOrigin": security_origin,+ "mimeType": mime_type,+ "adFrameStatus": { "adFrameType": "none" },+ "secureContextType": secure_context,+ "crossOriginIsolatedContextType": "NotIsolated",+ "gatedAPIFeatures": [],+ });+ if let Some(parent_id) = parent_id {+ frame["parentId"] = json!(parent_id);+ }+ frame+}+fn child_frame_value(page_frame_id: &str, frame: &obscura_js::frame::FrameRealm) -> Value {let id = child_frame_id(page_frame_id, frame.frame_id());let parent_id = if frame.parent_frame_id() == 0 {@@ -26,16 +83,13 @@ fn child_frame_value(page_frame_id: &str, frame: &obscura_js::frame::FrameRealm)} else {child_frame_id(page_frame_id, frame.parent_frame_id())};- json!({- "id": id,- "parentId": parent_id,- "loaderId": format!("{id}-loader"),- "url": frame.url(),- "domainAndRegistry": "",- "securityOrigin": frame.origin(),- "mimeType": "text/html",- "adFrameStatus": { "adFrameType": "none" },- })+ frame_value(+ &id,+ Some(&parent_id),+ &format!("{id}-loader"),+ frame.url(),+ "text/html",+ )}/// The page's child frames, flattened with each parent ahead of its children@@ -59,7 +113,7 @@ pub fn child_frame_values(page: &obscura_browser::Page) -> Vec<Value> {/// The page's live frame hierarchy. `childFrames` used to be hardcoded empty,/// so a client was told the page had no frames however many it had built.-fn frame_tree(page: &obscura_browser::Page) -> Value {+fn frame_tree(page: &obscura_browser::Page, loader_id: &str) -> Value {fn children(page: &obscura_browser::Page, parent_frame_id: u32) -> Vec<Value> {page.frames.iter()@@ -74,15 +128,13 @@ fn frame_tree(page: &obscura_browser::Page) -> Value {}json!({- "frame": {- "id": page.frame_id,- "loaderId": "initial-loader",- "url": page.url_string(),- "domainAndRegistry": "",- "securityOrigin": page.url_string(),- "mimeType": "text/html",- "adFrameStatus": { "adFrameType": "none" },- },+ "frame": frame_value(+ &page.frame_id,+ None,+ loader_id,+ &page.url_string(),+ "text/html",+ ),"childFrames": children(page, 0),})}@@ -874,7 +926,7 @@ pub fn emit_navigation_events(},CdpEvent {method: "Page.frameNavigated".into(),- params: json!({"frame": {"id": frame_id, "loaderId": loader_id, "url": page_url, "domainAndRegistry": "", "securityOrigin": page_url, "mimeType": nav_mime, "adFrameStatus": {"adFrameType": "none"}}, "type": "Navigation"}),+ params: json!({"frame": frame_value(frame_id, None, loader_id, page_url, &nav_mime), "type": "Navigation"}),session_id: es.clone(),},CdpEvent {@@ -1229,7 +1281,12 @@ pub async fn handle(let page = ctx.get_session_page(session_id).ok_or("No page for session")?;- Ok(json!({ "frameTree": frame_tree(page) }))+ let loader_id = ctx+ .current_loader_ids+ .get(&page.id)+ .cloned()+ .unwrap_or_else(|| format!("loader-blank-{}", page.id));+ Ok(json!({ "frameTree": frame_tree(page, &loader_id) }))}"createIsolatedWorld" => {let (frame_id_param, world_name, page_url, page_id) = {diff --git a/crates/obscura-cdp/tests/page_frame_contract.rs b/crates/obscura-cdp/tests/page_frame_contract.rsnew file mode 100644index 00000000..e7f39825--- /dev/null+++ b/crates/obscura-cdp/tests/page_frame_contract.rs@@ -0,0 +1,229 @@+use obscura_cdp::dispatch::{dispatch, CdpContext};+use obscura_cdp::types::CdpRequest;+use serde_json::{json, Value};+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::TcpListener;++async fn serve() -> String {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ tokio::spawn(async move {+ while let Ok((mut socket, _)) = listener.accept().await {+ tokio::spawn(async move {+ let mut buffer = [0u8; 2048];+ let read = socket.read(&mut buffer).await.unwrap_or(0);+ let request = String::from_utf8_lossy(&buffer[..read]);+ let body = if request.starts_with("GET /child.html ") {+ "<html><body>child</body></html>"+ } else {+ r##"<!doctype html><html><body>+ <a id="route" href="#next">next</a>+ <iframe src="/child.html"></iframe>+ <script>+ route.addEventListener('click', event => {+ event.preventDefault();+ history.pushState({}, '', '/next');+ });+ </script>+ </body></html>"##+ };+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ let _ = socket.write_all(response.as_bytes()).await;+ });+ }+ });+ format!("http://{address}/")+}++async fn cdp(+ ctx: &mut CdpContext,+ id: u64,+ method: &str,+ params: Value,+ session_id: Option<&str>,+) -> Value {+ let response = dispatch(+ &CdpRequest {+ id,+ method: method.to_string(),+ params,+ session_id: session_id.map(str::to_string),+ },+ ctx,+ )+ .await;+ assert!(+ response.error.is_none(),+ "CDP {method} failed: {:?}",+ response.error+ );+ response.result.unwrap_or_else(|| json!({}))+}++fn assert_frame_contract(frame: &Value) {+ for field in [+ "id",+ "loaderId",+ "url",+ "domainAndRegistry",+ "securityOrigin",+ "mimeType",+ "secureContextType",+ "crossOriginIsolatedContextType",+ ] {+ assert!(+ frame[field].is_string(),+ "{field} is missing or not a string: {frame}"+ );+ }+ assert!(+ matches!(+ frame["secureContextType"].as_str(),+ Some("Secure" | "SecureLocalhost" | "InsecureScheme" | "InsecureAncestor")+ ),+ "invalid secureContextType: {frame}"+ );+ assert!(+ matches!(+ frame["crossOriginIsolatedContextType"].as_str(),+ Some("Isolated" | "NotIsolated" | "NotIsolatedFeatureDisabled")+ ),+ "invalid crossOriginIsolatedContextType: {frame}"+ );+ assert!(+ frame["gatedAPIFeatures"].is_array(),+ "gatedAPIFeatures is missing: {frame}"+ );+}++#[tokio::test(flavor = "current_thread")]+async fn every_page_frame_path_uses_the_current_cdp_contract() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let mut ctx = CdpContext::new();++ let created = cdp(+ &mut ctx,+ 1,+ "Target.createTarget",+ json!({"url": "about:blank"}),+ None,+ )+ .await;+ let page_id = created["targetId"].as_str().unwrap().to_string();+ let attached = cdp(+ &mut ctx,+ 2,+ "Target.attachToTarget",+ json!({"targetId": page_id, "flatten": true}),+ None,+ )+ .await;+ let session_id = attached["sessionId"].as_str().unwrap().to_string();++ let initial_tree = cdp(+ &mut ctx,+ 3,+ "Page.getFrameTree",+ json!({}),+ Some(&session_id),+ )+ .await;+ let initial_frame = &initial_tree["frameTree"]["frame"];+ assert_frame_contract(initial_frame);+ assert_eq!(initial_frame["loaderId"], format!("loader-blank-{page_id}"));+ assert_eq!(initial_frame["secureContextType"], "Secure");++ let navigation_event_start = ctx.pending_events.len();+ let navigated = cdp(+ &mut ctx,+ 4,+ "Page.navigate",+ json!({"url": serve().await, "waitUntil": "load"}),+ Some(&session_id),+ )+ .await;+ let loader_id = navigated["loaderId"].as_str().unwrap();+ let navigation_frame = &ctx.pending_events[navigation_event_start..]+ .iter()+ .find(|event| {+ event.method == "Page.frameNavigated" && event.params["frame"]["id"] == page_id+ })+ .expect("main-frame navigation event was not emitted")+ .params["frame"];+ assert_frame_contract(navigation_frame);+ assert_eq!(navigation_frame["loaderId"], loader_id);+ assert_eq!(navigation_frame["secureContextType"], "SecureLocalhost");++ cdp(+ &mut ctx,+ 5,+ "Runtime.evaluate",+ json!({"expression": "document.title", "returnByValue": true}),+ Some(&session_id),+ )+ .await;+ let loaded_tree = cdp(+ &mut ctx,+ 6,+ "Page.getFrameTree",+ json!({}),+ Some(&session_id),+ )+ .await;+ let root = &loaded_tree["frameTree"];+ assert_frame_contract(&root["frame"]);+ assert_eq!(root["frame"]["loaderId"], loader_id);+ let child = &root["childFrames"][0]["frame"];+ assert_frame_contract(child);+ assert_eq!(child["parentId"], root["frame"]["id"]);+ let child_event_frame = &ctx+ .pending_events+ .iter()+ .find(|event| {+ event.method == "Page.frameNavigated" && event.params["frame"]["id"] == child["id"]+ })+ .expect("child-frame navigation event was not emitted")+ .params["frame"];+ assert_frame_contract(child_event_frame);++ cdp(+ &mut ctx,+ 7,+ "Runtime.evaluate",+ json!({+ "expression": "document.elementFromPoint = () => document.getElementById('route')"+ }),+ Some(&session_id),+ )+ .await;+ cdp(+ &mut ctx,+ 8,+ "Input.dispatchMouseEvent",+ json!({"type": "mousePressed", "x": 0, "y": 0, "button": "left"}),+ Some(&session_id),+ )+ .await;+ let route_event_start = ctx.pending_events.len();+ cdp(+ &mut ctx,+ 9,+ "Input.dispatchMouseEvent",+ json!({"type": "mouseReleased", "x": 0, "y": 0, "button": "left"}),+ Some(&session_id),+ )+ .await;+ let route_frame = &ctx.pending_events[route_event_start..]+ .iter()+ .find(|event| {+ event.method == "Page.frameNavigated" && event.params["frame"]["id"] == page_id+ })+ .expect("same-document navigation event was not emitted")+ .params["frame"];+ assert_frame_contract(route_frame);+ assert_eq!(route_frame["loaderId"], loader_id);+ assert!(route_frame["url"].as_str().unwrap().ends_with("/next"));+}