Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(webidl): validate remaining Document member receivers

ldm0db615d78ebb7
diff --git a/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs b/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs
index 638f3b996..3c3dc19b7 100644
--- a/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs
+++ b/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs
@@ -111,7 +111,7 @@ struct CssStyleDeclarationTemplateMethodsDeclaration {
}
#[derive(WebApiFunctionTemplate)]
-#[webapi(interface = web_api_interfaces::HTMLDocument, enumerable)]
+#[webapi(interface = web_api_interfaces::HTMLDocument, enumerable, receiver = web_api_interfaces::Document::is_instance)]
struct HtmlDocumentTemplateAccessorsDeclaration {
#[webapi(
accessor_property = "location",
diff --git a/moli-renderer-v8/src/context_bootstrap/event_template.rs b/moli-renderer-v8/src/context_bootstrap/event_template.rs
index 46c8aa539..bec0b0fe1 100644
--- a/moli-renderer-v8/src/context_bootstrap/event_template.rs
+++ b/moli-renderer-v8/src/context_bootstrap/event_template.rs
@@ -306,7 +306,7 @@ struct EventTargetTemplateMethodsDeclaration {
}
#[derive(WebApiFunctionTemplate)]
-#[webapi(interface = web_api_interfaces::Document, enumerable)]
+#[webapi(interface = web_api_interfaces::Document, enumerable, receiver)]
struct DocumentEventTemplateMethodsDeclaration {
#[webapi(method = "createEvent", length = 1, callback = document_create_event_callback)]
create_event: (),
diff --git a/moli-renderer-v8/src/context_bootstrap/range_surface/install.rs b/moli-renderer-v8/src/context_bootstrap/range_surface/install.rs
index a211ec7ce..48f75fa4f 100644
--- a/moli-renderer-v8/src/context_bootstrap/range_surface/install.rs
+++ b/moli-renderer-v8/src/context_bootstrap/range_surface/install.rs
@@ -20,7 +20,7 @@ use crate::web_api_interfaces;
use moli_webapi_declare::WebApiFunctionTemplate;
#[derive(WebApiFunctionTemplate)]
-#[webapi(interface = web_api_interfaces::Document, enumerable)]
+#[webapi(interface = web_api_interfaces::Document, enumerable, receiver)]
struct DocumentRangePrototypeDeclaration {
#[webapi(method, length = 0, callback = document_create_range_callback)]
create_range: (),
diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
index ccf0de846..0dc469d97 100644
--- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
+++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
@@ -87,7 +87,7 @@ struct DocumentStaticMethodsDeclaration {
}
#[derive(Default, WebApiObject)]
-#[webapi(fragment, prototype = "Document", enumerable)]
+#[webapi(fragment, prototype = "Document", enumerable, receiver = web_api_interfaces::Document::is_instance)]
struct DocumentPrototypeRuntimeDeclaration {
#[webapi(
accessor_property = "designMode",
diff --git a/moli-renderer-v8/src/context_bootstrap/view_transition_runtime/bindings.rs b/moli-renderer-v8/src/context_bootstrap/view_transition_runtime/bindings.rs
index 9b8e060b2..f1836ec34 100644
--- a/moli-renderer-v8/src/context_bootstrap/view_transition_runtime/bindings.rs
+++ b/moli-renderer-v8/src/context_bootstrap/view_transition_runtime/bindings.rs
@@ -17,7 +17,7 @@ use crate::web_api_interfaces;
use moli_webapi_declare::WebApiFunctionTemplate;
#[derive(WebApiFunctionTemplate)]
-#[webapi(interface = web_api_interfaces::Document, enumerable)]
+#[webapi(interface = web_api_interfaces::Document, enumerable, receiver)]
struct DocumentViewTransitionTemplateDeclaration {
#[webapi(
method = "startViewTransition",
diff --git a/moli-renderer-v8/src/native_bridge/document.rs b/moli-renderer-v8/src/native_bridge/document.rs
index 60f36fdfb..89b173931 100644
--- a/moli-renderer-v8/src/native_bridge/document.rs
+++ b/moli-renderer-v8/src/native_bridge/document.rs
@@ -413,7 +413,7 @@ struct DocumentStatePrototypeDeclaration {
}
#[derive(WebApiFunctionTemplate)]
-#[webapi(interface = web_api_interfaces::Document, enumerable)]
+#[webapi(interface = web_api_interfaces::Document, enumerable, receiver)]
struct DocumentCollectionAccessorsPrototypeDeclaration {
#[webapi(accessor_property, getter = document_forms_getter_function)]
forms: (),
@@ -434,7 +434,7 @@ struct DocumentCollectionAccessorsPrototypeDeclaration {
}
#[derive(WebApiFunctionTemplate)]
-#[webapi(interface = web_api_interfaces::Document)]
+#[webapi(interface = web_api_interfaces::Document, receiver)]
struct DocumentCollectionQueryPrototypeDeclaration {
#[webapi(
method,
@@ -463,7 +463,7 @@ struct DocumentCollectionQueryPrototypeDeclaration {
}
#[derive(WebApiFunctionTemplate)]
-#[webapi(interface = web_api_interfaces::Document, enumerable)]
+#[webapi(interface = web_api_interfaces::Document, enumerable, receiver)]
struct DocumentObsoleteMethodsPrototypeDeclaration {
#[webapi(method, length = 0, callback = document_obsolete_noop_callback)]
clear: (),
@@ -1421,14 +1421,14 @@ pub(crate) fn install_document_template_bindings<'s>(
}
#[derive(WebApiFunctionTemplate)]
-#[webapi(interface = web_api_interfaces::Document)]
+#[webapi(interface = web_api_interfaces::Document, receiver)]
struct DocumentGetElementByIdTemplateDeclaration {
#[webapi(method = "getElementById", length = 1, callback = node_get_element_by_id_callback)]
get_element_by_id: (),
}
#[derive(WebApiFunctionTemplate)]
-#[webapi(interface = web_api_interfaces::Document, enumerable)]
+#[webapi(interface = web_api_interfaces::Document, enumerable, receiver)]
struct DocumentPrototypeMethodsDeclaration {
#[webapi(method = "createElement", length = 1, callback = node_create_element_callback)]
create_element: (),
@@ -1553,12 +1553,14 @@ struct DocumentPrototypeMethodsDeclaration {
#[webapi(
method = "hasStorageAccess",
length = 0,
+ returns_promise,
callback = node_document_has_storage_access_callback
)]
has_storage_access: (),
#[webapi(
method = "requestStorageAccess",
length = 0,
+ returns_promise,
callback = node_document_request_storage_access_callback
)]
request_storage_access: (),
diff --git a/moli-renderer-v8/src/native_bridge/element.rs b/moli-renderer-v8/src/native_bridge/element.rs
index 785aa6198..f634ccd22 100644
--- a/moli-renderer-v8/src/native_bridge/element.rs
+++ b/moli-renderer-v8/src/native_bridge/element.rs
@@ -1387,7 +1387,7 @@ struct ElementAriaElementReflectionDeclaration {
}
#[derive(WebApiFunctionTemplate)]
-#[webapi(interface = web_api_interfaces::Document)]
+#[webapi(interface = web_api_interfaces::Document, receiver)]
struct DocumentCustomElementRegistryPrototypeDeclaration {
#[webapi(
accessor_property = "customElementRegistry",
diff --git a/moli-renderer-v8/src/native_bridge/node.rs b/moli-renderer-v8/src/native_bridge/node.rs
index 0e56c09c7..396c93df7 100644
--- a/moli-renderer-v8/src/native_bridge/node.rs
+++ b/moli-renderer-v8/src/native_bridge/node.rs
@@ -112,31 +112,48 @@ struct NodePrototypeReflectionDeclaration {
normalize: (),
}
-#[derive(WebApiFunctionTemplate)]
-#[webapi(name = "ParentNode", enumerable)]
-struct ParentNodePrototypeDeclaration {
- #[webapi(accessor_property, getter = parent_node_children_getter_function)]
- children: (),
- #[webapi(accessor_property, getter = parent_node_first_element_child_getter_function)]
- first_element_child: (),
- #[webapi(accessor_property, getter = parent_node_last_element_child_getter_function)]
- last_element_child: (),
- #[webapi(accessor_property, getter = parent_node_child_element_count_getter_function)]
- child_element_count: (),
- #[webapi(method, length = 0, callback = node_prepend_callback)]
- prepend: (),
- #[webapi(method, length = 0, callback = node_append_callback)]
- append: (),
- #[webapi(method, length = 0, callback = node_replace_children_callback)]
- replace_children: (),
- #[webapi(method = "moveBefore", length = 2, callback = node_move_before_callback)]
- move_before: (),
- #[webapi(method, length = 1, callback = super::element::node_query_selector_callback)]
- query_selector: (),
- #[webapi(method, length = 1, callback = super::element::node_query_selector_all_callback)]
- query_selector_all: (),
+macro_rules! declare_parent_node_prototype {
+ ($declaration:ident, $($binding:tt)*) => {
+ #[derive(WebApiFunctionTemplate)]
+ #[webapi($($binding)*)]
+ struct $declaration {
+ #[webapi(accessor_property, getter = parent_node_children_getter_function)]
+ children: (),
+ #[webapi(accessor_property, getter = parent_node_first_element_child_getter_function)]
+ first_element_child: (),
+ #[webapi(accessor_property, getter = parent_node_last_element_child_getter_function)]
+ last_element_child: (),
+ #[webapi(accessor_property, getter = parent_node_child_element_count_getter_function)]
+ child_element_count: (),
+ #[webapi(method, length = 0, callback = node_prepend_callback)]
+ prepend: (),
+ #[webapi(method, length = 0, callback = node_append_callback)]
+ append: (),
+ #[webapi(method, length = 0, callback = node_replace_children_callback)]
+ replace_children: (),
+ #[webapi(method = "moveBefore", length = 2, callback = node_move_before_callback)]
+ move_before: (),
+ #[webapi(method, length = 1, callback = super::element::node_query_selector_callback)]
+ query_selector: (),
+ #[webapi(method, length = 1, callback = super::element::node_query_selector_all_callback)]
+ query_selector_all: (),
+ }
+ };
}
+declare_parent_node_prototype!(
+ ParentNodePrototypeDeclaration,
+ name = "ParentNode",
+ enumerable
+);
+// A mixin member must validate the interface whose prototype owns it.
+declare_parent_node_prototype!(
+ DocumentParentNodePrototypeDeclaration,
+ interface = web_api_interfaces::Document,
+ enumerable,
+ receiver
+);
+
#[derive(WebApiFunctionTemplate)]
#[webapi(name = "ChildNode", enumerable)]
struct ChildNodePrototypeDeclaration {
@@ -1226,7 +1243,9 @@ pub(crate) fn install_node_template_bindings<'s>(
if interface_name == "Node" {
NodePrototypeReflectionDeclaration::initialize_prototype_template(scope, prototype);
}
- if matches!(interface_name, "Document" | "DocumentFragment" | "Element") {
+ if interface_name == "Document" {
+ DocumentParentNodePrototypeDeclaration::initialize_prototype_template(scope, prototype);
+ } else if matches!(interface_name, "DocumentFragment" | "Element") {
ParentNodePrototypeDeclaration::initialize_prototype_template(scope, prototype);
}
if matches!(interface_name, "DocumentType" | "Element" | "CharacterData") {
diff --git a/moli-renderer-v8/src/script_vm/tests/webidl_receivers.rs b/moli-renderer-v8/src/script_vm/tests/webidl_receivers.rs
index 0a20819f4..90009b7c5 100644
--- a/moli-renderer-v8/src/script_vm/tests/webidl_receivers.rs
+++ b/moli-renderer-v8/src/script_vm/tests/webidl_receivers.rs
@@ -1,5 +1,6 @@
use super::*;
+mod document;
mod dom;
#[test]
diff --git a/moli-renderer-v8/src/script_vm/tests/webidl_receivers/document.rs b/moli-renderer-v8/src/script_vm/tests/webidl_receivers/document.rs
new file mode 100644
index 000000000..e7c084ef5
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/webidl_receivers/document.rs
@@ -0,0 +1,27 @@
+use super::*;
+
+#[test]
+fn document_members_validate_receivers_before_conversion_in_the_callee_realm() {
+ run_document_member_probe("documentMemberReceiverProbe");
+}
+
+#[test]
+fn document_members_preserve_genuine_receivers_and_collection_contents() {
+ run_document_member_probe("documentGenuineReceiverProbe");
+}
+
+fn run_document_member_probe(probe: &str) {
+ let mut vm = new_parsed_test_vm(
+ "https://document-member-receivers.test/",
+ "<!doctype html><body><iframe id='document-member-child'></iframe></body>",
+ );
+ materialize_single_child_default_realm_for_test(&mut vm, "Document member receiver realm");
+ let fixture = include_str!("../../../../tests/fixtures/document-member-receivers.js");
+ vm.eval(&format!(
+ "{fixture}\n{probe}().then(result => {{ globalThis.documentMemberResult = result; }}, error => {{ globalThis.documentMemberResult = String(error.stack || error); }});"
+ )).expect("Document member receiver probe should run");
+ assert_eq!(
+ vm.eval("JSON.stringify(documentMemberResult)").unwrap(),
+ "[]"
+ );
+}
diff --git a/moli-renderer-v8/tests/fixtures/document-member-receivers.js b/moli-renderer-v8/tests/fixtures/document-member-receivers.js
new file mode 100644
index 000000000..718e7726f
--- /dev/null
+++ b/moli-renderer-v8/tests/fixtures/document-member-receivers.js
@@ -0,0 +1,158 @@
+async function documentMemberReceiverProbe() {
+ const failures = [];
+ const child = document.getElementById('document-member-child').contentWindow;
+ let traps = 0;
+ let conversions = 0;
+ const poison = new Proxy({}, {
+ get() { conversions++; throw new Error('argument conversion'); }
+ });
+ const revoked = Proxy.revocable(document, {});
+ revoked.revoke();
+ const invalid = [
+ undefined, null, false, 1, 'document', Symbol('document'), 1n, {}, window,
+ Document.prototype, HTMLDocument.prototype, XMLDocument.prototype,
+ Object.create(Document.prototype), Object.create(document),
+ Object.create(child.document), document.createElement('div'),
+ document.createTextNode('text'), document.createDocumentFragment(),
+ new Proxy(document, {
+ get() { traps++; throw new Error('receiver get trap'); },
+ getPrototypeOf() { traps++; throw new Error('receiver prototype trap'); }
+ }), revoked.proxy, new Proxy(child.document, {})
+ ];
+ const promiseMethods = new Set(['hasStorageAccess', 'requestStorageAccess']);
+ const node = document.createElement('div');
+ const nodeArguments = {
+ importNode: [node, false], adoptNode: [node], moveBefore: [node, null],
+ createNodeIterator: [document], createTreeWalker: [document],
+ createNSResolver: [document], evaluate: ['.', document, null, 0, null]
+ };
+ for (const [realmName, realm] of [['parent', window], ['child', child]]) {
+ // Discover every installed member so newly added Document members cannot
+ // silently escape the same receiver contract. Inherited Node methods have
+ // their own interface contract and are tested separately.
+ for (const C of [realm.Document, realm.HTMLDocument, realm.XMLDocument]) {
+ for (const [name, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(C.prototype))) {
+ if (name === 'constructor') continue;
+ for (const kind of ['get', 'set', 'value']) {
+ const fn = descriptor[kind];
+ if (typeof fn !== 'function') continue;
+ const label = `${realmName}/${C.name}.${name}/${kind}`;
+ const lenient = name === 'onmouseenter' || name === 'onmouseleave';
+ const argumentLists = kind === 'get' ? [[]] : kind === 'set' ? [[poison]] :
+ [[], Array(5).fill(poison), ...(nodeArguments[name] ? [nodeArguments[name]] : [])];
+ const errors = [];
+ for (const args of argumentLists) {
+ for (const [index, receiver] of invalid.entries()) {
+ let result;
+ let caught;
+ try { result = Reflect.apply(fn, receiver, args); }
+ catch (error) { caught = error; }
+ if (promiseMethods.has(name)) {
+ if (caught || !(result instanceof realm.Promise)) {
+ errors.push([index, caught ? `threw ${caught.name}` : 'not a callee Promise']);
+ continue;
+ }
+ try { await result; } catch (error) { caught = error; }
+ }
+ if (lenient) {
+ if (caught || result !== undefined) errors.push([index, caught ? caught.name : 'returned a value']);
+ } else if (!caught || Object.getPrototypeOf(caught) !== realm.TypeError.prototype) {
+ errors.push([index, caught ? caught.name : 'accepted']);
+ }
+ }
+ }
+ if (errors.length) failures.push([label, errors]);
+ }
+ }
+ }
+ }
+ if (traps) failures.push(['receiver traps', traps]);
+ if (conversions) failures.push(['argument conversions', conversions]);
+ return failures;
+}
+
+async function documentGenuineReceiverProbe() {
+ const failures = [];
+ const check = (label, condition) => { if (!condition) failures.push(label); };
+ const child = document.getElementById('document-member-child').contentWindow;
+ const collections = ['forms', 'images', 'scripts', 'links', 'anchors', 'embeds', 'plugins', 'applets'];
+ const html = '<form id="form" name="named"></form><img id="image">' +
+ '<script id="script" type="text/plain"></script><a id="link" name="anchor" href="#"></a>' +
+ '<embed id="embed"><div id="target" class="target" name="named"></div>';
+ for (const [realmName, realm] of [['parent', window], ['child', child]]) {
+ const proto = realm.Document.prototype;
+ const get = (name, doc) => Object.getOwnPropertyDescriptor(proto, name).get.call(doc);
+ for (const owner of [window, child]) {
+ const doc = owner.document.implementation.createHTMLDocument('collections');
+ doc.body.innerHTML = html;
+ const expectedIds = ['form', 'image', 'script', 'link', 'link', 'embed', 'embed', ''];
+ const form = doc.getElementById('form');
+ const target = doc.getElementById('target');
+ const root = doc.documentElement;
+ Object.setPrototypeOf(doc, null);
+ for (const [index, name] of collections.entries()) {
+ const collection = get(name, doc);
+ check(`${realmName}/${name}/contents`, Array.from(collection, node => node.id).join() === expectedIds[index]);
+ check(`${realmName}/${name}/length`, collection.length === (name === 'applets' ? 0 : 1));
+ }
+ form.remove();
+ check(`${realmName}/forms/removed`, get('forms', doc).length === 0);
+ for (const [name, args, expectedNode] of [
+ ['getElementById', ['target'], target], ['querySelector', ['.target'], target],
+ ['getElementsByTagName', ['div'], target],
+ ['getElementsByTagNameNS', ['http://www.w3.org/1999/xhtml', 'div'], target],
+ ['getElementsByClassName', ['target'], target], ['getElementsByName', ['named'], target],
+ ['querySelectorAll', ['.target'], target]
+ ]) {
+ const result = Reflect.apply(proto[name], doc, args);
+ check(`${realmName}/${name}/native`, (result[0] || result) === expectedNode);
+ }
+ check(`${realmName}/children/native`, get('children', doc)[0] === root);
+ check(`${realmName}/firstElementChild/native`, get('firstElementChild', doc) === root);
+ check(`${realmName}/lastElementChild/native`, get('lastElementChild', doc) === root);
+ check(`${realmName}/childElementCount/native`, get('childElementCount', doc) === 1);
+ check(`${realmName}/createRange/native`, proto.createRange.call(doc).startContainer === doc);
+ check(`${realmName}/createEvent/native`, proto.createEvent.call(doc, 'Event').type === '');
+ check(`${realmName}/createElement/native`, proto.createElement.call(doc, 'section').ownerDocument === doc);
+ check(`${realmName}/createTextNode/native`, proto.createTextNode.call(doc, 'text').ownerDocument === doc);
+ check(`${realmName}/createDocumentFragment/native`, proto.createDocumentFragment.call(doc).ownerDocument === doc);
+ for (const name of ['clear', 'captureEvents', 'releaseEvents']) {
+ check(`${realmName}/${name}/native`, proto[name].call(doc) === undefined);
+ }
+ const design = Object.getOwnPropertyDescriptor(proto, 'designMode');
+ design.set.call(doc, 'on');
+ check(`${realmName}/designMode/native`, design.get.call(doc) === 'on');
+ const fullscreen = Object.getOwnPropertyDescriptor(proto, 'fullscreenEnabled');
+ const before = fullscreen.get.call(doc);
+ const poison = new Proxy({}, {get() { throw new Error('lenient setter conversion'); }});
+ check(`${realmName}/fullscreenEnabled/lenient-set`, fullscreen.set.call(doc, poison) === undefined);
+ check(`${realmName}/fullscreenEnabled/unchanged`, fullscreen.get.call(doc) === before);
+ }
+ // HTML and XML documents, subclass instances and a changed prototype all
+ // retain native identity even when ordinary instanceof checks cannot work.
+ const changed = new child.Document();
+ Object.setPrototypeOf(changed, null);
+ for (const doc of [document, child.document, new Document(), new child.Document(),
+ new (class extends Document {})(), changed,
+ new DOMParser().parseFromString('<root/>', 'application/xml')]) {
+ for (const name of collections) {
+ try { get(name, doc); } catch (error) { failures.push(`${realmName}/${name}/genuine: ${error.name}`); }
+ }
+ check(`${realmName}/factory/genuine`, proto.createComment.call(doc, 'comment').ownerDocument === doc);
+ }
+ for (const doc of [document, child.document]) {
+ const forms = get('forms', doc);
+ const length = forms.length;
+ const form = doc.body.appendChild(doc.createElement('form'));
+ check(`${realmName}/forms/live-insert`, forms.length === length + 1);
+ form.remove();
+ check(`${realmName}/forms/live-remove`, forms.length === length);
+ for (const name of ['hasStorageAccess', 'requestStorageAccess']) {
+ const promise = proto[name].call(doc);
+ check(`${realmName}/${name}/Promise-realm`, promise instanceof realm.Promise);
+ try { await promise; } catch (error) { failures.push(`${realmName}/${name}/genuine: ${error.name}`); }
+ }
+ }
+ }
+ return failures;
+}