Truly independent web browser
LibWeb: Implement Encrypted Media Extensions in Rust
Shannon Boothccd5796457ff
diff --git a/Libraries/LibWeb/EncryptedMediaExtensions/Algorithms.cpp b/Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/algorithms.rssimilarity index 53%rename from Libraries/LibWeb/EncryptedMediaExtensions/Algorithms.cpprename to Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/algorithms.rsindex 413373d9332..0db163c97a9 100644--- a/Libraries/LibWeb/EncryptedMediaExtensions/Algorithms.cpp+++ b/Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/algorithms.rs@@ -1,73 +1,92 @@/** Copyright (c) 2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/-#include <LibWeb/EncryptedMediaExtensions/Algorithms.h>-#include <LibWebCommon/MimeSniff/MimeType.h>+use ak::Utf16String;+use liburl_rust::origin::Origin;+use libwebcommon_rust::mime_sniff::mime_type::MimeType;-namespace Web::EncryptedMediaExtensions {+use super::encrypted_media_extensions::{CapabilitiesType, ConsentConfiguration, ConsentStatus, MediaKeyRestrictions};+use super::key_system::{ClearKeySystem, KeySystem};+use super::media_key_system_access::{+ MediaKeySystemConfiguration, MediaKeySystemMediaCapability, MediaKeysRequirement,+};-bool supports_container([[maybe_unused]] Utf16String const& container)-{+pub(crate) fn supports_container(_container: &str) -> bool {// FIXME: Check FFmpeg?- return true;+ true}// https://w3c.github.io/encrypted-media/#get-supported-capabilities-for-audio-video-type-Optional<Vector<MediaKeySystemMediaCapability>> get_supported_capabilities_for_audio_video_type(KeySystem const& implementation, CapabilitiesType type, Vector<MediaKeySystemMediaCapability> requested_capabilities, MediaKeySystemConfiguration config, MediaKeyRestrictions restrictions)-{+pub(crate) fn get_supported_capabilities_for_audio_video_type(+ implementation: &dyn KeySystem,+ r#type: CapabilitiesType,+ requested_capabilities: Vec<MediaKeySystemMediaCapability>,+ config: MediaKeySystemConfiguration,+ restrictions: &MediaKeyRestrictions,+) -> Option<Vec<MediaKeySystemMediaCapability>> {// 1. Let local accumulated configuration be a local copy of accumulated configuration.- MediaKeySystemConfiguration accumulated_configuration = config;+ let mut accumulated_configuration = config;// 2. Let supported media capabilities be an empty sequence of MediaKeySystemMediaCapability dictionaries.- Vector<MediaKeySystemMediaCapability> supported_media_capabilities;+ let mut supported_media_capabilities = Vec::new();// 3. For each requested media capability in requested media capabilities:- for (auto& capability : requested_capabilities) {+ for capability in requested_capabilities {// 1. Let content type be requested media capability's contentType member.- auto const& content_type = capability.content_type;+ let content_type = &capability.content_type;// 2. Let encryption scheme be requested media capability’s encryptionScheme member.- auto const& encryption_scheme = capability.encryption_scheme;+ let encryption_scheme = capability.encryption_scheme.as_ref();// 3. Let robustness be requested media capability's robustness member.- auto const& robustness = capability.robustness;+ let robustness = &capability.robustness;// 4. If content type is the empty string, return null.- if (content_type.is_empty())- return {};+ if content_type.is_empty() {+ return None;+ }// 5. Let mimeType be the result of running parse a MIME type with content type.- auto mime_type = MimeSniff::MimeType::parse(content_type);+ let content_type = char::decode_utf16(content_type.to_utf16().iter().copied())+ .map(|code_point| code_point.unwrap_or(char::REPLACEMENT_CHARACTER))+ .collect::<Vec<_>>();+ let mime_type = MimeType::parse(&content_type);// 6. If mimeType is failure or is unrecognized, continue to the next iteration.- if (!mime_type.has_value())+ let Some(mime_type) = mime_type else {continue;+ };// 7. Let container be the container type specified by mimeType.- auto const& container = Utf16String::from_utf8(mime_type->essence());+ let essence = mime_type.essence();+ let container = format!("{}/{}", essence.type_, essence.subtype);// 8. If the user agent does not support container, continue to the next iteration.// The case-sensitivity of string comparisons is determined by the appropriate RFC.- if (!supports_container(container))+ if !supports_container(&container) {continue;+ }// 9. Let parameters be the "codecs" and "profiles" RFC 6381 [RFC6381] parameters, if any, of mimeType.- auto parameters = mime_type->parameters();+ let mut parameters = mime_type.parameters();// FIXME: 10. If the user agent does not recognize one or more parameters, or// if any parameters are not valid per the relevant specification, continue to the next iteration.// 11. Let media types be the set of codecs and codec constraints specified by parameters.// The case-sensitivity of string comparisons is determined by the appropriate RFC or other specification.- auto media_types = Utf16String::from_utf8(parameters.get("codecs"sv).value_or({}));+ let media_types = parameters+ .find(|(name, _)| *name == "codecs")+ .map_or("", |(_, value)| value);// 12. If media types is empty:- if (media_types.is_empty()) {+ if media_types.is_empty() {// FIXME: If container normatively implies a specific set of codecs and codec constraints:- if (false) {+ if false {// Let parameters be that set.}// Otherwise:@@ -78,247 +97,284 @@ Optional<Vector<MediaKeySystemMediaCapability>> get_supported_capabilities_for_a}// 13. If mimeType is not strictly an audio/video type, continue to the next iteration.- if (!mime_type->is_audio_or_video())+ if !essence.is_audio_or_video() {continue;+ }// 14. If encryption scheme is non-null and is not recognized or not supported by implementation,// continue to the next iteration.- if (encryption_scheme.has_value() && !implementation.supports_encryption_scheme(*encryption_scheme))+ if encryption_scheme+ .is_some_and(|encryption_scheme| !implementation.supports_encryption_scheme(encryption_scheme))+ {continue;+ }// 15. If robustness is not the empty string and contains an unrecognized value or a value not supported// by implementation, continue to the next iteration. String comparison is case-sensitive.- if (!robustness.is_empty() && !implementation.supports_robustness(robustness))+ if !robustness.is_empty() && !implementation.supports_robustness(robustness) {continue;+ }// 16. If the user agent and implementation definitely support playback of encrypted media data for// the combination of container, media types, encryption scheme, robustness and// local accumulated configuration in combination with restrictions:- if (implementation.definitely_supports_playback(container, media_types, encryption_scheme, robustness, accumulated_configuration, restrictions)) {+ if implementation.definitely_supports_playback(+ &container,+ media_types,+ encryption_scheme,+ robustness,+ &accumulated_configuration,+ restrictions,+ ) {// 1. Add requested media capability to supported media capabilities.- supported_media_capabilities.append(move(capability));+ supported_media_capabilities.push(capability.clone());// 2. If audio/video type is Video:- if (type == CapabilitiesType::Video) {+ if r#type == CapabilitiesType::Video {// Add requested media capability to the videoCapabilities member of local accumulated configuration.- accumulated_configuration.video_capabilities.append(capability);+ accumulated_configuration.video_capabilities.push(capability.clone());}// If audio/video type is Audio:- if (type == CapabilitiesType::Audio) {+ if r#type == CapabilitiesType::Audio {// Add requested media capability to the audioCapabilities member of local accumulated configuration.- accumulated_configuration.audio_capabilities.append(capability);+ accumulated_configuration.audio_capabilities.push(capability.clone());}}}// 4. If supported media capabilities is empty, return null.- if (supported_media_capabilities.is_empty())- return {};+ if supported_media_capabilities.is_empty() {+ return None;+ }// 5. Return supported media capabilities.- return supported_media_capabilities;+ Some(supported_media_capabilities)}// https://w3c.github.io/encrypted-media/#dfn-is-persistent-session-type-bool is_persistent_session_type(Utf16String const& session_type)-{+pub(crate) fn is_persistent_session_type(session_type: &Utf16String) -> bool {// 1. Let the session type be the specified MediaKeySessionType value.// 2. Follow the steps for the value of session type from the following list:// * "temporary"- if (session_type == "temporary"sv) {+ if *session_type == "temporary" {// Return false.return false;}// * "persistent-license"- if (session_type == "persistent-license"sv) {+ if *session_type == "persistent-license" {// Return true.return true;}- VERIFY_NOT_REACHED();+ unreachable!("the session type is a MediaKeySessionType value")}// https://w3c.github.io/encrypted-media/#get-consent-status-ConsentStatus get_consent_status(MediaKeySystemConfiguration const& accumulated_configuration, MediaKeyRestrictions& restrictions, URL::Origin const& origin)-{+pub(crate) fn get_consent_status(+ _accumulated_configuration: &MediaKeySystemConfiguration,+ _restrictions: &mut MediaKeyRestrictions,+ _origin: &Origin,+) -> ConsentStatus {// FIXME: Implement this- (void)accumulated_configuration;- (void)restrictions;- (void)origin;-- dbgln("get_consent_status: Not implemented, returning Allowed by default");+ eprintln!("get_consent_status: Not implemented, returning Allowed by default");- return ConsentStatus::Allowed;+ ConsentStatus::Allowed}// https://w3c.github.io/encrypted-media/#get-supported-configuration-and-consent-Optional<ConsentConfiguration> get_supported_configuration_and_consent(KeySystem const& implementation, MediaKeySystemConfiguration const& candidate_configuration, MediaKeyRestrictions& restrictions, URL::Origin const& origin)-{+pub(crate) fn get_supported_configuration_and_consent(+ implementation: &dyn KeySystem,+ candidate_configuration: &MediaKeySystemConfiguration,+ restrictions: &mut MediaKeyRestrictions,+ origin: &Origin,+) -> Option<ConsentConfiguration> {// 1. Let accumulated configuration be a new MediaKeySystemConfiguration dictionary.- MediaKeySystemConfiguration accumulated_configuration;-// 2. Set the label member of accumulated configuration to equal the label member of candidate configuration.- accumulated_configuration.label = candidate_configuration.label;+ let mut accumulated_configuration = MediaKeySystemConfiguration {+ label: candidate_configuration.label.clone(),+ ..Default::default()+ };// 3. If the initDataTypes member of candidate configuration is non-empty, run the following steps:- if (!candidate_configuration.init_data_types.is_empty()) {+ if !candidate_configuration.init_data_types.is_empty() {// 1. Let supported types be an empty sequence of DOMStrings.- Vector<Utf16String> supported_types;+ let mut supported_types = Vec::new();// 2. For each value in candidate configuration's initDataTypes member:- for (auto const& init_data_type : candidate_configuration.init_data_types) {+ for init_data_type in &candidate_configuration.init_data_types {// 1. Let initDataType be the value.// 2. If the implementation supports generating requests based on initDataType, add initDataType to supported types.// String comparison is case-sensitive. The empty string is never supported.- if (implementation.supports_init_data_type(init_data_type))- supported_types.append(init_data_type);+ if implementation.supports_init_data_type(init_data_type) {+ supported_types.push(init_data_type.clone());+ }}// 3. If supported types is empty, return NotSupported.- if (supported_types.is_empty())- return {};+ if supported_types.is_empty() {+ return None;+ }// 4. Set the initDataTypes member of accumulated configuration to supported types.- accumulated_configuration.init_data_types = move(supported_types);+ accumulated_configuration.init_data_types = supported_types;}// 4. Let distinctive identifier requirement be the value of candidate configuration's distinctiveIdentifier member.- auto distinctive_identifier_requirement = candidate_configuration.distinctive_identifier;+ let mut distinctive_identifier_requirement = candidate_configuration.distinctive_identifier;// 5. If distinctive identifier requirement is "optional" and Distinctive Identifiers are not allowed according to restrictions,// set distinctive identifier requirement to "not-allowed".- if (distinctive_identifier_requirement == MediaKeysRequirement::Optional && !restrictions.distinctive_identifiers)+ if distinctive_identifier_requirement == MediaKeysRequirement::Optional && !restrictions.distinctive_identifiers {distinctive_identifier_requirement = MediaKeysRequirement::NotAllowed;+ }// 6. Follow the steps for distinctive identifier requirement from the following list:- switch (distinctive_identifier_requirement) {- case MediaKeysRequirement::Required:- // FIXME: If the implementation does not support use of Distinctive Identifier(s) in combination- // with accumulated configuration and restrictions, return NotSupported.- break;- case MediaKeysRequirement::Optional:- // Continue with the following steps.- break;- case MediaKeysRequirement::NotAllowed:- // FIXME: If the implementation requires use of Distinctive Identifier(s) or Distinctive Permanent Identifier(s)- // in combination with accumulated configuration and restrictions, return NotSupported.- break;+ match distinctive_identifier_requirement {+ MediaKeysRequirement::Required => {+ // FIXME: If the implementation does not support use of Distinctive Identifier(s) in combination+ // with accumulated configuration and restrictions, return NotSupported.+ }+ MediaKeysRequirement::Optional => {+ // Continue with the following steps.+ }+ MediaKeysRequirement::NotAllowed => {+ // FIXME: If the implementation requires use of Distinctive Identifier(s) or Distinctive Permanent Identifier(s)+ // in combination with accumulated configuration and restrictions, return NotSupported.+ }}// 7. Set the distinctiveIdentifier member of accumulated configuration to equal distinctive identifier requirement.accumulated_configuration.distinctive_identifier = distinctive_identifier_requirement;// 8. Let persistent state requirement be equal to the value of candidate configuration's persistentState member.- auto persistent_state_requirement = candidate_configuration.persistent_state;+ let mut persistent_state_requirement = candidate_configuration.persistent_state;// 9. If persistent state requirement is "optional" and persisting state is not allowed according to restrictions,// set persistent state requirement to "not-allowed".- if (persistent_state_requirement == MediaKeysRequirement::Optional && !restrictions.persist_state)+ if persistent_state_requirement == MediaKeysRequirement::Optional && !restrictions.persist_state {persistent_state_requirement = MediaKeysRequirement::NotAllowed;+ }// 10. Follow the steps for persistent state requirement from the following list:- switch (persistent_state_requirement) {- case MediaKeysRequirement::Required:- // FIXME: If the implementation does not support persisting state in combination with accumulated configuration- // and restrictions, return NotSupported.- break;- case MediaKeysRequirement::Optional:- // Continue with the following steps.- break;- case MediaKeysRequirement::NotAllowed:- // FIXME: If the implementation requires persisting state in combination with accumulated configuration- // and restrictions, return NotSupported.- break;+ match persistent_state_requirement {+ MediaKeysRequirement::Required => {+ // FIXME: If the implementation does not support persisting state in combination with accumulated configuration+ // and restrictions, return NotSupported.+ }+ MediaKeysRequirement::Optional => {+ // Continue with the following steps.+ }+ MediaKeysRequirement::NotAllowed => {+ // FIXME: If the implementation requires persisting state in combination with accumulated configuration+ // and restrictions, return NotSupported.+ }}// 12. Set the persistentState member of accumulated configuration to equal the value of persistent state requirement.accumulated_configuration.persistent_state = persistent_state_requirement;- Vector<Utf16String> session_types;// 1. Follow the steps for the first matching condition from the following list:-- // * If the sessionTypes member is present in candidate configuration- if (candidate_configuration.session_types.has_value()) {- // Let session types be candidate configuration's sessionTypes member.- session_types = *candidate_configuration.session_types;- }- // * Otherwise- else {- // Let session types be [ "temporary" ].- session_types.append("temporary"_utf16);- }+ let session_types = match &candidate_configuration.session_types {+ // * If the sessionTypes member is present in candidate configuration+ Some(session_types) => {+ // Let session types be candidate configuration's sessionTypes member.+ session_types.clone()+ }+ // * Otherwise+ None => {+ // Let session types be [ "temporary" ].+ vec![Utf16String::from_ascii(b"temporary")]+ }+ };// 13. For each value in session types:- for (auto const& session_type : session_types) {+ for session_type in &session_types {// 1. Let session type be the value.// 2. If accumulated configuration's persistentState value is "not-allowed" and the Is persistent session type? algorithm// returns true for session type return NotSupported.- if (accumulated_configuration.persistent_state == MediaKeysRequirement::NotAllowed && is_persistent_session_type(session_type))- return {};+ if accumulated_configuration.persistent_state == MediaKeysRequirement::NotAllowed+ && is_persistent_session_type(session_type)+ {+ return None;+ }// 3. FIXME: If the implementation does not support session type in combination with accumulated configuration and restrictions for other reasons, return NotSupported.// 4. If accumulated configuration's persistentState value is "optional" and the result of running the Is persistent session type? algorithm// on session type is true, change accumulated configuration's persistentState value to "required".- if (accumulated_configuration.persistent_state == MediaKeysRequirement::Optional && is_persistent_session_type(session_type))+ if accumulated_configuration.persistent_state == MediaKeysRequirement::Optional+ && is_persistent_session_type(session_type)+ {accumulated_configuration.persistent_state = MediaKeysRequirement::Required;+ }}// 14. Set the sessionTypes member of accumulated configuration to session types.- accumulated_configuration.session_types = move(session_types);+ accumulated_configuration.session_types = Some(session_types);// 15. If the videoCapabilities and audioCapabilities members in candidate configuration are both empty, return NotSupported.- if (candidate_configuration.video_capabilities.is_empty() && candidate_configuration.audio_capabilities.is_empty())- return {};+ if candidate_configuration.video_capabilities.is_empty() && candidate_configuration.audio_capabilities.is_empty() {+ return None;+ }// 16. If the videoCapabilities member in candidate configuration is non-empty:- if (!candidate_configuration.video_capabilities.is_empty()) {+ if !candidate_configuration.video_capabilities.is_empty() {// 1. Let video capabilities be the result of executing the Get Supported Capabilities for Audio/Video Type algorithm// on Video, candidate configuration's videoCapabilities member, accumulated configuration, and restrictions.- auto video_capabilities = get_supported_capabilities_for_audio_video_type(implementation, CapabilitiesType::Video, candidate_configuration.video_capabilities, accumulated_configuration, restrictions);+ let video_capabilities = get_supported_capabilities_for_audio_video_type(+ implementation,+ CapabilitiesType::Video,+ candidate_configuration.video_capabilities.clone(),+ accumulated_configuration.clone(),+ restrictions,+ );// 2. If video capabilities is null, return NotSupported.- if (!video_capabilities.has_value())- return {};+ let video_capabilities = video_capabilities?;// 3. Set the videoCapabilities member of accumulated configuration to video capabilities.- accumulated_configuration.video_capabilities = *video_capabilities;+ accumulated_configuration.video_capabilities = video_capabilities;}// Otherwise:else {// 1. Set the videoCapabilities member of accumulated configuration to an empty sequence.- accumulated_configuration.video_capabilities = Vector<MediaKeySystemMediaCapability> {};+ accumulated_configuration.video_capabilities = Vec::new();}// 1. If the audioCapabilities member in candidate configuration is non-empty:- if (!candidate_configuration.audio_capabilities.is_empty()) {+ if !candidate_configuration.audio_capabilities.is_empty() {// 1. Let audio capabilities be the result of executing the Get Supported Capabilities for Audio/Video Type algorithm// on Audio, candidate configuration's audioCapabilities member, accumulated configuration, and restrictions.- auto audio_capabilities = get_supported_capabilities_for_audio_video_type(implementation, CapabilitiesType::Audio, candidate_configuration.audio_capabilities, accumulated_configuration, restrictions);+ let audio_capabilities = get_supported_capabilities_for_audio_video_type(+ implementation,+ CapabilitiesType::Audio,+ candidate_configuration.audio_capabilities.clone(),+ accumulated_configuration.clone(),+ restrictions,+ );// 2. If audio capabilities is null, return NotSupported.- if (!audio_capabilities.has_value())- return {};+ let audio_capabilities = audio_capabilities?;// 3. Set the audioCapabilities member of accumulated configuration to audio capabilities.- accumulated_configuration.audio_capabilities = *audio_capabilities;+ accumulated_configuration.audio_capabilities = audio_capabilities;}// Otherwise:else {// 1. Set the audioCapabilities member of accumulated configuration to an empty sequence.- accumulated_configuration.audio_capabilities = Vector<MediaKeySystemMediaCapability> {};+ accumulated_configuration.audio_capabilities = Vec::new();}// 18. If accumulated configuration's distinctiveIdentifier value is "optional", follow the steps for the first matching condition from the following list:- if (accumulated_configuration.distinctive_identifier == MediaKeysRequirement::Optional) {+ if accumulated_configuration.distinctive_identifier == MediaKeysRequirement::Optional {// FIXME: 1. If the implementation requires use of Distinctive Identifier(s) or Distinctive Permanent Identifier(s) for any of the combinations in accumulated configuration:- if (false) {+ if false {// 1. Change accumulated configuration's distinctiveIdentifier value to "required".accumulated_configuration.distinctive_identifier = MediaKeysRequirement::Required;}@@ -330,9 +386,9 @@ Optional<ConsentConfiguration> get_supported_configuration_and_consent(KeySystem}// 19. If accumulated configuration's persistentState value is "optional", follow the steps for the first matching condition from the following list:- if (accumulated_configuration.persistent_state == MediaKeysRequirement::Optional) {+ if accumulated_configuration.persistent_state == MediaKeysRequirement::Optional {// FIXME: 1. If the implementation requires persisting state for any of the combinations in accumulated configuration- if (false) {+ if false {// 1. Change accumulated configuration's persistentState value to "required".accumulated_configuration.persistent_state = MediaKeysRequirement::Required;}@@ -352,71 +408,84 @@ Optional<ConsentConfiguration> get_supported_configuration_and_consent(KeySystem// 22. Let consent status and updated restrictions be the result of running the Get Consent Status algorithm// on accumulated configuration, restrictions and origin and follow the steps for the value of consent status from the following list:- auto consent_status = get_consent_status(accumulated_configuration, restrictions, origin);- switch (consent_status) {- case ConsentStatus::ConsentDenied:- // Return ConsentDenied and updated restrictions.- return {};- case ConsentStatus::InformUser:- // FIXME: Inform the user that accumulated configuration is in use in the origin including, specifically,- // the information that Distinctive Identifier(s) and/or Distinctive Permanent Identifier(s) as- // appropriate will be used if the distinctiveIdentifier member of accumulated configuration is "required".- // Continue to the next step.- break;- case ConsentStatus::Allowed:- // Continue to the next step.- break;+ let consent_status = get_consent_status(&accumulated_configuration, restrictions, origin);+ match consent_status {+ ConsentStatus::ConsentDenied => {+ // Return ConsentDenied and updated restrictions.+ return None;+ }+ ConsentStatus::InformUser => {+ // FIXME: Inform the user that accumulated configuration is in use in the origin including, specifically,+ // the information that Distinctive Identifier(s) and/or Distinctive Permanent Identifier(s) as+ // appropriate will be used if the distinctiveIdentifier member of accumulated configuration is "required".+ // Continue to the next step.+ }+ ConsentStatus::Allowed => {+ // Continue to the next step.+ }}// 23. Return accumulated configuration.- return ConsentConfiguration { consent_status, accumulated_configuration };+ Some(ConsentConfiguration {+ status: consent_status,+ configuration: Some(accumulated_configuration),+ })}// https://w3c.github.io/encrypted-media/#get-supported-configuration-Optional<ConsentConfiguration> get_supported_configuration(KeySystem const& implementation, MediaKeySystemConfiguration const& candidate_configuration, URL::Origin const& origin)-{+pub(crate) fn get_supported_configuration(+ implementation: &dyn KeySystem,+ candidate_configuration: &MediaKeySystemConfiguration,+ origin: &Origin,+) -> Option<ConsentConfiguration> {// 1. Let supported configuration be ConsentDenied.- Optional<ConsentConfiguration> supported_configuration = ConsentConfiguration { ConsentStatus::ConsentDenied, {} };+ let mut supported_configuration = Some(ConsentConfiguration {+ status: ConsentStatus::ConsentDenied,+ configuration: None,+ });// 2. Initialize restrictions to indicate that no configurations have had user consent denied.- MediaKeyRestrictions restrictions;+ let mut restrictions = MediaKeyRestrictions::default();- size_t loop_count = 0;+ let mut loop_count = 0;// 3. Repeat the following step while supported configuration is ConsentDenied:- while (supported_configuration.has_value() && supported_configuration->status == ConsentStatus::ConsentDenied) {+ while supported_configuration+ .as_ref()+ .is_some_and(|supported_configuration| supported_configuration.status == ConsentStatus::ConsentDenied)+ {// 1. Let supported configuration and, if provided, restrictions be the result of executing// the Get Supported Configuration and Consent algorithm with implementation, candidate configuration, restrictions and origin.- supported_configuration = get_supported_configuration_and_consent(implementation, candidate_configuration, restrictions, origin);+ supported_configuration =+ get_supported_configuration_and_consent(implementation, candidate_configuration, &mut restrictions, origin);// AD-HOC: While this is being implemented, we use this to avoid a possible infinite loop- if (loop_count++ > 5) {+ if loop_count > 5 {break;}+ loop_count += 1;}// 4. Return supported configuration.- return supported_configuration;+ supported_configuration}// https://w3c.github.io/encrypted-media/#dfn-common-key-systems-bool is_supported_key_system(Utf16String const& key_system)-{- constexpr Array<Utf16View, 1> supported_key_systems = {+pub(crate) fn is_supported_key_system(key_system: &Utf16String) -> bool {+ const SUPPORTED_KEY_SYSTEMS: [&str; 1] = [// https://w3c.github.io/encrypted-media/#clear-key- "org.w3.clearkey"sv,- };+ "org.w3.clearkey",+ ];- return supported_key_systems.contains_slow(key_system);+ SUPPORTED_KEY_SYSTEMS+ .iter()+ .any(|supported_key_system| *key_system == *supported_key_system)}-NonnullOwnPtr<KeySystem> key_system_from_string(Utf16String const& key_system)-{- if (key_system == "org.w3.clearkey"_utf16) {- return adopt_own(*new ClearKeySystem());+pub(crate) fn key_system_from_string(key_system: &Utf16String) -> Box<dyn KeySystem> {+ if *key_system == "org.w3.clearkey" {+ return Box::new(ClearKeySystem);}- VERIFY_NOT_REACHED();-}-+ unreachable!("the key system is supported")}diff --git a/Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/encrypted_media_extensions.rs b/Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/encrypted_media_extensions.rsnew file mode 100644index 00000000000..91d0010e1e0--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/encrypted_media_extensions.rs@@ -0,0 +1,45 @@+/*+ * Copyright (c) 2025, Psychpsyo <[email protected]>+ * Copyright (c) 2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use super::media_key_system_access::MediaKeySystemConfiguration;++pub(crate) struct MediaKeyRestrictions {+ pub(crate) distinctive_identifiers: bool,+ pub(crate) persist_state: bool,+}++impl Default for MediaKeyRestrictions {+ fn default() -> Self {+ Self {+ distinctive_identifiers: true,+ persist_state: true,+ }+ }+}++#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum CapabilitiesType {+ Audio,+ Video,+}++#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum ConsentStatus {+ ConsentDenied,+ #[cfg_attr(+ web_idl_bindings,+ expect(dead_code, reason = "Get Consent Status is not implemented yet")+ )]+ InformUser,+ Allowed,+}++pub(crate) struct ConsentConfiguration {+ pub(crate) status: ConsentStatus,+ pub(crate) configuration: Option<MediaKeySystemConfiguration>,+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/key_system.rs b/Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/key_system.rsnew file mode 100644index 00000000000..b51a5a30939--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/key_system.rs@@ -0,0 +1,67 @@+/*+ * Copyright (c) 2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use ak::Utf16String;++use super::encrypted_media_extensions::MediaKeyRestrictions;+use super::media_key_system_access::MediaKeySystemConfiguration;++pub(crate) trait KeySystem {+ fn supports_init_data_type(&self, init_data_type: &Utf16String) -> bool;+ fn supports_encryption_scheme(&self, encryption_scheme: &Utf16String) -> bool;+ fn supports_robustness(&self, robustness: &Utf16String) -> bool;+ fn definitely_supports_playback(+ &self,+ container: &str,+ media_types: &str,+ encryption_scheme: Option<&Utf16String>,+ robustness: &Utf16String,+ accumulated_configuration: &MediaKeySystemConfiguration,+ restrictions: &MediaKeyRestrictions,+ ) -> bool;+}++pub(crate) struct ClearKeySystem;++impl KeySystem for ClearKeySystem {+ // https://w3c.github.io/encrypted-media/#clear-key-behavior+ fn supports_init_data_type(&self, init_data_type: &Utf16String) -> bool {+ // Implementations SHOULD support the "keyids" type+ // TODO: Implementations MAY support any combination of registered Initialization Data Types+ // https://www.w3.org/TR/eme-initdata-registry/+ const REGISTERED_INIT_DATA_TYPES: [&str; 1] = ["keyids"];++ REGISTERED_INIT_DATA_TYPES+ .iter()+ .any(|registered_init_data_type| *init_data_type == *registered_init_data_type)+ }++ // https://w3c.github.io/encrypted-media/#clear-key-capabilities+ fn supports_encryption_scheme(&self, encryption_scheme: &Utf16String) -> bool {+ // encryptionScheme: Implementations MUST support the "cenc" scheme, and MAY support other schemes.+ *encryption_scheme == "cenc"+ }++ // https://w3c.github.io/encrypted-media/#clear-key-capabilities+ fn supports_robustness(&self, robustness: &Utf16String) -> bool {+ // robustness: Only the empty string is supported.+ robustness.is_empty()+ }++ fn definitely_supports_playback(+ &self,+ _container: &str,+ _media_types: &str,+ _encryption_scheme: Option<&Utf16String>,+ _robustness: &Utf16String,+ _accumulated_configuration: &MediaKeySystemConfiguration,+ _restrictions: &MediaKeyRestrictions,+ ) -> bool {+ // FIXME: Do some checks here+ true+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/media_key_system_access.rs b/Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/media_key_system_access.rsnew file mode 100644index 00000000000..f9a786af1a0--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/media_key_system_access.rs@@ -0,0 +1,98 @@+/*+ * Copyright (c) 2025, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! MediaKeySystemAccess, https://w3c.github.io/encrypted-media/#mediakeysystemaccess-interface++use ak::Utf16String;+use libjs_rust::api::{Trace, Vm};++use super::key_system::KeySystem;+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};++// https://w3c.github.io/encrypted-media/#dom-mediakeysrequirement+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum MediaKeysRequirement {+ Required,+ Optional,+ NotAllowed,+}++// https://w3c.github.io/encrypted-media/#dom-mediakeysystemconfiguration+#[derive(Clone)]+pub(crate) struct MediaKeySystemConfiguration {+ pub(crate) label: Utf16String,+ pub(crate) init_data_types: Vec<Utf16String>,+ pub(crate) audio_capabilities: Vec<MediaKeySystemMediaCapability>,+ pub(crate) video_capabilities: Vec<MediaKeySystemMediaCapability>,+ pub(crate) distinctive_identifier: MediaKeysRequirement,+ pub(crate) persistent_state: MediaKeysRequirement,+ pub(crate) session_types: Option<Vec<Utf16String>>,+}++impl Default for MediaKeySystemConfiguration {+ fn default() -> Self {+ Self {+ label: Utf16String::from_ascii(b""),+ init_data_types: Vec::new(),+ audio_capabilities: Vec::new(),+ video_capabilities: Vec::new(),+ distinctive_identifier: MediaKeysRequirement::Optional,+ persistent_state: MediaKeysRequirement::Optional,+ session_types: None,+ }+ }+}++// https://w3c.github.io/encrypted-media/#dom-mediakeysystemmediacapability+#[derive(Clone)]+pub(crate) struct MediaKeySystemMediaCapability {+ pub(crate) content_type: Utf16String,+ pub(crate) encryption_scheme: Option<Utf16String>,+ pub(crate) robustness: Utf16String,+}++// https://w3c.github.io/encrypted-media/#dom-mediakeysystemaccess+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct MediaKeySystemAccess {+ key_system: Utf16String,++ #[gc(untraced)]+ configuration: MediaKeySystemConfiguration,+ #[gc(untraced)]+ #[cfg_attr(+ web_idl_bindings,+ expect(dead_code, reason = "createMediaKeys() is not implemented yet")+ )]+ cdm_implementation: Box<dyn KeySystem>,+}++impl Wrappable for MediaKeySystemAccess {}++impl MediaKeySystemAccess {+ pub(crate) fn create(+ vm: &Vm,+ key_system: Utf16String,+ configuration: MediaKeySystemConfiguration,+ cdm_implementation: Box<dyn KeySystem>,+ ) -> Ref<Self> {+ allocate(vm, |_| Self {+ key_system,+ configuration,+ cdm_implementation,+ })+ }++ pub(crate) fn key_system(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self.key_system.clone())+ }++ pub(crate) fn get_configuration(&self, _: &mut CallContext) -> WebIdlResult<MediaKeySystemConfiguration> {+ Ok(self.configuration.clone())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/mod.rsnew file mode 100644index 00000000000..6d74c989288--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/encrypted_media_extensions/mod.rs@@ -0,0 +1,13 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Encrypted Media Extensions, https://w3c.github.io/encrypted-media/++pub(crate) mod algorithms;+#[allow(clippy::module_inception, reason = "the module mirrors EncryptedMediaExtensions.h")]+pub(crate) mod encrypted_media_extensions;+pub(crate) mod key_system;+pub(crate) mod media_key_system_access;diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rsindex 811a48f60ee..ab8f38f98e1 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs@@ -73,6 +73,8 @@ pub(crate) mod message_port;#[cfg(not(test))]pub(crate) mod navigable;#[cfg(not(test))]+pub(crate) mod navigator;+#[cfg(not(test))]pub(crate) mod numbers;#[cfg(not(test))]pub(crate) mod offscreen_canvas;diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/navigator.rs b/Libraries/LibWeb/Bindings/Rust/src/html/navigator.rsnew file mode 100644index 00000000000..28073c31228--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/html/navigator.rs@@ -0,0 +1,179 @@+/*+ * Copyright (c) 2022, Andrew Kaster <[email protected]>+ * Copyright (c) 2022, Linus Groh <[email protected]>+ * Copyright (c) 2024, Jamie Mansfield <[email protected]>+ * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The members of Navigator that are implemented in Rust, https://html.spec.whatwg.org/multipage/system-state.html#navigator++use core::ffi::c_void;++use ak::Utf16String;+use libjs_rust::api::{Gc, Realm, Trace, Value};+use liburl_rust::origin::Origin;++use crate::bindings::conversions::CppInterface;+use crate::bindings::global_object::CppWindow;+use crate::bindings::interface::{with_temporary_execution_context_and_callbacks, wrap};+use crate::bindings::promise::{+ WebIdlPromise, deferred_invoke, promise_realm, reject_promise_with_exception, resolve_promise,+};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::encrypted_media_extensions::algorithms::{+ get_supported_configuration, is_supported_key_system, key_system_from_string,+};+use crate::encrypted_media_extensions::media_key_system_access::{MediaKeySystemAccess, MediaKeySystemConfiguration};+use crate::permissions_policy::permissions_policy::PolicyControlledFeature;++unsafe extern "C" {+ fn web_html_navigator_window(navigator_wrapper: *mut c_void) -> *mut c_void;+}++/// https://html.spec.whatwg.org/multipage/system-state.html#navigator+fn window_of(navigator: &CppInterface) -> CppWindow {+ // SAFETY: The wrapper is a live Navigator wrapper, and LibWeb returns the live Window of the Navigator.+ unsafe { CppWindow::from_raw(web_html_navigator_window(navigator.wrapper().as_ptr().cast())) }+}++/// What the parallel steps of requestMediaKeySystemAccess() capture.+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+struct RequestMediaKeySystemAccessCaptures {+ realm: Gc<Realm>,+ promise: WebIdlPromise,+ key_system: Utf16String,+ #[gc(untraced)]+ supported_configurations: Vec<MediaKeySystemConfiguration>,+ #[gc(untraced)]+ origin: Origin,+}++// https://w3c.github.io/encrypted-media/#navigator-extension-requestmediakeysystemaccess+pub(crate) fn request_media_key_system_access(+ this: &CppInterface,+ cx: &mut CallContext,+ promise: WebIdlPromise,+ key_system: Utf16String,+ supported_configurations: Vec<MediaKeySystemConfiguration>,+) -> WebIdlResult<()> {+ let vm = cx.vm();++ // 1. If this's relevant global object's associated Document is not allowed to use the encrypted-media feature, then throw a "SecurityError" DOMException and abort these steps.+ let associated_document = window_of(this).associated_document();+ if !associated_document.is_allowed_to_use_feature(PolicyControlledFeature::EncryptedMedia) {+ reject_promise_with_exception(+ vm,+ promise,+ Exception::Dom(+ "SecurityError",+ Utf16String::from_ascii(b"This document is not allowed to use the encrypted-media feature"),+ ),+ );+ return Ok(());+ }++ // 2. If keySystem is the empty string, return a promise rejected with a newly created TypeError.+ if key_system.is_empty() {+ reject_promise_with_exception(+ vm,+ promise,+ Exception::TypeError(Utf16String::from_ascii(b"keySystem must not be empty")),+ );+ return Ok(());+ }++ // 3. If supportedConfigurations is empty, return a promise rejected with a newly created TypeError.+ if supported_configurations.is_empty() {+ reject_promise_with_exception(+ vm,+ promise,+ Exception::TypeError(Utf16String::from_ascii(b"supportedConfigurations must not be empty")),+ );+ return Ok(());+ }++ // 4. Let document be the calling context's Document.+ // FIXME: Is this the same as the associated document?+ let document = associated_document;++ // 5. Let origin be the origin of document.+ let origin = document.origin();++ // 7. Run the following steps in parallel:+ let captures = RequestMediaKeySystemAccessCaptures {+ realm: promise_realm(promise),+ promise,+ key_system,+ supported_configurations,+ origin,+ };+ deferred_invoke(vm, captures, |vm, captures| {+ let RequestMediaKeySystemAccessCaptures {+ realm,+ promise,+ key_system,+ supported_configurations,+ origin,+ } = captures;+ with_temporary_execution_context_and_callbacks(realm, || {+ // 1. If keySystem is not one of the Key Systems supported by the user agent, reject promise with a NotSupportedError. String comparison is case-sensitive.+ if !is_supported_key_system(&key_system) {+ reject_promise_with_exception(+ vm,+ promise,+ Exception::Dom("NotSupportedError", Utf16String::from_ascii(b"Unsupported key system")),+ );+ return;+ }++ // 2. Let implementation be the implementation of keySystem.+ let implementation = key_system_from_string(&key_system);++ // 3. For each value in supportedConfigurations:+ for candidate_configuration in &supported_configurations {+ // 1. Let candidate configuration be the value.++ // 2. Let supported configuration be the result of executing the Get Supported Configuration algorithm on implementation, candidate configuration, and origin.+ let supported_configuration =+ get_supported_configuration(implementation.as_ref(), candidate_configuration, &origin);++ // 3. If supported configuration is not NotSupported, run the following steps:+ if let Some(supported_configuration) = supported_configuration {+ // 1. Let access be a new MediaKeySystemAccess object, and initialize it as follows:+ // 1. Set the keySystem attribute to keySystem.+ // 2. Let the configuration value be supported configuration.+ // 3. Let the cdm implementation value be implementation.+ let access = MediaKeySystemAccess::create(+ vm,+ key_system,+ supported_configuration+ .configuration+ .expect("a supported configuration has a configuration"),+ implementation,+ );++ // 2. Resolve promise with access and abort the parallel steps of this algorithm.+ let wrapper = wrap(&CallContext::new(vm, realm), access);+ resolve_promise(vm, promise, Value::from_object(wrapper));+ return;+ }+ }++ // 4. Reject promise with a NotSupportedError.+ reject_promise_with_exception(+ vm,+ promise,+ Exception::Dom(+ "NotSupportedError",+ Utf16String::from_ascii(b"No supported configurations found for the requested key system"),+ ),+ );+ });+ });++ Ok(())+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 9d80bc0f17e..235fd69ac46 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -142,6 +142,16 @@ pub(crate) mod encoding;clippy::unnecessary_wraps,reason = "the bindings call every attribute and operation as one that can throw")]+pub(crate) mod encrypted_media_extensions;+#[cfg(not(test))]+#[cfg_attr(+ not(web_idl_bindings),+ allow(dead_code, reason = "only the generated bindings use the interfaces")+)]+#[allow(+ clippy::unnecessary_wraps,+ reason = "the bindings call every attribute and operation as one that can throw"+)]pub(crate) mod event_timing;#[cfg(not(test))]pub(crate) mod fetch;diff --git a/Libraries/LibWeb/Bindings/Rust/src/permissions_policy/permissions_policy.rs b/Libraries/LibWeb/Bindings/Rust/src/permissions_policy/permissions_policy.rsindex f6f945fce7a..a3709e22669 100644--- a/Libraries/LibWeb/Bindings/Rust/src/permissions_policy/permissions_policy.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/permissions_policy/permissions_policy.rs@@ -8,6 +8,7 @@#[derive(Clone, Copy)]#[repr(u8)]pub(crate) enum PolicyControlledFeature {+ EncryptedMedia = 3,Gamepad = 6,Geolocation = 7,}diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex c9b90ee36e9..6cd0eb8302e 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -279,6 +279,7 @@ bool web_bindings_document_is_fully_active(DOM::Document* document)return document->is_fully_active();}+static_assert(to_underlying(DOM::PolicyControlledFeature::EncryptedMedia) == 3);static_assert(to_underlying(DOM::PolicyControlledFeature::Geolocation) == 7);bool web_bindings_document_is_allowed_to_use_feature(DOM::Document* document, u8 feature)diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 89ae7a8f0fa..6fc1b83f0f4 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -268,8 +268,6 @@ set(SOURCESEditing/StyledMarkupSerializer.cppEditing/VisiblePosition.cppEditing/ReplaceSelection.cpp- EncryptedMediaExtensions/Algorithms.cpp- EncryptedMediaExtensions/MediaKeySystemAccess.cppEntriesAPI/FileSystemEntry.cppEventTiming/EventTiming.cppFetch/Body.cppdiff --git a/Libraries/LibWeb/EncryptedMediaExtensions/Algorithms.h b/Libraries/LibWeb/EncryptedMediaExtensions/Algorithms.hdeleted file mode 100644index d4b839c9225..00000000000--- a/Libraries/LibWeb/EncryptedMediaExtensions/Algorithms.h+++ /dev/null@@ -1,28 +0,0 @@-/*- * Copyright (c) 2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <AK/OwnPtr.h>-#include <AK/Types.h>-#include <AK/Utf16String.h>-#include <AK/Vector.h>-#include <LibURL/URL.h>-#include <LibWeb/EncryptedMediaExtensions/KeySystem.h>--namespace Web::EncryptedMediaExtensions {--bool supports_container(Utf16String const& container);-bool is_persistent_session_type(Utf16String const& session_type);-bool is_supported_key_system(Utf16String const& key_system);-NonnullOwnPtr<KeySystem> key_system_from_string(Utf16String const& key_system);-ConsentStatus get_consent_status(MediaKeySystemConfiguration const&, MediaKeyRestrictions&, URL::Origin const&);-Optional<Vector<MediaKeySystemMediaCapability>> get_supported_capabilities_for_audio_video_type(KeySystem const&, CapabilitiesType, Vector<MediaKeySystemMediaCapability>, MediaKeySystemConfiguration, MediaKeyRestrictions);-Optional<ConsentConfiguration> get_supported_configuration_and_consent(KeySystem const&, MediaKeySystemConfiguration const&, MediaKeyRestrictions&, URL::Origin const&);-Optional<ConsentConfiguration> get_supported_configuration(KeySystem const&, MediaKeySystemConfiguration const&, URL::Origin const&);--}diff --git a/Libraries/LibWeb/EncryptedMediaExtensions/EncryptedMediaExtensions.h b/Libraries/LibWeb/EncryptedMediaExtensions/EncryptedMediaExtensions.hdeleted file mode 100644index 51f157e4f69..00000000000--- a/Libraries/LibWeb/EncryptedMediaExtensions/EncryptedMediaExtensions.h+++ /dev/null@@ -1,42 +0,0 @@-/*- * Copyright (c) 2025, Psychpsyo <[email protected]>- * Copyright (c) 2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <AK/Utf16String.h>-#include <AK/Vector.h>-#include <LibWeb/Bindings/MediaKeySystemAccess.h>--namespace Web::EncryptedMediaExtensions {--using MediaKeysRequirement = Bindings::MediaKeysRequirement;-using MediaKeySystemConfiguration = Bindings::MediaKeySystemConfiguration;-using MediaKeySystemMediaCapability = Bindings::MediaKeySystemMediaCapability;--struct MediaKeyRestrictions {- bool distinctive_identifiers { true };- bool persist_state { true };-};--enum CapabilitiesType {- Audio,- Video-};--enum ConsentStatus {- ConsentDenied,- InformUser,- Allowed-};--struct ConsentConfiguration {- ConsentStatus status { ConsentStatus::ConsentDenied };- Optional<MediaKeySystemConfiguration> configuration;-};--}diff --git a/Libraries/LibWeb/EncryptedMediaExtensions/KeySystem.h b/Libraries/LibWeb/EncryptedMediaExtensions/KeySystem.hdeleted file mode 100644index 0fbc32a992a..00000000000--- a/Libraries/LibWeb/EncryptedMediaExtensions/KeySystem.h+++ /dev/null@@ -1,75 +0,0 @@-/*- * Copyright (c) 2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/OwnPtr.h>-#include <AK/Utf16String.h>-#include <LibWeb/EncryptedMediaExtensions/EncryptedMediaExtensions.h>--namespace Web::EncryptedMediaExtensions {--class KeySystem {-public:- virtual ~KeySystem() = default;-- virtual bool supports_init_data_type(Utf16String const& init_data_type) const = 0;- virtual bool supports_encryption_scheme(Utf16String const& encryption_scheme) const = 0;- virtual bool supports_robustness(Utf16String const& robustness) const = 0;- virtual bool definitely_supports_playback(Utf16String const& container, Utf16String const& media_types, Optional<Utf16String> encryption_scheme, Utf16String const& robustness, MediaKeySystemConfiguration const& accumulated_configuration, MediaKeyRestrictions const& restrictions) const = 0;--private:-};--class ClearKeySystem : public KeySystem {-public:- AK_ALLOC_WITH_KMALLOC;-- ClearKeySystem() = default;- virtual ~ClearKeySystem() override = default;-- // https://w3c.github.io/encrypted-media/#clear-key-behavior- virtual bool supports_init_data_type(Utf16String const& init_data_type) const override- {- // Implementations SHOULD support the "keyids" type- // TODO: Implementations MAY support any combination of registered Initialization Data Types- // https://www.w3.org/TR/eme-initdata-registry/- constexpr Array<Utf16View, 1> registered_init_data_types = {- "keyids"sv,- };-- return registered_init_data_types.contains_slow(init_data_type);- }-- // https://w3c.github.io/encrypted-media/#clear-key-capabilities- virtual bool supports_encryption_scheme(Utf16String const& encryption_scheme) const override- {- // encryptionScheme: Implementations MUST support the "cenc" scheme, and MAY support other schemes.- return encryption_scheme == "cenc"sv;- }-- // https://w3c.github.io/encrypted-media/#clear-key-capabilities- virtual bool supports_robustness(Utf16String const& robustness) const override- {- // robustness: Only the empty string is supported.- return robustness.is_empty();- }-- virtual bool definitely_supports_playback(Utf16String const& container, Utf16String const& media_types, Optional<Utf16String> encryption_scheme, Utf16String const& robustness, MediaKeySystemConfiguration const& accumulated_configuration, MediaKeyRestrictions const& restrictions) const override- {- (void)container;- (void)media_types;- (void)encryption_scheme;- (void)robustness;- (void)accumulated_configuration;- (void)restrictions;-- // FIXME: Do some checks here- return true;- }-};--}diff --git a/Libraries/LibWeb/EncryptedMediaExtensions/MediaKeySystemAccess.cpp b/Libraries/LibWeb/EncryptedMediaExtensions/MediaKeySystemAccess.cppdeleted file mode 100644index e2c16339fd4..00000000000--- a/Libraries/LibWeb/EncryptedMediaExtensions/MediaKeySystemAccess.cpp+++ /dev/null@@ -1,27 +0,0 @@-/*- * Copyright (c) 2025, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibWeb/EncryptedMediaExtensions/MediaKeySystemAccess.h>--namespace Web::EncryptedMediaExtensions {--GC_DEFINE_ALLOCATOR(MediaKeySystemAccess);--MediaKeySystemAccess::~MediaKeySystemAccess() = default;--MediaKeySystemAccess::MediaKeySystemAccess(Utf16String const& key_system, MediaKeySystemConfiguration configuration, NonnullOwnPtr<KeySystem> cdm_implementation)- : m_key_system(key_system)- , m_configuration(move(configuration))- , m_cdm_implementation(move(cdm_implementation))-{-}--GC::Ref<MediaKeySystemAccess> MediaKeySystemAccess::create(Utf16String const& key_system, MediaKeySystemConfiguration configuration, NonnullOwnPtr<KeySystem> cdm_implementation)-{- return GC::Heap::the().allocate<MediaKeySystemAccess>(key_system, move(configuration), move(cdm_implementation));-}--}diff --git a/Libraries/LibWeb/EncryptedMediaExtensions/MediaKeySystemAccess.h b/Libraries/LibWeb/EncryptedMediaExtensions/MediaKeySystemAccess.hindex b2394ef69b9..25c0c17e211 100644--- a/Libraries/LibWeb/EncryptedMediaExtensions/MediaKeySystemAccess.h+++ b/Libraries/LibWeb/EncryptedMediaExtensions/MediaKeySystemAccess.h@@ -6,34 +6,13 @@#pragma once-#include <AK/RefPtr.h>-#include <LibGC/Heap.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/EncryptedMediaExtensions/EncryptedMediaExtensions.h>-#include <LibWeb/EncryptedMediaExtensions/KeySystem.h>+#include <LibWeb/Bindings/MediaKeySystemAccess.h>+#include <LibWeb/Bindings/RustInterface.h>namespace Web::EncryptedMediaExtensions {-// https://w3c.github.io/encrypted-media/#dom-mediakeysystemaccess-class MediaKeySystemAccess : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(MediaKeySystemAccess, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(MediaKeySystemAccess);--public:- virtual ~MediaKeySystemAccess() override;- [[nodiscard]] static GC::Ref<MediaKeySystemAccess> create(Utf16String const&, MediaKeySystemConfiguration, NonnullOwnPtr<KeySystem>);-- [[nodiscard]] Utf16String key_system() const { return m_key_system; }- [[nodiscard]] MediaKeySystemConfiguration const& get_configuration() const { return m_configuration; }--protected:- explicit MediaKeySystemAccess(Utf16String const&, MediaKeySystemConfiguration, NonnullOwnPtr<KeySystem>);--private:- Utf16String m_key_system;-- MediaKeySystemConfiguration m_configuration;- NonnullOwnPtr<KeySystem> m_cdm_implementation;+class MediaKeySystemAccess : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(MediaKeySystemAccess, media_key_system_access)};}diff --git a/Libraries/LibWeb/EncryptedMediaExtensions/MediaKeySystemAccess.idl b/Libraries/LibWeb/EncryptedMediaExtensions/MediaKeySystemAccess.idlindex 9bc9c9dccbc..31d255a7e74 100644--- a/Libraries/LibWeb/EncryptedMediaExtensions/MediaKeySystemAccess.idl+++ b/Libraries/LibWeb/EncryptedMediaExtensions/MediaKeySystemAccess.idl@@ -1,5 +1,5 @@// https://w3c.github.io/encrypted-media/#mediakeysystemaccess-interface-[Exposed=Window, SecureContext]+[Exposed=Window, SecureContext, ImplementedIn=Rust]interface MediaKeySystemAccess {readonly attribute DOMString keySystem;MediaKeySystemConfiguration getConfiguration();@@ -39,7 +39,7 @@ enum MediaKeySessionType {// https://w3c.github.io/encrypted-media/#navigator-extension-requestmediakeysystemaccess[Exposed=Window]partial interface Navigator {- [CreatesPromise, SecureContext] Promise<MediaKeySystemAccess> requestMediaKeySystemAccess(+ [CreatesPromise, SecureContext, ImplementedIn=Rust] Promise<MediaKeySystemAccess> requestMediaKeySystemAccess(DOMString keySystem,sequence<MediaKeySystemConfiguration> supportedConfigurations);diff --git a/Libraries/LibWeb/HTML/Navigator.cpp b/Libraries/LibWeb/HTML/Navigator.cppindex f0c520744ce..9b6845594c0 100644--- a/Libraries/LibWeb/HTML/Navigator.cpp+++ b/Libraries/LibWeb/HTML/Navigator.cpp@@ -8,25 +8,20 @@*/#include <LibGC/Heap.h>+#include <LibJS/HostClassBuilder.h>#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/Clipboard/Clipboard.h>#include <LibWeb/CredentialManagement/CredentialsContainer.h>#include <LibWeb/DOM/Document.h>-#include <LibWeb/EncryptedMediaExtensions/Algorithms.h>-#include <LibWeb/EncryptedMediaExtensions/EncryptedMediaExtensions.h>-#include <LibWeb/EncryptedMediaExtensions/MediaKeySystemAccess.h>#include <LibWeb/Geolocation/Geolocation.h>#include <LibWeb/HTML/Navigator.h>#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/Window.h>#include <LibWeb/Loader/ResourceLoader.h>#include <LibWeb/MediaCapture/MediaDevices.h>#include <LibWeb/MediaSession/MediaSession.h>#include <LibWeb/Page/Page.h>#include <LibWeb/PermissionsAPI/Permissions.h>-#include <LibWeb/Platform/EventLoopPlugin.h>#include <LibWeb/ServiceWorker/ServiceWorkerContainer.h>#include <LibWeb/WebIDL/AbstractOperations.h>#include <LibWeb/WebIDL/CallbackType.h>@@ -34,6 +29,12 @@namespace Web::HTML {+extern "C" {++// Called by Bindings/Rust/src/html/navigator.rs.+Window* web_html_navigator_window(JSObject* navigator_wrapper);+}+GC_DEFINE_ALLOCATOR(Navigator);GC::Ref<Navigator> Navigator::create(Window& window)@@ -232,69 +233,9 @@ GC::Ref<PermissionsAPI::Permissions> Navigator::permissions()return *m_permissions;}-void Navigator::request_media_key_system_access(Utf16String key_system, Vector<EncryptedMediaExtensions::MediaKeySystemConfiguration> supported_configurations, GC::Ref<WebIDL::Promise> promise)+Window* web_html_navigator_window(JSObject* navigator_wrapper){- // 1. If this's relevant global object's associated Document is not allowed to use the encrypted-media feature, then throw a "SecurityError" DOMException and abort these steps.- auto& associated_document = window().associated_document();- if (!associated_document.is_allowed_to_use_feature(DOM::PolicyControlledFeature::EncryptedMedia)) {- WebIDL::reject_promise(promise, WebIDL::SecurityError::create("This document is not allowed to use the encrypted-media feature"_utf16));- return;- }-- // 2. If keySystem is the empty string, return a promise rejected with a newly created TypeError.- if (key_system.is_empty()) {- WebIDL::reject_promise_with_exception(promise, WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "keySystem must not be empty"_utf16 });- return;- }-- // 3. If supportedConfigurations is empty, return a promise rejected with a newly created TypeError.- if (supported_configurations.is_empty()) {- WebIDL::reject_promise_with_exception(promise, WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "supportedConfigurations must not be empty"_utf16 });- return;- }-- // 4. Let document be the calling context's Document.- // FIXME: Is this the same as the associated document?- auto& document = associated_document;-- // 5. Let origin be the origin of document.- auto origin = document.origin();-- // 7. Run the following steps in parallel:- auto& realm = WebIDL::promise_realm(promise);- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, key_system, move(supported_configurations), origin, promise), [](auto& realm, auto& key_system, auto& supported_configurations, auto& origin, auto& promise) {- TemporaryExecutionContext context(realm, TemporaryExecutionContext::CallbacksEnabled::Yes);-- // 1. If keySystem is not one of the Key Systems supported by the user agent, reject promise with a NotSupportedError. String comparison is case-sensitive.- if (!EncryptedMediaExtensions::is_supported_key_system(key_system))- return WebIDL::reject_promise(promise, WebIDL::NotSupportedError::create("Unsupported key system"_utf16));-- // 2. Let implementation be the implementation of keySystem.- auto implementation = EncryptedMediaExtensions::key_system_from_string(key_system);-- // 3. For each value in supportedConfigurations:- for (auto const& candidate_configuration : supported_configurations) {- // 1. Let candidate configuration be the value.-- // 2. Let supported configuration be the result of executing the Get Supported Configuration algorithm on implementation, candidate configuration, and origin.- auto supported_configuration = EncryptedMediaExtensions::get_supported_configuration(*implementation, candidate_configuration, origin);-- // 3. If supported configuration is not NotSupported, run the following steps:- if (supported_configuration.has_value()) {- // 1. Let access be a new MediaKeySystemAccess object, and initialize it as follows:- // 1. Set the keySystem attribute to keySystem.- // 2. Let the configuration value be supported configuration.- // 3. Let the cdm implementation value be implementation.- auto access = EncryptedMediaExtensions::MediaKeySystemAccess::create(key_system, *supported_configuration->configuration, move(implementation));-- // 2. Resolve promise with access and abort the parallel steps of this algorithm.- return WebIDL::resolve_promise(promise, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, access));- }- }-- // 4. Reject promise with a NotSupportedError.- WebIDL::reject_promise(promise, WebIDL::NotSupportedError::create("No supported configurations found for the requested key system"_utf16));- }));+ return &Bindings::impl_from<Navigator>(JS::HostABI::object_from_abi(navigator_wrapper))->window();}}diff --git a/Libraries/LibWeb/HTML/Navigator.h b/Libraries/LibWeb/HTML/Navigator.hindex 1d0afad0ff7..5df457ea4ae 100644--- a/Libraries/LibWeb/HTML/Navigator.h+++ b/Libraries/LibWeb/HTML/Navigator.h@@ -70,7 +70,6 @@ public:GC::Ref<WebIDL::Promise> get_battery();void start_get_battery_steps(GC::Ref<WebIDL::Promise>);[[nodiscard]] GC::Ref<PermissionsAPI::Permissions> permissions();- void request_media_key_system_access(Utf16String key_system, Vector<EncryptedMediaExtensions::MediaKeySystemConfiguration> supported_configurations, GC::Ref<WebIDL::Promise>);GC::Ref<ServiceWorker::ServiceWorkerContainer> service_worker();diff --git a/Libraries/LibWeb/MediaCapabilitiesAPI/MediaCapabilities.h b/Libraries/LibWeb/MediaCapabilitiesAPI/MediaCapabilities.hindex 8e48f8b920a..f20f4a4f19b 100644--- a/Libraries/LibWeb/MediaCapabilitiesAPI/MediaCapabilities.h+++ b/Libraries/LibWeb/MediaCapabilitiesAPI/MediaCapabilities.h@@ -15,7 +15,7 @@#include <LibMediaCodecs/DecoderCapabilities.h>#include <LibWeb/Bindings/MediaCapabilities.h>#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/EncryptedMediaExtensions/EncryptedMediaExtensions.h>+#include <LibWeb/EncryptedMediaExtensions/MediaKeySystemAccess.h>#include <LibWebCommon/WebIDL/Types.h>namespace Web::MediaCapabilitiesAPI {