The headless browser for AI agents and web scraping
fix(cdp): deliver Runtime.bindingCalled to the session that subscribed
xrip6df7c577895c
diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rsindex 997078d2..980eb0ca 100644--- a/crates/obscura-cdp/src/dispatch.rs+++ b/crates/obscura-cdp/src/dispatch.rs@@ -56,6 +56,12 @@ pub struct CdpContext {target_session_counter: u64,pub preload_scripts: Vec<(String, String)>, // (identifier, source)pub preload_counter: u32,+ // Which sessions asked for each `Runtime.addBinding` name. A binding is a+ // session-scoped subscription in CDP, and a client discards any event whose+ // sessionId is not one it holds, so the call has to go back to the session+ // that registered the name rather than to whichever session of the page+ // happens to come first out of a HashMap.+ pub binding_sessions: HashMap<String, Vec<String>>, // binding name -> session ids// World names registered via Page.createIsolatedWorld. After every// navigation Obscura clears execution contexts (via// Runtime.executionContextsCleared) and must re-emit a@@ -166,6 +172,7 @@ impl CdpContext {browser_context_counter: 0,target_session_counter: 0,preload_scripts: Vec::new(),+ binding_sessions: HashMap::new(),preload_counter: 0,fetch_intercept: FetchInterceptState::new(),intercept_tx: None,@@ -552,12 +559,21 @@ pub async fn dispatch(req: &CdpRequest, ctx: &mut CdpContext) -> CdpResponse {// in the queue while V8 is running inside a CDP handler, so there is no// window in which they could pile up without a draining opportunity.pub(crate) fn drain_binding_calls(ctx: &mut CdpContext) {- // page_id -> session_id (any one session that holds this page).- let page_to_session: HashMap<String, String> = ctx- .sessions- .iter()- .map(|(sid, pid)| (pid.clone(), sid.clone()))- .collect();+ // page_id -> every session on that page. A page commonly has more than one:+ // Target.createTarget opens a session and the Target.attachToTarget that+ // follows opens another, so a client that reaches a page the ordinary way+ // holds two and uses the second.+ let mut page_to_sessions: HashMap<&str, Vec<&str>> = HashMap::new();+ for (session_id, page_id) in &ctx.sessions {+ page_to_sessions+ .entry(page_id.as_str())+ .or_default()+ .push(session_id.as_str());+ }+ // ctx.sessions is a HashMap, so fix an order the events can be asserted in.+ for sessions in page_to_sessions.values_mut() {+ sessions.sort_unstable();+ }let mut events: Vec<CdpEvent> = Vec::new();for page in &mut ctx.pages {@@ -565,25 +581,44 @@ pub(crate) fn drain_binding_calls(ctx: &mut CdpContext) {if calls.is_empty() {continue;}- let Some(session_id) = page_to_session.get(&page.id).cloned() else {+ let Some(page_sessions) = page_to_sessions.get(page.id.as_str()) else {// No session attached — drop the calls; there is no client to// deliver them to.continue;};for (name, payload) in calls {- events.push(CdpEvent {- method: "Runtime.bindingCalled".into(),- // Use executionContextId=2: the default main-frame context- // emitted post-navigation (see domains/page.rs phase1).- // Puppeteer matches on session_id + binding name and- // tolerates any registered context id.- params: json!({- "name": name,- "payload": payload,- "executionContextId": 2,- }),- session_id: Some(session_id.clone()),- });+ // The sessions that asked for this binding, narrowed to the page the+ // call came from. Falling back to every session of the page keeps a+ // binding that was installed without a session (a preload, or a+ // direct embedder) deliverable rather than silently dropped.+ let registered = ctx.binding_sessions.get(&name);+ let targets: Vec<&str> = page_sessions+ .iter()+ .copied()+ .filter(|session| {+ registered.is_none_or(|owners| owners.iter().any(|owner| owner == session))+ })+ .collect();+ let targets = if targets.is_empty() {+ page_sessions.clone()+ } else {+ targets+ };+ for session_id in targets {+ events.push(CdpEvent {+ method: "Runtime.bindingCalled".into(),+ // Use executionContextId=2: the default main-frame context+ // emitted post-navigation (see domains/page.rs phase1).+ // Puppeteer matches on session_id + binding name and+ // tolerates any registered context id.+ params: json!({+ "name": name,+ "payload": payload,+ "executionContextId": 2,+ }),+ session_id: Some(session_id.to_string()),+ });+ }}}ctx.pending_events.extend(events);diff --git a/crates/obscura-cdp/src/domains/runtime.rs b/crates/obscura-cdp/src/domains/runtime.rsindex 652c68fe..8f5b0b6c 100644--- a/crates/obscura-cdp/src/domains/runtime.rs+++ b/crates/obscura-cdp/src/domains/runtime.rs@@ -365,6 +365,18 @@ pub async fn handle(let key = format!("__obscura_binding__{}", name);ctx.preload_scripts.retain(|(k, _)| k != &key);ctx.preload_scripts.push((key, shim.clone()));+ // Remember who subscribed, so the call goes back to this+ // session rather than to whichever session of the page a+ // HashMap happens to yield first. A client discards an event+ // addressed to a session it does not hold, and the session+ // Target.createTarget leaves behind is not the one a client+ // ends up using.+ if let Some(session_id) = session_id {+ let owners = ctx.binding_sessions.entry(name.to_string()).or_default();+ if !owners.contains(session_id) {+ owners.push(session_id.clone());+ }+ }// Install on the current page so the binding is usable// immediately, without waiting for the next navigation.if let Some(page) = ctx.get_session_page_mut(session_id) {@@ -378,6 +390,14 @@ pub async fn handle(if !name.is_empty() {let key = format!("__obscura_binding__{}", name);ctx.preload_scripts.retain(|(k, _)| k != &key);+ if let Some(session_id) = session_id {+ if let Some(owners) = ctx.binding_sessions.get_mut(name) {+ owners.retain(|owner| owner != session_id);+ if owners.is_empty() {+ ctx.binding_sessions.remove(name);+ }+ }+ }if let Some(page) = ctx.get_session_page_mut(session_id) {page.evaluate(&format!("delete globalThis['{}'];", name));}diff --git a/crates/obscura-cdp/tests/binding_called_session.rs b/crates/obscura-cdp/tests/binding_called_session.rsnew file mode 100644index 00000000..b811e54c--- /dev/null+++ b/crates/obscura-cdp/tests/binding_called_session.rs@@ -0,0 +1,181 @@+//! `Runtime.bindingCalled` was addressed to one arbitrary session of the page,+//! picked by HashMap ordering. A client reaching a page the ordinary way holds+//! two sessions — `Target.createTarget` opens one and the `Target.attachToTarget`+//! after it opens another — and discards any event whose sessionId is not the+//! one it attached with, so `page.exposeFunction()` never fired its callback.++use obscura_cdp::dispatch::{dispatch, CdpContext};+use obscura_cdp::types::CdpRequest;+use serde_json::{json, Value};++async fn cdp(+ ctx: &mut CdpContext,+ id: u64,+ method: &str,+ params: Value,+ session: Option<&str>,+) -> Value {+ let resp = dispatch(+ &CdpRequest {+ id,+ method: method.to_string(),+ params,+ session_id: session.map(str::to_string),+ },+ ctx,+ )+ .await;+ assert!(resp.error.is_none(), "CDP {method} failed: {:?}", resp.error);+ resp.result.unwrap_or_else(|| json!({}))+}++/// Opens a page the way Puppeteer and Playwright do, rather than inserting a+/// session for a hand-made page, and returns `(targetId, sessionId)`.+async fn created_and_attached(ctx: &mut CdpContext) -> (String, String) {+ let created = cdp(ctx, 900, "Target.createTarget", json!({"url": "about:blank"}), None).await;+ let target_id = created["targetId"].as_str().expect("no targetId").to_string();+ let session = attach_to(ctx, &target_id, 901).await;+ (target_id, session)+}++async fn attach_to(ctx: &mut CdpContext, target_id: &str, id: u64) -> String {+ let attached = cdp(+ ctx,+ id,+ "Target.attachToTarget",+ json!({"targetId": target_id, "flatten": true}),+ None,+ )+ .await;+ attached["sessionId"]+ .as_str()+ .expect("no sessionId")+ .to_string()+}++fn binding_calls<'a>(ctx: &'a CdpContext) -> Vec<(&'a str, &'a Value)> {+ ctx.pending_events+ .iter()+ .filter(|e| e.method == "Runtime.bindingCalled")+ .map(|e| (e.session_id.as_deref().unwrap_or(""), &e.params))+ .collect()+}++/// The deterministic guard. Two sessions each subscribe, so the correct answer+/// is two events. Delivering to one session of the page — whichever a HashMap+/// yields — can only ever produce one, so this fails on the old behaviour no+/// matter which session that ordering happens to pick.+#[tokio::test(flavor = "current_thread")]+async fn every_session_that_added_the_binding_is_called() {+ let mut ctx = CdpContext::new();+ let (target_id, first) = created_and_attached(&mut ctx).await;+ let second = attach_to(&mut ctx, &target_id, 902).await;+ assert_ne!(first, second, "the second attach reused the first session");++ for (id, session) in [(1, &first), (2, &second)] {+ cdp(&mut ctx, id, "Runtime.enable", json!({}), Some(session)).await;+ cdp(+ &mut ctx,+ id + 10,+ "Runtime.addBinding",+ json!({"name": "obscuraProbe"}),+ Some(session),+ )+ .await;+ }++ cdp(+ &mut ctx,+ 3,+ "Runtime.evaluate",+ json!({"expression": "obscuraProbe('HELLO')"}),+ Some(&first),+ )+ .await;++ let called = binding_calls(&ctx);+ let mut got: Vec<&str> = called.iter().map(|(session, _)| *session).collect();+ got.sort_unstable();+ let mut want = vec![first.as_str(), second.as_str()];+ want.sort_unstable();+ assert_eq!(got, want, "both subscribers should have been called: {called:?}");+ for (_, params) in &called {+ assert_eq!(params["name"], "obscuraProbe");+ assert_eq!(params["payload"], "HELLO");+ }+}++/// A session that never asked for the binding is not told about it, so a client+/// does not see a call it has no handler for.+#[tokio::test(flavor = "current_thread")]+async fn a_session_that_did_not_subscribe_is_not_called() {+ let mut ctx = CdpContext::new();+ let (target_id, subscriber) = created_and_attached(&mut ctx).await;+ let bystander = attach_to(&mut ctx, &target_id, 902).await;++ cdp(&mut ctx, 1, "Runtime.enable", json!({}), Some(&subscriber)).await;+ cdp(&mut ctx, 2, "Runtime.enable", json!({}), Some(&bystander)).await;+ cdp(+ &mut ctx,+ 3,+ "Runtime.addBinding",+ json!({"name": "obscuraProbe"}),+ Some(&subscriber),+ )+ .await;+ cdp(+ &mut ctx,+ 4,+ "Runtime.evaluate",+ json!({"expression": "obscuraProbe('HELLO')"}),+ Some(&subscriber),+ )+ .await;++ let called = binding_calls(&ctx);+ assert_eq!(+ called.iter().map(|(s, _)| *s).collect::<Vec<_>>(),+ vec![subscriber.as_str()],+ "only the subscribing session should be called: {called:?}"+ );+}++/// Removing the binding drops both the shim and the subscription, so a later+/// call cannot be delivered to a client that has stopped listening.+#[tokio::test(flavor = "current_thread")]+async fn a_removed_binding_is_not_called() {+ let mut ctx = CdpContext::new();+ let (_, session) = created_and_attached(&mut ctx).await;++ cdp(&mut ctx, 1, "Runtime.enable", json!({}), Some(&session)).await;+ cdp(+ &mut ctx,+ 2,+ "Runtime.addBinding",+ json!({"name": "obscuraProbe"}),+ Some(&session),+ )+ .await;+ cdp(+ &mut ctx,+ 3,+ "Runtime.removeBinding",+ json!({"name": "obscuraProbe"}),+ Some(&session),+ )+ .await;++ let gone = cdp(+ &mut ctx,+ 4,+ "Runtime.evaluate",+ json!({"expression": "typeof globalThis.obscuraProbe", "returnByValue": true}),+ Some(&session),+ )+ .await;+ assert_eq!(gone["result"]["value"], "undefined");+ assert!(+ binding_calls(&ctx).is_empty(),+ "a removed binding still delivered a call"+ );+}