Skip to content

Truly independent web browser

LibWeb: Implement Sanitizer and its configuration in Rust

Shannon Boothd6f98a559a93
diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/element.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/element.rs
index 9e1d01f4c10..64a511e25c5 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/dom/element.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/element.rs
@@ -12,6 +12,7 @@ use libjs_rust::api::Trace;
use crate::bindings::cpp_cell::CppCell;
unsafe extern "C" {
+ fn web_dom_is_valid_attribute_local_name(name: usize) -> bool;
fn web_dom_element_attribute(
element: *mut c_void,
name: ak::Span<'_, u8>,
@@ -54,3 +55,9 @@ impl CppElement {
value
}
}
+
+// https://dom.spec.whatwg.org/#valid-attribute-local-name
+pub(crate) fn is_valid_attribute_local_name(name: &Utf16String) -> bool {
+ // SAFETY: The name is live for the call.
+ unsafe { web_dom_is_valid_attribute_local_name(name.raw_identity()) }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
index 10768cd5822..e40095d3d56 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
@@ -83,6 +83,10 @@ pub(crate) mod path2d;
#[cfg(not(test))]
pub(crate) mod port_channel;
#[cfg(not(test))]
+pub(crate) mod sanitizer;
+#[cfg(not(test))]
+pub(crate) mod sanitizer_configuration;
+#[cfg(not(test))]
pub(crate) mod storage;
#[cfg(not(test))]
pub(crate) mod storage_event;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/sanitizer.rs b/Libraries/LibWeb/Bindings/Rust/src/html/sanitizer.rs
new file mode 100644
index 00000000000..4c8e7a3a9cf
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/sanitizer.rs
@@ -0,0 +1,802 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use core::cell::RefCell;
+use core::ffi::c_void;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Utf16View, Vm};
+
+use super::sanitizer_configuration::{
+ PermissiveDefaults, SanitizerConfiguration, SanitizerName, built_in_non_replaceable_elements_list_contains,
+ built_in_safe_default_configuration, canonicalize_sanitizer_attribute, canonicalize_sanitizer_config,
+ canonicalize_sanitizer_element, canonicalize_sanitizer_element_with_attributes,
+ canonicalize_sanitizer_processing_instruction, configure_sanitizer_configuration, is_custom_data_attribute,
+ remove_an_attribute_from_sanitizer_config, remove_an_element_from_sanitizer_config,
+ remove_unsafe_from_sanitizer_config, sanitizer_configuration_is_valid, sanitizer_configuration_to_bindings,
+ sanitizer_list_contains, sanitizer_list_remove,
+};
+use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi};
+use crate::bindings::{CallContext, WebIdlResult};
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum SanitizerPresets {
+ Default,
+}
+
+#[derive(Clone)]
+pub(crate) struct SanitizerElementNamespace {
+ pub(crate) name: Utf16String,
+ pub(crate) namespace: Option<Utf16String>,
+}
+
+#[derive(Clone)]
+pub(crate) struct SanitizerElementNamespaceWithAttributes {
+ pub(crate) parent: SanitizerElementNamespace,
+ pub(crate) attributes: Option<Vec<SanitizerAttribute>>,
+ pub(crate) remove_attributes: Option<Vec<SanitizerAttribute>>,
+}
+
+#[derive(Clone)]
+pub(crate) struct SanitizerAttributeNamespace {
+ pub(crate) name: Utf16String,
+ pub(crate) namespace: Option<Utf16String>,
+}
+
+#[derive(Clone)]
+pub(crate) struct SanitizerProcessingInstruction {
+ pub(crate) target: Utf16String,
+}
+
+#[derive(Clone)]
+pub(crate) enum SanitizerElement {
+ DOMString(Utf16String),
+ SanitizerElementNamespace(SanitizerElementNamespace),
+}
+
+#[derive(Clone)]
+pub(crate) enum SanitizerElementWithAttributes {
+ DOMString(Utf16String),
+ SanitizerElementNamespaceWithAttributes(SanitizerElementNamespaceWithAttributes),
+}
+
+#[derive(Clone)]
+pub(crate) enum SanitizerAttribute {
+ DOMString(Utf16String),
+ SanitizerAttributeNamespace(SanitizerAttributeNamespace),
+}
+
+#[derive(Clone)]
+pub(crate) enum SanitizerPI {
+ DOMString(Utf16String),
+ SanitizerProcessingInstruction(SanitizerProcessingInstruction),
+}
+
+#[derive(Clone, Default)]
+pub(crate) struct SanitizerConfig {
+ pub(crate) elements: Option<Vec<SanitizerElementWithAttributes>>,
+ pub(crate) remove_elements: Option<Vec<SanitizerElement>>,
+ pub(crate) replace_with_children_elements: Option<Vec<SanitizerElement>>,
+ pub(crate) processing_instructions: Option<Vec<SanitizerPI>>,
+ pub(crate) remove_processing_instructions: Option<Vec<SanitizerPI>>,
+ pub(crate) attributes: Option<Vec<SanitizerAttribute>>,
+ pub(crate) remove_attributes: Option<Vec<SanitizerAttribute>>,
+ pub(crate) comments: Option<bool>,
+ pub(crate) data_attributes: Option<bool>,
+ pub(crate) javascript_ur_ls: Option<bool>,
+}
+
+pub(crate) enum SanitizerConfigOrSanitizerPresets {
+ SanitizerConfig(SanitizerConfig),
+ SanitizerPresets(SanitizerPresets),
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sanitizer
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Sanitizer {
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sanitizer-configuration
+ #[gc(untraced)]
+ configuration: RefCell<SanitizerConfiguration>,
+}
+
+impl Wrappable for Sanitizer {}
+
+impl Sanitizer {
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-constructor
+ pub(crate) fn construct(
+ _: &mut CallContext,
+ configuration: SanitizerConfigOrSanitizerPresets,
+ ) -> WebIdlResult<Self> {
+ // 1. If configuration is a SanitizerPresets string:
+ // 1. Assert: configuration is "default".
+ // 2. Set configuration to the built-in safe default configuration.
+ let fresh_configuration = match configuration {
+ SanitizerConfigOrSanitizerPresets::SanitizerConfig(config) => canonicalize_sanitizer_config(&config),
+ SanitizerConfigOrSanitizerPresets::SanitizerPresets(preset) => {
+ assert!(preset == SanitizerPresets::Default);
+ built_in_safe_default_configuration().clone()
+ }
+ };
+
+ // 2. Configure this given configuration and true.
+ let canonical_configuration = configure_sanitizer_configuration(fresh_configuration, PermissiveDefaults::Yes)?;
+ Ok(Self::new(canonical_configuration))
+ }
+
+ fn new(configuration: SanitizerConfiguration) -> Self {
+ assert!(sanitizer_configuration_is_valid(&configuration));
+ Self {
+ configuration: RefCell::new(configuration),
+ }
+ }
+
+ pub(crate) fn create_with_configuration(vm: &Vm, configuration: SanitizerConfiguration) -> Ref<Self> {
+ allocate(vm, |_| Self::new(configuration))
+ }
+
+ pub(crate) fn configuration(&self) -> SanitizerConfiguration {
+ self.configuration.borrow().clone()
+ }
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#compare-sanitizer-items
+fn compare_sanitizer_items(item_a: &SanitizerName, item_b: &SanitizerName) -> bool {
+ // 1. Let namespaceA be itemA["namespace"].
+ let namespace_a = &item_a.namespace_;
+
+ // 2. Let namespaceB be itemB["namespace"].
+ let namespace_b = &item_b.namespace_;
+
+ // 3. If namespaceA is null:
+ if namespace_a.is_none() {
+ // 1. If namespaceB is not null, then return true.
+ if namespace_b.is_some() {
+ return true;
+ }
+ }
+ // 4. Otherwise:
+ else {
+ // 1. If namespaceB is null, then return false.
+ let Some(namespace_b) = namespace_b else {
+ return false;
+ };
+ let namespace_a = namespace_a.as_ref().unwrap();
+
+ // 2. If namespaceA is code unit less than namespaceB, then return true.
+ if Utf16View::of_string(namespace_a)
+ .code_units()
+ .cmp(Utf16View::of_string(namespace_b).code_units())
+ .is_lt()
+ {
+ return true;
+ }
+
+ // 3. If namespaceA is not namespaceB, then return false.
+ if namespace_a != namespace_b {
+ return false;
+ }
+ }
+
+ // 5. If itemA["name"] is code unit less than itemB["name"], then return true.
+ if Utf16View::of_string(&item_a.name)
+ .code_units()
+ .cmp(Utf16View::of_string(&item_b.name).code_units())
+ .is_lt()
+ {
+ return true;
+ }
+
+ // 6. Return false.
+ false
+}
+
+fn sort_sanitizer_items(list: &mut [SanitizerName]) {
+ list.sort_unstable_by(sanitizer_item_order);
+}
+fn sanitizer_item_order(a: &SanitizerName, b: &SanitizerName) -> core::cmp::Ordering {
+ if compare_sanitizer_items(a, b) {
+ core::cmp::Ordering::Less
+ } else if compare_sanitizer_items(b, a) {
+ core::cmp::Ordering::Greater
+ } else {
+ core::cmp::Ordering::Equal
+ }
+}
+fn sort_processing_instructions(list: &mut [Utf16String]) {
+ list.sort_unstable_by(|a, b| {
+ Utf16View::of_string(a)
+ .code_units()
+ .cmp(Utf16View::of_string(b).code_units())
+ });
+}
+
+// https://infra.spec.whatwg.org/#create-a-set
+fn create_a_set(list: &[SanitizerName]) -> Vec<SanitizerName> {
+ let mut set = Vec::new();
+ for item in list {
+ if !set.contains(item) {
+ set.push(item.clone());
+ }
+ }
+ set
+}
+// https://infra.spec.whatwg.org/#set-difference
+fn difference(a: &[SanitizerName], b: &[SanitizerName]) -> Vec<SanitizerName> {
+ let mut result = Vec::new();
+ for item in a {
+ if !b.contains(item) {
+ result.push(item.clone());
+ }
+ }
+ result
+}
+// https://infra.spec.whatwg.org/#set-intersection
+fn intersection(a: &[SanitizerName], b: &[SanitizerName]) -> Vec<SanitizerName> {
+ let mut result = Vec::new();
+ for item in a {
+ if b.contains(item) {
+ result.push(item.clone());
+ }
+ }
+ result
+}
+
+impl Sanitizer {
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-get
+ pub(crate) fn get(&self, _: &mut CallContext) -> WebIdlResult<SanitizerConfig> {
+ // NOTE: Outside of the get() method, the order of the Sanitizer's elements and attributes is unobservable. By
+ // explicitly sorting the result of this method, we give implementations the opportunity to optimize by,
+ // for example, using unordered sets internally.
+ // 1. Let config be this's configuration.
+ let mut config = self.configuration.borrow().clone();
+
+ // 2. Assert: config is valid.
+ assert!(sanitizer_configuration_is_valid(&config));
+
+ // 3. If config["elements"] exists:
+ if let Some(elements) = &mut config.elements {
+ // 1. For each element of config["elements"]:
+ for element in elements.iter_mut() {
+ // 1. If element["attributes"] exists, then set element["attributes"] to the result of sorting
+ // element["attributes"], with compare sanitizer items.
+ if let Some(list) = &mut element.attributes {
+ sort_sanitizer_items(list);
+ }
+
+ // 2. If element["removeAttributes"] exists, then set element["removeAttributes"] to the result of sorting
+ // element["removeAttributes"], with compare sanitizer items.
+ if let Some(list) = &mut element.remove_attributes {
+ sort_sanitizer_items(list);
+ }
+ }
+
+ // 2. Set config["elements"] to the result of sorting config["elements"], with compare sanitizer items.
+ elements.sort_unstable_by(|a, b| sanitizer_item_order(&a.element, &b.element));
+ }
+ // 4. Otherwise:
+ else {
+ // 1. Set config["removeElements"] to the result of sorting config["removeElements"], with compare sanitizer
+ // items.
+ sort_sanitizer_items(config.remove_elements.as_mut().unwrap());
+ }
+
+ // 5. If config["replaceWithChildrenElements"] exists, then set config["replaceWithChildrenElements"] to the result
+ // of sorting config["replaceWithChildrenElements"], with compare sanitizer items.
+ if let Some(list) = &mut config.replace_with_children_elements {
+ sort_sanitizer_items(list);
+ }
+
+ // 6. If config["processingInstructions"] exists, then set config["processingInstructions"] to the result of
+ // sorting config["processingInstructions"], with piA["target"] being code unit less than piB["target"].
+ if let Some(list) = &mut config.processing_instructions {
+ sort_processing_instructions(list);
+ }
+ // 7. Otherwise:
+ else {
+ // 1. Set config["removeProcessingInstructions"] to the result of sorting
+ // config["removeProcessingInstructions"], with piA["target"] being code unit less than piB["target"].
+ sort_processing_instructions(config.remove_processing_instructions.as_mut().unwrap());
+ }
+
+ // 8. If config["attributes"] exists, then set config["attributes"] to the result of sorting config["attributes"]
+ // given compare sanitizer items.
+ if let Some(list) = &mut config.attributes {
+ sort_sanitizer_items(list);
+ }
+ // 9. Otherwise:
+ else {
+ // 1. Set config["removeAttributes"] to the result of sorting config["removeAttributes"] given compare
+ // sanitizer items.
+ sort_sanitizer_items(config.remove_attributes.as_mut().unwrap());
+ }
+
+ // 10. Return config.
+ Ok(sanitizer_configuration_to_bindings(&config))
+ }
+
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-allowelement
+ pub(crate) fn allow_element(
+ &self,
+ _: &mut CallContext,
+ element_input: SanitizerElementWithAttributes,
+ ) -> WebIdlResult<bool> {
+ // 1. Let configuration be this's configuration.
+ let mut configuration = self.configuration.borrow_mut();
+
+ // 2. Assert: configuration is valid.
+ assert!(sanitizer_configuration_is_valid(&configuration));
+
+ // 3. Set element to the result of canonicalizing element.
+ let mut element = canonicalize_sanitizer_element_with_attributes(&element_input);
+
+ // 4. If configuration["elements"] exists:
+ if configuration.elements.is_some() {
+ // 1. Let modified be the result of removing element from configuration["replaceWithChildrenElements"].
+ let modified = sanitizer_list_remove(&mut configuration.replace_with_children_elements, &element.element);
+
+ // 2. If configuration["attributes"] exists:
+ if let Some(attributes) = &configuration.attributes {
+ // 1. If element["attributes"] exists:
+ if let Some(list) = &element.attributes {
+ // 1. Set element["attributes"] to the result of creating a set from element["attributes"].
+ element.attributes = Some(create_a_set(list));
+
+ // 2. Set element["attributes"] to the difference of element["attributes"] and
+ // configuration["attributes"].
+ element.attributes = Some(difference(element.attributes.as_ref().unwrap(), attributes));
+
+ // 3. If configuration["dataAttributes"] is true, then remove all items item from element["attributes"]
+ // where item is a custom data attribute.
+ if configuration.data_attributes == Some(true) {
+ element
+ .attributes
+ .as_mut()
+ .unwrap()
+ .retain(|item| !is_custom_data_attribute(item));
+ }
+ }
+
+ // 2. If element["removeAttributes"] exists:
+ if let Some(list) = &element.remove_attributes {
+ // 1. Set element["removeAttributes"] to the result of creating a set from element["removeAttributes"].
+ element.remove_attributes = Some(create_a_set(list));
+
+ // 2. Set element["removeAttributes"] to the intersection of element["removeAttributes"] and
+ // configuration["attributes"].
+ element.remove_attributes =
+ Some(intersection(element.remove_attributes.as_ref().unwrap(), attributes));
+ }
+ }
+ // 3. Otherwise:
+ else {
+ // 1. If element["attributes"] exists:
+ if let Some(list) = &element.attributes {
+ // 1. Set element["attributes"] to the result of creating a set from element["attributes"].
+ element.attributes = Some(create_a_set(list));
+
+ // 2. Set element["attributes"] to the difference of element["attributes"] and
+ // element["removeAttributes"] with default « ».
+ element.attributes = Some(difference(
+ element.attributes.as_ref().unwrap(),
+ element.remove_attributes.as_deref().unwrap_or(&[]),
+ ));
+
+ // 3. Remove element["removeAttributes"].
+ element.remove_attributes = None;
+
+ // 4. Set element["attributes"] to the difference of element["attributes"] and
+ // configuration["removeAttributes"].
+ element.attributes = Some(difference(
+ element.attributes.as_ref().unwrap(),
+ configuration.remove_attributes.as_ref().unwrap(),
+ ));
+ }
+
+ // 2. If element["removeAttributes"] exists:
+ if let Some(list) = &element.remove_attributes {
+ // 1. Set element["removeAttributes"] to the result of creating a set from element["removeAttributes"].
+ element.remove_attributes = Some(create_a_set(list));
+
+ // 2. Set element["removeAttributes"] to the difference of element["removeAttributes"] and
+ // configuration["removeAttributes"].
+ element.remove_attributes = Some(difference(
+ element.remove_attributes.as_ref().unwrap(),
+ configuration.remove_attributes.as_ref().unwrap(),
+ ));
+ }
+ }
+
+ // 4. If configuration["elements"] does not contain element:
+ let elements = configuration.elements.as_mut().unwrap();
+ let current_element = elements.iter().position(|item| item.element == element.element);
+ if current_element.is_none() {
+ // 1. Append element to configuration["elements"].
+ elements.push(element);
+
+ // 2. Return true.
+ return Ok(true);
+ }
+
+ // 5. Let currentElement be the item in configuration["elements"] whose name member is element's name member
+ // and whose namespace member is element's namespace member.
+ // 6. If element is equal to currentElement, then return modified.
+ let current_element = current_element.unwrap();
+ if element == elements[current_element] {
+ return Ok(modified);
+ }
+
+ // 7. Remove element from configuration["elements"].
+ elements.remove(current_element);
+
+ // 8. Append element to configuration["elements"].
+ elements.push(element);
+
+ // 9. Return true.
+ return Ok(true);
+ }
+
+ // 5. Otherwise:
+ // 1. If element["attributes"] exists or element["removeAttributes"] with default « » is not empty, then return
+ // false.
+ if element.attributes.is_some() || element.remove_attributes.as_ref().is_some_and(|list| !list.is_empty()) {
+ return Ok(false);
+ }
+
+ // 2. Let modified be the result of removing element from configuration["replaceWithChildrenElements"].
+ let modified = sanitizer_list_remove(&mut configuration.replace_with_children_elements, &element.element);
+
+ // 3. If configuration["removeElements"] does not contain element, then return modified.
+ if !configuration
+ .remove_elements
+ .as_ref()
+ .unwrap()
+ .contains(&element.element)
+ {
+ return Ok(modified);
+ }
+
+ // 4. Remove element from configuration["removeElements"].
+ sanitizer_list_remove(&mut configuration.remove_elements, &element.element);
+
+ // 5. Return true.
+ Ok(true)
+ }
+
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-removeelement
+ pub(crate) fn remove_element(&self, _: &mut CallContext, element: SanitizerElement) -> WebIdlResult<bool> {
+ // The removeElement(element) method steps are to return the result of removing element from this's
+ // configuration.
+ Ok(remove_an_element_from_sanitizer_config(
+ &mut self.configuration.borrow_mut(),
+ &canonicalize_sanitizer_element(&element),
+ ))
+ }
+
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-replaceelementwithchildren
+ pub(crate) fn replace_element_with_children(
+ &self,
+ _: &mut CallContext,
+ element_input: SanitizerElement,
+ ) -> WebIdlResult<bool> {
+ // 1. Let configuration be this's configuration.
+ let mut configuration = self.configuration.borrow_mut();
+
+ // 2. Assert: configuration is valid.
+ assert!(sanitizer_configuration_is_valid(&configuration));
+
+ // 3. Set element to the result of canonicalizing element.
+ let element = canonicalize_sanitizer_element(&element_input);
+
+ // 4. If the built-in non-replaceable elements list contains element, then return false.
+ if built_in_non_replaceable_elements_list_contains(&element) {
+ return Ok(false);
+ }
+
+ // 5. Let modified be the result of removing element from configuration["elements"].
+ let mut modified = false;
+ if let Some(elements) = &mut configuration.elements {
+ let size = elements.len();
+ elements.retain(|item| item.element != element);
+ modified = size != elements.len();
+ }
+
+ // 6. If removing element from configuration["removeElements"] is true, then set modified to true.
+ if sanitizer_list_remove(&mut configuration.remove_elements, &element) {
+ modified = true;
+ }
+
+ // 7. If configuration["replaceWithChildrenElements"] does not contain element:
+ if !sanitizer_list_contains(configuration.replace_with_children_elements.as_deref(), &element) {
+ // 1. Append element to configuration["replaceWithChildrenElements"].
+ configuration
+ .replace_with_children_elements
+ .get_or_insert_with(Vec::new)
+ .push(element);
+
+ // 2. Return true.
+ return Ok(true);
+ }
+
+ // 8. Return modified.
+ Ok(modified)
+ }
+
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-allowattribute
+ pub(crate) fn allow_attribute(
+ &self,
+ _: &mut CallContext,
+ attribute_input: SanitizerAttribute,
+ ) -> WebIdlResult<bool> {
+ // 1. Let configuration be this's configuration.
+ let mut configuration = self.configuration.borrow_mut();
+
+ // 2. Assert: configuration is valid.
+ assert!(sanitizer_configuration_is_valid(&configuration));
+
+ // 3. Set attribute to the result of canonicalizing attribute.
+ let attribute = canonicalize_sanitizer_attribute(&attribute_input);
+
+ // 4. If configuration["attributes"] exists:
+ if configuration.attributes.is_some() {
+ // 1. If configuration["dataAttributes"] is true and attribute is a custom data attribute, then return false.
+ if configuration.data_attributes == Some(true) && is_custom_data_attribute(&attribute) {
+ return Ok(false);
+ }
+
+ // 2. If configuration["attributes"] contains attribute, then return false.
+ if configuration.attributes.as_ref().unwrap().contains(&attribute) {
+ return Ok(false);
+ }
+
+ // 3. If configuration["elements"] exists:
+ if let Some(elements) = &mut configuration.elements {
+ // 1. For each element in configuration["elements"]:
+ for element in elements {
+ // 1. If element["attributes"] with default « » contains attribute, then remove attribute from
+ // element["attributes"].
+ sanitizer_list_remove(&mut element.attributes, &attribute);
+ }
+ }
+
+ // 4. Append attribute to configuration["attributes"].
+ configuration.attributes.as_mut().unwrap().push(attribute);
+
+ // 5. Return true.
+ return Ok(true);
+ }
+
+ // 5. Otherwise:
+ // 1. If configuration["removeAttributes"] does not contain attribute, then return false.
+ if !configuration.remove_attributes.as_ref().unwrap().contains(&attribute) {
+ return Ok(false);
+ }
+
+ // 2. Remove attribute from configuration["removeAttributes"].
+ sanitizer_list_remove(&mut configuration.remove_attributes, &attribute);
+
+ // 3. Return true.
+ Ok(true)
+ }
+
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-removeattribute
+ pub(crate) fn remove_attribute(&self, _: &mut CallContext, attribute: SanitizerAttribute) -> WebIdlResult<bool> {
+ // The removeAttribute(attribute) method steps are to return the result of removing attribute from this's
+ // configuration.
+ Ok(remove_an_attribute_from_sanitizer_config(
+ &mut self.configuration.borrow_mut(),
+ &canonicalize_sanitizer_attribute(&attribute),
+ ))
+ }
+
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-setcomments
+ pub(crate) fn set_comments(&self, _: &mut CallContext, allow: bool) -> WebIdlResult<bool> {
+ // 1. Let configuration be this's configuration.
+ let mut configuration = self.configuration.borrow_mut();
+
+ // 2. Assert: configuration is valid.
+ assert!(sanitizer_configuration_is_valid(&configuration));
+
+ // 3. If configuration["comments"] is allow, then return false.
+ if configuration.comments == Some(allow) {
+ return Ok(false);
+ }
+
+ // 4. Set configuration["comments"] to allow.
+ configuration.comments = Some(allow);
+
+ // 5. Return true.
+ Ok(true)
+ }
+
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-setdataattributes
+ pub(crate) fn set_data_attributes(&self, _: &mut CallContext, allow: bool) -> WebIdlResult<bool> {
+ // 1. Let configuration be this's configuration.
+ let mut configuration = self.configuration.borrow_mut();
+
+ // 2. Assert: configuration is valid.
+ assert!(sanitizer_configuration_is_valid(&configuration));
+
+ // 3. If configuration["attributes"] does not exist, then return false.
+ if configuration.attributes.is_none() {
+ return Ok(false);
+ }
+
+ // 4. If configuration["dataAttributes"] exists and is equal to allow, then return false.
+ if configuration.data_attributes == Some(allow) {
+ return Ok(false);
+ }
+
+ // 5. If allow is true:
+ if allow {
+ // 1. If configuration["elements"] exists:
+ if let Some(elements) = &mut configuration.elements {
+ // 1. For each element of configuration["elements"]:
+ for element in elements {
+ // 1. If element["attributes"] exists, then remove all items item from element["attributes"] where item
+ // is a custom data attribute.
+ if let Some(attributes) = &mut element.attributes {
+ attributes.retain(|item| !is_custom_data_attribute(item));
+ }
+ }
+ }
+
+ // 2. Remove all items item from configuration["attributes"] where item is a custom data attribute.
+ configuration
+ .attributes
+ .as_mut()
+ .unwrap()
+ .retain(|item| !is_custom_data_attribute(item));
+ }
+
+ // 6. Set configuration["dataAttributes"] to allow.
+ configuration.data_attributes = Some(allow);
+
+ // 7. Return true.
+ Ok(true)
+ }
+
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-setjavascripturls
+ pub(crate) fn set_javascript_urls(&self, _: &mut CallContext, allow: bool) -> WebIdlResult<bool> {
+ // 1. Let configuration be this's configuration.
+ let mut configuration = self.configuration.borrow_mut();
+
+ // 2. Assert: configuration is valid.
+ assert!(sanitizer_configuration_is_valid(&configuration));
+
+ // 3. If configuration["javascriptURLs"] is allow, then return false.
+ if configuration.javascript_urls == Some(allow) {
+ return Ok(false);
+ }
+
+ // 4. Set configuration["javascriptURLs"] to allow.
+ configuration.javascript_urls = Some(allow);
+
+ // 5. Return true.
+ Ok(true)
+ }
+
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-allowprocessinginstruction
+ pub(crate) fn allow_processing_instruction(
+ &self,
+ _: &mut CallContext,
+ pi_input: SanitizerPI,
+ ) -> WebIdlResult<bool> {
+ // 1. Let configuration be this's configuration.
+ let mut configuration = self.configuration.borrow_mut();
+
+ // 2. Assert: configuration is valid.
+ assert!(sanitizer_configuration_is_valid(&configuration));
+
+ // 3. Set pi to the result of canonicalizing pi.
+ let pi = canonicalize_sanitizer_processing_instruction(&pi_input);
+
+ // 4. If configuration["processingInstructions"] exists:
+ if let Some(list) = &mut configuration.processing_instructions {
+ // 1. If configuration["processingInstructions"] contains pi, then return false.
+ if list.contains(&pi) {
+ return Ok(false);
+ }
+
+ // 2. Append pi to configuration["processingInstructions"].
+ list.push(pi);
+
+ // 3. Return true.
+ return Ok(true);
+ }
+
+ // 5. Otherwise:
+ // 1. If configuration["removeProcessingInstructions"] contains pi:
+ if configuration
+ .remove_processing_instructions
+ .as_ref()
+ .unwrap()
+ .contains(&pi)
+ {
+ // 1. Remove pi from configuration["removeProcessingInstructions"].
+ configuration
+ .remove_processing_instructions
+ .as_mut()
+ .unwrap()
+ .retain(|item| *item != pi);
+
+ // 2. Return true.
+ return Ok(true);
+ }
+
+ // 2. Return false.
+ Ok(false)
+ }
+
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-removeprocessinginstruction
+ pub(crate) fn remove_processing_instruction(
+ &self,
+ _: &mut CallContext,
+ pi_input: SanitizerPI,
+ ) -> WebIdlResult<bool> {
+ // 1. Let configuration be this's configuration.
+ let mut configuration = self.configuration.borrow_mut();
+
+ // 2. Assert: configuration is valid.
+ assert!(sanitizer_configuration_is_valid(&configuration));
+
+ // 3. Set pi to the result of canonicalizing pi.
+ let pi = canonicalize_sanitizer_processing_instruction(&pi_input);
+
+ // 4. If configuration["processingInstructions"] exists:
+ if let Some(list) = &mut configuration.processing_instructions {
+ // 1. If configuration["processingInstructions"] contains pi:
+ if list.contains(&pi) {
+ // 1. Remove pi from configuration["processingInstructions"].
+ list.retain(|item| *item != pi);
+
+ // 2. Return true.
+ return Ok(true);
+ }
+
+ // 2. Return false.
+ return Ok(false);
+ }
+
+ // 5. Otherwise:
+ // 1. If configuration["removeProcessingInstructions"] contains pi, then return false.
+ if configuration
+ .remove_processing_instructions
+ .as_ref()
+ .unwrap()
+ .contains(&pi)
+ {
+ return Ok(false);
+ }
+
+ // 2. Append pi to configuration["removeProcessingInstructions"].
+ configuration.remove_processing_instructions.as_mut().unwrap().push(pi);
+
+ // 3. Return true.
+ Ok(true)
+ }
+
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-removeunsafe
+ pub(crate) fn remove_unsafe(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ // The removeUnsafe() method steps are to return the result of removing unsafe from this's configuration.
+ Ok(remove_unsafe_from_sanitizer_config(
+ &mut self.configuration.borrow_mut(),
+ ))
+ }
+}
+
+/// Copies the Sanitizer’s configuration.
+///
+/// # Safety
+///
+/// `sanitizer` must be a live Sanitizer cell.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_sanitizer_configuration(sanitizer: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes a live Sanitizer.
+ let sanitizer = unsafe { cell_from_abi::<Sanitizer>(sanitizer) };
+ Arc::into_raw(Arc::new(sanitizer.configuration())).cast_mut().cast()
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/sanitizer_configuration.rs b/Libraries/LibWeb/Bindings/Rust/src/html/sanitizer_configuration.rs
new file mode 100644
index 00000000000..7032e7d005c
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/sanitizer_configuration.rs
@@ -0,0 +1,1931 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use core::ffi::c_void;
+use std::sync::{Arc, OnceLock};
+
+use ak::Utf16String;
+use libjs_rust::api::Utf16View;
+use liburl_rust::url::{BasicParseOptions, UrlInput, basic_parse};
+
+use super::sanitizer::{
+ self, Sanitizer, SanitizerAttribute, SanitizerAttributeNamespace, SanitizerConfig, SanitizerElement,
+ SanitizerElementNamespace, SanitizerElementNamespaceWithAttributes, SanitizerPI, SanitizerPresets,
+ SanitizerProcessingInstruction,
+};
+use crate::bindings::interface::{Ref, cell_from_abi, cell_into_abi};
+use crate::bindings::{Exception, WebIdlResult};
+
+const HTML: &str = "http://www.w3.org/1999/xhtml";
+const SVG: &str = "http://www.w3.org/2000/svg";
+const MATHML: &str = "http://www.w3.org/1998/Math/MathML";
+const XLINK: &str = "http://www.w3.org/1999/xlink";
+
+// NB: A canonicalized SanitizerElementNamespace or SanitizerAttributeNamespace dictionary.
+#[derive(Clone, PartialEq, Eq)]
+pub(crate) struct SanitizerName {
+ pub(crate) name: Utf16String,
+ pub(crate) namespace_: Option<Utf16String>,
+}
+
+// NB: A canonicalized SanitizerElementNamespaceWithAttributes dictionary.
+#[derive(Clone, PartialEq, Eq)]
+pub(crate) struct SanitizerElementWithAttributes {
+ pub(crate) element: SanitizerName,
+ pub(crate) attributes: Option<Vec<SanitizerName>>,
+ pub(crate) remove_attributes: Option<Vec<SanitizerName>>,
+}
+
+// NB: A canonicalized SanitizerConfig dictionary. Processing instructions are represented by their target.
+#[derive(Clone, Default)]
+pub(crate) struct SanitizerConfiguration {
+ pub(crate) elements: Option<Vec<SanitizerElementWithAttributes>>,
+ pub(crate) remove_elements: Option<Vec<SanitizerName>>,
+ pub(crate) replace_with_children_elements: Option<Vec<SanitizerName>>,
+ pub(crate) processing_instructions: Option<Vec<Utf16String>>,
+ pub(crate) remove_processing_instructions: Option<Vec<Utf16String>>,
+ pub(crate) attributes: Option<Vec<SanitizerName>>,
+ pub(crate) remove_attributes: Option<Vec<SanitizerName>>,
+ pub(crate) comments: Option<bool>,
+ pub(crate) data_attributes: Option<bool>,
+ pub(crate) javascript_urls: Option<bool>,
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sanitizer-action
+// NB: SanitizerAction in SanitizerConfiguration.h matches this.
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub(crate) enum SanitizerAction {
+ Keep,
+ Remove,
+ ReplaceWithChildren,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum PermissiveDefaults {
+ No,
+ Yes,
+}
+
+pub(crate) enum NameInput<'a> {
+ String(&'a Utf16String),
+ Dictionary(&'a Utf16String, Option<&'a Utf16String>),
+}
+
+impl<'a> From<&'a SanitizerElement> for NameInput<'a> {
+ fn from(element: &'a SanitizerElement) -> Self {
+ match element {
+ SanitizerElement::DOMString(name) => Self::String(name),
+ SanitizerElement::SanitizerElementNamespace(dictionary) => {
+ Self::Dictionary(&dictionary.name, dictionary.namespace.as_ref())
+ }
+ }
+ }
+}
+
+impl<'a> From<&'a sanitizer::SanitizerElementWithAttributes> for NameInput<'a> {
+ fn from(element: &'a sanitizer::SanitizerElementWithAttributes) -> Self {
+ match element {
+ sanitizer::SanitizerElementWithAttributes::DOMString(name) => Self::String(name),
+ sanitizer::SanitizerElementWithAttributes::SanitizerElementNamespaceWithAttributes(dictionary) => {
+ Self::Dictionary(&dictionary.parent.name, dictionary.parent.namespace.as_ref())
+ }
+ }
+ }
+}
+
+impl<'a> From<&'a SanitizerAttribute> for NameInput<'a> {
+ fn from(attribute: &'a SanitizerAttribute) -> Self {
+ match attribute {
+ SanitizerAttribute::DOMString(name) => Self::String(name),
+ SanitizerAttribute::SanitizerAttributeNamespace(dictionary) => {
+ Self::Dictionary(&dictionary.name, dictionary.namespace.as_ref())
+ }
+ }
+ }
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-a-sanitizer-name
+fn canonicalize_a_sanitizer_name(name: NameInput<'_>, default_namespace: Option<&str>) -> SanitizerName {
+ match name {
+ NameInput::String(string) => {
+ // 1. If name is a DOMString, then return «[ "name" → name, "namespace" → defaultNamespace ]».
+ SanitizerName {
+ name: string.clone(),
+ namespace_: default_namespace.map(Utf16String::from_utf8),
+ }
+ }
+ NameInput::Dictionary(name, namespace_) => {
+ // 2. Assert: name is a dictionary and both name["name"] and name["namespace"] exist.
+ let mut namespace_ = namespace_.cloned();
+
+ // 3. If name["namespace"] is the empty string, then set it to null.
+ if namespace_.as_ref().is_some_and(Utf16String::is_empty) {
+ namespace_ = None;
+ }
+
+ // 4. Return «[ "name" → name["name"], "namespace" → name["namespace"] ]».
+ SanitizerName {
+ name: name.clone(),
+ namespace_,
+ }
+ }
+ }
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-a-sanitizer-element
+fn canonicalize_a_sanitizer_element(element: NameInput<'_>) -> SanitizerName {
+ // Return the result of canonicalizing element with the HTML namespace as the default namespace.
+ canonicalize_a_sanitizer_name(element, Some(HTML))
+}
+
+// NB: Attributes are canonicalized with the default namespace of null.
+fn canonicalize_a_sanitizer_attribute(attribute: NameInput<'_>) -> SanitizerName {
+ canonicalize_a_sanitizer_name(attribute, None)
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-a-sanitizer-element-list
+fn canonicalize_a_sanitizer_element_list(list: &[SanitizerElement]) -> Vec<SanitizerName> {
+ // 1. Let newList be « ».
+ let mut new_list = Vec::with_capacity(list.len());
+
+ // 2. For each item in list, append the result of canonicalizing item to newList.
+ for item in list {
+ new_list.push(canonicalize_a_sanitizer_element(item.into()));
+ }
+
+ // 3. Return newList.
+ new_list
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-a-sanitizer-list
+fn canonicalize_a_sanitizer_list(list: &[SanitizerAttribute]) -> Vec<SanitizerName> {
+ // 1. Let newList be « ».
+ let mut new_list = Vec::with_capacity(list.len());
+
+ // 2. For each item in list, append the result of canonicalizing item to newList.
+ for item in list {
+ new_list.push(canonicalize_a_sanitizer_attribute(item.into()));
+ }
+
+ // 3. Return newList.
+ new_list
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-a-processing-instruction-list
+fn canonicalize_a_processing_instruction_list(list: &[SanitizerPI]) -> Vec<Utf16String> {
+ // 1. Let newList be « ».
+ let mut new_list = Vec::with_capacity(list.len());
+
+ // 2. For each item in list, append the result of canonicalizing item to newList.
+ for item in list {
+ new_list.push(canonicalize_sanitizer_processing_instruction(item));
+ }
+
+ // 3. Return newList.
+ new_list
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-a-sanitizer-element-with-attributes
+fn canonicalize_a_sanitizer_element_with_attributes(
+ element: &sanitizer::SanitizerElementWithAttributes,
+) -> SanitizerElementWithAttributes {
+ // 1. Let result be the result of canonicalizing element.
+ let mut result = SanitizerElementWithAttributes {
+ element: canonicalize_a_sanitizer_element(element.into()),
+ attributes: None,
+ remove_attributes: None,
+ };
+
+ // 2. If element is a dictionary:
+ if let sanitizer::SanitizerElementWithAttributes::SanitizerElementNamespaceWithAttributes(dictionary) = element {
+ // 1. If element["attributes"] exists, then set result["attributes"] to the result of canonicalizing
+ // element["attributes"].
+ if let Some(attributes) = &dictionary.attributes {
+ result.attributes = Some(canonicalize_a_sanitizer_list(attributes));
+ }
+
+ // 2. If element["removeAttributes"] exists, then set result["removeAttributes"] to the result of
+ // canonicalizing element["removeAttributes"].
+ if let Some(attributes) = &dictionary.remove_attributes {
+ result.remove_attributes = Some(canonicalize_a_sanitizer_list(attributes));
+ }
+ }
+
+ // 3. If neither result["attributes"] nor result["removeAttributes"] exists, then set result["removeAttributes"]
+ // to an empty list.
+ if result.attributes.is_none() && result.remove_attributes.is_none() {
+ result.remove_attributes = Some(Vec::new());
+ }
+
+ // 4. Return result.
+ result
+}
+
+pub(crate) fn canonicalize_sanitizer_element(element: &SanitizerElement) -> SanitizerName {
+ canonicalize_a_sanitizer_element(element.into())
+}
+pub(crate) fn canonicalize_sanitizer_element_with_attributes(
+ element: &sanitizer::SanitizerElementWithAttributes,
+) -> SanitizerElementWithAttributes {
+ canonicalize_a_sanitizer_element_with_attributes(element)
+}
+pub(crate) fn canonicalize_sanitizer_attribute(attribute: &SanitizerAttribute) -> SanitizerName {
+ canonicalize_a_sanitizer_attribute(attribute.into())
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-a-processing-instruction
+pub(crate) fn canonicalize_sanitizer_processing_instruction(pi: &SanitizerPI) -> Utf16String {
+ match pi {
+ // 1. If pi is a DOMString, then return «[ "target" → pi ]».
+ SanitizerPI::DOMString(string) => string.clone(),
+
+ // 2. Assert: pi is a dictionary and pi["target"] exists.
+ // 3. Return «[ "target" → pi["target"] ]».
+ SanitizerPI::SanitizerProcessingInstruction(dictionary) => dictionary.target.clone(),
+ }
+}
+
+// NB: This performs the per-item canonicalization steps of "canonicalize the configuration" on a dictionary supplied
+// by script. The remaining steps are performed by canonicalize_the_configuration().
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-the-configuration
+pub(crate) fn canonicalize_sanitizer_config(configuration: &SanitizerConfig) -> SanitizerConfiguration {
+ let mut result = SanitizerConfiguration::default();
+
+ // 4. If configuration["elements"] exists:
+ if let Some(elements) = &configuration.elements {
+ // 1. Let newElements be « ».
+ let mut new_elements = Vec::with_capacity(elements.len());
+
+ // 2. For each element of configuration["elements"], append the result of canonicalizing element to
+ // newElements.
+ for element in elements {
+ new_elements.push(canonicalize_a_sanitizer_element_with_attributes(element));
+ }
+
+ // 3. Set configuration["elements"] to newElements.
+ result.elements = Some(new_elements);
+ }
+
+ // 5. If configuration["removeElements"] exists, then set configuration["removeElements"] to the result of
+ // canonicalizing configuration["removeElements"].
+ if let Some(list) = &configuration.remove_elements {
+ result.remove_elements = Some(canonicalize_a_sanitizer_element_list(list));
+ }
+
+ // 6. If configuration["attributes"] exists, then set configuration["attributes"] to the result of canonicalizing
+ // configuration["attributes"].
+ if let Some(list) = &configuration.attributes {
+ result.attributes = Some(canonicalize_a_sanitizer_list(list));
+ }
+
+ // 7. If configuration["removeAttributes"] exists, then set configuration["removeAttributes"] to the result of
+ // canonicalizing configuration["removeAttributes"].
+ if let Some(list) = &configuration.remove_attributes {
+ result.remove_attributes = Some(canonicalize_a_sanitizer_list(list));
+ }
+
+ // 8. If configuration["replaceWithChildrenElements"] exists, then set configuration["replaceWithChildrenElements"]
+ // to the result of canonicalizing configuration["replaceWithChildrenElements"].
+ if let Some(list) = &configuration.replace_with_children_elements {
+ result.replace_with_children_elements = Some(canonicalize_a_sanitizer_element_list(list));
+ }
+
+ // 9. If configuration["processingInstructions"] exists, then set configuration["processingInstructions"] to the
+ // result of canonicalizing configuration["processingInstructions"].
+ if let Some(list) = &configuration.processing_instructions {
+ result.processing_instructions = Some(canonicalize_a_processing_instruction_list(list));
+ }
+
+ // 10. If configuration["removeProcessingInstructions"] exists, then set
+ // configuration["removeProcessingInstructions"] to the result of canonicalizing
+ // configuration["removeProcessingInstructions"].
+ if let Some(list) = &configuration.remove_processing_instructions {
+ result.remove_processing_instructions = Some(canonicalize_a_processing_instruction_list(list));
+ }
+ result.comments = configuration.comments;
+ result.data_attributes = configuration.data_attributes;
+ result.javascript_urls = configuration.javascript_ur_ls;
+ result
+}
+
+// NB: This performs the steps of "canonicalize the configuration" that do not canonicalize individual items. Items of
+// a SanitizerConfiguration are always canonical, see canonicalize_sanitizer_config().
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-the-configuration
+fn canonicalize_the_configuration(configuration: &mut SanitizerConfiguration, permissive_defaults: PermissiveDefaults) {
+ let permissive = permissive_defaults == PermissiveDefaults::Yes;
+
+ // 1. If neither configuration["elements"] nor configuration["removeElements"] exists, then set
+ // configuration["removeElements"] to an empty list.
+ if configuration.elements.is_none() && configuration.remove_elements.is_none() {
+ configuration.remove_elements = Some(Vec::new());
+ }
+
+ // 2. If neither configuration["attributes"] nor configuration["removeAttributes"] exists, then set
+ // configuration["removeAttributes"] to an empty list.
+ if configuration.attributes.is_none() && configuration.remove_attributes.is_none() {
+ configuration.remove_attributes = Some(Vec::new());
+ }
+
+ // 3. If neither configuration["processingInstructions"] nor configuration["removeProcessingInstructions"] exists:
+ if configuration.processing_instructions.is_none() && configuration.remove_processing_instructions.is_none() {
+ // 1. If permissiveDefaults is true, then set configuration["removeProcessingInstructions"] to an empty list.
+ if permissive {
+ configuration.remove_processing_instructions = Some(Vec::new());
+ }
+ // 2. Otherwise, set configuration["processingInstructions"] to an empty list.
+ else {
+ configuration.processing_instructions = Some(Vec::new());
+ }
+ }
+ // NB: Steps 4 to 10 canonicalize individual items, which canonicalize_sanitizer_config() has done.
+ // 11. If configuration["comments"] does not exist, then set it to permissiveDefaults.
+ if configuration.comments.is_none() {
+ configuration.comments = Some(permissive);
+ }
+
+ // 12. If configuration["attributes"] exists and configuration["dataAttributes"] does not exist, then set it to
+ // permissiveDefaults.
+ if configuration.attributes.is_some() && configuration.data_attributes.is_none() {
+ configuration.data_attributes = Some(permissive);
+ }
+
+ // 13. If configuration["javascriptURLs"] does not exist, then set it to permissiveDefaults.
+ if configuration.javascript_urls.is_none() {
+ configuration.javascript_urls = Some(permissive);
+ }
+}
+
+pub(crate) fn sanitizer_list_contains(list: Option<&[SanitizerName]>, item: &SanitizerName) -> bool {
+ list.is_some_and(|list| list.contains(item))
+}
+// NB: Returns whether the list contained the item.
+pub(crate) fn sanitizer_list_remove(list: &mut Option<Vec<SanitizerName>>, item: &SanitizerName) -> bool {
+ let Some(list) = list else {
+ return false;
+ };
+ let size = list.len();
+ list.retain(|entry| entry != item);
+ size != list.len()
+}
+
+fn find_element<'a>(
+ elements: Option<&'a [SanitizerElementWithAttributes]>,
+ local_name: &Utf16String,
+ namespace_: Option<&Utf16String>,
+) -> Option<&'a SanitizerElementWithAttributes> {
+ elements?
+ .iter()
+ .find(|element| element.element.name == *local_name && element.element.namespace_.as_ref() == namespace_)
+}
+fn elements_contain(elements: Option<&[SanitizerElementWithAttributes]>, name: &SanitizerName) -> bool {
+ find_element(elements, &name.name, name.namespace_.as_ref()).is_some()
+}
+fn elements_remove(elements: &mut Option<Vec<SanitizerElementWithAttributes>>, name: &SanitizerName) -> bool {
+ let Some(elements) = elements else {
+ return false;
+ };
+ let size = elements.len();
+ elements.retain(|element| element.element != *name);
+ size != elements.len()
+}
+
+// https://infra.spec.whatwg.org/#list-has-duplicates
+fn has_duplicates<T: PartialEq>(list: &[T]) -> bool {
+ for i in 0..list.len() {
+ for j in i + 1..list.len() {
+ if list[i] == list[j] {
+ return true;
+ }
+ }
+ }
+ false
+}
+
+// https://infra.spec.whatwg.org/#set-intersection
+fn intersection_is_empty<T: PartialEq>(a: &[T], b: &[T]) -> bool {
+ for item in a {
+ for other in b {
+ if item == other {
+ return false;
+ }
+ }
+ }
+ true
+}
+
+// https://infra.spec.whatwg.org/#set-subset
+fn is_subset(subset: &[SanitizerName], superset: &[SanitizerName]) -> bool {
+ for item in subset {
+ if !superset.contains(item) {
+ return false;
+ }
+ }
+ true
+}
+
+// https://html.spec.whatwg.org/multipage/dom.html#custom-data-attribute
+pub(crate) fn is_custom_data_attribute(attribute: &SanitizerName) -> bool {
+ // A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least
+ // one character after the hyphen, is a valid attribute local name, and contains no ASCII upper alphas.
+ if attribute.namespace_.is_some() {
+ return false;
+ }
+ let name = Utf16View::of_string(&attribute.name);
+ if !name.starts_with(Utf16View::Ascii(b"data-")) || name.length_in_code_units() <= 5 {
+ return false;
+ }
+ if !crate::dom::element::is_valid_attribute_local_name(&attribute.name) {
+ return false;
+ }
+ !name
+ .code_units()
+ .any(|unit| u8::try_from(unit).is_ok_and(|unit| unit.is_ascii_uppercase()))
+}
+
+fn contains_custom_data_attribute(list: &[SanitizerName]) -> bool {
+ list.iter().any(is_custom_data_attribute)
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizerconfig-valid
+pub(crate) fn sanitizer_configuration_is_valid(config: &SanitizerConfiguration) -> bool {
+ // 1. Assert: config["elements"] exists or config["removeElements"] exists.
+ assert!(config.elements.is_some() || config.remove_elements.is_some());
+
+ // 2. If config["elements"] exists and config["removeElements"] exists, then return false.
+ if config.elements.is_some() && config.remove_elements.is_some() {
+ return false;
+ }
+
+ // 3. Assert: Either config["processingInstructions"] exists or config["removeProcessingInstructions"] exists.
+ assert!(config.processing_instructions.is_some() || config.remove_processing_instructions.is_some());
+
+ // 4. If config["processingInstructions"] exists and config["removeProcessingInstructions"] exists, then return
+ // false.
+ if config.processing_instructions.is_some() && config.remove_processing_instructions.is_some() {
+ return false;
+ }
+
+ // 5. Assert: Either config["attributes"] exists or config["removeAttributes"] exists.
+ assert!(config.attributes.is_some() || config.remove_attributes.is_some());
+
+ // 6. If config["attributes"] exists and config["removeAttributes"] exists, then return false.
+ if config.attributes.is_some() && config.remove_attributes.is_some() {
+ return false;
+ }
+
+ // 7. Assert: All SanitizerElementNamespaceWithAttributes, SanitizerElementNamespace,
+ // SanitizerProcessingInstruction, and SanitizerAttributeNamespace items in config are canonical, meaning they
+ // have been run through canonicalizing, as appropriate.
+ // NB: The items of a SanitizerConfiguration are canonical by construction.
+ // 8. If config["elements"] exists:
+ if let Some(elements) = &config.elements {
+ // 1. If config["elements"] has duplicates, then return false.
+ for i in 0..elements.len() {
+ for j in i + 1..elements.len() {
+ if elements[i].element == elements[j].element {
+ return false;
+ }
+ }
+ }
+ }
+ // 9. Otherwise:
+ else {
+ // 1. If config["removeElements"] has duplicates, then return false.
+ if has_duplicates(config.remove_elements.as_ref().unwrap()) {
+ return false;
+ }
+ }
+
+ // 10. If config["replaceWithChildrenElements"] exists and has duplicates, then return false.
+ if config
+ .replace_with_children_elements
+ .as_ref()
+ .is_some_and(|list| has_duplicates(list))
+ {
+ return false;
+ }
+
+ // 11. If config["processingInstructions"] exists:
+ if let Some(list) = &config.processing_instructions {
+ // 1. If config["processingInstructions"] has duplicates, then return false.
+ if has_duplicates(list) {
+ return false;
+ }
+ }
+ // 12. Otherwise:
+ else {
+ // 1. If config["removeProcessingInstructions"] has duplicates, then return false.
+ if has_duplicates(config.remove_processing_instructions.as_ref().unwrap()) {
+ return false;
+ }
+ }
+
+ // 13. If config["attributes"] exists:
+ if let Some(list) = &config.attributes {
+ // 1. If config["attributes"] has duplicates, then return false.
+ if has_duplicates(list) {
+ return false;
+ }
+ }
+ // 14. Otherwise:
+ else {
+ // 1. If config["removeAttributes"] has duplicates, then return false.
+ if has_duplicates(config.remove_attributes.as_ref().unwrap()) {
+ return false;
+ }
+ }
+
+ // 15. If config["replaceWithChildrenElements"] exists:
+ if let Some(replace) = &config.replace_with_children_elements {
+ // 1. For each element of config["replaceWithChildrenElements"]:
+ for element in replace {
+ // 1. If the built-in non-replaceable elements list contains element, then return false.
+ if built_in_non_replaceable_elements_list_contains(element) {
+ return false;
+ }
+ }
+
+ // 2. If config["elements"] exists:
+ if let Some(elements) = &config.elements {
+ // 1. If the intersection of config["elements"] and config["replaceWithChildrenElements"] is not empty, then
+ // return false.
+ if elements.iter().any(|element| replace.contains(&element.element)) {
+ return false;
+ }
+ }
+ // 3. Otherwise:
+ else {
+ // 1. If the intersection of config["removeElements"] and config["replaceWithChildrenElements"] is not
+ // empty, then return false.
+ if !intersection_is_empty(config.remove_elements.as_ref().unwrap(), replace) {
+ return false;
+ }
+ }
+ }
+
+ // 16. If config["attributes"] exists:
+ if let Some(attributes) = &config.attributes {
+ // 1. Assert: config["dataAttributes"] exists.
+ assert!(config.data_attributes.is_some());
+
+ // 2. If config["elements"] exists:
+ if let Some(elements) = &config.elements {
+ // 1. For each element of config["elements"]:
+ for element in elements {
+ // 1. If element["attributes"] exists and element["attributes"] has duplicates, then return false.
+ if element.attributes.as_ref().is_some_and(|list| has_duplicates(list)) {
+ return false;
+ }
+
+ // 2. If element["removeAttributes"] exists and element["removeAttributes"] has duplicates, then return
+ // false.
+ if element
+ .remove_attributes
+ .as_ref()
+ .is_some_and(|list| has_duplicates(list))
+ {
+ return false;
+ }
+
+ // 3. If the intersection of config["attributes"] and element["attributes"] with default « » is not
+ // empty, then return false.
+ if element
+ .attributes
+ .as_ref()
+ .is_some_and(|list| !intersection_is_empty(attributes, list))
+ {
+ return false;
+ }
+
+ // 4. If element["removeAttributes"] with default « » is not a subset of config["attributes"], then
+ // return false.
+ if element
+ .remove_attributes
+ .as_ref()
+ .is_some_and(|list| !is_subset(list, attributes))
+ {
+ return false;
+ }
+
+ // 5. If config["dataAttributes"] is true and element["attributes"] contains a custom data attribute,
+ // then return false.
+ if config.data_attributes == Some(true)
+ && element
+ .attributes
+ .as_ref()
+ .is_some_and(|list| contains_custom_data_attribute(list))
+ {
+ return false;
+ }
+ }
+ }
+
+ // 3. If config["dataAttributes"] is true and config["attributes"] contains a custom data attribute, then return
+ // false.
+ if config.data_attributes == Some(true) && contains_custom_data_attribute(attributes) {
+ return false;
+ }
+ }
+ // 17. Otherwise:
+ else {
+ // 1. If config["elements"] exists:
+ if let Some(elements) = &config.elements {
+ // 1. For each element of config["elements"]:
+ for element in elements {
+ // 1. If element["attributes"] exists and element["removeAttributes"] exists, then return false.
+ if element.attributes.is_some() && element.remove_attributes.is_some() {
+ return false;
+ }
+
+ // 2. If element["attributes"] exists and element["attributes"] has duplicates, then return false.
+ if element.attributes.as_ref().is_some_and(|list| has_duplicates(list)) {
+ return false;
+ }
+
+ // 3. If element["removeAttributes"] exists and element["removeAttributes"] has duplicates, then return
+ // false.
+ if element
+ .remove_attributes
+ .as_ref()
+ .is_some_and(|list| has_duplicates(list))
+ {
+ return false;
+ }
+
+ // 4. If the intersection of config["removeAttributes"] and element["attributes"] with default « » is
+ // not empty, then return false.
+ if element
+ .attributes
+ .as_ref()
+ .is_some_and(|list| !intersection_is_empty(config.remove_attributes.as_ref().unwrap(), list))
+ {
+ return false;
+ }
+
+ // 5. If the intersection of config["removeAttributes"] and element["removeAttributes"] with default « »
+ // is not empty, then return false.
+ if element
+ .remove_attributes
+ .as_ref()
+ .is_some_and(|list| !intersection_is_empty(config.remove_attributes.as_ref().unwrap(), list))
+ {
+ return false;
+ }
+ }
+ }
+
+ // 2. If config["dataAttributes"] exists, then return false.
+ if config.data_attributes.is_some() {
+ return false;
+ }
+ }
+
+ // 18. Return true.
+ true
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#configure-a-sanitizer
+pub(crate) fn configure_sanitizer_configuration(
+ mut fresh_configuration: SanitizerConfiguration,
+ permissive_defaults: PermissiveDefaults,
+) -> WebIdlResult<SanitizerConfiguration> {
+ // 1. Let freshConfiguration be a clone of configuration.
+ // NB: The caller passes a clone.
+ // 2. Canonicalize the configuration freshConfiguration with permissiveDefaults.
+ canonicalize_the_configuration(&mut fresh_configuration, permissive_defaults);
+
+ // 3. If freshConfiguration is not valid, then throw a TypeError.
+ if !sanitizer_configuration_is_valid(&fresh_configuration) {
+ return Err(Exception::type_error("Sanitizer configuration is not valid"));
+ }
+
+ // 4. Set sanitizer's configuration to freshConfiguration.
+ // NB: The caller stores the result.
+ Ok(fresh_configuration)
+}
+
+fn to_bindings_name(name: &SanitizerName) -> SanitizerElementNamespace {
+ SanitizerElementNamespace {
+ name: name.name.clone(),
+ namespace: name.namespace_.clone(),
+ }
+}
+fn to_bindings_attribute_list(list: &[SanitizerName]) -> Vec<SanitizerAttribute> {
+ list.iter()
+ .map(|name| {
+ SanitizerAttribute::SanitizerAttributeNamespace(SanitizerAttributeNamespace {
+ name: name.name.clone(),
+ namespace: name.namespace_.clone(),
+ })
+ })
+ .collect()
+}
+fn to_bindings_element_list(list: &[SanitizerName]) -> Vec<SanitizerElement> {
+ list.iter()
+ .map(|name| SanitizerElement::SanitizerElementNamespace(to_bindings_name(name)))
+ .collect()
+}
+fn to_bindings_processing_instruction_list(list: &[Utf16String]) -> Vec<SanitizerPI> {
+ list.iter()
+ .map(|target| {
+ SanitizerPI::SanitizerProcessingInstruction(SanitizerProcessingInstruction { target: target.clone() })
+ })
+ .collect()
+}
+
+pub(crate) fn sanitizer_configuration_to_bindings(configuration: &SanitizerConfiguration) -> SanitizerConfig {
+ SanitizerConfig {
+ elements: configuration.elements.as_ref().map(|elements| {
+ elements
+ .iter()
+ .map(|element| {
+ sanitizer::SanitizerElementWithAttributes::SanitizerElementNamespaceWithAttributes(
+ SanitizerElementNamespaceWithAttributes {
+ parent: to_bindings_name(&element.element),
+ attributes: element.attributes.as_ref().map(|list| to_bindings_attribute_list(list)),
+ remove_attributes: element
+ .remove_attributes
+ .as_ref()
+ .map(|list| to_bindings_attribute_list(list)),
+ },
+ )
+ })
+ .collect()
+ }),
+ remove_elements: configuration
+ .remove_elements
+ .as_ref()
+ .map(|list| to_bindings_element_list(list)),
+ replace_with_children_elements: configuration
+ .replace_with_children_elements
+ .as_ref()
+ .map(|list| to_bindings_element_list(list)),
+ processing_instructions: configuration
+ .processing_instructions
+ .as_ref()
+ .map(|list| to_bindings_processing_instruction_list(list)),
+ remove_processing_instructions: configuration
+ .remove_processing_instructions
+ .as_ref()
+ .map(|list| to_bindings_processing_instruction_list(list)),
+ attributes: configuration
+ .attributes
+ .as_ref()
+ .map(|list| to_bindings_attribute_list(list)),
+ remove_attributes: configuration
+ .remove_attributes
+ .as_ref()
+ .map(|list| to_bindings_attribute_list(list)),
+ comments: configuration.comments,
+ data_attributes: configuration.data_attributes,
+ javascript_ur_ls: configuration.javascript_urls,
+ }
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#remove-an-element-from-sanitizer-config
+pub(crate) fn remove_an_element_from_sanitizer_config(
+ configuration: &mut SanitizerConfiguration,
+ element: &SanitizerName,
+) -> bool {
+ // 1. Assert: configuration is valid.
+ // 2. Set element to the result of canonicalizing element.
+ // NB: element is canonical.
+ // 3. Let modified be the result of removing element from configuration["replaceWithChildrenElements"].
+ let modified = sanitizer_list_remove(&mut configuration.replace_with_children_elements, element);
+
+ // 4. If configuration["elements"] exists:
+ if configuration.elements.is_some() {
+ // 1. If configuration["elements"] contains element:
+ if elements_contain(configuration.elements.as_deref(), element) {
+ // 1. Remove element from configuration["elements"].
+ elements_remove(&mut configuration.elements, element);
+
+ // 2. Return true.
+ return true;
+ }
+
+ // 2. Return modified.
+ return modified;
+ }
+
+ // 5. Otherwise:
+ // 1. If configuration["removeElements"] contains element, then return modified.
+ if configuration.remove_elements.as_ref().unwrap().contains(element) {
+ return modified;
+ }
+
+ // 2. Append element to configuration["removeElements"].
+ configuration.remove_elements.as_mut().unwrap().push(element.clone());
+
+ // 3. Return true.
+ true
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#remove-an-attribute-from-sanitizer-config
+pub(crate) fn remove_an_attribute_from_sanitizer_config(
+ configuration: &mut SanitizerConfiguration,
+ attribute: &SanitizerName,
+) -> bool {
+ // 1. Assert: configuration is valid.
+ // 2. Set attribute to the result of canonicalizing attribute.
+ // NB: attribute is canonical.
+ // 3. If configuration["attributes"] exists:
+ if configuration.attributes.is_some() {
+ // 1. Let modified be the result of removing attribute from configuration["attributes"].
+ let mut modified = sanitizer_list_remove(&mut configuration.attributes, attribute);
+
+ // 2. If configuration["elements"] exists:
+ if let Some(elements) = &mut configuration.elements {
+ // 1. For each element of configuration["elements"]:
+ for element in elements {
+ // 1. If element["attributes"] with default « » contains attribute:
+ if sanitizer_list_contains(element.attributes.as_deref(), attribute) {
+ // 1. Set modified to true.
+ modified = true;
+
+ // 2. Remove attribute from element["attributes"].
+ sanitizer_list_remove(&mut element.attributes, attribute);
+ }
+
+ // 2. If element["removeAttributes"] with default « » contains attribute:
+ if sanitizer_list_contains(element.remove_attributes.as_deref(), attribute) {
+ // 1. Assert: modified is true.
+ assert!(modified);
+
+ // 2. Remove attribute from element["removeAttributes"].
+ sanitizer_list_remove(&mut element.remove_attributes, attribute);
+ }
+ }
+ }
+
+ // 3. Return modified.
+ return modified;
+ }
+
+ // 4. Otherwise:
+ // 1. If configuration["removeAttributes"] contains attribute, then return false.
+ if configuration.remove_attributes.as_ref().unwrap().contains(attribute) {
+ return false;
+ }
+
+ // 2. If configuration["elements"] exists:
+ if let Some(elements) = &mut configuration.elements {
+ // 1. For each element in configuration["elements"]:
+ for element in elements {
+ // 1. If element["attributes"] with default « » contains attribute, then remove attribute from
+ // element["attributes"].
+ sanitizer_list_remove(&mut element.attributes, attribute);
+
+ // 2. If element["removeAttributes"] with default « » contains attribute, then remove attribute from
+ // element["removeAttributes"].
+ sanitizer_list_remove(&mut element.remove_attributes, attribute);
+ }
+ }
+
+ // 3. Append attribute to configuration["removeAttributes"].
+ configuration
+ .remove_attributes
+ .as_mut()
+ .unwrap()
+ .push(attribute.clone());
+
+ // 4. Return true.
+ true
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#remove-unsafe
+pub(crate) fn remove_unsafe_from_sanitizer_config(configuration: &mut SanitizerConfiguration) -> bool {
+ // 1. Assert: configuration is valid.
+ // 2. Let result be false.
+ let mut result = false;
+
+ // 3. For each element in built-in safe baseline configuration["removeElements"]:
+ for element in built_in_safe_baseline_configuration().remove_elements.as_ref().unwrap() {
+ // 1. If removing element from configuration is true, then set result to true.
+ if remove_an_element_from_sanitizer_config(configuration, element) {
+ result = true;
+ }
+ }
+
+ // 4. For each attribute in built-in safe baseline configuration["removeAttributes"]:
+ for attribute in built_in_safe_baseline_configuration()
+ .remove_attributes
+ .as_ref()
+ .unwrap()
+ {
+ // 1. If removing attribute from configuration is true, then set result to true.
+ if remove_an_attribute_from_sanitizer_config(configuration, attribute) {
+ result = true;
+ }
+ }
+
+ // 5. For each attribute that is an event handler content attribute:
+ for &attribute in event_handler_content_attributes() {
+ // 1. If removing attribute from configuration is true, then set result to true.
+ if remove_an_attribute_from_sanitizer_config(
+ configuration,
+ &SanitizerName {
+ // SAFETY: C++ lends its immutable process-lifetime list of event handler names.
+ name: unsafe { Utf16String::from_raw_borrowed(attribute) },
+ namespace_: None,
+ },
+ ) {
+ result = true;
+ }
+ }
+
+ // 6. If configuration["javascriptURLs"] is true:
+ if configuration.javascript_urls == Some(true) {
+ // 1. Set result to true.
+ result = true;
+
+ // 2. Set configuration["javascriptURLs"] to false.
+ configuration.javascript_urls = Some(false);
+ }
+
+ // 7. Return result.
+ result
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sanitizer-config-allows-comments
+pub(crate) fn sanitizer_config_allows_comments(configuration: &SanitizerConfiguration) -> bool {
+ // Return true if configuration["comments"] is true; otherwise false.
+ configuration.comments == Some(true)
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sanitizer-config-allows-processing-instruction-target
+pub(crate) fn sanitizer_config_allows_processing_instruction_target(
+ pi_target: Utf16View<'_>,
+ configuration: &SanitizerConfiguration,
+) -> bool {
+ // 1. Let pi be «[ "target" → piTarget ]».
+ let contains = |list: &[Utf16String]| {
+ list.iter()
+ .any(|target| Utf16View::of_string(target).code_units().eq(pi_target.code_units()))
+ };
+
+ // 2. If configuration["processingInstructions"] exists, then return whether
+ // configuration["processingInstructions"] contains pi.
+ if let Some(list) = &configuration.processing_instructions {
+ return contains(list);
+ }
+
+ // 3. If configuration["removeProcessingInstructions"] exists and configuration["removeProcessingInstructions"]
+ // contains pi, then return false.
+ if configuration
+ .remove_processing_instructions
+ .as_ref()
+ .is_some_and(|list| contains(list))
+ {
+ return false;
+ }
+
+ // 4. Return true.
+ true
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#get-the-sanitizer-action-for-an-element-name
+pub(crate) fn sanitizer_action_for_element_name(
+ local_name: &Utf16String,
+ namespace_: Option<&Utf16String>,
+ configuration: &SanitizerConfiguration,
+) -> SanitizerAction {
+ // 1. Let elementName be «[ "name" → localName, "namespace" → namespace ]».
+ let element_name = SanitizerName {
+ name: local_name.clone(),
+ namespace_: namespace_.cloned(),
+ };
+
+ // 2. If configuration["replaceWithChildrenElements"] exists and configuration["replaceWithChildrenElements"]
+ // contains elementName, then return "Replace with children".
+ if sanitizer_list_contains(configuration.replace_with_children_elements.as_deref(), &element_name) {
+ return SanitizerAction::ReplaceWithChildren;
+ }
+
+ // 3. If configuration["elements"] exists:
+ if configuration.elements.is_some() {
+ // 1. If there is no item in configuration["elements"] whose name member is localName and whose namespace
+ // member is namespace, then return "Remove".
+ if find_element(configuration.elements.as_deref(), local_name, namespace_).is_none() {
+ return SanitizerAction::Remove;
+ }
+ }
+ // 4. Otherwise, if configuration["removeElements"] contains elementName, then return "Remove".
+ else if sanitizer_list_contains(configuration.remove_elements.as_deref(), &element_name) {
+ return SanitizerAction::Remove;
+ }
+
+ // 5. Return "Keep".
+ SanitizerAction::Keep
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#contains-a-javascript:-url
+fn contains_a_javascript_url(value: Utf16View<'_>) -> bool {
+ // 1. Let url be the result of running the basic URL parser on value.
+ let input = match value {
+ Utf16View::Ascii(bytes) | Utf16View::Latin1(bytes) => UrlInput::Latin1(bytes),
+ Utf16View::Utf16(units) => UrlInput::Utf16(units),
+ };
+ let url = basic_parse(input, BasicParseOptions::new());
+
+ // 2. If url is failure, then return false.
+ let Some(url) = url else {
+ return false;
+ };
+
+ // 3. Return true if url's scheme is "javascript", and false otherwise.
+ url.scheme() == "javascript"
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#built-in-navigating-url-attributes-list
+fn built_in_navigating_url_attributes_list_matches(
+ element_name: &SanitizerName,
+ attribute_name: &SanitizerName,
+) -> bool {
+ // The built-in navigating URL attributes list corresponds to all HTML elements marked with navigating URL
+ // attributes in their normative definitions, as well as the element-attribute pairs represented in the following
+ // table.
+ const LIST: &[(&str, &str, &str, Option<&str>)] = &[
+ ("a", HTML, "href", None),
+ ("area", HTML, "href", None),
+ ("form", HTML, "action", None),
+ ("input", HTML, "formaction", None),
+ ("button", HTML, "formaction", None),
+ ("a", SVG, "href", None),
+ ("a", SVG, "href", Some(XLINK)),
+ ];
+ for &(element, namespace_, attribute, attribute_namespace) in LIST {
+ if element_name.name != element
+ || element_name
+ .namespace_
+ .as_ref()
+ .is_none_or(|value| *value != namespace_)
+ {
+ continue;
+ }
+ if attribute_name.name != attribute {
+ continue;
+ }
+ if let Some(namespace_) = attribute_namespace {
+ if attribute_name
+ .namespace_
+ .as_ref()
+ .is_some_and(|value| *value == namespace_)
+ {
+ return true;
+ }
+ } else if attribute_name.namespace_.is_none() {
+ return true;
+ }
+ }
+ false
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#built-in-animating-url-attributes-list
+fn built_in_animating_url_attributes_list_contains(
+ element_name: &SanitizerName,
+ attribute_name: &SanitizerName,
+) -> bool {
+ if element_name.namespace_.as_ref().is_none_or(|value| *value != SVG) || attribute_name.namespace_.is_some() {
+ return false;
+ }
+ if attribute_name.name != "attributeName" {
+ return false;
+ }
+ ["animate", "animateTransform", "set"]
+ .iter()
+ .any(|name| element_name.name == *name)
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sanitizer-config-allows-an-attribute
+pub(crate) fn sanitizer_config_allows_attribute(
+ local_name: &Utf16String,
+ namespace_: Option<&Utf16String>,
+ value: Utf16View<'_>,
+ element_local_name: &Utf16String,
+ element_namespace: Option<&Utf16String>,
+ configuration: &SanitizerConfiguration,
+) -> bool {
+ // 1. Let attrName be «[ "name" → localName, "namespace" → namespace ]».
+ let attribute_name = SanitizerName {
+ name: local_name.clone(),
+ namespace_: namespace_.cloned(),
+ };
+
+ // 2. Let elementName be «[ "name" → elementLocalName, "namespace" → elementNamespace ]».
+ let element_name = SanitizerName {
+ name: element_local_name.clone(),
+ namespace_: element_namespace.cloned(),
+ };
+
+ // 3. Let elementWithLocalAttributes be «[ ]».
+ // 4. If configuration["elements"] exists and there is an item element in configuration["elements"] whose name
+ // member is elementLocalName and whose namespace member is elementNamespace, then set
+ // elementWithLocalAttributes to element.
+ let element_with_local_attributes =
+ find_element(configuration.elements.as_deref(), element_local_name, element_namespace);
+ let no_attributes = None;
+ let local_attributes = element_with_local_attributes.map_or(&no_attributes, |element| &element.attributes);
+ let local_remove_attributes =
+ element_with_local_attributes.map_or(&no_attributes, |element| &element.remove_attributes);
+
+ // 5. If elementWithLocalAttributes["removeAttributes"] exists and elementWithLocalAttributes["removeAttributes"]
+ // contains attrName, then return false.
+ if sanitizer_list_contains(local_remove_attributes.as_deref(), &attribute_name) {
+ return false;
+ }
+ // 6. Otherwise, if configuration["attributes"] exists:
+ else if let Some(attributes) = &configuration.attributes {
+ // 1. If configuration["attributes"] does not contain attrName and elementWithLocalAttributes["attributes"]
+ // with default « » does not contain attrName, and if "data-" is not a code unit prefix of localName or
+ // namespace is not null or configuration["dataAttributes"] is not true, then return false.
+ if !attributes.contains(&attribute_name)
+ && !sanitizer_list_contains(local_attributes.as_deref(), &attribute_name)
+ && (!Utf16View::of_string(local_name).starts_with(Utf16View::Ascii(b"data-"))
+ || namespace_.is_some()
+ || configuration.data_attributes != Some(true))
+ {
+ return false;
+ }
+ }
+ // 7. Otherwise:
+ else {
+ // 1. If elementWithLocalAttributes["attributes"] exists and elementWithLocalAttributes["attributes"] does not
+ // contain attrName, then return false.
+ if local_attributes
+ .as_ref()
+ .is_some_and(|list| !list.contains(&attribute_name))
+ {
+ return false;
+ }
+
+ // 2. Otherwise, if configuration["removeAttributes"] exists and configuration["removeAttributes"] contains
+ // attrName, then return false.
+ if sanitizer_list_contains(configuration.remove_attributes.as_deref(), &attribute_name) {
+ return false;
+ }
+ }
+
+ // 8. If configuration["javascriptURLs"] is true, then return true.
+ if configuration.javascript_urls == Some(true) {
+ return true;
+ }
+
+ // 9. If the pair (elementName, attrName) matches an entry in the built-in navigating URL attributes list, and if
+ // value contains a javascript: URL, then return false.
+ if built_in_navigating_url_attributes_list_matches(&element_name, &attribute_name)
+ && contains_a_javascript_url(value)
+ {
+ return false;
+ }
+
+ // 10. If elementNamespace is the MathML namespace, localName is "href", namespace is null or the XLink namespace,
+ // and value contains a javascript: URL, then return false.
+ if element_namespace.is_some_and(|value| *value == MATHML)
+ && *local_name == "href"
+ && namespace_.is_none_or(|value| *value == XLINK)
+ && contains_a_javascript_url(value)
+ {
+ return false;
+ }
+
+ // 11. If the built-in animating URL attributes list contains the pair (elementName, attrName), and value is "href"
+ // or "xlink:href", then return false.
+ if built_in_animating_url_attributes_list_contains(&element_name, &attribute_name)
+ && (value == "href" || value == "xlink:href")
+ {
+ return false;
+ }
+
+ // 12. Return true.
+ true
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#built-in-non-replaceable-elements-list
+pub(crate) fn built_in_non_replaceable_elements_list_contains(element: &SanitizerName) -> bool {
+ let Some(namespace_) = &element.namespace_ else {
+ return false;
+ };
+ (element.name == "html" && *namespace_ == HTML)
+ || (element.name == "svg" && *namespace_ == SVG)
+ || (element.name == "math" && *namespace_ == MATHML)
+}
+
+fn name_with_namespace(name: &str, namespace_: Option<&str>) -> SanitizerName {
+ SanitizerName {
+ name: Utf16String::from_utf8(name),
+ namespace_: namespace_.map(Utf16String::from_utf8),
+ }
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#built-in-safe-baseline-configuration
+pub(crate) fn built_in_safe_baseline_configuration() -> &'static SanitizerConfiguration {
+ // The built-in safe baseline configuration is a SanitizerConfig. Its removeElements list consists of all HTML
+ // elements normatively marked as Unsafe within their individual definitions, along with the obsolete frame
+ // element, and the SVG script and SVG use elements, and its removeAttributes list is empty.
+ static CONFIGURATION: OnceLock<SanitizerConfiguration> = OnceLock::new();
+ CONFIGURATION.get_or_init(|| SanitizerConfiguration {
+ remove_elements: Some(vec![
+ name_with_namespace("base", Some(HTML)),
+ name_with_namespace("embed", Some(HTML)),
+ name_with_namespace("frame", Some(HTML)),
+ name_with_namespace("iframe", Some(HTML)),
+ name_with_namespace("object", Some(HTML)),
+ name_with_namespace("script", Some(HTML)),
+ name_with_namespace("script", Some(SVG)),
+ name_with_namespace("use", Some(SVG)),
+ ]),
+ remove_attributes: Some(Vec::new()),
+ ..Default::default()
+ })
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#built-in-safe-default-configuration
+pub(crate) fn built_in_safe_default_configuration() -> &'static SanitizerConfiguration {
+ static CONFIGURATION: OnceLock<SanitizerConfiguration> = OnceLock::new();
+ CONFIGURATION.get_or_init(|| {
+ let attribute_list = |attributes: &str| attributes.split(' ').filter(|name| !name.is_empty()).map(|name| name_with_namespace(name, None)).collect::<Vec<_>>();
+ let mut configuration = SanitizerConfiguration::default();
+ // elements
+ // All HTML elements normatively categorized as Default within their individual definitions, alongside the
+ // MathML and SVG elements listed in the table below. Attributes included in those definitions are included
+ // in each element's respective attributes list.
+ const HTML_ELEMENTS: &[(&str, &str)] = &[
+ ("html", ""),
+ ("head", ""),
+ ("title", ""),
+ ("body", ""),
+ ("article", ""),
+ ("section", ""),
+ ("nav", ""),
+ ("aside", ""),
+ ("h1", ""),
+ ("h2", ""),
+ ("h3", ""),
+ ("h4", ""),
+ ("h5", ""),
+ ("h6", ""),
+ ("hgroup", ""),
+ ("header", ""),
+ ("footer", ""),
+ ("address", ""),
+ ("p", ""),
+ ("hr", ""),
+ ("pre", ""),
+ ("blockquote", "cite"),
+ ("ol", "reversed start type"),
+ ("ul", ""),
+ ("menu", ""),
+ ("li", "value"),
+ ("dl", ""),
+ ("dt", ""),
+ ("dd", ""),
+ ("figure", ""),
+ ("figcaption", ""),
+ ("main", ""),
+ ("search", ""),
+ ("div", ""),
+ ("a", "href hreflang type"),
+ ("em", ""),
+ ("strong", ""),
+ ("small", ""),
+ ("s", ""),
+ ("cite", ""),
+ ("q", ""),
+ ("dfn", ""),
+ ("abbr", ""),
+ ("ruby", ""),
+ ("rt", ""),
+ ("rp", ""),
+ ("data", "value"),
+ ("time", "datetime"),
+ ("code", ""),
+ ("var", ""),
+ ("samp", ""),
+ ("kbd", ""),
+ ("sub", ""),
+ ("sup", ""),
+ ("i", ""),
+ ("b", ""),
+ ("u", ""),
+ ("mark", ""),
+ ("bdi", ""),
+ ("bdo", ""),
+ ("span", ""),
+ ("br", ""),
+ ("wbr", ""),
+ ("ins", "cite datetime"),
+ ("del", "cite datetime"),
+ ("table", ""),
+ ("caption", ""),
+ ("colgroup", "span"),
+ ("col", "span"),
+ ("tbody", ""),
+ ("thead", ""),
+ ("tfoot", ""),
+ ("tr", ""),
+ ("td", "colspan headers rowspan"),
+ ("th", "abbr colspan headers rowspan scope"),
+ ];
+ const MATHML_ELEMENTS: &[(&str, &str)] = &[
+ ("a", "href hreflang type"),
+ ("math", ""),
+ ("merror", ""),
+ ("mfrac", ""),
+ ("mi", ""),
+ ("mmultiscripts", ""),
+ ("mn", ""),
+ ("mo", "fence form largeop lspace maxsize minsize movablelimits rspace separator stretchy symmetric"),
+ ("mover", "accent"),
+ ("mpadded", "depth height lspace voffset width"),
+ ("mphantom", ""),
+ ("mprescripts", ""),
+ ("mroot", ""),
+ ("mrow", ""),
+ ("ms", ""),
+ ("mspace", "depth height width"),
+ ("msqrt", ""),
+ ("mstyle", ""),
+ ("msub", ""),
+ ("msubsup", ""),
+ ("msup", ""),
+ ("mtable", ""),
+ ("mtd", "columnspan rowspan"),
+ ("mtext", ""),
+ ("mtr", ""),
+ ("munder", "accentunder"),
+ ("munderover", "accent accentunder"),
+ ("semantics", ""),
+ ];
+ const SVG_ELEMENTS: &[(&str, &str)] = &[
+ ("a", "href hreflang type"),
+ ("circle", "cx cy pathLength r"),
+ ("defs", ""),
+ ("desc", ""),
+ ("ellipse", "cx cy pathLength rx ry"),
+ ("foreignObject", "height width x y"),
+ ("g", ""),
+ ("line", "pathLength x1 x2 y1 y2"),
+ ("marker", "markerHeight markerUnits markerWidth orient preserveAspectRatio refX refY viewBox"),
+ ("metadata", ""),
+ ("path", "d pathLength"),
+ ("polygon", "pathLength points"),
+ ("polyline", "pathLength points"),
+ ("rect", "height pathLength rx ry width x y"),
+ ("svg", "height preserveAspectRatio viewBox width x y"),
+ ("text", "dx dy lengthAdjust rotate textLength x y"),
+ ("textPath", "lengthAdjust method path side spacing startOffset textLength"),
+ ("title", ""),
+ ("tspan", "dx dy lengthAdjust rotate textLength x y"),
+ ];
+ let mut elements = Vec::new();
+ for (list, namespace_) in [(HTML_ELEMENTS, HTML), (MATHML_ELEMENTS, MATHML), (SVG_ELEMENTS, SVG)] {
+ for &(name, attributes) in list {
+ elements.push(SanitizerElementWithAttributes { element: name_with_namespace(name, Some(namespace_)), attributes: Some(attribute_list(attributes)), remove_attributes: None });
+ }
+ }
+ configuration.elements = Some(elements);
+ // processingInstructions
+ // « »
+ configuration.processing_instructions = Some(Vec::new());
+ // attributes
+ configuration.attributes = Some(attribute_list("dir lang title alignment-baseline baseline-shift clip-path clip-rule color color-interpolation cursor direction display displaystyle dominant-baseline fill fill-opacity fill-rule font-family font-size font-size-adjust font-stretch font-style font-variant font-weight letter-spacing marker-end marker-mid marker-start mathbackground mathcolor mathsize opacity paint-order pointer-events scriptlevel shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-overflow text-rendering transform transform-origin unicode-bidi vector-effect visibility white-space word-spacing writing-mode"));
+ // comments
+ // false
+ configuration.comments = Some(false);
+ // dataAttributes
+ // false
+ configuration.data_attributes = Some(false);
+ // javascriptURLs
+ // false
+ configuration.javascript_urls = Some(false);
+ configuration
+ })
+}
+
+#[derive(libjs_rust::api::Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum SanitizerInput {
+ Sanitizer(Ref<Sanitizer>),
+ Config(#[gc(untraced)] SanitizerConfig),
+ Preset(#[gc(untraced)] SanitizerPresets),
+}
+
+#[derive(libjs_rust::api::Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum SanitizerOptions {
+ Dictionary(Option<SanitizerInput>),
+ Trusted(#[gc(untraced)] Option<Arc<SanitizerConfiguration>>),
+}
+
+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#get-a-sanitizer-config-from-options
+pub(crate) fn get_a_sanitizer_config_from_options<'a>(
+ options: &'a SanitizerOptions,
+ safe: bool,
+) -> WebIdlResult<Option<SanitizerConfiguration>> {
+ enum ConfigurationInput<'a> {
+ Empty,
+ Sanitizer(&'a Sanitizer),
+ Dictionary(&'a SanitizerConfig),
+ Configuration(&'a SanitizerConfiguration),
+ }
+
+ // 1. Let sanitizerInput be null.
+ let mut sanitizer_input = ConfigurationInput::Empty;
+ let set_sanitizer_input = |sanitizer: &'a SanitizerInput| {
+ match sanitizer {
+ SanitizerInput::Config(config) => ConfigurationInput::Dictionary(config),
+ SanitizerInput::Preset(preset) => {
+ // 1. Assert: sanitizerInput is "default".
+ assert!(*preset == SanitizerPresets::Default);
+
+ // 2. Set sanitizerInput to the built-in safe default configuration.
+ ConfigurationInput::Configuration(built_in_safe_default_configuration())
+ }
+ SanitizerInput::Sanitizer(sanitizer) => ConfigurationInput::Sanitizer(sanitizer),
+ }
+ };
+
+ // 2. If options is a TrustedHTMLParserOptions:
+ if let SanitizerOptions::Trusted(configuration) = options {
+ // 1. If options's sanitizer configuration is null:
+ if configuration.is_none() {
+ // 1. Assert: safe is false.
+ assert!(!safe);
+
+ // 2. Return null.
+ return Ok(None);
+ }
+
+ // 2. Set sanitizerInput to options's sanitizer configuration.
+ sanitizer_input = ConfigurationInput::Configuration(configuration.as_ref().unwrap());
+ }
+
+ // 3. Otherwise, if options["sanitizer"] exists, then set sanitizerInput to options["sanitizer"].
+ let has_sanitizer = match options {
+ SanitizerOptions::Trusted(_) => true,
+ SanitizerOptions::Dictionary(Some(input)) => {
+ sanitizer_input = set_sanitizer_input(input);
+ true
+ }
+ SanitizerOptions::Dictionary(None) => false,
+ };
+ if !has_sanitizer {
+ // 4. Otherwise, if safe is false, then return null.
+ if !safe {
+ return Ok(None);
+ }
+
+ // 5. Otherwise, set sanitizerInput to "default".
+ // NB: The following step sets sanitizerInput to the built-in safe default configuration.
+ sanitizer_input = ConfigurationInput::Configuration(built_in_safe_default_configuration());
+ }
+
+ // 6. Assert: sanitizerInput is either a Sanitizer instance, a SanitizerPresets member, or a SanitizerConfig
+ // dictionary.
+ // 7. If sanitizerInput is a string:
+ // 1. Assert: sanitizerInput is "default".
+ // 2. Set sanitizerInput to the built-in safe default configuration.
+ // NB: This was done above.
+ // 8. If sanitizerInput is a Sanitizer, then set sanitizerInput to sanitizerInput's configuration.
+ // 9. Assert: sanitizerInput is a dictionary.
+ let clone = match sanitizer_input {
+ ConfigurationInput::Empty => unreachable!("sanitizer input has been selected"),
+ ConfigurationInput::Sanitizer(sanitizer) => sanitizer.configuration(),
+ ConfigurationInput::Dictionary(config) => canonicalize_sanitizer_config(config),
+ ConfigurationInput::Configuration(config) => config.clone(),
+ };
+
+ // 10. Let sanitizer be a new Sanitizer object.
+ // 11. Let permissiveDefaults be true if safe is false; false otherwise.
+ let permissive_defaults = if safe {
+ PermissiveDefaults::No
+ } else {
+ PermissiveDefaults::Yes
+ };
+
+ // 12. Configure sanitizer given sanitizerInput and permissiveDefaults.
+ // 13. Let configuration be sanitizer's configuration.
+ let mut configuration = configure_sanitizer_configuration(clone, permissive_defaults)?;
+
+ // 14. If safe is true, then remove unsafe from configuration.
+ if safe {
+ remove_unsafe_from_sanitizer_config(&mut configuration);
+ }
+
+ // 15. Assert: configuration is valid.
+ assert!(sanitizer_configuration_is_valid(&configuration));
+
+ // 16. Return configuration.
+ // NOTE: The returned SanitizerConfig is a fresh copy, so removing unsafe items from it never affects a Sanitizer
+ // object or SanitizerConfig dictionary that script can observe.
+ Ok(Some(configuration))
+}
+
+// https://w3c.github.io/trusted-types/dist/spec/#get-a-sanitizer-from-dictionary
+// NB: The steps of "get a sanitizer from dictionary" after sanitizerInput has been found to be non-null.
+pub(crate) fn get_a_sanitizer_from_sanitizer_input(
+ vm: &libjs_rust::api::Vm,
+ sanitizer_input: &SanitizerInput,
+) -> WebIdlResult<Ref<Sanitizer>> {
+ // 3. Let configuration be null.
+ let configuration = match sanitizer_input {
+ // 4. If sanitizerInput is a SanitizerPresets:
+ SanitizerInput::Preset(preset) => {
+ // 1. Assert: sanitizerInput is "default".
+ assert!(*preset == SanitizerPresets::Default);
+
+ // 2. Set configuration to the built-in safe default configuration.
+ built_in_safe_default_configuration().clone()
+ }
+
+ // 5. Otherwise, if sanitizerInput is a Sanitizer:
+ // 1. Set configuration to sanitizerInput's configuration.
+ SanitizerInput::Sanitizer(sanitizer) => sanitizer.configuration(),
+
+ // 6. Otherwise, if sanitizerInput is a SanitizerConfig:
+ // 1. Set configuration to sanitizerInput.
+ SanitizerInput::Config(config) => canonicalize_sanitizer_config(config),
+ };
+
+ // 7. Assert: configuration is not null.
+ // 8. Let sanitizer be a new Sanitizer in realm.
+ // 9. Configure sanitizer given configuration and true.
+ let canonical_configuration = configure_sanitizer_configuration(configuration, PermissiveDefaults::Yes)?;
+
+ // 10. Return sanitizer.
+ Ok(Sanitizer::create_with_configuration(vm, canonical_configuration))
+}
+
+// NB: SanitizerInputKind in SanitizerConfiguration.cpp matches this.
+#[derive(Clone, Copy)]
+#[repr(u8)]
+#[allow(dead_code, reason = "C++ constructs the variants")]
+pub(crate) enum SanitizerInputKind {
+ None,
+ DefaultPreset,
+ Config,
+ Sanitizer,
+ TrustedOptions,
+}
+
+// NB: SanitizerConfigurationStatus in SanitizerConfiguration.cpp matches this.
+#[repr(u8)]
+pub(crate) enum SanitizerConfigurationStatus {
+ Null,
+ Configuration,
+ Invalid,
+}
+
+// NB: SanitizerOptionalBoolean in SanitizerConfiguration.cpp matches this.
+#[derive(Clone, Copy)]
+#[repr(u8)]
+#[allow(dead_code, reason = "C++ constructs the variants")]
+pub(crate) enum OptionalBooleanAbi {
+ Absent,
+ False,
+ True,
+}
+
+impl From<OptionalBooleanAbi> for Option<bool> {
+ fn from(value: OptionalBooleanAbi) -> Self {
+ match value {
+ OptionalBooleanAbi::Absent => None,
+ OptionalBooleanAbi::False => Some(false),
+ OptionalBooleanAbi::True => Some(true),
+ }
+ }
+}
+
+#[repr(C)]
+pub(crate) struct NameInputAbi {
+ is_string: bool,
+ name: usize,
+ namespace_: usize,
+}
+
+#[repr(C)]
+pub(crate) struct ListInputAbi<'a, T> {
+ present: bool,
+ values: ak::Span<'a, T>,
+}
+
+#[repr(C)]
+pub(crate) struct ElementInputAbi<'a> {
+ name: NameInputAbi,
+ attributes: ListInputAbi<'a, NameInputAbi>,
+ remove_attributes: ListInputAbi<'a, NameInputAbi>,
+}
+
+#[repr(C)]
+pub(crate) struct ConfigInputAbi<'a> {
+ elements: ListInputAbi<'a, ElementInputAbi<'a>>,
+ remove_elements: ListInputAbi<'a, NameInputAbi>,
+ replace_with_children_elements: ListInputAbi<'a, NameInputAbi>,
+ processing_instructions: ListInputAbi<'a, NameInputAbi>,
+ remove_processing_instructions: ListInputAbi<'a, NameInputAbi>,
+ attributes: ListInputAbi<'a, NameInputAbi>,
+ remove_attributes: ListInputAbi<'a, NameInputAbi>,
+ comments: OptionalBooleanAbi,
+ data_attributes: OptionalBooleanAbi,
+ javascript_urls: OptionalBooleanAbi,
+}
+
+impl NameInputAbi {
+ unsafe fn name(&self) -> Utf16String {
+ // SAFETY: C++ lends a live string for the conversion.
+ unsafe { Utf16String::from_raw_borrowed(self.name) }
+ }
+ unsafe fn namespace(&self) -> Option<Utf16String> {
+ // SAFETY: A nonzero namespace is a live string lent by C++.
+ (self.namespace_ != 0).then(|| unsafe { Utf16String::from_raw_borrowed(self.namespace_) })
+ }
+ unsafe fn element(&self) -> SanitizerElement {
+ // SAFETY: C++ lends the strings for the conversion.
+ let name = unsafe { self.name() };
+ if self.is_string {
+ SanitizerElement::DOMString(name)
+ } else {
+ SanitizerElement::SanitizerElementNamespace(SanitizerElementNamespace {
+ name,
+ // SAFETY: C++ lends the namespace for the conversion.
+ namespace: unsafe { self.namespace() },
+ })
+ }
+ }
+ unsafe fn attribute(&self) -> SanitizerAttribute {
+ // SAFETY: C++ lends the strings for the conversion.
+ let name = unsafe { self.name() };
+ if self.is_string {
+ SanitizerAttribute::DOMString(name)
+ } else {
+ SanitizerAttribute::SanitizerAttributeNamespace(SanitizerAttributeNamespace {
+ name,
+ // SAFETY: C++ lends the namespace for the conversion.
+ namespace: unsafe { self.namespace() },
+ })
+ }
+ }
+ unsafe fn pi(&self) -> SanitizerPI {
+ // SAFETY: C++ lends the target for the conversion.
+ let target = unsafe { self.name() };
+ if self.is_string {
+ SanitizerPI::DOMString(target)
+ } else {
+ SanitizerPI::SanitizerProcessingInstruction(SanitizerProcessingInstruction { target })
+ }
+ }
+}
+
+impl<T> ListInputAbi<'_, T> {
+ fn convert<R>(&self, convert: impl FnMut(&T) -> R) -> Option<Vec<R>> {
+ self.present
+ .then(|| self.values.as_slice().iter().map(convert).collect())
+ }
+}
+
+impl ConfigInputAbi<'_> {
+ /// Copies the lent view into the Rust dictionary.
+ ///
+ /// # Safety
+ ///
+ /// Every list buffer and string of the view must be live for the call.
+ unsafe fn config(&self) -> SanitizerConfig {
+ // SAFETY: C++ lends all list buffers and strings until conversion completes.
+ unsafe {
+ SanitizerConfig {
+ elements: self.elements.convert(|element| {
+ if element.name.is_string {
+ sanitizer::SanitizerElementWithAttributes::DOMString(element.name.name())
+ } else {
+ sanitizer::SanitizerElementWithAttributes::SanitizerElementNamespaceWithAttributes(
+ SanitizerElementNamespaceWithAttributes {
+ parent: SanitizerElementNamespace {
+ name: element.name.name(),
+ namespace: element.name.namespace(),
+ },
+ attributes: element.attributes.convert(|name| name.attribute()),
+ remove_attributes: element.remove_attributes.convert(|name| name.attribute()),
+ },
+ )
+ }
+ }),
+ remove_elements: self.remove_elements.convert(|name| name.element()),
+ replace_with_children_elements: self.replace_with_children_elements.convert(|name| name.element()),
+ processing_instructions: self.processing_instructions.convert(|name| name.pi()),
+ remove_processing_instructions: self.remove_processing_instructions.convert(|name| name.pi()),
+ attributes: self.attributes.convert(|name| name.attribute()),
+ remove_attributes: self.remove_attributes.convert(|name| name.attribute()),
+ comments: self.comments.into(),
+ data_attributes: self.data_attributes.into(),
+ javascript_ur_ls: self.javascript_urls.into(),
+ }
+ }
+ }
+}
+
+unsafe fn input_from_abi(kind: SanitizerInputKind, input: *const c_void) -> SanitizerInput {
+ match kind {
+ SanitizerInputKind::DefaultPreset => SanitizerInput::Preset(SanitizerPresets::Default),
+ // SAFETY: C++ passes a live view whose buffers and strings outlive this conversion.
+ SanitizerInputKind::Config => {
+ SanitizerInput::Config(unsafe { (&*input.cast::<ConfigInputAbi<'_>>()).config() })
+ }
+ // SAFETY: C++ passes a live Sanitizer cell.
+ SanitizerInputKind::Sanitizer => SanitizerInput::Sanitizer(unsafe { cell_from_abi(input.cast_mut()) }),
+ SanitizerInputKind::None | SanitizerInputKind::TrustedOptions => {
+ unreachable!("C++ passes a sanitizer input kind")
+ }
+ }
+}
+
+/// Retains an immutable configuration snapshot.
+///
+/// # Safety
+///
+/// `configuration` must be a live Arc-owned SanitizerConfiguration.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_sanitizer_configuration_retain(configuration: *const SanitizerConfiguration) {
+ // SAFETY: The caller keeps an Arc reference alive for this call.
+ unsafe { Arc::increment_strong_count(configuration) };
+}
+
+/// Releases an immutable configuration snapshot.
+///
+/// # Safety
+///
+/// `configuration` must be null or an Arc-owned SanitizerConfiguration reference handed to the caller.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_sanitizer_configuration_release(configuration: *const SanitizerConfiguration) {
+ if !configuration.is_null() {
+ // SAFETY: C++ hands back its owned Arc reference.
+ drop(unsafe { Arc::from_raw(configuration) });
+ }
+}
+
+/// Obtains a configuration from converted HTML options.
+///
+/// # Safety
+///
+/// `input` must be the live configuration view, Sanitizer cell, or snapshot identified by `kind`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_get_a_sanitizer_config_from_options(
+ kind: SanitizerInputKind,
+ input: *const c_void,
+ safe: bool,
+ out_configuration: &mut *const SanitizerConfiguration,
+) -> SanitizerConfigurationStatus {
+ let options = match kind {
+ SanitizerInputKind::TrustedOptions => {
+ let snapshot = if input.is_null() {
+ None
+ } else {
+ let pointer = input.cast::<SanitizerConfiguration>();
+ // SAFETY: C++ holds a live Arc snapshot. This acquires a reference for the options.
+ unsafe {
+ Arc::increment_strong_count(pointer);
+ Some(Arc::from_raw(pointer))
+ }
+ };
+ SanitizerOptions::Trusted(snapshot)
+ }
+ SanitizerInputKind::None => SanitizerOptions::Dictionary(None),
+ // SAFETY: The caller lends the indicated input until this function returns.
+ _ => SanitizerOptions::Dictionary(Some(unsafe { input_from_abi(kind, input) })),
+ };
+ match get_a_sanitizer_config_from_options(&options, safe) {
+ Ok(Some(configuration)) => {
+ *out_configuration = Arc::into_raw(Arc::new(configuration));
+ SanitizerConfigurationStatus::Configuration
+ }
+ Ok(None) => SanitizerConfigurationStatus::Null,
+ Err(_) => SanitizerConfigurationStatus::Invalid,
+ }
+}
+
+/// Obtains a Sanitizer from converted input.
+///
+/// # Safety
+///
+/// `input` must be the live configuration view or Sanitizer cell identified by `kind`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_get_a_sanitizer_from_sanitizer_input(
+ vm: &libjs_rust::api::Vm,
+ kind: SanitizerInputKind,
+ input: *const c_void,
+) -> *mut c_void {
+ // SAFETY: The caller lends the indicated input until this function returns.
+ let input = unsafe { input_from_abi(kind, input) };
+ match get_a_sanitizer_from_sanitizer_input(vm, &input) {
+ Ok(sanitizer) => cell_into_abi(sanitizer),
+ Err(_) => core::ptr::null_mut(),
+ }
+}
+
+#[repr(C)]
+pub(crate) struct StringViewAbi<'a> {
+ latin1: ak::Span<'a, u8>,
+ utf16: ak::Span<'a, u16>,
+}
+
+impl StringViewAbi<'_> {
+ fn view(&self) -> Utf16View<'_> {
+ if self.utf16.as_slice().is_empty() {
+ Utf16View::Latin1(self.latin1.as_slice())
+ } else {
+ Utf16View::Utf16(self.utf16.as_slice())
+ }
+ }
+}
+
+unsafe extern "C" {
+ fn web_sanitizer_event_handler_content_attributes(out: &mut ak::Span<'static, usize>);
+}
+
+fn event_handler_content_attributes() -> &'static [usize] {
+ let mut names = ak::Span::default();
+ // SAFETY: C++ lends its immutable process-lifetime list of live string representations.
+ unsafe { web_sanitizer_event_handler_content_attributes(&mut names) };
+ names.as_slice()
+}
+
+/// Checks whether the configuration allows comments.
+///
+/// # Safety
+///
+/// `configuration` must point to a live SanitizerConfiguration.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_sanitizer_config_allows_comments(configuration: &SanitizerConfiguration) -> bool {
+ sanitizer_config_allows_comments(configuration)
+}
+
+/// Checks whether the configuration allows a processing-instruction target.
+///
+/// # Safety
+///
+/// `configuration` and the target's buffers must be live for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_sanitizer_config_allows_processing_instruction_target(
+ configuration: &SanitizerConfiguration,
+ target: StringViewAbi<'_>,
+) -> bool {
+ sanitizer_config_allows_processing_instruction_target(target.view(), configuration)
+}
+
+/// Returns the sanitizer action for the element name.
+///
+/// # Safety
+///
+/// The configuration and nonzero string representations must be live for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_sanitizer_action_for_element_name(
+ configuration: &SanitizerConfiguration,
+ name: usize,
+ namespace_: usize,
+) -> SanitizerAction {
+ // SAFETY: C++ lends the strings for the query.
+ let (name, namespace_) = unsafe {
+ (
+ Utf16String::from_raw_borrowed(name),
+ (namespace_ != 0).then(|| Utf16String::from_raw_borrowed(namespace_)),
+ )
+ };
+ sanitizer_action_for_element_name(&name, namespace_.as_ref(), configuration)
+}
+
+/// Checks whether the configuration allows an attribute.
+///
+/// # Safety
+///
+/// The configuration, value buffers, and nonzero string representations must be live for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_sanitizer_config_allows_attribute(
+ configuration: &SanitizerConfiguration,
+ name: usize,
+ namespace_: usize,
+ value: StringViewAbi<'_>,
+ element_name: usize,
+ element_namespace: usize,
+) -> bool {
+ // SAFETY: C++ lends all strings for the query.
+ let (name, namespace_, element_name, element_namespace) = unsafe {
+ (
+ Utf16String::from_raw_borrowed(name),
+ (namespace_ != 0).then(|| Utf16String::from_raw_borrowed(namespace_)),
+ Utf16String::from_raw_borrowed(element_name),
+ (element_namespace != 0).then(|| Utf16String::from_raw_borrowed(element_namespace)),
+ )
+ };
+ sanitizer_config_allows_attribute(
+ &name,
+ namespace_.as_ref(),
+ value.view(),
+ &element_name,
+ element_namespace.as_ref(),
+ configuration,
+ )
+}
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp
index a88037e7abf..64f6dcd9020 100644
--- a/Libraries/LibWeb/DOM/Element.cpp
+++ b/Libraries/LibWeb/DOM/Element.cpp
@@ -7399,3 +7399,15 @@ WebIDL::ExceptionOr<void> set_attribute_ns(DOM::Element& element, Optional<Utf16
}
}
+
+namespace Web::DOM {
+
+extern "C" bool web_dom_is_valid_attribute_local_name(FlatPtr name);
+
+bool web_dom_is_valid_attribute_local_name(FlatPtr name)
+{
+ auto string = Utf16String::from_raw(name);
+ return is_valid_attribute_local_name(string.utf16_view());
+}
+
+}
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 19f460c5d9f..9bb1974ab47 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -826,7 +826,7 @@ class RadioNodeList;
class RemoteNavigable;
class RemoteWindow;
class Sanitizer;
-struct SanitizerConfiguration;
+class SanitizerConfiguration;
class ScriptRegistry;
class SessionHistoryEntry;
class SharedResourceRequest;
diff --git a/Libraries/LibWeb/HTML/Sanitizer.cpp b/Libraries/LibWeb/HTML/Sanitizer.cpp
index 396963f724c..cc0010ec0d4 100644
--- a/Libraries/LibWeb/HTML/Sanitizer.cpp
+++ b/Libraries/LibWeb/HTML/Sanitizer.cpp
@@ -4,587 +4,15 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/QuickSort.h>
-#include <LibGC/Heap.h>
-#include <LibWeb/Bindings/Sanitizer.h>
#include <LibWeb/HTML/Sanitizer.h>
namespace Web::HTML {
-GC_DEFINE_ALLOCATOR(Sanitizer);
+extern "C" void const* web_rust_sanitizer_configuration(Sanitizer const*);
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-constructor
-WebIDL::ExceptionOr<GC::Ref<Sanitizer>> Sanitizer::create(Variant<Bindings::SanitizerConfig, Bindings::SanitizerPresets> const& configuration)
+SanitizerConfiguration Sanitizer::configuration() const
{
- // 1. If configuration is a SanitizerPresets string:
- // 1. Assert: configuration is "default".
- // 2. Set configuration to the built-in safe default configuration.
- auto fresh_configuration = configuration.visit(
- [](Bindings::SanitizerConfig const& config) { return canonicalize_sanitizer_config(config); },
- [](Bindings::SanitizerPresets preset) {
- VERIFY(preset == Bindings::SanitizerPresets::Default);
- return built_in_safe_default_configuration();
- });
-
- // 2. Configure this given configuration and true.
- auto canonical_configuration = TRY(configure_sanitizer_configuration(move(fresh_configuration), PermissiveDefaults::Yes));
- return create_with_configuration(move(canonical_configuration));
-}
-
-GC::Ref<Sanitizer> Sanitizer::create_with_configuration(SanitizerConfiguration configuration)
-{
- VERIFY(sanitizer_configuration_is_valid(configuration));
- return GC::Heap::the().allocate<Sanitizer>(move(configuration));
-}
-
-Sanitizer::Sanitizer(SanitizerConfiguration configuration)
- : m_configuration(move(configuration))
-{
-}
-
-Sanitizer::~Sanitizer() = default;
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#compare-sanitizer-items
-static bool compare_sanitizer_items(SanitizerName const& item_a, SanitizerName const& item_b)
-{
- // 1. Let namespaceA be itemA["namespace"].
- auto const& namespace_a = item_a.namespace_;
-
- // 2. Let namespaceB be itemB["namespace"].
- auto const& namespace_b = item_b.namespace_;
-
- // 3. If namespaceA is null:
- if (!namespace_a.has_value()) {
- // 1. If namespaceB is not null, then return true.
- if (namespace_b.has_value())
- return true;
- }
- // 4. Otherwise:
- else {
- // 1. If namespaceB is null, then return false.
- if (!namespace_b.has_value())
- return false;
-
- // 2. If namespaceA is code unit less than namespaceB, then return true.
- if (namespace_a->view().is_code_unit_less_than(namespace_b->view()))
- return true;
-
- // 3. If namespaceA is not namespaceB, then return false.
- if (*namespace_a != *namespace_b)
- return false;
- }
-
- // 5. If itemA["name"] is code unit less than itemB["name"], then return true.
- if (item_a.name.view().is_code_unit_less_than(item_b.name.view()))
- return true;
-
- // 6. Return false.
- return false;
-}
-
-static void sort_sanitizer_items(Vector<SanitizerName>& list)
-{
- quick_sort(list, compare_sanitizer_items);
-}
-
-static void sort_processing_instructions(Vector<Utf16String>& list)
-{
- quick_sort(list, [](auto const& pi_a, auto const& pi_b) { return pi_a.utf16_view().is_code_unit_less_than(pi_b.utf16_view()); });
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-get
-Bindings::SanitizerConfig Sanitizer::get() const
-{
- // NOTE: Outside of the get() method, the order of the Sanitizer's elements and attributes is unobservable. By
- // explicitly sorting the result of this method, we give implementations the opportunity to optimize by,
- // for example, using unordered sets internally.
-
- // 1. Let config be this's configuration.
- auto config = m_configuration;
-
- // 2. Assert: config is valid.
- VERIFY(sanitizer_configuration_is_valid(config));
-
- // 3. If config["elements"] exists:
- if (config.elements.has_value()) {
- // 1. For each element of config["elements"]:
- for (auto& element : *config.elements) {
- // 1. If element["attributes"] exists, then set element["attributes"] to the result of sorting
- // element["attributes"], with compare sanitizer items.
- if (element.attributes.has_value())
- sort_sanitizer_items(*element.attributes);
-
- // 2. If element["removeAttributes"] exists, then set element["removeAttributes"] to the result of sorting
- // element["removeAttributes"], with compare sanitizer items.
- if (element.remove_attributes.has_value())
- sort_sanitizer_items(*element.remove_attributes);
- }
-
- // 2. Set config["elements"] to the result of sorting config["elements"], with compare sanitizer items.
- quick_sort(*config.elements, [](auto const& a, auto const& b) { return compare_sanitizer_items(a.element, b.element); });
- }
- // 4. Otherwise:
- else {
- // 1. Set config["removeElements"] to the result of sorting config["removeElements"], with compare sanitizer
- // items.
- sort_sanitizer_items(*config.remove_elements);
- }
-
- // 5. If config["replaceWithChildrenElements"] exists, then set config["replaceWithChildrenElements"] to the result
- // of sorting config["replaceWithChildrenElements"], with compare sanitizer items.
- if (config.replace_with_children_elements.has_value())
- sort_sanitizer_items(*config.replace_with_children_elements);
-
- // 6. If config["processingInstructions"] exists, then set config["processingInstructions"] to the result of
- // sorting config["processingInstructions"], with piA["target"] being code unit less than piB["target"].
- if (config.processing_instructions.has_value())
- sort_processing_instructions(*config.processing_instructions);
- // 7. Otherwise:
- else {
- // 1. Set config["removeProcessingInstructions"] to the result of sorting
- // config["removeProcessingInstructions"], with piA["target"] being code unit less than piB["target"].
- sort_processing_instructions(*config.remove_processing_instructions);
- }
-
- // 8. If config["attributes"] exists, then set config["attributes"] to the result of sorting config["attributes"]
- // given compare sanitizer items.
- if (config.attributes.has_value())
- sort_sanitizer_items(*config.attributes);
- // 9. Otherwise:
- else {
- // 1. Set config["removeAttributes"] to the result of sorting config["removeAttributes"] given compare
- // sanitizer items.
- sort_sanitizer_items(*config.remove_attributes);
- }
-
- // 10. Return config.
- return sanitizer_configuration_to_bindings(config);
-}
-
-// https://infra.spec.whatwg.org/#create-a-set
-static Vector<SanitizerName> create_a_set(Vector<SanitizerName> const& list)
-{
- Vector<SanitizerName> set;
- for (auto const& item : list) {
- if (!sanitizer_list_contains(set, item))
- set.append(item);
- }
- return set;
-}
-
-// https://infra.spec.whatwg.org/#set-difference
-static Vector<SanitizerName> difference(Vector<SanitizerName> const& a, Vector<SanitizerName> const& b)
-{
- Vector<SanitizerName> result;
- for (auto const& item : a) {
- if (!sanitizer_list_contains(b, item))
- result.append(item);
- }
- return result;
-}
-
-// https://infra.spec.whatwg.org/#set-intersection
-static Vector<SanitizerName> intersection(Vector<SanitizerName> const& a, Vector<SanitizerName> const& b)
-{
- Vector<SanitizerName> result;
- for (auto const& item : a) {
- if (sanitizer_list_contains(b, item))
- result.append(item);
- }
- return result;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-allowelement
-bool Sanitizer::allow_element(Variant<Utf16String, Bindings::SanitizerElementNamespaceWithAttributes> const& element_input)
-{
- // 1. Let configuration be this's configuration.
- auto& configuration = m_configuration;
-
- // 2. Assert: configuration is valid.
- VERIFY(sanitizer_configuration_is_valid(configuration));
-
- // 3. Set element to the result of canonicalizing element.
- auto element = canonicalize_sanitizer_element_with_attributes(element_input);
-
- // 4. If configuration["elements"] exists:
- if (configuration.elements.has_value()) {
- // 1. Let modified be the result of removing element from configuration["replaceWithChildrenElements"].
- bool modified = sanitizer_list_remove(configuration.replace_with_children_elements, element.element);
-
- // 2. If configuration["attributes"] exists:
- if (configuration.attributes.has_value()) {
- // 1. If element["attributes"] exists:
- if (element.attributes.has_value()) {
- // 1. Set element["attributes"] to the result of creating a set from element["attributes"].
- element.attributes = create_a_set(*element.attributes);
-
- // 2. Set element["attributes"] to the difference of element["attributes"] and
- // configuration["attributes"].
- element.attributes = difference(*element.attributes, *configuration.attributes);
-
- // 3. If configuration["dataAttributes"] is true, then remove all items item from element["attributes"]
- // where item is a custom data attribute.
- if (configuration.data_attributes == true)
- element.attributes->remove_all_matching([](auto const& item) { return is_custom_data_attribute(item); });
- }
-
- // 2. If element["removeAttributes"] exists:
- if (element.remove_attributes.has_value()) {
- // 1. Set element["removeAttributes"] to the result of creating a set from element["removeAttributes"].
- element.remove_attributes = create_a_set(*element.remove_attributes);
-
- // 2. Set element["removeAttributes"] to the intersection of element["removeAttributes"] and
- // configuration["attributes"].
- element.remove_attributes = intersection(*element.remove_attributes, *configuration.attributes);
- }
- }
- // 3. Otherwise:
- else {
- // 1. If element["attributes"] exists:
- if (element.attributes.has_value()) {
- // 1. Set element["attributes"] to the result of creating a set from element["attributes"].
- element.attributes = create_a_set(*element.attributes);
-
- // 2. Set element["attributes"] to the difference of element["attributes"] and
- // element["removeAttributes"] with default « ».
- element.attributes = difference(*element.attributes, element.remove_attributes.value_or({}));
-
- // 3. Remove element["removeAttributes"].
- element.remove_attributes = {};
-
- // 4. Set element["attributes"] to the difference of element["attributes"] and
- // configuration["removeAttributes"].
- element.attributes = difference(*element.attributes, *configuration.remove_attributes);
- }
-
- // 2. If element["removeAttributes"] exists:
- if (element.remove_attributes.has_value()) {
- // 1. Set element["removeAttributes"] to the result of creating a set from element["removeAttributes"].
- element.remove_attributes = create_a_set(*element.remove_attributes);
-
- // 2. Set element["removeAttributes"] to the difference of element["removeAttributes"] and
- // configuration["removeAttributes"].
- element.remove_attributes = difference(*element.remove_attributes, *configuration.remove_attributes);
- }
- }
-
- // 4. If configuration["elements"] does not contain element:
- auto current_element = configuration.elements->find_if([&](auto const& item) { return item.element == element.element; });
- if (current_element.is_end()) {
- // 1. Append element to configuration["elements"].
- configuration.elements->append(move(element));
-
- // 2. Return true.
- return true;
- }
-
- // 5. Let currentElement be the item in configuration["elements"] whose name member is element's name member
- // and whose namespace member is element's namespace member.
- // 6. If element is equal to currentElement, then return modified.
- if (element == *current_element)
- return modified;
-
- // 7. Remove element from configuration["elements"].
- configuration.elements->remove(current_element.index());
-
- // 8. Append element to configuration["elements"].
- configuration.elements->append(move(element));
-
- // 9. Return true.
- return true;
- }
-
- // 5. Otherwise:
- // 1. If element["attributes"] exists or element["removeAttributes"] with default « » is not empty, then return
- // false.
- if (element.attributes.has_value() || (element.remove_attributes.has_value() && !element.remove_attributes->is_empty()))
- return false;
-
- // 2. Let modified be the result of removing element from configuration["replaceWithChildrenElements"].
- bool modified = sanitizer_list_remove(configuration.replace_with_children_elements, element.element);
-
- // 3. If configuration["removeElements"] does not contain element, then return modified.
- if (!sanitizer_list_contains(*configuration.remove_elements, element.element))
- return modified;
-
- // 4. Remove element from configuration["removeElements"].
- sanitizer_list_remove(configuration.remove_elements, element.element);
-
- // 5. Return true.
- return true;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-removeelement
-bool Sanitizer::remove_element(Variant<Utf16String, Bindings::SanitizerElementNamespace> const& element)
-{
- // The removeElement(element) method steps are to return the result of removing element from this's
- // configuration.
- return remove_an_element_from_sanitizer_config(m_configuration, canonicalize_sanitizer_element(element));
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-replaceelementwithchildren
-bool Sanitizer::replace_element_with_children(Variant<Utf16String, Bindings::SanitizerElementNamespace> const& element_input)
-{
- // 1. Let configuration be this's configuration.
- auto& configuration = m_configuration;
-
- // 2. Assert: configuration is valid.
- VERIFY(sanitizer_configuration_is_valid(configuration));
-
- // 3. Set element to the result of canonicalizing element.
- auto element = canonicalize_sanitizer_element(element_input);
-
- // 4. If the built-in non-replaceable elements list contains element, then return false.
- if (built_in_non_replaceable_elements_list_contains(element))
- return false;
-
- // 5. Let modified be the result of removing element from configuration["elements"].
- bool modified = false;
- if (configuration.elements.has_value())
- modified = configuration.elements->remove_all_matching([&](auto const& item) { return item.element == element; });
-
- // 6. If removing element from configuration["removeElements"] is true, then set modified to true.
- if (sanitizer_list_remove(configuration.remove_elements, element))
- modified = true;
-
- // 7. If configuration["replaceWithChildrenElements"] does not contain element:
- if (!configuration.replace_with_children_elements.has_value() || !sanitizer_list_contains(*configuration.replace_with_children_elements, element)) {
- // 1. Append element to configuration["replaceWithChildrenElements"].
- if (!configuration.replace_with_children_elements.has_value())
- configuration.replace_with_children_elements = Vector<SanitizerName> {};
- configuration.replace_with_children_elements->append(element);
-
- // 2. Return true.
- return true;
- }
-
- // 8. Return modified.
- return modified;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-allowattribute
-bool Sanitizer::allow_attribute(Variant<Utf16String, Bindings::SanitizerAttributeNamespace> const& attribute_input)
-{
- // 1. Let configuration be this's configuration.
- auto& configuration = m_configuration;
-
- // 2. Assert: configuration is valid.
- VERIFY(sanitizer_configuration_is_valid(configuration));
-
- // 3. Set attribute to the result of canonicalizing attribute.
- auto attribute = canonicalize_sanitizer_attribute(attribute_input);
-
- // 4. If configuration["attributes"] exists:
- if (configuration.attributes.has_value()) {
- // 1. If configuration["dataAttributes"] is true and attribute is a custom data attribute, then return false.
- if (configuration.data_attributes == true && is_custom_data_attribute(attribute))
- return false;
-
- // 2. If configuration["attributes"] contains attribute, then return false.
- if (sanitizer_list_contains(*configuration.attributes, attribute))
- return false;
-
- // 3. If configuration["elements"] exists:
- if (configuration.elements.has_value()) {
- // 1. For each element in configuration["elements"]:
- for (auto& element : *configuration.elements) {
- // 1. If element["attributes"] with default « » contains attribute, then remove attribute from
- // element["attributes"].
- sanitizer_list_remove(element.attributes, attribute);
- }
- }
-
- // 4. Append attribute to configuration["attributes"].
- configuration.attributes->append(attribute);
-
- // 5. Return true.
- return true;
- }
-
- // 5. Otherwise:
- // 1. If configuration["removeAttributes"] does not contain attribute, then return false.
- if (!sanitizer_list_contains(*configuration.remove_attributes, attribute))
- return false;
-
- // 2. Remove attribute from configuration["removeAttributes"].
- sanitizer_list_remove(configuration.remove_attributes, attribute);
-
- // 3. Return true.
- return true;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-removeattribute
-bool Sanitizer::remove_attribute(Variant<Utf16String, Bindings::SanitizerAttributeNamespace> const& attribute)
-{
- // The removeAttribute(attribute) method steps are to return the result of removing attribute from this's
- // configuration.
- return remove_an_attribute_from_sanitizer_config(m_configuration, canonicalize_sanitizer_attribute(attribute));
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-setcomments
-bool Sanitizer::set_comments(bool allow)
-{
- // 1. Let configuration be this's configuration.
- auto& configuration = m_configuration;
-
- // 2. Assert: configuration is valid.
- VERIFY(sanitizer_configuration_is_valid(configuration));
-
- // 3. If configuration["comments"] is allow, then return false.
- if (configuration.comments == allow)
- return false;
-
- // 4. Set configuration["comments"] to allow.
- configuration.comments = allow;
-
- // 5. Return true.
- return true;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-setdataattributes
-bool Sanitizer::set_data_attributes(bool allow)
-{
- // 1. Let configuration be this's configuration.
- auto& configuration = m_configuration;
-
- // 2. Assert: configuration is valid.
- VERIFY(sanitizer_configuration_is_valid(configuration));
-
- // 3. If configuration["attributes"] does not exist, then return false.
- if (!configuration.attributes.has_value())
- return false;
-
- // 4. If configuration["dataAttributes"] exists and is equal to allow, then return false.
- if (configuration.data_attributes == allow)
- return false;
-
- // 5. If allow is true:
- if (allow) {
- // 1. If configuration["elements"] exists:
- if (configuration.elements.has_value()) {
- // 1. For each element of configuration["elements"]:
- for (auto& element : *configuration.elements) {
- // 1. If element["attributes"] exists, then remove all items item from element["attributes"] where item
- // is a custom data attribute.
- if (element.attributes.has_value())
- element.attributes->remove_all_matching([](auto const& item) { return is_custom_data_attribute(item); });
- }
- }
-
- // 2. Remove all items item from configuration["attributes"] where item is a custom data attribute.
- configuration.attributes->remove_all_matching([](auto const& item) { return is_custom_data_attribute(item); });
- }
-
- // 6. Set configuration["dataAttributes"] to allow.
- configuration.data_attributes = allow;
-
- // 7. Return true.
- return true;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-setjavascripturls
-bool Sanitizer::set_javascript_urls(bool allow)
-{
- // 1. Let configuration be this's configuration.
- auto& configuration = m_configuration;
-
- // 2. Assert: configuration is valid.
- VERIFY(sanitizer_configuration_is_valid(configuration));
-
- // 3. If configuration["javascriptURLs"] is allow, then return false.
- if (configuration.javascript_urls == allow)
- return false;
-
- // 4. Set configuration["javascriptURLs"] to allow.
- configuration.javascript_urls = allow;
-
- // 5. Return true.
- return true;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-allowprocessinginstruction
-bool Sanitizer::allow_processing_instruction(Variant<Utf16String, Bindings::SanitizerProcessingInstruction> const& pi_input)
-{
- // 1. Let configuration be this's configuration.
- auto& configuration = m_configuration;
-
- // 2. Assert: configuration is valid.
- VERIFY(sanitizer_configuration_is_valid(configuration));
-
- // 3. Set pi to the result of canonicalizing pi.
- auto pi = canonicalize_sanitizer_processing_instruction(pi_input);
-
- // 4. If configuration["processingInstructions"] exists:
- if (configuration.processing_instructions.has_value()) {
- // 1. If configuration["processingInstructions"] contains pi, then return false.
- if (configuration.processing_instructions->contains_slow(pi))
- return false;
-
- // 2. Append pi to configuration["processingInstructions"].
- configuration.processing_instructions->append(move(pi));
-
- // 3. Return true.
- return true;
- }
-
- // 5. Otherwise:
- // 1. If configuration["removeProcessingInstructions"] contains pi:
- if (configuration.remove_processing_instructions->contains_slow(pi)) {
- // 1. Remove pi from configuration["removeProcessingInstructions"].
- configuration.remove_processing_instructions->remove_all_matching([&](auto const& item) { return item == pi; });
-
- // 2. Return true.
- return true;
- }
-
- // 2. Return false.
- return false;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-removeprocessinginstruction
-bool Sanitizer::remove_processing_instruction(Variant<Utf16String, Bindings::SanitizerProcessingInstruction> const& pi_input)
-{
- // 1. Let configuration be this's configuration.
- auto& configuration = m_configuration;
-
- // 2. Assert: configuration is valid.
- VERIFY(sanitizer_configuration_is_valid(configuration));
-
- // 3. Set pi to the result of canonicalizing pi.
- auto pi = canonicalize_sanitizer_processing_instruction(pi_input);
-
- // 4. If configuration["processingInstructions"] exists:
- if (configuration.processing_instructions.has_value()) {
- // 1. If configuration["processingInstructions"] contains pi:
- if (configuration.processing_instructions->contains_slow(pi)) {
- // 1. Remove pi from configuration["processingInstructions"].
- configuration.processing_instructions->remove_all_matching([&](auto const& item) { return item == pi; });
-
- // 2. Return true.
- return true;
- }
-
- // 2. Return false.
- return false;
- }
-
- // 5. Otherwise:
- // 1. If configuration["removeProcessingInstructions"] contains pi, then return false.
- if (configuration.remove_processing_instructions->contains_slow(pi))
- return false;
-
- // 2. Append pi to configuration["removeProcessingInstructions"].
- configuration.remove_processing_instructions->append(move(pi));
-
- // 3. Return true.
- return true;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizer-removeunsafe
-bool Sanitizer::remove_unsafe()
-{
- // The removeUnsafe() method steps are to return the result of removing unsafe from this's configuration.
- return remove_unsafe_from_sanitizer_config(m_configuration);
+ return SanitizerConfiguration { web_rust_sanitizer_configuration(this) };
}
}
diff --git a/Libraries/LibWeb/HTML/Sanitizer.h b/Libraries/LibWeb/HTML/Sanitizer.h
index 94b0b8e7c86..969ff2173fe 100644
--- a/Libraries/LibWeb/HTML/Sanitizer.h
+++ b/Libraries/LibWeb/HTML/Sanitizer.h
@@ -6,55 +6,18 @@
#pragma once
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
+#include <LibWeb/Bindings/RustInterface.h>
+#include <LibWeb/Bindings/Sanitizer.h>
+#include <LibWeb/Export.h>
#include <LibWeb/HTML/SanitizerConfiguration.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::Bindings {
-
-enum class SanitizerPresets : u8;
-struct SanitizerElementNamespace;
-struct SanitizerElementNamespaceWithAttributes;
-struct SanitizerAttributeNamespace;
-struct SanitizerProcessingInstruction;
-
-}
namespace Web::HTML {
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sanitizer
-class Sanitizer final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(Sanitizer, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(Sanitizer);
+class WEB_API Sanitizer final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(Sanitizer, sanitizer)
public:
- static WebIDL::ExceptionOr<GC::Ref<Sanitizer>> create(Variant<Bindings::SanitizerConfig, Bindings::SanitizerPresets> const& configuration);
- static GC::Ref<Sanitizer> create_with_configuration(SanitizerConfiguration);
-
- virtual ~Sanitizer() override;
-
- Bindings::SanitizerConfig get() const;
-
- bool allow_element(Variant<Utf16String, Bindings::SanitizerElementNamespaceWithAttributes> const&);
- bool remove_element(Variant<Utf16String, Bindings::SanitizerElementNamespace> const&);
- bool replace_element_with_children(Variant<Utf16String, Bindings::SanitizerElementNamespace> const&);
- bool allow_processing_instruction(Variant<Utf16String, Bindings::SanitizerProcessingInstruction> const&);
- bool remove_processing_instruction(Variant<Utf16String, Bindings::SanitizerProcessingInstruction> const&);
- bool allow_attribute(Variant<Utf16String, Bindings::SanitizerAttributeNamespace> const&);
- bool remove_attribute(Variant<Utf16String, Bindings::SanitizerAttributeNamespace> const&);
- bool set_comments(bool allow);
- bool set_data_attributes(bool allow);
- bool set_javascript_urls(bool allow);
- bool remove_unsafe();
-
- SanitizerConfiguration const& configuration() const { return m_configuration; }
-
-private:
- explicit Sanitizer(SanitizerConfiguration);
-
- // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sanitizer-configuration
- SanitizerConfiguration m_configuration;
+ SanitizerConfiguration configuration() const;
};
}
diff --git a/Libraries/LibWeb/HTML/Sanitizer.idl b/Libraries/LibWeb/HTML/Sanitizer.idl
index 92ac2f05637..818b7efa960 100644
--- a/Libraries/LibWeb/HTML/Sanitizer.idl
+++ b/Libraries/LibWeb/HTML/Sanitizer.idl
@@ -19,7 +19,7 @@ dictionary ParseHTMLUnsafeOptions {
};
// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sanitizer
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface Sanitizer {
constructor(optional (SanitizerConfig or SanitizerPresets) configuration = "default");
diff --git a/Libraries/LibWeb/HTML/SanitizerConfiguration.cpp b/Libraries/LibWeb/HTML/SanitizerConfiguration.cpp
index 30b2857fff5..aee87116b28 100644
--- a/Libraries/LibWeb/HTML/SanitizerConfiguration.cpp
+++ b/Libraries/LibWeb/HTML/SanitizerConfiguration.cpp
@@ -5,1377 +5,320 @@
*/
#include <AK/NeverDestroyed.h>
-#include <AK/QuickSort.h>
-#include <LibURL/Parser.h>
+#include <AK/StdLibExtras.h>
+#include <AK/Vector.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
#include <LibWeb/Bindings/Sanitizer.h>
-#include <LibWeb/DOM/Element.h>
#include <LibWeb/HTML/AttributeNames.h>
#include <LibWeb/HTML/GlobalEventHandlers.h>
#include <LibWeb/HTML/Sanitizer.h>
#include <LibWeb/HTML/SanitizerConfiguration.h>
-#include <LibWeb/HTML/TagNames.h>
#include <LibWeb/HTML/WindowEventHandlers.h>
-#include <LibWeb/Namespace.h>
#include <LibWeb/TrustedTypes/TrustedHTMLParserOptions.h>
namespace Web::HTML {
-template<typename T>
-static constexpr bool is_string_type = IsSame<RemoveCVReference<T>, Utf16String>;
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-a-sanitizer-name
-template<typename Name>
-static SanitizerName canonicalize_a_sanitizer_name(Name const& name, Optional<Utf16FlyString> const& default_namespace)
-{
- return name.visit(
- [&](Utf16String const& string) {
- // 1. If name is a DOMString, then return «[ "name" → name, "namespace" → defaultNamespace ]».
- return SanitizerName { Utf16FlyString { string }, default_namespace };
- },
- [&](auto const& dictionary) {
- // 2. Assert: name is a dictionary and both name["name"] and name["namespace"] exist.
- Optional<Utf16FlyString> namespace_;
- if (dictionary.namespace_.has_value())
- namespace_ = Utf16FlyString { *dictionary.namespace_ };
-
- // 3. If name["namespace"] is the empty string, then set it to null.
- if (namespace_.has_value() && namespace_->is_empty())
- namespace_ = {};
-
- // 4. Return «[ "name" → name["name"], "namespace" → name["namespace"] ]».
- return SanitizerName { Utf16FlyString { dictionary.name }, move(namespace_) };
- });
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-a-sanitizer-element
-template<typename Element>
-static SanitizerName canonicalize_a_sanitizer_element(Element const& element)
-{
- // Return the result of canonicalizing element with the HTML namespace as the default namespace.
- return canonicalize_a_sanitizer_name(element, Namespace::HTML);
-}
-
-// NB: Attributes are canonicalized with the default namespace of null.
-template<typename Attribute>
-static SanitizerName canonicalize_a_sanitizer_attribute(Attribute const& attribute)
-{
- return canonicalize_a_sanitizer_name(attribute, OptionalNone {});
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-a-sanitizer-element-list
-template<typename List>
-static Vector<SanitizerName> canonicalize_a_sanitizer_element_list(List const& list)
-{
- // 1. Let newList be « ».
- Vector<SanitizerName> new_list;
- new_list.ensure_capacity(list.size());
-
- // 2. For each item in list, append the result of canonicalizing item to newList.
- for (auto const& item : list)
- new_list.unchecked_append(canonicalize_a_sanitizer_element(item));
-
- // 3. Return newList.
- return new_list;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-a-sanitizer-list
-template<typename List>
-static Vector<SanitizerName> canonicalize_a_sanitizer_list(List const& list)
-{
- // 1. Let newList be « ».
- Vector<SanitizerName> new_list;
- new_list.ensure_capacity(list.size());
-
- // 2. For each item in list, append the result of canonicalizing item to newList.
- for (auto const& item : list)
- new_list.unchecked_append(canonicalize_a_sanitizer_attribute(item));
-
- // 3. Return newList.
- return new_list;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-a-processing-instruction-list
-template<typename List>
-static Vector<Utf16String> canonicalize_a_processing_instruction_list(List const& list)
-{
- // 1. Let newList be « ».
- Vector<Utf16String> new_list;
- new_list.ensure_capacity(list.size());
-
- // 2. For each item in list, append the result of canonicalizing item to newList.
- for (auto const& item : list)
- new_list.unchecked_append(canonicalize_sanitizer_processing_instruction(item));
+// NB: These match the enums of the same names in sanitizer_configuration.rs.
+enum class SanitizerInputKind : u8 {
+ None,
+ DefaultPreset,
+ Config,
+ Sanitizer,
+ TrustedOptions,
+};
- // 3. Return newList.
- return new_list;
-}
+enum class SanitizerConfigurationStatus : u8 {
+ Null,
+ Configuration,
+ Invalid,
+};
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-a-sanitizer-element-with-attributes
-template<typename Element>
-static SanitizerElementWithAttributes canonicalize_a_sanitizer_element_with_attributes(Element const& element)
-{
- // 1. Let result be the result of canonicalizing element.
- SanitizerElementWithAttributes result { canonicalize_a_sanitizer_element(element), {}, {} };
+enum class SanitizerOptionalBoolean : u8 {
+ Absent,
+ False,
+ True,
+};
- // 2. If element is a dictionary:
- if (auto const* dictionary = element.template get_pointer<Bindings::SanitizerElementNamespaceWithAttributes>()) {
- // 1. If element["attributes"] exists, then set result["attributes"] to the result of canonicalizing
- // element["attributes"].
- if (dictionary->attributes.has_value())
- result.attributes = canonicalize_a_sanitizer_list(*dictionary->attributes);
+struct SanitizerNameInput {
+ bool is_string { false };
+ FlatPtr name { 0 };
+ FlatPtr namespace_ { 0 };
+};
- // 2. If element["removeAttributes"] exists, then set result["removeAttributes"] to the result of
- // canonicalizing element["removeAttributes"].
- if (dictionary->remove_attributes.has_value())
- result.remove_attributes = canonicalize_a_sanitizer_list(*dictionary->remove_attributes);
- }
+template<typename T>
+struct SanitizerListInput {
+ bool present { false };
+ ReadonlySpan<T> values;
+};
- // 3. If neither result["attributes"] nor result["removeAttributes"] exists, then set result["removeAttributes"]
- // to an empty list.
- if (!result.attributes.has_value() && !result.remove_attributes.has_value())
- result.remove_attributes = Vector<SanitizerName> {};
+struct SanitizerElementInput {
+ SanitizerNameInput name;
+ SanitizerListInput<SanitizerNameInput> attributes;
+ SanitizerListInput<SanitizerNameInput> remove_attributes;
+};
- // 4. Return result.
- return result;
-}
+struct SanitizerConfigInput {
+ SanitizerListInput<SanitizerElementInput> elements;
+ SanitizerListInput<SanitizerNameInput> remove_elements;
+ SanitizerListInput<SanitizerNameInput> replace_with_children_elements;
+ SanitizerListInput<SanitizerNameInput> processing_instructions;
+ SanitizerListInput<SanitizerNameInput> remove_processing_instructions;
+ SanitizerListInput<SanitizerNameInput> attributes;
+ SanitizerListInput<SanitizerNameInput> remove_attributes;
+ SanitizerOptionalBoolean comments { SanitizerOptionalBoolean::Absent };
+ SanitizerOptionalBoolean data_attributes { SanitizerOptionalBoolean::Absent };
+ SanitizerOptionalBoolean javascript_urls { SanitizerOptionalBoolean::Absent };
+};
-SanitizerName canonicalize_sanitizer_element(Variant<Utf16String, Bindings::SanitizerElementNamespace> const& element)
-{
- return canonicalize_a_sanitizer_element(element);
-}
+struct SanitizerStringView {
+ ReadonlyBytes latin1;
+ ReadonlySpan<u16> utf16;
+};
-SanitizerElementWithAttributes canonicalize_sanitizer_element_with_attributes(Variant<Utf16String, Bindings::SanitizerElementNamespaceWithAttributes> const& element)
-{
- return canonicalize_a_sanitizer_element_with_attributes(element);
+extern "C" {
+void web_rust_sanitizer_configuration_retain(void const*);
+void web_rust_sanitizer_configuration_release(void const*);
+SanitizerConfigurationStatus web_rust_get_a_sanitizer_config_from_options(SanitizerInputKind, void const* input, bool safe, void const** out_configuration);
+Sanitizer* web_rust_get_a_sanitizer_from_sanitizer_input(JSVM*, SanitizerInputKind, void const* input);
+bool web_rust_sanitizer_config_allows_comments(void const*);
+bool web_rust_sanitizer_config_allows_processing_instruction_target(void const*, SanitizerStringView);
+SanitizerAction web_rust_sanitizer_action_for_element_name(void const*, FlatPtr name, FlatPtr namespace_);
+bool web_rust_sanitizer_config_allows_attribute(void const*, FlatPtr name, FlatPtr namespace_, SanitizerStringView, FlatPtr element_name, FlatPtr element_namespace);
+void web_sanitizer_event_handler_content_attributes(ReadonlySpan<FlatPtr>*);
}
-SanitizerName canonicalize_sanitizer_attribute(Variant<Utf16String, Bindings::SanitizerAttributeNamespace> const& attribute)
+SanitizerConfiguration::SanitizerConfiguration(void const* configuration)
+ : m_configuration(configuration)
{
- return canonicalize_a_sanitizer_attribute(attribute);
+ VERIFY(m_configuration);
}
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-a-processing-instruction
-Utf16String canonicalize_sanitizer_processing_instruction(Variant<Utf16String, Bindings::SanitizerProcessingInstruction> const& pi)
+SanitizerConfiguration::SanitizerConfiguration(SanitizerConfiguration const& other)
+ : m_configuration(other.m_configuration)
{
- return pi.visit(
- // 1. If pi is a DOMString, then return «[ "target" → pi ]».
- [](Utf16String const& string) { return string; },
- // 2. Assert: pi is a dictionary and pi["target"] exists.
- // 3. Return «[ "target" → pi["target"] ]».
- [](Bindings::SanitizerProcessingInstruction const& dictionary) { return dictionary.target; });
+ if (m_configuration)
+ web_rust_sanitizer_configuration_retain(m_configuration);
}
-// NB: This performs the per-item canonicalization steps of "canonicalize the configuration" on a dictionary supplied
-// by script. The remaining steps are performed by canonicalize_the_configuration().
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-the-configuration
-SanitizerConfiguration canonicalize_sanitizer_config(Bindings::SanitizerConfig const& configuration)
+SanitizerConfiguration::SanitizerConfiguration(SanitizerConfiguration&& other)
+ : m_configuration(exchange(other.m_configuration, nullptr))
{
- SanitizerConfiguration result;
-
- // 4. If configuration["elements"] exists:
- if (configuration.elements.has_value()) {
- // 1. Let newElements be « ».
- Vector<SanitizerElementWithAttributes> new_elements;
- new_elements.ensure_capacity(configuration.elements->size());
-
- // 2. For each element of configuration["elements"], append the result of canonicalizing element to
- // newElements.
- for (auto const& element : *configuration.elements)
- new_elements.unchecked_append(canonicalize_a_sanitizer_element_with_attributes(element));
-
- // 3. Set configuration["elements"] to newElements.
- result.elements = move(new_elements);
- }
-
- // 5. If configuration["removeElements"] exists, then set configuration["removeElements"] to the result of
- // canonicalizing configuration["removeElements"].
- if (configuration.remove_elements.has_value())
- result.remove_elements = canonicalize_a_sanitizer_element_list(*configuration.remove_elements);
-
- // 6. If configuration["attributes"] exists, then set configuration["attributes"] to the result of canonicalizing
- // configuration["attributes"].
- if (configuration.attributes.has_value())
- result.attributes = canonicalize_a_sanitizer_list(*configuration.attributes);
-
- // 7. If configuration["removeAttributes"] exists, then set configuration["removeAttributes"] to the result of
- // canonicalizing configuration["removeAttributes"].
- if (configuration.remove_attributes.has_value())
- result.remove_attributes = canonicalize_a_sanitizer_list(*configuration.remove_attributes);
-
- // 8. If configuration["replaceWithChildrenElements"] exists, then set configuration["replaceWithChildrenElements"]
- // to the result of canonicalizing configuration["replaceWithChildrenElements"].
- if (configuration.replace_with_children_elements.has_value())
- result.replace_with_children_elements = canonicalize_a_sanitizer_element_list(*configuration.replace_with_children_elements);
-
- // 9. If configuration["processingInstructions"] exists, then set configuration["processingInstructions"] to the
- // result of canonicalizing configuration["processingInstructions"].
- if (configuration.processing_instructions.has_value())
- result.processing_instructions = canonicalize_a_processing_instruction_list(*configuration.processing_instructions);
-
- // 10. If configuration["removeProcessingInstructions"] exists, then set
- // configuration["removeProcessingInstructions"] to the result of canonicalizing
- // configuration["removeProcessingInstructions"].
- if (configuration.remove_processing_instructions.has_value())
- result.remove_processing_instructions = canonicalize_a_processing_instruction_list(*configuration.remove_processing_instructions);
-
- result.comments = configuration.comments;
- result.data_attributes = configuration.data_attributes;
- result.javascript_urls = configuration.javascript_ur_ls;
-
- return result;
}
-// NB: This performs the steps of "canonicalize the configuration" that do not canonicalize individual items. Items of
-// a SanitizerConfiguration are always canonical, see canonicalize_sanitizer_config().
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#canonicalize-the-configuration
-void canonicalize_the_configuration(SanitizerConfiguration& configuration, PermissiveDefaults permissive_defaults)
+SanitizerConfiguration& SanitizerConfiguration::operator=(SanitizerConfiguration const& other)
{
- bool permissive = permissive_defaults == PermissiveDefaults::Yes;
-
- // 1. If neither configuration["elements"] nor configuration["removeElements"] exists, then set
- // configuration["removeElements"] to an empty list.
- if (!configuration.elements.has_value() && !configuration.remove_elements.has_value())
- configuration.remove_elements = Vector<SanitizerName> {};
-
- // 2. If neither configuration["attributes"] nor configuration["removeAttributes"] exists, then set
- // configuration["removeAttributes"] to an empty list.
- if (!configuration.attributes.has_value() && !configuration.remove_attributes.has_value())
- configuration.remove_attributes = Vector<SanitizerName> {};
-
- // 3. If neither configuration["processingInstructions"] nor configuration["removeProcessingInstructions"] exists:
- if (!configuration.processing_instructions.has_value() && !configuration.remove_processing_instructions.has_value()) {
- // 1. If permissiveDefaults is true, then set configuration["removeProcessingInstructions"] to an empty list.
- if (permissive)
- configuration.remove_processing_instructions = Vector<Utf16String> {};
- // 2. Otherwise, set configuration["processingInstructions"] to an empty list.
- else
- configuration.processing_instructions = Vector<Utf16String> {};
+ if (this != &other) {
+ if (other.m_configuration)
+ web_rust_sanitizer_configuration_retain(other.m_configuration);
+ web_rust_sanitizer_configuration_release(m_configuration);
+ m_configuration = other.m_configuration;
}
-
- // NB: Steps 4 to 10 canonicalize individual items, which canonicalize_sanitizer_config() has done.
-
- // 11. If configuration["comments"] does not exist, then set it to permissiveDefaults.
- if (!configuration.comments.has_value())
- configuration.comments = permissive;
-
- // 12. If configuration["attributes"] exists and configuration["dataAttributes"] does not exist, then set it to
- // permissiveDefaults.
- if (configuration.attributes.has_value() && !configuration.data_attributes.has_value())
- configuration.data_attributes = permissive;
-
- // 13. If configuration["javascriptURLs"] does not exist, then set it to permissiveDefaults.
- if (!configuration.javascript_urls.has_value())
- configuration.javascript_urls = permissive;
-}
-
-bool sanitizer_list_contains(Vector<SanitizerName> const& list, SanitizerName const& item)
-{
- return list.contains_slow(item);
-}
-
-static bool sanitizer_list_contains(Optional<Vector<SanitizerName>> const& list, SanitizerName const& item)
-{
- return list.has_value() && sanitizer_list_contains(*list, item);
-}
-
-// NB: Returns whether the list contained the item.
-bool sanitizer_list_remove(Optional<Vector<SanitizerName>>& list, SanitizerName const& item)
-{
- if (!list.has_value())
- return false;
- return list->remove_all_matching([&](auto const& entry) { return entry == item; });
+ return *this;
}
-static SanitizerElementWithAttributes const* find_element(Optional<Vector<SanitizerElementWithAttributes>> const& elements, Utf16FlyString const& local_name, Optional<Utf16FlyString> const& namespace_)
+SanitizerConfiguration& SanitizerConfiguration::operator=(SanitizerConfiguration&& other)
{
- if (!elements.has_value())
- return nullptr;
- for (auto const& element : *elements) {
- if (element.element.name == local_name && element.element.namespace_ == namespace_)
- return &element;
+ if (this != &other) {
+ web_rust_sanitizer_configuration_release(m_configuration);
+ m_configuration = exchange(other.m_configuration, nullptr);
}
- return nullptr;
+ return *this;
}
-static bool elements_contain(Optional<Vector<SanitizerElementWithAttributes>> const& elements, SanitizerName const& name)
+SanitizerConfiguration::~SanitizerConfiguration()
{
- return find_element(elements, name.name, name.namespace_);
+ web_rust_sanitizer_configuration_release(m_configuration);
}
-static bool elements_remove(Optional<Vector<SanitizerElementWithAttributes>>& elements, SanitizerName const& name)
+void const* SanitizerConfiguration::rust_configuration() const
{
- if (!elements.has_value())
- return false;
- return elements->remove_all_matching([&](auto const& entry) { return entry.element == name; });
+ VERIFY(m_configuration);
+ return m_configuration;
}
-// https://infra.spec.whatwg.org/#list-has-duplicates
-static bool has_duplicates(Vector<SanitizerName> const& list)
+static SanitizerNameInput to_name_input(Utf16String const& string)
{
- for (size_t i = 0; i < list.size(); ++i) {
- for (size_t j = i + 1; j < list.size(); ++j) {
- if (list[i] == list[j])
- return true;
- }
- }
- return false;
+ return { true, string.raw_identity(), 0 };
}
-static bool has_duplicates(Vector<SanitizerElementWithAttributes> const& list)
+template<typename Dictionary>
+static SanitizerNameInput to_name_input(Dictionary const& dictionary)
{
- for (size_t i = 0; i < list.size(); ++i) {
- for (size_t j = i + 1; j < list.size(); ++j) {
- if (list[i].element == list[j].element)
- return true;
- }
- }
- return false;
+ return { false, dictionary.name.raw_identity(), dictionary.namespace_.has_value() ? dictionary.namespace_->raw_identity() : 0 };
}
-static bool has_duplicates(Vector<Utf16String> const& list)
+template<typename Input>
+static SanitizerNameInput to_pi_input(Input const& input)
{
- for (size_t i = 0; i < list.size(); ++i) {
- for (size_t j = i + 1; j < list.size(); ++j) {
- if (list[i] == list[j])
- return true;
- }
- }
- return false;
+ return input.visit(
+ [](Utf16String const& string) { return SanitizerNameInput { true, string.raw_identity(), 0 }; },
+ [](Bindings::SanitizerProcessingInstruction const& dictionary) { return SanitizerNameInput { false, dictionary.target.raw_identity(), 0 }; });
}
-// https://infra.spec.whatwg.org/#set-intersection
-template<typename A, typename B>
-static bool intersection_is_empty(A const& a, B const& b)
-{
- for (auto const& item : a) {
- for (auto const& other : b) {
- if constexpr (IsSame<RemoveCVReference<decltype(item)>, SanitizerElementWithAttributes>) {
- if (item.element == other)
- return false;
- } else {
- if (item == other)
- return false;
+struct SanitizerConfigView {
+ explicit SanitizerConfigView(Bindings::SanitizerConfig const& config)
+ {
+ auto names = [](auto const& value) { return value.visit([](auto const& name) { return to_name_input(name); }); };
+ if (config.elements.has_value()) {
+ for (auto const& element : *config.elements) {
+ elements.append(element.visit(
+ [](Utf16String const& string) { return SanitizerElementInput { to_name_input(string), {}, {} }; },
+ [&](Bindings::SanitizerElementNamespaceWithAttributes const& dictionary) {
+ return SanitizerElementInput { to_name_input(dictionary), list(dictionary.attributes, names), list(dictionary.remove_attributes, names) };
+ }));
}
+ input.elements = { true, elements };
}
- }
- return true;
-}
-
-// https://infra.spec.whatwg.org/#set-subset
-static bool is_subset(Vector<SanitizerName> const& subset, Vector<SanitizerName> const& superset)
-{
- for (auto const& item : subset) {
- if (!sanitizer_list_contains(superset, item))
- return false;
- }
- return true;
-}
+ input.remove_elements = list(config.remove_elements, names);
+ input.replace_with_children_elements = list(config.replace_with_children_elements, names);
+ input.processing_instructions = list(config.processing_instructions, [](auto const& pi) { return to_pi_input(pi); });
+ input.remove_processing_instructions = list(config.remove_processing_instructions, [](auto const& pi) { return to_pi_input(pi); });
+ input.attributes = list(config.attributes, names);
+ input.remove_attributes = list(config.remove_attributes, names);
+ auto boolean = [](Optional<bool> value) {
+ if (!value.has_value())
+ return SanitizerOptionalBoolean::Absent;
+ return *value ? SanitizerOptionalBoolean::True : SanitizerOptionalBoolean::False;
+ };
+ input.comments = boolean(config.comments);
+ input.data_attributes = boolean(config.data_attributes);
+ input.javascript_urls = boolean(config.javascript_ur_ls);
+ }
+
+ template<typename T, typename Convert>
+ SanitizerListInput<SanitizerNameInput> list(Optional<Vector<T>> const& values, Convert convert)
+ {
+ if (!values.has_value())
+ return {};
+ Vector<SanitizerNameInput> converted;
+ converted.ensure_capacity(values->size());
+ for (auto const& value : *values)
+ converted.unchecked_append(convert(value));
+ lists.append(move(converted));
+ return { true, lists.last() };
+ }
+
+ SanitizerConfigInput input;
+ Vector<SanitizerElementInput> elements;
+ Vector<Vector<SanitizerNameInput>> lists;
+};
-// https://html.spec.whatwg.org/multipage/dom.html#custom-data-attribute
-bool is_custom_data_attribute(SanitizerName const& attribute)
+template<typename Function>
+static auto with_sanitizer_input(SanitizerInput const& input, Function function)
{
- // A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least
- // one character after the hyphen, is a valid attribute local name, and contains no ASCII upper alphas.
- if (attribute.namespace_.has_value())
- return false;
- auto name = attribute.name.view();
- if (!name.starts_with("data-"sv) || name.length_in_code_units() <= 5)
- return false;
- if (!DOM::is_valid_attribute_local_name(name))
- return false;
- for (size_t i = 0; i < name.length_in_code_units(); ++i) {
- if (is_ascii_upper_alpha(name.code_unit_at(i)))
- return false;
- }
- return true;
+ return input.visit(
+ [&](GC::Ref<Sanitizer> sanitizer) { return function(SanitizerInputKind::Sanitizer, sanitizer.ptr()); },
+ [&](Bindings::SanitizerConfig const& config) {
+ SanitizerConfigView view { config };
+ return function(SanitizerInputKind::Config, &view.input);
+ },
+ [&](Bindings::SanitizerPresets preset) {
+ VERIFY(preset == Bindings::SanitizerPresets::Default);
+ return function(SanitizerInputKind::DefaultPreset, nullptr);
+ });
}
-static bool contains_custom_data_attribute(Vector<SanitizerName> const& list)
+// NB: The Rust implementation throws this error itself when script calls the Sanitizer constructor.
+static WebIDL::SimpleException invalid_configuration_error()
{
- return list.contains([](auto const& attribute) { return is_custom_data_attribute(attribute); });
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Sanitizer configuration is not valid"_utf16 };
}
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-sanitizerconfig-valid
-bool sanitizer_configuration_is_valid(SanitizerConfiguration const& config)
+WebIDL::ExceptionOr<Optional<SanitizerConfiguration>> get_a_sanitizer_config_from_options(SanitizerOptions const& options, SanitizerSafety safety)
{
- // 1. Assert: config["elements"] exists or config["removeElements"] exists.
- VERIFY(config.elements.has_value() || config.remove_elements.has_value());
-
- // 2. If config["elements"] exists and config["removeElements"] exists, then return false.
- if (config.elements.has_value() && config.remove_elements.has_value())
- return false;
-
- // 3. Assert: Either config["processingInstructions"] exists or config["removeProcessingInstructions"] exists.
- VERIFY(config.processing_instructions.has_value() || config.remove_processing_instructions.has_value());
-
- // 4. If config["processingInstructions"] exists and config["removeProcessingInstructions"] exists, then return
- // false.
- if (config.processing_instructions.has_value() && config.remove_processing_instructions.has_value())
- return false;
-
- // 5. Assert: Either config["attributes"] exists or config["removeAttributes"] exists.
- VERIFY(config.attributes.has_value() || config.remove_attributes.has_value());
-
- // 6. If config["attributes"] exists and config["removeAttributes"] exists, then return false.
- if (config.attributes.has_value() && config.remove_attributes.has_value())
- return false;
-
- // 7. Assert: All SanitizerElementNamespaceWithAttributes, SanitizerElementNamespace,
- // SanitizerProcessingInstruction, and SanitizerAttributeNamespace items in config are canonical, meaning they
- // have been run through canonicalizing, as appropriate.
- // NB: The items of a SanitizerConfiguration are canonical by construction.
-
- // 8. If config["elements"] exists:
- if (config.elements.has_value()) {
- // 1. If config["elements"] has duplicates, then return false.
- if (has_duplicates(*config.elements))
- return false;
- }
- // 9. Otherwise:
- else {
- // 1. If config["removeElements"] has duplicates, then return false.
- if (has_duplicates(*config.remove_elements))
- return false;
- }
-
- // 10. If config["replaceWithChildrenElements"] exists and has duplicates, then return false.
- if (config.replace_with_children_elements.has_value() && has_duplicates(*config.replace_with_children_elements))
- return false;
-
- // 11. If config["processingInstructions"] exists:
- if (config.processing_instructions.has_value()) {
- // 1. If config["processingInstructions"] has duplicates, then return false.
- if (has_duplicates(*config.processing_instructions))
- return false;
- }
- // 12. Otherwise:
- else {
- // 1. If config["removeProcessingInstructions"] has duplicates, then return false.
- if (has_duplicates(*config.remove_processing_instructions))
- return false;
- }
-
- // 13. If config["attributes"] exists:
- if (config.attributes.has_value()) {
- // 1. If config["attributes"] has duplicates, then return false.
- if (has_duplicates(*config.attributes))
- return false;
- }
- // 14. Otherwise:
- else {
- // 1. If config["removeAttributes"] has duplicates, then return false.
- if (has_duplicates(*config.remove_attributes))
- return false;
- }
-
- // 15. If config["replaceWithChildrenElements"] exists:
- if (config.replace_with_children_elements.has_value()) {
- // 1. For each element of config["replaceWithChildrenElements"]:
- for (auto const& element : *config.replace_with_children_elements) {
- // 1. If the built-in non-replaceable elements list contains element, then return false.
- if (built_in_non_replaceable_elements_list_contains(element))
- return false;
- }
-
- // 2. If config["elements"] exists:
- if (config.elements.has_value()) {
- // 1. If the intersection of config["elements"] and config["replaceWithChildrenElements"] is not empty, then
- // return false.
- if (!intersection_is_empty(*config.elements, *config.replace_with_children_elements))
- return false;
- }
- // 3. Otherwise:
- else {
- // 1. If the intersection of config["removeElements"] and config["replaceWithChildrenElements"] is not
- // empty, then return false.
- if (!intersection_is_empty(*config.remove_elements, *config.replace_with_children_elements))
- return false;
- }
- }
-
- // 16. If config["attributes"] exists:
- if (config.attributes.has_value()) {
- // 1. Assert: config["dataAttributes"] exists.
- VERIFY(config.data_attributes.has_value());
-
- // 2. If config["elements"] exists:
- if (config.elements.has_value()) {
- // 1. For each element of config["elements"]:
- for (auto const& element : *config.elements) {
- // 1. If element["attributes"] exists and element["attributes"] has duplicates, then return false.
- if (element.attributes.has_value() && has_duplicates(*element.attributes))
- return false;
-
- // 2. If element["removeAttributes"] exists and element["removeAttributes"] has duplicates, then return
- // false.
- if (element.remove_attributes.has_value() && has_duplicates(*element.remove_attributes))
- return false;
-
- // 3. If the intersection of config["attributes"] and element["attributes"] with default « » is not
- // empty, then return false.
- if (element.attributes.has_value() && !intersection_is_empty(*config.attributes, *element.attributes))
- return false;
-
- // 4. If element["removeAttributes"] with default « » is not a subset of config["attributes"], then
- // return false.
- if (element.remove_attributes.has_value() && !is_subset(*element.remove_attributes, *config.attributes))
- return false;
-
- // 5. If config["dataAttributes"] is true and element["attributes"] contains a custom data attribute,
- // then return false.
- if (*config.data_attributes && element.attributes.has_value() && contains_custom_data_attribute(*element.attributes))
- return false;
- }
- }
-
- // 3. If config["dataAttributes"] is true and config["attributes"] contains a custom data attribute, then return
- // false.
- if (*config.data_attributes && contains_custom_data_attribute(*config.attributes))
- return false;
- }
- // 17. Otherwise:
- else {
- // 1. If config["elements"] exists:
- if (config.elements.has_value()) {
- // 1. For each element of config["elements"]:
- for (auto const& element : *config.elements) {
- // 1. If element["attributes"] exists and element["removeAttributes"] exists, then return false.
- if (element.attributes.has_value() && element.remove_attributes.has_value())
- return false;
-
- // 2. If element["attributes"] exists and element["attributes"] has duplicates, then return false.
- if (element.attributes.has_value() && has_duplicates(*element.attributes))
- return false;
-
- // 3. If element["removeAttributes"] exists and element["removeAttributes"] has duplicates, then return
- // false.
- if (element.remove_attributes.has_value() && has_duplicates(*element.remove_attributes))
- return false;
-
- // 4. If the intersection of config["removeAttributes"] and element["attributes"] with default « » is
- // not empty, then return false.
- if (element.attributes.has_value() && !intersection_is_empty(*config.remove_attributes, *element.attributes))
- return false;
-
- // 5. If the intersection of config["removeAttributes"] and element["removeAttributes"] with default « »
- // is not empty, then return false.
- if (element.remove_attributes.has_value() && !intersection_is_empty(*config.remove_attributes, *element.remove_attributes))
- return false;
- }
+ auto get_configuration = [&](SanitizerInputKind kind, void const* input) -> WebIDL::ExceptionOr<Optional<SanitizerConfiguration>> {
+ void const* configuration = nullptr;
+ switch (web_rust_get_a_sanitizer_config_from_options(kind, input, safety == SanitizerSafety::Safe, &configuration)) {
+ case SanitizerConfigurationStatus::Null:
+ return Optional<SanitizerConfiguration> {};
+ case SanitizerConfigurationStatus::Configuration:
+ return Optional<SanitizerConfiguration> { SanitizerConfiguration { configuration } };
+ case SanitizerConfigurationStatus::Invalid:
+ return invalid_configuration_error();
}
-
- // 2. If config["dataAttributes"] exists, then return false.
- if (config.data_attributes.has_value())
- return false;
- }
-
- // 18. Return true.
- return true;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#configure-a-sanitizer
-WebIDL::ExceptionOr<SanitizerConfiguration> configure_sanitizer_configuration(SanitizerConfiguration fresh_configuration, PermissiveDefaults permissive_defaults)
-{
- // 1. Let freshConfiguration be a clone of configuration.
- // NB: The caller passes a clone.
-
- // 2. Canonicalize the configuration freshConfiguration with permissiveDefaults.
- canonicalize_the_configuration(fresh_configuration, permissive_defaults);
-
- // 3. If freshConfiguration is not valid, then throw a TypeError.
- if (!sanitizer_configuration_is_valid(fresh_configuration))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Sanitizer configuration is not valid"_utf16 };
-
- // 4. Set sanitizer's configuration to freshConfiguration.
- // NB: The caller stores the result.
- return fresh_configuration;
+ VERIFY_NOT_REACHED();
+ };
+ return options.visit(
+ [&](GC::Ref<TrustedTypes::TrustedHTMLParserOptions> trusted_options) {
+ auto const& configuration = trusted_options->sanitizer_configuration();
+ return get_configuration(SanitizerInputKind::TrustedOptions, configuration.has_value() ? configuration->rust_configuration() : nullptr);
+ },
+ [&](Bindings::SetHTMLOptions const* dictionary) {
+ return with_sanitizer_input(dictionary->sanitizer, get_configuration);
+ },
+ [&](auto const* dictionary) -> WebIDL::ExceptionOr<Optional<SanitizerConfiguration>> {
+ if (!dictionary->sanitizer.has_value())
+ return get_configuration(SanitizerInputKind::None, nullptr);
+ return with_sanitizer_input(*dictionary->sanitizer, get_configuration);
+ });
}
-static Bindings::SanitizerElementNamespace to_bindings_name(SanitizerName const& name)
+WebIDL::ExceptionOr<GC::Ref<Sanitizer>> get_a_sanitizer_from_sanitizer_input(SanitizerInput const& input)
{
- Bindings::SanitizerElementNamespace result;
- result.name = name.name.to_utf16_string();
- result.namespace_ = name.namespace_.map([](auto const& namespace_) { return namespace_.to_utf16_string(); });
- return result;
+ return with_sanitizer_input(input, [](SanitizerInputKind kind, void const* data) -> WebIDL::ExceptionOr<GC::Ref<Sanitizer>> {
+ auto* sanitizer = web_rust_get_a_sanitizer_from_sanitizer_input(JS::HostABI::vm_to_abi(JS::VM::the()), kind, data);
+ if (!sanitizer)
+ return invalid_configuration_error();
+ return GC::Ref { *sanitizer };
+ });
}
-static Vector<Variant<Utf16String, Bindings::SanitizerAttributeNamespace>> to_bindings_attribute_list(Vector<SanitizerName> const& list)
+static SanitizerStringView to_string_view(Utf16View value)
{
- Vector<Variant<Utf16String, Bindings::SanitizerAttributeNamespace>> result;
- result.ensure_capacity(list.size());
- for (auto const& item : list) {
- Bindings::SanitizerAttributeNamespace attribute;
- attribute.name = item.name.to_utf16_string();
- attribute.namespace_ = item.namespace_.map([](auto const& namespace_) { return namespace_.to_utf16_string(); });
- result.unchecked_append(move(attribute));
- }
- return result;
+ if (value.has_latin1_storage())
+ return { value.latin1_span(), {} };
+ auto units = value.utf16_span();
+ return { {}, { reinterpret_cast<u16 const*>(units.data()), units.size() } };
}
-static Vector<Variant<Utf16String, Bindings::SanitizerElementNamespace>> to_bindings_element_list(Vector<SanitizerName> const& list)
+bool sanitizer_config_allows_comments(SanitizerConfiguration const& configuration)
{
- Vector<Variant<Utf16String, Bindings::SanitizerElementNamespace>> result;
- result.ensure_capacity(list.size());
- for (auto const& item : list)
- result.unchecked_append(to_bindings_name(item));
- return result;
+ return web_rust_sanitizer_config_allows_comments(configuration.rust_configuration());
}
-static Vector<Variant<Utf16String, Bindings::SanitizerProcessingInstruction>> to_bindings_processing_instruction_list(Vector<Utf16String> const& list)
+bool sanitizer_config_allows_processing_instruction_target(Utf16View const& target, SanitizerConfiguration const& configuration)
{
- Vector<Variant<Utf16String, Bindings::SanitizerProcessingInstruction>> result;
- result.ensure_capacity(list.size());
- for (auto const& item : list) {
- Bindings::SanitizerProcessingInstruction processing_instruction;
- processing_instruction.target = item;
- result.unchecked_append(move(processing_instruction));
- }
- return result;
+ return web_rust_sanitizer_config_allows_processing_instruction_target(configuration.rust_configuration(), to_string_view(target));
}
-Bindings::SanitizerConfig sanitizer_configuration_to_bindings(SanitizerConfiguration const& configuration)
+SanitizerAction sanitizer_action_for_element_name(Utf16FlyString const& local_name, Optional<Utf16FlyString> const& namespace_, SanitizerConfiguration const& configuration)
{
- Bindings::SanitizerConfig result;
- if (configuration.elements.has_value()) {
- Vector<Variant<Utf16String, Bindings::SanitizerElementNamespaceWithAttributes>> elements;
- elements.ensure_capacity(configuration.elements->size());
- for (auto const& element : *configuration.elements) {
- Bindings::SanitizerElementNamespaceWithAttributes dictionary;
- dictionary.name = element.element.name.to_utf16_string();
- dictionary.namespace_ = element.element.namespace_.map([](auto const& namespace_) { return namespace_.to_utf16_string(); });
- if (element.attributes.has_value())
- dictionary.attributes = to_bindings_attribute_list(*element.attributes);
- if (element.remove_attributes.has_value())
- dictionary.remove_attributes = to_bindings_attribute_list(*element.remove_attributes);
- elements.unchecked_append(move(dictionary));
- }
- result.elements = move(elements);
- }
- if (configuration.remove_elements.has_value())
- result.remove_elements = to_bindings_element_list(*configuration.remove_elements);
- if (configuration.replace_with_children_elements.has_value())
- result.replace_with_children_elements = to_bindings_element_list(*configuration.replace_with_children_elements);
- if (configuration.processing_instructions.has_value())
- result.processing_instructions = to_bindings_processing_instruction_list(*configuration.processing_instructions);
- if (configuration.remove_processing_instructions.has_value())
- result.remove_processing_instructions = to_bindings_processing_instruction_list(*configuration.remove_processing_instructions);
- if (configuration.attributes.has_value())
- result.attributes = to_bindings_attribute_list(*configuration.attributes);
- if (configuration.remove_attributes.has_value())
- result.remove_attributes = to_bindings_attribute_list(*configuration.remove_attributes);
- result.comments = configuration.comments;
- result.data_attributes = configuration.data_attributes;
- result.javascript_ur_ls = configuration.javascript_urls;
- return result;
+ return web_rust_sanitizer_action_for_element_name(configuration.rust_configuration(), local_name.raw_identity(), namespace_.has_value() ? namespace_->raw_identity() : 0);
}
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#remove-an-element-from-sanitizer-config
-bool remove_an_element_from_sanitizer_config(SanitizerConfiguration& configuration, SanitizerName const& element)
-{
- // 1. Assert: configuration is valid.
- // 2. Set element to the result of canonicalizing element.
- // NB: element is canonical.
-
- // 3. Let modified be the result of removing element from configuration["replaceWithChildrenElements"].
- bool modified = sanitizer_list_remove(configuration.replace_with_children_elements, element);
-
- // 4. If configuration["elements"] exists:
- if (configuration.elements.has_value()) {
- // 1. If configuration["elements"] contains element:
- if (elements_contain(configuration.elements, element)) {
- // 1. Remove element from configuration["elements"].
- elements_remove(configuration.elements, element);
-
- // 2. Return true.
- return true;
- }
-
- // 2. Return modified.
- return modified;
- }
-
- // 5. Otherwise:
- // 1. If configuration["removeElements"] contains element, then return modified.
- if (sanitizer_list_contains(*configuration.remove_elements, element))
- return modified;
-
- // 2. Append element to configuration["removeElements"].
- configuration.remove_elements->append(element);
-
- // 3. Return true.
- return true;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#remove-an-attribute-from-sanitizer-config
-bool remove_an_attribute_from_sanitizer_config(SanitizerConfiguration& configuration, SanitizerName const& attribute)
+bool sanitizer_config_allows_attribute(Utf16FlyString const& local_name, Optional<Utf16FlyString> const& namespace_, Utf16View const& value, Utf16FlyString const& element_local_name, Optional<Utf16FlyString> const& element_namespace, SanitizerConfiguration const& configuration)
{
- // 1. Assert: configuration is valid.
- // 2. Set attribute to the result of canonicalizing attribute.
- // NB: attribute is canonical.
-
- // 3. If configuration["attributes"] exists:
- if (configuration.attributes.has_value()) {
- // 1. Let modified be the result of removing attribute from configuration["attributes"].
- bool modified = sanitizer_list_remove(configuration.attributes, attribute);
-
- // 2. If configuration["elements"] exists:
- if (configuration.elements.has_value()) {
- // 1. For each element of configuration["elements"]:
- for (auto& element : *configuration.elements) {
- // 1. If element["attributes"] with default « » contains attribute:
- if (sanitizer_list_contains(element.attributes, attribute)) {
- // 1. Set modified to true.
- modified = true;
-
- // 2. Remove attribute from element["attributes"].
- sanitizer_list_remove(element.attributes, attribute);
- }
-
- // 2. If element["removeAttributes"] with default « » contains attribute:
- if (sanitizer_list_contains(element.remove_attributes, attribute)) {
- // 1. Assert: modified is true.
- VERIFY(modified);
-
- // 2. Remove attribute from element["removeAttributes"].
- sanitizer_list_remove(element.remove_attributes, attribute);
- }
- }
- }
-
- // 3. Return modified.
- return modified;
- }
-
- // 4. Otherwise:
- // 1. If configuration["removeAttributes"] contains attribute, then return false.
- if (sanitizer_list_contains(*configuration.remove_attributes, attribute))
- return false;
-
- // 2. If configuration["elements"] exists:
- if (configuration.elements.has_value()) {
- // 1. For each element in configuration["elements"]:
- for (auto& element : *configuration.elements) {
- // 1. If element["attributes"] with default « » contains attribute, then remove attribute from
- // element["attributes"].
- sanitizer_list_remove(element.attributes, attribute);
-
- // 2. If element["removeAttributes"] with default « » contains attribute, then remove attribute from
- // element["removeAttributes"].
- sanitizer_list_remove(element.remove_attributes, attribute);
- }
- }
-
- // 3. Append attribute to configuration["removeAttributes"].
- configuration.remove_attributes->append(attribute);
-
- // 4. Return true.
- return true;
+ return web_rust_sanitizer_config_allows_attribute(configuration.rust_configuration(), local_name.raw_identity(), namespace_.has_value() ? namespace_->raw_identity() : 0, to_string_view(value), element_local_name.raw_identity(), element_namespace.has_value() ? element_namespace->raw_identity() : 0);
}
-static Vector<SanitizerName> const& event_handler_content_attributes()
+static auto const& event_handler_content_attributes()
{
- static NeverDestroyed<Vector<SanitizerName> const> attributes { [] {
- Vector<SanitizerName> attributes;
+ struct Attributes {
+ Vector<Utf16String> names;
+ Vector<FlatPtr> representations;
+ };
+ static NeverDestroyed<Attributes const> attributes { [] {
+ Attributes attributes;
#define __ENUMERATE(attribute_name, event_name) \
- attributes.append({ HTML::AttributeNames::attribute_name, {} });
+ attributes.names.append(HTML::AttributeNames::attribute_name.to_utf16_string());
ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
ENUMERATE_WINDOW_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE
- attributes.append({ "onbegin"_utf16_fly_string, {} });
- attributes.append({ "onend"_utf16_fly_string, {} });
- attributes.append({ "onrepeat"_utf16_fly_string, {} });
+ attributes.names.append("onbegin"_utf16);
+ attributes.names.append("onend"_utf16);
+ attributes.names.append("onrepeat"_utf16);
+ attributes.representations.ensure_capacity(attributes.names.size());
+ for (auto const& name : attributes.names)
+ attributes.representations.unchecked_append(name.raw_identity());
return attributes;
}() };
return *attributes;
}
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#remove-unsafe
-bool remove_unsafe_from_sanitizer_config(SanitizerConfiguration& configuration)
-{
- // 1. Assert: configuration is valid.
-
- // 2. Let result be false.
- bool result = false;
-
- // 3. For each element in built-in safe baseline configuration["removeElements"]:
- for (auto const& element : *built_in_safe_baseline_configuration().remove_elements) {
- // 1. If removing element from configuration is true, then set result to true.
- if (remove_an_element_from_sanitizer_config(configuration, element))
- result = true;
- }
-
- // 4. For each attribute in built-in safe baseline configuration["removeAttributes"]:
- for (auto const& attribute : *built_in_safe_baseline_configuration().remove_attributes) {
- // 1. If removing attribute from configuration is true, then set result to true.
- if (remove_an_attribute_from_sanitizer_config(configuration, attribute))
- result = true;
- }
-
- // 5. For each attribute that is an event handler content attribute:
- for (auto const& attribute : event_handler_content_attributes()) {
- // 1. If removing attribute from configuration is true, then set result to true.
- if (remove_an_attribute_from_sanitizer_config(configuration, attribute))
- result = true;
- }
-
- // 6. If configuration["javascriptURLs"] is true:
- if (configuration.javascript_urls == true) {
- // 1. Set result to true.
- result = true;
-
- // 2. Set configuration["javascriptURLs"] to false.
- configuration.javascript_urls = false;
- }
-
- // 7. Return result.
- return result;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sanitizer-config-allows-comments
-bool sanitizer_config_allows_comments(SanitizerConfiguration const& configuration)
-{
- // Return true if configuration["comments"] is true; otherwise false.
- return configuration.comments == true;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sanitizer-config-allows-processing-instruction-target
-bool sanitizer_config_allows_processing_instruction_target(Utf16View const& pi_target, SanitizerConfiguration const& configuration)
-{
- // 1. Let pi be «[ "target" → piTarget ]».
- auto contains = [&](Vector<Utf16String> const& list) {
- return list.contains([&](auto const& target) { return target.utf16_view() == pi_target; });
- };
-
- // 2. If configuration["processingInstructions"] exists, then return whether
- // configuration["processingInstructions"] contains pi.
- if (configuration.processing_instructions.has_value())
- return contains(*configuration.processing_instructions);
-
- // 3. If configuration["removeProcessingInstructions"] exists and configuration["removeProcessingInstructions"]
- // contains pi, then return false.
- if (configuration.remove_processing_instructions.has_value() && contains(*configuration.remove_processing_instructions))
- return false;
-
- // 4. Return true.
- return true;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#get-the-sanitizer-action-for-an-element-name
-SanitizerAction sanitizer_action_for_element_name(Utf16FlyString const& local_name, Optional<Utf16FlyString> const& namespace_, SanitizerConfiguration const& configuration)
-{
- // 1. Let elementName be «[ "name" → localName, "namespace" → namespace ]».
- SanitizerName element_name { local_name, namespace_ };
-
- // 2. If configuration["replaceWithChildrenElements"] exists and configuration["replaceWithChildrenElements"]
- // contains elementName, then return "Replace with children".
- if (sanitizer_list_contains(configuration.replace_with_children_elements, element_name))
- return SanitizerAction::ReplaceWithChildren;
-
- // 3. If configuration["elements"] exists:
- if (configuration.elements.has_value()) {
- // 1. If there is no item in configuration["elements"] whose name member is localName and whose namespace
- // member is namespace, then return "Remove".
- if (!find_element(configuration.elements, local_name, namespace_))
- return SanitizerAction::Remove;
- }
- // 4. Otherwise, if configuration["removeElements"] contains elementName, then return "Remove".
- else if (sanitizer_list_contains(configuration.remove_elements, element_name)) {
- return SanitizerAction::Remove;
- }
-
- // 5. Return "Keep".
- return SanitizerAction::Keep;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#contains-a-javascript:-url
-static bool contains_a_javascript_url(Utf16View const& value)
+void web_sanitizer_event_handler_content_attributes(ReadonlySpan<FlatPtr>* names)
{
- // 1. Let url be the result of running the basic URL parser on value.
- auto url = URL::Parser::basic_parse(value);
-
- // 2. If url is failure, then return false.
- if (!url.has_value())
- return false;
-
- // 3. Return true if url's scheme is "javascript", and false otherwise.
- return url->scheme() == "javascript"sv;
-}
-
-struct NavigatingURLAttribute {
- Utf16FlyString const& element_name;
- Utf16FlyString const& element_namespace;
- Utf16FlyString const& attribute_name;
- Utf16FlyString const* attribute_namespace;
-};
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#built-in-navigating-url-attributes-list
-static bool built_in_navigating_url_attributes_list_matches(SanitizerName const& element_name, SanitizerName const& attribute_name)
-{
- // The built-in navigating URL attributes list corresponds to all HTML elements marked with navigating URL
- // attributes in their normative definitions, as well as the element-attribute pairs represented in the following
- // table.
- static NavigatingURLAttribute const list[] = {
- { HTML::TagNames::a, Namespace::HTML, HTML::AttributeNames::href, nullptr },
- { HTML::TagNames::area, Namespace::HTML, HTML::AttributeNames::href, nullptr },
- { HTML::TagNames::form, Namespace::HTML, HTML::AttributeNames::action, nullptr },
- { HTML::TagNames::input, Namespace::HTML, HTML::AttributeNames::formaction, nullptr },
- { HTML::TagNames::button, Namespace::HTML, HTML::AttributeNames::formaction, nullptr },
- { HTML::TagNames::a, Namespace::SVG, HTML::AttributeNames::href, nullptr },
- { HTML::TagNames::a, Namespace::SVG, HTML::AttributeNames::href, &Namespace::XLink },
- };
- for (auto const& entry : list) {
- if (element_name.name != entry.element_name || element_name.namespace_ != entry.element_namespace)
- continue;
- if (attribute_name.name != entry.attribute_name)
- continue;
- if (entry.attribute_namespace) {
- if (attribute_name.namespace_ == *entry.attribute_namespace)
- return true;
- } else if (!attribute_name.namespace_.has_value()) {
- return true;
- }
- }
- return false;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#built-in-animating-url-attributes-list
-static bool built_in_animating_url_attributes_list_contains(SanitizerName const& element_name, SanitizerName const& attribute_name)
-{
- if (element_name.namespace_ != Namespace::SVG || attribute_name.namespace_.has_value())
- return false;
- if (attribute_name.name != "attributeName"_utf16_fly_string)
- return false;
- return element_name.name.is_one_of("animate"_utf16_fly_string, "animateTransform"_utf16_fly_string, "set"_utf16_fly_string);
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sanitizer-config-allows-an-attribute
-bool sanitizer_config_allows_attribute(Utf16FlyString const& local_name, Optional<Utf16FlyString> const& namespace_, Utf16View const& value, Utf16FlyString const& element_local_name, Optional<Utf16FlyString> const& element_namespace, SanitizerConfiguration const& configuration)
-{
- // 1. Let attrName be «[ "name" → localName, "namespace" → namespace ]».
- SanitizerName attribute_name { local_name, namespace_ };
-
- // 2. Let elementName be «[ "name" → elementLocalName, "namespace" → elementNamespace ]».
- SanitizerName element_name { element_local_name, element_namespace };
-
- // 3. Let elementWithLocalAttributes be «[ ]».
- // 4. If configuration["elements"] exists and there is an item element in configuration["elements"] whose name
- // member is elementLocalName and whose namespace member is elementNamespace, then set
- // elementWithLocalAttributes to element.
- auto const* element_with_local_attributes = find_element(configuration.elements, element_local_name, element_namespace);
- Optional<Vector<SanitizerName>> const no_attributes;
- auto const& local_attributes = element_with_local_attributes ? element_with_local_attributes->attributes : no_attributes;
- auto const& local_remove_attributes = element_with_local_attributes ? element_with_local_attributes->remove_attributes : no_attributes;
-
- // 5. If elementWithLocalAttributes["removeAttributes"] exists and elementWithLocalAttributes["removeAttributes"]
- // contains attrName, then return false.
- if (sanitizer_list_contains(local_remove_attributes, attribute_name))
- return false;
-
- // 6. Otherwise, if configuration["attributes"] exists:
- if (configuration.attributes.has_value()) {
- // 1. If configuration["attributes"] does not contain attrName and elementWithLocalAttributes["attributes"]
- // with default « » does not contain attrName, and if "data-" is not a code unit prefix of localName or
- // namespace is not null or configuration["dataAttributes"] is not true, then return false.
- if (!sanitizer_list_contains(*configuration.attributes, attribute_name)
- && !sanitizer_list_contains(local_attributes, attribute_name)
- && (!local_name.view().starts_with("data-"sv) || namespace_.has_value() || configuration.data_attributes != true)) {
- return false;
- }
- }
- // 7. Otherwise:
- else {
- // 1. If elementWithLocalAttributes["attributes"] exists and elementWithLocalAttributes["attributes"] does not
- // contain attrName, then return false.
- if (local_attributes.has_value() && !sanitizer_list_contains(*local_attributes, attribute_name))
- return false;
-
- // 2. Otherwise, if configuration["removeAttributes"] exists and configuration["removeAttributes"] contains
- // attrName, then return false.
- if (sanitizer_list_contains(configuration.remove_attributes, attribute_name))
- return false;
- }
-
- // 8. If configuration["javascriptURLs"] is true, then return true.
- if (configuration.javascript_urls == true)
- return true;
-
- // 9. If the pair (elementName, attrName) matches an entry in the built-in navigating URL attributes list, and if
- // value contains a javascript: URL, then return false.
- if (built_in_navigating_url_attributes_list_matches(element_name, attribute_name) && contains_a_javascript_url(value))
- return false;
-
- // 10. If elementNamespace is the MathML namespace, localName is "href", namespace is null or the XLink namespace,
- // and value contains a javascript: URL, then return false.
- if (element_namespace == Namespace::MathML && local_name == HTML::AttributeNames::href
- && (!namespace_.has_value() || namespace_ == Namespace::XLink)
- && contains_a_javascript_url(value)) {
- return false;
- }
-
- // 11. If the built-in animating URL attributes list contains the pair (elementName, attrName), and value is "href"
- // or "xlink:href", then return false.
- if (built_in_animating_url_attributes_list_contains(element_name, attribute_name) && (value == "href"sv || value == "xlink:href"sv))
- return false;
-
- // 12. Return true.
- return true;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#built-in-non-replaceable-elements-list
-bool built_in_non_replaceable_elements_list_contains(SanitizerName const& element)
-{
- return (element.name == HTML::TagNames::html && element.namespace_ == Namespace::HTML)
- || (element.name == "svg"_utf16_fly_string && element.namespace_ == Namespace::SVG)
- || (element.name == "math"_utf16_fly_string && element.namespace_ == Namespace::MathML);
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#built-in-safe-baseline-configuration
-SanitizerConfiguration const& built_in_safe_baseline_configuration()
-{
- // The built-in safe baseline configuration is a SanitizerConfig. Its removeElements list consists of all HTML
- // elements normatively marked as Unsafe within their individual definitions, along with the obsolete frame
- // element, and the SVG script and SVG use elements, and its removeAttributes list is empty.
- static NeverDestroyed<SanitizerConfiguration const> configuration { [] {
- SanitizerConfiguration configuration;
- configuration.remove_elements = Vector<SanitizerName> {
- { HTML::TagNames::base, Namespace::HTML },
- { HTML::TagNames::embed, Namespace::HTML },
- { HTML::TagNames::frame, Namespace::HTML },
- { HTML::TagNames::iframe, Namespace::HTML },
- { HTML::TagNames::object, Namespace::HTML },
- { HTML::TagNames::script, Namespace::HTML },
- { HTML::TagNames::script, Namespace::SVG },
- { "use"_utf16_fly_string, Namespace::SVG },
- };
- configuration.remove_attributes = Vector<SanitizerName> {};
- return configuration;
- }() };
- return *configuration;
-}
-
-struct DefaultElement {
- StringView name;
- StringView attributes;
-};
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#built-in-safe-default-configuration
-SanitizerConfiguration const& built_in_safe_default_configuration()
-{
- static NeverDestroyed<SanitizerConfiguration const> configuration { [] {
- auto attribute_list = [](StringView attributes) {
- Vector<SanitizerName> list;
- attributes.for_each_split_view(' ', SplitBehavior::Nothing, [&](StringView attribute) {
- list.append({ Utf16FlyString::from_utf8(attribute), {} });
- });
- return list;
- };
-
- SanitizerConfiguration configuration;
-
- // elements
- // All HTML elements normatively categorized as Default within their individual definitions, alongside the
- // MathML and SVG elements listed in the table below. Attributes included in those definitions are included
- // in each element's respective attributes list.
- static constexpr DefaultElement html_elements[] = {
- { "html"sv, {} },
- { "head"sv, {} },
- { "title"sv, {} },
- { "body"sv, {} },
- { "article"sv, {} },
- { "section"sv, {} },
- { "nav"sv, {} },
- { "aside"sv, {} },
- { "h1"sv, {} },
- { "h2"sv, {} },
- { "h3"sv, {} },
- { "h4"sv, {} },
- { "h5"sv, {} },
- { "h6"sv, {} },
- { "hgroup"sv, {} },
- { "header"sv, {} },
- { "footer"sv, {} },
- { "address"sv, {} },
- { "p"sv, {} },
- { "hr"sv, {} },
- { "pre"sv, {} },
- { "blockquote"sv, "cite"sv },
- { "ol"sv, "reversed start type"sv },
- { "ul"sv, {} },
- { "menu"sv, {} },
- { "li"sv, "value"sv },
- { "dl"sv, {} },
- { "dt"sv, {} },
- { "dd"sv, {} },
- { "figure"sv, {} },
- { "figcaption"sv, {} },
- { "main"sv, {} },
- { "search"sv, {} },
- { "div"sv, {} },
- { "a"sv, "href hreflang type"sv },
- { "em"sv, {} },
- { "strong"sv, {} },
- { "small"sv, {} },
- { "s"sv, {} },
- { "cite"sv, {} },
- { "q"sv, {} },
- { "dfn"sv, {} },
- { "abbr"sv, {} },
- { "ruby"sv, {} },
- { "rt"sv, {} },
- { "rp"sv, {} },
- { "data"sv, "value"sv },
- { "time"sv, "datetime"sv },
- { "code"sv, {} },
- { "var"sv, {} },
- { "samp"sv, {} },
- { "kbd"sv, {} },
- { "sub"sv, {} },
- { "sup"sv, {} },
- { "i"sv, {} },
- { "b"sv, {} },
- { "u"sv, {} },
- { "mark"sv, {} },
- { "bdi"sv, {} },
- { "bdo"sv, {} },
- { "span"sv, {} },
- { "br"sv, {} },
- { "wbr"sv, {} },
- { "ins"sv, "cite datetime"sv },
- { "del"sv, "cite datetime"sv },
- { "table"sv, {} },
- { "caption"sv, {} },
- { "colgroup"sv, "span"sv },
- { "col"sv, "span"sv },
- { "tbody"sv, {} },
- { "thead"sv, {} },
- { "tfoot"sv, {} },
- { "tr"sv, {} },
- { "td"sv, "colspan headers rowspan"sv },
- { "th"sv, "abbr colspan headers rowspan scope"sv },
- };
-
- static constexpr DefaultElement mathml_elements[] = {
- { "a"sv, "href hreflang type"sv },
- { "math"sv, {} },
- { "merror"sv, {} },
- { "mfrac"sv, {} },
- { "mi"sv, {} },
- { "mmultiscripts"sv, {} },
- { "mn"sv, {} },
- { "mo"sv, "fence form largeop lspace maxsize minsize movablelimits rspace separator stretchy symmetric"sv },
- { "mover"sv, "accent"sv },
- { "mpadded"sv, "depth height lspace voffset width"sv },
- { "mphantom"sv, {} },
- { "mprescripts"sv, {} },
- { "mroot"sv, {} },
- { "mrow"sv, {} },
- { "ms"sv, {} },
- { "mspace"sv, "depth height width"sv },
- { "msqrt"sv, {} },
- { "mstyle"sv, {} },
- { "msub"sv, {} },
- { "msubsup"sv, {} },
- { "msup"sv, {} },
- { "mtable"sv, {} },
- { "mtd"sv, "columnspan rowspan"sv },
- { "mtext"sv, {} },
- { "mtr"sv, {} },
- { "munder"sv, "accentunder"sv },
- { "munderover"sv, "accent accentunder"sv },
- { "semantics"sv, {} },
- };
-
- static constexpr DefaultElement svg_elements[] = {
- { "a"sv, "href hreflang type"sv },
- { "circle"sv, "cx cy pathLength r"sv },
- { "defs"sv, {} },
- { "desc"sv, {} },
- { "ellipse"sv, "cx cy pathLength rx ry"sv },
- { "foreignObject"sv, "height width x y"sv },
- { "g"sv, {} },
- { "line"sv, "pathLength x1 x2 y1 y2"sv },
- { "marker"sv, "markerHeight markerUnits markerWidth orient preserveAspectRatio refX refY viewBox"sv },
- { "metadata"sv, {} },
- { "path"sv, "d pathLength"sv },
- { "polygon"sv, "pathLength points"sv },
- { "polyline"sv, "pathLength points"sv },
- { "rect"sv, "height pathLength rx ry width x y"sv },
- { "svg"sv, "height preserveAspectRatio viewBox width x y"sv },
- { "text"sv, "dx dy lengthAdjust rotate textLength x y"sv },
- { "textPath"sv, "lengthAdjust method path side spacing startOffset textLength"sv },
- { "title"sv, {} },
- { "tspan"sv, "dx dy lengthAdjust rotate textLength x y"sv },
- };
-
- Vector<SanitizerElementWithAttributes> elements;
- auto append_elements = [&](ReadonlySpan<DefaultElement> list, Utf16FlyString const& namespace_) {
- for (auto const& element : list)
- elements.append({ { Utf16FlyString::from_utf8(element.name), namespace_ }, attribute_list(element.attributes), {} });
- };
- append_elements(html_elements, Namespace::HTML);
- append_elements(mathml_elements, Namespace::MathML);
- append_elements(svg_elements, Namespace::SVG);
- configuration.elements = move(elements);
-
- // processingInstructions
- // « »
- configuration.processing_instructions = Vector<Utf16String> {};
-
- // attributes
- configuration.attributes = attribute_list(
- "dir lang title alignment-baseline baseline-shift clip-path clip-rule color color-interpolation cursor "
- "direction display displaystyle dominant-baseline fill fill-opacity fill-rule font-family font-size "
- "font-size-adjust font-stretch font-style font-variant font-weight letter-spacing marker-end marker-mid "
- "marker-start mathbackground mathcolor mathsize opacity paint-order pointer-events scriptlevel "
- "shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap "
- "stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-overflow "
- "text-rendering transform transform-origin unicode-bidi vector-effect visibility white-space word-spacing "
- "writing-mode"sv);
-
- // comments
- // false
- configuration.comments = false;
-
- // dataAttributes
- // false
- configuration.data_attributes = false;
-
- // javascriptURLs
- // false
- configuration.javascript_urls = false;
-
- return configuration;
- }() };
- return *configuration;
-}
-
-// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#get-a-sanitizer-config-from-options
-WebIDL::ExceptionOr<Optional<SanitizerConfiguration>> get_a_sanitizer_config_from_options(SanitizerOptions const& options, SanitizerSafety safety)
-{
- bool safe = safety == SanitizerSafety::Safe;
-
- // 1. Let sanitizerInput be null.
- using SanitizerInput = Variant<Empty, GC::Ref<Sanitizer>, Bindings::SanitizerConfig const*, SanitizerConfiguration const*>;
- SanitizerInput sanitizer_input;
-
- auto set_sanitizer_input = [&](auto const& sanitizer) {
- sanitizer.visit(
- [&](Bindings::SanitizerConfig const& config) { sanitizer_input = &config; },
- [&](Bindings::SanitizerPresets preset) {
- // 1. Assert: sanitizerInput is "default".
- VERIFY(preset == Bindings::SanitizerPresets::Default);
-
- // 2. Set sanitizerInput to the built-in safe default configuration.
- sanitizer_input = &built_in_safe_default_configuration();
- },
- [&](auto const& sanitizer_object) { sanitizer_input = GC::Ref<Sanitizer> { *sanitizer_object }; });
- };
-
- // 2. If options is a TrustedHTMLParserOptions:
- if (auto const* trusted_options = options.get_pointer<GC::Ref<TrustedTypes::TrustedHTMLParserOptions>>()) {
- // 1. If options's sanitizer configuration is null:
- if (!(*trusted_options)->sanitizer_configuration().has_value()) {
- // 1. Assert: safe is false.
- VERIFY(!safe);
-
- // 2. Return null.
- return Optional<SanitizerConfiguration> {};
- }
-
- // 2. Set sanitizerInput to options's sanitizer configuration.
- sanitizer_input = &*(*trusted_options)->sanitizer_configuration();
- }
-
- // 3. Otherwise, if options["sanitizer"] exists, then set sanitizerInput to options["sanitizer"].
- bool has_sanitizer = options.visit(
- [&](GC::Ref<TrustedTypes::TrustedHTMLParserOptions>) {
- return true;
- },
- [&](Bindings::SetHTMLOptions const* set_html_options) {
- set_sanitizer_input(set_html_options->sanitizer);
- return true;
- },
- [&](auto const* dictionary) {
- if (!dictionary->sanitizer.has_value())
- return false;
- set_sanitizer_input(*dictionary->sanitizer);
- return true;
- });
-
- if (!has_sanitizer) {
- // 4. Otherwise, if safe is false, then return null.
- if (!safe)
- return Optional<SanitizerConfiguration> {};
-
- // 5. Otherwise, set sanitizerInput to "default".
- // NB: The following step sets sanitizerInput to the built-in safe default configuration.
- sanitizer_input = &built_in_safe_default_configuration();
- }
-
- // 6. Assert: sanitizerInput is either a Sanitizer instance, a SanitizerPresets member, or a SanitizerConfig
- // dictionary.
- // 7. If sanitizerInput is a string:
- // 1. Assert: sanitizerInput is "default".
- // 2. Set sanitizerInput to the built-in safe default configuration.
- // NB: This was done above.
-
- // 8. If sanitizerInput is a Sanitizer, then set sanitizerInput to sanitizerInput's configuration.
- // 9. Assert: sanitizerInput is a dictionary.
- auto clone = sanitizer_input.visit(
- [](Empty) -> SanitizerConfiguration { VERIFY_NOT_REACHED(); },
- [](GC::Ref<Sanitizer> sanitizer) { return sanitizer->configuration(); },
- [](Bindings::SanitizerConfig const* config) { return canonicalize_sanitizer_config(*config); },
- [](SanitizerConfiguration const* config) { return *config; });
-
- // 10. Let sanitizer be a new Sanitizer object.
- // 11. Let permissiveDefaults be true if safe is false; false otherwise.
- auto permissive_defaults = safe ? PermissiveDefaults::No : PermissiveDefaults::Yes;
-
- // 12. Configure sanitizer given sanitizerInput and permissiveDefaults.
- // 13. Let configuration be sanitizer's configuration.
- auto configuration = TRY(configure_sanitizer_configuration(move(clone), permissive_defaults));
-
- // 14. If safe is true, then remove unsafe from configuration.
- if (safe)
- remove_unsafe_from_sanitizer_config(configuration);
-
- // 15. Assert: configuration is valid.
- VERIFY(sanitizer_configuration_is_valid(configuration));
-
- // 16. Return configuration.
- // NOTE: The returned SanitizerConfig is a fresh copy, so removing unsafe items from it never affects a Sanitizer
- // object or SanitizerConfig dictionary that script can observe.
- return Optional<SanitizerConfiguration> { move(configuration) };
-}
-
-// https://w3c.github.io/trusted-types/dist/spec/#get-a-sanitizer-from-dictionary
-// NB: The steps of "get a sanitizer from dictionary" after sanitizerInput has been found to be non-null.
-WebIDL::ExceptionOr<GC::Ref<Sanitizer>> get_a_sanitizer_from_sanitizer_input(SanitizerInput const& sanitizer_input)
-{
- // 3. Let configuration be null.
- auto configuration = sanitizer_input.visit(
- // 4. If sanitizerInput is a SanitizerPresets:
- [](Bindings::SanitizerPresets preset) {
- // 1. Assert: sanitizerInput is "default".
- VERIFY(preset == Bindings::SanitizerPresets::Default);
-
- // 2. Set configuration to the built-in safe default configuration.
- return built_in_safe_default_configuration();
- },
- // 5. Otherwise, if sanitizerInput is a Sanitizer:
- // 1. Set configuration to sanitizerInput's configuration.
- [](GC::Ref<Sanitizer> sanitizer) { return sanitizer->configuration(); },
- // 6. Otherwise, if sanitizerInput is a SanitizerConfig:
- // 1. Set configuration to sanitizerInput.
- [](Bindings::SanitizerConfig const& config) { return canonicalize_sanitizer_config(config); });
-
- // 7. Assert: configuration is not null.
- // 8. Let sanitizer be a new Sanitizer in realm.
- // 9. Configure sanitizer given configuration and true.
- auto canonical_configuration = TRY(configure_sanitizer_configuration(move(configuration), PermissiveDefaults::Yes));
-
- // 10. Return sanitizer.
- return Sanitizer::create_with_configuration(move(canonical_configuration));
+ *names = event_handler_content_attributes().representations;
}
}
diff --git a/Libraries/LibWeb/HTML/SanitizerConfiguration.h b/Libraries/LibWeb/HTML/SanitizerConfiguration.h
index 18755acfa07..267be2525f1 100644
--- a/Libraries/LibWeb/HTML/SanitizerConfiguration.h
+++ b/Libraries/LibWeb/HTML/SanitizerConfiguration.h
@@ -8,9 +8,7 @@
#include <AK/Optional.h>
#include <AK/Utf16FlyString.h>
-#include <AK/Utf16String.h>
#include <AK/Variant.h>
-#include <AK/Vector.h>
#include <LibGC/Ptr.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
@@ -23,85 +21,39 @@ struct SanitizerConfig;
struct SetHTMLOptions;
struct SetHTMLUnsafeOptions;
struct ParseHTMLUnsafeOptions;
-struct SanitizerElementNamespace;
-struct SanitizerElementNamespaceWithAttributes;
-struct SanitizerAttributeNamespace;
-struct SanitizerProcessingInstruction;
}
namespace Web::HTML {
-// NB: A canonicalized SanitizerElementNamespace or SanitizerAttributeNamespace dictionary.
-struct SanitizerName {
- Utf16FlyString name;
- Optional<Utf16FlyString> namespace_;
+class WEB_API SanitizerConfiguration {
+public:
+ explicit SanitizerConfiguration(void const*);
+ SanitizerConfiguration(SanitizerConfiguration const&);
+ SanitizerConfiguration(SanitizerConfiguration&&);
+ SanitizerConfiguration& operator=(SanitizerConfiguration const&);
+ SanitizerConfiguration& operator=(SanitizerConfiguration&&);
+ ~SanitizerConfiguration();
- bool operator==(SanitizerName const&) const = default;
-};
-
-// NB: A canonicalized SanitizerElementNamespaceWithAttributes dictionary.
-struct SanitizerElementWithAttributes {
- SanitizerName element;
- Optional<Vector<SanitizerName>> attributes;
- Optional<Vector<SanitizerName>> remove_attributes;
+ void const* rust_configuration() const;
- bool operator==(SanitizerElementWithAttributes const&) const = default;
-};
-
-// NB: A canonicalized SanitizerConfig dictionary. Processing instructions are represented by their target.
-struct SanitizerConfiguration {
- Optional<Vector<SanitizerElementWithAttributes>> elements;
- Optional<Vector<SanitizerName>> remove_elements;
- Optional<Vector<SanitizerName>> replace_with_children_elements;
- Optional<Vector<Utf16String>> processing_instructions;
- Optional<Vector<Utf16String>> remove_processing_instructions;
- Optional<Vector<SanitizerName>> attributes;
- Optional<Vector<SanitizerName>> remove_attributes;
- Optional<bool> comments;
- Optional<bool> data_attributes;
- Optional<bool> javascript_urls;
+private:
+ void const* m_configuration { nullptr };
};
// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sanitizer-action
+// NB: SanitizerAction in sanitizer_configuration.rs matches this.
enum class SanitizerAction : u8 {
Keep,
Remove,
ReplaceWithChildren,
};
-enum class PermissiveDefaults : u8 {
- No,
- Yes,
-};
-
-SanitizerConfiguration canonicalize_sanitizer_config(Bindings::SanitizerConfig const&);
-SanitizerName canonicalize_sanitizer_element(Variant<Utf16String, Bindings::SanitizerElementNamespace> const&);
-SanitizerElementWithAttributes canonicalize_sanitizer_element_with_attributes(Variant<Utf16String, Bindings::SanitizerElementNamespaceWithAttributes> const&);
-SanitizerName canonicalize_sanitizer_attribute(Variant<Utf16String, Bindings::SanitizerAttributeNamespace> const&);
-Utf16String canonicalize_sanitizer_processing_instruction(Variant<Utf16String, Bindings::SanitizerProcessingInstruction> const&);
-void canonicalize_the_configuration(SanitizerConfiguration&, PermissiveDefaults);
-bool sanitizer_configuration_is_valid(SanitizerConfiguration const&);
-WebIDL::ExceptionOr<SanitizerConfiguration> configure_sanitizer_configuration(SanitizerConfiguration, PermissiveDefaults);
-Bindings::SanitizerConfig sanitizer_configuration_to_bindings(SanitizerConfiguration const&);
-
-bool remove_an_element_from_sanitizer_config(SanitizerConfiguration&, SanitizerName const&);
-bool remove_an_attribute_from_sanitizer_config(SanitizerConfiguration&, SanitizerName const&);
-bool remove_unsafe_from_sanitizer_config(SanitizerConfiguration&);
-
-bool is_custom_data_attribute(SanitizerName const&);
-bool sanitizer_list_contains(Vector<SanitizerName> const&, SanitizerName const&);
-bool sanitizer_list_remove(Optional<Vector<SanitizerName>>&, SanitizerName const&);
-
WEB_API bool sanitizer_config_allows_comments(SanitizerConfiguration const&);
WEB_API bool sanitizer_config_allows_processing_instruction_target(Utf16View const& target, SanitizerConfiguration const&);
WEB_API SanitizerAction sanitizer_action_for_element_name(Utf16FlyString const& local_name, Optional<Utf16FlyString> const& namespace_, SanitizerConfiguration const&);
WEB_API bool sanitizer_config_allows_attribute(Utf16FlyString const& local_name, Optional<Utf16FlyString> const& namespace_, Utf16View const& value, Utf16FlyString const& element_local_name, Optional<Utf16FlyString> const& element_namespace, SanitizerConfiguration const&);
-SanitizerConfiguration const& built_in_safe_default_configuration();
-SanitizerConfiguration const& built_in_safe_baseline_configuration();
-bool built_in_non_replaceable_elements_list_contains(SanitizerName const&);
-
enum class SanitizerSafety : u8 {
Unsafe,
Safe,