Skip to content

The headless browser for AI agents and web scraping

Route child-frame CDP calls through their evaluation worlds

SGavrl7a2b9aea7feb
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index 10dcbd0a..0f9f912e 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -4598,11 +4598,28 @@ impl Page {
return_by_value: bool,
await_promise: bool,
await_timeout_ms: u64,
+ ) -> Result<obscura_js::runtime::RemoteObjectInfo, String> {
+ self.evaluate_for_cdp_in_frame_with_timeout(
+ None, expression, return_by_value, await_promise, await_timeout_ms,
+ ).await
+ }
+
+ #[doc(hidden)]
+ pub async fn evaluate_for_cdp_in_frame_with_timeout(
+ &mut self,
+ frame_id: Option<u32>,
+ expression: &str,
+ return_by_value: bool,
+ await_promise: bool,
+ await_timeout_ms: u64,
) -> Result<obscura_js::runtime::RemoteObjectInfo, String> {
if let Some(js) = &mut self.js {
- let evaluation = js.start_cdp_evaluation(expression, return_by_value, await_promise)?;
+ let evaluation = js.start_cdp_evaluation_in_frame(
+ frame_id, expression, return_by_value, await_promise,
+ )?;
self.await_cdp_evaluation(evaluation, return_by_value, await_timeout_ms, "Runtime.evaluate").await
} else {
+ if frame_id.is_some() { return Err("JavaScript runtime unavailable".into()); }
let value = self.evaluate(expression);
Ok(obscura_js::runtime::RemoteObjectInfo {
thrown: false,
@@ -4679,9 +4696,27 @@ impl Page {
return_by_value: bool,
await_promise: bool,
await_timeout_ms: u64,
+ ) -> Result<obscura_js::runtime::RemoteObjectInfo, String> {
+ self.call_function_on_for_cdp_in_frame_with_timeout(
+ None, function_declaration, object_id, args, return_by_value,
+ await_promise, await_timeout_ms,
+ ).await
+ }
+
+ #[doc(hidden)]
+ pub async fn call_function_on_for_cdp_in_frame_with_timeout(
+ &mut self,
+ frame_id: Option<u32>,
+ function_declaration: &str,
+ object_id: Option<&str>,
+ args: &[serde_json::Value],
+ return_by_value: bool,
+ await_promise: bool,
+ await_timeout_ms: u64,
) -> Result<obscura_js::runtime::RemoteObjectInfo, String> {
let js = self.js.as_mut().ok_or("JavaScript runtime unavailable")?;
- let evaluation = js.start_cdp_call(
+ let evaluation = js.start_cdp_call_in_frame(
+ frame_id,
function_declaration,
object_id,
args,
diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rs
index 9d0e663e..c78d66b1 100644
--- a/crates/obscura-cdp/src/dispatch.rs
+++ b/crates/obscura-cdp/src/dispatch.rs
@@ -426,13 +426,21 @@ impl CdpContext {
}
pub(crate) fn ensure_default_context(&mut self, page_id: &str) -> Option<ExecutionContextRecord> {
- if let Some(context) = self.contexts_for_page(page_id).into_iter().find(|context| context.is_default) {
- return Some(context.clone());
- }
let page = self.get_page(page_id)?;
let frame_id = page.frame_id.clone();
let origin = page.url_string();
- Some(self.allocate_context(page_id, &frame_id, &origin, "", true))
+ Some(self.ensure_frame_default_context(page_id, &frame_id, &origin).0)
+ }
+
+ fn ensure_frame_default_context(
+ &mut self, page_id: &str, frame_id: &str, origin: &str,
+ ) -> (ExecutionContextRecord, bool) {
+ if let Some(context) = self.contexts_for_page(page_id)
+ .find(|context| context.is_default && context.frame_id == frame_id)
+ {
+ return (context.clone(), false);
+ }
+ (self.allocate_context(page_id, frame_id, origin, "", true), true)
}
/// The single hook for an installed replacement Document.
@@ -442,6 +450,7 @@ impl CdpContext {
frame_id: &str,
origin: &str,
) -> Vec<ExecutionContextRecord> {
+ self.announced_frames.remove(page_id);
self.dom_documents.retain(|session, document| {
if document.page_id != page_id { return true; }
self.pending_events.push(CdpEvent {
@@ -514,8 +523,10 @@ impl CdpContext {
}
pub(crate) fn default_context_id(&self, page_id: &str) -> Option<i64> {
+ let frame_id = &self.get_page(page_id)?.frame_id;
self.contexts_for_page(page_id)
- .find(|context| context.is_default).map(|context| context.id)
+ .find(|context| context.is_default && &context.frame_id == frame_id)
+ .map(|context| context.id)
}
fn remove_frame_contexts(
@@ -1132,6 +1143,7 @@ pub(crate) fn drain_frame_events(ctx: &mut CdpContext) {
let mut events: Vec<CdpEvent> = Vec::new();
let mut announced: HashMap<String, Vec<String>> = HashMap::new();
let mut detached = Vec::new();
+ let mut frame_contexts = Vec::new();
for page in &ctx.pages {
let Some(session_ids) = page_to_sessions.get(&page.id) else {
continue;
@@ -1148,6 +1160,10 @@ pub(crate) fn drain_frame_events(ctx: &mut CdpContext) {
if known.is_some_and(|ids| ids.iter().any(|seen| seen == id)) {
continue;
}
+ frame_contexts.push((
+ page.id.clone(), id.to_string(),
+ frame["url"].as_str().unwrap_or_default().to_string(),
+ ));
for session_id in session_ids {
// Attach before navigate: a client builds its frame from the
// attach event and treats a navigation of a frame it has never
@@ -1184,6 +1200,33 @@ pub(crate) fn drain_frame_events(ctx: &mut CdpContext) {
}
announced.insert(page.id.clone(), live_ids);
}
+ for (page_id, frame_id, origin) in frame_contexts {
+ let (context, created) = ctx.ensure_frame_default_context(&page_id, &frame_id, &origin);
+ if created {
+ let mut contexts = vec![context];
+ let mut worlds = ctx.isolated_worlds.clone();
+ if let Some(page_worlds) = ctx.page_isolated_worlds.get(&page_id) {
+ for world in page_worlds {
+ if !worlds.contains(world) { worlds.push(world.clone()); }
+ }
+ }
+ for world in worlds {
+ if world.is_empty() { continue; }
+ let (context, _) = ctx.create_isolated_context(
+ &page_id, &frame_id, &origin, &world, false,
+ );
+ contexts.push(context);
+ }
+ let sessions = ctx.runtime_sessions_for_page(&page_id);
+ for context in contexts {
+ for session_id in &sessions {
+ events.push(crate::domains::runtime::execution_context_created_event(
+ &context, Some(session_id.clone()),
+ ));
+ }
+ }
+ }
+ }
for (page_id, frame_id, page_sessions) in detached {
let removed = ctx.remove_frame_contexts(&page_id, &frame_id);
let runtime_sessions = ctx.runtime_sessions_for_page(&page_id);
diff --git a/crates/obscura-cdp/src/domains/runtime.rs b/crates/obscura-cdp/src/domains/runtime.rs
index a89a54ec..58bfb903 100644
--- a/crates/obscura-cdp/src/domains/runtime.rs
+++ b/crates/obscura-cdp/src/domains/runtime.rs
@@ -26,6 +26,7 @@ impl DeferredEvaluation {
let js = ctx.get_page_mut(&self.page_id).and_then(|page| page.js.as_mut())
.ok_or("Execution context was destroyed")?;
if !js.has_cdp_evaluation(&self.pending) {
+ js.cancel_cdp_evaluation(self.pending);
return Err("Execution context was destroyed".into());
}
let remaining = self.command_deadline.map(|deadline| deadline.saturating_duration_since(tokio::time::Instant::now()));
@@ -60,7 +61,7 @@ pub(crate) async fn start_awaited_evaluation(
command_budget_ms: u64,
) -> Result<Option<DeferredEvaluation>, String> {
let field = if method == "evaluate" { "contextId" } else { "executionContextId" };
- validate_context(params, field, ctx, session_id, method)?;
+ let frame_id = validate_context(params, field, ctx, session_id, method)?;
let return_by_value = params.get("returnByValue").and_then(Value::as_bool).unwrap_or(false);
let timeout_ms = params.get("timeout").and_then(Value::as_u64).unwrap_or(30_000);
let deadline = tokio::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
@@ -69,9 +70,13 @@ pub(crate) async fn start_awaited_evaluation(
let page = ctx.get_session_page_mut(session_id).ok_or("No page")?;
let Some(js) = page.js.as_mut() else { return Ok(None); };
let evaluation = if method == "evaluate" {
- js.start_cdp_evaluation(params.get("expression").and_then(Value::as_str).ok_or("expression required")?, return_by_value, true)?
+ js.start_cdp_evaluation_in_frame(
+ frame_id, params.get("expression").and_then(Value::as_str).ok_or("expression required")?,
+ return_by_value, true,
+ )?
} else {
- js.start_cdp_call(
+ js.start_cdp_call_in_frame(
+ frame_id,
params.get("functionDeclaration").and_then(Value::as_str).unwrap_or("() => undefined"),
params.get("objectId").and_then(Value::as_str),
params.get("arguments").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]),
@@ -287,7 +292,7 @@ pub async fn handle(
.and_then(|v| v.as_bool())
.unwrap_or(false);
- validate_context(params, "contextId", ctx, session_id, "evaluate")?;
+ let frame_id = validate_context(params, "contextId", ctx, session_id, "evaluate")?;
let await_promise = params
.get("awaitPromise")
@@ -305,7 +310,8 @@ pub async fn handle(
let info = match tokio::time::timeout(
std::time::Duration::from_millis(timeout_ms),
- with_live_peers(ctx, session_id, |page| page.evaluate_for_cdp_with_timeout(
+ with_live_peers(ctx, session_id, |page| page.evaluate_for_cdp_in_frame_with_timeout(
+ frame_id,
expression,
return_by_value,
await_promise,
@@ -350,8 +356,8 @@ pub async fn handle(
// does. CDP names this field `executionContextId` on
// callFunctionOn (not `contextId`); a request may omit it when
// `objectId` is supplied — in that case context validation is a
- // no-op and the default context is used.
- validate_context(params, "executionContextId", ctx, session_id, "callFunctionOn")?;
+ // no-op and the native call uses the handle's recorded evaluation realm.
+ let frame_id = validate_context(params, "executionContextId", ctx, session_id, "callFunctionOn")?;
// Keep awaitPromise alive for the same command budget as evaluate.
// Playwright implements waits with callFunctionOn on some utility
@@ -364,7 +370,8 @@ pub async fn handle(
let info = match tokio::time::timeout(
std::time::Duration::from_millis(timeout_ms),
- with_live_peers(ctx, session_id, |page| page.call_function_on_for_cdp_with_timeout(
+ with_live_peers(ctx, session_id, |page| page.call_function_on_for_cdp_in_frame_with_timeout(
+ frame_id,
function_declaration,
object_id,
&arguments,
@@ -411,6 +418,8 @@ pub async fn handle(
let page = ctx
.get_session_page_mut(session_id)
.ok_or("No page")?;
+ let retrieval = page.js.as_mut().ok_or("No runtime")?
+ .cdp_object_expression(oid)?;
// The child ids minted below are `<parent>::<key>` and the key
// is a property name off a page object, so the page decides
// what ends up inside this literal. A JSON literal covers the
@@ -419,7 +428,7 @@ pub async fn handle(
let oid_literal = crate::util::object_id_literal(oid);
let code = format!(
"(function() {{\
- var obj = globalThis.__obscura_objects[{oid}];\
+ var obj = {retrieval};\
if (!obj || typeof obj !== 'object') return [];\
var keys = Object.keys(obj);\
return keys.map(function(k) {{\
@@ -447,17 +456,21 @@ pub async fn handle(
}});\
}})()",
oid = oid_literal,
+ retrieval = retrieval,
);
let result = page.evaluate(&code);
if let serde_json::Value::Array(props) = result {
let descriptors: Vec<Value> = props
.iter()
- .map(|p| {
+ .map(|p| -> Result<Value, String> {
let name = p.get("name").and_then(|v| v.as_str()).unwrap_or("");
let prop_type =
p.get("type").and_then(|v| v.as_str()).unwrap_or("undefined");
let mut remote = json!({ "type": prop_type });
if let Some(child_oid) = p.get("childOid").and_then(|v| v.as_str()) {
+ if let Some(js) = &mut page.js {
+ js.register_cdp_property_object(oid, child_oid)?;
+ }
remote["type"] = json!("object");
if let Some(sub) = p.get("subtype").and_then(|v| v.as_str()) {
remote["subtype"] = json!(sub);
@@ -493,16 +506,16 @@ pub async fn handle(
}
}
}
- json!({
+ Ok(json!({
"name": name,
"value": remote,
"configurable": true,
"enumerable": true,
"writable": true,
"isOwn": true,
- })
+ }))
})
- .collect();
+ .collect::<Result<_, _>>()?;
Ok(json!({ "result": descriptors, "internalProperties": [] }))
} else {
Ok(json!({ "result": [], "internalProperties": [] }))
@@ -608,7 +621,7 @@ fn validate_context(
ctx: &crate::dispatch::CdpContext,
session_id: &Option<String>,
method: &str,
-) -> Result<(), String> {
+) -> Result<Option<u32>, String> {
let id = params.get(field).and_then(|value| value.as_i64());
let unique_id = params.get("uniqueContextId").and_then(|value| value.as_str());
if id.is_some() && unique_id.is_some() {
@@ -617,24 +630,30 @@ fn validate_context(
));
}
if id.is_none() && unique_id.is_none() {
- return Ok(());
+ return Ok(None);
}
let record = id.and_then(|id| ctx.context_by_id(id))
.or_else(|| unique_id.and_then(|id| ctx.context_by_unique_id(id)));
if let Some(record) = record {
let owner = session_id.as_ref().and_then(|session| ctx.sessions.get(session));
if owner == Some(&record.page_id) {
- // This registry currently validates ownership/routing only. A
- // named isolated context still executes in the owning page's
- // current V8 runtime/global; it is not a separate V8 realm yet.
- return Ok(());
+ let page = ctx.get_session_page(session_id).ok_or("No page")?;
+ if record.frame_id == page.frame_id { return Ok(None); }
+ if let Some(frame_id) = record.frame_id.strip_prefix(&page.frame_id)
+ .and_then(|suffix| suffix.strip_prefix("-frame-"))
+ .and_then(|id| id.parse::<u32>().ok())
+ {
+ if page.frames.iter().any(|frame| frame.frame_id() == frame_id) {
+ return Ok(Some(frame_id));
+ }
+ }
}
} else if session_id.is_none() && unique_id.is_none()
&& id.is_some_and(|id| ctx.valid_context_ids.contains(&id))
{
// Direct embedders can still reserve an id through the existing public
// next_isolated_context API. Attached sessions require page ownership.
- return Ok(());
+ return Ok(None);
}
let identity = id.map(|id| id.to_string())
.or_else(|| unique_id.map(str::to_string))
@@ -645,7 +664,7 @@ fn validate_context(
identity
));
}
- Ok(())
+ Ok(None)
}
/// Shape one `Runtime.evaluate` or `Runtime.callFunctionOn` reply.
diff --git a/crates/obscura-cdp/tests/call_function_on_object_id_arg.rs b/crates/obscura-cdp/tests/call_function_on_object_id_arg.rs
index f906a893..b04667fa 100644
--- a/crates/obscura-cdp/tests/call_function_on_object_id_arg.rs
+++ b/crates/obscura-cdp/tests/call_function_on_object_id_arg.rs
@@ -43,21 +43,20 @@ async fn call_with_arguments(session_id: &str, arguments: Value, declaration: &s
reply["result"].clone()
}
-// go-rod marshals CallArgument from a Go struct, so `omitempty` never drops the
-// unset `Value` field (gson.JSON is a struct) and every object handle reaches
-// the wire as `{"value":null,"objectId":"..."}`. value must not win over
-// objectId, or rod's JS helpers get `null` instead of the `functions` object:
-// "TypeError: Cannot set properties of null (setting 'selectable')".
#[tokio::test(flavor = "current_thread")]
-async fn object_id_argument_wins_over_a_null_value() {
- let result = call_with_arguments(
- "rod-null-shadow",
- json!([{"value": null, "objectId": "__never_resolves__"}]),
- "function(o) { return o === undefined; }",
- )
- .await;
- assert_eq!(result["type"], "boolean", "{result}");
- assert_eq!(result["value"], json!(true), "{result}");
+async fn unknown_object_id_argument_does_not_fall_back_to_a_null_value() {
+ let mut ctx = CdpContext::new();
+ let page_id = ctx.create_page();
+ ctx.sessions.insert("rod-null-shadow".to_string(), page_id);
+ let response = dispatch(&CdpRequest {
+ id: 1, method: "Runtime.callFunctionOn".to_string(),
+ params: json!({
+ "functionDeclaration": "function(o) { globalThis.__called = true; return o; }",
+ "arguments": [{"value":null,"objectId":"__never_resolves__"}],
+ }),
+ session_id: Some("rod-null-shadow".to_string()),
+ }, &mut ctx).await;
+ assert_eq!(response.error.unwrap().message, "Could not find object with given id");
}
#[tokio::test(flavor = "current_thread")]
diff --git a/crates/obscura-cdp/tests/child_frame_tree.rs b/crates/obscura-cdp/tests/child_frame_tree.rs
index 44c69de3..63fc6667 100644
--- a/crates/obscura-cdp/tests/child_frame_tree.rs
+++ b/crates/obscura-cdp/tests/child_frame_tree.rs
@@ -21,11 +21,11 @@ async fn serve() -> String {
let read = socket.read(&mut buf).await.unwrap_or(0);
let request = String::from_utf8_lossy(&buf[..read]).to_string();
let body = if request.starts_with("GET /child.html ") {
- "<html><body><iframe src=\"/grandchild.html\"></iframe></body></html>"
+ "<html><body><h2>Child heading</h2><iframe src=\"/grandchild.html\"></iframe></body></html>"
} else if request.starts_with("GET /grandchild.html ") {
"<html><body><p>deep</p></body></html>"
} else {
- "<html><body><iframe src=\"/child.html\"></iframe></body></html>"
+ "<html><body><h1>Main heading</h1><iframe src=\"/child.html\"></iframe></body></html>"
};
let resp = format!(
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
@@ -90,6 +90,313 @@ async fn attached_session(ctx: &mut CdpContext) -> String {
.to_string()
}
+#[tokio::test(flavor = "current_thread")]
+async fn child_default_and_isolated_contexts_evaluate_their_own_documents() {
+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
+ let url = serve().await;
+ let mut ctx = CdpContext::new();
+ let session = attached_session(&mut ctx).await;
+ cdp(&mut ctx, 1, "Runtime.enable", json!({}), &session).await;
+ cdp(&mut ctx, 2, "Page.navigate", json!({"url": url}), &session).await;
+ cdp(&mut ctx, 3, "Runtime.evaluate", json!({"expression": "1"}), &session).await;
+ let tree = cdp(&mut ctx, 4, "Page.getFrameTree", json!({}), &session).await;
+ let child = &tree["frameTree"]["childFrames"][0];
+ let grandchild = &child["childFrames"][0];
+
+ for frame in [child, grandchild] {
+ let id = frame["frame"]["id"].as_str().unwrap();
+ let context = ctx.pending_events.iter().find(|event| {
+ event.method == "Runtime.executionContextCreated"
+ && event.session_id.as_deref() == Some(session.as_str())
+ && event.params["context"]["auxData"]["frameId"] == id
+ && event.params["context"]["auxData"]["isDefault"] == true
+ }).unwrap_or_else(|| panic!("no default execution context for {id}"));
+ let context_id = context.params["context"]["id"].as_i64().unwrap();
+ let evaluated = cdp(&mut ctx, 5, "Runtime.evaluate", json!({
+ "expression": "Promise.resolve(document.URL)",
+ "contextId": context_id, "returnByValue": true, "awaitPromise": true,
+ }), &session).await;
+ assert_eq!(evaluated["result"]["value"], frame["frame"]["url"]);
+
+ let isolated = cdp(&mut ctx, 6, "Page.createIsolatedWorld", json!({
+ "frameId": id, "worldName": "child-utility-probe",
+ }), &session).await;
+ let called = cdp(&mut ctx, 7, "Runtime.callFunctionOn", json!({
+ "functionDeclaration": "async function() { return document.URL; }",
+ "executionContextId": isolated["executionContextId"],
+ "returnByValue": true, "awaitPromise": true,
+ }), &session).await;
+ assert_eq!(called["result"]["value"], frame["frame"]["url"]);
+ }
+
+ let child_id = child["frame"]["id"].as_str().unwrap();
+ let isolated = cdp(&mut ctx, 8, "Page.createIsolatedWorld", json!({
+ "frameId": child_id, "worldName": "child-utility-probe",
+ }), &session).await;
+ let handle = cdp(&mut ctx, 9, "Runtime.evaluate", json!({
+ "expression": "document.querySelector('h2')",
+ "contextId": isolated["executionContextId"], "returnByValue": false,
+ }), &session).await;
+ assert_eq!(handle["result"]["subtype"], "node");
+ let text = cdp(&mut ctx, 10, "Runtime.callFunctionOn", json!({
+ "functionDeclaration": "function() { return this.textContent; }",
+ "objectId": handle["result"]["objectId"], "returnByValue": true,
+ }), &session).await;
+ assert_eq!(text["result"]["value"], "Child heading");
+ let main = cdp(&mut ctx, 11, "Runtime.evaluate", json!({
+ "expression": "document.querySelector('h1').textContent", "returnByValue": true,
+ }), &session).await;
+ assert_eq!(main["result"]["value"], "Main heading");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn object_and_property_handles_preserve_the_evaluation_world() {
+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
+ let url = serve().await;
+ let mut ctx = CdpContext::new();
+ let session = attached_session(&mut ctx).await;
+ cdp(&mut ctx, 1, "Runtime.enable", json!({}), &session).await;
+ cdp(&mut ctx, 2, "Page.navigate", json!({"url":url}), &session).await;
+ cdp(&mut ctx, 3, "Runtime.evaluate", json!({"expression":"1"}), &session).await;
+ let tree = cdp(&mut ctx, 4, "Page.getFrameTree", json!({}), &session).await;
+ let child = &tree["frameTree"]["childFrames"][0]["frame"];
+ let child_context = ctx.pending_events.iter().find(|event| {
+ event.method == "Runtime.executionContextCreated"
+ && event.session_id.as_deref() == Some(session.as_str())
+ && event.params["context"]["auxData"]["frameId"] == child["id"]
+ && event.params["context"]["auxData"]["isDefault"] == true
+ }).unwrap().params["context"]["id"].as_i64().unwrap();
+ cdp(&mut ctx, 5, "Runtime.evaluate", json!({
+ "expression":"globalThis.childObject = {nested:{answer:42}}", "contextId":child_context,
+ }), &session).await;
+ let cases = [
+ ("document.querySelector('h1')", None, url.as_str()),
+ ("document.querySelector('h2')", Some(child_context), child["url"].as_str().unwrap()),
+ ("document.querySelector('iframe').contentDocument.querySelector('h2')", None, url.as_str()),
+ ("document.querySelector('iframe').contentWindow", None, url.as_str()),
+ ("childObject", Some(child_context), child["url"].as_str().unwrap()),
+ ("document.querySelector('iframe').contentWindow.childObject", None, url.as_str()),
+ ];
+ let mut child_handles = Vec::new();
+ let mut root_handles = Vec::new();
+ for (expression, context, expected_url) in cases {
+ for awaited in [false, true] {
+ let mut params = json!({"expression":expression, "awaitPromise":awaited});
+ if let Some(context) = context { params["contextId"] = json!(context); }
+ let handle = cdp(&mut ctx, 6, "Runtime.evaluate", params, &session).await;
+ let oid = handle["result"]["objectId"].as_str().unwrap().to_string();
+ let called = cdp(&mut ctx, 7, "Runtime.callFunctionOn", json!({
+ "functionDeclaration":"async function(value) { return [document.URL, Array.isArray(value), value instanceof Array]; }",
+ "objectId":oid, "arguments":[{"value":[]}], "awaitPromise":true, "returnByValue":true,
+ }), &session).await;
+ assert_eq!(called["result"]["value"], json!([expected_url,true,true]), "{expression}");
+ if expression.ends_with("childObject") {
+ let props = cdp(&mut ctx, 8, "Runtime.getProperties", json!({"objectId":oid}), &session).await;
+ let nested = props["result"].as_array().unwrap().iter().find(|prop| prop["name"] == "nested")
+ .unwrap()["value"]["objectId"].as_str().unwrap().to_string();
+ let called = cdp(&mut ctx, 9, "Runtime.callFunctionOn", json!({
+ "functionDeclaration":"function() { return [document.URL, this.answer]; }",
+ "objectId":nested, "returnByValue":true,
+ }), &session).await;
+ assert_eq!(called["result"]["value"], json!([expected_url,42]));
+ if context.is_some() { child_handles.push(nested); } else { root_handles.push(nested); }
+ }
+ if context.is_some() { child_handles.push(oid); } else { root_handles.push(oid); }
+ }
+ }
+ cdp(&mut ctx, 10, "Runtime.evaluate", json!({
+ "expression":"document.querySelector('iframe').remove()",
+ }), &session).await;
+ ctx.get_session_page_mut(&Some(session.clone())).unwrap().settle(1_000).await;
+ cdp(&mut ctx, 11, "Runtime.evaluate", json!({"expression":"1"}), &session).await;
+ for oid in &child_handles {
+ for method in ["Runtime.callFunctionOn", "Runtime.getProperties"] {
+ let result = dispatch(&CdpRequest {
+ id:12, method:method.to_string(),
+ params:json!({"objectId":oid,"functionDeclaration":"function() { return document.URL; }"}),
+ session_id:Some(session.clone()),
+ }, &mut ctx).await;
+ assert_eq!(result.error.unwrap().message, "Execution context was destroyed", "{method}");
+ }
+ }
+ for oid in &root_handles {
+ let called = cdp(&mut ctx, 13, "Runtime.callFunctionOn", json!({
+ "objectId":oid, "functionDeclaration":"function() { return document.URL; }", "returnByValue":true,
+ }), &session).await;
+ assert_eq!(called["result"]["value"], url);
+ }
+ cdp(&mut ctx, 14, "Runtime.releaseObject", json!({"objectId":root_handles[0]}), &session).await;
+ let released = dispatch(&CdpRequest {
+ id:15, method:"Runtime.getProperties".to_string(),
+ params:json!({"objectId":root_handles[0]}), session_id:Some(session.clone()),
+ }, &mut ctx).await;
+ assert_eq!(released.error.unwrap().message, "Could not find object with given id");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn child_object_handles_reject_a_retired_execution_context() {
+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
+ let url = serve().await;
+ let mut ctx = CdpContext::new();
+ let session = attached_session(&mut ctx).await;
+ cdp(&mut ctx, 1, "Runtime.enable", json!({}), &session).await;
+ cdp(&mut ctx, 2, "Page.navigate", json!({"url": url}), &session).await;
+ cdp(&mut ctx, 3, "Runtime.evaluate", json!({"expression": "1"}), &session).await;
+ let tree = cdp(&mut ctx, 4, "Page.getFrameTree", json!({}), &session).await;
+ let child = &tree["frameTree"]["childFrames"][0]["frame"];
+ let context_id = ctx.pending_events.iter().find(|event| {
+ event.method == "Runtime.executionContextCreated"
+ && event.session_id.as_deref() == Some(session.as_str())
+ && event.params["context"]["auxData"]["frameId"] == child["id"]
+ && event.params["context"]["auxData"]["isDefault"] == true
+ }).unwrap().params["context"]["id"].as_i64().unwrap();
+ let handle = cdp(&mut ctx, 5, "Runtime.evaluate", json!({
+ "expression": "({kind:'child'})", "contextId": context_id,
+ }), &session).await;
+ let live = cdp(&mut ctx, 6, "Runtime.callFunctionOn", json!({
+ "functionDeclaration": "function() { return document.URL; }",
+ "objectId": handle["result"]["objectId"], "returnByValue": true,
+ }), &session).await;
+ assert_eq!(live["result"]["value"], child["url"]);
+ cdp(&mut ctx, 7, "Runtime.evaluate", json!({
+ "expression": "document.querySelector('iframe').remove()",
+ }), &session).await;
+ ctx.get_session_page_mut(&Some(session.clone())).unwrap().settle(1_000).await;
+ cdp(&mut ctx, 8, "Runtime.evaluate", json!({"expression": "1"}), &session).await;
+ let tree = cdp(&mut ctx, 9, "Page.getFrameTree", json!({}), &session).await;
+ assert!(tree["frameTree"]["childFrames"].as_array().is_none_or(Vec::is_empty));
+ let retired = dispatch(&CdpRequest {
+ id: 10, method: "Runtime.callFunctionOn".to_string(),
+ params: json!({
+ "functionDeclaration": "function() { return document.URL; }",
+ "objectId": handle["result"]["objectId"], "returnByValue": true,
+ }),
+ session_id: Some(session.clone()),
+ }, &mut ctx).await;
+ assert_eq!(retired.error.unwrap().message, "Execution context was destroyed");
+ let main = cdp(&mut ctx, 11, "Runtime.evaluate", json!({
+ "expression": "document.querySelector('h1').textContent", "returnByValue": true,
+ }), &session).await;
+ assert_eq!(main["result"]["value"], "Main heading");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn late_runtime_enable_reports_child_default_and_registered_utility_contexts_once() {
+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
+ let url = serve().await;
+ let mut ctx = CdpContext::new();
+ let session = attached_session(&mut ctx).await;
+ let initial = cdp(&mut ctx, 1, "Page.getFrameTree", json!({}), &session).await;
+ cdp(&mut ctx, 2, "Page.createIsolatedWorld", json!({
+ "frameId": initial["frameTree"]["frame"]["id"], "worldName": "frame-auto-utility",
+ }), &session).await;
+ cdp(&mut ctx, 2, "Page.navigate", json!({"url": url}), &session).await;
+ cdp(&mut ctx, 3, "Runtime.evaluate", json!({"expression": "1"}), &session).await;
+ let tree = cdp(&mut ctx, 4, "Page.getFrameTree", json!({}), &session).await;
+ let child_id = tree["frameTree"]["childFrames"][0]["frame"]["id"].as_str().unwrap();
+ ctx.pending_events.clear();
+ cdp(&mut ctx, 5, "Runtime.enable", json!({}), &session).await;
+ cdp(&mut ctx, 6, "Runtime.enable", json!({}), &session).await;
+ let contexts = ctx.pending_events.iter().filter(|event| {
+ event.method == "Runtime.executionContextCreated"
+ && event.session_id.as_deref() == Some(session.as_str())
+ && event.params["context"]["auxData"]["frameId"] == child_id
+ }).collect::<Vec<_>>();
+ assert_eq!(contexts.iter().filter(|event| {
+ event.params["context"]["auxData"]["isDefault"] == true
+ }).count(), 1);
+ assert_eq!(contexts.iter().filter(|event| {
+ event.params["context"]["name"] == "frame-auto-utility"
+ }).count(), 1);
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn cross_origin_child_contexts_are_privileged_without_exposing_the_window_to_parent_script() {
+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
+ let url = serve().await;
+ let html = format!("<!doctype html><h1>Main</h1><iframe src=\"{url}child.html\"></iframe>");
+ let encoded = url::form_urlencoded::byte_serialize(html.as_bytes()).collect::<String>()
+ .replace('+', "%20");
+ let mut ctx = CdpContext::new();
+ let session = attached_session(&mut ctx).await;
+ cdp(&mut ctx, 1, "Runtime.enable", json!({}), &session).await;
+ cdp(&mut ctx, 2, "Page.navigate", json!({
+ "url": format!("data:text/html,{encoded}"),
+ }), &session).await;
+ cdp(&mut ctx, 3, "Runtime.evaluate", json!({"expression": "1"}), &session).await;
+ let tree = cdp(&mut ctx, 4, "Page.getFrameTree", json!({}), &session).await;
+ let child = &tree["frameTree"]["childFrames"][0]["frame"];
+ assert!(child["id"].is_string(), "cross-origin frame was not built: {tree}");
+ let context_id = ctx.pending_events.iter().find(|event| {
+ event.method == "Runtime.executionContextCreated"
+ && event.session_id.as_deref() == Some(session.as_str())
+ && event.params["context"]["auxData"]["frameId"] == child["id"]
+ && event.params["context"]["auxData"]["isDefault"] == true
+ }).unwrap().params["context"]["id"].as_i64().unwrap();
+ let parent_private = cdp(&mut ctx, 5, "Runtime.evaluate", json!({
+ "expression": "document.querySelector('iframe').contentDocument === null",
+ "returnByValue": true,
+ }), &session).await;
+ assert_eq!(parent_private["result"]["value"], true);
+ let argument_realm = cdp(&mut ctx, 6, "Runtime.callFunctionOn", json!({
+ "functionDeclaration": "function(value) { return this.document.URL === document.URL && Object.getPrototypeOf(value) === Array.prototype; }",
+ "executionContextId": context_id, "arguments": [{"value": [1, 2]}],
+ "returnByValue": true,
+ }), &session).await;
+ assert_eq!(argument_realm["result"]["value"], true);
+ let window = cdp(&mut ctx, 7, "Runtime.evaluate", json!({
+ "expression": "globalThis", "contextId": context_id,
+ }), &session).await;
+ assert!(window["result"]["objectId"].is_string(), "{window}");
+ let from_window = cdp(&mut ctx, 8, "Runtime.callFunctionOn", json!({
+ "functionDeclaration": "function() { return this.document.URL; }",
+ "objectId": window["result"]["objectId"], "returnByValue": true,
+ }), &session).await;
+ assert_eq!(from_window["result"]["value"], child["url"]);
+ let parent_private = cdp(&mut ctx, 9, "Runtime.evaluate", json!({
+ "expression": "document.querySelector('iframe').contentDocument === null",
+ "returnByValue": true,
+ }), &session).await;
+ assert_eq!(parent_private["result"]["value"], true);
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn repeated_navigation_reannounces_child_contexts_and_rejects_the_previous_document() {
+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
+ let url = serve().await;
+ let mut ctx = CdpContext::new();
+ let session = attached_session(&mut ctx).await;
+ cdp(&mut ctx, 1, "Runtime.enable", json!({}), &session).await;
+ let mut previous_context = None;
+ for _ in 0..3 {
+ ctx.pending_events.clear();
+ cdp(&mut ctx, 2, "Page.navigate", json!({"url": url}), &session).await;
+ cdp(&mut ctx, 3, "Runtime.evaluate", json!({"expression": "1"}), &session).await;
+ let tree = cdp(&mut ctx, 4, "Page.getFrameTree", json!({}), &session).await;
+ let child = &tree["frameTree"]["childFrames"][0]["frame"];
+ let context = ctx.pending_events.iter().find(|event| {
+ event.method == "Runtime.executionContextCreated"
+ && event.session_id.as_deref() == Some(session.as_str())
+ && event.params["context"]["auxData"]["frameId"] == child["id"]
+ && event.params["context"]["auxData"]["isDefault"] == true
+ }).expect("replacement document did not advertise a child context");
+ let context_id = context.params["context"]["id"].as_i64().unwrap();
+ let reply = cdp(&mut ctx, 5, "Runtime.evaluate", json!({
+ "expression": "document.URL", "contextId": context_id, "returnByValue": true,
+ }), &session).await;
+ assert_eq!(reply["result"]["value"], child["url"]);
+ if let Some(previous) = previous_context {
+ let stale = dispatch(&CdpRequest {
+ id: 6, method: "Runtime.evaluate".to_string(),
+ params: json!({"expression": "document.URL", "contextId": previous}),
+ session_id: Some(session.clone()),
+ }, &mut ctx).await;
+ assert!(stale.error.is_some(), "previous document's context still routes");
+ }
+ previous_context = Some(context_id);
+ }
+}
+
#[tokio::test(flavor = "current_thread")]
async fn get_frame_tree_reports_nested_child_frames() {
std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 09daa053..694b70df 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -239,6 +239,8 @@ pub enum CdpEvaluation {
pub struct PendingCdpEvaluation {
object_id: String,
recipe: Option<String>,
+ // A numeric frame id can be reused after its realm is retired.
+ frame: Option<(u32, v8::Global<v8::Context>)>,
}
/// CDP remote objects that can be rebuilt when a page's V8 runtime is
@@ -255,9 +257,15 @@ pub struct CdpObjectState {
evaluation_recipes: HashMap<String, String>,
}
+struct CdpObjectRecord {
+ retrieval: String,
+ // The evaluation world can differ from the value's creation realm.
+ frame: Option<(u32, v8::Global<v8::Context>)>,
+}
+
pub struct ObscuraJsRuntime {
state: Rc<RefCell<ObscuraState>>,
- object_store: HashMap<String, String>,
+ object_store: HashMap<String, CdpObjectRecord>,
evaluation_recipes: HashMap<String, String>,
object_counter: u64,
import_map: Rc<RefCell<ImportMap>>,
@@ -1468,20 +1476,60 @@ impl ObscuraJsRuntime {
.and_then(|rest| rest.split_once('-'))
.and_then(|(frame_id, _)| frame_id.parse::<u32>().ok())
.unwrap_or(0);
- let object_id_lit = js_string_literal(object_id);
- let retrieval = if frame_id == 0 {
- format!("globalThis.__obscura_objects[{object_id_lit}]")
- } else {
- format!(
- "globalThis.__obscura_frameObjects[{frame_id}]?.window?.__obscura_objects[{object_id_lit}]"
- )
- };
- self.object_store.insert(object_id.to_string(), retrieval);
+ if let Err(error) = self.retain_console_object(object_id, frame_id) {
+ tracing::warn!(object_id, %error, "Could not retain console object");
+ }
}
}
events
}
+ fn retain_console_object(&mut self, object_id: &str, frame_id: u32) -> Result<(), String> {
+ let watchdog = self.arm_watchdog(std::time::Duration::from_secs(5));
+ let result = self.retain_console_object_in_context(object_id, frame_id);
+ if self.disarm_watchdog(watchdog) {
+ return Err("Console object retention exceeded its deadline".into());
+ }
+ self.finish_heap_checked(result)
+ }
+
+ fn retain_console_object_in_context(&mut self, object_id: &str, frame_id: u32) -> Result<(), String> {
+ let frame = if frame_id == 0 { None } else {
+ Some((frame_id, self.cdp_context(Some(frame_id))?))
+ };
+ if let Some((_, context)) = &frame {
+ let value = {
+ let mut entered = self.runtime();
+ v8::scope_with_context!(scope, entered.v8_isolate(), context.clone());
+ v8::tc_scope!(let scope, scope);
+ let key = v8::String::new(scope, "__obscura_objects").ok_or("Console store allocation failed")?;
+ let global = scope.get_current_context().global(scope);
+ let objects = global.get(scope, key.into()).and_then(|value| value.to_object(scope))
+ .ok_or("Console object store unavailable")?;
+ let key = v8::String::new(scope, object_id).ok_or("Console object key allocation failed")?;
+ let value = objects.get(scope, key.into()).ok_or("Console object unavailable")?;
+ let value = v8::Global::new(scope, value);
+ if objects.delete(scope, key.into()) != Some(true) { return Err("Cannot move console object".into()); }
+ value
+ };
+ let mut entered = self.runtime();
+ let context = entered.main_context();
+ v8::scope_with_context!(scope, entered.v8_isolate(), context);
+ v8::tc_scope!(let scope, scope);
+ let key = v8::String::new(scope, "__obscura_objects").ok_or("Console store allocation failed")?;
+ let global = scope.get_current_context().global(scope);
+ let objects = global.get(scope, key.into()).and_then(|value| value.to_object(scope))
+ .ok_or("Console object store unavailable")?;
+ let key = v8::String::new(scope, object_id).ok_or("Console object key allocation failed")?;
+ let value = v8::Local::new(scope, value);
+ if objects.set(scope, key.into(), value) != Some(true) { return Err("Cannot retain console object".into()); }
+ }
+ self.object_store.insert(object_id.to_string(), CdpObjectRecord {
+ retrieval: format!("globalThis.__obscura_objects[{}]", js_string_literal(object_id)), frame,
+ });
+ Ok(())
+ }
+
pub fn set_runtime_events_enabled(&self, enabled: bool) {
self.state.borrow_mut().runtime_events_enabled = enabled;
}
@@ -2690,14 +2738,33 @@ impl ObscuraJsRuntime {
return_by_value: bool,
await_promise: bool,
) -> Result<CdpEvaluation, String> {
+ self.start_cdp_evaluation_in_frame(None, expression, return_by_value, await_promise)
+ }
+
+ fn cdp_context(&mut self, frame_id: Option<u32>) -> Result<v8::Global<v8::Context>, String> {
+ match frame_id {
+ Some(id) => self.realm_states().borrow().context(id)
+ .ok_or_else(|| "Execution context was destroyed".to_string()),
+ None => Ok(self.runtime().main_context()),
+ }
+ }
+
+ #[doc(hidden)]
+ pub fn start_cdp_evaluation_in_frame(
+ &mut self,
+ frame_id: Option<u32>,
+ expression: &str,
+ return_by_value: bool,
+ await_promise: bool,
+ ) -> Result<CdpEvaluation, String> {
+ let context = self.cdp_context(frame_id)?;
self.begin_javascript_task();
self.object_counter += 1;
let oid = self.make_oid(self.object_counter);
// Compile the script itself, not a string passed through the page's eval.
let record = (|| {
let mut entered = self.runtime();
- let context = entered.main_context();
- v8::scope_with_context!(scope, entered.v8_isolate(), context);
+ v8::scope_with_context!(scope, entered.v8_isolate(), context.clone());
v8::tc_scope!(let scope, scope);
let source = v8::String::new(scope, expression).ok_or("CDP source allocation failed")?;
let name = v8::String::new(scope, "<eval-remote>").ok_or("CDP origin allocation failed")?;
@@ -2720,7 +2787,8 @@ impl ObscuraJsRuntime {
self.pending_cdp_evaluations.insert(oid.clone(), record);
let pending = PendingCdpEvaluation {
object_id: oid,
- recipe: if return_by_value { None } else { Some(expression.to_string()) },
+ recipe: if return_by_value || frame_id.is_some() { None } else { Some(expression.to_string()) },
+ frame: frame_id.map(|id| (id, context)),
};
if await_promise {
Ok(CdpEvaluation::Pending(pending))
@@ -2770,18 +2838,50 @@ impl ObscuraJsRuntime {
return_by_value: bool,
await_promise: bool,
) -> Result<CdpEvaluation, String> {
+ self.start_cdp_call_in_frame(
+ None, function_declaration, object_id, arguments, return_by_value, await_promise,
+ )
+ }
+
+ #[doc(hidden)]
+ pub fn start_cdp_call_in_frame(
+ &mut self,
+ mut frame_id: Option<u32>,
+ function_declaration: &str,
+ object_id: Option<&str>,
+ arguments: &[serde_json::Value],
+ return_by_value: bool,
+ await_promise: bool,
+ ) -> Result<CdpEvaluation, String> {
+ if let Some(object_id) = object_id {
+ self.validate_cdp_object_context(object_id)?;
+ let object_frame = self.object_store.get(object_id)
+ .and_then(|record| record.frame.as_ref().map(|(id, _)| *id));
+ if frame_id.is_some() && frame_id != object_frame {
+ return Err("Object belongs to a different execution context".into());
+ }
+ frame_id = object_frame;
+ }
+ let context = self.cdp_context(frame_id)?;
self.begin_javascript_task();
- let this_expr = self.resolve_this(object_id);
- let receiver = self.execute_runtime_script("<cdp-receiver>", this_expr)
- .map_err(|error| format!("JS error: {error}"))?;
- let arguments = arguments.iter().map(|argument| self.cdp_call_argument(argument))
+ let receiver = if object_id.is_some() {
+ let this_expr = self.resolve_this(object_id)?;
+ self.execute_runtime_script("<cdp-receiver>", this_expr)
+ .map_err(|error| format!("JS error: {error}"))?
+ } else {
+ let mut entered = self.runtime();
+ v8::scope_with_context!(scope, entered.v8_isolate(), context.clone());
+ let global = scope.get_current_context().global(scope);
+ let value: v8::Local<v8::Value> = global.into();
+ v8::Global::new(scope, value)
+ };
+ let arguments = arguments.iter().map(|argument| self.cdp_call_argument(argument, &context))
.collect::<Result<Vec<_>, _>>()?;
self.object_counter += 1;
let oid = self.make_oid(self.object_counter);
let record = (|| {
let mut entered = self.runtime();
- let context = entered.main_context();
- v8::scope_with_context!(scope, entered.v8_isolate(), context);
+ v8::scope_with_context!(scope, entered.v8_isolate(), context.clone());
v8::tc_scope!(let scope, scope);
let receiver = v8::Local::new(scope, &receiver);
let arguments = arguments.iter().map(|argument| v8::Local::new(scope, argument))
@@ -2813,7 +2913,9 @@ impl ObscuraJsRuntime {
})();
let record = self.finish_heap_checked(record)?;
self.pending_cdp_evaluations.insert(oid.clone(), record);
- let pending = PendingCdpEvaluation { object_id: oid, recipe: None };
+ let pending = PendingCdpEvaluation {
+ object_id: oid, recipe: None, frame: frame_id.map(|id| (id, context)),
+ };
if await_promise {
Ok(CdpEvaluation::Pending(pending))
} else {
@@ -2824,6 +2926,9 @@ impl ObscuraJsRuntime {
#[doc(hidden)]
pub fn has_cdp_evaluation(&self, pending: &PendingCdpEvaluation) -> bool {
self.pending_cdp_evaluations.contains_key(&pending.object_id)
+ && pending.frame.as_ref().is_none_or(|(id, context)| {
+ self.realm_states().borrow().context(*id).as_ref() == Some(context)
+ })
}
fn has_ready_cdp_evaluations(&mut self) -> bool {
@@ -2841,6 +2946,7 @@ impl ObscuraJsRuntime {
#[doc(hidden)]
pub fn cdp_evaluation_ready(&mut self, pending: &PendingCdpEvaluation) -> bool {
+ if !self.has_cdp_evaluation(pending) { return false; }
let Some(record) = self.pending_cdp_evaluations.get(&pending.object_id).cloned() else {
return false;
};
@@ -2863,6 +2969,11 @@ impl ObscuraJsRuntime {
let oid = pending.object_id;
let record = self.pending_cdp_evaluations.remove(&oid)
.ok_or("Evaluation result unavailable")?;
+ if pending.frame.as_ref().is_some_and(|(id, context)| {
+ self.realm_states().borrow().context(*id).as_ref() != Some(context)
+ }) {
+ return Err("Execution context was destroyed".into());
+ }
let (value, rejected) = {
let mut entered = self.runtime();
let context = entered.main_context();
@@ -2891,15 +3002,38 @@ impl ObscuraJsRuntime {
(v8::Global::new(scope, value), rejected)
};
if return_by_value && !rejected { return self.v8_to_cdp_value(value); }
- let meta = self.execute_runtime_script(
- "<readMeta>", Self::meta_extract_js(&format!("globalThis.__obscura_objects[{}]", js_string_literal(&oid))),
- ).map_err(|e| format!("JS error: {e}"))?;
+ let meta = if let Some((_, context)) = &pending.frame {
+ let result = (|| {
+ let mut entered = self.runtime();
+ v8::scope_with_context!(scope, entered.v8_isolate(), context.clone());
+ v8::tc_scope!(let scope, scope);
+ let source = format!("(function(value) {{ return {}; }})", Self::meta_extract_js("value"));
+ let source = v8::String::new(scope, &source).ok_or("CDP metadata allocation failed")?;
+ let function = v8::Script::compile(scope, source, None)
+ .and_then(|script| script.run(scope))
+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
+ .ok_or_else(|| exception_text(scope))?;
+ let value = v8::Local::new(scope, &value);
+ let receiver = v8::undefined(scope).into();
+ let result = function.call(scope, receiver, &[value])
+ .ok_or_else(|| exception_text(scope))?;
+ Ok(v8::Global::new(scope, result))
+ })();
+ self.finish_heap_checked(result)?
+ } else {
+ self.execute_runtime_script(
+ "<readMeta>", Self::meta_extract_js(&format!("globalThis.__obscura_objects[{}]", js_string_literal(&oid))),
+ ).map_err(|e| format!("JS error: {e}"))?
+ };
let meta = self.v8_to_json(meta)?;
let meta = if let serde_json::Value::String(value) = &meta {
serde_json::from_str(value).unwrap_or(meta)
} else { meta };
let mut info = self.finish_cdp_result(&meta, &oid)?;
info.thrown = rejected;
+ if info.object_id.is_some() {
+ self.object_store.get_mut(&oid).ok_or("Cannot store evaluation context")?.frame = pending.frame;
+ }
if !rejected && info.object_id.is_some() {
if let Some(recipe) = pending.recipe { self.evaluation_recipes.insert(oid, recipe); }
}
@@ -2956,7 +3090,10 @@ impl ObscuraJsRuntime {
.map_err(|e| format!("Store error: {}", e))?;
self.object_store.insert(
oid.clone(),
- format!("globalThis.__obscura_objects[{}]", js_string_literal(&oid)),
+ CdpObjectRecord {
+ retrieval: format!("globalThis.__obscura_objects[{}]", js_string_literal(&oid)),
+ frame: None,
+ },
);
Ok(oid)
}
@@ -2990,44 +3127,51 @@ impl ObscuraJsRuntime {
self.finish_cdp_result(&meta_json, &oid)
}
+ #[doc(hidden)]
+ pub fn validate_cdp_object_context(&self, object_id: &str) -> Result<(), String> {
+ let record = self.object_store.get(object_id);
+ if record.is_none() && !self.evaluation_recipes.contains_key(object_id)
+ && !object_id.strip_prefix("node-").is_some_and(|id| {
+ !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()) && id.parse::<u32>().is_ok()
+ })
+ {
+ return Err("Could not find object with given id".into());
+ }
+ if record.and_then(|record| record.frame.as_ref())
+ .is_some_and(|(id, context)| self.realm_states().borrow().context(*id).as_ref() != Some(context))
+ {
+ return Err("Execution context was destroyed".into());
+ }
+ Ok(())
+ }
+
+ #[doc(hidden)]
+ pub fn cdp_object_expression(&mut self, object_id: &str) -> Result<String, String> {
+ self.validate_cdp_object_context(object_id)?;
+ self.resolve_this(Some(object_id))
+ }
+
+ #[doc(hidden)]
+ pub fn register_cdp_property_object(&mut self, parent_id: &str, object_id: &str) -> Result<(), String> {
+ self.validate_cdp_object_context(parent_id)?;
+ let frame = self.object_store.get(parent_id).and_then(|record| record.frame.clone());
+ self.object_store.insert(object_id.to_string(), CdpObjectRecord {
+ retrieval: format!("globalThis.__obscura_objects[{}]", js_string_literal(object_id)),
+ frame,
+ });
+ Ok(())
+ }
+
pub fn release_object(&mut self, object_id: &str) {
self.evaluation_recipes.remove(object_id);
- if self.object_store.remove(object_id).is_some() {
- let frame_id = object_id
- .strip_prefix("console-")
- .and_then(|rest| rest.split_once('-'))
- .and_then(|(frame_id, _)| frame_id.parse::<u32>().ok())
- .unwrap_or(0);
- let object_id_lit = js_string_literal(object_id);
- let code = if frame_id == 0 {
- format!("delete globalThis.__obscura_objects[{object_id_lit}];")
- } else {
- format!(
- "delete globalThis.__obscura_frameObjects[{frame_id}]?.window?.__obscura_objects[{object_id_lit}];"
- )
- };
+ if let Some(record) = self.object_store.remove(object_id) {
+ let code = format!("delete ({});", record.retrieval);
let _ = self.execute_runtime_script("<release>", code);
}
}
pub fn release_object_group(&mut self) {
- let mut frame_ids: Vec<u32> = self
- .object_store
- .keys()
- .filter_map(|object_id| object_id.strip_prefix("console-"))
- .filter_map(|rest| rest.split_once('-'))
- .filter_map(|(frame_id, _)| frame_id.parse().ok())
- .filter(|frame_id| *frame_id != 0)
- .collect();
- frame_ids.sort_unstable();
- frame_ids.dedup();
- let mut code = "globalThis.__obscura_objects = {};".to_string();
- for frame_id in frame_ids {
- code.push_str(&format!(
- "if(globalThis.__obscura_frameObjects[{frame_id}]?.window)globalThis.__obscura_frameObjects[{frame_id}].window.__obscura_objects={{}};"
- ));
- }
- let _ = self.execute_runtime_script("<releaseGroup>", code);
+ let _ = self.execute_runtime_script("<releaseGroup>", "globalThis.__obscura_objects = {};".to_string());
self.object_store.clear();
self.evaluation_recipes.clear();
}
@@ -4167,10 +4311,7 @@ impl ObscuraJsRuntime {
pub fn with_remote_dom_node<R>(&mut self, object_id: &str,
inspect: impl FnOnce(&DomTree, NodeId, u32, &str, &str) -> R) -> Result<R, String> {
self.begin_javascript_task();
- // getProperties also stores child handles directly in the realm's table.
- let retrieval = self.resolve_remote_object(object_id).unwrap_or_else(|| {
- format!("globalThis.__obscura_objects[{}]", js_string_literal(object_id))
- });
+ let retrieval = self.cdp_object_expression(object_id)?;
let receiver = self.execute_runtime_script("<cdp-dom-node>", retrieval)
.map_err(|error| format!("Could not resolve remote node: {error}"))?;
let watchdog = self.arm_watchdog(std::time::Duration::from_secs(5));
@@ -4359,7 +4500,7 @@ impl ObscuraJsRuntime {
fn resolve_remote_object(&mut self, object_id: &str) -> Option<String> {
if let Some(retrieval) = self.object_store.get(object_id) {
- return Some(retrieval.clone());
+ return Some(retrieval.retrieval.clone());
}
let expression = self.evaluation_recipes.get(object_id)?.clone();
let object_id_literal = js_string_literal(object_id);
@@ -4368,19 +4509,23 @@ impl ObscuraJsRuntime {
self.execute_runtime_script("<restore-cdp-object>", code)
.ok()?;
let retrieval = format!("globalThis.__obscura_objects[{object_id_literal}]");
- self.object_store
- .insert(object_id.to_string(), retrieval.clone());
+ self.object_store.insert(object_id.to_string(), CdpObjectRecord {
+ retrieval: retrieval.clone(), frame: None,
+ });
Some(retrieval)
}
- fn resolve_this(&mut self, object_id: Option<&str>) -> String {
+ fn resolve_this(&mut self, object_id: Option<&str>) -> Result<String, String> {
match object_id {
Some(oid) => {
if let Some(retrieval) = self.resolve_remote_object(oid) {
- retrieval
+ Ok(retrieval)
} else if oid.starts_with("node-") {
- let nid = oid.strip_prefix("node-").unwrap_or("0");
- format!(
+ let nid = oid.strip_prefix("node-").filter(|id| {
+ !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit())
+ }).and_then(|id| id.parse::<u32>().ok())
+ .ok_or("Could not find object with given id")?;
+ Ok(format!(
"(function() {{ \
var nid = {}; \
var cache = globalThis._cache || new Map(); \
@@ -4388,19 +4533,28 @@ impl ObscuraJsRuntime {
return null; \
}})()",
nid
- )
+ ))
} else {
- "globalThis".to_string()
+ Err("Could not find object with given id".into())
}
}
- None => "globalThis".to_string(),
+ None => Ok("globalThis".to_string()),
}
}
- fn cdp_call_argument(&mut self, argument: &serde_json::Value) -> Result<v8::Global<v8::Value>, String> {
+ fn cdp_call_argument(
+ &mut self,
+ argument: &serde_json::Value,
+ context: &v8::Global<v8::Context>,
+ ) -> Result<v8::Global<v8::Value>, String> {
// Remote handles take precedence over value, including rod's value:null.
if let Some(id) = argument.get("objectId").and_then(|value| value.as_str()) {
- let expression = self.resolve_remote_object(id).unwrap_or_else(|| "undefined".into());
+ let expression = self.cdp_object_expression(id)?;
+ let object_context = self.object_store.get(id).and_then(|record| record.frame.as_ref())
+ .map(|(_, context)| context.clone()).unwrap_or_else(|| self.runtime().main_context());
+ if &object_context != context {
+ return Err("Object belongs to a different execution context".into());
+ }
return self.execute_runtime_script("<cdp-argument>", expression)
.map_err(|error| format!("JS error: {error}"));
}
@@ -4414,8 +4568,7 @@ impl ObscuraJsRuntime {
}
let result = (|| {
let mut entered = self.runtime();
- let context = entered.main_context();
- v8::scope_with_context!(scope, entered.v8_isolate(), context);
+ v8::scope_with_context!(scope, entered.v8_isolate(), context.clone());
v8::tc_scope!(let scope, scope);
let value = if let Some(value) = argument.get("value") {
// JSON data is not an object literal: __proto__ must be an own property.
@@ -4493,7 +4646,10 @@ impl ObscuraJsRuntime {
}
self.object_store.insert(
oid.to_string(),
- format!("globalThis.__obscura_objects[{}]", js_string_literal(oid)),
+ CdpObjectRecord {
+ retrieval: format!("globalThis.__obscura_objects[{}]", js_string_literal(oid)),
+ frame: None,
+ },
);
Ok(Self::info_from_meta(meta, Some(oid.to_string())))
}
@@ -5151,6 +5307,155 @@ mod tests {
})()"#).unwrap(), serde_json::json!([true,1,"b",2,3]));
}
+ #[test]
+ fn cdp_frame_console_retention_bounds_page_owned_store_getters() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ rt.set_runtime_events_enabled(true);
+ let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
+ "http://foreign.test/child", "<html><body>child</body></html>").unwrap();
+ frame.execute_script(&mut rt, r#"console.log({answer:42});
+ globalThis.__obscura_objects = new Proxy({}, {get() { while (true) {} }});
+ void 0;
+ "#).unwrap();
+ let events = rt.take_pending_runtime_events();
+ assert!(events.iter().any(|event| matches!(event, RuntimeEvent::Console(_))));
+ assert!(rt.object_store.is_empty());
+ assert_eq!(rt.evaluate("1 + 1").unwrap(), serde_json::json!(2.0));
+ drop(frame);
+ }
+
+ #[test]
+ fn cdp_frame_console_objects_keep_their_world_without_leaking_child_store_entries() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ rt.set_runtime_events_enabled(true);
+ let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
+ "http://foreign.test/child", "<html><body>child</body></html>").unwrap();
+ frame.execute_script(&mut rt, "console.log({answer:42})").unwrap();
+ let events = rt.take_pending_runtime_events();
+ let oid = events.iter().find_map(|event| match event {
+ RuntimeEvent::Console(event) => event.args.iter().find_map(|arg| arg["objectId"].as_str()),
+ _ => None,
+ }).expect("missing console object").to_string();
+ let CdpEvaluation::Complete(result) = rt.start_cdp_call(
+ "function() { return [document.URL, this.answer]; }", Some(&oid), &[], true, false,
+ ).unwrap() else { panic!("expected a value"); };
+ assert_eq!(result.value.unwrap(), serde_json::json!(["http://foreign.test/child",42]));
+ assert_eq!(frame.evaluate(&mut rt, "Object.keys(globalThis.__obscura_objects).length").unwrap(),
+ serde_json::json!(0));
+ rt.release_object(&oid);
+ assert_eq!(rt.evaluate("Object.keys(globalThis.__obscura_objects).length").unwrap(), serde_json::json!(0.0));
+ assert!(rt.start_cdp_call("function() { return this; }", Some(&oid), &[], true, false).is_err());
+ drop(frame);
+ }
+
+ #[test]
+ fn cdp_frame_handles_keep_the_wrapping_world_and_reject_reused_realms() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
+ "http://example.com/child", "<html><body>child</body></html>").unwrap();
+ frame.evaluate(&mut rt, "globalThis.childObject = {nested: {answer:42}}").unwrap();
+ let child = rt.start_cdp_evaluation_in_frame(Some(1), "childObject", false, false).unwrap();
+ let CdpEvaluation::Complete(child) = child else { panic!("expected a handle"); };
+ let child_id = child.object_id.unwrap();
+ let root = rt.start_cdp_evaluation(
+ "globalThis.__obscura_frameObjects[1].window.childObject", false, false,
+ ).unwrap();
+ let CdpEvaluation::Complete(root) = root else { panic!("expected a handle"); };
+ let root_id = root.object_id.unwrap();
+ for (id, expected) in [(&root_id, "http://example.com/test"), (&child_id, "http://example.com/child")] {
+ let result = rt.start_cdp_call("function() { return document.URL; }", Some(id), &[], true, false).unwrap();
+ let CdpEvaluation::Complete(result) = result else { panic!("expected a value"); };
+ assert_eq!(result.value.unwrap(), serde_json::json!(expected));
+ }
+ drop(frame);
+ let _replacement = crate::frame::FrameRealm::new(&mut rt, 1, 0,
+ "http://example.com/new", "<html><body>new</body></html>").unwrap();
+ assert_eq!(rt.validate_cdp_object_context(&child_id).unwrap_err(), "Execution context was destroyed");
+ assert!(rt.start_cdp_call("function() { return 1; }", Some(&child_id), &[], true, false).is_err());
+ assert!(rt.start_cdp_call("function() { return document.URL; }", Some(&root_id), &[], true, false).is_ok());
+ }
+
+ #[test]
+ fn cdp_calls_reject_unknown_released_cross_world_and_malformed_node_handles() {
+ let mut rt = setup_runtime("<html><body><h1>Main</h1></body></html>");
+ let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
+ "http://example.com/child", "<html><body>child</body></html>").unwrap();
+ let CdpEvaluation::Complete(child) = rt.start_cdp_evaluation_in_frame(
+ Some(1), "({answer:42})", false, false,
+ ).unwrap() else { panic!("expected a handle"); };
+ let child_id = child.object_id.unwrap();
+ let invalid = ["unknown", "node-", "node--1", "node-+1", "node-1e1", "node-4294967296",
+ "node-1;globalThis.__pwned=1;//", "node-1\n"];
+ for id in invalid {
+ assert!(rt.start_cdp_call("function() { globalThis.__pwned=1; }",
+ Some(id), &[], true, false).is_err(), "{id}");
+ assert!(rt.start_cdp_call("function(value) { globalThis.__pwned=1; }",
+ None, &[serde_json::json!({"objectId":id,"value":null})], true, false).is_err(), "{id}");
+ }
+ assert!(rt.start_cdp_call("function(value) { globalThis.__pwned=1; }", None,
+ &[serde_json::json!({"objectId":child_id})], true, false).is_err());
+ assert!(rt.start_cdp_call_in_frame(Some(1), "function(value) { return value.answer; }", None,
+ &[serde_json::json!({"objectId":child_id,"value":null})], true, false).is_ok());
+ let node_id = rt.with_dom(|dom| dom.query_selector("h1").unwrap().unwrap().raw()).unwrap();
+ assert!(rt.start_cdp_call("function() { return this.textContent; }",
+ Some(&format!("node-{node_id}")), &[], true, false).is_ok());
+ rt.release_object(&child_id);
+ assert!(rt.start_cdp_call("function() { globalThis.__pwned=1; }",
+ Some(&child_id), &[], true, false).is_err());
+ assert_eq!(rt.evaluate("globalThis.__pwned").unwrap(), serde_json::Value::Null);
+ drop(frame);
+ }
+
+ #[test]
+ fn cdp_suspension_recipes_never_restore_child_handles_in_the_main_world() {
+ let mut rt = setup_runtime("<html><body><h1>Main</h1></body></html>");
+ let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
+ "http://example.com/child", "<html><body>child</body></html>").unwrap();
+ let CdpEvaluation::Complete(child) = rt.start_cdp_evaluation_in_frame(
+ Some(1), "({answer:42})", false, false,
+ ).unwrap() else { panic!("expected a handle"); };
+ let child_id = child.object_id.unwrap();
+ let CdpEvaluation::Complete(root) = rt.start_cdp_evaluation(
+ "document.querySelector('h1')", false, false,
+ ).unwrap() else { panic!("expected a handle"); };
+ let root_id = root.object_id.unwrap();
+ let state = rt.take_cdp_object_state();
+ drop(frame);
+ drop(rt);
+ let mut rt = setup_runtime("<html><body><h1>Main</h1></body></html>");
+ rt.restore_cdp_object_state(state);
+ assert!(rt.start_cdp_call("function() { return document.URL; }",
+ Some(&child_id), &[], true, false).is_err());
+ let CdpEvaluation::Complete(value) = rt.start_cdp_call("function() { return this.textContent; }",
+ Some(&root_id), &[], true, false).unwrap() else { panic!("expected a value"); };
+ assert_eq!(value.value.unwrap(), serde_json::json!("Main"));
+ rt.release_object_group();
+ assert!(rt.start_cdp_call("function() { return this; }",
+ Some(&root_id), &[], true, false).is_err());
+ }
+
+ #[test]
+ fn pending_cdp_frame_evaluation_rejects_a_retired_realm_with_a_reused_id() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
+ "http://example.com/child", "<html><body>old</body></html>").unwrap();
+ let evaluation = rt.start_cdp_evaluation_in_frame(
+ Some(1), "new Promise(() => {})", true, true,
+ ).unwrap();
+ let CdpEvaluation::Pending(pending) = evaluation else {
+ panic!("expected a pending child evaluation");
+ };
+ assert!(rt.has_cdp_evaluation(&pending));
+ drop(frame);
+ let _replacement = crate::frame::FrameRealm::new(&mut rt, 1, 0,
+ "http://example.com/child", "<html><body>new</body></html>").unwrap();
+ assert!(!rt.has_cdp_evaluation(&pending));
+ assert!(!rt.cdp_evaluation_ready(&pending));
+ assert_eq!(rt.finish_cdp_evaluation(pending, true).unwrap_err(),
+ "Execution context was destroyed");
+ assert!(rt.pending_cdp_evaluations.is_empty());
+ }
+
#[test]
fn table_rows_are_live_ordered_readonly_collections() {
let mut rt = setup_runtime("<html><body></body></html>");
@@ -20819,7 +21124,7 @@ mod tests {
// store holds it; simulate a store entry whose id carries source text.
let hostile = "x'];globalThis.__pwned=1;//";
rt.object_store
- .insert(hostile.to_string(), "undefined".to_string());
+ .insert(hostile.to_string(), CdpObjectRecord { retrieval: "undefined".to_string(), frame: None });
rt.release_object(hostile);
assert_eq!(
rt.evaluate("globalThis.__pwned").unwrap(),
diff --git a/docs/Architecture-overview.md b/docs/Architecture-overview.md
index afd4d309..42793ff5 100644
--- a/docs/Architecture-overview.md
+++ b/docs/Architecture-overview.md
@@ -125,9 +125,19 @@ their native owning document, including handles obtained through the parent.
The document element carries that document's protocol frame ID, so Playwright
can discover an element handle's owner frame. Retired frame handles fail
instead of reading a same-numbered node in the main document.
-Child-frame CDP evaluation routing and iframe content compositing remain
-separate compatibility gaps; loading a document does not establish support
-for Playwright frame locators or iframe screenshot fidelity.
+Live child frames advertise their default CDP execution contexts.
+`Runtime.evaluate` and `Runtime.callFunctionOn`, including awaited calls,
+enter the frame's actual V8 realm and use its document. Remote objects remain
+in the page's central handle store, while result metadata is read in the
+owning realm. Object handles and their property handles retain the realm
+of the evaluation that produced them, not the object's creation realm.
+Calls reject retired realms and unknown or released handles rather than
+falling back to the main document.
+Pending evaluations reject retired frame contexts instead of reading a
+replacement document. Named utility contexts still alias their
+frame's realm rather than providing separate JavaScript worlds.
+Iframe content compositing remains a separate compatibility gap; evaluating
+a child document does not establish iframe screenshot fidelity.
## Robustness