1pub mod lan;
9pub mod pairing;
10pub mod session_init;
11
12use alloc::string::{String, ToString};
13use alloc::vec::Vec;
14
15use base64::Engine as _;
16use serde::{Deserialize, Serialize};
17use zeroize::{Zeroize, ZeroizeOnDrop};
18
19use crate::types::Duration;
20
21pub use lan::{
22 CancelPreparePairing, LONG_POLL_HOLD, LONG_POLL_TIMEOUT, NodeListing, PreparePairing,
23 PrepareRefused, WaitAction, WaitErrorMessage, WaitForPairing, WaitInstruction,
24};
25pub use pairing::{
26 ConnectionDetails, ConnectionDetailsPost, ConnectionDetailsRequest, FinalizePairing,
27 MINIMUM_SERVER_DELAY, NextStep, PAIRING_BUDGET, Pairing, PairingAccepted, PairingAttemptId,
28 PairingClient, PairingErrorMessage, PairingRefused, PairingRequest, PairingServer, PairingStep,
29};
30pub use session_init::{
31 COMMUNICATION_TOKEN_LIFETIME, CommunicationDetails, SessionCredentials, SessionErrorMessage,
32 SessionGrant, SessionInitClient, SessionInitServer, SessionRefused, SessionRequest, TokenStore,
33 UnpairRequest,
34};
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
41#[serde(rename_all = "UPPERCASE")]
42pub enum Role {
43 Cem,
45 Rm,
47}
48
49impl Role {
50 #[must_use]
52 pub const fn service_subtype(self) -> &'static str {
53 match self {
54 Role::Cem => "_cem",
55 Role::Rm => "_rm",
56 }
57 }
58
59 #[must_use]
62 pub const fn can_pair_with(self, other: Self) -> bool {
63 !matches!((self, other), (Role::Cem, Role::Cem) | (Role::Rm, Role::Rm))
64 }
65
66 #[must_use]
68 pub const fn other(self) -> Self {
69 match self {
70 Role::Cem => Role::Rm,
71 Role::Rm => Role::Cem,
72 }
73 }
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
78#[serde(rename_all = "UPPERCASE")]
79pub enum Deployment {
80 Wan,
82 Lan,
84}
85
86impl Deployment {
87 #[must_use]
93 pub const fn communication_server(cem: Self, rm: Self) -> Role {
94 match (cem, rm) {
95 (Deployment::Lan, Deployment::Wan) => Role::Rm,
96 _ => Role::Cem,
97 }
98 }
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
111#[serde(transparent)]
112pub struct NodeId(pub crate::types::Id);
113
114impl NodeId {
115 #[cfg(feature = "uuid")]
117 #[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
118 #[must_use]
119 pub fn generate() -> Self {
120 Self(crate::types::Id::generate())
121 }
122
123 pub fn parse(s: &str) -> Result<Self, ConnectError> {
125 crate::types::Id::parse(s)
126 .map(Self)
127 .map_err(|_| ConnectError::MalformedNodeId)
128 }
129}
130
131impl core::fmt::Display for NodeId {
132 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
133 self.0.fmt(f)
134 }
135}
136
137#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
147#[serde(transparent)]
148pub struct NodeIdAlias(pub String);
149
150impl NodeIdAlias {
151 pub const MAX_LEN: usize = 64;
158
159 pub fn parse(s: &str) -> Result<Self, ConnectError> {
161 if s.is_empty() || s.len() > Self::MAX_LEN || !s.bytes().all(|b| b.is_ascii_alphanumeric())
162 {
163 return Err(ConnectError::MalformedPairingCode);
164 }
165 Ok(Self(s.to_string()))
166 }
167}
168
169impl<'de> Deserialize<'de> for NodeIdAlias {
170 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
171 let raw = <&str as Deserialize>::deserialize(deserializer)?;
172 Self::parse(raw).map_err(serde::de::Error::custom)
173 }
174}
175
176#[derive(Clone, Zeroize, ZeroizeOnDrop)]
181pub struct PairingToken(Vec<u8>);
182
183impl PartialEq for PairingToken {
186 fn eq(&self, other: &Self) -> bool {
187 use subtle::ConstantTimeEq as _;
188 self.0.ct_eq(&other.0).into()
189 }
190}
191
192impl Eq for PairingToken {}
193
194impl PairingToken {
195 pub const MIN_DYNAMIC: usize = 4;
197 pub const MIN_STATIC: usize = 6;
199 pub const MAX_LEN: usize = 256;
205
206 pub fn parse(s: &str, kind: TokenKind) -> Result<Self, ConnectError> {
208 let minimum = match kind {
209 TokenKind::Dynamic => Self::MIN_DYNAMIC,
210 TokenKind::Static => Self::MIN_STATIC,
211 };
212 if s.len() < minimum
213 || s.len() > Self::MAX_LEN
214 || !s.bytes().all(|b| b.is_ascii_alphanumeric())
215 {
216 return Err(ConnectError::MalformedPairingCode);
217 }
218 Ok(Self(s.as_bytes().to_vec()))
219 }
220
221 #[must_use]
225 pub fn as_bytes(&self) -> &[u8] {
226 &self.0
227 }
228}
229
230impl core::fmt::Debug for PairingToken {
231 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
232 write!(f, "PairingToken(<{} characters>)", self.0.len())
234 }
235}
236
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
255pub enum TokenKind {
256 Dynamic,
259 Static,
262}
263
264#[derive(Debug, Clone, PartialEq, Eq)]
269pub struct PairingCode {
270 pub alias: Option<NodeIdAlias>,
272 pub token: PairingToken,
274}
275
276impl PairingCode {
277 pub fn parse(code: &str, kind: TokenKind) -> Result<Self, ConnectError> {
295 match code.split_once('-') {
296 Some((alias, token)) => Ok(Self {
299 alias: Some(NodeIdAlias::parse(alias)?),
300 token: PairingToken::parse(token, kind)?,
301 }),
302 None => Ok(Self {
303 alias: None,
304 token: PairingToken::parse(code, kind)?,
305 }),
306 }
307 }
308}
309
310#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)]
315#[serde(transparent)]
316pub struct AccessToken(String);
317
318#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)]
323#[serde(transparent)]
324pub struct CommunicationToken(String);
325
326macro_rules! opaque_token {
327 ($ty:ident, $name:literal, $lifetime:expr) => {
328 impl $ty {
329 pub const MIN_BYTES: usize = 32;
331
332 #[must_use]
334 pub fn new(value: impl Into<String>) -> Self {
335 Self(value.into())
336 }
337
338 pub fn from_entropy(bytes: &[u8]) -> Result<Self, ConnectError> {
343 if bytes.len() < Self::MIN_BYTES {
344 return Err(ConnectError::WeakSecret {
345 got: bytes.len(),
346 need: Self::MIN_BYTES,
347 });
348 }
349 Ok(Self(
350 base64::engine::general_purpose::STANDARD.encode(bytes),
351 ))
352 }
353
354 #[must_use]
356 pub fn as_str(&self) -> &str {
357 &self.0
358 }
359
360 #[must_use]
362 pub const fn lifetime() -> Duration {
363 $lifetime
364 }
365
366 #[must_use]
368 pub fn verify(&self, other: &Self) -> bool {
369 self.verify_str(&other.0)
370 }
371
372 #[must_use]
379 pub fn verify_str(&self, presented: &str) -> bool {
380 use subtle::ConstantTimeEq as _;
381 self.0.len() == presented.len()
384 && bool::from(self.0.as_bytes().ct_eq(presented.as_bytes()))
385 }
386 }
387
388 impl core::fmt::Debug for $ty {
389 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
390 write!(f, concat!($name, "(<redacted>)"))
391 }
392 }
393 };
394}
395
396opaque_token!(AccessToken, "AccessToken", Duration::from_secs(157_680_000));
398opaque_token!(
399 CommunicationToken,
400 "CommunicationToken",
401 Duration::from_secs(30)
402);
403
404#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
406pub struct NodeDescription {
407 pub id: NodeId,
409 pub brand: String,
411 #[serde(rename = "logoUrl", skip_serializing_if = "Option::is_none")]
413 pub logo_url: Option<String>,
414 #[serde(rename = "type")]
416 pub kind: String,
417 #[serde(rename = "modelName")]
419 pub model_name: String,
420 #[serde(rename = "userDefinedName", skip_serializing_if = "Option::is_none")]
422 pub user_defined_name: Option<String>,
423 pub role: Role,
425}
426
427#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
429pub struct EndpointDescription {
430 #[serde(skip_serializing_if = "Option::is_none")]
432 pub name: Option<String>,
433 #[serde(rename = "logoUrl", skip_serializing_if = "Option::is_none")]
435 pub logo_url: Option<String>,
436 #[serde(skip_serializing_if = "Option::is_none")]
438 pub deployment: Option<Deployment>,
439}
440
441#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
443#[non_exhaustive]
444pub enum ConnectError {
445 #[error("the pairing code is malformed")]
448 MalformedPairingCode,
449 #[error("the node identifier is malformed")]
451 MalformedNodeId,
452 #[error("a secret of {got} bytes is weaker than the {need} the specification requires")]
454 WeakSecret {
455 got: usize,
457 need: usize,
459 },
460 #[error("the challenge response does not match")]
463 ChallengeFailed,
464 #[error("a {0:?} cannot pair with another {0:?}")]
466 SameRole(Role),
467 #[error("{got} arrived while waiting for {expected}")]
469 OutOfOrder {
470 got: &'static str,
472 expected: &'static str,
474 },
475 #[error("the {what} budget of {} seconds ran out", limit.as_secs_f64())]
477 Expired {
478 what: &'static str,
480 limit: Duration,
482 },
483 #[error("another pairing attempt for this node is in progress")]
489 RateLimited,
490 #[error("no common {0}")]
492 NoOverlap(&'static str),
493 #[error("not paired")]
495 NotPaired,
496 #[error("pairing refused: {:?}", .0.error_message)]
500 Refused(pairing::PairingRefused),
501 #[error("session refused: {:?}", .0.error_message)]
503 SessionRefused(session_init::SessionRefused),
504}
505
506#[derive(Debug, Clone, PartialEq, Eq)]
513pub enum HmacBinding {
514 LeafFingerprint(Vec<u8>),
520 DomainName(String),
523}
524
525impl HmacBinding {
526 pub fn from_hex_fingerprint(hex: &str) -> Result<Self, ConnectError> {
528 let digits: Vec<u8> = hex.bytes().filter(|b| *b != b':' && *b != b' ').collect();
529 if !digits.len().is_multiple_of(2) || digits.is_empty() {
530 return Err(ConnectError::WeakSecret {
531 got: digits.len() / 2,
532 need: 32,
533 });
534 }
535 let mut bytes = Vec::with_capacity(digits.len() / 2);
536 for pair in digits.chunks(2) {
537 let hi = hex_value(*pair.first().unwrap_or(&0))?;
538 let lo = hex_value(*pair.get(1).unwrap_or(&0))?;
539 bytes.push(hi << 4 | lo);
540 }
541 if bytes.len() < 32 {
542 return Err(ConnectError::WeakSecret {
543 got: bytes.len(),
544 need: 32,
545 });
546 }
547 Ok(Self::LeafFingerprint(bytes))
548 }
549
550 fn as_bytes(&self) -> &[u8] {
551 match self {
552 HmacBinding::LeafFingerprint(bytes) => bytes,
553 HmacBinding::DomainName(name) => name.as_bytes(),
554 }
555 }
556}
557
558fn hex_value(b: u8) -> Result<u8, ConnectError> {
559 match b {
560 b'0'..=b'9' => Ok(b - b'0'),
561 b'a'..=b'f' => Ok(b - b'a' + 10),
562 b'A'..=b'F' => Ok(b - b'A' + 10),
563 _ => Err(ConnectError::MalformedPairingCode),
564 }
565}
566
567#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
572#[non_exhaustive]
573pub enum CommunicationProtocol {
574 WebSocket,
576}
577
578#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
580#[non_exhaustive]
581pub enum HmacHashingAlgorithm {
582 #[serde(rename = "SHA256")]
584 Sha256,
585}
586
587#[derive(Debug, Clone, PartialEq, Eq)]
593pub struct ChallengeResponse {
594 bytes: [u8; 32],
595}
596
597impl ChallengeResponse {
598 pub fn compute(
619 challenge: &[u8],
620 token: &PairingToken,
621 binding: &HmacBinding,
622 ) -> Result<Self, ConnectError> {
623 use hmac::Mac as _;
624 if challenge.len() < 32 {
625 return Err(ConnectError::WeakSecret {
626 got: challenge.len(),
627 need: 32,
628 });
629 }
630 let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::KeyInit>::new_from_slice(challenge)
631 .map_err(|_| ConnectError::ChallengeFailed)?;
632 mac.update(token.as_bytes());
633 mac.update(binding.as_bytes());
634 let out = mac.finalize().into_bytes();
635 let mut bytes = [0u8; 32];
636 bytes.copy_from_slice(&out);
637 Ok(Self { bytes })
638 }
639
640 pub fn from_base64(encoded: &str) -> Result<Self, ConnectError> {
642 let decoded = base64::engine::general_purpose::STANDARD
643 .decode(encoded)
644 .map_err(|_| ConnectError::ChallengeFailed)?;
645 if decoded.len() != 32 {
646 return Err(ConnectError::ChallengeFailed);
647 }
648 let mut bytes = [0u8; 32];
649 bytes.copy_from_slice(&decoded);
650 Ok(Self { bytes })
651 }
652
653 #[must_use]
655 pub fn as_base64(&self) -> String {
656 base64::engine::general_purpose::STANDARD.encode(self.bytes)
657 }
658
659 #[must_use]
661 pub fn verify(&self, theirs: &str) -> bool {
662 use subtle::ConstantTimeEq as _;
663 let Ok(other) = Self::from_base64(theirs) else {
664 return false;
665 };
666 self.bytes.ct_eq(&other.bytes).into()
667 }
668}
669
670pub(crate) fn base64_encode(bytes: &[u8]) -> String {
671 base64::engine::general_purpose::STANDARD.encode(bytes)
672}
673
674pub(crate) fn base64_decode(encoded: &str) -> Option<Vec<u8>> {
675 base64::engine::general_purpose::STANDARD
676 .decode(encoded)
677 .ok()
678}
679
680pub type Backoff = crate::session::Backoff;
685
686pub mod dnssd {
688 use super::{Deployment, Role};
689 use alloc::string::{String, ToString};
690 use alloc::vec::Vec;
691
692 pub const SERVICE_TYPE: &str = "_s2connect";
694 pub const PROTOCOL: &str = "_tcp";
696 pub const TXT_VERSION: &str = "1";
698
699 #[derive(Debug, Clone, Default, PartialEq, Eq)]
701 pub struct ServiceRecord {
702 pub endpoint_name: Option<String>,
704 pub endpoint_logo_url: Option<String>,
706 pub pairing_url: Option<String>,
708 pub longpolling_url: Option<String>,
711 pub roles: Vec<Role>,
713 }
714
715 impl ServiceRecord {
716 #[must_use]
722 pub fn txt_pairs(&self) -> Vec<(&'static str, String)> {
723 let mut out = alloc::vec![("txtver", TXT_VERSION.to_string())];
724 if let Some(name) = &self.endpoint_name {
725 out.push(("e_name", name.clone()));
726 }
727 if let Some(logo) = &self.endpoint_logo_url {
728 out.push(("e_logoUrl", logo.clone()));
729 }
730 if let Some(url) = &self.pairing_url {
731 out.push(("pairingUrl", url.clone()));
732 }
733 if let Some(url) = &self.longpolling_url {
734 out.push(("longpollingUrl", url.clone()));
735 }
736 out
737 }
738
739 #[must_use]
744 pub fn from_txt<'a, I>(pairs: I) -> Option<Self>
745 where
746 I: IntoIterator<Item = (&'a str, &'a str)>,
747 {
748 let mut record = Self::default();
749 let mut version_seen = false;
750 for (key, value) in pairs {
751 match key {
752 "txtver" | "txtvers" => {
753 if value != TXT_VERSION {
754 return None;
755 }
756 version_seen = true;
757 }
758 "e_name" => record.endpoint_name = Some(value.to_string()),
759 "e_logoUrl" => record.endpoint_logo_url = Some(value.to_string()),
760 "pairingUrl" => record.pairing_url = Some(value.to_string()),
761 "longpollingUrl" => record.longpolling_url = Some(value.to_string()),
762 _ => {}
763 }
764 }
765 if !version_seen || (record.pairing_url.is_none() && record.longpolling_url.is_none()) {
768 return None;
769 }
770 Some(record)
771 }
772
773 #[must_use]
776 pub fn has_pairing_server(&self) -> bool {
777 self.pairing_url.is_some()
778 }
779
780 #[must_use]
782 pub fn subtypes(&self) -> Vec<&'static str> {
783 self.roles.iter().map(|r| r.service_subtype()).collect()
784 }
785
786 #[must_use]
788 pub fn is_consistent_with(&self, deployment: Deployment) -> bool {
789 self.longpolling_url.is_none() || deployment == Deployment::Lan
790 }
791 }
792}
793
794#[cfg(test)]
795mod tests {
796 use super::*;
797
798 fn token() -> PairingToken {
799 PairingToken::parse("A1b2C3", TokenKind::Static).expect("a legal token")
800 }
801
802 #[test]
803 fn a_pairing_code_splits_at_the_first_dash() {
804 let code = PairingCode::parse("evse7-A1b2C3", TokenKind::Static).unwrap();
805 assert_eq!(code.alias.unwrap().0, "evse7");
806 assert_eq!(code.token.as_bytes(), b"A1b2C3");
807
808 let code = PairingCode::parse("A1b2C3", TokenKind::Static).unwrap();
809 assert!(code.alias.is_none());
810 }
811
812 #[test]
813 fn a_pairing_code_is_checked_before_the_network_is() {
814 assert!(PairingCode::parse("abc", TokenKind::Dynamic).is_err());
816 assert!(PairingCode::parse("abcd", TokenKind::Dynamic).is_ok());
817 assert!(PairingCode::parse("abcde", TokenKind::Static).is_err());
818 assert!(PairingCode::parse("abcdef", TokenKind::Static).is_ok());
819 assert!(PairingCode::parse("ab cd", TokenKind::Dynamic).is_err());
821 assert!(PairingCode::parse("ab.cd", TokenKind::Dynamic).is_err());
822 assert!(PairingCode::parse("", TokenKind::Dynamic).is_err());
823 assert!(PairingCode::parse("-abcd", TokenKind::Dynamic).is_err());
825 }
826
827 #[test]
828 fn everything_an_unauthenticated_peer_chooses_is_bounded() {
829 use alloc::string::ToString;
830
831 assert!(NodeIdAlias::parse(&"a".repeat(NodeIdAlias::MAX_LEN)).is_ok());
833 assert!(NodeIdAlias::parse(&"a".repeat(NodeIdAlias::MAX_LEN + 1)).is_err());
834
835 let long = alloc::format!("\"{}\"", "a".repeat(NodeIdAlias::MAX_LEN + 1));
839 assert!(serde_json::from_str::<NodeIdAlias>(&long).is_err());
840 assert!(serde_json::from_str::<NodeIdAlias>("\"has space\"").is_err());
841 assert!(serde_json::from_str::<NodeIdAlias>("\"\"").is_err());
842 assert_eq!(
843 serde_json::from_str::<NodeIdAlias>("\"hub7\"").unwrap().0,
844 "hub7".to_string()
845 );
846
847 let longest = "a".repeat(PairingToken::MAX_LEN);
849 assert!(PairingToken::parse(&longest, TokenKind::Static).is_ok());
850 assert!(PairingToken::parse(&alloc::format!("{longest}a"), TokenKind::Static).is_err());
851 assert!(PairingCode::parse(&alloc::format!("hub7-{longest}a"), TokenKind::Static).is_err());
853 }
854
855 #[test]
856 fn a_secret_never_prints_itself() {
857 let code = PairingCode::parse("evse7-SuperSecret", TokenKind::Static).unwrap();
858 let rendered = alloc::format!("{:?}", code.token);
859 assert!(!rendered.contains("SuperSecret"), "{rendered}");
860 let access = AccessToken::new("hunter2");
861 assert_eq!(alloc::format!("{access:?}"), "AccessToken(<redacted>)");
862 }
863
864 #[test]
865 fn a_token_needs_the_entropy_the_specification_demands() {
866 assert!(AccessToken::from_entropy(&[0u8; 31]).is_err());
867 let token = AccessToken::from_entropy(&[0u8; 32]).unwrap();
868 assert_eq!(token.as_str().len(), 44);
870 assert_eq!(CommunicationToken::lifetime(), Duration::from_secs(30));
871 }
872
873 #[test]
874 fn the_challenge_binds_to_the_server_it_was_answered_by() {
875 let challenge = [9u8; 32];
876 let here = HmacBinding::DomainName("pairing.example.com".into());
877 let there = HmacBinding::DomainName("pairing.example.com.evil.test".into());
878
879 let ours = ChallengeResponse::compute(&challenge, &token(), &here).unwrap();
880 let theirs = ChallengeResponse::compute(&challenge, &token(), &here).unwrap();
881 assert!(ours.verify(&theirs.as_base64()));
882
883 let forged = ChallengeResponse::compute(&challenge, &token(), &there).unwrap();
886 assert!(!ours.verify(&forged.as_base64()));
887
888 let wrong = PairingToken::parse("Z9y8X7", TokenKind::Static).unwrap();
890 let forged = ChallengeResponse::compute(&challenge, &wrong, &here).unwrap();
891 assert!(!ours.verify(&forged.as_base64()));
892 }
893
894 #[test]
895 fn a_short_challenge_is_refused_rather_than_padded() {
896 let binding = HmacBinding::DomainName("x.example".into());
897 assert!(matches!(
898 ChallengeResponse::compute(&[0u8; 31], &token(), &binding),
899 Err(ConnectError::WeakSecret { need: 32, .. })
900 ));
901 }
902
903 #[test]
904 fn a_fingerprint_is_read_with_or_without_colons() {
905 let colons = "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:\
906 AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99";
907 let plain = colons.replace(':', "");
908 assert_eq!(
909 HmacBinding::from_hex_fingerprint(colons).unwrap(),
910 HmacBinding::from_hex_fingerprint(&plain).unwrap()
911 );
912 assert!(HmacBinding::from_hex_fingerprint("AABB").is_err());
914 assert!(HmacBinding::from_hex_fingerprint("nonsense").is_err());
915 }
916
917 #[test]
918 fn verification_refuses_anything_that_is_not_a_response() {
919 let ours = ChallengeResponse::compute(
920 &[1u8; 32],
921 &token(),
922 &HmacBinding::DomainName("x.example".into()),
923 )
924 .unwrap();
925 assert!(!ours.verify("not base64 at all !!"));
926 assert!(!ours.verify(""));
927 assert!(!ours.verify(&base64::engine::general_purpose::STANDARD.encode([0u8; 16])));
929 }
930
931 #[test]
932 fn only_a_cem_and_an_rm_may_pair() {
933 assert!(Role::Cem.can_pair_with(Role::Rm));
934 assert!(Role::Rm.can_pair_with(Role::Cem));
935 assert!(!Role::Cem.can_pair_with(Role::Cem));
936 assert!(!Role::Rm.can_pair_with(Role::Rm));
937 }
938
939 #[test]
940 fn the_communication_server_is_the_one_the_standard_names() {
941 use Deployment::{Lan, Wan};
942 assert_eq!(Deployment::communication_server(Wan, Lan), Role::Cem);
945 assert_eq!(Deployment::communication_server(Lan, Wan), Role::Rm);
946 assert_eq!(Deployment::communication_server(Wan, Wan), Role::Cem);
949 assert_eq!(Deployment::communication_server(Lan, Lan), Role::Cem);
950 }
951
952 #[test]
953 fn the_dns_sd_record_round_trips_and_accepts_both_spellings() {
954 use dnssd::ServiceRecord;
955 let record = ServiceRecord {
956 endpoint_name: Some("EVSE1038".into()),
957 endpoint_logo_url: None,
958 pairing_url: Some("https://EVSE1038.local:443/pairing/".into()),
959 longpolling_url: None,
960 roles: alloc::vec![Role::Rm],
961 };
962 let pairs = record.txt_pairs();
963 assert_eq!(pairs[0], ("txtver", "1".to_string()));
964 assert_eq!(record.subtypes(), alloc::vec!["_rm"]);
965
966 let borrowed: alloc::vec::Vec<(&str, &str)> =
967 pairs.iter().map(|(k, v)| (*k, v.as_str())).collect();
968 let back = ServiceRecord::from_txt(borrowed).unwrap();
969 assert_eq!(back.pairing_url, record.pairing_url);
970
971 let back =
973 ServiceRecord::from_txt([("txtvers", "1"), ("pairingUrl", "https://x.local/pairing/")])
974 .unwrap();
975 assert!(back.has_pairing_server());
976
977 assert!(ServiceRecord::from_txt([("txtver", "1")]).is_none());
979 assert!(ServiceRecord::from_txt([("txtver", "2"), ("pairingUrl", "x")]).is_none());
981 }
982
983 #[test]
984 fn long_polling_is_a_lan_only_arrangement() {
985 use dnssd::ServiceRecord;
986 let record = ServiceRecord {
987 longpolling_url: Some("https://rm.local/pairing/".into()),
988 roles: alloc::vec![Role::Rm],
989 ..ServiceRecord::default()
990 };
991 assert!(record.is_consistent_with(Deployment::Lan));
992 assert!(!record.is_consistent_with(Deployment::Wan));
993 }
994}