Skip to content

Truly independent web browser

LibWeb: Implement TrustedTypePolicy and its factory in Rust

Shannon Booth3ad8e49ccbc6
diff --git a/AK/Rust/src/lib.rs b/AK/Rust/src/lib.rs
index b35c36af43b..ac23d2d0203 100644
--- a/AK/Rust/src/lib.rs
+++ b/AK/Rust/src/lib.rs
@@ -346,6 +346,22 @@ impl Utf16String {
result
}
+ pub fn to_ascii_lowercase(&self) -> Self {
+ match self.as_units() {
+ Utf16StringUnits::Ascii(units) => Self::from_ascii(&units.to_ascii_lowercase()),
+ Utf16StringUnits::Latin1(units) => Self::from_latin1(&units.to_ascii_lowercase()),
+ Utf16StringUnits::Utf16(units) => Self::from_utf16(
+ &units
+ .iter()
+ .map(|&code_unit| match u8::try_from(code_unit) {
+ Ok(byte) => u16::from(byte.to_ascii_lowercase()),
+ Err(_) => code_unit,
+ })
+ .collect::<Vec<u16>>(),
+ ),
+ }
+ }
+
/// Creates a string in AK's native representation from the Latin-1 bytes of `pieces` one after the other, which
/// add up to `length` bytes, copying each piece into the string's storage directly. `is_ascii` tells whether
/// every byte is ASCII.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs
index e8a89aca5a8..aabfbe6cf2b 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs
@@ -100,6 +100,10 @@ impl CallbackType {
}
impl CallbackFunction {
+ pub(crate) fn as_ptr(&self) -> *mut c_void {
+ self.0.0.as_ptr()
+ }
+
/// The callback function value of a JS value, https://webidl.spec.whatwg.org/#js-callback-function
pub(crate) fn from_js(vm: &Vm, value: Value) -> ThrowCompletionOr<Self> {
CallbackType::from_js(vm, value, false).map(Self)
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/global_event_handlers.rs b/Libraries/LibWeb/Bindings/Rust/src/html/global_event_handlers.rs
new file mode 100644
index 00000000000..88ea03f0398
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/global_event_handlers.rs
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! GlobalEventHandlers, https://html.spec.whatwg.org/multipage/webappapis.html#globaleventhandlers
+
+use ak::Utf16String;
+
+unsafe extern "C" {
+ fn web_html_is_event_handler_content_attribute(name: usize) -> bool;
+}
+
+/// https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-content-attributes
+pub(crate) fn is_event_handler_content_attribute(name: &Utf16String) -> bool {
+ // SAFETY: The string is live for the call.
+ unsafe { web_html_is_event_handler_content_attribute(name.raw_identity()) }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
index 927518cd8c4..10768cd5822 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
@@ -57,6 +57,8 @@ pub(crate) mod canvas_transform;
#[cfg(not(test))]
pub(crate) mod exports;
#[cfg(not(test))]
+pub(crate) mod global_event_handlers;
+#[cfg(not(test))]
pub(crate) mod html_form_element;
#[cfg(not(test))]
pub(crate) mod image_bitmap;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/window_or_worker_global_scope.rs b/Libraries/LibWeb/Bindings/Rust/src/html/window_or_worker_global_scope.rs
index 988ee287806..023e46350e7 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/window_or_worker_global_scope.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/window_or_worker_global_scope.rs
@@ -10,11 +10,19 @@
//! WindowOrWorkerGlobalScope, https://html.spec.whatwg.org/multipage/webappapis.html#windoworworkerglobalscope
+use core::ffi::c_void;
+
use libjs_rust::api::{Gc, Object, Value};
+use crate::bindings::interface::{Ref, cell_from_abi};
use crate::bindings::{CallContext, WebIdlResult};
use crate::html::structured_serialize::transfer_record::TransferRecord;
use crate::html::structured_serialize::{structured_deserialize_with_transfer, structured_serialize_with_transfer};
+use crate::trusted_types::trusted_type_policy_factory::TrustedTypePolicyFactory;
+
+unsafe extern "C" {
+ fn web_html_window_or_worker_global_scope_trusted_types(global_object: *mut c_void) -> *mut c_void;
+}
// https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone
pub(crate) fn structured_clone(cx: &CallContext, value: Value, transfer: &[Gc<Object>]) -> WebIdlResult<Value> {
@@ -28,3 +36,13 @@ pub(crate) fn structured_clone(cx: &CallContext, value: Value, transfer: &[Gc<Ob
// 3. Return deserializeRecord.[[Deserialized]].
Ok(deserialize_record?.deserialized)
}
+
+// https://w3c.github.io/trusted-types/dist/spec/#dom-windoworworkerglobalscope-trustedtypes
+pub(crate) fn trusted_types(global_object: Gc<Object>) -> Ref<TrustedTypePolicyFactory> {
+ // SAFETY: The global object is a live Window or WorkerGlobalScope, whose live factory LibWeb returns.
+ unsafe {
+ cell_from_abi(web_html_window_or_worker_global_scope_trusted_types(
+ global_object.as_ptr().cast(),
+ ))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/trusted_types/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/trusted_types/mod.rs
index a71ef4c2bff..c23a9929092 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/trusted_types/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/trusted_types/mod.rs
@@ -6,6 +6,9 @@
//! Trusted Types, https://w3c.github.io/trusted-types/dist/spec/
+pub(crate) mod require_trusted_types_for_directive;
pub(crate) mod trusted_html;
pub(crate) mod trusted_script;
pub(crate) mod trusted_script_url;
+pub(crate) mod trusted_type_policy;
+pub(crate) mod trusted_type_policy_factory;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/trusted_types/require_trusted_types_for_directive.rs b/Libraries/LibWeb/Bindings/Rust/src/trusted_types/require_trusted_types_for_directive.rs
new file mode 100644
index 00000000000..1fd33cd394c
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/trusted_types/require_trusted_types_for_directive.rs
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2025, Miguel Sacristán Izcue <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Integration with Content Security Policy, https://w3c.github.io/trusted-types/dist/spec/#integration-with-content-security-policy
+
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::{Gc, Object, Realm};
+
+unsafe extern "C" {
+ fn web_trusted_types_does_sink_require_trusted_types(
+ global: *mut c_void,
+ sink_group: usize,
+ include_report_only_policies: bool,
+ ) -> bool;
+ fn web_trusted_types_should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(
+ global: *mut c_void,
+ sink: usize,
+ sink_group: usize,
+ source: usize,
+ ) -> bool;
+ fn web_trusted_types_should_trusted_type_policy_creation_be_blocked_by_content_security_policy(
+ realm: *mut c_void,
+ global: *mut c_void,
+ policy_name: usize,
+ created_policy_names: ak::Span<'_, usize>,
+ ) -> bool;
+}
+
+// https://w3c.github.io/trusted-types/dist/spec/#does-sink-require-trusted-types
+pub(crate) fn does_sink_require_trusted_types(
+ global: Gc<Object>,
+ sink_group: &Utf16String,
+ include_report_only_policies: bool,
+) -> bool {
+ // SAFETY: The global object and the string are live for the call.
+ unsafe {
+ web_trusted_types_does_sink_require_trusted_types(
+ global.as_ptr().cast(),
+ sink_group.raw_identity(),
+ include_report_only_policies,
+ )
+ }
+}
+
+/// https://w3c.github.io/trusted-types/dist/spec/#should-block-sink-type-mismatch
+pub(crate) fn should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(
+ global: Gc<Object>,
+ sink: &Utf16String,
+ sink_group: &Utf16String,
+ source: &Utf16String,
+) -> bool {
+ // SAFETY: The global object and the strings are live for the call.
+ unsafe {
+ web_trusted_types_should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(
+ global.as_ptr().cast(),
+ sink.raw_identity(),
+ sink_group.raw_identity(),
+ source.raw_identity(),
+ )
+ }
+}
+
+/// https://w3c.github.io/trusted-types/dist/spec/#should-block-create-policy
+pub(crate) fn should_trusted_type_policy_creation_be_blocked_by_content_security_policy(
+ realm: Gc<Realm>,
+ global: Gc<Object>,
+ policy_name: &Utf16String,
+ created_policy_names: &[Utf16String],
+) -> bool {
+ let created_policy_names: Vec<usize> = created_policy_names.iter().map(Utf16String::raw_identity).collect();
+ // SAFETY: The realm, the global object and the strings are live for the call.
+ unsafe {
+ web_trusted_types_should_trusted_type_policy_creation_be_blocked_by_content_security_policy(
+ realm.as_ptr().cast(),
+ global.as_ptr().cast(),
+ policy_name.raw_identity(),
+ ak::Span::new(&created_policy_names),
+ )
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/trusted_types/trusted_type_policy.rs b/Libraries/LibWeb/Bindings/Rust/src/trusted_types/trusted_type_policy.rs
new file mode 100644
index 00000000000..0aced151485
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/trusted_types/trusted_type_policy.rs
@@ -0,0 +1,723 @@
+/*
+ * Copyright (c) 2025, Miguel Sacristán Izcue <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! TrustedTypePolicy, https://w3c.github.io/trusted-types/dist/spec/#trusted-type-policy
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::{
+ Gc, MarkedVec, Object, PrimitiveString, RawNativeFunctionResult, Trace, Utf16View, Value, Vm, utf16_formatted,
+};
+
+use crate::bindings::callback::CallbackFunction;
+use crate::bindings::conversions::{CppDictionary, CppInterface, to_dom_string, to_usv_string};
+use crate::bindings::interface::{Ref, Wrappable, cell_from_abi, cell_into_abi};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::html::window_or_worker_global_scope::trusted_types;
+use crate::trusted_types::require_trusted_types_for_directive::{
+ does_sink_require_trusted_types, should_sink_type_mismatch_violation_be_blocked_by_content_security_policy,
+};
+use crate::trusted_types::trusted_html::TrustedHTML;
+use crate::trusted_types::trusted_script::TrustedScript;
+use crate::trusted_types::trusted_script_url::TrustedScriptURL;
+use crate::trusted_types::trusted_type_policy_factory::{
+ HTML_NAMESPACE, SVG_NAMESPACE, get_trusted_type_data_for_attribute,
+};
+
+unsafe extern "C" {
+ /// https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicy-createparseroptions
+ fn web_trusted_types_create_parser_options(
+ global: *mut c_void,
+ create_parser_options: *mut c_void,
+ options: *mut c_void,
+ arguments: ak::Span<'_, Value>,
+ ) -> RawNativeFunctionResult;
+}
+
+/// https://w3c.github.io/trusted-types/dist/spec/#trusted-type-policy-options
+pub(crate) struct TrustedTypePolicyOptions {
+ pub(crate) create_html: Option<CallbackFunction>,
+ pub(crate) create_parser_options: Option<CallbackFunction>,
+ pub(crate) create_script: Option<CallbackFunction>,
+ pub(crate) create_script_url: Option<CallbackFunction>,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum TrustedTypeName {
+ TrustedHTML,
+ TrustedScript,
+ TrustedScriptURL,
+}
+
+impl TrustedTypeName {
+ pub(crate) fn from_abi(value: u8) -> Self {
+ match value {
+ 0 => Self::TrustedHTML,
+ 1 => Self::TrustedScript,
+ 2 => Self::TrustedScriptURL,
+ _ => unreachable!("{value} is not a TrustedTypeName"),
+ }
+ }
+
+ pub(crate) fn name(self) -> &'static str {
+ match self {
+ Self::TrustedHTML => "TrustedHTML",
+ Self::TrustedScript => "TrustedScript",
+ Self::TrustedScriptURL => "TrustedScriptURL",
+ }
+ }
+}
+
+/// https://w3c.github.io/trusted-types/dist/spec/#typedefdef-trustedtype
+pub(crate) enum TrustedType {
+ TrustedHTML(Ref<TrustedHTML>),
+ TrustedScript(Ref<TrustedScript>),
+ TrustedScriptURL(Ref<TrustedScriptURL>),
+}
+
+impl TrustedType {
+ pub(crate) fn data(&self) -> &Utf16String {
+ match self {
+ Self::TrustedHTML(value) => value.data(),
+ Self::TrustedScript(value) => value.data(),
+ Self::TrustedScriptURL(value) => value.data(),
+ }
+ }
+
+ fn type_name(&self) -> TrustedTypeName {
+ match self {
+ Self::TrustedHTML(_) => TrustedTypeName::TrustedHTML,
+ Self::TrustedScript(_) => TrustedTypeName::TrustedScript,
+ Self::TrustedScriptURL(_) => TrustedTypeName::TrustedScriptURL,
+ }
+ }
+
+ fn create(vm: &Vm, trusted_type_name: TrustedTypeName, data_string: Utf16String) -> Self {
+ match trusted_type_name {
+ TrustedTypeName::TrustedHTML => Self::TrustedHTML(TrustedHTML::create(vm, data_string)),
+ TrustedTypeName::TrustedScript => Self::TrustedScript(TrustedScript::create(vm, data_string)),
+ TrustedTypeName::TrustedScriptURL => Self::TrustedScriptURL(TrustedScriptURL::create(vm, data_string)),
+ }
+ }
+}
+
+pub(crate) enum TrustedTypeOrString {
+ TrustedType(TrustedType),
+ String(Utf16String),
+}
+
+impl TrustedTypeOrString {
+ pub(crate) fn stringified(&self) -> Utf16String {
+ match self {
+ Self::TrustedType(value) => value.data().clone(),
+ Self::String(value) => value.clone(),
+ }
+ }
+}
+
+fn stringify(vm: &Vm, trusted_type_name: TrustedTypeName, policy_value: Value) -> WebIdlResult<Utf16String> {
+ match trusted_type_name {
+ TrustedTypeName::TrustedHTML | TrustedTypeName::TrustedScript => Ok(to_dom_string(vm, policy_value)?),
+ TrustedTypeName::TrustedScriptURL => Ok(to_usv_string(vm, policy_value)?.into()),
+ }
+}
+
+/// https://w3c.github.io/trusted-types/dist/spec/#trusted-type-policy
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct TrustedTypePolicy {
+ name: Utf16String,
+ create_html: Option<CallbackFunction>,
+ create_script: Option<CallbackFunction>,
+ create_script_url: Option<CallbackFunction>,
+ create_parser_options: Option<CallbackFunction>,
+}
+
+impl Wrappable for TrustedTypePolicy {}
+
+impl TrustedTypePolicy {
+ pub(crate) fn new(name: Utf16String, options: TrustedTypePolicyOptions) -> Self {
+ Self {
+ name,
+ create_html: options.create_html,
+ create_script: options.create_script,
+ create_script_url: options.create_script_url,
+ create_parser_options: options.create_parser_options,
+ }
+ }
+
+ pub(crate) fn create_parser_options_callback(&self) -> Option<&CallbackFunction> {
+ self.create_parser_options.as_ref()
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicy-name
+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.name.clone())
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicy-createhtml
+ pub(crate) fn create_html(
+ &self,
+ cx: &mut CallContext,
+ input: Utf16String,
+ arguments: MarkedVec<'_, Value>,
+ ) -> WebIdlResult<Ref<TrustedHTML>> {
+ // 1. Returns the result of executing the Create a Trusted Type algorithm, with the following arguments:
+ // policy
+ // this value
+ // trustedTypeName
+ // "TrustedHTML"
+ // value
+ // input
+ // arguments
+ // arguments
+ match self.create_a_trusted_type(cx.vm(), TrustedTypeName::TrustedHTML, &input, &arguments)? {
+ TrustedType::TrustedHTML(trusted_html) => Ok(trusted_html),
+ _ => unreachable!("create a trusted type creates an object of the type name"),
+ }
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicy-createscript
+ pub(crate) fn create_script(
+ &self,
+ cx: &mut CallContext,
+ input: Utf16String,
+ arguments: MarkedVec<'_, Value>,
+ ) -> WebIdlResult<Ref<TrustedScript>> {
+ // 1. Returns the result of executing the Create a Trusted Type algorithm, with the following arguments:
+ // policy
+ // this value
+ // trustedTypeName
+ // "TrustedScript"
+ // value
+ // input
+ // arguments
+ // arguments
+ match self.create_a_trusted_type(cx.vm(), TrustedTypeName::TrustedScript, &input, &arguments)? {
+ TrustedType::TrustedScript(trusted_script) => Ok(trusted_script),
+ _ => unreachable!("create a trusted type creates an object of the type name"),
+ }
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicy-createscripturl
+ pub(crate) fn create_script_url(
+ &self,
+ cx: &mut CallContext,
+ input: Utf16String,
+ arguments: MarkedVec<'_, Value>,
+ ) -> WebIdlResult<Ref<TrustedScriptURL>> {
+ // 1. Returns the result of executing the Create a Trusted Type algorithm, with the following arguments:
+ // policy
+ // this value
+ // trustedTypeName
+ // "TrustedScriptURL"
+ // value
+ // input
+ // arguments
+ // arguments
+ match self.create_a_trusted_type(cx.vm(), TrustedTypeName::TrustedScriptURL, &input, &arguments)? {
+ TrustedType::TrustedScriptURL(trusted_script_url) => Ok(trusted_script_url),
+ _ => unreachable!("create a trusted type creates an object of the type name"),
+ }
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicy-createparseroptions
+ pub(crate) fn create_parser_options(
+ &self,
+ cx: &mut CallContext,
+ options: CppDictionary,
+ arguments: MarkedVec<'_, Value>,
+ ) -> WebIdlResult<CppInterface> {
+ let global = cx.realm().global_object();
+ let callback = self
+ .create_parser_options
+ .as_ref()
+ .map_or(core::ptr::null_mut(), CallbackFunction::as_ptr);
+ // SAFETY: The global object, the callback, the options and the arguments are live for the call.
+ let wrapper = unsafe {
+ web_trusted_types_create_parser_options(
+ global.as_ptr().cast(),
+ callback,
+ options.as_ptr(),
+ ak::Span::new(&arguments.values()),
+ )
+ }
+ .into_completion()?;
+ // SAFETY: LibWeb returns the wrapper of a TrustedHTMLParserOptions.
+ Ok(unsafe { CppInterface::from_wrapper(wrapper.as_object()) })
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#create-a-trusted-type-algorithm
+ fn create_a_trusted_type(
+ &self,
+ vm: &Vm,
+ trusted_type_name: TrustedTypeName,
+ value: &Utf16String,
+ arguments: &MarkedVec<'_, Value>,
+ ) -> WebIdlResult<TrustedType> {
+ // 1. Let policyValue be the result of executing Get Trusted Type policy value with the same arguments
+ // as this algorithm and additionally true as throwIfMissing.
+ // 2. If the algorithm threw an error, rethrow the error and abort the following steps.
+ let policy_value =
+ self.get_trusted_type_policy_value(vm, trusted_type_name, value, &arguments.values(), true)?;
+
+ // 3. Let dataString be the result of stringifying policyValue.
+ let mut data_string = stringify(vm, trusted_type_name, policy_value)?;
+
+ // 4. If policyValue is null or undefined, set dataString to the empty string.
+ if policy_value.is_nullish() {
+ data_string = Utf16String::default();
+ }
+
+ // 5. Return a new instance of an interface with a type name trustedTypeName, with its associated data value set to dataString.
+ Ok(TrustedType::create(vm, trusted_type_name, data_string))
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-policy-value
+ fn get_trusted_type_policy_value(
+ &self,
+ vm: &Vm,
+ trusted_type_name: TrustedTypeName,
+ value: &Utf16String,
+ values: &[Value],
+ throw_if_missing: bool,
+ ) -> WebIdlResult<Value> {
+ // 1. Let functionName be a function name for the given trustedTypeName, based on the following table:
+ // 2. Let function be policy’s options[functionName].
+ let function = match trusted_type_name {
+ TrustedTypeName::TrustedHTML => &self.create_html,
+ TrustedTypeName::TrustedScript => &self.create_script,
+ TrustedTypeName::TrustedScriptURL => &self.create_script_url,
+ };
+
+ // 3. If function is null, then:
+ let Some(function) = function else {
+ // 1. If throwIfMissing throw a TypeError.
+ if throw_if_missing {
+ return Err(Exception::type_error(
+ "Trying to create a trusted type without a callback",
+ ));
+ }
+
+ // 2. Else return null
+ return Ok(Value::NULL);
+ };
+
+ // 4. Let args be << value >>.
+ let args = MarkedVec::new(vm);
+ args.push(Value::from_string(PrimitiveString::create(vm, value.clone())));
+
+ // 5. Append each item in arguments to args.
+ args.extend_from_slice(values);
+
+ // 6. Let policyValue be the result of invoking function with args and "rethrow".
+ let policy_value = function.invoke(None, &args.values())?;
+
+ // 7. Return policyValue.
+ Ok(policy_value)
+ }
+}
+
+// https://w3c.github.io/trusted-types/dist/spec/#process-value-with-a-default-policy-algorithm
+pub(crate) fn process_value_with_a_default_policy(
+ vm: &Vm,
+ trusted_type_name: TrustedTypeName,
+ global: Gc<Object>,
+ input: &TrustedTypeOrString,
+ sink: &Utf16String,
+) -> WebIdlResult<Option<TrustedType>> {
+ // 1. Let defaultPolicy be the value of global’s trusted type policy factory’s default policy.
+ let default_policy = trusted_types(global).default_policy_value();
+
+ // This algorithm routes a value to be assigned to an injection sink through a default policy, should one exist.
+ // FIXME: Open an issue upstream. It is not immediately clear what to do if the default policy does not exist.
+ // Ref: https://github.com/w3c/trusted-types/issues/595
+ let Some(default_policy) = default_policy else {
+ return Ok(None);
+ };
+
+ // 2. Let policyValue be the result of executing Get Trusted Type policy value, with the following arguments:
+ // policy:
+ // defaultPolicy
+ // value:
+ // stringified input
+ // trustedTypeName:
+ // expectedType’s type name
+ // arguments:
+ // « trustedTypeName, sink »
+ // throwIfMissing:
+ // false
+ // 3. If the algorithm threw an error, rethrow the error and abort the following steps.
+ let arguments = [
+ Value::from_string(PrimitiveString::create(
+ vm,
+ Utf16String::from_utf8(trusted_type_name.name()),
+ )),
+ Value::from_string(PrimitiveString::create(vm, sink.clone())),
+ ];
+ let policy_value =
+ default_policy.get_trusted_type_policy_value(vm, trusted_type_name, &input.stringified(), &arguments, false)?;
+
+ // 4. If policyValue is null or undefined, return policyValue.
+ if policy_value.is_nullish() {
+ return Ok(None);
+ }
+
+ // 5. Let dataString be the result of stringifying policyValue.
+ let data_string = stringify(vm, trusted_type_name, policy_value)?;
+
+ // 6. Return a new instance of an interface with a type name trustedTypeName, with its associated data value set to dataString.
+ Ok(Some(TrustedType::create(vm, trusted_type_name, data_string)))
+}
+
+// https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-compliant-string-algorithm
+pub(crate) fn get_trusted_type_compliant_string(
+ vm: &Vm,
+ expected_type: TrustedTypeName,
+ global: Gc<Object>,
+ input: &TrustedTypeOrString,
+ sink: &Utf16String,
+ sink_group: &Utf16String,
+) -> WebIdlResult<Utf16String> {
+ // 1. If input is an instance of expectedType, return stringified input and abort these steps.
+ if let TrustedTypeOrString::TrustedType(value) = input
+ && value.type_name() == expected_type
+ {
+ return Ok(value.data().clone());
+ }
+
+ // 2. Let requireTrustedTypes be the result of executing Does sink type require trusted types? algorithm, passing global, sinkGroup, and true.
+ let require_trusted_types = does_sink_require_trusted_types(global, sink_group, true);
+
+ // 3. If requireTrustedTypes is false, return stringified input and abort these steps.
+ if !require_trusted_types {
+ return Ok(input.stringified());
+ }
+
+ // 4. Let convertedInput be the result of executing Process value with a default policy with the same arguments as this algorithm.
+ // 5. If the algorithm threw an error, rethrow the error and abort the following steps.
+ let converted_input = process_value_with_a_default_policy(vm, expected_type, global, input, sink)?;
+
+ // 6. If convertedInput is null or undefined, execute the following steps:
+ let Some(converted_input) = converted_input else {
+ // 1. Let disposition be the result of executing Should sink type mismatch violation be blocked by Content Security Policy?
+ // algorithm, passing global, stringified input as source, sinkGroup and sink.
+ let blocked = should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(
+ global,
+ sink,
+ sink_group,
+ &input.stringified(),
+ );
+
+ // 2. If disposition is “Allowed”, return stringified input and abort further steps.
+ if !blocked {
+ return Ok(input.stringified());
+ }
+
+ // 3. Throw a TypeError and abort further steps.
+ return Err(Exception::TypeError(utf16_formatted(
+ "Sink {} of type {} requires a TrustedType to be used",
+ &[sink, sink_group],
+ )));
+ };
+
+ // 7. Assert: convertedInput is an instance of expectedType.
+ assert!(converted_input.type_name() == expected_type);
+
+ // 8. Return stringified convertedInput.
+ Ok(converted_input.data().clone())
+}
+
+// https://w3c.github.io/trusted-types/dist/spec/#validate-attribute-mutation
+pub(crate) fn get_trusted_types_compliant_attribute_value(
+ vm: &Vm,
+ attribute_name: &Utf16String,
+ attribute_ns: Option<&Utf16String>,
+ element_local_name: &Utf16String,
+ element_namespace: &Utf16String,
+ global: Gc<Object>,
+ new_value: &TrustedTypeOrString,
+) -> WebIdlResult<Utf16String> {
+ // 1. If attributeNs is the empty string, set attributeNs to null.
+ let attribute_ns = attribute_ns.filter(|attribute_ns| !attribute_ns.is_empty());
+
+ // 2. Set attributeData to the result of Get Trusted Type data for attribute algorithm, with the following arguments:
+ // element
+ // attributeName
+ // attributeNs
+ let attribute_data = get_trusted_type_data_for_attribute(
+ &element_interface(element_local_name, element_namespace),
+ attribute_name,
+ attribute_ns,
+ );
+
+ // 3. If attributeData is null, then:
+ let Some(attribute_data) = attribute_data else {
+ // 1. If newValue is a string, return newValue.
+ // 2. Assert: newValue is TrustedHTML or TrustedScript or TrustedScriptURL.
+ // 3. Return value’s associated data.
+ // FIXME: This is badly worded in the spec it should say "Return stringified newvalues's"
+ return Ok(new_value.stringified());
+ };
+
+ // 4. Let expectedType be the value of the fourth member of attributeData.
+ let expected_type = attribute_data.trusted_type;
+
+ // 5. Let sink be the value of the fifth member of attributeData.
+ let sink = attribute_data.sink;
+
+ // 6. Return the result of executing Get Trusted Type compliant string with the following arguments:
+ // expectedType
+ // newValue as input
+ // element’s node document’s relevant global object as global
+ // sink
+ // 'script' as sinkGroup
+ get_trusted_type_compliant_string(
+ vm,
+ expected_type,
+ global,
+ new_value,
+ &sink,
+ &Utf16String::from_utf8(SCRIPT_SINK_GROUP),
+ )
+}
+
+/// https://w3c.github.io/trusted-types/dist/spec/#trusted-types-sink-group
+pub(crate) const SCRIPT_SINK_GROUP: &str = "'script'";
+
+// FIXME: Add-hoc definition of an element interface
+pub(crate) struct ElementInterface {
+ pub(crate) element_name: &'static str,
+ pub(crate) element_ns: Utf16String,
+}
+
+pub(crate) fn element_interface(local_name: &Utf16String, element_ns: &Utf16String) -> ElementInterface {
+ // FIXME: We don't have a method in ElementFactory that can give us the interface name but these are all the cases
+ // we care about in the table in get_trusted_type_data_for_attribute function
+ let local_name_view = Utf16View::of_string(local_name);
+ let element_ns_view = Utf16View::of_string(element_ns);
+ let element_name = if local_name_view == "iframe" && element_ns_view == HTML_NAMESPACE {
+ "HTMLIFrameElement"
+ } else if local_name_view == "script" && element_ns_view == HTML_NAMESPACE {
+ "HTMLScriptElement"
+ } else if local_name_view == "script" && element_ns_view == SVG_NAMESPACE {
+ "SVGScriptElement"
+ } else {
+ "Element"
+ };
+ ElementInterface {
+ element_name,
+ element_ns: element_ns.clone(),
+ }
+}
+
+/// What a Rust export of the algorithms tells C++: a string, a thrown value, or the message of a TypeError.
+#[repr(u8)]
+enum AlgorithmResultAbi {
+ Normal = 0,
+ Thrown = 1,
+ TypeError = 2,
+}
+
+/// The result, written to `string` (a raw AK::Utf16String handed over) or `exception`.
+///
+/// # Safety
+///
+/// `string` and `exception` must be writable.
+unsafe fn result_into_abi(result: WebIdlResult<Utf16String>, string: *mut usize, exception: *mut u64) -> u8 {
+ // SAFETY: The caller passes writable pointers.
+ unsafe {
+ match result {
+ Ok(value) => {
+ *string = value.into_raw();
+ AlgorithmResultAbi::Normal as u8
+ }
+ Err(Exception::Thrown(throw)) => {
+ *exception = throw.value().to_raw();
+ AlgorithmResultAbi::Thrown as u8
+ }
+ Err(Exception::TypeError(message)) => {
+ *string = message.into_raw();
+ AlgorithmResultAbi::TypeError as u8
+ }
+ Err(_) => unreachable!("the Trusted Types algorithms throw only TypeErrors"),
+ }
+ }
+}
+
+/// The TrustedType or string that C++ passes: a cell of the kind's interface, or a raw AK::Utf16String it hands over.
+///
+/// # Safety
+///
+/// `cell` must be a live cell of the interface of `kind` (TrustedTypeName + 1), or `string` a live raw string if `kind`
+/// is 0.
+unsafe fn trusted_type_or_string_from_abi(kind: u8, cell: *mut c_void, string: usize) -> TrustedTypeOrString {
+ // SAFETY: The caller passes a live cell of the interface, or a live string.
+ unsafe {
+ match kind {
+ 0 => TrustedTypeOrString::String(Utf16String::from_raw_owned(string)),
+ 1 => TrustedTypeOrString::TrustedType(TrustedType::TrustedHTML(cell_from_abi(cell))),
+ 2 => TrustedTypeOrString::TrustedType(TrustedType::TrustedScript(cell_from_abi(cell))),
+ 3 => TrustedTypeOrString::TrustedType(TrustedType::TrustedScriptURL(cell_from_abi(cell))),
+ _ => unreachable!("{kind} is not a kind of TrustedType or string"),
+ }
+ }
+}
+
+/// https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-compliant-string-algorithm
+///
+/// # Safety
+///
+/// `vm` must be the live VM and `global` a live global object. `input_kind`, `input_cell` and `input_string` must be
+/// as trusted_type_or_string_from_abi() takes them, `sink` and `sink_group` raw strings that C++ hands over, and
+/// `string` and `exception` writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_trusted_types_get_trusted_type_compliant_string(
+ vm: *mut c_void,
+ expected_type: u8,
+ global: *mut c_void,
+ input_kind: u8,
+ input_cell: *mut c_void,
+ input_string: usize,
+ sink: usize,
+ sink_group: usize,
+ string: *mut usize,
+ exception: *mut u64,
+) -> u8 {
+ // SAFETY: The caller passes the live VM, a live global object, a live input and live strings.
+ let (vm, global, input, sink, sink_group) = unsafe {
+ (
+ &*vm.cast::<Vm>(),
+ Gc::from_non_null(NonNull::new(global.cast::<Object>()).expect("C++ passes a global object")),
+ trusted_type_or_string_from_abi(input_kind, input_cell, input_string),
+ Utf16String::from_raw_owned(sink),
+ Utf16String::from_raw_owned(sink_group),
+ )
+ };
+ let result = get_trusted_type_compliant_string(
+ vm,
+ TrustedTypeName::from_abi(expected_type),
+ global,
+ &input,
+ &sink,
+ &sink_group,
+ );
+ // SAFETY: The caller passes writable pointers.
+ unsafe { result_into_abi(result, string, exception) }
+}
+
+/// https://w3c.github.io/trusted-types/dist/spec/#validate-attribute-mutation
+///
+/// # Safety
+///
+/// As web_rust_trusted_types_get_trusted_type_compliant_string(), with `attribute_ns` a live raw string if
+/// `has_attribute_ns`, and the names raw strings that C++ hands over.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_trusted_types_get_trusted_types_compliant_attribute_value(
+ vm: *mut c_void,
+ attribute_name: usize,
+ has_attribute_ns: bool,
+ attribute_ns: usize,
+ element_local_name: usize,
+ element_namespace: usize,
+ global: *mut c_void,
+ input_kind: u8,
+ input_cell: *mut c_void,
+ input_string: usize,
+ string: *mut usize,
+ exception: *mut u64,
+) -> u8 {
+ // SAFETY: The caller passes the live VM, a live global object, a live input and live strings.
+ let (vm, global, input, attribute_name, attribute_ns, element_local_name, element_namespace) = unsafe {
+ (
+ &*vm.cast::<Vm>(),
+ Gc::from_non_null(NonNull::new(global.cast::<Object>()).expect("C++ passes a global object")),
+ trusted_type_or_string_from_abi(input_kind, input_cell, input_string),
+ Utf16String::from_raw_owned(attribute_name),
+ has_attribute_ns.then(|| Utf16String::from_raw_owned(attribute_ns)),
+ Utf16String::from_raw_owned(element_local_name),
+ Utf16String::from_raw_owned(element_namespace),
+ )
+ };
+ let result = get_trusted_types_compliant_attribute_value(
+ vm,
+ &attribute_name,
+ attribute_ns.as_ref(),
+ &element_local_name,
+ &element_namespace,
+ global,
+ &input,
+ );
+ // SAFETY: The caller passes writable pointers.
+ unsafe { result_into_abi(result, string, exception) }
+}
+
+/// https://w3c.github.io/trusted-types/dist/spec/#process-value-with-a-default-policy-algorithm
+///
+/// # Safety
+///
+/// As web_rust_trusted_types_get_trusted_type_compliant_string(), with `result` writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_trusted_types_process_value_with_a_default_policy(
+ vm: *mut c_void,
+ trusted_type_name: u8,
+ global: *mut c_void,
+ input_kind: u8,
+ input_cell: *mut c_void,
+ input_string: usize,
+ sink: usize,
+ result: *mut *mut c_void,
+ exception: *mut u64,
+) -> bool {
+ // SAFETY: The caller passes the live VM, a live global object, a live input and a live string.
+ let (vm, global, input, sink) = unsafe {
+ (
+ &*vm.cast::<Vm>(),
+ Gc::from_non_null(NonNull::new(global.cast::<Object>()).expect("C++ passes a global object")),
+ trusted_type_or_string_from_abi(input_kind, input_cell, input_string),
+ Utf16String::from_raw_owned(sink),
+ )
+ };
+ let converted =
+ process_value_with_a_default_policy(vm, TrustedTypeName::from_abi(trusted_type_name), global, &input, &sink);
+ // SAFETY: The caller passes writable pointers.
+ unsafe {
+ match converted {
+ Ok(converted) => {
+ *result = match converted {
+ None => core::ptr::null_mut(),
+ Some(TrustedType::TrustedHTML(value)) => cell_into_abi(value),
+ Some(TrustedType::TrustedScript(value)) => cell_into_abi(value),
+ Some(TrustedType::TrustedScriptURL(value)) => cell_into_abi(value),
+ };
+ false
+ }
+ Err(Exception::Thrown(throw)) => {
+ *exception = throw.value().to_raw();
+ true
+ }
+ Err(_) => unreachable!("process value with a default policy throws only what the policy throws"),
+ }
+ }
+}
+
+/// The policy's options["createParserOptions"], or null.
+///
+/// # Safety
+///
+/// `policy` must be the live cell of a TrustedTypePolicy.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_trusted_types_trusted_type_policy_create_parser_options(
+ policy: *mut c_void,
+) -> *mut c_void {
+ // SAFETY: The caller passes a live cell.
+ unsafe { cell_from_abi::<TrustedTypePolicy>(policy) }
+ .create_parser_options_callback()
+ .map_or(core::ptr::null_mut(), CallbackFunction::as_ptr)
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/trusted_types/trusted_type_policy_factory.rs b/Libraries/LibWeb/Bindings/Rust/src/trusted_types/trusted_type_policy_factory.rs
new file mode 100644
index 00000000000..e814bff3e43
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/trusted_types/trusted_type_policy_factory.rs
@@ -0,0 +1,400 @@
+/*
+ * Copyright (c) 2025, Miguel Sacristán Izcue <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! TrustedTypePolicyFactory, https://w3c.github.io/trusted-types/dist/spec/#trustedtypepolicyfactory
+
+use core::cell::{Cell, RefCell};
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::{Gc, Object, Realm, Trace, Utf16View, Value, Vm, utf16_formatted};
+
+use crate::bindings::global_object::relevant_global_object;
+use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, implementation_if_wrapper};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::html::global_event_handlers::is_event_handler_content_attribute;
+use crate::trusted_types::require_trusted_types_for_directive::should_trusted_type_policy_creation_be_blocked_by_content_security_policy;
+use crate::trusted_types::trusted_html::TrustedHTML;
+use crate::trusted_types::trusted_script::TrustedScript;
+use crate::trusted_types::trusted_script_url::TrustedScriptURL;
+use crate::trusted_types::trusted_type_policy::{
+ ElementInterface, TrustedTypeName, TrustedTypePolicy, TrustedTypePolicyOptions, element_interface,
+};
+
+pub(crate) const HTML_NAMESPACE: &str = "http://www.w3.org/1999/xhtml";
+pub(crate) const SVG_NAMESPACE: &str = "http://www.w3.org/2000/svg";
+pub(crate) const MATHML_NAMESPACE: &str = "http://www.w3.org/1998/Math/MathML";
+const XLINK_NAMESPACE: &str = "http://www.w3.org/1999/xlink";
+
+/// https://w3c.github.io/trusted-types/dist/spec/#trustedtypepolicyfactory
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct TrustedTypePolicyFactory {
+ realm: Gc<Realm>,
+
+ // https://w3c.github.io/trusted-types/dist/spec/#trustedtypepolicyfactory-created-policy-names
+ #[gc(untraced)]
+ created_policy_names: RefCell<Vec<Utf16String>>,
+
+ // https://w3c.github.io/trusted-types/dist/spec/#trustedtypepolicyfactory-default-policy
+ default_policy: Cell<Option<Ref<TrustedTypePolicy>>>,
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-emptyhtml
+ empty_html: Cell<Option<Ref<TrustedHTML>>>,
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-emptyscript
+ empty_script: Cell<Option<Ref<TrustedScript>>>,
+}
+
+impl Wrappable for TrustedTypePolicyFactory {
+ fn relevant_realm(&self) -> Option<Gc<Realm>> {
+ Some(self.realm)
+ }
+}
+
+impl TrustedTypePolicyFactory {
+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ realm,
+ created_policy_names: RefCell::new(Vec::new()),
+ default_policy: Cell::new(None),
+ empty_html: Cell::new(None),
+ empty_script: Cell::new(None),
+ })
+ }
+
+ pub(crate) fn default_policy_value(&self) -> Option<Ref<TrustedTypePolicy>> {
+ self.default_policy.get()
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-getattributetype
+ pub(crate) fn get_attribute_type(
+ &self,
+ _: &mut CallContext,
+ tag_name: Utf16String,
+ attribute: Utf16String,
+ element_ns: Option<Utf16String>,
+ attr_ns: Option<Utf16String>,
+ ) -> WebIdlResult<Option<Utf16String>> {
+ // 1. Set localName to tagName in ASCII lowercase.
+ let local_name = tag_name.to_ascii_lowercase();
+
+ // 2. Set attribute to attribute in ASCII lowercase.
+ let attribute_local_name = attribute.to_ascii_lowercase();
+
+ // 3. If elementNs is null or an empty string, set elementNs to HTML namespace.
+ let element_namespace = match element_ns {
+ Some(element_ns) if !element_ns.is_empty() => element_ns,
+ _ => Utf16String::from_utf8(HTML_NAMESPACE),
+ };
+
+ // 4. If attrNs is an empty string, set attrNs to null.
+ let attr_ns = attr_ns.filter(|attr_ns| !attr_ns.is_empty());
+
+ // 5. Let interface be the element interface for localName and elementNs.
+ let interface = element_interface(&local_name, &element_namespace);
+
+ // 6. Let expectedType be null.
+ let mut expected_type = None;
+
+ // 7. Set attributeData to the result of Get Trusted Type data for attribute algorithm,
+ // with the following arguments, interface as element, attribute, attrNs
+ let attribute_data = get_trusted_type_data_for_attribute(&interface, &attribute_local_name, attr_ns.as_ref());
+
+ // 8. If attributeData is not null, then set expectedType to the interface’s name of the value of the fourth member of attributeData.
+ if let Some(attribute_data) = attribute_data {
+ expected_type = Some(Utf16String::from_utf8(attribute_data.trusted_type.name()));
+ }
+
+ // 9. Return expectedType.
+ Ok(expected_type)
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-getpropertytype
+ pub(crate) fn get_property_type(
+ &self,
+ _: &mut CallContext,
+ tag_name: Utf16String,
+ property: Utf16String,
+ element_ns: Option<Utf16String>,
+ ) -> WebIdlResult<Option<Utf16String>> {
+ // 1. Set localName to tagName in ASCII lowercase.
+ let local_name = tag_name.to_ascii_lowercase();
+
+ // 2. If elementNs is null or an empty string, set elementNs to HTML namespace.
+ let element_namespace = match element_ns {
+ Some(element_ns) if !element_ns.is_empty() => element_ns,
+ _ => Utf16String::from_utf8(HTML_NAMESPACE),
+ };
+
+ // FIXME: We don't have a method in ElementFactory that can give us the interface name but these are all the cases
+ // we care about in the table in get_trusted_type_data_for_attribute function
+ // 3. Let interface be the element interface for localName and elementNs.
+ let local_name = Utf16View::of_string(&local_name);
+ let is_html = Utf16View::of_string(&element_namespace) == HTML_NAMESPACE;
+ let interface = if local_name == "iframe" && is_html {
+ "HTMLIFrameElement"
+ } else if local_name == "script" && is_html {
+ "HTMLScriptElement"
+ } else {
+ "Element"
+ };
+
+ // 4. Let expectedType be null.
+ let mut expected_type = None;
+
+ const TABLE: [(&str, &str, TrustedTypeName); 7] = [
+ ("HTMLIFrameElement", "srcdoc", TrustedTypeName::TrustedHTML),
+ ("HTMLScriptElement", "innerText", TrustedTypeName::TrustedScript),
+ ("HTMLScriptElement", "src", TrustedTypeName::TrustedScriptURL),
+ ("HTMLScriptElement", "text", TrustedTypeName::TrustedScript),
+ ("HTMLScriptElement", "textContent", TrustedTypeName::TrustedScript),
+ ("*", "innerHTML", TrustedTypeName::TrustedHTML),
+ ("*", "outerHTML", TrustedTypeName::TrustedHTML),
+ ];
+
+ // 5. Find the row in the following table, where the first column is "*" or interface’s name, and property is in the second column.
+ // If a matching row is found, set expectedType to the interface’s name of the value of the third column.
+ let property = Utf16View::of_string(&property);
+ let matching_row = TABLE.iter().find(|(row_interface, row_property, _)| {
+ (*row_interface == interface || *row_interface == "*") && property == *row_property
+ });
+
+ if let Some((_, _, trusted_type)) = matching_row {
+ expected_type = Some(Utf16String::from_utf8(trusted_type.name()));
+ }
+
+ // 6. Return expectedType.
+ Ok(expected_type)
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-createpolicy
+ pub(crate) fn create_policy(
+ &self,
+ cx: &mut CallContext,
+ policy_name: Utf16String,
+ policy_options: TrustedTypePolicyOptions,
+ ) -> WebIdlResult<Ref<TrustedTypePolicy>> {
+ // 1. Returns the result of executing a Create a Trusted Type Policy algorithm, with the following arguments:
+ // factory: this value
+ // policyName: policyName
+ // options: policyOptions
+ // global: this value’s relevant global object
+ self.create_a_trusted_type_policy(cx, policy_name, policy_options, relevant_global_object(self))
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-ishtml
+ pub(crate) fn is_html(&self, _: &mut CallContext, value: Value) -> WebIdlResult<bool> {
+ // 1. Returns true if value is an instance of TrustedHTML and has an associated data value set, false otherwise.
+ Ok(value.is_object() && implementation_if_wrapper::<TrustedHTML>(value.as_object()).is_some())
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-isscript
+ pub(crate) fn is_script(&self, _: &mut CallContext, value: Value) -> WebIdlResult<bool> {
+ // 1. Returns true if value is an instance of TrustedScript and has an associated data value set, false otherwise.
+ Ok(value.is_object() && implementation_if_wrapper::<TrustedScript>(value.as_object()).is_some())
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-isscripturl
+ pub(crate) fn is_script_url(&self, _: &mut CallContext, value: Value) -> WebIdlResult<bool> {
+ // 1. Returns true if value is an instance of TrustedScriptURL and has an associated data value set, false otherwise.
+ Ok(value.is_object() && implementation_if_wrapper::<TrustedScriptURL>(value.as_object()).is_some())
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-emptyhtml
+ pub(crate) fn empty_html(&self, cx: &mut CallContext) -> WebIdlResult<Ref<TrustedHTML>> {
+ if let Some(empty_html) = self.empty_html.get() {
+ return Ok(empty_html);
+ }
+ let empty_html = TrustedHTML::create(cx.vm(), Utf16String::default());
+ self.empty_html.set(Some(empty_html));
+ Ok(empty_html)
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-emptyscript
+ pub(crate) fn empty_script(&self, cx: &mut CallContext) -> WebIdlResult<Ref<TrustedScript>> {
+ if let Some(empty_script) = self.empty_script.get() {
+ return Ok(empty_script);
+ }
+ let empty_script = TrustedScript::create(cx.vm(), Utf16String::default());
+ self.empty_script.set(Some(empty_script));
+ Ok(empty_script)
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-defaultpolicy
+ pub(crate) fn default_policy(&self, _: &mut CallContext) -> WebIdlResult<Option<Ref<TrustedTypePolicy>>> {
+ Ok(self.default_policy.get())
+ }
+
+ // https://w3c.github.io/trusted-types/dist/spec/#create-trusted-type-policy-algorithm
+ fn create_a_trusted_type_policy(
+ &self,
+ cx: &CallContext,
+ policy_name: Utf16String,
+ options: TrustedTypePolicyOptions,
+ global: Gc<Object>,
+ ) -> WebIdlResult<Ref<TrustedTypePolicy>> {
+ // 1. Let allowedByCSP be the result of executing Should Trusted Type policy creation be blocked by Content Security Policy? algorithm with global, policyName and factory’s created policy names value.
+ let blocked = should_trusted_type_policy_creation_be_blocked_by_content_security_policy(
+ cx.realm(),
+ global,
+ &policy_name,
+ &self.created_policy_names.borrow(),
+ );
+
+ // 2. If allowedByCSP is "Blocked", throw a TypeError and abort further steps.
+ if blocked {
+ return Err(Exception::TypeError(utf16_formatted(
+ "Content Security Policy blocked the creation of the policy {}",
+ &[&policy_name],
+ )));
+ }
+
+ // 3. If policyName is default and the factory’s default policy value is not null, throw a TypeError and abort further steps.
+ let is_default = Utf16View::of_string(&policy_name) == "default";
+ if is_default && self.default_policy.get().is_some() {
+ return Err(Exception::type_error(
+ "Policy Factory already has a default value defined",
+ ));
+ }
+
+ // 4. Let policy be a new TrustedTypePolicy object.
+ // 5. Set policy’s name property value to policyName.
+ // 6. Set policy’s options value to «[ "createHTML" -> options["createHTML", "createScript" -> options["createScript", "createScriptURL" -> options["createScriptURL" ]».
+ let policy = allocate(cx.vm(), |_| TrustedTypePolicy::new(policy_name.clone(), options));
+
+ // 7. If the policyName is default, set the factory’s default policy value to policy.
+ if is_default {
+ self.default_policy.set(Some(policy));
+ }
+
+ // 8. Append policyName to factory’s created policy names.
+ self.created_policy_names.borrow_mut().push(policy_name);
+
+ // 9. Return policy.
+ Ok(policy)
+ }
+}
+
+pub(crate) struct TrustedTypeData {
+ pub(crate) trusted_type: TrustedTypeName,
+ pub(crate) sink: Utf16String,
+}
+
+// https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-data-for-attribute
+pub(crate) fn get_trusted_type_data_for_attribute(
+ element: &ElementInterface,
+ attribute: &Utf16String,
+ attribute_ns: Option<&Utf16String>,
+) -> Option<TrustedTypeData> {
+ // 1. Let data be null.
+
+ let element_name = element.element_name;
+ let element_ns = Utf16View::of_string(&element.element_ns);
+ let attribute_view = Utf16View::of_string(attribute);
+
+ // 2. If attributeNs is null, « HTML namespace, SVG namespace, MathML namespace » contains element’s namespace, and attribute is the name of an event handler content attribute:
+ if attribute_view.starts_with(Utf16View::Ascii(b"on"))
+ && attribute_ns.is_none()
+ && (element_ns == HTML_NAMESPACE || element_ns == SVG_NAMESPACE || element_ns == MATHML_NAMESPACE)
+ && is_event_handler_content_attribute(attribute)
+ {
+ // 1. Return (Element, null, attribute, TrustedScript, "Element " + attribute).
+ return Some(TrustedTypeData {
+ trusted_type: TrustedTypeName::TrustedScript,
+ sink: utf16_formatted("Element {}", &[attribute]),
+ });
+ }
+
+ // OPTIMIZATION: Every remaining row has one of these three attribute names.
+ if !(attribute_view == "srcdoc" || attribute_view == "src" || attribute_view == "href") {
+ return None;
+ }
+
+ const TABLE: [(&str, Option<&str>, &str, TrustedTypeName, &str); 4] = [
+ (
+ "HTMLIFrameElement",
+ None,
+ "srcdoc",
+ TrustedTypeName::TrustedHTML,
+ "HTMLIFrameElement srcdoc",
+ ),
+ (
+ "HTMLScriptElement",
+ None,
+ "src",
+ TrustedTypeName::TrustedScriptURL,
+ "HTMLScriptElement src",
+ ),
+ (
+ "SVGScriptElement",
+ None,
+ "href",
+ TrustedTypeName::TrustedScriptURL,
+ "SVGScriptElement href",
+ ),
+ (
+ "SVGScriptElement",
+ Some(XLINK_NAMESPACE),
+ "href",
+ TrustedTypeName::TrustedScriptURL,
+ "SVGScriptElement href",
+ ),
+ ];
+
+ // 3. Find the row in the following table, where element is in the first column, attributeNs is in the second column,
+ // and attribute is in the third column. If a matching row is found, set data to that row.
+ let data = TABLE
+ .iter()
+ .find(|(row_element, row_attribute_ns, row_attribute, _, _)| {
+ *row_element == element_name
+ && match (row_attribute_ns, attribute_ns) {
+ (None, None) => true,
+ (Some(row_attribute_ns), Some(attribute_ns)) => {
+ Utf16View::of_string(attribute_ns) == *row_attribute_ns
+ }
+ _ => false,
+ }
+ && attribute_view == *row_attribute
+ });
+
+ // 4. Return data
+ data.map(|(_, _, _, trusted_type, sink)| TrustedTypeData {
+ trusted_type: *trusted_type,
+ sink: Utf16String::from_utf8(sink),
+ })
+}
+
+/// A new TrustedTypePolicyFactory for the global object of the realm.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `realm` the live realm of a Window or a WorkerGlobalScope.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_trusted_types_create_trusted_type_policy_factory(
+ vm: *mut c_void,
+ realm: *mut c_void,
+) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and a live realm.
+ let (vm, realm) = unsafe { crate::bindings::interface::realm_arguments(vm, realm) };
+ cell_into_abi(TrustedTypePolicyFactory::create(vm, realm))
+}
+
+/// The factory's default policy, or null.
+///
+/// # Safety
+///
+/// `factory` must be the live cell of a TrustedTypePolicyFactory.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_trusted_types_trusted_type_policy_factory_default_policy(
+ factory: *mut c_void,
+) -> *mut c_void {
+ // SAFETY: The caller passes a live cell.
+ unsafe { cell_from_abi::<TrustedTypePolicyFactory>(factory) }
+ .default_policy_value()
+ .map_or(core::ptr::null_mut(), cell_into_abi)
+}
diff --git a/Libraries/LibWeb/HTML/GlobalEventHandlers.cpp b/Libraries/LibWeb/HTML/GlobalEventHandlers.cpp
index d0db416cc04..0c77f396333 100644
--- a/Libraries/LibWeb/HTML/GlobalEventHandlers.cpp
+++ b/Libraries/LibWeb/HTML/GlobalEventHandlers.cpp
@@ -5,8 +5,10 @@
*/
#include <LibWeb/DOM/EventTarget.h>
+#include <LibWeb/HTML/AttributeNames.h>
#include <LibWeb/HTML/EventNames.h>
#include <LibWeb/HTML/GlobalEventHandlers.h>
+#include <LibWeb/HTML/WindowEventHandlers.h>
#include <LibWeb/UIEvents/EventNames.h>
namespace Web::HTML {
@@ -29,4 +31,22 @@ ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
GlobalEventHandlers::~GlobalEventHandlers() = default;
+extern "C" {
+
+// Called by Bindings/Rust/src/html/global_event_handlers.rs.
+bool web_html_is_event_handler_content_attribute(FlatPtr name);
+
+bool web_html_is_event_handler_content_attribute(FlatPtr name)
+{
+ auto attribute = Utf16String::from_raw(name);
+#define __ENUMERATE(attribute_name, event_name) \
+ if (attribute.utf16_view() == HTML::AttributeNames::attribute_name.view()) \
+ return true;
+ ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
+ ENUMERATE_WINDOW_EVENT_HANDLERS(__ENUMERATE)
+#undef __ENUMERATE
+ return false;
+}
+}
+
}
diff --git a/Libraries/LibWeb/HTML/Sanitizer.idl b/Libraries/LibWeb/HTML/Sanitizer.idl
index f5df3561288..92ac2f05637 100644
--- a/Libraries/LibWeb/HTML/Sanitizer.idl
+++ b/Libraries/LibWeb/HTML/Sanitizer.idl
@@ -7,6 +7,7 @@ dictionary SetHTMLOptions {
};
// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sethtmlunsafeoptions
+[ImplementedIn=Cpp]
dictionary SetHTMLUnsafeOptions {
(Sanitizer or SanitizerConfig or SanitizerPresets) sanitizer;
boolean runScripts = false;
diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
index e61eb98b5c8..a594bd5baf2 100644
--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
@@ -1499,10 +1499,23 @@ GC::Ref<ServiceWorker::CacheStorage> WindowOrWorkerGlobalScopeMixin::caches()
GC::Ref<TrustedTypes::TrustedTypePolicyFactory> WindowOrWorkerGlobalScopeMixin::trusted_types()
{
if (!m_trusted_type_policy_factory)
- m_trusted_type_policy_factory = GC::Heap::the().allocate<TrustedTypes::TrustedTypePolicyFactory>(this_impl());
+ m_trusted_type_policy_factory = TrustedTypes::TrustedTypePolicyFactory::create(relevant_realm(*this));
return *m_trusted_type_policy_factory;
}
+extern "C" {
+
+// Called by Bindings/Rust/src/html/window_or_worker_global_scope.rs.
+TrustedTypes::TrustedTypePolicyFactory* web_html_window_or_worker_global_scope_trusted_types(JSObject* global_object);
+
+TrustedTypes::TrustedTypePolicyFactory* web_html_window_or_worker_global_scope_trusted_types(JSObject* global_object)
+{
+ auto* global = window_or_worker_global_scope_from_global_object(*JS::HostABI::object_from_abi(global_object));
+ VERIFY(global);
+ return global->trusted_types().ptr();
+}
+}
+
// https://html.spec.whatwg.org/multipage/webappapis.html#windoworworkerglobalscope-mixin:extract-an-origin
Optional<URL::Origin> WindowOrWorkerGlobalScopeMixin::window_or_worker_global_scope_extract_an_origin() const
{
diff --git a/Libraries/LibWeb/TrustedTypes/BindingsGlue.h b/Libraries/LibWeb/TrustedTypes/BindingsGlue.h
deleted file mode 100644
index 6b9704734e0..00000000000
--- a/Libraries/LibWeb/TrustedTypes/BindingsGlue.h
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/TrustedTypes/TrustedHTMLParserOptions.h>
-#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>
-
-namespace Web::Bindings {
-
-inline WebIDL::ExceptionOr<GC::Ref<TrustedTypes::TrustedHTMLParserOptions>> create_parser_options(JS::Realm& realm, TrustedTypes::TrustedTypePolicy& policy, SetHTMLUnsafeOptions const& options, GC::RootVector<JS::Value> const& arguments)
-{
- return policy.create_parser_options(realm.global_object(), options, arguments);
-}
-
-}
diff --git a/Libraries/LibWeb/TrustedTypes/InjectionSink.h b/Libraries/LibWeb/TrustedTypes/InjectionSink.h
index e3eab9ee9ee..35437f9e725 100644
--- a/Libraries/LibWeb/TrustedTypes/InjectionSink.h
+++ b/Libraries/LibWeb/TrustedTypes/InjectionSink.h
@@ -7,14 +7,9 @@
#pragma once
#include <AK/Utf16String.h>
-#include <LibWeb/HTML/GlobalEventHandlers.h>
-#include <LibWeb/HTML/WindowEventHandlers.h>
namespace Web::TrustedTypes {
-#define EVENT_HANDLERS_INJECTION_SINKS(attribute_name, event_name) \
- __ENUMERATE_INJECTION_SINKS(Element_##attribute_name, "Element " #attribute_name)
-
// https://w3c.github.io/trusted-types/dist/spec/#injection-sink
#define ENUMERATE_INJECTION_SINKS \
__ENUMERATE_INJECTION_SINKS(Document_parseHTMLUnsafe, "Document parseHTMLUnsafe") \
@@ -52,9 +47,7 @@ namespace Web::TrustedTypes {
__ENUMERATE_INJECTION_SINKS(Window_setTimeout, "Window setTimeout") \
__ENUMERATE_INJECTION_SINKS(Worker_constructor, "Worker constructor") \
__ENUMERATE_INJECTION_SINKS(WorkerGlobalScope_setInterval, "WorkerGlobalScope setInterval") \
- __ENUMERATE_INJECTION_SINKS(WorkerGlobalScope_setTimeout, "WorkerGlobalScope setTimeout") \
- ENUMERATE_GLOBAL_EVENT_HANDLERS(EVENT_HANDLERS_INJECTION_SINKS) \
- ENUMERATE_WINDOW_EVENT_HANDLERS(EVENT_HANDLERS_INJECTION_SINKS)
+ __ENUMERATE_INJECTION_SINKS(WorkerGlobalScope_setTimeout, "WorkerGlobalScope setTimeout")
enum class InjectionSink {
#define __ENUMERATE_INJECTION_SINKS(name, value) name,
diff --git a/Libraries/LibWeb/TrustedTypes/RequireTrustedTypesForDirective.cpp b/Libraries/LibWeb/TrustedTypes/RequireTrustedTypesForDirective.cpp
index d2950be482f..fae19dd0622 100644
--- a/Libraries/LibWeb/TrustedTypes/RequireTrustedTypesForDirective.cpp
+++ b/Libraries/LibWeb/TrustedTypes/RequireTrustedTypesForDirective.cpp
@@ -7,6 +7,8 @@
#include <LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h>
#include <AK/Utf16StringBuilder.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibWeb/ContentSecurityPolicy/Directives/KeywordTrustedTypes.h>
#include <LibWeb/ContentSecurityPolicy/Directives/Names.h>
#include <LibWeb/ContentSecurityPolicy/PolicyList.h>
#include <LibWeb/ContentSecurityPolicy/Violation.h>
@@ -145,7 +147,7 @@ bool does_sink_require_trusted_types(JS::Object& global, Utf16View sink_group, I
}
// https://w3c.github.io/trusted-types/dist/spec/#should-block-sink-type-mismatch
-ContentSecurityPolicy::Directives::Directive::Result should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(JS::Object& global, TrustedTypes::InjectionSink sink, Utf16View sink_group, Utf16String source)
+ContentSecurityPolicy::Directives::Directive::Result should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(JS::Object& global, Utf16View sink, Utf16View sink_group, Utf16String source)
{
auto& realm = HTML::relevant_realm(global);
@@ -156,7 +158,7 @@ ContentSecurityPolicy::Directives::Directive::Result should_sink_type_mismatch_v
auto sample = source.substring_view(0);
// 3. If sink is "Function", then:
- if (sink == TrustedTypes::InjectionSink::Function) {
+ if (sink == "Function"sv) {
// 1. If sample starts with "function anonymous", strip that from sample.
if (sample.starts_with("function anonymous"sv)) {
sample = sample.substring_view("function anonymous"sv.length());
@@ -208,7 +210,7 @@ ContentSecurityPolicy::Directives::Directive::Result should_sink_type_mismatch_v
// 7. Set violation’s sample to be the result of concatenating the list « sink, trimmedSample « using "|" as a separator.
Utf16StringBuilder sample_builder;
- sample_builder.append(to_string(sink));
+ sample_builder.append(sink);
sample_builder.append_ascii('|');
sample_builder.append(trimmed_sample);
violation->set_sample(sample_builder.to_string());
@@ -225,4 +227,102 @@ ContentSecurityPolicy::Directives::Directive::Result should_sink_type_mismatch_v
return result;
}
+// https://w3c.github.io/trusted-types/dist/spec/#should-block-create-policy
+ContentSecurityPolicy::Directives::Directive::Result should_trusted_type_policy_creation_be_blocked_by_content_security_policy(JS::Realm& realm, JS::Object& global, Utf16String const& policy_name, ReadonlySpan<Utf16String> created_policy_names)
+{
+ // 1. Let result be "Allowed".
+ auto result = ContentSecurityPolicy::Directives::Directive::Result::Allowed;
+
+ // 2. For each policy in global’s CSP list:
+ auto const& csp_list = HTML::relevant_settings_object(global).policy_container()->csp_list;
+ for (auto const& policy : csp_list.policies()) {
+ // 1. Let createViolation be false.
+ bool create_violation = false;
+
+ // 2. If policy’s directive set does not contain a directive which name is "trusted-types", skip to the next policy.
+ if (!policy->contains_directive_with_name(ContentSecurityPolicy::Directives::Names::TrustedTypes))
+ continue;
+
+ // 3. Let directive be the policy’s directive set’s directive which name is "trusted-types"
+ auto const directive = policy->get_directive_by_name(ContentSecurityPolicy::Directives::Names::TrustedTypes);
+
+ // 4. If directive’s value only contains a tt-keyword which is a match for a value 'none', set createViolation to true.
+ if (directive->value().size() == 1 && directive->value().first().equals_ignoring_ascii_case(ContentSecurityPolicy::Directives::KeywordTrustedTypes::None.view()))
+ create_violation = true;
+
+ // 5. If createdPolicyNames contains policyName and directive’s value does not contain a tt-keyword which is a match for a value 'allow-duplicates', set createViolation to true.
+ if (created_policy_names.contains_slow(policy_name)) {
+ auto maybe_allow_duplicates = directive->value().find_if([](auto const& directive_value) {
+ return directive_value.equals_ignoring_ascii_case(ContentSecurityPolicy::Directives::KeywordTrustedTypes::AllowDuplicates.view());
+ });
+ if (maybe_allow_duplicates.is_end())
+ create_violation = true;
+ }
+
+ // 6. If directive’s value does not contain a tt-policy-name, which value is policyName, and directive’s value does not contain a tt-wildcard, set createViolation to true.
+ auto directive_value_iterator = directive->value().find(policy_name);
+ if (directive_value_iterator.is_end()) {
+ auto maybe_wild_card = directive->value().find_if([](auto const& directive_value) {
+ return directive_value.equals_ignoring_ascii_case(ContentSecurityPolicy::Directives::KeywordTrustedTypes::WildCard.view());
+ });
+
+ if (maybe_wild_card.is_end())
+ create_violation = true;
+ }
+
+ // 7. If createViolation is false, skip to the next policy.
+ if (!create_violation)
+ continue;
+
+ // 8. Let violation be the result of executing Create a violation object for global, policy, and directive on global, policy and "trusted-types"
+ auto const violation = ContentSecurityPolicy::Violation::create_a_violation_object_for_global_policy_and_directive(global, policy, ContentSecurityPolicy::Directives::Names::TrustedTypes.view().to_utf8_but_should_be_ported_to_utf16());
+
+ // 9. Set violation’s resource to "trusted-types-policy".
+ violation->set_resource(ContentSecurityPolicy::Violation::Resource::TrustedTypesPolicy);
+
+ // 10. Set violation’s sample to the substring of policyName, containing its first 40 characters.
+ auto sample = policy_name.substring_view(0, min(policy_name.length_in_code_points(), 40));
+ violation->set_sample(Utf16String::from_utf16(sample));
+
+ // 11. Execute Report a violation on violation.
+ violation->report_a_violation(realm);
+
+ // 12. If policy’s disposition is "enforce", then set result to "Blocked".
+ if (policy->disposition() == ContentSecurityPolicy::Policy::Disposition::Enforce)
+ result = ContentSecurityPolicy::Directives::Directive::Result::Blocked;
+ }
+
+ // 3. Return result.
+ return result;
+}
+
+extern "C" {
+
+// Called by Bindings/Rust/src/trusted_types/require_trusted_types_for_directive.rs.
+bool web_trusted_types_does_sink_require_trusted_types(JSObject* global, FlatPtr sink_group, bool include_report_only_policies);
+bool web_trusted_types_should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(JSObject* global, FlatPtr sink, FlatPtr sink_group, FlatPtr source);
+bool web_trusted_types_should_trusted_type_policy_creation_be_blocked_by_content_security_policy(JS::Realm*, JSObject* global, FlatPtr policy_name, ReadonlySpan<FlatPtr> created_policy_names);
+
+bool web_trusted_types_does_sink_require_trusted_types(JSObject* global, FlatPtr sink_group, bool include_report_only_policies)
+{
+ return does_sink_require_trusted_types(*JS::HostABI::object_from_abi(global), Utf16String::from_raw(sink_group), include_report_only_policies ? IncludeReportOnlyPolicies::Yes : IncludeReportOnlyPolicies::No);
+}
+
+bool web_trusted_types_should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(JSObject* global, FlatPtr sink, FlatPtr sink_group, FlatPtr source)
+{
+ return should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(*JS::HostABI::object_from_abi(global), Utf16String::from_raw(sink), Utf16String::from_raw(sink_group), Utf16String::from_raw(source))
+ == ContentSecurityPolicy::Directives::Directive::Result::Blocked;
+}
+
+bool web_trusted_types_should_trusted_type_policy_creation_be_blocked_by_content_security_policy(JS::Realm* realm, JSObject* global, FlatPtr policy_name, ReadonlySpan<FlatPtr> created_policy_names)
+{
+ Vector<Utf16String> names;
+ names.ensure_capacity(created_policy_names.size());
+ for (auto name : created_policy_names)
+ names.unchecked_append(Utf16String::from_raw(name));
+ return should_trusted_type_policy_creation_be_blocked_by_content_security_policy(*realm, *JS::HostABI::object_from_abi(global), Utf16String::from_raw(policy_name), names)
+ == ContentSecurityPolicy::Directives::Directive::Result::Blocked;
+}
+}
+
}
diff --git a/Libraries/LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h b/Libraries/LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h
index 28b7d1f5f7f..656e5bd4e53 100644
--- a/Libraries/LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h
+++ b/Libraries/LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h
@@ -30,6 +30,8 @@ ContentSecurityPolicy::Directives::Directive::Result require_trusted_types_for_p
bool does_sink_require_trusted_types(JS::Object&, Utf16View, IncludeReportOnlyPolicies);
-ContentSecurityPolicy::Directives::Directive::Result should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(JS::Object& global, TrustedTypes::InjectionSink sink, Utf16View sink_group, Utf16String source);
+ContentSecurityPolicy::Directives::Directive::Result should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(JS::Object& global, Utf16View sink, Utf16View sink_group, Utf16String source);
+
+ContentSecurityPolicy::Directives::Directive::Result should_trusted_type_policy_creation_be_blocked_by_content_security_policy(JS::Realm&, JS::Object& global, Utf16String const& policy_name, ReadonlySpan<Utf16String> created_policy_names);
}
diff --git a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.cpp b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.cpp
index cac93632853..8564ef55390 100644
--- a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.cpp
+++ b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.cpp
@@ -6,19 +6,18 @@
#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>
-#include <LibGC/Heap.h>
#include <LibGC/Ptr.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/Value.h>
+#include <LibWeb/Bindings/CppDictionary.h>
#include <LibWeb/Bindings/Sanitizer.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/HTML/Sanitizer.h>
#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/TagNames.h>
#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
#include <LibWeb/Namespace.h>
-#include <LibWeb/SVG/TagNames.h>
#include <LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h>
#include <LibWeb/TrustedTypes/TrustedHTML.h>
#include <LibWeb/TrustedTypes/TrustedHTMLParserOptions.h>
@@ -28,79 +27,33 @@
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/CallbackType.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
+#include <LibWeb/WebIDL/ExceptionOrUtils.h>
namespace Web::TrustedTypes {
-GC_DEFINE_ALLOCATOR(TrustedTypePolicy);
+extern "C" {
+// Defined in Bindings/Rust/src/trusted_types/trusted_type_policy.rs.
+WebIDL::CallbackType* web_rust_trusted_types_trusted_type_policy_create_parser_options(TrustedTypePolicy*);
+u8 web_rust_trusted_types_get_trusted_type_compliant_string(JSVM*, u8 expected_type, JSObject* global, u8 input_kind, void* input_cell, FlatPtr input_string, FlatPtr sink, FlatPtr sink_group, FlatPtr* string, JSValue* exception);
+u8 web_rust_trusted_types_get_trusted_types_compliant_attribute_value(JSVM*, FlatPtr attribute_name, bool has_attribute_ns, FlatPtr attribute_ns, FlatPtr element_local_name, FlatPtr element_namespace, JSObject* global, u8 input_kind, void* input_cell, FlatPtr input_string, FlatPtr* string, JSValue* exception);
+bool web_rust_trusted_types_process_value_with_a_default_policy(JSVM*, u8 trusted_type_name, JSObject* global, u8 input_kind, void* input_cell, FlatPtr input_string, FlatPtr sink, void** result, JSValue* exception);
-TrustedTypePolicy::TrustedTypePolicy(Utf16String const& name, TrustedTypePolicyOptions const& options)
- : m_name(name)
- , m_create_html(options.create_html)
- , m_create_script(options.create_script)
- , m_create_script_url(options.create_script_url)
- , m_create_parser_options(options.create_parser_options)
-{
-}
-
-void TrustedTypePolicy::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_create_html);
- visitor.visit(m_create_script);
- visitor.visit(m_create_script_url);
- visitor.visit(m_create_parser_options);
-}
-
-Utf16String to_string(TrustedTypeName trusted_type_name)
-{
- switch (trusted_type_name) {
- case TrustedTypeName::TrustedHTML:
- return "TrustedHTML"_utf16;
- case TrustedTypeName::TrustedScript:
- return "TrustedScript"_utf16;
- case TrustedTypeName::TrustedScriptURL:
- return "TrustedScriptURL"_utf16;
- default:
- VERIFY_NOT_REACHED();
- }
+// Called by Bindings/Rust/src/trusted_types/trusted_type_policy.rs.
+JSCompletion web_trusted_types_create_parser_options(JSObject* global, WebIDL::CallbackType* create_parser_options, Bindings::CppDictionary<Bindings::SetHTMLUnsafeOptions>* options, ReadonlySpan<JSValue> arguments);
}
-TrustedHTML* trusted_html_from_value(JS::Value value)
+GC::Ptr<WebIDL::CallbackType> TrustedTypePolicy::create_parser_options_callback() const
{
- if (!value.is_object())
- return nullptr;
- return Bindings::impl_from<TrustedHTML>(&value.as_object());
+ return web_rust_trusted_types_trusted_type_policy_create_parser_options(const_cast<TrustedTypePolicy*>(this));
}
-TrustedScript* trusted_script_from_value(JS::Value value)
+static TrustedScript* trusted_script_from_value(JS::Value value)
{
if (!value.is_object())
return nullptr;
return Bindings::impl_from<TrustedScript>(&value.as_object());
}
-TrustedScriptURL* trusted_script_url_from_value(JS::Value value)
-{
- if (!value.is_object())
- return nullptr;
- return Bindings::impl_from<TrustedScriptURL>(&value.as_object());
-}
-
-bool is_trusted_html_value(JS::Value value)
-{
- return trusted_html_from_value(value);
-}
-
-bool is_trusted_script_value(JS::Value value)
-{
- return trusted_script_from_value(value);
-}
-
-bool is_trusted_script_url_value(JS::Value value)
-{
- return trusted_script_url_from_value(value);
-}
-
bool trusted_script_value_matches(JS::Value value, StringView expected)
{
auto* trusted_script = trusted_script_from_value(value);
@@ -120,59 +73,11 @@ bool trusted_script_values_match(ReadonlySpan<JS::Value> values, ReadonlySpan<St
return true;
}
-JS::Completion invoke_trusted_type_policy_callback(WebIDL::CallbackType& callback, GC::RootVector<JS::Value> const& arguments)
+static JS::Completion invoke_trusted_type_policy_callback(WebIDL::CallbackType& callback, GC::RootVector<JS::Value> const& arguments)
{
return WebIDL::invoke_callback(callback, {}, WebIDL::ExceptionBehavior::Rethrow, arguments);
}
-// https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicy-createhtml
-WebIDL::ExceptionOr<GC::Ref<TrustedHTML>> TrustedTypePolicy::create_html(JS::VM& vm, Utf16String const& input, GC::RootVector<JS::Value> const& arguments)
-{
- // 1. Returns the result of executing the Create a Trusted Type algorithm, with the following arguments:
- // policy
- // this value
- // trustedTypeName
- // "TrustedHTML"
- // value
- // input
- // arguments
- // arguments
- auto const trusted_type = TRY(create_a_trusted_type(vm, TrustedTypeName::TrustedHTML, input, arguments));
- return trusted_type.get<GC::Ref<TrustedHTML>>();
-}
-
-// https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicy-createscript
-WebIDL::ExceptionOr<GC::Ref<TrustedScript>> TrustedTypePolicy::create_script(JS::VM& vm, Utf16String const& input, GC::RootVector<JS::Value> const& arguments)
-{
- // 1. Returns the result of executing the Create a Trusted Type algorithm, with the following arguments:
- // policy
- // this value
- // trustedTypeName
- // "TrustedScript"
- // value
- // input
- // arguments
- // arguments
- auto const trusted_type = TRY(create_a_trusted_type(vm, TrustedTypeName::TrustedScript, input, arguments));
- return trusted_type.get<GC::Ref<TrustedScript>>();
-}
-
-// https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicy-createscripturl
-WebIDL::ExceptionOr<GC::Ref<TrustedScriptURL>> TrustedTypePolicy::create_script_url(JS::VM& vm, Utf16String const& input, GC::RootVector<JS::Value> const& arguments)
-{
- // 1. Returns the result of executing the Create a Trusted Type algorithm, with the following arguments:
- // policy
- // this value
- // trustedTypeName
- // "TrustedScriptURL"
- // value
- // input
- // arguments
- // arguments
- auto const trusted_type = TRY(create_a_trusted_type(vm, TrustedTypeName::TrustedScriptURL, input, arguments));
- return trusted_type.get<GC::Ref<TrustedScriptURL>>();
-}
-
// https://w3c.github.io/trusted-types/dist/spec/#create-a-parser-options-callback-argument
template<typename Options>
static WebIDL::ExceptionOr<JS::Value> create_a_parser_options_callback_argument(JS::Object& global, Options const& dictionary)
@@ -224,8 +129,44 @@ static WebIDL::ExceptionOr<Optional<HTML::SanitizerConfiguration>> get_a_sanitiz
return Optional<HTML::SanitizerConfiguration> { sanitizer->configuration() };
}
+// https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-policy-value
+// NB: The steps for the "TrustedHTMLParserOptions" type name.
+template<typename Options>
+static WebIDL::ExceptionOr<JS::Value> get_parser_options_policy_value(JS::Object& global, GC::Ptr<WebIDL::CallbackType> function, Options const& value, GC::RootVector<JS::Value> const& arguments, ThrowIfCallbackMissing throw_if_missing)
+{
+ // 1. Let functionName be a function name for the given trustedTypeName, based on the following table:
+ // 2. Let function be policy's options[functionName].
+ // NB: The caller passes function.
+
+ // 3. If function is null, then:
+ if (!function) {
+ // 1. If throwIfMissing throw a TypeError.
+ if (throw_if_missing == ThrowIfCallbackMissing::Yes)
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Trying to create a trusted type without a callback"_utf16 };
+
+ // 2. Else return null.
+ return JS::js_null();
+ }
+
+ // 4. If trustedTypeName is "TrustedHTMLParserOptions":
+ // 1. Set value to the result of creating a parser options callback argument given policy's relevant realm and
+ // value.
+ auto argument = TRY(create_a_parser_options_callback_argument(global, value));
+
+ // 5. Let args be « value ».
+ GC::RootVector<JS::Value> args;
+ args.append(argument);
+
+ // 6. Append each item in arguments to args.
+ args.extend(arguments);
+
+ // 7. Let policyValue be the result of invoking function with args and "rethrow".
+ // 8. Return policyValue.
+ return TRY(invoke_trusted_type_policy_callback(*function, args));
+}
+
// https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicy-createparseroptions
-WebIDL::ExceptionOr<GC::Ref<TrustedHTMLParserOptions>> TrustedTypePolicy::create_parser_options(JS::Object& global, Bindings::SetHTMLUnsafeOptions const& options, GC::RootVector<JS::Value> const& arguments)
+static WebIDL::ExceptionOr<GC::Ref<TrustedHTMLParserOptions>> create_parser_options(JS::Object& global, GC::Ptr<WebIDL::CallbackType> create_parser_options_callback, Bindings::SetHTMLUnsafeOptions const& options, GC::RootVector<JS::Value> const& arguments)
{
// Returns the result of executing the create a trusted type algorithm, with the following arguments:
// policy: this value
@@ -236,7 +177,7 @@ WebIDL::ExceptionOr<GC::Ref<TrustedHTMLParserOptions>> TrustedTypePolicy::create
// 1. Let policyValue be the result of executing get trusted type policy value with the same arguments as this
// algorithm and additionally true as throwIfMissing.
// 2. If the algorithm threw an error, rethrow the error and abort the following steps.
- auto policy_value = TRY(to_optional_set_html_unsafe_options(global.vm(), TRY(get_parser_options_policy_value(global, options, arguments, ThrowIfCallbackMissing::Yes))));
+ auto policy_value = TRY(to_optional_set_html_unsafe_options(global.vm(), TRY(get_parser_options_policy_value(global, create_parser_options_callback, options, arguments, ThrowIfCallbackMissing::Yes))));
// 3. If trustedTypeName is "TrustedHTMLParserOptions":
// 1. If policyValue is null, throw a TypeError.
@@ -257,45 +198,25 @@ WebIDL::ExceptionOr<GC::Ref<TrustedHTMLParserOptions>> TrustedTypePolicy::create
return TrustedHTMLParserOptions::create(move(sanitizer_config), run_scripts);
}
-// https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-policy-value
-// NB: The steps of "get trusted type policy value" for the "TrustedHTMLParserOptions" type name.
-template<typename Options>
-WebIDL::ExceptionOr<JS::Value> TrustedTypePolicy::get_parser_options_policy_value(JS::Object& global, Options const& value, GC::RootVector<JS::Value> const& arguments, ThrowIfCallbackMissing throw_if_missing)
+JSCompletion web_trusted_types_create_parser_options(JSObject* global, WebIDL::CallbackType* create_parser_options_callback, Bindings::CppDictionary<Bindings::SetHTMLUnsafeOptions>* options, ReadonlySpan<JSValue> arguments)
{
- // 1. Let functionName be a function name for the given trustedTypeName, based on the following table:
- // 2. Let function be policy's options[functionName].
- auto function = m_create_parser_options;
-
- // 3. If function is null, then:
- if (!function) {
- // 1. If throwIfMissing throw a TypeError.
- if (throw_if_missing == ThrowIfCallbackMissing::Yes)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Trying to create a trusted type without a callback"_utf16 };
-
- // 2. Else return null.
- return JS::js_null();
+ auto& global_object = *JS::HostABI::object_from_abi(global);
+ GC::RootVector<JS::Value> argument_values;
+ for (auto argument : arguments)
+ argument_values.append(JS::HostABI::value_from_abi(argument));
+ auto result = create_parser_options(global_object, create_parser_options_callback, options->dictionary(), argument_values);
+ if (result.is_exception()) {
+ auto& vm = global_object.vm();
+ return JS::HostABI::throw_completion_to_abi(WebIDL::exception_to_throw_completion(vm, *vm.current_realm(), result.exception()).value());
}
-
- // 4. If trustedTypeName is "TrustedHTMLParserOptions":
- // 1. Set value to the result of creating a parser options callback argument given policy's relevant realm and
- // value.
- auto argument = TRY(create_a_parser_options_callback_argument(global, value));
-
- // 5. Let args be « value ».
- GC::RootVector<JS::Value> args;
- args.append(argument);
-
- // 6. Append each item in arguments to args.
- args.extend(arguments);
-
- // 7. Let policyValue be the result of invoking function with args and "rethrow".
- // 8. Return policyValue.
- return TRY(invoke_trusted_type_policy_callback(*function, args));
+ auto& realm = HTML::relevant_realm(global_object);
+ auto wrapper = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, result.release_value());
+ return JS::HostABI::normal_completion_to_abi(JS::HostABI::value_to_abi(wrapper));
}
// NB: A SetHTMLUnsafeOptions or ParseHTMLUnsafeOptions options needs vetting if options["runScripts"] exists and is
// true, or if options["sanitizer"] exists and is not an empty SanitizerConfig.
-// https://w3c.github.io/trusted-types/dist/spec/#needs-vetting
+// https://w3c.github.io/trusted-types/dist/spec/#parser-options-need-vetting
template<typename Options>
static bool needs_vetting(Options const& options)
{
@@ -342,7 +263,7 @@ WebIDL::ExceptionOr<CompliantParserOptions<Options>> get_trusted_type_compliant_
auto reject_unless_allowed = [&]() -> WebIDL::ExceptionOr<CompliantParserOptions<Options>> {
// 1. Let disposition be the result of executing should sink type mismatch violation be blocked by content
// security policy? algorithm, passing global, sink, "script", and the empty string as source.
- auto disposition = should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(global, sink, Script.view(), {});
+ auto disposition = should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(global, to_string(sink), Script.view(), {});
// 2. If disposition is "Allowed", return input.
if (disposition == ContentSecurityPolicy::Directives::Directive::Result::Allowed)
@@ -368,8 +289,10 @@ WebIDL::ExceptionOr<CompliantParserOptions<Options>> get_trusted_type_compliant_
}
// 8. Let function be defaultPolicy's options["createParserOptions"].
+ auto function = default_policy->create_parser_options_callback();
+
// 9. If function is null:
- if (!default_policy->has_create_parser_options()) {
+ if (!function) {
// 1. If requirePolicy is true:
if (require_policy)
return reject_unless_allowed();
@@ -388,7 +311,7 @@ WebIDL::ExceptionOr<CompliantParserOptions<Options>> get_trusted_type_compliant_
GC::RootVector<JS::Value> arguments;
arguments.append(JS::PrimitiveString::create(vm, "TrustedHTMLParserOptions"_utf16));
arguments.append(JS::PrimitiveString::create(vm, to_string(sink)));
- auto policy_value = TRY(to_optional_set_html_unsafe_options(vm, TRY(default_policy->get_parser_options_policy_value(global, options, arguments, ThrowIfCallbackMissing::Yes))));
+ auto policy_value = TRY(to_optional_set_html_unsafe_options(vm, TRY(get_parser_options_policy_value(global, function, options, arguments, ThrowIfCallbackMissing::Yes))));
// 13. If policyValue is null or undefined:
if (!policy_value.has_value()) {
@@ -446,308 +369,109 @@ WebIDL::ExceptionOr<CompliantInput<Options>> get_trusted_type_compliant_input(JS
template WebIDL::ExceptionOr<CompliantInput<Bindings::SetHTMLUnsafeOptions>> get_trusted_type_compliant_input(JS::Object&, TrustedHTMLOrString const&, CompliantParserOptions<Bindings::SetHTMLUnsafeOptions> const&, InjectionSink, DocumentType, OptionsFromAuthor);
template WebIDL::ExceptionOr<CompliantInput<Bindings::ParseHTMLUnsafeOptions>> get_trusted_type_compliant_input(JS::Object&, TrustedHTMLOrString const&, CompliantParserOptions<Bindings::ParseHTMLUnsafeOptions> const&, InjectionSink, DocumentType, OptionsFromAuthor);
-// https://w3c.github.io/trusted-types/dist/spec/#create-a-trusted-type-algorithm
-TrustedTypesVariants TrustedTypePolicy::create_a_trusted_type(JS::VM& vm, TrustedTypeName trusted_type_name, Utf16String const& value, GC::RootVector<JS::Value> const& arguments)
-{
- // 1. Let policyValue be the result of executing Get Trusted Type policy value with the same arguments
- // as this algorithm and additionally true as throwIfMissing.
- // 2. If the algorithm threw an error, rethrow the error and abort the following steps.
- auto const policy_value = TRY(get_trusted_type_policy_value(vm, trusted_type_name, value, arguments, ThrowIfCallbackMissing::Yes));
-
- // 3. Let dataString be the result of stringifying policyValue.
- Utf16String data_string;
- switch (trusted_type_name) {
- case TrustedTypeName::TrustedHTML:
- case TrustedTypeName::TrustedScript:
- data_string = TRY(WebIDL::to_utf16_string(vm, policy_value));
- break;
- case TrustedTypeName::TrustedScriptURL:
- data_string = TRY(WebIDL::to_utf16_usv_string(vm, policy_value));
- break;
- default:
- VERIFY_NOT_REACHED();
- }
+// The kind is 0 for a string, or the TrustedTypeName plus one.
+struct InputABI {
+ u8 kind { 0 };
+ void* cell { nullptr };
+ FlatPtr string { 0 };
+};
- // 4. If policyValue is null or undefined, set dataString to the empty string.
- if (policy_value.is_nullish())
- data_string = ""_utf16;
+static InputABI input_to_abi(Variant<GC::Ref<TrustedHTML>, GC::Ref<TrustedScript>, GC::Ref<TrustedScriptURL>, Utf16String> const& input)
+{
+ return input.visit(
+ [](GC::Ref<TrustedHTML> const& value) { return InputABI { 1, value.ptr(), 0 }; },
+ [](GC::Ref<TrustedScript> const& value) { return InputABI { 2, value.ptr(), 0 }; },
+ [](GC::Ref<TrustedScriptURL> const& value) { return InputABI { 3, value.ptr(), 0 }; },
+ [](Utf16String const& value) { return InputABI { 0, nullptr, Utf16String { value }.into_raw() }; });
+}
- // 5. Return a new instance of an interface with a type name trustedTypeName, with its associated data value set to dataString.
- switch (trusted_type_name) {
- case TrustedTypeName::TrustedHTML:
- return TrustedType { TrustedHTML::create(move(data_string)) };
- case TrustedTypeName::TrustedScript:
- return TrustedType { TrustedScript::create(move(data_string)) };
- case TrustedTypeName::TrustedScriptURL:
- return TrustedType { TrustedScriptURL::create(move(data_string)) };
- default:
- VERIFY_NOT_REACHED();
- }
+static Utf16String stringified(Variant<GC::Ref<TrustedHTML>, GC::Ref<TrustedScript>, GC::Ref<TrustedScriptURL>, Utf16String> const& input)
+{
+ return input.visit(
+ [](Utf16String const& value) { return value; },
+ [](auto const& value) { return value->to_string(); });
}
-// https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-policy-value
-WebIDL::ExceptionOr<JS::Value> TrustedTypePolicy::get_trusted_type_policy_value(JS::VM& vm, TrustedTypeName trusted_type_name, Utf16String const& value, GC::RootVector<JS::Value> const& values, ThrowIfCallbackMissing throw_if_missing)
+static WebIDL::ExceptionOr<Utf16String> result_from_abi(u8 result, FlatPtr string, JSValue exception)
{
- // 1. Let functionName be a function name for the given trustedTypeName, based on the following table:
- // 2. Let function be policy’s options[functionName].
- GC::Ptr<WebIDL::CallbackType> function;
- switch (trusted_type_name) {
- case TrustedTypeName::TrustedHTML:
- function = m_create_html;
- break;
- case TrustedTypeName::TrustedScript:
- function = m_create_script;
- break;
- case TrustedTypeName::TrustedScriptURL:
- function = m_create_script_url;
- break;
+ switch (result) {
+ case 0:
+ return Utf16String::adopt_raw(string);
+ case 1:
+ return JS::throw_completion(JS::HostABI::value_from_abi(exception));
+ case 2:
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::adopt_raw(string) };
default:
VERIFY_NOT_REACHED();
}
-
- // 3. If function is null, then:
- if (!function) {
- // 1. If throwIfMissing throw a TypeError.
- if (throw_if_missing == ThrowIfCallbackMissing::Yes)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Trying to create a trusted type without a callback"_utf16 };
-
- // 2. Else return null
- return JS::js_null();
- }
-
- // 4. Let args be << value >>.
- GC::RootVector<JS::Value> args;
- args.append(JS::PrimitiveString::create(vm, value));
-
- // 5. Append each item in arguments to args.
- args.extend(values);
-
- // 6. Let policyValue be the result of invoking function with args and "rethrow".
- auto const policy_value = TRY(invoke_trusted_type_policy_callback(*function, args));
-
- // 7. Return policyValue.
- return policy_value;
}
-// https://www.w3.org/TR/trusted-types/#process-value-with-a-default-policy-algorithm
+// https://w3c.github.io/trusted-types/dist/spec/#process-value-with-a-default-policy-algorithm
WebIDL::ExceptionOr<Optional<TrustedType>> process_value_with_a_default_policy(TrustedTypeName trusted_type_name, JS::Object& global, Variant<GC::Ref<TrustedHTML>, GC::Ref<TrustedScript>, GC::Ref<TrustedScriptURL>, Utf16String> input, InjectionSink sink)
{
- auto& vm = global.vm();
- // 1. Let defaultPolicy be the value of global’s trusted type policy factory’s default policy.
- auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(global);
- VERIFY(global_scope);
- auto const& default_policy = global_scope->trusted_types()->default_policy();
-
- // This algorithm routes a value to be assigned to an injection sink through a default policy, should one exist.
- // FIXME: Open an issue upstream. It is not immediately clear what to do if the default policy does not exist.
- // Ref: https://github.com/w3c/trusted-types/issues/595
- if (!default_policy)
- return Optional<TrustedType> {};
-
- // 2. Let policyValue be the result of executing Get Trusted Type policy value, with the following arguments:
- // policy:
- // defaultPolicy
- // value:
- // stringified input
- // trustedTypeName:
- // expectedType’s type name
- // arguments:
- // « trustedTypeName, sink »
- // throwIfMissing:
- // false
- // 3. If the algorithm threw an error, rethrow the error and abort the following steps.
- auto arguments = GC::RootVector<JS::Value> {};
- arguments.append(JS::PrimitiveString::create(vm, to_string(trusted_type_name)));
- arguments.append(JS::PrimitiveString::create(vm, to_string(sink)));
- auto policy_value = TRY(default_policy->get_trusted_type_policy_value(
- vm,
- trusted_type_name,
- input.visit(
- [](auto& value) { return value->to_string(); },
- [](Utf16String& value) { return value; }),
- arguments,
- ThrowIfCallbackMissing::No));
-
- // 4. If policyValue is null or undefined, return policyValue.
- if (policy_value.is_nullish())
+ auto input_abi = input_to_abi(input);
+ void* result = nullptr;
+ JSValue exception {};
+ if (web_rust_trusted_types_process_value_with_a_default_policy(JS::HostABI::vm_to_abi(global.vm()), to_underlying(trusted_type_name), JS::HostABI::object_to_abi(&global), input_abi.kind, input_abi.cell, input_abi.string, to_string(sink).into_raw(), &result, &exception))
+ return JS::throw_completion(JS::HostABI::value_from_abi(exception));
+ if (!result)
return Optional<TrustedType> {};
-
- // 5. Let dataString be the result of stringifying policyValue.
- Utf16String data_string;
switch (trusted_type_name) {
case TrustedTypeName::TrustedHTML:
+ return TrustedType { GC::Ref { *static_cast<TrustedHTML*>(result) } };
case TrustedTypeName::TrustedScript:
- data_string = TRY(WebIDL::to_utf16_string(vm, policy_value));
- break;
+ return TrustedType { GC::Ref { *static_cast<TrustedScript*>(result) } };
case TrustedTypeName::TrustedScriptURL:
- data_string = TRY(WebIDL::to_utf16_usv_string(vm, policy_value));
- break;
- default:
- VERIFY_NOT_REACHED();
- }
-
- // 6. Return a new instance of an interface with a type name trustedTypeName, with its associated data value set to dataString.
- switch (trusted_type_name) {
- case TrustedTypeName::TrustedHTML:
- return TrustedType { TrustedHTML::create(move(data_string)) };
- case TrustedTypeName::TrustedScript:
- return TrustedType { TrustedScript::create(move(data_string)) };
- case TrustedTypeName::TrustedScriptURL:
- return TrustedType { TrustedScriptURL::create(move(data_string)) };
+ return TrustedType { GC::Ref { *static_cast<TrustedScriptURL*>(result) } };
}
VERIFY_NOT_REACHED();
}
-// https://www.w3.org/TR/trusted-types/#get-trusted-type-compliant-string-algorithm
+// https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-compliant-string-algorithm
WebIDL::ExceptionOr<Utf16String> get_trusted_type_compliant_string(TrustedTypeName expected_type, JS::Object& global, Variant<GC::Ref<TrustedHTML>, GC::Ref<TrustedScript>, GC::Ref<TrustedScriptURL>, Utf16String> input, InjectionSink sink, Utf16View sink_group)
{
- // 1. If input is an instance of expectedType, return stringified input and abort these steps.
- switch (expected_type) {
- case TrustedTypeName::TrustedHTML:
- if (auto* const value = input.get_pointer<GC::Ref<TrustedHTML>>(); value)
- return (*value)->to_string();
- break;
- case TrustedTypeName::TrustedScript:
- if (auto* const value = input.get_pointer<GC::Ref<TrustedScript>>(); value)
- return (*value)->to_string();
- break;
- case TrustedTypeName::TrustedScriptURL:
- if (auto* const value = input.get_pointer<GC::Ref<TrustedScriptURL>>(); value)
- return (*value)->to_string();
- break;
- }
-
- // 2. Let requireTrustedTypes be the result of executing Does sink type require trusted types? algorithm, passing global, sinkGroup, and true.
- auto const require_trusted_types = does_sink_require_trusted_types(global, sink_group, IncludeReportOnlyPolicies::Yes);
-
- // 3. If requireTrustedTypes is false, return stringified input and abort these steps.
- if (!require_trusted_types)
- return input.visit(
- [](auto const& value) {
- return value->to_string();
- },
- [](Utf16String const& value) {
- return value;
- });
-
- // 4. Let convertedInput be the result of executing Process value with a default policy with the same arguments as this algorithm.
- // 5. If the algorithm threw an error, rethrow the error and abort the following steps.
- auto const converted_input = TRY(process_value_with_a_default_policy(expected_type, global, input, sink));
-
- // 6. If convertedInput is null or undefined, execute the following steps:
- if (!converted_input.has_value()) {
- // 1. Let disposition be the result of executing Should sink type mismatch violation be blocked by Content Security Policy?
- // algorithm, passing global, stringified input as source, sinkGroup and sink.
- auto const disposition = should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(
- global,
- sink,
- sink_group,
- input.visit(
- [](auto const& value) {
- return value->to_string();
- },
- [](Utf16String const& value) {
- return value;
- }));
-
- // 2. If disposition is “Allowed”, return stringified input and abort further steps.
- if (disposition == ContentSecurityPolicy::Directives::Directive::Result::Allowed) {
- return input.visit(
- [](auto const& value) {
- return value->to_string();
- },
- [](Utf16String const& value) {
- return value;
- });
- }
-
- // 3. Throw a TypeError and abort further steps.
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Sink {} of type {} requires a TrustedType to be used", to_string(sink), sink_group) };
- }
-
- // 7. Assert: convertedInput is an instance of expectedType.
- // 8. Return stringified convertedInput.
- VERIFY(converted_input.has_value());
- return converted_input.value().visit([&]<typename Type>(Type const& trusted_type) {
- switch (expected_type) {
- case TrustedTypeName::TrustedHTML:
- VERIFY(IsSame<Type, GC::Ref<TrustedHTML>>);
- break;
- case TrustedTypeName::TrustedScript:
- VERIFY(IsSame<Type, GC::Ref<TrustedScript>>);
- break;
- case TrustedTypeName::TrustedScriptURL:
- VERIFY(IsSame<Type, GC::Ref<TrustedScriptURL>>);
- break;
- }
- return trusted_type->to_string();
- });
+ // NB: Steps 1 to 3, so that pages that don't require Trusted Types never call into Rust.
+ auto input_is_expected_type = input.visit(
+ [&](GC::Ref<TrustedHTML> const&) { return expected_type == TrustedTypeName::TrustedHTML; },
+ [&](GC::Ref<TrustedScript> const&) { return expected_type == TrustedTypeName::TrustedScript; },
+ [&](GC::Ref<TrustedScriptURL> const&) { return expected_type == TrustedTypeName::TrustedScriptURL; },
+ [](Utf16String const&) { return false; });
+ if (input_is_expected_type || !does_sink_require_trusted_types(global, sink_group, IncludeReportOnlyPolicies::Yes))
+ return stringified(input);
+
+ auto input_abi = input_to_abi(input);
+ FlatPtr string = 0;
+ JSValue exception {};
+ auto result = web_rust_trusted_types_get_trusted_type_compliant_string(JS::HostABI::vm_to_abi(global.vm()), to_underlying(expected_type), JS::HostABI::object_to_abi(&global), input_abi.kind, input_abi.cell, input_abi.string, to_string(sink).into_raw(), Utf16String::from_utf16(sink_group).into_raw(), &string, &exception);
+ return result_from_abi(result, string, exception);
}
// https://w3c.github.io/trusted-types/dist/spec/#validate-attribute-mutation
WebIDL::ExceptionOr<Utf16String> get_trusted_types_compliant_attribute_value(Utf16FlyString const& attribute_name, Optional<Utf16FlyString> attribute_ns, DOM::Element const& element, Variant<GC::Ref<TrustedHTML>, GC::Ref<TrustedScript>, GC::Ref<TrustedScriptURL>, Utf16String> const& new_value)
{
- // 1. If attributeNs is the empty string, set attributeNs to null.
- if (attribute_ns.has_value() && attribute_ns.value().is_empty())
- attribute_ns.clear();
-
- // 2. Set attributeData to the result of Get Trusted Type data for attribute algorithm, with the following arguments:
- // element
- // attributeName
- // attributeNs
- auto const attribute_data = get_trusted_type_data_for_attribute(
- element_interface(
- element.local_name(),
- element.namespace_uri().value_or(Namespace::HTML)),
- attribute_name,
- attribute_ns);
-
- // 3. If attributeData is null, then:
- if (!attribute_data.has_value()) {
- // 1. If newValue is a string, return newValue.
- if (new_value.has<Utf16String>())
- return new_value.get<Utf16String>();
-
- // 2. Assert: newValue is TrustedHTML or TrustedScript or TrustedScriptURL.
- VERIFY(new_value.has<GC::Ref<TrustedHTML>>() || new_value.has<GC::Ref<TrustedScript>>() || new_value.has<GC::Ref<TrustedScriptURL>>());
-
- // 3. Return value’s associated data.
- // FIXME: This is badly worded in the spec it should say "Return stringified newvalues's"
- return new_value.downcast<TrustedType>().visit([](auto& value) { return value->to_string(); });
- }
-
- // 4. Let expectedType be the value of the fourth member of attributeData.
- auto const expected_type = attribute_data->trusted_type;
-
- // 5. Let sink be the value of the fifth member of attributeData.
- auto const sink = attribute_data->sink;
-
- // 6. Return the result of executing Get Trusted Type compliant string with the following arguments:
- // expectedType
- // newValue as input
- // element’s node document’s relevant global object as global
- // sink
- // 'script' as sinkGroup
- return get_trusted_type_compliant_string(
- expected_type,
- HTML::relevant_global_object(element.document()),
- new_value,
- sink,
- Script.view());
-}
-
-ElementInterface element_interface(Utf16FlyString const& local_name, Utf16FlyString const& element_ns)
-{
- // FIXME: We don't have a method in ElementFactory that can give us the interface name but these are all the cases
- // we care about in the table in get_trusted_type_data_for_attribute function
- if (local_name == HTML::TagNames::iframe && element_ns == Namespace::HTML)
- return { "HTMLIFrameElement"_utf16, element_ns };
- if (local_name == HTML::TagNames::script && element_ns == Namespace::HTML)
- return { "HTMLScriptElement"_utf16, element_ns };
- if (local_name == SVG::TagNames::script && element_ns == Namespace::SVG)
- return { "SVGScriptElement"_utf16, element_ns };
-
- return { "Element"_utf16, element_ns };
+ auto& global = HTML::relevant_global_object(element.document());
+
+ // NB: Unless 'script' requires Trusted Types, every step returns stringified newValue.
+ if (!does_sink_require_trusted_types(global, Script.view(), IncludeReportOnlyPolicies::Yes))
+ return stringified(new_value);
+
+ auto input_abi = input_to_abi(new_value);
+ FlatPtr string = 0;
+ JSValue exception {};
+ auto result = web_rust_trusted_types_get_trusted_types_compliant_attribute_value(
+ JS::HostABI::vm_to_abi(global.vm()),
+ attribute_name.to_utf16_string().into_raw(),
+ attribute_ns.has_value(),
+ attribute_ns.has_value() ? attribute_ns->to_utf16_string().into_raw() : 0,
+ element.local_name().to_utf16_string().into_raw(),
+ element.namespace_uri().value_or(Namespace::HTML).to_utf16_string().into_raw(),
+ JS::HostABI::object_to_abi(&global),
+ input_abi.kind,
+ input_abi.cell,
+ input_abi.string,
+ &string,
+ &exception);
+ return result_from_abi(result, string, exception);
}
}
diff --git a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.h b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.h
index 51b9098fa8a..c23d4dacc40 100644
--- a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.h
+++ b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.h
@@ -6,13 +6,12 @@
#pragma once
-#include <AK/FlyString.h>
#include <AK/Optional.h>
#include <AK/Utf16String.h>
#include <AK/Variant.h>
#include <LibJS/Forward.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/Bindings/TrustedTypePolicy.h>
-#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Forward.h>
#include <LibWeb/TrustedTypes/InjectionSink.h>
#include <LibWeb/TrustedTypes/TrustedHTML.h>
@@ -29,62 +28,28 @@ namespace Web::TrustedTypes {
class TrustedHTMLParserOptions;
-using TrustedTypePolicyOptions = Bindings::TrustedTypePolicyOptions;
-
// https://www.w3.org/TR/trusted-types/#typedefdef-trustedtype
using TrustedType = Variant<
GC::Ref<TrustedHTML>,
GC::Ref<TrustedScript>,
GC::Ref<TrustedScriptURL>>;
-using TrustedTypesVariants = WebIDL::ExceptionOr<TrustedType>;
-
-enum class TrustedTypeName {
+enum class TrustedTypeName : u8 {
TrustedHTML,
TrustedScript,
TrustedScriptURL,
};
-Utf16String to_string(TrustedTypeName);
-
enum class ThrowIfCallbackMissing {
Yes,
No
};
-class TrustedTypePolicy final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(TrustedTypePolicy, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(TrustedTypePolicy);
+class TrustedTypePolicy final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(TrustedTypePolicy, trusted_type_policy)
public:
- virtual ~TrustedTypePolicy() override = default;
-
- Utf16String const& name() const { return m_name; }
-
- WebIDL::ExceptionOr<GC::Ref<TrustedHTML>> create_html(JS::VM&, Utf16String const&, GC::RootVector<JS::Value> const&);
- WebIDL::ExceptionOr<GC::Ref<TrustedScript>> create_script(JS::VM&, Utf16String const&, GC::RootVector<JS::Value> const&);
- WebIDL::ExceptionOr<GC::Ref<TrustedScriptURL>> create_script_url(JS::VM&, Utf16String const&, GC::RootVector<JS::Value> const&);
- WebIDL::ExceptionOr<GC::Ref<TrustedHTMLParserOptions>> create_parser_options(JS::Object&, Bindings::SetHTMLUnsafeOptions const&, GC::RootVector<JS::Value> const&);
-
- bool has_create_parser_options() const { return m_create_parser_options != nullptr; }
-
- template<typename Options>
- WebIDL::ExceptionOr<JS::Value> get_parser_options_policy_value(JS::Object&, Options const& value, GC::RootVector<JS::Value> const& arguments, ThrowIfCallbackMissing);
-
- WebIDL::ExceptionOr<JS::Value> get_trusted_type_policy_value(JS::VM&, TrustedTypeName, Utf16String const& value, GC::RootVector<JS::Value> const& values, ThrowIfCallbackMissing throw_if_missing);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
-private:
- explicit TrustedTypePolicy(Utf16String const&, TrustedTypePolicyOptions const&);
-
- TrustedTypesVariants create_a_trusted_type(JS::VM&, TrustedTypeName, Utf16String const&, GC::RootVector<JS::Value> const& values);
-
- Utf16String const m_name;
- GC::Ptr<WebIDL::CallbackType> const m_create_html;
- GC::Ptr<WebIDL::CallbackType> const m_create_script;
- GC::Ptr<WebIDL::CallbackType> const m_create_script_url;
- GC::Ptr<WebIDL::CallbackType> const m_create_parser_options;
+ GC::Ptr<WebIDL::CallbackType> create_parser_options_callback() const;
};
WebIDL::ExceptionOr<Optional<TrustedType>> process_value_with_a_default_policy(TrustedTypeName, JS::Object&, Variant<GC::Ref<TrustedHTML>, GC::Ref<TrustedScript>, GC::Ref<TrustedScriptURL>, Utf16String>, InjectionSink);
@@ -92,15 +57,8 @@ WebIDL::ExceptionOr<Optional<TrustedType>> process_value_with_a_default_policy(T
WebIDL::ExceptionOr<Utf16String> get_trusted_type_compliant_string(TrustedTypeName, JS::Object&, Variant<GC::Ref<TrustedHTML>, GC::Ref<TrustedScript>, GC::Ref<TrustedScriptURL>, Utf16String> input, InjectionSink sink, Utf16View sink_group);
WebIDL::ExceptionOr<Utf16String> get_trusted_types_compliant_attribute_value(Utf16FlyString const& attribute_name, Optional<Utf16FlyString> attribute_ns, DOM::Element const& element, Variant<GC::Ref<TrustedHTML>, GC::Ref<TrustedScript>, GC::Ref<TrustedScriptURL>, Utf16String> const& new_value);
-TrustedHTML* trusted_html_from_value(JS::Value);
-TrustedScript* trusted_script_from_value(JS::Value);
-TrustedScriptURL* trusted_script_url_from_value(JS::Value);
-bool is_trusted_html_value(JS::Value);
-bool is_trusted_script_value(JS::Value);
-bool is_trusted_script_url_value(JS::Value);
bool trusted_script_value_matches(JS::Value, StringView expected);
bool trusted_script_values_match(ReadonlySpan<JS::Value>, ReadonlySpan<String> expected);
-JS::Completion invoke_trusted_type_policy_callback(WebIDL::CallbackType&, GC::RootVector<JS::Value> const& arguments);
enum class DocumentType : u8 {
HTML,
@@ -127,12 +85,4 @@ WebIDL::ExceptionOr<CompliantParserOptions<Options>> get_trusted_type_compliant_
template<typename Options>
WebIDL::ExceptionOr<CompliantInput<Options>> get_trusted_type_compliant_input(JS::Object& global, TrustedHTMLOrString const& input, CompliantParserOptions<Options> const& options, InjectionSink, DocumentType = DocumentType::HTML, OptionsFromAuthor = OptionsFromAuthor::Yes);
-// FIXME: Add-hoc definition of an element interface
-struct ElementInterface {
- Utf16String element_name;
- Utf16FlyString element_ns;
-};
-
-ElementInterface element_interface(Utf16FlyString const& local_name, Utf16FlyString const& element_ns);
-
}
diff --git a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.idl b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.idl
index 16a90ca0db5..403c1f32c57 100644
--- a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.idl
+++ b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.idl
@@ -2,13 +2,13 @@
typedef (TrustedHTML or TrustedScript or TrustedScriptURL) TrustedType;
// https://w3c.github.io/trusted-types/dist/spec/#trusted-type-policy
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface TrustedTypePolicy {
readonly attribute DOMString name;
[NeedsCallerRealm] TrustedHTML createHTML(DOMString input, any... arguments);
[NeedsCallerRealm] TrustedScript createScript(DOMString input, any... arguments);
[NeedsCallerRealm] TrustedScriptURL createScriptURL(DOMString input, any... arguments);
- [Exposed=Window, NeedsCallerRealm, ImplementedInBindings] TrustedHTMLParserOptions createParserOptions(optional SetHTMLUnsafeOptions options = {}, any... arguments);
+ [Exposed=Window, NeedsCallerRealm] TrustedHTMLParserOptions createParserOptions(optional SetHTMLUnsafeOptions options = {}, any... arguments);
};
// https://w3c.github.io/trusted-types/dist/spec/#trusted-type-policy-options
diff --git a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicyFactory.cpp b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicyFactory.cpp
index 64e3df33a69..4f9b32f2dda 100644
--- a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicyFactory.cpp
+++ b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicyFactory.cpp
@@ -4,349 +4,28 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibWeb/TrustedTypes/TrustedTypePolicyFactory.h>
-
-#include <LibGC/Heap.h>
-#include <LibGC/Ptr.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/ContentSecurityPolicy/Directives/Directive.h>
-#include <LibWeb/ContentSecurityPolicy/Directives/KeywordTrustedTypes.h>
-#include <LibWeb/ContentSecurityPolicy/Directives/Names.h>
-#include <LibWeb/ContentSecurityPolicy/PolicyList.h>
-#include <LibWeb/ContentSecurityPolicy/Violation.h>
-#include <LibWeb/DOM/EventTarget.h>
-#include <LibWeb/HTML/AttributeNames.h>
-#include <LibWeb/HTML/GlobalEventHandlers.h>
-#include <LibWeb/HTML/PolicyContainers.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/TagNames.h>
-#include <LibWeb/HTML/Window.h>
-#include <LibWeb/HTML/WindowEventHandlers.h>
-#include <LibWeb/HTML/WorkerGlobalScope.h>
-#include <LibWeb/Namespace.h>
-#include <LibWeb/SVG/TagNames.h>
-#include <LibWeb/TrustedTypes/TrustedHTML.h>
-#include <LibWeb/TrustedTypes/TrustedScript.h>
-#include <LibWeb/TrustedTypes/TrustedScriptURL.h>
+#include <LibJS/Runtime/VM.h>
#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
+#include <LibWeb/TrustedTypes/TrustedTypePolicyFactory.h>
namespace Web::TrustedTypes {
-GC_DEFINE_ALLOCATOR(TrustedTypePolicyFactory);
-
-// https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-getattributetype
-Optional<Utf16String> TrustedTypePolicyFactory::get_attribute_type(Utf16FlyString const& tag_name, Utf16FlyString const& attribute, Optional<Utf16FlyString> element_ns, Optional<Utf16FlyString> attr_ns)
-{
- // 1. Set localName to tagName in ASCII lowercase.
- auto const local_name = tag_name.to_ascii_lowercase();
-
- // 2. Set attribute to attribute in ASCII lowercase.
- auto const attribute_local_name = attribute.to_ascii_lowercase();
-
- // 3. If elementNs is null or an empty string, set elementNs to HTML namespace.
- if (!element_ns.has_value() || element_ns.value().is_empty())
- element_ns = Namespace::HTML;
- auto const element_namespace = element_ns.value();
-
- // 4. If attrNs is an empty string, set attrNs to null.
- if (attr_ns.has_value() && attr_ns.value().is_empty())
- attr_ns.clear();
-
- // 5. Let interface be the element interface for localName and elementNs.
- auto const interface = element_interface(local_name, element_namespace);
-
- // 6. Let expectedType be null.
- Optional<Utf16String> expected_type {};
-
- // 7. Set attributeData to the result of Get Trusted Type data for attribute algorithm,
- // with the following arguments, interface as element, attribute, attrNs
- auto const attribute_data = get_trusted_type_data_for_attribute(interface, attribute_local_name, attr_ns);
-
- // 8. If attributeData is not null, then set expectedType to the interface’s name of the value of the fourth member of attributeData.
- if (attribute_data.has_value()) {
- expected_type = to_string(attribute_data.value().trusted_type);
- }
-
- // 9. Return expectedType.
- return expected_type;
-}
-
-// https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-getpropertytype
-Optional<Utf16String> TrustedTypePolicyFactory::get_property_type(Utf16FlyString const& tag_name, Utf16FlyString const& property, Optional<Utf16FlyString> element_ns)
-{
- // 1. Set localName to tagName in ASCII lowercase.
- auto const local_name = tag_name.to_ascii_lowercase();
-
- // 2. If elementNs is null or an empty string, set elementNs to HTML namespace.
- if (!element_ns.has_value() || element_ns.value().is_empty())
- element_ns = Namespace::HTML;
- auto const element_namespace = element_ns.value();
-
- // FIXME: We don't have a method in ElementFactory that can give us the interface name but these are all the cases
- // we care about in the table in get_trusted_type_data_for_attribute function
- // 3. Let interface be the element interface for localName and elementNs.
- Utf16String interface;
- if (local_name == HTML::TagNames::iframe && element_namespace == Namespace::HTML) {
- interface = "HTMLIFrameElement"_utf16;
- } else if (local_name == HTML::TagNames::script && element_namespace == Namespace::HTML) {
- interface = "HTMLScriptElement"_utf16;
- } else {
- interface = "Element"_utf16;
- }
-
- // 4. Let expectedType be null.
- Optional<Utf16String> expected_type;
-
- struct TrustedTypesPropertyTypeData {
- Utf16String interface;
- Utf16String property;
- TrustedTypeName trusted_type;
- };
-
- static auto const& table = *new Vector<TrustedTypesPropertyTypeData> {
- { "HTMLIFrameElement"_utf16, "srcdoc"_utf16, TrustedTypeName::TrustedHTML },
- { "HTMLScriptElement"_utf16, "innerText"_utf16, TrustedTypeName::TrustedScript },
- { "HTMLScriptElement"_utf16, "src"_utf16, TrustedTypeName::TrustedScriptURL },
- { "HTMLScriptElement"_utf16, "text"_utf16, TrustedTypeName::TrustedScript },
- { "HTMLScriptElement"_utf16, "textContent"_utf16, TrustedTypeName::TrustedScript },
- { "*"_utf16, "innerHTML"_utf16, TrustedTypeName::TrustedHTML },
- { "*"_utf16, "outerHTML"_utf16, TrustedTypeName::TrustedHTML },
- };
-
- // 5. Find the row in the following table, where the first column is "*" or interface’s name, and property is in the second column.
- // If a matching row is found, set expectedType to the interface’s name of the value of the third column.
- auto const matching_row = table.first_matching([&interface, &property](auto const& row) {
- return (row.interface == interface || row.interface == "*"sv) && row.property == property;
- });
-
- if (matching_row.has_value()) {
- expected_type = to_string(matching_row.value().trusted_type);
- }
-
- // 6. Return expectedType.
- return expected_type;
-}
-
-TrustedTypePolicyFactory::TrustedTypePolicyFactory(DOM::EventTarget& owner)
- : m_owner(owner)
-{
-}
-
-GC::Ptr<Bindings::Wrappable> TrustedTypePolicyFactory::relevant_global_impl() const
-{
- return m_owner;
-}
-
-void TrustedTypePolicyFactory::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_owner);
- visitor.visit(m_default_policy);
- visitor.visit(m_empty_html);
- visitor.visit(m_empty_script);
-}
-
-JS::Realm& TrustedTypePolicyFactory::relevant_realm() const
-{
- if (auto const* window = as_if<HTML::Window>(m_owner.ptr()))
- return HTML::relevant_realm(*window);
-
- auto const* worker_global_scope = as_if<HTML::WorkerGlobalScope>(m_owner.ptr());
- VERIFY(worker_global_scope);
- return HTML::relevant_realm(*worker_global_scope);
-}
-
-// https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-createpolicy
-WebIDL::ExceptionOr<GC::Ref<TrustedTypePolicy>> TrustedTypePolicyFactory::create_policy(JS::Realm& realm, Utf16String const& policy_name, TrustedTypePolicyOptions const& policy_options)
-{
- // 1. Returns the result of executing a Create a Trusted Type Policy algorithm, with the following arguments:
- // factory: this value
- // policyName: policyName
- // options: policyOptions
- // global: this value’s relevant global object
- return create_a_trusted_type_policy(realm, policy_name, policy_options, relevant_realm().global_object());
-}
-
-// https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-ishtml
-bool TrustedTypePolicyFactory::is_html(JS::Value value) const
-{
- // 1. Returns true if value is an instance of TrustedHTML and has an associated data value set, false otherwise.
- return is_trusted_html_value(value);
-}
-
-// https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-isscript
-bool TrustedTypePolicyFactory::is_script(JS::Value value) const
-{
- // 1. Returns true if value is an instance of TrustedScript and has an associated data value set, false otherwise.
- return is_trusted_script_value(value);
-}
-
-// https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-isscripturl
-bool TrustedTypePolicyFactory::is_script_url(JS::Value value) const
-{
- // 1. Returns true if value is an instance of TrustedScriptURL and has an associated data value set, false otherwise.
- return is_trusted_script_url_value(value);
-}
-
-GC::Ref<TrustedHTML> TrustedTypePolicyFactory::empty_html()
-{
- if (!m_empty_html)
- m_empty_html = TrustedHTML::create(""_utf16);
-
- return GC::Ref { *m_empty_html };
-}
-
-GC::Ref<TrustedScript> TrustedTypePolicyFactory::empty_script()
-{
- if (!m_empty_script)
- m_empty_script = TrustedScript::create(""_utf16);
-
- return GC::Ref { *m_empty_script };
+extern "C" {
+// Defined in Bindings/Rust/src/trusted_types/trusted_type_policy_factory.rs.
+TrustedTypePolicyFactory* web_rust_trusted_types_create_trusted_type_policy_factory(JSVM*, JS::Realm*);
+TrustedTypePolicy* web_rust_trusted_types_trusted_type_policy_factory_default_policy(TrustedTypePolicyFactory*);
}
-// https://w3c.github.io/trusted-types/dist/spec/#create-trusted-type-policy-algorithm
-WebIDL::ExceptionOr<GC::Ref<TrustedTypePolicy>> TrustedTypePolicyFactory::create_a_trusted_type_policy(JS::Realm& realm, Utf16String const& policy_name, TrustedTypePolicyOptions const& options, JS::Object& global)
+GC::Ref<TrustedTypePolicyFactory> TrustedTypePolicyFactory::create(JS::Realm& realm)
{
- // 1. Let allowedByCSP be the result of executing Should Trusted Type policy creation be blocked by Content Security Policy? algorithm with global, policyName and factory’s created policy names value.
- auto const allowed_by_csp = should_trusted_type_policy_be_blocked_by_content_security_policy(realm, global, policy_name, m_created_policy_names);
-
- // 2. If allowedByCSP is "Blocked", throw a TypeError and abort further steps.
- if (allowed_by_csp == ContentSecurityPolicy::Directives::Directive::Result::Blocked)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Content Security Policy blocked the creation of the policy {}", policy_name) };
-
- // 3. If policyName is default and the factory’s default policy value is not null, throw a TypeError and abort further steps.
- if (policy_name == "default"sv && m_default_policy)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Policy Factory already has a default value defined"_utf16 };
-
- // 4. Let policy be a new TrustedTypePolicy object.
- // 5. Set policy’s name property value to policyName.
- // 6. Set policy’s options value to «[ "createHTML" -> options["createHTML", "createScript" -> options["createScript", "createScriptURL" -> options["createScriptURL" ]».
- auto const policy = GC::Heap::the().allocate<TrustedTypePolicy>(policy_name, options);
-
- // 7. If the policyName is default, set the factory’s default policy value to policy.
- if (policy_name == "default"sv)
- m_default_policy = policy;
-
- // 8. Append policyName to factory’s created policy names.
- m_created_policy_names.append(policy_name);
-
- // 9. Return policy.
- return policy;
+ return *web_rust_trusted_types_create_trusted_type_policy_factory(JS::HostABI::vm_to_abi(realm.vm()), &realm);
}
-// https://www.w3.org/TR/trusted-types/#should-block-create-policy
-ContentSecurityPolicy::Directives::Directive::Result TrustedTypePolicyFactory::should_trusted_type_policy_be_blocked_by_content_security_policy(JS::Realm& realm, JS::Object& global, Utf16String const& policy_name, Vector<Utf16String> const& created_policy_names)
+GC::Ptr<TrustedTypePolicy> TrustedTypePolicyFactory::default_policy() const
{
- // 1. Let result be "Allowed".
- auto result = ContentSecurityPolicy::Directives::Directive::Result::Allowed;
-
- // 2. For each policy in global’s CSP list:
- auto const& csp_list = HTML::relevant_settings_object(global).policy_container()->csp_list;
- for (auto const& policy : csp_list.policies()) {
- // 1. Let createViolation be false.
- bool create_violation = false;
-
- // 2. If policy’s directive set does not contain a directive which name is "trusted-types", skip to the next policy.
- if (!policy->contains_directive_with_name(ContentSecurityPolicy::Directives::Names::TrustedTypes))
- continue;
-
- // 3. Let directive be the policy’s directive set’s directive which name is "trusted-types"
- auto const directive = policy->get_directive_by_name(ContentSecurityPolicy::Directives::Names::TrustedTypes);
-
- // 4. If directive’s value only contains a tt-keyword which is a match for a value 'none', set createViolation to true.
- if (directive->value().size() == 1 && directive->value().first().equals_ignoring_ascii_case(ContentSecurityPolicy::Directives::KeywordTrustedTypes::None.view()))
- create_violation = true;
-
- // 5. If createdPolicyNames contains policyName and directive’s value does not contain a tt-keyword which is a match for a value 'allow-duplicates', set createViolation to true.
- auto created_policy_names_iterator = created_policy_names.find(policy_name);
- if (!created_policy_names_iterator.is_end()) {
- auto maybe_allow_duplicates = directive->value().find_if([](auto const& directive_value) {
- return directive_value.equals_ignoring_ascii_case(ContentSecurityPolicy::Directives::KeywordTrustedTypes::AllowDuplicates.view());
- });
- if (maybe_allow_duplicates.is_end())
- create_violation = true;
- }
-
- // 6. If directive’s value does not contain a tt-policy-name, which value is policyName, and directive’s value does not contain a tt-wildcard, set createViolation to true.
- auto directive_value_iterator = directive->value().find(policy_name);
- if (directive_value_iterator.is_end()) {
- auto maybe_wild_card = directive->value().find_if([](auto const& directive_value) {
- return directive_value.equals_ignoring_ascii_case(ContentSecurityPolicy::Directives::KeywordTrustedTypes::WildCard.view());
- });
-
- if (maybe_wild_card.is_end())
- create_violation = true;
- }
-
- // 7. If createViolation is false, skip to the next policy.
- if (!create_violation)
- continue;
-
- // 8. Let violation be the result of executing Create a violation object for global, policy, and directive on global, policy and "trusted-types"
- auto const violation = ContentSecurityPolicy::Violation::create_a_violation_object_for_global_policy_and_directive(global, policy, ContentSecurityPolicy::Directives::Names::TrustedTypes.view().to_utf8_but_should_be_ported_to_utf16());
-
- // 9. Set violation’s resource to "trusted-types-policy".
- violation->set_resource(ContentSecurityPolicy::Violation::Resource::TrustedTypesPolicy);
-
- // 10. Set violation’s sample to the substring of policyName, containing its first 40 characters.
- auto sample = policy_name.substring_view(0, min(policy_name.length_in_code_points(), 40));
- violation->set_sample(Utf16String::from_utf16(sample));
-
- // 11. Execute Report a violation on violation.
- violation->report_a_violation(realm);
-
- // 12. If policy’s disposition is "enforce", then set result to "Blocked".
- if (policy->disposition() == ContentSecurityPolicy::Policy::Disposition::Enforce)
- result = ContentSecurityPolicy::Directives::Directive::Result::Blocked;
- }
-
- // 3. Return result.
- return result;
-}
-
-// https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-data-for-attribute
-Optional<TrustedTypeData> get_trusted_type_data_for_attribute(ElementInterface const& element, Utf16FlyString const& attribute, Optional<Utf16FlyString> const& attribute_ns)
-{
- // 1. Let data be null.
- Optional<TrustedTypeData const&> data {};
-
- auto const& [element_name, element_ns] = element;
-
- // 2. If attributeNs is null, « HTML namespace, SVG namespace, MathML namespace » contains element’s namespace, and attribute is the name of an event handler content attribute:
- if (attribute.starts_with("on"sv)
- && !attribute_ns.has_value()
- && (Namespace::HTML == element_ns || Namespace::SVG == element_ns || Namespace::MathML == element_ns)) {
-#undef __ENUMERATE
-#define __ENUMERATE(attribute_name, event_name) \
- if (attribute == HTML::AttributeNames::attribute_name) { \
- /* 1. Return (Element, null, attribute, TrustedScript, "Element " + attribute). */ \
- return TrustedTypeData { "Element"_utf16, {}, HTML::AttributeNames::attribute_name, TrustedTypeName::TrustedScript, InjectionSink::Element_##attribute_name }; \
- }
- ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
- ENUMERATE_WINDOW_EVENT_HANDLERS(__ENUMERATE)
-#undef __ENUMERATE
- }
-
- // OPTIMIZATION: Every remaining row has one of these three attribute names.
- if (!attribute.is_one_of(HTML::AttributeNames::srcdoc, HTML::AttributeNames::src, HTML::AttributeNames::href))
- return {};
-
- static auto const& table = *new Vector<TrustedTypeData> {
- { "HTMLIFrameElement"_utf16, {}, HTML::AttributeNames::srcdoc, TrustedTypeName::TrustedHTML, InjectionSink::HTMLIFrameElement_srcdoc },
- { "HTMLScriptElement"_utf16, {}, HTML::AttributeNames::src, TrustedTypeName::TrustedScriptURL, InjectionSink::HTMLScriptElement_src },
- { "SVGScriptElement"_utf16, {}, HTML::AttributeNames::href, TrustedTypeName::TrustedScriptURL, InjectionSink::SVGScriptElement_href },
- { "SVGScriptElement"_utf16, Namespace::XLink, HTML::AttributeNames::href, TrustedTypeName::TrustedScriptURL, InjectionSink::SVGScriptElement_href },
- };
-
- // 3. Find the row in the following table, where element is in the first column, attributeNs is in the second column,
- // and attribute is in the third column. If a matching row is found, set data to that row.
- data = table.first_matching([&element_name, &attribute, &attribute_ns](auto const& row) {
- return row.element == element_name && row.attribute_ns == attribute_ns && row.attribute_local_name == attribute;
- });
-
- // 4. Return data
- return data.copy();
+ return web_rust_trusted_types_trusted_type_policy_factory_default_policy(const_cast<TrustedTypePolicyFactory*>(this));
}
}
diff --git a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicyFactory.h b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicyFactory.h
index b6e0bc42dcf..b606455f3d6 100644
--- a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicyFactory.h
+++ b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicyFactory.h
@@ -6,76 +6,21 @@
#pragma once
-#include <AK/Optional.h>
-#include <AK/Utf16String.h>
-#include <AK/Vector.h>
#include <LibJS/Forward.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/ContentSecurityPolicy/Directives/Directive.h>
-#include <LibWeb/TrustedTypes/InjectionSink.h>
-#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>
+#include <LibWeb/Bindings/RustInterface.h>
+#include <LibWeb/Bindings/TrustedTypePolicyFactory.h>
+#include <LibWeb/Forward.h>
namespace Web::TrustedTypes {
-class TrustedTypePolicyFactory final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(TrustedTypePolicyFactory, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(TrustedTypePolicyFactory);
+class TrustedTypePolicyFactory final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(TrustedTypePolicyFactory, trusted_type_policy_factory)
public:
- virtual ~TrustedTypePolicyFactory() override { }
-
- JS::Realm& relevant_realm() const;
-
- WebIDL::ExceptionOr<GC::Ref<TrustedTypePolicy>> create_policy(JS::Realm&, Utf16String const&, TrustedTypePolicyOptions const&);
-
- bool is_html(JS::Value) const;
- bool is_script(JS::Value) const;
- bool is_script_url(JS::Value) const;
-
- GC::Ref<TrustedHTML> empty_html();
- GC::Ref<TrustedScript> empty_script();
-
- Optional<Utf16String> get_attribute_type(Utf16FlyString const& tag_name, Utf16FlyString const& attribute, Optional<Utf16FlyString> element_ns, Optional<Utf16FlyString> attr_ns);
- Optional<Utf16String> get_property_type(Utf16FlyString const& tag_name, Utf16FlyString const& property, Optional<Utf16FlyString> element_ns);
-
- GC::Ptr<TrustedTypePolicy> default_policy() const
- {
- return m_default_policy;
- }
- static constexpr size_t default_policy_offset() { return offsetof(TrustedTypePolicyFactory, m_default_policy); }
-
-private:
- explicit TrustedTypePolicyFactory(DOM::EventTarget&);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
- virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;
-
- WebIDL::ExceptionOr<GC::Ref<TrustedTypePolicy>> create_a_trusted_type_policy(JS::Realm&, Utf16String const&, TrustedTypePolicyOptions const&, JS::Object&);
- ContentSecurityPolicy::Directives::Directive::Result should_trusted_type_policy_be_blocked_by_content_security_policy(JS::Realm&, JS::Object&, Utf16String const&, Vector<Utf16String> const&);
-
- GC::Ref<DOM::EventTarget> m_owner;
-
- // https://w3c.github.io/trusted-types/dist/spec/#trustedtypepolicyfactory-created-policy-names
- Vector<Utf16String> m_created_policy_names;
+ [[nodiscard]] static GC::Ref<TrustedTypePolicyFactory> create(JS::Realm&);
// https://w3c.github.io/trusted-types/dist/spec/#trustedtypepolicyfactory-default-policy
- GC::Ptr<TrustedTypePolicy> m_default_policy;
-
- // https://www.w3.org/TR/trusted-types/#dom-trustedtypepolicyfactory-emptyhtml
- GC::Ptr<TrustedHTML> m_empty_html;
-
- // https://www.w3.org/TR/trusted-types/#dom-trustedtypepolicyfactory-emptyscript
- GC::Ptr<TrustedScript> m_empty_script;
-};
-
-struct TrustedTypeData {
- Utf16String element;
- Optional<Utf16FlyString> attribute_ns;
- Utf16FlyString attribute_local_name;
- TrustedTypeName trusted_type;
- InjectionSink sink;
+ GC::Ptr<TrustedTypePolicy> default_policy() const;
};
-Optional<TrustedTypeData> get_trusted_type_data_for_attribute(ElementInterface const& element, Utf16FlyString const&, Optional<Utf16FlyString> const&);
-
}
diff --git a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicyFactory.idl b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicyFactory.idl
index bd0deab506d..fafa14ad408 100644
--- a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicyFactory.idl
+++ b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicyFactory.idl
@@ -4,7 +4,7 @@ partial interface mixin WindowOrWorkerGlobalScope {
};
// https://w3c.github.io/trusted-types/dist/spec/#trustedtypepolicyfactory
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface TrustedTypePolicyFactory {
[NeedsCallerRealm]
TrustedTypePolicy createPolicy(
@@ -15,13 +15,13 @@ interface TrustedTypePolicyFactory {
readonly attribute TrustedHTML emptyHTML;
readonly attribute TrustedScript emptyScript;
DOMString? getAttributeType(
- [FlyString] DOMString tagName,
- [FlyString] DOMString attribute,
- optional [FlyString] DOMString? elementNs = "",
- optional [FlyString] DOMString? attrNs = "");
+ DOMString tagName,
+ DOMString attribute,
+ optional DOMString? elementNs = "",
+ optional DOMString? attrNs = "");
DOMString? getPropertyType(
- [FlyString] DOMString tagName,
- [FlyString] DOMString property,
- optional [FlyString] DOMString? elementNs = "");
- [DirectGetter] readonly attribute TrustedTypePolicy? defaultPolicy;
+ DOMString tagName,
+ DOMString property,
+ optional DOMString? elementNs = "");
+ readonly attribute TrustedTypePolicy? defaultPolicy;
};
diff --git a/Meta/Generators/libweb_bindings/glue_headers.py b/Meta/Generators/libweb_bindings/glue_headers.py
index f3a207ea666..96dcb61ad70 100644
--- a/Meta/Generators/libweb_bindings/glue_headers.py
+++ b/Meta/Generators/libweb_bindings/glue_headers.py
@@ -16,7 +16,6 @@ def bindings_glue_header_for_interface(interface: Interface, wrapper_interface_n
"CSS": "LibWeb/CSS/BindingsGlue.h",
"CookieStore": "LibWeb/CookieStore/BindingsGlue.h",
"IndexedDB": "LibWeb/IndexedDB/BindingsGlue.h",
- "TrustedTypes": "LibWeb/TrustedTypes/BindingsGlue.h",
"WebRTC": "LibWeb/WebRTC/BindingsGlue.h",
}
if module in module_headers:
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 384e8a9167f..c8fef97b0f2 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -81,7 +81,11 @@ ALLOWED_REALM_MENTIONS = {
),
"StorageAPI": (2, 3, "the C++ glue of the Rust StorageManager creates one in a realm"),
"Streams": (7, 17, "the C++ facade of the Rust streams creates streams and promises in caller-selected realms"),
- "TrustedTypes": (2, 9, "Trusted Types policy factory operations still use selected realms"),
+ "TrustedTypes": (
+ 4,
+ 8,
+ "policy creation reports CSP violations in the caller's realm, and the Rust factory is created for its global's realm",
+ ),
"WebAssembly": (
2,
8,