Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(dom): preserve DOMImplementation argument and result realms

ldm0bc67a4797054
diff --git a/moli-renderer-v8/src/context_bootstrap/constructors/dom_implementation.rs b/moli-renderer-v8/src/context_bootstrap/constructors/dom_implementation.rs
index c65cb7114..103852f8c 100644
--- a/moli-renderer-v8/src/context_bootstrap/constructors/dom_implementation.rs
+++ b/moli-renderer-v8/src/context_bootstrap/constructors/dom_implementation.rs
@@ -13,7 +13,7 @@ struct DomImplementationSingletonDeclaration<'scope> {
}
#[derive(WebApiFunctionTemplate)]
-#[webapi(interface = web_api_interfaces::DOMImplementation)]
+#[webapi(interface = web_api_interfaces::DOMImplementation, receiver)]
struct DomImplementationPrototypeMethodsDeclaration {
#[webapi(method, enumerable, length = 0, callback = dom_implementation_has_feature_callback)]
has_feature: (),
@@ -79,11 +79,11 @@ struct DomImplementationCreateDocumentArgs<'s> {
#[webidl(
required,
name = "qualifiedName",
- converter = "raw",
+ treat_null_as_empty_string,
missing_message = "Failed to execute 'createDocument' on 'DOMImplementation': 2 arguments required."
)]
- qualified_name: v8::Local<'s, v8::Value>,
- #[webidl(index = 2, converter = "raw", nullable)]
+ qualified_name: String,
+ #[webidl(index = 2, nullable, interface = web_api_interfaces::DocumentType)]
doctype: Option<v8::Local<'s, v8::Object>>,
}
@@ -106,6 +106,34 @@ fn current_document_object<'s>(
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
}
+fn dom_implementation_owner_document<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ implementation: v8::Local<'s, v8::Object>,
+) -> Option<v8::Local<'s, v8::Object>> {
+ get_private_object(
+ scope,
+ implementation,
+ DOM_IMPLEMENTATION_OWNER_DOCUMENT_SLOT,
+ )
+ .or_else(|| current_document_object(scope))
+}
+
+fn create_document_type_value<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ parsed: &DomImplementationCreateDocumentTypeArgs,
+ owner_document: Option<v8::Local<'s, v8::Object>>,
+) -> Option<v8::Local<'s, v8::Value>> {
+ let qualified_name = v8_string(scope, &parsed.qualified_name)?;
+ let public_id = v8_string(scope, &parsed.public_id)?;
+ let system_id = v8_string(scope, &parsed.system_id)?;
+ let mut argv = vec![qualified_name.into(), public_id.into(), system_id.into()];
+ if let Some(owner_document) = owner_document {
+ argv.push(owner_document.into());
+ }
+ let (bridge, method) = global_bridge_method(scope, "__createDetachedDocumentType")?;
+ method.call(scope, bridge.into(), &argv)
+}
+
fn dom_implementation_create_document_type_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
@@ -124,30 +152,13 @@ fn dom_implementation_create_document_type_callback<'s>(
);
return;
}
- let Some(qualified_name) = v8_string(scope, &parsed.qualified_name) else {
- rv.set_undefined();
- return;
- };
- let Some(public_id) = v8_string(scope, &parsed.public_id) else {
- rv.set_undefined();
- return;
- };
- let Some(system_id) = v8_string(scope, &parsed.system_id) else {
- rv.set_undefined();
- return;
- };
- let mut argv = vec![qualified_name.into(), public_id.into(), system_id.into()];
- if let Some(owner_document) =
- get_private_object(scope, args.this(), DOM_IMPLEMENTATION_OWNER_DOCUMENT_SLOT)
- .or_else(|| current_document_object(scope))
- {
- argv.push(owner_document.into());
- }
- let Some((bridge, method)) = global_bridge_method(scope, "__createDetachedDocumentType") else {
- rv.set_undefined();
- return;
- };
- match method.call(scope, bridge.into(), &argv) {
+ let owner_document = dom_implementation_owner_document(scope, args.this());
+ let relevant_context = owner_document
+ .and_then(|document| crate::native_bridge::node_relevant_context(scope, document))
+ .or_else(|| args.this().get_creation_context(scope))
+ .unwrap_or_else(|| scope.get_current_context());
+ let target_scope = &mut v8::ContextScope::new(scope, relevant_context);
+ match create_document_type_value(target_scope, &parsed, owner_document) {
Some(value) => rv.set(value),
None => rv.set_undefined(),
}
@@ -168,44 +179,47 @@ fn dom_implementation_create_html_document_callback<'s>(
else {
return;
};
- let Some((bridge, method)) = global_bridge_method(scope, "__createDetachedHTMLDocument") else {
- rv.set_undefined();
- return;
- };
- let call_args = match parsed.title {
- Some(title) => {
- let Some(title) = v8_string(scope, &title) else {
- rv.set_undefined();
- return;
- };
- vec![title.into()]
- }
- None => Vec::new(),
- };
- match method.call(scope, bridge.into(), &call_args) {
+ let owner_document = dom_implementation_owner_document(scope, args.this());
+ let relevant_context = owner_document
+ .and_then(|document| crate::native_bridge::node_relevant_context(scope, document))
+ .or_else(|| args.this().get_creation_context(scope))
+ .unwrap_or_else(|| scope.get_current_context());
+ let target_scope = &mut v8::ContextScope::new(scope, relevant_context);
+ match create_html_document_value(target_scope, parsed.title.as_deref()) {
Some(value) => rv.set(value),
None => rv.set_undefined(),
}
}
-fn dom_implementation_create_document_qualified_name<'s>(
+fn create_html_document_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
- value: v8::Local<'s, v8::Value>,
+ title: Option<&str>,
) -> Option<v8::Local<'s, v8::Value>> {
- if value.is_null() {
- return Some(v8::null(scope).into());
- }
- match webidl::convert::<webidl::DomString>(
- scope,
- value,
- webidl::Context::argument("DOMImplementation.createDocument", 2),
- ) {
- Ok(value) => v8_string(scope, &value.0).map(v8::Local::<v8::Value>::from),
- Err(error) => {
- webidl::throw_error(scope, &error);
- None
- }
- }
+ let (bridge, method) = global_bridge_method(scope, "__createDetachedHTMLDocument")?;
+ let call_args = match title {
+ Some(title) => vec![v8_string(scope, title)?.into()],
+ None => Vec::new(),
+ };
+ method.call(scope, bridge.into(), &call_args)
+}
+
+fn create_document_value<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ namespace_uri: Option<&str>,
+ qualified_name: &str,
+ doctype: Option<v8::Local<'s, v8::Object>>,
+) -> Option<v8::Local<'s, v8::Value>> {
+ let namespace_uri = match namespace_uri {
+ Some(namespace_uri) => v8_string(scope, namespace_uri)?.into(),
+ None => v8::null(scope).into(),
+ };
+ let qualified_name = v8_string(scope, qualified_name)?.into();
+ let doctype = doctype
+ .map(v8::Local::<v8::Value>::from)
+ .unwrap_or_else(|| v8::null(scope).into());
+ let argv = [namespace_uri, qualified_name, doctype];
+ let (bridge, method) = global_bridge_method(scope, "__createDetachedXmlDocument")?;
+ method.call(scope, bridge.into(), &argv)
}
fn dom_implementation_create_document_callback<'s>(
@@ -217,32 +231,18 @@ fn dom_implementation_create_document_callback<'s>(
else {
return;
};
- let namespace_uri = match parsed.namespace_uri {
- Some(namespace_uri) => {
- let Some(namespace_uri) = v8_string(scope, &namespace_uri) else {
- rv.set_undefined();
- return;
- };
- namespace_uri.into()
- }
- None => v8::null(scope).into(),
- };
- let Some(qualified_name) =
- dom_implementation_create_document_qualified_name(scope, parsed.qualified_name)
- else {
- rv.set_undefined();
- return;
- };
- let doctype = parsed
- .doctype
- .map(v8::Local::<v8::Value>::from)
- .unwrap_or_else(|| v8::null(scope).into());
- let argv = [namespace_uri, qualified_name, doctype];
- let Some((bridge, method)) = global_bridge_method(scope, "__createDetachedXmlDocument") else {
- rv.set_undefined();
- return;
- };
- match method.call(scope, bridge.into(), &argv) {
+ let owner_document = dom_implementation_owner_document(scope, args.this());
+ let relevant_context = owner_document
+ .and_then(|document| crate::native_bridge::node_relevant_context(scope, document))
+ .or_else(|| args.this().get_creation_context(scope))
+ .unwrap_or_else(|| scope.get_current_context());
+ let target_scope = &mut v8::ContextScope::new(scope, relevant_context);
+ match create_document_value(
+ target_scope,
+ parsed.namespace_uri.as_deref(),
+ &parsed.qualified_name,
+ parsed.doctype,
+ ) {
Some(value) => rv.set(value),
None => rv.set_undefined(),
}
diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects/mutation.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects/mutation.rs
index 378cd1708..7710f74ab 100644
--- a/moli-renderer-v8/src/native_bridge/document/detached_objects/mutation.rs
+++ b/moli-renderer-v8/src/native_bridge/document/detached_objects/mutation.rs
@@ -1,3 +1,4 @@
+use super::state_tree::owner_document_native_handle;
use super::*;
use crate::{
native_bridge::document::detached_install::{
@@ -113,20 +114,6 @@ fn string_or_null<'s>(
})
}
-fn owner_document_native_handle<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- runtime_ptr: *mut JsContextHost,
- owner_document: v8::Local<'s, v8::Object>,
-) -> Option<DomHandle> {
- detached_native_handle_for_runtime(scope, runtime_ptr, owner_document).or_else(|| {
- node_runtime_and_handle_from_object(scope, owner_document)
- .ok()
- .and_then(|(node_runtime_ptr, handle)| {
- (node_runtime_ptr == runtime_ptr).then_some(handle)
- })
- })
-}
-
fn define_detached_attribute_maps_for_live_element<'s>(
scope: &mut v8::PinScope<'s, '_>,
state: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects/state_tree.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects/state_tree.rs
index 142fcf279..ef383ccae 100644
--- a/moli-renderer-v8/src/native_bridge/document/detached_objects/state_tree.rs
+++ b/moli-renderer-v8/src/native_bridge/document/detached_objects/state_tree.rs
@@ -172,6 +172,20 @@ fn detached_set_owner_document_inner<'s>(
}
}
+pub(super) fn owner_document_native_handle<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ runtime_ptr: *mut JsContextHost,
+ owner_document: v8::Local<'s, v8::Object>,
+) -> Option<DomHandle> {
+ detached_native_handle_for_runtime(scope, runtime_ptr, owner_document).or_else(|| {
+ node_runtime_and_handle_from_object(scope, owner_document)
+ .ok()
+ .and_then(|(node_runtime_ptr, handle)| {
+ (node_runtime_ptr == runtime_ptr).then_some(handle)
+ })
+ })
+}
+
fn sync_detached_native_owner_document<'s>(
scope: &mut v8::PinScope<'s, '_>,
node: v8::Local<'s, v8::Object>,
@@ -184,8 +198,7 @@ fn sync_detached_native_owner_document<'s>(
let Some(handle) = detached_native_handle_for_runtime(scope, runtime_ptr, node) else {
return false;
};
- let Some(document_handle) =
- detached_native_handle_for_runtime(scope, runtime_ptr, owner_document)
+ let Some(document_handle) = owner_document_native_handle(scope, runtime_ptr, owner_document)
else {
return false;
};
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_implementation_arguments.js b/moli-renderer-v8/src/script_vm/tests/dom_implementation_arguments.js
new file mode 100644
index 000000000..b16d88380
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/dom_implementation_arguments.js
@@ -0,0 +1,135 @@
+(async () => {
+ const checks = [];
+ const check = (name, actual, expected) => checks.push({name, actual, expected, passed: JSON.stringify(actual) === JSON.stringify(expected)});
+ const capture = (action, sentinel, callee) => {
+ try { action(); return null; } catch (error) {
+ if (error === sentinel) return 'sentinel';
+ if (error.name === 'TypeError' && Object.getPrototypeOf(error) !== callee.TypeError.prototype) return 'wrong-realm-TypeError';
+ return error.name;
+ }
+ };
+ const frame = document.createElement('iframe'); document.body.appendChild(frame);
+ let popup;
+ try {
+ const realms = [['main', window], ['iframe', frame.contentWindow]];
+ const includePopup = globalThis.__domImplementationIncludePopup !== false;
+ if (includePopup) {
+ popup = window.open('', '_blank');
+ if (!popup) throw new Error('popup unavailable');
+ await new Promise(resolve => setTimeout(resolve, 0));
+ realms.push(['popup', popup]);
+ }
+ for (const [ownerName, owner] of realms) {
+ const documents = [
+ ['live', owner.document],
+ ['html', owner.document.implementation.createHTMLDocument('')],
+ ['xml', owner.document.implementation.createDocument(null, 'root')],
+ ['parsed-html', new owner.DOMParser().parseFromString('<!doctype html><body>', 'text/html')],
+ ['parsed-xml', new owner.DOMParser().parseFromString('<root/>', 'application/xml')],
+ ['new-document', new owner.Document()],
+ ];
+ for (const [docName, doc] of documents) {
+ const implementation = doc.implementation;
+ for (const [calleeName, callee] of realms) {
+ const prefix = `${ownerName}/${docName}/${calleeName}`;
+ const methods = callee.DOMImplementation.prototype;
+ check(prefix + '/genuine-hasFeature', methods.hasFeature.call(implementation), true);
+ const html = methods.createHTMLDocument.call(implementation, 'native title');
+ check(prefix + '/genuine-html', [html.title, html instanceof owner.HTMLDocument, html.body.ownerDocument === html], ['native title', true, true]);
+ const doctype = methods.createDocumentType.call(implementation, 'root', 'public', 'system');
+ check(prefix + '/genuine-doctype', [doctype.name, doctype.publicId, doctype.systemId, doctype.ownerDocument === doc, doctype instanceof owner.DocumentType], ['root', 'public', 'system', true, true]);
+ const xml = methods.createDocument.call(implementation, 'urn:test', 'root', doctype);
+ check(prefix + '/genuine-xml', [xml instanceof owner.XMLDocument, xml.doctype === doctype, doctype.ownerDocument === xml, xml.documentElement.namespaceURI], [true, true, true, 'urn:test']);
+
+ for (const [receiverName, makeReceiver] of [
+ ['plain', () => ({})],
+ ['prototype', () => Object.create(owner.DOMImplementation.prototype)],
+ ['inherited', () => Object.create(implementation)],
+ ['proxy', () => new Proxy(implementation, {})],
+ ['revoked', () => { const revocable = Proxy.revocable(implementation, {}); revocable.revoke(); return revocable.proxy; }],
+ ['document', () => doc],
+ ['element', () => doc.createElement('select')],
+ ['null', () => null],
+ ['undefined', () => undefined],
+ ['number', () => 1],
+ ['symbol', () => Symbol()],
+ ]) {
+ for (const method of ['hasFeature', 'createHTMLDocument', 'createDocumentType', 'createDocument']) {
+ const log = [];
+ const argument = label => ({toString() {log.push(label); return 'root';}});
+ const args = method === 'hasFeature' ? [argument('feature'), argument('version')]
+ : method === 'createHTMLDocument' ? [argument('title')]
+ : method === 'createDocumentType' ? [argument('name'), argument('public'), argument('system')]
+ : [argument('namespace'), argument('name'), {}];
+ check(`${prefix}/receiver/${receiverName}/${method}`, [capture(() => methods[method].apply(makeReceiver(), args), undefined, callee), log], ['TypeError', []]);
+ check(`${prefix}/receiver-arity/${receiverName}/${method}`, capture(() => methods[method].call(makeReceiver()), undefined, callee), 'TypeError');
+ }
+ }
+ const traps = [];
+ const receiver = new Proxy(implementation, {
+ get() {traps.push('get'); throw new Error('receiver get trap');},
+ getPrototypeOf() {traps.push('getPrototypeOf'); throw new Error('receiver prototype trap');},
+ });
+ for (const method of ['hasFeature', 'createHTMLDocument', 'createDocumentType', 'createDocument']) {
+ check(`${prefix}/receiver-traps/${method}`, [capture(() => methods[method].call(receiver), undefined, callee), traps.slice()], ['TypeError', []]);
+ }
+
+ for (const [valueName, makeValue, accepted] of [
+ ['omitted', () => undefined, true],
+ ['null', () => null, true],
+ ['genuine', () => implementation.createDocumentType('root', '', ''), true],
+ ['plain', () => ({}), false],
+ ['prototype', () => Object.create(owner.DocumentType.prototype), false],
+ ['inherited', () => Object.create(implementation.createDocumentType('root', '', '')), false],
+ ['proxy', () => new Proxy(implementation.createDocumentType('root', '', ''), {}), false],
+ ['revoked', () => {const revocable = Proxy.revocable(implementation.createDocumentType('root', '', ''), {}); revocable.revoke(); return revocable.proxy;}, false],
+ ['number', () => 1, false],
+ ['string', () => 'root', false],
+ ['symbol', () => Symbol(), false],
+ ['document', () => doc, false],
+ ]) {
+ for (const nameValid of [false, true]) for (const stop of [-1, 0, 1]) {
+ const log = [], sentinel = {};
+ const argument = (text, label, index) => ({toString() {log.push(label); if (stop === index) throw sentinel; return text;}});
+ const namespace = argument('urn:test', 'namespace', 0);
+ const name = argument(nameValid ? 'root' : 'bad name', 'name', 1);
+ const value = makeValue();
+ const expectedError = stop >= 0 ? 'sentinel' : !accepted ? 'TypeError' : nameValid ? null : 'InvalidCharacterError';
+ const expectedLog = stop === 0 ? ['namespace'] : ['namespace', 'name'];
+ check(`${prefix}/doctype/${valueName}/${nameValid}/${stop}`, [capture(() => methods.createDocument.call(implementation, namespace, name, value), sentinel, callee), log], [expectedError, expectedLog]);
+ }
+ }
+ for (const value of [null, undefined]) {
+ const empty = methods.createDocument.call(implementation, null, value, null);
+ check(`${prefix}/legacy-null-name/${String(value)}`, empty.documentElement?.localName ?? null, value === null ? null : 'undefined');
+ }
+ const nameLog = [], sentinel = {};
+ check(prefix + '/throwing-name-before-invalid-doctype', capture(() => methods.createDocument.call(implementation, null, {toString() {nameLog.push('name'); throw sentinel;}}, 1), sentinel, callee), 'sentinel');
+ check(prefix + '/throwing-name-log', nameLog, ['name']);
+ for (const value of [{}, 1, Symbol()]) {
+ check(`${prefix}/symbol-name/${typeof value}`, capture(() => methods.createDocument.call(implementation, null, Symbol(), value), undefined, callee), 'TypeError');
+ check(`${prefix}/namespace-before-doctype/${typeof value}`, capture(() => methods.createDocument.call(implementation, null, 'p:root', value), undefined, callee), 'TypeError');
+ }
+ const argumentTraps = [];
+ const invalidDoctype = new Proxy(doctype, {
+ get() {argumentTraps.push('get'); throw new Error('doctype get trap');},
+ getPrototypeOf() {argumentTraps.push('getPrototypeOf'); throw new Error('doctype prototype trap');},
+ });
+ check(prefix + '/doctype-traps', [capture(() => methods.createDocument.call(implementation, null, 'bad name', invalidDoctype), undefined, callee), argumentTraps], ['TypeError', []]);
+ for (const [method, args, expectedLog] of [
+ ['createDocument', [{toString() {throw new Error('arity conversion');}}], []],
+ ['createDocumentType', ['root', {toString() {throw new Error('arity conversion');}}], []],
+ ]) {
+ const log = [];
+ check(`${prefix}/genuine-arity/${method}`, [capture(() => methods[method].apply(implementation, args), undefined, callee), log], ['TypeError', expectedLog]);
+ }
+ }
+ }
+ }
+ globalThis.__uiEventResults = {complete: true, includePopup, total: checks.length, passed: checks.filter(row => row.passed).length, checks};
+ return checks.every(row => row.passed);
+ } finally {
+ if (popup) popup.close();
+ frame.remove();
+ }
+})()
diff --git a/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs b/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs
index f80ee0a58..2e5875046 100644
--- a/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs
+++ b/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs
@@ -368,3 +368,32 @@ async fn mutation_record_node_lists_are_native_readonly_snapshots() {
"true"
);
}
+
+#[tokio::test(flavor = "current_thread")]
+async fn dom_implementation_derives_receiver_and_argument_conversion_in_each_document_realm() {
+ let loader = static_http_loader(std::iter::empty::<String>());
+ let mut vm = new_page_task_executor_test_vm_with_loader(
+ "https://dom-implementation-arguments.test/",
+ &loader,
+ );
+ // Actual popup Pages run the same fixture over CDP.
+ vm.exec("globalThis.__domImplementationIncludePopup = false;", None)
+ .unwrap();
+ vm.exec(include_str!("dom_implementation_arguments.js"), None)
+ .unwrap();
+ advance_page_task_executor_until_eval_equals(
+ &mut vm,
+ &loader,
+ "String(globalThis.__uiEventResults?.complete === true)",
+ "true",
+ "DOMImplementation receiver and argument conversion",
+ )
+ .await;
+ assert_eq!(
+ vm.eval("JSON.stringify(__uiEventResults.checks.filter(row => !row.passed))")
+ .unwrap(),
+ "[]",
+ );
+ assert_eq!(vm.eval("__uiEventResults.includePopup").unwrap(), "false");
+ assert_eq!(vm.eval("__uiEventResults.total").unwrap(), "4344");
+}