connector.rs (6067B)
1 use radroots_transport::host::websocket::{Admission, Connector, Error, IoFuture, Socket}; 2 use std::{net::IpAddr, num::NonZeroUsize, sync::Arc, time::Duration}; 3 4 /// Inert provider whose DOM socket and callbacks stay on their origin thread. 5 #[derive(Clone, Default)] 6 pub struct BrowserConnector { 7 #[cfg(any(target_arch = "wasm32", test))] 8 scope: Arc<crate::scope::Scope>, 9 } 10 11 impl std::fmt::Debug for BrowserConnector { 12 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 13 formatter.write_str("BrowserConnector([owned])") 14 } 15 } 16 17 impl BrowserConnector { 18 /// Permanently refuses new socket owners and waits for local callback 19 /// disposal on every original socket in this scope. Does not join upstream 20 /// SDK tasks or prove a remote close handshake. Resume after cancellation. 21 /// An unpolled future has no effect. Clones share this same close boundary. 22 pub fn close(&self) -> IoFuture<'_, Result<(), Error>> { 23 Box::pin(async move { 24 #[cfg(any(target_arch = "wasm32", test))] 25 { 26 self.scope.close().await 27 } 28 #[cfg(not(any(target_arch = "wasm32", test)))] 29 { 30 Ok(()) 31 } 32 }) 33 } 34 } 35 36 impl Connector for BrowserConnector { 37 fn supports_ping(&self) -> bool { 38 false 39 } 40 41 fn connect<'a>( 42 &'a self, 43 endpoint: &'a str, 44 timeout: Duration, 45 max_message_bytes: NonZeroUsize, 46 admission: Arc<dyn Admission>, 47 ) -> IoFuture<'a, Result<Arc<dyn Socket>, Error>> { 48 Box::pin(async move { 49 validate_endpoint(endpoint, admission.as_ref())?; 50 if timeout.is_zero() { 51 return Err(Error::Timeout); 52 } 53 #[cfg(target_arch = "wasm32")] 54 { 55 crate::browser::connect( 56 endpoint, 57 timeout, 58 max_message_bytes, 59 admission, 60 &self.scope, 61 ) 62 .await 63 } 64 #[cfg(not(target_arch = "wasm32"))] 65 { 66 let _ = max_message_bytes; 67 Err(Error::Unsupported) 68 } 69 }) 70 } 71 } 72 73 fn validate_endpoint(endpoint: &str, admission: &dyn Admission) -> Result<(), Error> { 74 let url = url::Url::parse(endpoint).map_err(|_| Error::Policy)?; 75 if !matches!(url.scheme(), "ws" | "wss") 76 || !url.username().is_empty() 77 || url.password().is_some() 78 || url.fragment().is_some() 79 { 80 return Err(Error::Policy); 81 } 82 let host = url 83 .host_str() 84 .ok_or(Error::Policy)? 85 .trim_matches(['[', ']']); 86 if let Ok(address) = host.parse::<IpAddr>() 87 && !admission.permits_address(address) 88 { 89 return Err(Error::Policy); 90 } 91 Ok(()) 92 } 93 94 #[cfg(test)] 95 mod tests { 96 use super::*; 97 use crate::state::tests::AdmissionCounter as Grant; 98 #[test] 99 fn endpoint_validation_is_explicit_and_never_resolves_dns() { 100 for endpoint in [ 101 "invalid", 102 "https://example.org", 103 "ws://a:b@example.org", 104 "wss://example.org/#fragment", 105 ] { 106 assert_eq!( 107 validate_endpoint(endpoint, Grant::new(true).as_ref()), 108 Err(Error::Policy) 109 ); 110 } 111 for endpoint in ["ws://127.0.0.1", "wss://[::1]"] { 112 assert_eq!( 113 validate_endpoint(endpoint, Grant::new(false).as_ref()), 114 Err(Error::Policy) 115 ); 116 assert_eq!( 117 validate_endpoint(endpoint, Grant::new(true).as_ref()), 118 Ok(()) 119 ); 120 } 121 assert_eq!( 122 validate_endpoint("wss://relay.example/path?q=1", Grant::new(false).as_ref()), 123 Ok(()) 124 ); 125 } 126 #[test] 127 fn non_browser_connection_refuses_and_zero_deadline_does_not_start_io() { 128 let connector = BrowserConnector::default(); 129 assert!(!connector.supports_ping()); 130 for (endpoint, duration, error) in [ 131 ("ws://127.0.0.1", Duration::from_secs(1), Error::Unsupported), 132 ("wss://example.org", Duration::ZERO, Error::Timeout), 133 ("invalid", Duration::from_secs(1), Error::Policy), 134 ] { 135 let result = futures::executor::block_on(connector.connect( 136 endpoint, 137 duration, 138 NonZeroUsize::new(1).unwrap(), 139 Grant::new(true), 140 )); 141 assert!(matches!(result, Err(found) if found == error)); 142 } 143 } 144 145 #[test] 146 fn factory_constructs_the_shared_session_without_host_effects() { 147 use radroots_transport_nostr::{ 148 Config, RelayAccess, RelayEndpoint, RelayProfile, RelayProfileKind, RelayUrlPolicy, 149 }; 150 let endpoint = RelayEndpoint::new( 151 "wss://relay.example", 152 RelayUrlPolicy::Public, 153 RelayAccess::ReadWrite, 154 ) 155 .unwrap(); 156 let profile = RelayProfile::explicit(RelayProfileKind::Public, [endpoint]).unwrap(); 157 let _transport = crate::create_transport(Config::from_profile(profile)); 158 } 159 160 #[test] 161 fn clones_share_disposal_and_diagnostics_never_expose_buffered_peer_data() { 162 use crate::state::{Shared, Status}; 163 let connector = BrowserConnector::default(); 164 let socket = Arc::new(Shared::new(Grant::new(true), 64)); 165 socket.lock().unwrap().status = Status::Open; 166 socket 167 .push(radroots_transport::host::websocket::Frame::Text( 168 "private buffered peer content".into(), 169 )) 170 .unwrap(); 171 connector.scope.register(&socket).unwrap(); 172 assert!(!format!("{connector:?}").contains("private buffered peer content")); 173 let clone = connector.clone(); 174 socket.finish(); 175 futures::executor::block_on(clone.close()).unwrap(); 176 assert_eq!(connector.scope.register(&socket), Err(Error::Closed)); 177 } 178 }