Skip to content

The headless browser for AI agents and web scraping

fix(runtime): create initial iframe realms synchronously

SGavrl24d87427f610
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index 15a14933..f2550204 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -3,6 +3,7 @@ use std::sync::Arc;
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use obscura_dom::{parse_html, DomTree};
use obscura_js::frame::FrameRealm;
+use obscura_js::ops::max_live_frames;
use obscura_js::runtime::ObscuraJsRuntime;
use obscura_net::{
CallbackRegistry, ObscuraHttpClient, ObscuraNetError, RequestCallback, ResourceRequest,
@@ -343,18 +344,6 @@ const MAX_STYLESHEET_IMPORT_DEPTH: u8 = 4;
const MAX_STYLESHEET_RESOURCES: usize = 128;
const DEFAULT_NAVIGATION_TIMEOUT_MS: u64 = 30_000;
-/// How many child frame realms one document may hold at once.
-///
-/// Real pages use a handful; the cap exists so a page that creates iframes in a
-/// loop cannot make the engine hold an unbounded number of contexts and DOM
-/// trees. Frames are released when the document is replaced.
-fn max_live_frames() -> usize {
- std::env::var("OBSCURA_MAX_LIVE_FRAMES")
- .ok()
- .and_then(|value| value.parse().ok())
- .unwrap_or(64)
-}
-
/// The first navigation counts. The low default stops a page that resets
/// `location` on every load.
const DEFAULT_NAVIGATION_CHAIN_LIMIT: usize = 10;
@@ -1413,6 +1402,9 @@ impl Page {
/// page's same-origin frame table. This also covers a frame rejected before
/// a `FrameRealm` exists, so the normal drop path cannot be skipped.
fn forget_frame_references(&mut self, frame_id: u32, parent_frame_id: u32) {
+ if let Some(js) = self.js.as_mut() {
+ js.forget_frame_state(frame_id);
+ }
let script = format!(
"if (globalThis.__obscura_frameElements[{frame_id}] &&\
globalThis.__obscura_frameElements[{frame_id}]._frameId === {frame_id}) {{\
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 674a7182..b701a017 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -4564,6 +4564,7 @@ class Element extends Node {
if (oldId) {
delete globalThis.__obscura_frameElements[oldId];
delete globalThis.__obscura_frameWindows[oldId];
+ delete globalThis.__obscura_frameObjects[oldId];
}
this._frameId = 0;
this._iframeLoadingUrl = null;
@@ -4600,6 +4601,7 @@ class Element extends Node {
// document below stays: it is what the parent reads through
// contentDocument.
const box = el.getBoundingClientRect();
+ if (el._frameId) globalThis.__obscura_forgetFrame(el._frameId);
el._frameId = __obscuraCore.ops.op_frame_document_ready(
loadedUrl, html, Math.round(box.width) || 300, Math.round(box.height) || 150);
if (el._frameId) globalThis.__obscura_frameElements[el._frameId] = el;
@@ -4634,6 +4636,7 @@ class Element extends Node {
}
get contentDocument() {
if (this.localName !== 'iframe') return undefined;
+ if (_ensureInitialFrameRealm(this) === false) return null;
const real = _frameObjectsFor(this);
if (real?.document) return real.document;
if (this._iframeDoc) {
@@ -4655,6 +4658,7 @@ class Element extends Node {
}
get contentWindow() {
if (this.localName !== 'iframe') return undefined;
+ if (_ensureInitialFrameRealm(this) === false) return null;
if (_frameObjectsFor(this)) {
const win = _frameWindowFor(this._frameId);
if (win) return win;
@@ -5649,7 +5653,10 @@ class Document extends Node {
}
title.textContent = value;
}
- get URL() { return _domParse("document_url") ?? ""; }
+ get URL() {
+ const get = _documentRealmMember(this, 'URL');
+ return get ? Reflect.apply(get, this, []) : (_domParse("document_url") ?? "");
+ }
get documentURI() { return this.URL; }
get domain() {
return this === globalThis.document
@@ -5676,7 +5683,10 @@ class Document extends Node {
get referrer() { return _domParse("document_referrer") ?? ""; }
get location() { return globalThis.location; }
set location(url) { __obscuraCore.ops.op_navigate(_resolveUrl(String(url)), 'GET', ''); }
- get defaultView() { return globalThis; }
+ get defaultView() {
+ const get = _documentRealmMember(this, 'defaultView');
+ return get ? Reflect.apply(get, this, []) : globalThis;
+ }
get nodeType() { return 9; }
get nodeName() { return "#document"; }
get ownerDocument() { return null; } // Document has no ownerDocument
@@ -5708,7 +5718,10 @@ class Document extends Node {
if (/\.(?:xml|svg)(?:[?#]|$)/i.test(url)) return "application/xml";
return "text/html";
}
- get readyState() { return globalThis.__documentReadyState__ || 'complete'; }
+ get readyState() {
+ const get = _documentRealmMember(this, 'readyState');
+ return get ? Reflect.apply(get, this, []) : (globalThis.__documentReadyState__ || 'complete');
+ }
get currentScript() {
// Next.js / Turbopack chunk loader reads document.currentScript.src to
// derive its base path. page.rs sets __currentScriptNid before each
@@ -5719,11 +5732,18 @@ class Document extends Node {
get hidden() { return false; }
get visibilityState() { return "visible"; }
getElementById(id) {
+ const method = _documentRealmMember(this, 'getElementById');
+ if (method) return Reflect.apply(method, this, [id]);
const needle = String(id);
return needle === "" ? null : _wrapEl(+_dom("get_element_by_id", needle));
}
- querySelector(s) { return _wrapEl(+_dom("query_selector", s)); }
+ querySelector(s) {
+ const method = _documentRealmMember(this, 'querySelector');
+ return method ? Reflect.apply(method, this, [s]) : _wrapEl(+_dom("query_selector", s));
+ }
querySelectorAll(s) {
+ const method = _documentRealmMember(this, 'querySelectorAll');
+ if (method) return Reflect.apply(method, this, [s]);
const ids = _domParse("query_selector_all", s) || [];
return _nodeList(ids.map(_wrapEl).filter(Boolean));
}
@@ -6216,8 +6236,12 @@ class Document extends Node {
this.write(args.join('') + '\n');
}
open() {
- if (this.head) this.head.innerHTML = '';
- var body = this.body;
+ const method = _documentRealmMember(this, 'open');
+ if (method) return Reflect.apply(method, this, []);
+ // Native algorithms use the receiver's tree, not script-overridden getters.
+ const head = _wrapEl(+_dom('query_selector', 'head'));
+ if (head) head.innerHTML = '';
+ const body = _wrapEl(+_dom('query_selector', 'body'));
if (body) body.innerHTML = '';
// A new parse begins. Whatever the input stream still held is gone.
_dom("document_write_reset");
@@ -6230,6 +6254,8 @@ class Document extends Node {
return this;
}
close() {
+ const method = _documentRealmMember(this, 'close');
+ if (method) return Reflect.apply(method, this, []);
if (!this._writeOpen) return;
this._writeOpen = false;
const generation = this._writeGeneration;
@@ -6258,6 +6284,18 @@ class Document extends Node {
execCommand() { return false; }
}
+// Preserve the receiver realm's implementations even if a membrane remaps the
+// document's public prototype. The ordinary own-document path makes no op call.
+const _documentMembers = Object.freeze(Object.fromEntries(
+ ['URL', 'defaultView', 'readyState', 'getElementById', 'querySelector', 'querySelectorAll', 'open', 'close'].map(name => {
+ const descriptor = Object.getOwnPropertyDescriptor(Document.prototype, name);
+ return [name, descriptor.value || descriptor.get];
+ })));
+function _documentRealmMember(receiver, name) {
+ return receiver === globalThis.document ? undefined
+ : __obscuraCore.ops.op_document_realm_member(receiver, name, _realmFrameId);
+}
+
class DocumentFragment extends Node {
constructor(nid) {
const created = nid === undefined;
@@ -13270,7 +13308,7 @@ globalThis.__obscura_forgetFrame = function (frameId) {
};
function _realmOrigin() {
- try { return new URL(_domParse('document_url')).origin; } catch (_) { return 'null'; }
+ return _domParse('document_origin') || 'null';
}
// Whether a postMessage restricted to `targetOrigin` may be delivered to a
@@ -13303,8 +13341,20 @@ function _sendRealmMessage(targetFrameId, data, targetOrigin) {
// An unspecified targetOrigin stays permissive (empty string); the receiver
// enforces a specified one against its own origin in __obscura_deliverMessage.
const to = (targetOrigin === undefined || targetOrigin === null) ? '' : String(targetOrigin);
- __obscuraCore.ops.op_post_frame_message(
- targetFrameId >>> 0, globalThis.__obscura_frameId >>> 0, _realmOrigin(), to, json);
+ if (__obscuraCore.ops.op_post_frame_message(targetFrameId >>> 0, to, json)) return;
+ // Top-level self-posts also work in a standalone runtime without a Page to
+ // drain cross-realm messages. Serialize only once, before scheduling.
+ const origin = _realmOrigin();
+ if (!_targetOriginAllows(targetOrigin, origin, origin)) return;
+ const clone = JSON.parse(json).v;
+ setTimeout(() => {
+ try {
+ globalThis.dispatchEvent(globalThis.__obscura_markTrusted(
+ new MessageEvent('message', { data: clone, origin, source: globalThis })));
+ } catch (error) {
+ console.error('message listener failed:', error && error.message || error);
+ }
+ }, 0);
}
// The frame's own window and document, when this page is allowed to touch
@@ -13322,6 +13372,44 @@ function _frameObjectsFor(element) {
return entry || null;
}
+function _ensureInitialFrameRealm(element) {
+ if (element._frameId || !element.isConnected) return;
+ // An opaque sandbox must never receive the creator's security token.
+ if (element.hasAttribute('sandbox') &&
+ !element.getAttribute('sandbox').split(/\s+/).includes('allow-same-origin')) return;
+ const frameId = __obscuraCore.ops.op_initial_frame(_realmFrameId, (child, id) => {
+ const core = child.__obscura_core_handoff;
+ for (const name of Object.keys(__obscuraCore.ops)) core.ops[name] = __obscuraCore.ops[name];
+ delete child.__obscura_core_handoff;
+ delete child.Deno;
+ for (const name of ['__obscura_ua', '__obscura_platform', '__obscura_ua_platform',
+ '__obscura_ua_platform_version', '__obscura_stealth',
+ '__obscura_geo_lat', '__obscura_geo_lon']) {
+ if (globalThis[name] !== undefined) child[name] = globalThis[name];
+ }
+ child.__obscura_frameId = id;
+ child.__obscura_parentFrameId = _realmFrameId;
+ child.__obscura_init();
+ Object.defineProperties(child, {
+ parent: { value: globalThis, configurable: true },
+ top: { value: globalThis.top, configurable: true },
+ frameElement: { value: element, configurable: true },
+ });
+ child.innerWidth = 300;
+ child.innerHeight = 150;
+ globalThis.__obscura_frameObjects[id] = {
+ window: child, document: child.document, initial: true,
+ };
+ });
+ if (frameId) {
+ element._frameId = frameId;
+ element._iframeWin = globalThis.__obscura_frameObjects[frameId].window;
+ element._iframeDoc = globalThis.__obscura_frameObjects[frameId].document;
+ globalThis.__obscura_frameElements[frameId] = element;
+ }
+ return frameId !== 0;
+}
+
// The window object this realm uses to stand for frame `frameId`, built once
// and reused so `event.source === iframe.contentWindow` holds.
//
@@ -13334,6 +13422,7 @@ function _frameWindowFor(frameId) {
const real = globalThis.__obscura_frameObjects?.[frameId]?.window;
const existing = globalThis.__obscura_frameWindows[frameId];
if (!real) return existing || null;
+ if (globalThis.__obscura_frameObjects[frameId].initial) return real;
if (existing && existing.__obscura_wrapsRealm) return existing;
const post = _markNative(function (data, targetOrigin, _transfer) {
@@ -14653,26 +14742,7 @@ globalThis.stop = function() {}; _markNative(globalThis.stop);
// Same realm, so this needs no host round trip; it is queued as a task because
// postMessage never delivers synchronously.
globalThis.postMessage = function(data, targetOrigin, _transfer) {
- let clone = data;
- // Match the cross-realm path: a value postMessage cannot carry is rejected
- // at the call, not delivered as something else.
- try {
- clone = JSON.parse(JSON.stringify({ v: data === undefined ? null : data })).v;
- } catch (_) {
- throw new DOMException('The object could not be cloned.', 'DataCloneError');
- }
- const origin = _realmOrigin();
- // A self-post honours targetOrigin too: sender and receiver are this realm,
- // so a targetOrigin naming a different origin drops the message.
- if (!_targetOriginAllows(targetOrigin, origin, origin)) return;
- setTimeout(() => {
- try {
- globalThis.dispatchEvent(globalThis.__obscura_markTrusted(
- new MessageEvent('message', { data: clone, origin, source: globalThis })));
- } catch (error) {
- console.error('message listener failed:', error && error.message || error);
- }
- }, 0);
+ _sendRealmMessage(_realmFrameId, data, targetOrigin);
};
_markNative(globalThis.postMessage);
globalThis.requestIdleCallback = globalThis.requestIdleCallback || function(cb) { return setTimeout(cb, 0); };
@@ -16070,6 +16140,7 @@ if (typeof ShadowRoot !== 'undefined' && !ShadowRoot.prototype.elementFromPoint)
globalThis.__obscura_init = function() {
// The host sets __obscura_frameId on a frame realm before calling this.
_realmFrameId = globalThis.__obscura_frameId >>> 0;
+ __obscuraCore.ops.op_register_document_realm(_documentMembers, _realmFrameId);
_browserPostedTaskWakePending = false;
for (const queue of _browserPostedTaskQueues) _browserPostedTaskDiscardQueue(queue);
_fpSeed = Date.now() ^ (Math.random() * 0xFFFFFFFF >>> 0);
diff --git a/crates/obscura-js/src/frame.rs b/crates/obscura-js/src/frame.rs
index 335e57e3..f50aaa31 100644
--- a/crates/obscura-js/src/frame.rs
+++ b/crates/obscura-js/src/frame.rs
@@ -60,6 +60,23 @@ impl FrameRealm {
url: &str,
html: &str,
) -> Option<Self> {
+ let realms = parent.realm_states();
+ let existing = realms.borrow().context(frame_id);
+ if let Some(context) = existing {
+ let state = realms.borrow().by_frame_id(frame_id)?;
+ let origin = state.borrow().inherited_origin.clone().unwrap_or_else(|| origin_of(url));
+ return Some(Self {
+ context,
+ realms,
+ frame_id,
+ parent_frame_id,
+ url: url.to_string(),
+ origin,
+ });
+ }
+ if realms.borrow().live_count() >= crate::ops::max_live_frames() {
+ return None;
+ }
let context = parent.create_realm_context()?;
if !parent.share_ops_with_realm(&context) {
return None;
@@ -260,7 +277,7 @@ impl FrameRealm {
parent: &mut ObscuraJsRuntime,
load_external: impl Fn(&str) -> Option<String>,
) -> Vec<String> {
- let scripts = match self.list_scripts(parent) {
+ let scripts = match self.list_scripts() {
Ok(scripts) => scripts,
Err(error) => return vec![error],
};
@@ -300,8 +317,8 @@ impl FrameRealm {
///
/// A caller that fetches over the network needs the list before running
/// anything, because `run_document_scripts` resolves sources synchronously.
- pub fn external_script_urls(&self, parent: &mut ObscuraJsRuntime) -> Vec<String> {
- self.list_scripts(parent)
+ pub fn external_script_urls(&self, _parent: &mut ObscuraJsRuntime) -> Vec<String> {
+ self.list_scripts()
.unwrap_or_default()
.iter()
.filter(|script| script.is_classic() && !script.src.is_empty())
@@ -318,26 +335,27 @@ impl FrameRealm {
.unwrap_or_else(|_| src.to_string())
}
- fn list_scripts(&self, parent: &mut ObscuraJsRuntime) -> Result<Vec<DocumentScript>, String> {
- let listed = self.evaluate(
- parent,
- r#"[...document.querySelectorAll('script')].map(node => ({
- src: node.getAttribute('src') || '',
- type: (node.getAttribute('type') || '').toLowerCase(),
- text: node.textContent || '',
- }))"#,
- );
- match listed {
- Ok(value) => Ok(serde_json::from_value(value).unwrap_or_default()),
- Err(error) => Err(format!("could not list frame scripts: {error}")),
- }
+ fn list_scripts(&self) -> Result<Vec<DocumentScript>, String> {
+ // Browser-owned discovery must not execute script-overridden DOM APIs.
+ let state = self.realms.borrow().by_frame_id(self.frame_id)
+ .ok_or_else(|| "could not list frame scripts: missing realm".to_string())?;
+ let state = state.borrow();
+ let dom = state.dom.as_ref()
+ .ok_or_else(|| "could not list frame scripts: missing document".to_string())?;
+ let nodes = dom.query_selector_all("script")?;
+ Ok(nodes.into_iter().filter_map(|id| {
+ let text = dom.text_content(id);
+ dom.with_node(id, |node| DocumentScript {
+ src: node.get_attribute("src").unwrap_or("").to_string(),
+ type_attribute: node.get_attribute("type").unwrap_or("").to_lowercase(),
+ text,
+ })
+ }).collect())
}
}
-#[derive(serde::Deserialize)]
struct DocumentScript {
src: String,
- #[serde(rename = "type")]
type_attribute: String,
text: String,
}
@@ -446,6 +464,103 @@ mod tests {
assert!(frame.is_same_origin_as("https://child.example"));
}
+ #[test]
+ fn initial_frame_adoption_preserves_the_realm_and_inherited_base() {
+ let mut parent = page("https://parent.example/pages/index.html", "<html><body></body></html>");
+ parent.execute_script("initial-frame", r#"
+ globalThis.frameElementProbe = document.createElement('iframe');
+ document.body.appendChild(frameElementProbe);
+ globalThis.initialWindowProbe = frameElementProbe.contentWindow;
+ initialWindowProbe.eval('globalThis.marker = 42; document.body.textContent = "child"');
+ "#).unwrap();
+ let pending = parent.take_pending_frames().pop().expect("initial frame queued");
+ let frame = FrameRealm::new(&mut parent, pending.frame_id, pending.parent_frame_id,
+ &pending.url, &pending.html).expect("adopt initial realm");
+ assert_eq!(frame.origin(), "https://parent.example");
+ assert_eq!(frame.evaluate(&mut parent,
+ "[marker, document.body.textContent, document.URL, document.baseURI]").unwrap(),
+ serde_json::json!([42, "child", "about:blank", "https://parent.example/pages/index.html"]));
+ assert_eq!(parent.evaluate(
+ "[initialWindowProbe === frameElementProbe.contentWindow, initialWindowProbe.parent === window, typeof marker, document.body.textContent]").unwrap(),
+ serde_json::json!([true, true, "undefined", ""]));
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn initial_frame_messages_keep_the_calling_realm_as_sender() {
+ let mut parent = page("https://parent.example/", "<html><body></body></html>");
+ parent.execute_script("initial-frame", r#"
+ globalThis.frameElementProbe = document.createElement('iframe');
+ document.body.appendChild(frameElementProbe);
+ globalThis.initialWindowProbe = frameElementProbe.contentWindow;
+ initialWindowProbe.postMessage('from-parent', '*');
+ "#).unwrap();
+ let pending = parent.take_pending_frames().pop().unwrap();
+ let frame = FrameRealm::new(&mut parent, pending.frame_id, 0,
+ &pending.url, &pending.html).unwrap();
+ frame.execute_script(&mut parent,
+ "parent.postMessage('from-child', '*'); postMessage('to-self', '*');").unwrap();
+ let messages = parent.take_pending_frame_messages();
+ assert_eq!(messages.iter().map(|message| (
+ message.target_frame_id, message.source_frame_id, message.origin.as_str()
+ )).collect::<Vec<_>>(), vec![
+ (frame.frame_id(), 0, "https://parent.example"),
+ (0, frame.frame_id(), "https://parent.example"),
+ (frame.frame_id(), frame.frame_id(), "https://parent.example"),
+ ]);
+ }
+
+ #[test]
+ fn nested_initial_frame_uses_its_owner_document_not_the_entered_page() {
+ let mut parent = page("https://parent.example/", "<html><body></body></html>");
+ parent.execute_script("nested-initial-frame", r#"
+ const iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ const child = iframe.contentWindow;
+ const nested = child.document.createElement('iframe');
+ child.document.body.appendChild(nested);
+ globalThis.nestedWindowProbe = nested.contentWindow;
+ "#).unwrap();
+ let pending = parent.take_pending_frames();
+ assert_eq!(pending.len(), 2);
+ assert_eq!(pending[0].parent_frame_id, 0);
+ assert_eq!(pending[1].parent_frame_id, pending[0].frame_id);
+ }
+
+ #[test]
+ fn initial_frame_script_discovery_does_not_read_the_parent_after_prototype_remap() {
+ let mut parent = page("https://parent.example/",
+ "<html><body><script src='/parent.js'></script></body></html>");
+ parent.execute_script("initial-frame", r#"
+ const iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ const child = iframe.contentWindow;
+ Object.setPrototypeOf(child.document, Document.prototype);
+ "#).unwrap();
+ let pending = parent.take_pending_frames().pop().unwrap();
+ let frame = FrameRealm::new(&mut parent, pending.frame_id, 0,
+ &pending.url, &pending.html).unwrap();
+ assert!(frame.external_script_urls(&mut parent).is_empty(),
+ "initial frame must not replay its parent's author scripts");
+ }
+
+ #[test]
+ fn initial_frame_script_discovery_ignores_overridden_dom_methods() {
+ let mut parent = page("https://parent.example/",
+ "<html><body><script src='/parent.js'></script></body></html>");
+ parent.execute_script("initial-frame", r#"
+ const iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ const child = iframe.contentWindow;
+ const parentScripts = document.querySelectorAll('script');
+ child.document.querySelectorAll = () => parentScripts;
+ "#).unwrap();
+ let pending = parent.take_pending_frames().pop().unwrap();
+ let frame = FrameRealm::new(&mut parent, pending.frame_id, 0,
+ &pending.url, &pending.html).unwrap();
+ assert!(frame.external_script_urls(&mut parent).is_empty(),
+ "author script discovery must use the actual frame DOM");
+ }
+
#[tokio::test(flavor = "current_thread")]
async fn frame_uses_its_embedding_viewport() {
let mut parent = page(
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 72e3002a..e027c1cd 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -111,6 +111,9 @@ pub(crate) struct CanvasBackingSurface {
pub struct ObscuraState {
pub dom: Option<DomTree>,
pub url: String,
+ /// Initial about:blank documents retain their creator's base URL and origin.
+ pub(crate) about_base_url: Option<String>,
+ pub(crate) inherited_origin: Option<String>,
/// WHATWG canonical name of the document's character encoding (e.g.
/// "UTF-8", "EUC-JP"). Backs `document.characterSet` and the URL query
/// encoding override for `<a>`/`<area>` hrefs in legacy-charset documents.
@@ -351,12 +354,32 @@ pub struct PendingFrameMessage {
}
impl ObscuraState {
+ pub(crate) fn inherit_resources(&mut self, parent: &Self) {
+ self.cookie_jar = parent.cookie_jar.clone();
+ self.http_client = parent.http_client.clone();
+ self.callbacks = parent.callbacks.clone();
+ self.encoding = parent.encoding.clone();
+ self.blocked_urls = parent.blocked_urls.clone();
+ self.intercept_enabled = parent.intercept_enabled;
+ self.page_in_flight = parent.page_in_flight.clone();
+ #[cfg(feature = "stealth")]
+ {
+ self.stealth_client = parent.stealth_client.clone();
+ }
+ #[cfg(feature = "render")]
+ if has_page_transport(parent) {
+ self.render_resources.set_sync_loading_enabled(false);
+ }
+ }
+
pub fn new() -> Self {
#[cfg(feature = "render")]
let (render_resource_tx, render_resource_rx) = tokio::sync::mpsc::unbounded_channel();
ObscuraState {
dom: None,
url: "about:blank".to_string(),
+ about_base_url: None,
+ inherited_origin: None,
encoding: "UTF-8".to_string(),
title: String::new(),
referrer: String::new(),
@@ -658,6 +681,18 @@ pub struct RealmStates {
}
impl RealmStates {
+ pub(crate) fn live_count(&self) -> usize {
+ self.entries.len()
+ }
+
+ pub(crate) fn context(&self, frame_id: u32) -> Option<v8::Global<v8::Context>> {
+ self.entries.iter().find(|(_, id, _)| *id == frame_id)
+ .map(|(context, _, _)| context.clone())
+ }
+
+ pub(crate) fn forget_frame(&mut self, frame_id: u32) {
+ self.entries.retain(|(_, id, _)| *id != frame_id);
+ }
pub fn register(
&mut self,
context: v8::Global<v8::Context>,
@@ -671,7 +706,7 @@ impl RealmStates {
self.entries.retain(|(known, _, _)| known != context);
}
- fn by_frame_id(&self, frame_id: u32) -> Option<SharedState> {
+ pub(crate) fn by_frame_id(&self, frame_id: u32) -> Option<SharedState> {
self.entries
.iter()
.find(|(_, id, _)| *id == frame_id)
@@ -1785,6 +1820,10 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->
serde_json::to_string(&title).unwrap_or("\"\"".into())
}
"document_url" => serde_json::to_string(&gs.url).unwrap_or("\"\"".into()),
+ "document_origin" => serde_json::to_string(&gs.inherited_origin.clone().unwrap_or_else(|| {
+ url::Url::parse(&gs.url).map(|url| url.origin().ascii_serialization())
+ .unwrap_or_else(|_| "null".to_string())
+ })).unwrap_or("\"null\"".into()),
// The base for relative URLs. It differs from document_url exactly when the page carries
// a <base href>, and that is the point: HTML resolves against the base, not the document.
"document_base_url" => serde_json::to_string(
@@ -5249,13 +5288,23 @@ fn frame_message_queue_byte_limit() -> usize {
// handshake actually depends on.
#[op2(fast)]
fn op_post_frame_message(
+ scope: &mut v8::PinScope,
state: &OpState,
target_frame_id: u32,
- source_frame_id: u32,
- #[string] origin: &str,
#[string] target_origin: &str,
#[string] data_json: &str,
-) {
+) -> bool {
+ let source = realm_state(scope, state);
+ let source = source.borrow();
+ let source_frame_id = source.frame_id;
+ if source_frame_id == 0 && target_frame_id == 0 {
+ return false; // The page's self-post uses its existing local task queue.
+ }
+ let origin = source.inherited_origin.clone().unwrap_or_else(|| {
+ url::Url::parse(&source.url).map(|url| url.origin().ascii_serialization())
+ .unwrap_or_else(|_| "null".to_string())
+ });
+ drop(source);
let gs = state.borrow::<SharedState>().clone();
let mut gs = gs.borrow_mut();
let over_entries = gs.pending_frame_messages.len() >= frame_message_queue_entry_limit();
@@ -5270,7 +5319,7 @@ fn op_post_frame_message(
gs.pending_frame_messages.len(),
gs.pending_frame_message_bytes,
);
- return;
+ return true;
}
gs.pending_frame_message_bytes = gs
.pending_frame_message_bytes
@@ -5278,10 +5327,11 @@ fn op_post_frame_message(
gs.pending_frame_messages.push(PendingFrameMessage {
target_frame_id,
source_frame_id,
- origin: origin.to_string(),
+ origin,
target_origin: target_origin.to_string(),
data_json: data_json.to_string(),
});
+ true
}
/// Resolves after `millis`, as the timer source for child frame realms.
@@ -5345,6 +5395,122 @@ fn op_frame_document_ready(
frame_id
}
+// deno_core owns the context-state and module-map slots. Store traced V8 values
+// after them, not Global handles that would keep the context alive after detach.
+const DOCUMENT_MEMBERS_SLOT: i32 = deno_core::MODULE_MAP_SLOT_INDEX + 1;
+const DOCUMENT_OWNER_SLOT: i32 = DOCUMENT_MEMBERS_SLOT + 1;
+
+#[op2(nofast)]
+fn op_register_document_realm(
+ scope: &mut v8::PinScope,
+ members: v8::Local<v8::Object>,
+ frame_id: u32,
+) {
+ if let Some(context) = members.get_creation_context(scope) {
+ context.set_embedder_data(DOCUMENT_MEMBERS_SLOT, members.into());
+ let id = v8::Integer::new_from_unsigned(scope, frame_id);
+ context.set_embedder_data(DOCUMENT_OWNER_SLOT, id.into());
+ }
+}
+
+/// Resolve a borrowed document member from the receiver's creation realm, not
+/// its public prototype, which a membrane is allowed to replace.
+#[op2]
+fn op_document_realm_member<'s, 'i>(
+ scope: &mut v8::PinScope<'s, 'i>,
+ receiver: v8::Local<'s, v8::Object>,
+ #[string] name: &str,
+ caller_frame_id: u32,
+) -> v8::Local<'s, v8::Value> {
+ let member = (|| {
+ let context = receiver.get_creation_context(scope)?;
+ let owner = context.get_embedder_data(scope, DOCUMENT_OWNER_SLOT)?.uint32_value(scope)?;
+ if owner == caller_frame_id { return None; }
+ let members = context.get_embedder_data(scope, DOCUMENT_MEMBERS_SLOT)?.to_object(scope)?;
+ let key = v8::String::new(scope, name)?;
+ let value = members.get(scope, key.into())?;
+ value.is_function().then_some(value)
+ })();
+ member.unwrap_or_else(|| v8::undefined(scope).into())
+}
+
+/// Limit live contexts and DOM trees, including initial realms awaiting Page
+/// adoption. Synchronous and fetched frames share the same per-page budget.
+pub fn max_live_frames() -> usize {
+ std::env::var("OBSCURA_MAX_LIVE_FRAMES").ok()
+ .and_then(|value| value.parse().ok()).unwrap_or(64)
+}
+
+/// An initial about:blank needs its own realm before the next JS statement.
+#[op2(nofast)]
+fn op_initial_frame(
+ scope: &mut v8::PinScope,
+ state: &OpState,
+ parent_frame_id: u32,
+ initialize: v8::Local<v8::Function>,
+) -> u32 {
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ let registry = state.borrow::<Rc<RefCell<RealmStates>>>().clone();
+ let page = state.borrow::<SharedState>().clone();
+ let parent_state = frame_state(state, parent_frame_id);
+ if registry.borrow().live_count() >= max_live_frames()
+ || page.borrow().pending_frames.len() >= MAX_PENDING_FRAME_DOCUMENTS
+ || page.borrow().pending_frame_bytes.saturating_add("about:blank".len()) > MAX_PENDING_FRAME_BYTES
+ {
+ return 0;
+ }
+ let Some(frame_id) = page.borrow().frame_id_counter.checked_add(1) else { return 0 };
+ page.borrow_mut().frame_id_counter = frame_id;
+ let Some(parent_context) = initialize.get_creation_context(scope) else { return 0 };
+ let main_context = scope.get_current_context();
+ let Some(context) = v8::Context::from_snapshot(scope, 1, Default::default())
+ .or_else(|| v8::Context::from_snapshot(scope, 0, Default::default()))
+ else { return 0 };
+ // Same borrowed deno_core slots as fetched frame realms. Child contexts
+ // must not own or free these pointers.
+ unsafe {
+ for index in [deno_core::CONTEXT_STATE_SLOT_INDEX, deno_core::MODULE_MAP_SLOT_INDEX] {
+ let pointer = main_context.get_aligned_pointer_from_embedder_data(index);
+ context.set_aligned_pointer_in_embedder_data(index, pointer);
+ }
+ }
+ context.set_security_token(parent_context.get_security_token(scope));
+ let mut child = ObscuraState::new();
+ {
+ let parent = parent_state.borrow();
+ child.dom = Some(obscura_dom::parse_html(
+ "<!DOCTYPE html><html><head></head><body></body></html>"));
+ child.frame_id = frame_id;
+ child.about_base_url = document_base_url(&parent);
+ child.inherited_origin = Some(parent.inherited_origin.clone().unwrap_or_else(|| {
+ url::Url::parse(&parent.url).map(|url| url.origin().ascii_serialization())
+ .unwrap_or_else(|_| "null".to_string())
+ }));
+ child.inherit_resources(&parent);
+ }
+ let handle = v8::Global::new(scope, context);
+ registry.borrow_mut().register(handle.clone(), frame_id, Rc::new(RefCell::new(child)));
+ let window = context.global(scope);
+ let id = v8::Integer::new_from_unsigned(scope, frame_id);
+ let receiver = v8::undefined(scope);
+ if initialize.call(scope, receiver.into(), &[window.into(), id.into()]).is_none() {
+ registry.borrow_mut().forget(&handle);
+ return 0;
+ }
+ let mut page = page.borrow_mut();
+ page.pending_frame_bytes = page.pending_frame_bytes.saturating_add("about:blank".len());
+ page.pending_frames.push(PendingFrame {
+ frame_id,
+ parent_frame_id,
+ url: "about:blank".to_string(),
+ html: String::new(),
+ viewport_width: 300,
+ viewport_height: 150,
+ });
+ frame_id
+ })).unwrap_or(0)
+}
+
/// Whether async host work can be scheduled without aborting the isolate.
///
/// Some low-level embedders intentionally execute a synchronous expression
@@ -6242,6 +6408,9 @@ pub fn build_extension() -> Extension {
op_session_history(),
op_history_traverse(),
op_frame_document_ready(),
+ op_initial_frame(),
+ op_document_realm_member(),
+ op_register_document_realm(),
op_post_frame_message(),
op_sleep(),
op_async_runtime_available(),
@@ -6467,7 +6636,7 @@ fn op_waapi_control(state: &OpState, id: f64, #[string] action: &str, value: f64
// Not tied to `render`: the JS layer resolves every relative URL through here, in all build
// variants.
pub(crate) fn document_base_url(state: &ObscuraState) -> Option<String> {
- let document_url = url::Url::parse(&state.url).ok()?;
+ let document_url = url::Url::parse(state.about_base_url.as_deref().unwrap_or(&state.url)).ok()?;
let base_href = state.dom.as_ref().and_then(|dom| {
dom.query_selector("base[href]")
.ok()
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 5dfc209f..9c890049 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -948,26 +948,15 @@ impl ObscuraJsRuntime {
/// client, callbacks and the stealth transport. A frame shares these with
/// its page, exactly as it shares them in a browser.
pub(crate) fn share_resources_with(&self, frame: &mut ObscuraState) {
- let parent = self.state.borrow();
- frame.cookie_jar = parent.cookie_jar.clone();
- frame.http_client = parent.http_client.clone();
- frame.callbacks = parent.callbacks.clone();
- frame.encoding = parent.encoding.clone();
- frame.blocked_urls = parent.blocked_urls.clone();
- frame.intercept_enabled = parent.intercept_enabled;
- frame.page_in_flight = parent.page_in_flight.clone();
- #[cfg(feature = "stealth")]
- {
- frame.stealth_client = parent.stealth_client.clone();
- }
// A frame realm shares the page transport, so its renderer cache must
// not open synchronous requests either. Frame geometry currently
// resolves against the main document's renderer state, so frame-scoped
// background loading is not wired up here.
- #[cfg(feature = "render")]
- if crate::ops::has_page_transport(&parent) {
- frame.render_resources.set_sync_loading_enabled(false);
- }
+ frame.inherit_resources(&self.state.borrow());
+ }
+
+ pub fn forget_frame_state(&mut self, frame_id: u32) {
+ self.realm_states().borrow_mut().forget_frame(frame_id);
}
/// The origin of the document this runtime is running, or `"null"` for a
@@ -4938,6 +4927,64 @@ mod tests {
);
}
+ #[test]
+ fn initial_blank_iframe_eval_uses_the_child_realm() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ assert_eq!(
+ rt.evaluate(
+ r#"(() => {
+ const iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ const child = iframe.contentWindow;
+ const globalMatches = child.eval('globalThis') === child;
+ const constructorMatches = child.eval('Array') === child.Array;
+ child.eval('globalThis.__initialFrameSentinel = 123');
+ return [globalMatches, constructorMatches,
+ child.__initialFrameSentinel === 123,
+ globalThis.__initialFrameSentinel === undefined];
+ })()"#,
+ ).unwrap(),
+ serde_json::json!([true, true, true, true])
+ );
+ }
+
+ #[test]
+ fn document_open_does_not_use_overridden_head_or_body_getters() {
+ let mut rt = setup_runtime(
+ "<html><head><base href='https://parent.example/'></head><body>parent</body></html>");
+ assert_eq!(rt.evaluate(r#"(() => {
+ const iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ const childDocument = iframe.contentDocument;
+ Object.defineProperties(childDocument, {
+ head: { get: () => document.head },
+ body: { get: () => document.body },
+ });
+ Document.prototype.open.call(childDocument);
+ return [document.body.textContent, document.baseURI];
+ })()"#).unwrap(), serde_json::json!(["parent", "https://parent.example/"]));
+ }
+
+ #[test]
+ fn borrowed_document_methods_keep_the_receiver_realm_after_prototype_remap() {
+ let mut rt = setup_runtime(
+ "<html><head><base href='https://parent.example/'></head><body>parent</body></html>");
+ assert_eq!(rt.evaluate(r#"(() => {
+ const iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ const child = iframe.contentWindow;
+ const childDocument = child.document;
+ Object.setPrototypeOf(childDocument, Document.prototype);
+ const initialUrl = childDocument.URL;
+ const separateBody = childDocument.querySelector('body') !== document.body;
+ Document.prototype.open.call(childDocument);
+ return [document.body.textContent, document.baseURI, document.readyState,
+ separateBody, initialUrl];
+ })()"#).unwrap(), serde_json::json!([
+ "parent", "https://parent.example/", "complete", true, "about:blank"
+ ]));
+ }
+
#[test]
fn iframe_content_window_exposes_realm_globals() {
let mut rt = setup_runtime("<html><body></body></html>");