diff --git a/moli-dom/src/native/document.rs b/moli-dom/src/native/document.rs index c72fa94cfe4..94cc237bb4e 100644 --- a/moli-dom/src/native/document.rs +++ b/moli-dom/src/native/document.rs @@ -72,6 +72,8 @@ struct DocumentMetadata { kind: DocumentKind, interface: DocumentInterface, design_mode_enabled: bool, + // Portable parser policy; inert/template documents keep scripting disabled. + scripting_enabled: bool, default_language: Option>, source_last_modified_ms: Option, base_url_state: DocumentBaseUrlState, @@ -97,14 +99,18 @@ impl Document { } pub fn new_html(url: Url) -> Self { - Self::new_with_kind(url, DocumentKind::Html) + Self::new_html_with_scripting(url, true) + } + + pub fn new_html_with_scripting(url: Url, scripting_enabled: bool) -> Self { + Self::new_with_kind(url, DocumentKind::Html, scripting_enabled) } pub fn new_xml(url: Url) -> Self { - Self::new_with_kind(url, DocumentKind::Xml) + Self::new_with_kind(url, DocumentKind::Xml, true) } - fn new_with_kind(url: Url, kind: DocumentKind) -> Self { + fn new_with_kind(url: Url, kind: DocumentKind, scripting_enabled: bool) -> Self { let (content_type, interface) = match kind { DocumentKind::Html => ("text/html", DocumentInterface::Html), DocumentKind::Xml => ("application/xml", DocumentInterface::Xml), @@ -120,6 +126,7 @@ impl Document { kind, interface, design_mode_enabled: false, + scripting_enabled, default_language: None, source_last_modified_ms: None, meta_referrer_policy: None, @@ -130,7 +137,7 @@ impl Document { pub(super) fn new_inert_template(kind: DocumentKind) -> Self { let url = Url::parse("about:blank").expect("about:blank is valid"); - let mut document = Self::new_with_kind(url, kind); + let mut document = Self::new_with_kind(url, kind, false); document.metadata.interface = DocumentInterface::Document; document.arena_state.is_inert_template_document = true; document @@ -258,6 +265,10 @@ impl Document { self.metadata.design_mode_enabled } + pub fn scripting_enabled(&self) -> bool { + self.metadata.scripting_enabled + } + pub fn fallback_base_url(&self) -> &Url { self.metadata.base_url_state.fallback_base_url() } @@ -297,6 +308,10 @@ impl Document { self.metadata.design_mode_enabled = design_mode_enabled; } + pub fn set_scripting_enabled(&mut self, scripting_enabled: bool) { + self.metadata.scripting_enabled = scripting_enabled; + } + pub fn set_css_target(&mut self, target: Option) -> bool { if self.arena_state.css_target == target { return false; diff --git a/moli-dom/src/native/host/document.rs b/moli-dom/src/native/host/document.rs index d3cae04e942..143277f67ca 100644 --- a/moli-dom/src/native/host/document.rs +++ b/moli-dom/src/native/host/document.rs @@ -22,8 +22,19 @@ impl DomHost { } pub fn create_detached_html_document_with_url(&mut self, url: Url) -> DomHandle { + self.create_detached_html_document_with_url_and_scripting(url, true) + } + + pub fn create_detached_html_document_with_url_and_scripting( + &mut self, + url: Url, + scripting_enabled: bool, + ) -> DomHandle { self.dom.create_node( - NodeData::Document(Box::new(Document::new_html(url))), + NodeData::Document(Box::new(Document::new_html_with_scripting( + url, + scripting_enabled, + ))), None, false, false, @@ -1075,6 +1086,15 @@ impl DomHost { true } + pub fn document_scripting_enabled_for_handle( + &self, + document_handle: DomHandle, + ) -> Option { + self.node(document_handle) + .and_then(Node::as_document) + .map(Document::scripting_enabled) + } + pub fn document_base_url(&self) -> Option { self.document_base_url_for_handle(self.document_handle()) } @@ -1266,6 +1286,25 @@ impl DomHost { true } + pub fn set_document_scripting_enabled_for_handle( + &mut self, + document_handle: DomHandle, + scripting_enabled: bool, + ) -> bool { + let Some(document) = self + .node_mut(document_handle) + .and_then(|node| node.data_mut().as_document_mut()) + else { + return false; + }; + if document.scripting_enabled() == scripting_enabled { + return false; + } + document.set_scripting_enabled(scripting_enabled); + self.record_mutation(MutationScope::LocalState); + true + } + pub fn set_document_quirks_mode_for_handle( &mut self, document_handle: DomHandle, diff --git a/moli-dom/src/native/html_serialization/engine.rs b/moli-dom/src/native/html_serialization/engine.rs index 519aea2b4ae..8818a396475 100644 --- a/moli-dom/src/native/html_serialization/engine.rs +++ b/moli-dom/src/native/html_serialization/engine.rs @@ -995,6 +995,24 @@ pub(super) fn serialize_html( .then_some(html) } +pub(super) fn serialize_html_with_stored_scripting_state( + dom: &NativeDom, + node_id: NativeNodeId, + target: HtmlSerializationTarget, +) -> Option { + let scripting_enabled_for_node = + |node| dom.node_document_scripting_enabled(node).unwrap_or(false); + let mut html = String::new(); + serialize_html_into_sink( + dom, + node_id, + HtmlSerializationOptions::new(target, &scripting_enabled_for_node), + &mut html, + ) + .expect("standard node serialization cannot enter embedded documents") + .then_some(html) +} + pub(in crate::native) fn serialize_html_with_options<'a>( dom: &'a NativeDom, node_id: NativeNodeId, @@ -1026,7 +1044,8 @@ pub(super) fn serialize_html_with_limit( node_id: NativeNodeId, max_bytes: usize, ) -> Result, HtmlSerializationLimitExceeded> { - let scripting_enabled_for_node = |_: NativeNodeId| true; + let scripting_enabled_for_node = + |node| dom.node_document_scripting_enabled(node).unwrap_or(false); let mut out = BoundedHtmlSerialization::new(max_bytes); if !serialize_html_into_sink( dom, diff --git a/moli-dom/src/native/html_serialization/mod.rs b/moli-dom/src/native/html_serialization/mod.rs index cccfc5033a1..709a1be0e3a 100644 --- a/moli-dom/src/native/html_serialization/mod.rs +++ b/moli-dom/src/native/html_serialization/mod.rs @@ -12,7 +12,9 @@ pub(super) use engine::{ HtmlSerializationOptions, HtmlSerializationTarget, HtmlSerializedShadowRoot, HtmlShadowRootProvider, serialize_html_with_options, }; -use engine::{serialize_html, serialize_html_with_limit}; +use engine::{ + serialize_html, serialize_html_with_limit, serialize_html_with_stored_scripting_state, +}; use std::borrow::Cow; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -153,7 +155,12 @@ impl NativeDom { } pub fn serialize_document(&self) -> String { - self.serialize_document_with_scripting_enabled(true) + serialize_html_with_stored_scripting_state( + self, + self.document_node_id, + HtmlSerializationTarget::ChildrenOnly, + ) + .unwrap_or_default() } pub fn serialize_document_with_scripting_enabled(&self, scripting_enabled: bool) -> String { @@ -167,7 +174,11 @@ impl NativeDom { } pub fn outer_html(&self, node_id: NativeNodeId) -> Option { - self.outer_html_with_scripting_enabled(node_id, true) + serialize_html_with_stored_scripting_state( + self, + node_id, + HtmlSerializationTarget::IncludeNode, + ) } pub fn outer_html_with_scripting_enabled( @@ -197,7 +208,11 @@ impl NativeDom { } pub fn inner_html(&self, node_id: NativeNodeId) -> Option { - self.inner_html_with_scripting_enabled(node_id, true) + serialize_html_with_stored_scripting_state( + self, + node_id, + HtmlSerializationTarget::ChildrenOnly, + ) } pub fn inner_html_with_scripting_enabled( diff --git a/moli-dom/src/native/mod.rs b/moli-dom/src/native/mod.rs index b447f2db819..9d6c21a3692 100644 --- a/moli-dom/src/native/mod.rs +++ b/moli-dom/src/native/mod.rs @@ -188,13 +188,20 @@ impl NativeDom { } pub fn new_html(final_url: url::Url) -> Self { + Self::new_html_with_scripting(final_url, true) + } + + pub fn new_html_with_scripting(final_url: url::Url, scripting_enabled: bool) -> Self { let document_node_id = NativeNodeId::new(0); let document_node = Node::new( document_node_id, None, None, NodeFlags::new(true), - NodeData::Document(Box::new(Document::new_html(final_url))), + NodeData::Document(Box::new(Document::new_html_with_scripting( + final_url, + scripting_enabled, + ))), ); Self { nodes: NativeNodeStorage::from_node(document_node), @@ -2864,6 +2871,12 @@ mod tests { .and_then(Node::owner_document) .expect("template content owner document"); assert_ne!(content_owner, dom.document_node_id()); + assert_eq!( + dom.node(content_owner) + .and_then(Node::as_document) + .map(Document::scripting_enabled), + Some(false) + ); let child = dom.create_element("span"); assert_eq!( diff --git a/moli-dom/src/native/queries.rs b/moli-dom/src/native/queries.rs index 50394673218..f38b09f8453 100644 --- a/moli-dom/src/native/queries.rs +++ b/moli-dom/src/native/queries.rs @@ -326,6 +326,17 @@ impl NativeDom { }) } + pub fn node_document_scripting_enabled(&self, node_id: NativeNodeId) -> Option { + let node = self.node(node_id)?; + if let Some(document) = node.as_document() { + return Some(document.scripting_enabled()); + } + let owner_document = node.owner_document()?; + self.node(owner_document) + .and_then(Node::as_document) + .map(|document| document.scripting_enabled()) + } + fn collect_matching_elements( &self, root: NativeNodeId, diff --git a/moli-parser/src/html.rs b/moli-parser/src/html.rs index 69dad6a70da..dcd553c472c 100644 --- a/moli-parser/src/html.rs +++ b/moli-parser/src/html.rs @@ -444,7 +444,13 @@ impl HtmlParser { } pub fn parse_dom_host(&self, final_url: Url, html: String) -> DomHost { - let stream = self.start_document(final_url); + let target = + ParserStreamHtmlTreeSinkTarget::new_with_declarative_shadow_roots_and_scripting( + final_url, + true, + self.scripting_enabled, + ); + let stream = HtmlTreeSinkStream::from_target_with_scripting(target, self.scripting_enabled); for chunk in html_chunks(&html) { stream.feed(chunk); } @@ -457,7 +463,11 @@ impl HtmlParser { html: String, ) -> NativeDom { let target = - ParserStreamHtmlTreeSinkTarget::new_with_declarative_shadow_roots(final_url, false); + ParserStreamHtmlTreeSinkTarget::new_with_declarative_shadow_roots_and_scripting( + final_url, + false, + self.scripting_enabled, + ); let stream = HtmlTreeSinkStream::from_target_with_scripting(target, self.scripting_enabled); for chunk in html_chunks(&html) { stream.feed(chunk); @@ -472,8 +482,10 @@ impl HtmlParser { /// Start a text document using the HTML tokenizer's plaintext state. /// Subsequent chunks remain literal text inside the browser-owned `pre`. pub fn start_text_document(&self, final_url: Url, content_type: &str) -> DocumentStream { - let stream = - DocumentStream::new_text_document(new_parser_stream_html_tree_sink_target(final_url)); + let stream = DocumentStream::new_text_document(new_parser_stream_html_tree_sink_target( + final_url, + self.scripting_enabled, + )); stream.inner.initialize_text_document(); let mut host = stream.inner.take_parser_stream_dom_host(); let document_handle = host.document_handle(); @@ -544,10 +556,12 @@ impl HtmlParser { allow_declarative_shadow_roots: bool, scripting_enabled: bool, ) -> NativeDom { - let target = ParserStreamHtmlTreeSinkTarget::new_with_declarative_shadow_roots( - final_url, - allow_declarative_shadow_roots, - ); + let target = + ParserStreamHtmlTreeSinkTarget::new_with_declarative_shadow_roots_and_scripting( + final_url, + allow_declarative_shadow_roots, + scripting_enabled, + ); let context = HtmlFragmentContext::new(None, context_namespace, context_local_name); let sink = DocumentSink::new(target); let parser = HtmlParserSession::new_fragment( @@ -2267,6 +2281,25 @@ mod tests { ); } + #[test] + fn standalone_html_parser_preserves_the_requested_scripting_mode() { + let document = HtmlParser::SCRIPTING_DISABLED.parse_without_declarative_shadow_roots( + Url::parse("https://example.test/").expect("test url"), + "".to_owned(), + ); + assert_eq!( + document + .document() + .map(|document| document.scripting_enabled()), + Some(false) + ); + let noscript = first_element_by_ns(&document, HTML_NS, "noscript"); + assert_eq!( + document.inner_html(noscript).as_deref(), + Some("& <>") + ); + } + #[test] fn mathml_annotation_xml_text_html_is_html_integration_point() { let document = parse_test_document(concat!( diff --git a/moli-parser/src/live_target.rs b/moli-parser/src/live_target.rs index cf40aaf1c45..38eb7bf9786 100644 --- a/moli-parser/src/live_target.rs +++ b/moli-parser/src/live_target.rs @@ -2156,15 +2156,15 @@ impl ParserStreamHtmlTreeSinkTarget { Some(move || sink.finish()) } - fn new(final_url: Url) -> Self { - Self::new_with_declarative_shadow_roots(final_url, true) - } - - pub(super) fn new_with_declarative_shadow_roots( + pub(super) fn new_with_declarative_shadow_roots_and_scripting( final_url: Url, allow_declarative_shadow_roots: bool, + scripting_enabled: bool, ) -> Self { - let dom_host = DomHost::from_dom(NativeDom::new(final_url.clone())); + let dom_host = DomHost::from_dom(NativeDom::new_html_with_scripting( + final_url.clone(), + scripting_enabled, + )); let document_handle = dom_host.document_handle(); Self { owned_dom_host: Some(dom_host), @@ -3744,8 +3744,13 @@ impl ParserStreamHtmlTreeSinkTarget { pub(super) fn new_parser_stream_html_tree_sink_target( final_url: Url, + scripting_enabled: bool, ) -> ParserStreamHtmlTreeSinkTarget { - ParserStreamHtmlTreeSinkTarget::new(final_url) + ParserStreamHtmlTreeSinkTarget::new_with_declarative_shadow_roots_and_scripting( + final_url, + true, + scripting_enabled, + ) } pub(super) fn new_parser_stream_html_tree_sink_stream( @@ -3753,7 +3758,7 @@ pub(super) fn new_parser_stream_html_tree_sink_stream( scripting_enabled: bool, ) -> HtmlTreeSinkStream { HtmlTreeSinkStream::from_target_with_scripting( - new_parser_stream_html_tree_sink_target(final_url), + new_parser_stream_html_tree_sink_target(final_url, scripting_enabled), scripting_enabled, ) } @@ -4514,6 +4519,54 @@ fn parser_stream_live_fragment_root_writes_fragment() { ); } +#[test] +fn live_fragment_parser_preserves_noscript_when_scripting_is_disabled() { + let url = Url::parse("https://example.test/").expect("test url"); + let mut dom_host = DomHost::from_dom(NativeDom::new_html_with_scripting(url.clone(), false)); + let document = dom_host.document_handle(); + let html = dom_host.create_element("html"); + let body = dom_host.create_element("body"); + assert!(dom_host.append_child(document, html)); + assert!(dom_host.append_child(html, body)); + let existing_noscript = dom_host.create_element("noscript"); + let existing_text = dom_host.create_text_node("existing&"); + assert!(dom_host.append_child(existing_noscript, existing_text)); + assert!(dom_host.append_child(body, existing_noscript)); + let fragment = dom_host.create_document_fragment_for_document(document); + let ptr = &mut dom_host as *mut DomHost; + let mut effects = DomMutationEffects::default(); + + { + let mut collector = TestMutationEffectCollector { + host: ptr, + effects: &mut effects, + panic_on_mutation: false, + finish_texts: None, + }; + crate::HtmlParser::with_scripting_enabled(false).parse_fragment_into_live_dom( + url, + fragment, + document, + HtmlFragmentContext::new(Some(body), "http://www.w3.org/1999/xhtml", "body"), + "tail", + &mut collector, + false, + ); + } + + assert_eq!( + dom_host + .elements_by_tag_name(fragment, "noscript", false) + .len(), + 1, + "a scripting-disabled live fragment must preserve its noscript root" + ); + assert_eq!( + dom_host.elements_by_tag_name(fragment, "span", false).len(), + 1 + ); +} + #[test] fn live_fragment_parser_uses_template_contents_owner_document() { let url = Url::parse("https://example.test/").expect("test url"); diff --git a/moli-renderer-v8/src/document_runtime/dom_facade.rs b/moli-renderer-v8/src/document_runtime/dom_facade.rs index 35afdf03a33..22f53b697c9 100644 --- a/moli-renderer-v8/src/document_runtime/dom_facade.rs +++ b/moli-renderer-v8/src/document_runtime/dom_facade.rs @@ -549,8 +549,13 @@ impl DocumentRuntime { self.dom_host.create_detached_xml_document() } - pub(crate) fn create_detached_html_document_with_url(&mut self, url: url::Url) -> DomHandle { - self.dom_host.create_detached_html_document_with_url(url) + pub(crate) fn create_detached_html_document_with_url_and_scripting( + &mut self, + url: url::Url, + scripting_enabled: bool, + ) -> DomHandle { + self.dom_host + .create_detached_html_document_with_url_and_scripting(url, scripting_enabled) } pub(crate) fn create_detached_xml_document_with_url(&mut self, url: url::Url) -> DomHandle { diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs index 5e5c56a12da..b475c95901a 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs @@ -822,6 +822,10 @@ impl PageScriptHost { } self.child_browsing_context_host_for_document_handle(document_handle) .map(|handle| self.child_browsing_context_scripting_enabled(handle)) + .or_else(|| { + self.dom_host() + .document_scripting_enabled_for_handle(document_handle) + }) // DOMParser and document.implementation documents have no browsing // context, so scripting is disabled for their fragment parsers too. .unwrap_or(false) diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs index 2daebfc9af5..afaf1d9a564 100644 --- a/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs +++ b/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs @@ -58,16 +58,20 @@ fn create_native_detached_document_handle_with_url( scope: &mut v8::PinScope<'_, '_>, kind: &str, url: Url, + scripting_enabled: bool, ) -> Option { let runtime_ptr = context_host_ptr_from_global_bridge(scope)?; let runtime = unsafe { &mut *runtime_ptr }; let source = runtime.current_realm_document_execution_context(scope); let handle = if kind == "html" { - runtime.create_detached_html_document_with_url(url) + runtime.create_detached_html_document_with_url_and_scripting(url, scripting_enabled) } else { runtime.create_detached_xml_document_with_url(url) }; runtime.set_inert_document_execution_context(handle, source); + let _ = runtime + .dom_host_mut() + .set_document_scripting_enabled_for_handle(handle, scripting_enabled); Some(handle) } @@ -84,6 +88,7 @@ fn new_detached_document_shell<'s>( kind: &str, content_type: &str, url: Url, + scripting_enabled: bool, ) -> Option> { let to_string_tag = if kind == "html" { Some("HTMLDocument") @@ -105,7 +110,8 @@ fn new_detached_document_shell<'s>( v8_string(scope, "complete")?.into(), ); define_detached_state(scope, document, state); - let handle = create_native_detached_document_handle_with_url(scope, kind, url)?; + let handle = + create_native_detached_document_handle_with_url(scope, kind, url, scripting_enabled)?; define_detached_native_handle(scope, document, handle); set_detached_document_content_type(scope, document, content_type)?; install_detached_document_instance_properties(scope, document, kind); @@ -189,6 +195,7 @@ pub(crate) fn build_detached_document_object_from_dom_host_with_content_type<'s> ) -> Option> { let url = detached_document_url(&parsed); let quirks_mode = parsed.dom().document()?.quirks_mode(); + let scripting_enabled = parsed.dom().document()?.scripting_enabled(); let compat_mode = if quirks_mode == selectors::matching::QuirksMode::Quirks { "BackCompat" } else { @@ -196,7 +203,7 @@ pub(crate) fn build_detached_document_object_from_dom_host_with_content_type<'s> }; let content_type = content_type.unwrap_or(parsed.dom().document()?.content_type()); let character_set = character_set.unwrap_or(parsed.dom().document()?.character_set()); - let document = new_detached_document_shell(scope, kind, content_type, url)?; + let document = new_detached_document_shell(scope, kind, content_type, url, scripting_enabled)?; if let Some(state) = detached_state_object(scope, document) { let _ = state.set( scope, @@ -306,6 +313,7 @@ pub(in crate::native_bridge::document) fn build_detached_html_document_object<'s "html", "text/html", Url::parse("about:blank").expect("static about:blank parses"), + false, )?; populate_native_html_document_shell(scope, document, title)?; Some(document) @@ -331,6 +339,7 @@ pub(in crate::native_bridge::document) fn build_detached_document_object<'s>( kind, content_type, Url::parse("about:blank").expect("static about:blank parses"), + false, )?; if let Some(doctype) = doctype { let doctype = if detached_is_node(scope, doctype) { diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/detached_document_and_element_surfaces.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/detached_document_and_element_surfaces.rs index 6e660624acb..36fd248e2d0 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/detached_document_and_element_surfaces.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/detached_document_and_element_surfaces.rs @@ -1775,3 +1775,55 @@ fn domparser_xml_preserves_requested_content_type_for_success_and_error_document r#"[["text/xml","text/xml","html"],["application/xml","application/xml","html"],["application/xhtml+xml","application/xhtml+xml","html"],["image/svg+xml","image/svg+xml","html"]]"# ); } + +#[test] +fn offline_html_documents_parse_and_serialize_noscript_with_scripting_disabled() { + let mut vm = new_storage_test_vm("https://offline-noscript.test/"); + + let result = vm + .eval( + r#" +(() => { + const encoded = '& <>'; + const decoded = '&\u00a0<>'; + const markup = value => ``; + const matches = (node, serialization) => + node.textContent === decoded && node.innerHTML === serialization; + + const live = document.createElement('div'); + live.innerHTML = markup(decoded); + + const parsed = new DOMParser().parseFromString( + `${markup(encoded)}`, + 'text/html' + ); + + const template = document.createElement('template'); + template.innerHTML = markup(encoded); + + const created = document.implementation.createHTMLDocument(''); + created.body.innerHTML = `
${markup(encoded)}
`; + + const contextualDocument = document.implementation.createHTMLDocument(''); + const range = contextualDocument.createRange(); + range.selectNode(contextualDocument.body); + const contextual = range.createContextualFragment(markup(encoded)); + + const written = document.implementation.createHTMLDocument(''); + written.write(`
${markup(decoded)}
`); + + return [ + matches(live.firstChild, decoded), + matches(parsed.body.firstChild, encoded), + matches(template.content.firstChild, encoded), + matches(created.body.firstChild.firstChild, encoded), + matches(contextual.firstChild, encoded), + matches(written.body.firstChild.firstChild, encoded) + ].join('|'); +})() +"#, + ) + .expect("offline noscript parsing and serialization probe should evaluate"); + + assert_eq!(result, "true|true|true|true|true|true"); +}