Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(webrtc): snapshot and validate peer connection configuration

ldm09a93e52517db
diff --git a/moli-renderer-v8/src/context_bootstrap/webrtc.rs b/moli-renderer-v8/src/context_bootstrap/webrtc.rs
index eeba3064a..fd573340e 100644
--- a/moli-renderer-v8/src/context_bootstrap/webrtc.rs
+++ b/moli-renderer-v8/src/context_bootstrap/webrtc.rs
@@ -5,6 +5,7 @@ use crate::util::{
use crate::web_api_interfaces;
use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};
+mod configuration;
mod events;
mod ice_candidate;
mod ice_candidate_parser;
@@ -161,8 +162,6 @@ struct RtcPeerConnectionPrototypeDeclaration {
create_offer: (),
#[webapi(method = "setLocalDescription", length = 0, callback = rtc_peer_connection_set_local_description_callback)]
set_local_description: (),
- #[webapi(method = "getConfiguration", length = 0, callback = rtc_peer_connection_get_configuration_callback)]
- get_configuration: (),
#[webapi(method, length = 0, callback = rtc_peer_connection_close_callback)]
close: (),
}
@@ -222,6 +221,7 @@ pub(in crate::context_bootstrap) fn install_webrtc_template_bindings<'s>(
}
"RTCPeerConnection" => {
RtcPeerConnectionPrototypeDeclaration::initialize_prototype_template(scope, prototype);
+ configuration::install(scope, prototype);
}
"RTCErrorEvent" => events::install_event_template_bindings(scope, template, interface_name),
"RTCRtpReceiver" => {
@@ -246,15 +246,7 @@ pub(in crate::context_bootstrap) fn rtc_peer_connection_constructor_callback<'s>
);
return;
}
- let configuration = if args.length() == 0 || args.get(0).is_null_or_undefined() {
- v8::Object::new(scope)
- } else if let Ok(configuration) = v8::Local::<v8::Object>::try_from(args.get(0)) {
- configuration
- } else {
- throw_type_error(
- scope,
- "Failed to construct 'RTCPeerConnection': The provided configuration is not a dictionary.",
- );
+ let Some(configuration) = configuration::constructor_configuration(scope, &args) else {
return;
};
let declaration = RtcPeerConnectionObjectDeclaration {
@@ -431,21 +423,6 @@ fn rtc_peer_connection_set_local_description_callback<'s>(
set_resolved_promise(scope, &mut rv, v8::undefined(scope).into());
}
-fn rtc_peer_connection_get_configuration_callback<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- args: v8::FunctionCallbackArguments<'s>,
- mut rv: v8::ReturnValue<'_, v8::Value>,
-) {
- if !rtc_peer_connection_receiver_branded(scope, args.this()) {
- throw_type_error(scope, "Illegal invocation");
- return;
- }
- rv.set(
- get_private_value(scope, args.this(), RTC_PEER_CONNECTION_CONFIGURATION_SLOT)
- .unwrap_or_else(|| v8::Object::new(scope).into()),
- );
-}
-
fn rtc_peer_connection_close_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
diff --git a/moli-renderer-v8/src/context_bootstrap/webrtc/configuration.rs b/moli-renderer-v8/src/context_bootstrap/webrtc/configuration.rs
new file mode 100644
index 000000000..ec7e21651
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/webrtc/configuration.rs
@@ -0,0 +1,474 @@
+//! Configuration dictionaries and snapshots, independent of an ICE transport.
+//! Argument conversion completes before inspecting or changing connection state.
+
+use super::{
+ RTC_PEER_CONNECTION_CONFIGURATION_SLOT, RTC_PEER_CONNECTION_LOCAL_DESCRIPTION_SLOT,
+ RTC_PEER_CONNECTION_SIGNALING_STATE_SLOT,
+};
+use crate::{
+ util::{get_private_value, new_null_prototype_object, set_private_value, v8str},
+ web_api_interfaces, webidl,
+};
+use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject, WebApiValue};
+
+#[derive(Clone, Copy, webidl::WebIdlEnum)]
+#[webidl(name = "RTCBundlePolicy")]
+enum BundlePolicy {
+ #[webidl(token = "balanced")]
+ Balanced,
+ #[webidl(token = "max-compat")]
+ MaxCompat,
+ #[webidl(token = "max-bundle")]
+ MaxBundle,
+}
+
+#[derive(Clone, Copy, webidl::WebIdlEnum)]
+#[webidl(name = "RTCIceTransportPolicy")]
+enum IceTransportPolicy {
+ #[webidl(token = "all")]
+ All,
+ #[webidl(token = "relay")]
+ Relay,
+}
+
+#[derive(Clone, Copy, webidl::WebIdlEnum)]
+#[webidl(name = "RTCRtcpMuxPolicy")]
+enum RtcpMuxPolicy {
+ #[webidl(token = "require")]
+ Require,
+}
+
+impl<'s> WebApiValue<'s> for BundlePolicy {
+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {
+ match self {
+ Self::Balanced => "balanced",
+ Self::MaxCompat => "max-compat",
+ Self::MaxBundle => "max-bundle",
+ }
+ .to_v8_value(scope)
+ }
+}
+
+impl<'s> WebApiValue<'s> for IceTransportPolicy {
+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {
+ match self {
+ Self::All => "all",
+ Self::Relay => "relay",
+ }
+ .to_v8_value(scope)
+ }
+}
+
+impl<'s> WebApiValue<'s> for RtcpMuxPolicy {
+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {
+ "require".to_v8_value(scope)
+ }
+}
+
+struct PoolSize(u8);
+
+impl<'s> webidl::WebIdlConverter<'s> for PoolSize {
+ type Options = ();
+
+ fn convert(
+ scope: &mut v8::PinScope<'s, '_>,
+ value: v8::Local<'s, v8::Value>,
+ context: webidl::Context,
+ _: &(),
+ ) -> Result<Self, webidl::WebIdlError> {
+ let value = webidl::convert::<webidl::EnforceRangeUnsignedLong>(scope, value, context)?.0;
+ u8::try_from(value)
+ .map(Self)
+ .map_err(|_| webidl::WebIdlError::cannot_convert(context, "[EnforceRange] octet"))
+ }
+}
+
+impl<'s> WebApiValue<'s> for PoolSize {
+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {
+ self.0.to_v8_value(scope)
+ }
+}
+
+struct Text(webidl::DomString16);
+
+impl<'s> webidl::WebIdlConverter<'s> for Text {
+ type Options = ();
+
+ fn convert(
+ scope: &mut v8::PinScope<'s, '_>,
+ value: v8::Local<'s, v8::Value>,
+ context: webidl::Context,
+ _: &(),
+ ) -> Result<Self, webidl::WebIdlError> {
+ webidl::convert::<webidl::DomString16>(scope, value, context).map(Self)
+ }
+}
+
+impl<'s> WebApiValue<'s> for Text {
+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {
+ v8::String::new_from_two_byte(scope, &self.0.0, v8::NewStringType::Normal).map(Into::into)
+ }
+}
+
+struct IceUrls(Vec<String>);
+
+impl<'s> webidl::WebIdlConverter<'s> for IceUrls {
+ type Options = ();
+
+ fn convert(
+ scope: &mut v8::PinScope<'s, '_>,
+ value: v8::Local<'s, v8::Value>,
+ context: webidl::Context,
+ _: &(),
+ ) -> Result<Self, webidl::WebIdlError> {
+ // Union discrimination must not read @@iterator twice or iterate strings.
+ if let Some(values) = webidl::convert_optional_sequence::<webidl::UsvString>(
+ scope,
+ value,
+ context,
+ &Default::default(),
+ )? {
+ return Ok(Self(values.0.into_iter().map(|value| value.0).collect()));
+ }
+ let value = webidl::convert::<webidl::UsvString>(scope, value, context)?.0;
+ Ok(Self(vec![value]))
+ }
+}
+
+impl<'s> WebApiValue<'s> for IceUrls {
+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {
+ self.0.to_v8_value(scope)
+ }
+}
+
+#[derive(webidl::WebIdlDictionary, WebApiObject)]
+#[webidl(prefix = "RTCIceServer")]
+#[webapi(plain, enumerable)]
+struct IceServer {
+ #[webidl(converter = "raw")]
+ #[webapi(data_property)]
+ credential: Option<Text>,
+ #[webidl(required, converter = "raw")]
+ #[webapi(data_property)]
+ urls: IceUrls,
+ #[webidl(converter = "raw")]
+ #[webapi(data_property)]
+ username: Option<Text>,
+}
+
+#[derive(webidl::WebIdlDictionary, WebApiObject)]
+#[webidl(prefix = "RTCConfiguration")]
+#[webapi(plain, enumerable)]
+struct Configuration<'s> {
+ #[webidl(converter = "enum", default = BundlePolicy::Balanced)]
+ #[webapi(data_property)]
+ bundle_policy: BundlePolicy,
+ #[webidl(sequence, interface = web_api_interfaces::RTCCertificate, default = Vec::new())]
+ #[webapi(data_property)]
+ certificates: Vec<v8::Local<'s, v8::Object>>,
+ #[webidl(converter = "raw", default = PoolSize(0))]
+ #[webapi(data_property)]
+ ice_candidate_pool_size: PoolSize,
+ #[webidl(sequence, converter = "dictionary", default = Vec::new())]
+ #[webapi(data_property)]
+ ice_servers: Vec<IceServer>,
+ #[webidl(converter = "enum", default = IceTransportPolicy::All)]
+ #[webapi(data_property)]
+ ice_transport_policy: IceTransportPolicy,
+ #[webidl(converter = "enum", default = RtcpMuxPolicy::Require)]
+ #[webapi(data_property)]
+ rtcp_mux_policy: RtcpMuxPolicy,
+}
+
+#[derive(webidl::WebIdlArgs)]
+#[webidl(prefix = "RTCPeerConnection")]
+struct ConfigurationArgs<'s> {
+ #[webidl(dictionary)]
+ configuration: Configuration<'s>,
+}
+
+#[derive(WebApiFunctionTemplate)]
+#[webapi(interface = web_api_interfaces::RTCPeerConnection, enumerable, receiver)]
+struct ConfigurationPrototype {
+ #[webapi(method, length = 0, callback = get_configuration)]
+ get_configuration: (),
+ #[webapi(method, length = 0, callback = set_configuration)]
+ set_configuration: (),
+}
+
+pub(super) fn install<'s>(
+ scope: &mut v8::PinScope<'s, '_, ()>,
+ prototype: v8::Local<'s, v8::ObjectTemplate>,
+) {
+ ConfigurationPrototype::initialize_prototype_template(scope, prototype);
+}
+
+pub(super) fn constructor_configuration<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: &v8::FunctionCallbackArguments<'s>,
+) -> Option<v8::Local<'s, v8::Object>> {
+ let parsed = webidl::parse_args::<ConfigurationArgs>(scope, args)?;
+ validate_servers(scope, &parsed.configuration)?;
+ let object = parsed
+ .configuration
+ .bind(scope)
+ .expect("converted RTCConfiguration");
+ Some(copy_configuration(scope, object, true))
+}
+
+fn target<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ receiver: v8::Local<'s, v8::Object>,
+) -> v8::Local<'s, v8::Object> {
+ moli_webapi_declare::web_api_object_target(scope, receiver)
+ .expect("validated RTCPeerConnection")
+}
+
+fn configuration<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ target: v8::Local<'s, v8::Object>,
+) -> v8::Local<'s, v8::Object> {
+ get_private_value(scope, target, RTC_PEER_CONNECTION_CONFIGURATION_SLOT)
+ .and_then(|value| v8::Local::try_from(value).ok())
+ .expect("native RTCConfiguration snapshot")
+}
+
+fn get_configuration<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let target = target(scope, args.this());
+ let stored = configuration(scope, target);
+ rv.set(copy_configuration(scope, stored, false).into());
+}
+
+fn set_configuration<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ _rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let Some(parsed) = webidl::parse_args::<ConfigurationArgs>(scope, &args) else {
+ return;
+ };
+ let target = target(scope, args.this());
+ let state = get_private_value(scope, target, RTC_PEER_CONNECTION_SIGNALING_STATE_SLOT)
+ .expect("native signaling state");
+ if state.strict_equals(v8str(scope, "closed").into()) {
+ webidl::throw_dom_exception(scope, "InvalidStateError", "The connection is closed.");
+ return;
+ }
+ let old = configuration(scope, target);
+ let next = parsed
+ .configuration
+ .bind(scope)
+ .expect("converted RTCConfiguration");
+ let local_description =
+ get_private_value(scope, target, RTC_PEER_CONNECTION_LOCAL_DESCRIPTION_SLOT)
+ .expect("native local description");
+ let unchanged = ["bundlePolicy", "rtcpMuxPolicy"]
+ .into_iter()
+ .all(|name| property(scope, old, name).strict_equals(property(scope, next, name)))
+ && same_certificates(scope, old, next)
+ && (local_description.is_null()
+ || property(scope, old, "iceCandidatePoolSize").strict_equals(property(
+ scope,
+ next,
+ "iceCandidatePoolSize",
+ )));
+ if !unchanged {
+ webidl::throw_dom_exception(
+ scope,
+ "InvalidModificationError",
+ "An immutable configuration member changed.",
+ );
+ return;
+ }
+ if validate_servers(scope, &parsed.configuration).is_none() {
+ return;
+ }
+ let snapshot = copy_configuration(scope, next, true);
+ set_private_value(
+ scope,
+ target,
+ RTC_PEER_CONNECTION_CONFIGURATION_SLOT,
+ snapshot.into(),
+ );
+}
+
+fn validate_servers(scope: &mut v8::PinScope<'_, '_>, config: &Configuration<'_>) -> Option<()> {
+ for server in &config.ice_servers {
+ if server.urls.0.is_empty() {
+ webidl::throw_dom_exception(
+ scope,
+ "SyntaxError",
+ "An ICE server needs at least one URL.",
+ );
+ return None;
+ }
+ for value in &server.urls.0 {
+ let Ok(turn) = validate_url(value) else {
+ webidl::throw_dom_exception(scope, "SyntaxError", "Invalid ICE server URL.");
+ return None;
+ };
+ if turn
+ && (server
+ .username
+ .as_ref()
+ .is_none_or(|value| String::from_utf16_lossy(&value.0.0).len() > 509)
+ || server
+ .credential
+ .as_ref()
+ .is_none_or(|value| value.0.0.is_empty()))
+ {
+ webidl::throw_dom_exception(
+ scope,
+ "InvalidAccessError",
+ "Invalid TURN username or credential.",
+ );
+ return None;
+ }
+ }
+ }
+ Some(())
+}
+
+// WebRTC-PC's ICE URL validation algorithm parses the opaque URI first,
+// then validates its host/port using the URL parser. It is not a generic
+// hierarchical URL: paths, userinfo, fragments and arbitrary queries fail.
+fn validate_url(value: &str) -> Result<bool, ()> {
+ let uri = url::Url::parse(value).map_err(|_| ())?;
+ let turn = match uri.scheme() {
+ "stun" | "stuns" => false,
+ "turn" | "turns" => true,
+ _ => return Err(()),
+ };
+ if !uri.cannot_be_a_base()
+ || uri.path().contains(['/', '\\', '@'])
+ || uri.fragment().is_some()
+ || uri
+ .query()
+ .is_some_and(|query| !turn || !matches!(query, "transport=udp" | "transport=tcp"))
+ {
+ return Err(());
+ }
+ let authority = url::Url::parse(&format!("https://{}", uri.path())).map_err(|_| ())?;
+ if authority.host().is_none()
+ || authority.path() != "/"
+ || !authority.username().is_empty()
+ || authority.password().is_some()
+ || authority.query().is_some()
+ || authority.fragment().is_some()
+ {
+ return Err(());
+ }
+ Ok(turn)
+}
+
+fn property<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+ name: &'static str,
+) -> v8::Local<'s, v8::Value> {
+ object
+ .get(scope, v8str(scope, name).into())
+ .expect("private dictionary data")
+}
+
+fn array_property<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+ name: &'static str,
+) -> v8::Local<'s, v8::Array> {
+ v8::Local::try_from(property(scope, object, name)).expect("private sequence")
+}
+
+fn same_certificates<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ old: v8::Local<'s, v8::Object>,
+ next: v8::Local<'s, v8::Object>,
+) -> bool {
+ let old = array_property(scope, old, "certificates");
+ let next = array_property(scope, next, "certificates");
+ old.length() == next.length()
+ && (0..old.length()).all(|index| {
+ old.get_index(scope, index)
+ .expect("certificate")
+ .strict_equals(next.get_index(scope, index).expect("certificate"))
+ })
+}
+
+fn copy_configuration<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ source: v8::Local<'s, v8::Object>,
+ internal: bool,
+) -> v8::Local<'s, v8::Object> {
+ let output = if internal {
+ new_null_prototype_object(scope)
+ } else {
+ v8::Object::new(scope)
+ };
+ for name in [
+ "bundlePolicy",
+ "certificates",
+ "iceCandidatePoolSize",
+ "iceServers",
+ "iceTransportPolicy",
+ "rtcpMuxPolicy",
+ ] {
+ let mut value = property(scope, source, name);
+ if matches!(name, "certificates" | "iceServers") {
+ let array = v8::Local::<v8::Array>::try_from(value).expect("private sequence");
+ let mut items = Vec::new();
+ for index in 0..array.length() {
+ let mut item = array
+ .get_index(scope, index)
+ .expect("private sequence item");
+ if name == "iceServers" {
+ let server =
+ v8::Local::<v8::Object>::try_from(item).expect("private ICE server");
+ item = copy_server(scope, server, internal).into();
+ }
+ items.push(item);
+ }
+ value = v8::Array::new_with_elements(scope, &items).into();
+ }
+ assert_eq!(
+ output.create_data_property(scope, v8str(scope, name).into(), value),
+ Some(true)
+ );
+ }
+ output
+}
+
+fn copy_server<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ source: v8::Local<'s, v8::Object>,
+ internal: bool,
+) -> v8::Local<'s, v8::Object> {
+ let output = if internal {
+ new_null_prototype_object(scope)
+ } else {
+ v8::Object::new(scope)
+ };
+ for name in ["credential", "urls", "username"] {
+ let key = v8str(scope, name);
+ // Optional members are absent, not inherited from a polluted prototype.
+ if source.has_own_property(scope, key.into()) != Some(true) {
+ continue;
+ }
+ let mut value = property(scope, source, name);
+ if name == "urls" {
+ let array = v8::Local::<v8::Array>::try_from(value).expect("private URL sequence");
+ let items: Vec<_> = (0..array.length())
+ .map(|index| array.get_index(scope, index).expect("private URL"))
+ .collect();
+ value = v8::Array::new_with_elements(scope, &items).into();
+ }
+ assert_eq!(
+ output.create_data_property(scope, key.into(), value),
+ Some(true)
+ );
+ }
+ output
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs
index b413f3041..486f6018a 100644
--- a/moli-renderer-v8/src/script_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs
@@ -2197,6 +2197,7 @@ mod queue_microtask;
mod readable_algorithm_arrays;
mod remote_playback_interface;
mod rendering_update;
+mod rtc_configuration;
mod script_terminal_completion;
mod speech_events;
mod storage_dense_name_arrays;
diff --git a/moli-renderer-v8/src/script_vm/tests/rtc_configuration.rs b/moli-renderer-v8/src/script_vm/tests/rtc_configuration.rs
new file mode 100644
index 000000000..ae20df7cd
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/rtc_configuration.rs
@@ -0,0 +1,94 @@
+use super::*;
+
+#[test]
+fn rtc_configuration_converts_dictionaries_and_keeps_atomic_independent_snapshots() {
+ let mut vm = new_storage_page_task_executor_test_vm("https://rtc-configuration.test/");
+ vm.eval("document.body.innerHTML = '<iframe></iframe>'")
+ .unwrap();
+ let result = vm
+ .eval(include_str!("../../../tests/fixtures/rtc-configuration.js"))
+ .unwrap();
+ if result != "true" {
+ panic!(
+ "{}",
+ vm.eval("JSON.stringify(__uiEventResults.checks.filter(row=>!row.passed))")
+ .unwrap()
+ );
+ }
+ assert_eq!(vm.eval("__uiEventResults.total").unwrap(), "184");
+ assert_eq!(
+ vm.eval("new Set(__uiEventResults.checks.map(row=>row.name)).size")
+ .unwrap(),
+ "184"
+ );
+}
+
+#[test]
+fn rtc_configuration_uses_registered_native_proxy_identity() {
+ let mut vm = new_storage_page_task_executor_test_vm("https://rtc-configuration.test/");
+ vm.eval("globalThis.pc = new RTCPeerConnection({iceTransportPolicy:'relay'})")
+ .unwrap();
+ let context_ptr = &vm.page_default_runtime.context as *const _;
+ vm.with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| {
+ let global = scope.get_current_context().global(scope);
+ let target = global
+ .get(scope, crate::util::v8str(scope, "pc").into())
+ .unwrap()
+ .to_object(scope)
+ .unwrap();
+ let handler = crate::util::new_null_prototype_object(scope);
+ let proxy = v8::Proxy::new(scope, target, handler).unwrap();
+ moli_webapi_declare::register_web_api_proxy(scope, proxy).unwrap();
+ assert_eq!(
+ global.create_data_property(
+ scope,
+ crate::util::v8str(scope, "nativePc").into(),
+ proxy.into()
+ ),
+ Some(true)
+ );
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(vm.eval(r#"(() => {
+ if (nativePc.getConfiguration().iceTransportPolicy !== 'relay') return false;
+ nativePc.setConfiguration({iceServers:[{urls:'stun:host.example'}]});
+ const config=pc.getConfiguration();
+ if (config.iceTransportPolicy !== 'all' || config.iceServers[0].urls[0] !== 'stun:host.example') return false;
+ let converted=0;
+ try { RTCPeerConnection.prototype.setConfiguration.call(new Proxy(nativePc, {}), {get iceServers(){converted++;return [];}}); return false; }
+ catch (error) { if (!(error instanceof TypeError) || converted !== 0) return false; }
+ pc.close();
+ try {nativePc.setConfiguration();return false;}catch(error){return error.name === 'InvalidStateError';}
+ })()"#).unwrap(), "true");
+}
+
+#[test]
+fn rtc_configuration_applies_reentrant_updates_before_validating_the_outer_call() {
+ let mut vm = new_storage_page_task_executor_test_vm("https://rtc-configuration.test/");
+ assert_eq!(vm.eval(r#"(() => {
+ const pc = new RTCPeerConnection();
+ let sentinel={};
+ try {
+ pc.setConfiguration({get iceServers(){pc.setConfiguration({iceTransportPolicy:'relay'});throw sentinel;}});
+ return false;
+ } catch (error) {if (error !== sentinel || pc.getConfiguration().iceTransportPolicy !== 'relay') return false;}
+ pc.setConfiguration({get iceServers(){pc.setConfiguration({iceTransportPolicy:'relay'});return [];}});
+ const result=pc.getConfiguration().iceTransportPolicy === 'all';pc.close();return result;
+ })()"#).unwrap(), "true");
+}
+
+#[test]
+fn rtc_configuration_cannot_resize_the_pool_after_setting_a_local_description() {
+ let mut vm = new_storage_page_task_executor_test_vm("https://rtc-configuration.test/");
+ vm.eval(r#"globalThis.pc = new RTCPeerConnection({iceCandidatePoolSize:2});
+ globalThis.configResult = false;
+ pc.createOffer().then(offer => pc.setLocalDescription(offer)).then(() => {
+ const before=JSON.stringify(pc.getConfiguration());
+ pc.setConfiguration({iceCandidatePoolSize:2,iceTransportPolicy:'relay'});
+ try {pc.setConfiguration({iceCandidatePoolSize:3});}
+ catch (error) {configResult=error.name === 'InvalidModificationError' && pc.getConfiguration().iceCandidatePoolSize === 2 && before !== JSON.stringify(pc.getConfiguration());}
+ pc.close();
+ });"#).unwrap();
+ assert_eq!(vm.eval("configResult").unwrap(), "true");
+}
diff --git a/moli-renderer-v8/src/web_api_interfaces.rs b/moli-renderer-v8/src/web_api_interfaces.rs
index d7bfbb6a6..9ab6e495b 100644
--- a/moli-renderer-v8/src/web_api_interfaces.rs
+++ b/moli-renderer-v8/src/web_api_interfaces.rs
@@ -397,6 +397,7 @@ interfaces! {
PushSubscription;
PushSubscriptionOptions;
QuotaExceededError: DOMException;
+ RTCCertificate;
RTCDataChannel: EventTarget;
RTCError: DOMException;
RTCErrorEvent: Event;
diff --git a/moli-renderer-v8/tests/fixtures/rtc-configuration.js b/moli-renderer-v8/tests/fixtures/rtc-configuration.js
new file mode 100644
index 000000000..0513cb8a8
--- /dev/null
+++ b/moli-renderer-v8/tests/fixtures/rtc-configuration.js
@@ -0,0 +1,153 @@
+(() => {
+ const checks = [];
+ const assert = (value, message = 'assertion failed') => { if (!value) throw Error(message); };
+ const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key=>[key,canonical(value[key])])) : value;
+ const equal = (value, expected) => assert(JSON.stringify(canonical(value)) === JSON.stringify(canonical(expected)), JSON.stringify({value, expected}));
+ const run = (name, body) => {
+ try { body(); checks.push({name, passed: true}); }
+ catch (error) { checks.push({name, passed: false, error: String(error)}); }
+ };
+ const defaults = {bundlePolicy:'balanced', certificates:[], iceCandidatePoolSize:0, iceServers:[], iceTransportPolicy:'all', rtcpMuxPolicy:'require'};
+ for (const [label, realm] of [['main', globalThis], ['iframe', document.querySelector('iframe').contentWindow]]) {
+ const C = realm.RTCPeerConnection;
+ const check = (name, body) => run(label + ': ' + name, body);
+ const withPc = (config, body) => { const pc = new C(config); try { body(pc); } finally { pc.close(); } };
+ const throws = (name, body) => {
+ let error; try { body(); } catch (caught) { error = caught; }
+ assert(error?.name === name, 'expected ' + name + ', got ' + String(error));
+ assert(error instanceof realm[name === 'TypeError' ? 'TypeError' : 'DOMException'], 'callee error realm');
+ };
+ check('method descriptors', () => {
+ for (const name of ['getConfiguration','setConfiguration']) {
+ const d = Object.getOwnPropertyDescriptor(C.prototype, name);
+ assert(d && d.writable && d.enumerable && d.configurable && d.value.length === 0);
+ }
+ });
+ for (const [name, config] of [['omitted',undefined],['null',null],['empty',{}],['function',function(){}]]) {
+ check('default ' + name, () => withPc(config, pc => {
+ const c = pc.getConfiguration();
+ for (const key of Object.keys(defaults)) equal(c[key], defaults[key]);
+ }));
+ }
+ for (const value of [0, true, 'configuration', Symbol('x'), 1n]) {
+ check('reject dictionary primitive ' + String(value), () => throws('TypeError', () => new C(value)));
+ }
+ check('constructor snapshots nested records', () => {
+ const urls = ['stun:stun.example.org', 'turn:turn.example.org?transport=tcp'];
+ const server = {urls, username:'user', credential:'secret'};
+ const input = {iceServers:[server], iceTransportPolicy:'relay', ignored:123};
+ withPc(input, pc => {
+ input.iceTransportPolicy = 'all'; urls[0] = 'stun:changed.example'; server.username = 'changed'; input.iceServers.push({urls:'stun:extra.example'});
+ const first = pc.getConfiguration();
+ equal(first.iceTransportPolicy,'relay'); equal(first.iceServers,[{urls:['stun:stun.example.org','turn:turn.example.org?transport=tcp'],username:'user',credential:'secret'}]);
+ assert(!Object.hasOwn(first, 'ignored'));
+ first.iceServers[0].urls[0] = 'stun:mutated.example'; first.iceServers[0].credential = 'mutated'; first.certificates.push({}); first.iceTransportPolicy='all';
+ const second = pc.getConfiguration(); assert(first !== second && first.iceServers !== second.iceServers && first.iceServers[0] !== second.iceServers[0]);
+ equal(second.iceTransportPolicy,'relay'); equal(second.iceServers[0].urls[0],'stun:stun.example.org'); equal(second.iceServers[0].credential,'secret'); equal(second.certificates,[]);
+ });
+ });
+ check('conversion getters read once in lexical order', () => {
+ const seen = [];
+ const value = new Proxy({}, {get(target, key) { seen.push(key); return undefined; }});
+ withPc(value, () => equal(seen,['bundlePolicy','certificates','iceCandidatePoolSize','iceServers','iceTransportPolicy','rtcpMuxPolicy']));
+ });
+ check('nested dictionary lexical order and iterator single read', () => {
+ const seen = [];
+ const iterable = {get [Symbol.iterator]() {seen.push('iterator'); return function*() {seen.push('next'); yield {toString(){seen.push('string');return 'stun:host.example';}};seen.push('done');};}};
+ const server = {get credential(){seen.push('credential');return undefined;},get urls(){seen.push('urls');return iterable;},get username(){seen.push('username');return undefined;}};
+ withPc({iceServers:[server]}, pc => {equal(pc.getConfiguration().iceServers[0].urls,['stun:host.example']); equal(seen,['credential','urls','iterator','next','string','done','username']);});
+ });
+ check('noniterable URLs fall back to USVString', () => withPc({iceServers:[{urls:{toString(){return 'stun:host.example';},[Symbol.iterator]:null}}]}, pc => equal(pc.getConfiguration().iceServers[0].urls,['stun:host.example'])));
+ check('bad iterator propagates before toString', () => {
+ let converted=0;
+ throws('TypeError', () => new C({iceServers:[{urls:{[Symbol.iterator]:1,toString(){converted++;return 'stun:host.example';}}}]}));
+ equal(converted,0);
+ });
+ check('DOMStrings preserve lone surrogates', () => withPc({iceServers:[{urls:'stun:host.example', username:'\ud800',credential:'\udfff'}]}, pc => {
+ equal(pc.getConfiguration().iceServers[0].username,'\ud800');equal(pc.getConfiguration().iceServers[0].credential,'\udfff');
+ }));
+ for (const value of [-1,256,NaN,Infinity,-Infinity,Symbol('pool')]) {
+ check('range pool ' + String(value), () => throws('TypeError', () => new C({iceCandidatePoolSize:value})));
+ }
+ for (const value of [0,255,255.9,-0.9,'2',null]) {
+ check('converted pool ' + String(value), () => withPc({iceCandidatePoolSize:value}, pc => equal(pc.getConfiguration().iceCandidatePoolSize, Math.trunc(Number(value)) || 0)));
+ }
+ for (const field of ['bundlePolicy','iceTransportPolicy','rtcpMuxPolicy']) {
+ check('invalid enum ' + field, () => throws('TypeError', () => new C({[field]:null})));
+ check('undefined enum default ' + field, () => withPc({[field]:undefined}, pc => equal(pc.getConfiguration()[field],defaults[field])));
+ }
+ for (const [index,value] of [null,[null],[undefined],[{}]].entries()) {
+ check('invalid servers ' + index, () => throws('TypeError', () => new C({iceServers:value})));
+ }
+ for (const [index,value] of [null,[null],[{}],[new Proxy({}, {})]].entries()) {
+ check('invalid certificates ' + index, () => throws('TypeError', () => new C({certificates:value})));
+ }
+ const invalid = ['', 'relative', 'https://host.example', 'stun:', 'stun::8191', 'stun:host.example:65536','stun:0:1:2:3:4:5:6:7', 'stun://host.example', 'stun:host.example/path', 'stun:host.example\\path', 'stun:[email protected]', 'stun:host.example#fragment', 'stun:host.example?', 'stun:host.example?transport=udp', 'turn:host.example?invalid', 'turn:host.example?transport=', 'turn:host.example?transport=UDP', 'turn:host.example?transport=datachannel', 'turn:host.example?transport=tcp&extra=1', 'turn:host.example?transport=udp?transport=tcp', 'turn:host.example#', 'turn:[email protected]', 'turn:host.example/path'];
+ for (const url of invalid) check('invalid URL ' + JSON.stringify(url), () => throws('SyntaxError', () => new C({iceServers:[{urls:url}]})));
+ check('empty URLs invalid', () => throws('SyntaxError', () => new C({iceServers:[{urls:[]}]})));
+ for (const url of ['stun:host.example','stuns:host.example:5349','stun:192.0.2.1:3478','stun:[2001:db8::1]:3478','turn:host.example?transport=udp','turns:host.example?transport=tcp']) {
+ check('valid URL ' + url, () => withPc({iceServers:[{urls:url,username:'',credential:'secret'}]}, pc => equal(pc.getConfiguration().iceServers[0].urls,[url])));
+ }
+ for (const credentials of [{},{username:''},{credential:'secret'},{username:'user',credential:''},{username:'é'.repeat(255),credential:'secret'}]) {
+ check('TURN credentials ' + JSON.stringify(credentials), () => throws('InvalidAccessError', () => new C({iceServers:[{urls:'turn:host.example',...credentials}]})));
+ }
+ check('TURN username 509 UTF8 bytes', () => withPc({iceServers:[{urls:'turn:host.example',username:'é'.repeat(254)+'a',credential:'secret'}]}, () => {}));
+ check('stored records ignore prototype pollution', () => withPc({iceServers:[{urls:'stun:host.example'}]}, pc => {
+ const root=realm.Object.prototype, array=realm.Array.prototype;
+ const saved=Object.getOwnPropertyDescriptor(array,Symbol.iterator);
+ Object.defineProperty(root,'username',{get(){throw Error('stored record consulted prototype');},configurable:true});
+ Object.defineProperty(array,Symbol.iterator,{value(){throw Error('stored arrays consulted iterator');},configurable:true});
+ try {const c=pc.getConfiguration();assert(c.iceServers.length===1 && c.iceServers[0].urls[0]==='stun:host.example' && !Object.hasOwn(c.iceServers[0],'username'));}
+ finally {delete root.username;Object.defineProperty(array,Symbol.iterator,saved);}
+ }));
+ check('getter exception identity', () => {
+ const sentinel = {};
+ let caught;try {new C({get iceServers(){throw sentinel;}});} catch(error){caught=error;}
+ assert(caught===sentinel);
+ });
+ check('setter replacement, snapshot and clear', () => withPc({}, pc => {
+ const input = {iceServers:[{urls:'stun:host.example'}],iceTransportPolicy:'relay',iceCandidatePoolSize:2};
+ assert(pc.setConfiguration(input)===undefined);input.iceServers[0].urls='stun:changed.example';
+ equal(pc.getConfiguration().iceServers,[{urls:['stun:host.example']}]);
+ assert(pc.setConfiguration()===undefined);const config=pc.getConfiguration();for(const key of Object.keys(defaults))equal(config[key],defaults[key]);
+ }));
+ check('failed validation is atomic', () => withPc({iceTransportPolicy:'relay'}, pc => {
+ const before=pc.getConfiguration();throws('SyntaxError', () => pc.setConfiguration({iceTransportPolicy:'all',iceServers:[{urls:''}]}));equal(pc.getConfiguration(),before);
+ }));
+ check('immutable bundle before URL validation', () => withPc({bundlePolicy:'max-bundle'}, pc => {
+ throws('InvalidModificationError', () => pc.setConfiguration({bundlePolicy:'max-compat',iceServers:[{urls:''}]}));
+ equal(pc.getConfiguration().bundlePolicy,'max-bundle');
+ throws('InvalidModificationError', () => pc.setConfiguration());
+ }));
+ check('closed connection after conversion', () => withPc({}, pc => {
+ pc.close();const sentinel={};let caught;
+ try {pc.setConfiguration({get iceServers(){throw sentinel;}});}catch(error){caught=error;}assert(caught===sentinel);
+ throws('InvalidStateError',()=>pc.setConfiguration({iceServers:[{urls:''}]}));
+ equal(pc.getConfiguration().iceTransportPolicy,'all');
+ }));
+ check('getter reentrancy closes before native mutation', () => withPc({}, pc => {
+ throws('InvalidStateError',()=>pc.setConfiguration({get iceServers(){pc.close();return [];}}));
+ equal(pc.getConfiguration().iceServers,[]);
+ }));
+ check('callee snapshot realm', () => withPc({}, pc => {
+ const config=pc.getConfiguration();assert(Object.getPrototypeOf(config)===realm.Object.prototype && config.iceServers instanceof realm.Array && config.certificates instanceof realm.Array);
+ }));
+ check('cross-realm genuine receiver', () => withPc({}, pc => {
+ const other = realm===globalThis?document.querySelector('iframe').contentWindow:globalThis;
+ other.RTCPeerConnection.prototype.setConfiguration.call(pc,{iceTransportPolicy:'relay'});
+ const c=other.RTCPeerConnection.prototype.getConfiguration.call(pc);equal(c.iceTransportPolicy,'relay');assert(Object.getPrototypeOf(c)===other.Object.prototype);
+ }));
+ withPc({}, real => {
+ const revoked=Proxy.revocable(real,{});revoked.revoke();
+ let traps=0;
+ for (const [name,receiver] of [['empty',{}],['prototype',Object.create(C.prototype)],['inherited',Object.create(real)],['author proxy',new Proxy(real,{get(){traps++;return undefined;}})],['revoked',revoked.proxy]]) {
+ check('invalid receiver ' + name, () => {
+ throws('TypeError',()=>C.prototype.getConfiguration.call(receiver));
+ let converted=0;throws('TypeError',()=>C.prototype.setConfiguration.call(receiver,{get iceServers(){converted++;return [];}}));equal(converted,0);equal(traps,0);
+ });
+ }
+ });
+ }
+ globalThis.__uiEventResults={complete:true,total:checks.length,passed:checks.filter(c=>c.passed).length,checks};
+ return checks.every(c=>c.passed);
+})()