target.rs (28654B)
1 //! Extensible transport identities and canonical operation targets. 2 3 use crate::{ 4 Error as TransportError, TransportId, 5 endpoint::{ENDPOINT_URI_MAX_BYTES, TARGET_LABEL_MAX_BYTES, TARGET_SCOPE_MAX_BYTES}, 6 }; 7 use alloc::collections::BTreeSet; 8 use alloc::format; 9 use alloc::string::{String, ToString}; 10 use alloc::vec::Vec; 11 use core::net::{IpAddr, Ipv6Addr}; 12 use core::str::FromStr; 13 use sha2::{Digest, Sha256}; 14 15 /// Maximum number of targets in one operation. 16 pub const TARGET_SET_MAX_ITEMS: usize = 64; 17 18 /// Construction policy for canonical Nostr relay targets. 19 /// 20 /// This policy controls only whether a cleartext relay identifier may be 21 /// represented. A concrete adapter must independently retain and enforce its 22 /// network policy before and after address resolution. 23 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 24 #[non_exhaustive] 25 pub enum TargetNetworkPolicy { 26 /// TLS relay targets plus exact loopback cleartext targets. 27 TlsOrLoopback, 28 /// Exact RFC1918 IPv4 or ULA IPv6 device targets, with or without TLS. 29 PrivateDevice, 30 } 31 32 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 33 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 34 /// Canonical transport endpoint URI. 35 pub struct EndpointUri(String); 36 37 impl EndpointUri { 38 pub fn parse(raw: impl AsRef<str>) -> Result<Self, TransportError> { 39 let canonical = canonicalize_uri(raw.as_ref())?; 40 Ok(Self(canonical)) 41 } 42 43 fn parse_nostr_relay( 44 raw: impl AsRef<str>, 45 policy: TargetNetworkPolicy, 46 ) -> Result<Self, TransportError> { 47 let canonical = canonicalize_nostr_relay_uri(raw.as_ref(), policy)?; 48 Ok(Self(canonical)) 49 } 50 51 pub fn as_str(&self) -> &str { 52 &self.0 53 } 54 } 55 56 impl core::fmt::Display for EndpointUri { 57 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 58 f.write_str(&self.0) 59 } 60 } 61 62 impl AsRef<str> for EndpointUri { 63 fn as_ref(&self) -> &str { 64 self.as_str() 65 } 66 } 67 68 impl FromStr for EndpointUri { 69 type Err = TransportError; 70 71 fn from_str(value: &str) -> Result<Self, Self::Err> { 72 Self::parse(value) 73 } 74 } 75 76 impl TryFrom<&str> for EndpointUri { 77 type Error = TransportError; 78 79 fn try_from(value: &str) -> Result<Self, Self::Error> { 80 Self::parse(value) 81 } 82 } 83 84 #[cfg(feature = "serde")] 85 impl<'de> serde::Deserialize<'de> for EndpointUri { 86 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 87 where 88 D: serde::Deserializer<'de>, 89 { 90 let raw = <String as serde::Deserialize>::deserialize(deserializer)?; 91 let parsed = Self::parse(raw.as_str()).map_err(serde::de::Error::custom)?; 92 if parsed.as_str() != raw { 93 return Err(serde::de::Error::custom( 94 "transport target URI is not canonical", 95 )); 96 } 97 Ok(parsed) 98 } 99 } 100 101 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 102 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 103 /// Optional transport-neutral target scope. 104 pub struct TargetScope(String); 105 106 impl TargetScope { 107 pub fn parse(raw: impl AsRef<str>) -> Result<Self, TransportError> { 108 let value = raw.as_ref(); 109 if value.is_empty() { 110 return Err(TransportError::EmptyTargetScope); 111 } 112 if value.len() > TARGET_SCOPE_MAX_BYTES 113 || value != value.trim() 114 || value 115 .chars() 116 .any(|ch| !(ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | '.'))) 117 { 118 return Err(TransportError::InvalidTargetScope); 119 } 120 Ok(Self(value.to_string())) 121 } 122 123 pub fn as_str(&self) -> &str { 124 &self.0 125 } 126 } 127 128 impl core::fmt::Display for TargetScope { 129 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 130 f.write_str(&self.0) 131 } 132 } 133 134 impl AsRef<str> for TargetScope { 135 fn as_ref(&self) -> &str { 136 self.as_str() 137 } 138 } 139 140 impl FromStr for TargetScope { 141 type Err = TransportError; 142 143 fn from_str(value: &str) -> Result<Self, Self::Err> { 144 Self::parse(value) 145 } 146 } 147 148 impl TryFrom<&str> for TargetScope { 149 type Error = TransportError; 150 151 fn try_from(value: &str) -> Result<Self, Self::Error> { 152 Self::parse(value) 153 } 154 } 155 156 #[cfg(feature = "serde")] 157 impl<'de> serde::Deserialize<'de> for TargetScope { 158 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 159 where 160 D: serde::Deserializer<'de>, 161 { 162 let raw = <String as serde::Deserialize>::deserialize(deserializer)?; 163 Self::parse(raw).map_err(serde::de::Error::custom) 164 } 165 } 166 167 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 168 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 169 /// Optional human-readable target label excluded from target identity. 170 pub struct TargetLabel(String); 171 172 impl TargetLabel { 173 pub fn parse(raw: impl AsRef<str>) -> Result<Self, TransportError> { 174 let raw = raw.as_ref(); 175 let trimmed = raw.trim(); 176 if trimmed.is_empty() { 177 return Err(TransportError::EmptyTargetLabel); 178 } 179 if raw.len() > TARGET_LABEL_MAX_BYTES || trimmed.chars().any(char::is_control) { 180 return Err(TransportError::InvalidTargetLabel); 181 } 182 Ok(Self(trimmed.to_string())) 183 } 184 185 pub fn as_str(&self) -> &str { 186 &self.0 187 } 188 } 189 190 impl core::fmt::Display for TargetLabel { 191 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 192 f.write_str(&self.0) 193 } 194 } 195 196 impl AsRef<str> for TargetLabel { 197 fn as_ref(&self) -> &str { 198 self.as_str() 199 } 200 } 201 202 impl FromStr for TargetLabel { 203 type Err = TransportError; 204 205 fn from_str(value: &str) -> Result<Self, Self::Err> { 206 Self::parse(value) 207 } 208 } 209 210 impl TryFrom<&str> for TargetLabel { 211 type Error = TransportError; 212 213 fn try_from(value: &str) -> Result<Self, Self::Error> { 214 Self::parse(value) 215 } 216 } 217 218 #[cfg(feature = "serde")] 219 impl<'de> serde::Deserialize<'de> for TargetLabel { 220 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 221 where 222 D: serde::Deserializer<'de>, 223 { 224 let raw = <String as serde::Deserialize>::deserialize(deserializer)?; 225 let parsed = Self::parse(raw.as_str()).map_err(serde::de::Error::custom)?; 226 if parsed.as_str() != raw { 227 return Err(serde::de::Error::custom( 228 "transport target label is not canonical", 229 )); 230 } 231 Ok(parsed) 232 } 233 } 234 235 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 236 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 237 /// Deterministic SHA-256 fingerprint of canonical target identity fields. 238 pub struct TargetFingerprint(String); 239 240 impl TargetFingerprint { 241 pub fn from_target(kind: &TransportId, uri: &EndpointUri, scope: Option<&TargetScope>) -> Self { 242 let mut hasher = Sha256::new(); 243 hasher.update(kind.canonical_label().as_bytes()); 244 hasher.update([0]); 245 hasher.update(uri.as_str().as_bytes()); 246 if let Some(scope) = scope { 247 hasher.update([0]); 248 hasher.update(scope.as_str().as_bytes()); 249 } 250 let digest = hasher.finalize(); 251 Self(hex_encode(&digest)) 252 } 253 254 pub fn parse(raw: impl AsRef<str>) -> Result<Self, TransportError> { 255 let raw = raw.as_ref(); 256 if raw.len() != 64 || !raw.bytes().all(|byte| byte.is_ascii_hexdigit()) { 257 return Err(TransportError::InvalidTargetFingerprint); 258 } 259 Ok(Self(raw.to_ascii_lowercase())) 260 } 261 262 pub fn as_str(&self) -> &str { 263 &self.0 264 } 265 } 266 267 fn hex_encode(bytes: &[u8]) -> String { 268 const HEX: &[u8; 16] = b"0123456789abcdef"; 269 let mut out = String::with_capacity(bytes.len() * 2); 270 for byte in bytes { 271 out.push(HEX[(byte >> 4) as usize] as char); 272 out.push(HEX[(byte & 0x0f) as usize] as char); 273 } 274 out 275 } 276 277 impl core::fmt::Display for TargetFingerprint { 278 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 279 f.write_str(&self.0) 280 } 281 } 282 283 impl AsRef<str> for TargetFingerprint { 284 fn as_ref(&self) -> &str { 285 self.as_str() 286 } 287 } 288 289 impl FromStr for TargetFingerprint { 290 type Err = TransportError; 291 292 fn from_str(value: &str) -> Result<Self, Self::Err> { 293 Self::parse(value) 294 } 295 } 296 297 impl TryFrom<&str> for TargetFingerprint { 298 type Error = TransportError; 299 300 fn try_from(value: &str) -> Result<Self, Self::Error> { 301 Self::parse(value) 302 } 303 } 304 305 #[cfg(feature = "serde")] 306 impl<'de> serde::Deserialize<'de> for TargetFingerprint { 307 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 308 where 309 D: serde::Deserializer<'de>, 310 { 311 let raw = <String as serde::Deserialize>::deserialize(deserializer)?; 312 let parsed = Self::parse(raw.as_str()).map_err(serde::de::Error::custom)?; 313 if parsed.as_str() != raw { 314 return Err(serde::de::Error::custom( 315 "transport target fingerprint is not canonical", 316 )); 317 } 318 Ok(parsed) 319 } 320 } 321 322 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 323 #[derive(Clone, Debug, PartialEq, Eq)] 324 /// Validated transport-neutral target. 325 pub struct Target { 326 kind: TransportId, 327 uri: EndpointUri, 328 scope: Option<TargetScope>, 329 label: Option<TargetLabel>, 330 fingerprint: TargetFingerprint, 331 #[cfg_attr( 332 feature = "serde", 333 serde(skip_serializing_if = "private_device_cleartext_is_false") 334 )] 335 private_device_cleartext: bool, 336 } 337 338 impl Target { 339 pub fn new(kind: TransportId, uri: impl AsRef<str>) -> Result<Self, TransportError> { 340 Self::new_with_metadata(kind, uri, None, None) 341 } 342 343 pub fn nostr_relay(uri: impl AsRef<str>) -> Result<Self, TransportError> { 344 Self::nostr_relay_with_metadata(uri, None, None) 345 } 346 347 /// Creates a Nostr relay target under an explicit construction policy. 348 /// 349 /// The private-device policy accepts only literal RFC1918 IPv4 or ULA IPv6 350 /// destinations. Named, public, loopback, link-local, unspecified, and 351 /// multicast destinations remain denied. 352 pub fn nostr_relay_with_policy( 353 uri: impl AsRef<str>, 354 policy: TargetNetworkPolicy, 355 ) -> Result<Self, TransportError> { 356 Self::new_with_metadata_and_nostr_policy(uri, None, None, policy) 357 } 358 359 pub fn nostr_relay_with_metadata( 360 uri: impl AsRef<str>, 361 scope: Option<TargetScope>, 362 label: Option<TargetLabel>, 363 ) -> Result<Self, TransportError> { 364 Self::new_with_metadata_and_nostr_policy( 365 uri, 366 scope, 367 label, 368 TargetNetworkPolicy::TlsOrLoopback, 369 ) 370 } 371 372 pub fn local(uri: impl AsRef<str>) -> Result<Self, TransportError> { 373 Self::local_with_metadata(uri, None, None) 374 } 375 376 pub fn local_with_metadata( 377 uri: impl AsRef<str>, 378 scope: Option<TargetScope>, 379 label: Option<TargetLabel>, 380 ) -> Result<Self, TransportError> { 381 Self::new_with_metadata(TransportId::LOCAL, uri, scope, label) 382 } 383 384 pub fn new_with_metadata( 385 kind: TransportId, 386 uri: impl AsRef<str>, 387 scope: Option<TargetScope>, 388 label: Option<TargetLabel>, 389 ) -> Result<Self, TransportError> { 390 if kind == TransportId::NOSTR { 391 return Self::new_with_metadata_and_nostr_policy( 392 uri, 393 scope, 394 label, 395 TargetNetworkPolicy::TlsOrLoopback, 396 ); 397 } 398 let uri = EndpointUri::parse(uri)?; 399 let fingerprint = TargetFingerprint::from_target(&kind, &uri, scope.as_ref()); 400 Ok(Self { 401 kind, 402 uri, 403 scope, 404 label, 405 fingerprint, 406 private_device_cleartext: false, 407 }) 408 } 409 410 fn new_with_metadata_and_nostr_policy( 411 uri: impl AsRef<str>, 412 scope: Option<TargetScope>, 413 label: Option<TargetLabel>, 414 policy: TargetNetworkPolicy, 415 ) -> Result<Self, TransportError> { 416 let uri = EndpointUri::parse_nostr_relay(uri, policy)?; 417 let fingerprint = TargetFingerprint::from_target(&TransportId::NOSTR, &uri, scope.as_ref()); 418 Ok(Self { 419 kind: TransportId::NOSTR, 420 private_device_cleartext: policy == TargetNetworkPolicy::PrivateDevice 421 && uri.as_str().starts_with("ws://"), 422 uri, 423 scope, 424 label, 425 fingerprint, 426 }) 427 } 428 429 pub fn kind(&self) -> &TransportId { 430 &self.kind 431 } 432 433 pub fn uri(&self) -> &EndpointUri { 434 &self.uri 435 } 436 437 /// Compares a captured Nostr relay identifier using this target's original 438 /// construction policy and canonical endpoint rules. Scope and labels are 439 /// separate. Matching supplies no route approval or network permission. 440 pub fn matches_nostr_relay(&self, raw: &str) -> Result<bool, TransportError> { 441 if self.kind != TransportId::NOSTR { 442 return Ok(false); 443 } 444 let policy = if self.private_device_cleartext { 445 TargetNetworkPolicy::PrivateDevice 446 } else { 447 TargetNetworkPolicy::TlsOrLoopback 448 }; 449 Ok(EndpointUri::parse_nostr_relay(raw, policy)? == self.uri) 450 } 451 452 pub fn scope(&self) -> Option<&TargetScope> { 453 self.scope.as_ref() 454 } 455 456 pub fn label(&self) -> Option<&TargetLabel> { 457 self.label.as_ref() 458 } 459 460 pub fn fingerprint(&self) -> &TargetFingerprint { 461 &self.fingerprint 462 } 463 } 464 465 #[cfg(feature = "serde")] 466 #[derive(serde::Deserialize)] 467 #[serde(deny_unknown_fields)] 468 struct TargetWire { 469 kind: TransportId, 470 uri: String, 471 scope: Option<String>, 472 label: Option<String>, 473 fingerprint: String, 474 private_device_cleartext: Option<bool>, 475 } 476 477 #[cfg(feature = "serde")] 478 impl<'de> serde::Deserialize<'de> for Target { 479 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 480 where 481 D: serde::Deserializer<'de>, 482 { 483 let wire = TargetWire::deserialize(deserializer)?; 484 let scope = wire 485 .scope 486 .map(TargetScope::parse) 487 .transpose() 488 .map_err(serde::de::Error::custom)?; 489 let label = wire 490 .label 491 .map(|label| { 492 let parsed = TargetLabel::parse(label.as_str())?; 493 if parsed.as_str() != label { 494 return Err(TransportError::InvalidTargetLabel); 495 } 496 Ok(parsed) 497 }) 498 .transpose() 499 .map_err(serde::de::Error::custom)?; 500 let fingerprint = TargetFingerprint::parse(wire.fingerprint.as_str()) 501 .map_err(serde::de::Error::custom)?; 502 if fingerprint.as_str() != wire.fingerprint { 503 return Err(serde::de::Error::custom( 504 "transport target fingerprint is not canonical", 505 )); 506 } 507 if wire.private_device_cleartext == Some(false) { 508 return Err(serde::de::Error::custom( 509 "transport target private-device marker is not canonical", 510 )); 511 } 512 let target = 513 if wire.kind == TransportId::NOSTR && wire.private_device_cleartext == Some(true) { 514 Self::new_with_metadata_and_nostr_policy( 515 wire.uri.as_str(), 516 scope.clone(), 517 label.clone(), 518 TargetNetworkPolicy::PrivateDevice, 519 ) 520 } else { 521 Self::new_with_metadata(wire.kind, wire.uri.as_str(), scope.clone(), label.clone()) 522 } 523 .map_err(serde::de::Error::custom)?; 524 if target.uri.as_str() != wire.uri 525 || target.scope != scope 526 || target.label != label 527 || target.fingerprint != fingerprint 528 { 529 return Err(serde::de::Error::custom( 530 "transport target identity does not match its canonical fields", 531 )); 532 } 533 Ok(target) 534 } 535 } 536 537 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 538 #[derive(Clone, Debug, PartialEq, Eq)] 539 /// Bounded non-empty set of targets with unique fingerprints. 540 pub struct TargetSet { 541 targets: Vec<Target>, 542 } 543 544 impl TargetSet { 545 pub fn new(targets: Vec<Target>) -> Result<Self, TransportError> { 546 if targets.is_empty() { 547 return Err(TransportError::EmptyTargetSet); 548 } 549 if targets.len() > TARGET_SET_MAX_ITEMS { 550 return Err(TransportError::TargetSetTooLarge); 551 } 552 let mut fingerprints = BTreeSet::new(); 553 for target in &targets { 554 if !fingerprints.insert(target.fingerprint.as_str().to_string()) { 555 return Err(TransportError::DuplicateTargetFingerprint); 556 } 557 } 558 Ok(Self { targets }) 559 } 560 561 pub fn targets(&self) -> &[Target] { 562 &self.targets 563 } 564 565 /// Returns whether this set contains the exact target fingerprint. 566 pub fn contains(&self, fingerprint: &TargetFingerprint) -> bool { 567 self.targets 568 .iter() 569 .any(|target| target.fingerprint() == fingerprint) 570 } 571 572 pub fn len(&self) -> usize { 573 self.targets.len() 574 } 575 576 pub fn is_empty(&self) -> bool { 577 self.targets.is_empty() 578 } 579 } 580 581 #[cfg(feature = "serde")] 582 #[derive(serde::Deserialize)] 583 #[serde(deny_unknown_fields)] 584 struct TargetSetWire { 585 targets: Vec<Target>, 586 } 587 588 #[cfg(feature = "serde")] 589 impl<'de> serde::Deserialize<'de> for TargetSet { 590 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 591 where 592 D: serde::Deserializer<'de>, 593 { 594 let wire = TargetSetWire::deserialize(deserializer)?; 595 Self::new(wire.targets).map_err(serde::de::Error::custom) 596 } 597 } 598 599 fn canonicalize_uri(raw: &str) -> Result<String, TransportError> { 600 let trimmed = raw.trim(); 601 if trimmed.is_empty() { 602 return Err(TransportError::EmptyTargetUri); 603 } 604 if raw != trimmed { 605 return Err(TransportError::InvalidTargetUri); 606 } 607 if trimmed.len() > ENDPOINT_URI_MAX_BYTES { 608 return Err(TransportError::InvalidTargetUri); 609 } 610 if trimmed 611 .chars() 612 .any(|ch| ch.is_ascii_control() || ch.is_ascii_whitespace()) 613 { 614 return Err(TransportError::InvalidTargetUri); 615 } 616 if let Some(colon) = trimmed.find(':') { 617 let scheme = &trimmed[..colon]; 618 if !is_valid_scheme(scheme) { 619 return Err(TransportError::InvalidTargetUri); 620 } 621 let rest = &trimmed[colon + 1..]; 622 if let Some(authority_rest) = rest.strip_prefix("//") { 623 let authority_end = authority_rest 624 .find(['/', '?', '#']) 625 .unwrap_or(authority_rest.len()); 626 let authority = &authority_rest[..authority_end]; 627 let suffix = &authority_rest[authority_end..]; 628 return Ok(format!( 629 "{}://{}{}", 630 scheme.to_ascii_lowercase(), 631 authority.to_ascii_lowercase(), 632 suffix 633 )); 634 } 635 return Ok(format!("{}:{rest}", scheme.to_ascii_lowercase())); 636 } 637 Ok(trimmed.to_string()) 638 } 639 640 fn is_valid_scheme(value: &str) -> bool { 641 let mut chars = value.chars(); 642 matches!(chars.next(), Some(first) if first.is_ascii_alphabetic()) 643 && chars.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '+' | '-' | '.')) 644 } 645 646 fn canonicalize_nostr_relay_uri( 647 raw: &str, 648 policy: TargetNetworkPolicy, 649 ) -> Result<String, TransportError> { 650 let trimmed = raw.trim(); 651 if trimmed.is_empty() { 652 return Err(TransportError::EmptyTargetUri); 653 } 654 if raw != trimmed { 655 return Err(TransportError::InvalidTargetUri); 656 } 657 if trimmed.len() > ENDPOINT_URI_MAX_BYTES { 658 return Err(TransportError::InvalidTargetUri); 659 } 660 if trimmed 661 .chars() 662 .any(|ch| ch.is_ascii_control() || ch.is_ascii_whitespace()) 663 { 664 return Err(TransportError::InvalidTargetUri); 665 } 666 if trimmed.contains('?') || trimmed.contains('#') || trimmed.contains('\\') { 667 return Err(TransportError::InvalidTargetUri); 668 } 669 let Some(scheme_end) = trimmed.find("://") else { 670 return Err(TransportError::InvalidTargetUri); 671 }; 672 let scheme = trimmed[..scheme_end].to_ascii_lowercase(); 673 if !matches!(scheme.as_str(), "wss" | "ws") { 674 return Err(TransportError::InvalidTargetUri); 675 } 676 let endpoint = &trimmed[scheme_end + 3..]; 677 let authority_end = endpoint.find('/').unwrap_or(endpoint.len()); 678 let authority = &endpoint[..authority_end]; 679 let path = &endpoint[authority_end..]; 680 let authority = canonicalize_nostr_relay_authority(authority, scheme.as_str(), policy)?; 681 validate_nostr_relay_path(path)?; 682 if path == "/" { 683 return Ok(format!("{scheme}://{authority}")); 684 } 685 Ok(format!("{scheme}://{authority}{path}")) 686 } 687 688 fn canonicalize_nostr_relay_authority( 689 authority: &str, 690 scheme: &str, 691 policy: TargetNetworkPolicy, 692 ) -> Result<String, TransportError> { 693 if authority.is_empty() || authority.contains('@') { 694 return Err(TransportError::InvalidTargetUri); 695 } 696 let (host, port) = if let Some(rest) = authority.strip_prefix('[') { 697 let Some(host_end) = rest.find(']') else { 698 return Err(TransportError::InvalidTargetUri); 699 }; 700 let host = &rest[..host_end]; 701 let suffix = &rest[host_end + 1..]; 702 if host.is_empty() 703 || host 704 .chars() 705 .any(|ch| matches!(ch, '[' | ']' | '/' | '?' | '#' | '@' | '\\')) 706 { 707 return Err(TransportError::InvalidTargetUri); 708 } 709 let canonical_host = canonicalize_nostr_relay_ipv6(host)?; 710 ( 711 format!("[{canonical_host}]"), 712 parse_nostr_relay_port(suffix)?, 713 ) 714 } else { 715 if authority.contains(['[', ']', '\\']) { 716 return Err(TransportError::InvalidTargetUri); 717 } 718 let mut parts = authority.splitn(2, ':'); 719 let host = parts.next().unwrap_or_default(); 720 let port = parts 721 .next() 722 .map(parse_nostr_relay_port_with_prefix) 723 .transpose()?; 724 (canonicalize_nostr_relay_host(host)?, port) 725 }; 726 match policy { 727 TargetNetworkPolicy::TlsOrLoopback => { 728 if scheme == "ws" && !is_local_ws_relay_host(host.as_str()) { 729 return Err(TransportError::InvalidTargetUri); 730 } 731 } 732 TargetNetworkPolicy::PrivateDevice => { 733 if !is_private_device_relay_host(host.as_str()) { 734 return Err(TransportError::InvalidTargetUri); 735 } 736 } 737 } 738 let port = 739 port.filter(|port| !matches!((scheme, port.as_str()), ("wss", "443") | ("ws", "80"))); 740 Ok(match port { 741 Some(port) => format!("{host}:{port}"), 742 None => host, 743 }) 744 } 745 746 fn parse_nostr_relay_port(suffix: &str) -> Result<Option<String>, TransportError> { 747 if suffix.is_empty() { 748 return Ok(None); 749 } 750 let Some(port) = suffix.strip_prefix(':') else { 751 return Err(TransportError::InvalidTargetUri); 752 }; 753 parse_nostr_relay_port_with_prefix(port).map(Some) 754 } 755 756 fn parse_nostr_relay_port_with_prefix(port: &str) -> Result<String, TransportError> { 757 if port.is_empty() 758 || !port.bytes().all(|byte| byte.is_ascii_digit()) 759 || port.len() > 1 && port.starts_with('0') 760 { 761 return Err(TransportError::InvalidTargetUri); 762 } 763 let value = port 764 .parse::<u32>() 765 .map_err(|_| TransportError::InvalidTargetUri)?; 766 if !(1..=u16::MAX as u32).contains(&value) { 767 return Err(TransportError::InvalidTargetUri); 768 } 769 Ok(port.to_string()) 770 } 771 772 fn canonicalize_nostr_relay_host(host: &str) -> Result<String, TransportError> { 773 let canonical = host.to_ascii_lowercase(); 774 if canonical_ipv4(canonical.as_str()) || canonical_dns_host(canonical.as_str()) { 775 return Ok(canonical); 776 } 777 Err(TransportError::InvalidTargetUri) 778 } 779 780 fn canonicalize_nostr_relay_ipv6(host: &str) -> Result<String, TransportError> { 781 if host.is_empty() 782 || !host 783 .bytes() 784 .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f' | b'A'..=b'F' | b':')) 785 { 786 return Err(TransportError::InvalidTargetUri); 787 } 788 host.parse::<Ipv6Addr>() 789 .map(|address| address.to_string()) 790 .map_err(|_| TransportError::InvalidTargetUri) 791 } 792 793 fn canonical_ipv4(value: &str) -> bool { 794 let mut count = 0usize; 795 for part in value.split('.') { 796 if part.is_empty() 797 || !part.bytes().all(|byte| byte.is_ascii_digit()) 798 || part.len() > 1 && part.starts_with('0') 799 || part.parse::<u8>().is_err() 800 { 801 return false; 802 } 803 count += 1; 804 } 805 count == 4 806 } 807 808 fn canonical_dns_host(value: &str) -> bool { 809 if value.is_empty() || value.len() > 253 { 810 return false; 811 } 812 let mut final_label = ""; 813 for label in value.split('.') { 814 if label.is_empty() 815 || label.len() > 63 816 || label.starts_with("xn--") 817 || !label 818 .bytes() 819 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') 820 || !label 821 .as_bytes() 822 .first() 823 .is_some_and(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit()) 824 || !label 825 .as_bytes() 826 .last() 827 .is_some_and(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit()) 828 { 829 return false; 830 } 831 final_label = label; 832 } 833 !dns_label_is_whatwg_number(final_label) 834 } 835 836 fn dns_label_is_whatwg_number(value: &str) -> bool { 837 value.bytes().all(|byte| byte.is_ascii_digit()) 838 || value 839 .strip_prefix("0x") 840 .is_some_and(|digits| digits.bytes().all(|byte| byte.is_ascii_hexdigit())) 841 } 842 843 fn validate_nostr_relay_path(path: &str) -> Result<(), TransportError> { 844 if path.is_empty() || path == "/" { 845 return Ok(()); 846 } 847 let Some(component) = path.strip_prefix('/') else { 848 return Err(TransportError::InvalidTargetUri); 849 }; 850 if relay_path_component_is_valid(component) { 851 Ok(()) 852 } else { 853 Err(TransportError::InvalidTargetUri) 854 } 855 } 856 857 fn relay_path_component_is_valid(value: &str) -> bool { 858 if value.split('/').any(relay_path_segment_is_dot) { 859 return false; 860 } 861 let bytes = value.as_bytes(); 862 let mut index = 0usize; 863 while index < bytes.len() { 864 if bytes[index] == b'%' { 865 if index + 2 >= bytes.len() 866 || !upper_hex_digit(bytes[index + 1]) 867 || !upper_hex_digit(bytes[index + 2]) 868 { 869 return false; 870 } 871 index += 3; 872 continue; 873 } 874 if !relay_path_character(bytes[index]) { 875 return false; 876 } 877 index += 1; 878 } 879 true 880 } 881 882 fn relay_path_segment_is_dot(segment: &str) -> bool { 883 let bytes = segment.as_bytes(); 884 let mut index = 0usize; 885 let mut dots = 0usize; 886 while index < bytes.len() { 887 if bytes[index] == b'.' { 888 dots += 1; 889 index += 1; 890 } else if bytes[index..].starts_with(b"%2E") { 891 dots += 1; 892 index += 3; 893 } else { 894 return false; 895 } 896 } 897 matches!(dots, 1 | 2) 898 } 899 900 fn relay_path_character(byte: u8) -> bool { 901 byte.is_ascii_alphanumeric() 902 || matches!( 903 byte, 904 b'-' | b'.' 905 | b'_' 906 | b'~' 907 | b'!' 908 | b'$' 909 | b'&' 910 | b'\'' 911 | b'(' 912 | b')' 913 | b'*' 914 | b'+' 915 | b',' 916 | b';' 917 | b'=' 918 | b':' 919 | b'@' 920 | b'/' 921 ) 922 } 923 924 fn upper_hex_digit(byte: u8) -> bool { 925 byte.is_ascii_digit() || matches!(byte, b'A'..=b'F') 926 } 927 928 fn is_local_ws_relay_host(host: &str) -> bool { 929 matches!(host, "localhost" | "127.0.0.1" | "[::1]") 930 } 931 932 fn is_private_device_relay_host(host: &str) -> bool { 933 match host.trim_matches(['[', ']']).parse::<IpAddr>() { 934 Ok(IpAddr::V4(address)) => address.is_private(), 935 Ok(IpAddr::V6(address)) => address.segments()[0] & 0xfe00 == 0xfc00, 936 Err(_) => false, 937 } 938 } 939 940 #[cfg(feature = "serde")] 941 const fn private_device_cleartext_is_false(value: &bool) -> bool { 942 !*value 943 }