Skip to main content

syncspin_client/
config.rs

1//! Connection configuration.
2
3use std::fmt;
4use std::sync::Arc;
5use std::time::Duration;
6
7use anyhow::{bail, Result};
8use syncspin_core::noise::Identity;
9
10use crate::client::MAX_VOLUME;
11use crate::storage::Storage;
12
13/// Longest player name the protocol allows, in bytes of UTF-8.
14pub const MAX_PLAYER_NAME_LEN: usize = 64;
15
16/// Longest delay between reconnect attempts a configuration starts with.
17///
18/// [`ClientConfig::new`] uses it; a host that wants a longer or shorter ceiling sets
19/// [`ClientConfig::max_backoff`] itself.
20pub const DEFAULT_MAX_BACKOFF: Duration = Duration::from_secs(30);
21
22/// Number of digits in a static pairing code.
23///
24/// The protocol fixes the length at eight decimal digits, so a configured code is exactly this
25/// many ASCII characters.
26#[cfg(feature = "pairing-code")]
27pub const STATIC_PAIRING_CODE_LEN: usize = 8;
28
29/// Longest `client/pair-pending` message the protocol allows, in bytes of UTF-8.
30#[cfg(feature = "pairing-code")]
31pub const MAX_PAIRING_PENDING_TEXT_LEN: usize = 200;
32
33/// How long an operator-opened pairing window admits attempts.
34///
35/// `pairing.md` recommends five minutes and starts the clock at the gesture, not at the first
36/// attempt.
37#[cfg(feature = "pairing-code")]
38pub const DEFAULT_PAIRING_WINDOW: Duration = Duration::from_secs(300);
39
40/// Emission format of a dynamic pairing code.
41///
42/// `pairing.md` defines two: `digits`, a six-digit decimal code the operator types into the
43/// server, and `qr_code`, a 24-byte code presented as a version-1 pairing token in a QR code. The
44/// format is chosen per connection by the server's `server/activate`, from the formats the client
45/// advertises; it decides how a host presents the code and what CPace's `PRS` is.
46#[cfg(feature = "pairing-code")]
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum CodeFormat {
49    /// Six decimal digits.
50    Digits,
51    /// A 24-byte code as a version-1 pairing token.
52    QrCode,
53}
54
55#[cfg(feature = "pairing-code")]
56impl CodeFormat {
57    /// Returns the identifier the wire and `client/hello` use.
58    pub(crate) fn as_wire(self) -> &'static str {
59        match self {
60            CodeFormat::Digits => "digits",
61            CodeFormat::QrCode => "qr_code",
62        }
63    }
64
65    /// Decodes an emission format from the wire, or `None` for a value this revision does not know.
66    pub(crate) fn from_wire(value: &str) -> Option<CodeFormat> {
67        match value {
68            "digits" => Some(CodeFormat::Digits),
69            "qr_code" => Some(CodeFormat::QrCode),
70            _ => None,
71        }
72    }
73}
74
75/// Channel a dynamic pairing code reaches the operator through.
76///
77/// The client advertises the channels its host can actually drive. `display` covers a screen, an
78/// e-ink panel or a seven-segment display; `speaker` covers a device that speaks the code from
79/// audio it bundles itself. The crate derives the code and emits it; rendering and speaking belong
80/// to the host.
81#[cfg(feature = "pairing-code")]
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum CodeOutChannel {
84    /// A display the host renders the code on.
85    Display,
86    /// A speaker the host plays the code through.
87    Speaker,
88}
89
90#[cfg(feature = "pairing-code")]
91impl CodeOutChannel {
92    /// Returns the identifier the wire and `client/hello` use.
93    pub(crate) fn as_wire(self) -> &'static str {
94        match self {
95            CodeOutChannel::Display => "display",
96            CodeOutChannel::Speaker => "speaker",
97        }
98    }
99}
100
101/// How the client wants the stream delivered.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum AudioMode {
104    /// Play raw samples.
105    ///
106    /// The session advertises PCM only, so the server delivers raw samples and the sink receives
107    /// [`AudioFrame::Pcm`](crate::AudioFrame::Pcm). An encoded stream would need a decoder this
108    /// build does not carry, so the session rejects one instead of handing encoded bytes to a
109    /// sink that expects samples.
110    Decode,
111    /// Forward encoded frames.
112    ///
113    /// The session advertises the encoded formats it can forward and the sink receives
114    /// [`AudioFrame::Encoded`](crate::AudioFrame::Encoded). A PCM stream still arrives as
115    /// [`AudioFrame::Pcm`](crate::AudioFrame::Pcm), because there is nothing to decode.
116    Passthrough,
117}
118
119/// Category of a pre-shared key, as the server announces it in Noise message 1.
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum PskCategory {
122    /// Long-term pairing key.
123    LongTerm,
124    /// Key for one pairing attempt.
125    Pairing,
126    /// The published key that authenticates nothing.
127    Sentinel,
128}
129
130impl PskCategory {
131    /// Decodes the two-letter category from the wire.
132    pub(crate) fn from_wire(value: &str) -> Option<PskCategory> {
133        match value {
134            "lt" => Some(PskCategory::LongTerm),
135            "pr" => Some(PskCategory::Pairing),
136            "sn" => Some(PskCategory::Sentinel),
137            _ => None,
138        }
139    }
140
141    /// Encodes the category the way the wire and a stored record spell it.
142    ///
143    /// The inverse of [`from_wire`](PskCategory::from_wire), so a backend this crate ships can
144    /// write a record it reads back with the same meaning.
145    #[cfg(feature = "storage-file")]
146    pub(crate) fn as_wire(self) -> &'static str {
147        match self {
148            PskCategory::LongTerm => "lt",
149            PskCategory::Pairing => "pr",
150            PskCategory::Sentinel => "sn",
151        }
152    }
153}
154
155/// Limits the session applies to a volume request.
156///
157/// A request at or below [`threshold`](VolumePolicy::threshold) is applied as asked, whether it
158/// raises or lowers the level. Above the threshold, one request may raise the level by at most
159/// [`max_step`](VolumePolicy::max_step); a lower request is still applied as asked, because the
160/// limit bounds raises only. The configuration validation rejects a policy that cannot describe a
161/// valid level before a connection is attempted.
162///
163/// [`VolumePolicy::default`] is the rule [`clamp_volume`](crate::clamp_volume) implements, so a
164/// host that does not configure a policy keeps the behaviour of earlier releases.
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub struct VolumePolicy {
167    /// At or below this level a request is applied as is, in the protocol's 0-100 range.
168    pub threshold: u8,
169    /// Above the threshold, at most this much may be added per command.
170    pub max_step: u8,
171    /// Whether a request above the threshold may always rise to the threshold itself.
172    ///
173    /// With `false` a low level creeps up by [`max_step`](VolumePolicy::max_step) per command, so
174    /// 1 + a request for 100 yields 21. With `true` the same request yields the threshold, 40,
175    /// because a level below the threshold may always reach it in one step.
176    pub threshold_floor: bool,
177}
178
179impl Default for VolumePolicy {
180    /// Returns the policy [`clamp_volume`](crate::clamp_volume) implements.
181    fn default() -> Self {
182        Self {
183            threshold: 40,
184            max_step: 20,
185            threshold_floor: false,
186        }
187    }
188}
189
190/// A pre-shared key the host stores for a known server.
191///
192/// Selection after Noise message 1 compares the announced category and key id; a match is only
193/// accepted when `server_id` equals the one in `server/init`. The key itself is never formatted or
194/// logged: `Debug` prints it redacted.
195#[derive(Clone, PartialEq, Eq)]
196pub struct StoredPsk {
197    /// Category the key belongs to.
198    pub category: PskCategory,
199    /// The 32-byte key.
200    pub psk: [u8; 32],
201    /// Static public key of the server this key belongs to, as announced in `server/init`.
202    pub server_id: String,
203}
204
205impl fmt::Debug for StoredPsk {
206    /// Formats the record with the key material redacted.
207    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
208        formatter
209            .debug_struct("StoredPsk")
210            .field("category", &self.category)
211            .field("psk", &"<redacted>")
212            .field("server_id", &self.server_id)
213            .finish()
214    }
215}
216
217/// What the client announces about the device it runs on.
218///
219/// The server shows these values to the operator, so they name the hardware rather than the
220/// protocol: a product name and a manufacturer are always sent, and the software version and MAC
221/// address are sent when the host knows them. The fields are plain text; the crate sends them as
222/// the host provides them, so their content and length belong to the host.
223#[derive(Debug, Clone, Default, PartialEq, Eq)]
224pub struct DeviceInfo {
225    /// Device model or product name.
226    pub product_name: String,
227    /// Device manufacturer.
228    pub manufacturer: String,
229    /// Software version of the host application, not the protocol version.
230    pub software_version: Option<String>,
231    /// Network interface MAC address as lowercase colon-separated bytes.
232    pub mac_address: Option<String>,
233}
234
235/// Everything the client needs to open a session.
236///
237/// The identity is the client's long-lived X25519 keypair. It also becomes the `client_id` the
238/// server sees, so reusing it keeps the player recognisable across reconnects; the crate never
239/// generates or replaces one on its own.
240#[derive(Clone)]
241pub struct ClientConfig {
242    /// Server address as `host:port`, or a full `ws://` URL.
243    ///
244    /// A bare address connects to `ws://<server>/sendspin`. TLS is not part of this build, so a
245    /// `wss://` URL is rejected rather than silently downgraded.
246    pub server: String,
247    /// Friendly name announced to the server, non-empty and at most [`MAX_PLAYER_NAME_LEN`] bytes.
248    pub player_name: String,
249    /// Description of the device the client runs on, announced in `client/hello`.
250    ///
251    /// The server displays it to the operator. A host that does not know the hardware passes
252    /// `None` and no `device_info` object is sent, so the server shows only the player name.
253    pub device_info: Option<DeviceInfo>,
254    /// Long-lived keypair that identifies this client.
255    ///
256    /// Restore a stored keypair with [`Identity::from_secret_base64`]; generating a fresh one
257    /// makes the server treat the player as a new device.
258    pub identity: Identity,
259    /// Where the pairing PSK and the pairing records live, or `None` for a guest-only client.
260    ///
261    /// The host owns the store; see [`Storage`]. With a store the client offers the Pairing PSK
262    /// method, keeps one pairing PSK across restarts and writes a record for every completed
263    /// pairing. Without one it offers no pairing method at all: it never draws a key it cannot
264    /// hand back, and it answers a pairing activation with `pair/abort` reason
265    /// `method_not_supported`. A plain guest session is unchanged either way.
266    pub storage: Option<Arc<dyn Storage>>,
267    /// Whether the sink receives samples or encoded frames.
268    pub audio_mode: AudioMode,
269    /// Output level to start from, in the protocol's 0-100 range.
270    ///
271    /// The session reports this level in its first `client/state` and applies the volume limit
272    /// against it, so a host passes the level it restored instead of an invented one. A host
273    /// without a stored level passes 100, which neither attenuates nor limits an incoming request.
274    pub volume: u8,
275    /// Mute state to start from.
276    ///
277    /// Reported in the first `client/state`; a host without a stored state passes `false`.
278    pub muted: bool,
279    /// Limits applied to every volume request.
280    ///
281    /// The session applies the policy to a command from the server and to a level the host sets
282    /// through [`ControlHandle::set_volume`](crate::ControlHandle::set_volume); the value it
283    /// reports back is always the applied one. [`VolumePolicy::default`] keeps the fixed rule of
284    /// earlier releases.
285    pub volume_policy: VolumePolicy,
286    /// Upper bound for the delay between reconnects.
287    ///
288    /// The connection reports a recommended delay in
289    /// [`Event::Disconnected`](crate::Event::Disconnected) and waits it before the next attempt;
290    /// [`next_backoff`](crate::next_backoff) never returns more than this.
291    pub max_backoff: Duration,
292    /// How long one pairing attempt may run, measured from `client/pair-init`.
293    ///
294    /// On expiry the client sends `pair/abort` with reason `attempt_timeout` and reports
295    /// [`Event::PairingFailed`](crate::Event::PairingFailed). The protocol recommends two minutes,
296    /// which is [`DEFAULT_PAIRING_TIMEOUT`](crate::DEFAULT_PAIRING_TIMEOUT); a host shortens it
297    /// only for tests or for a deployment that wants a tighter bound.
298    pub pairing_timeout: Duration,
299    /// The operator-facing static pairing code, exactly eight decimal digits.
300    ///
301    /// The code is configuration, never generated: a manufacturer provisions one per device, and
302    /// the operator reads it off the device or its leaflet. Offering the static code method in
303    /// `client/hello` depends on this field being set, so a client without a code never advertises
304    /// a method it cannot complete.
305    ///
306    /// The code is a credential: anyone who knows it and can reach the server may pair. It is
307    /// never formatted - [`ClientConfig`]'s `Debug` prints it redacted - and never logged.
308    #[cfg(feature = "pairing-code")]
309    pub static_pairing_code: Option<String>,
310    /// How long an operator-opened pairing window admits attempts, recommended five minutes.
311    ///
312    /// The window runs from [`ControlHandle::open_pairing_window`](crate::ControlHandle::open_pairing_window)
313    /// and does not pause during an attempt. On expiry it closes silently; an attempt already in
314    /// progress runs to its own end.
315    #[cfg(feature = "pairing-code")]
316    pub pairing_window: Duration,
317    /// Sentence sent in `client/pair-pending`, in the host's language.
318    ///
319    /// A host that wants to tell the operator what to do sets it here; without one the message is
320    /// sent with no text, because the crate does not invent operator-facing prose.
321    #[cfg(feature = "pairing-code")]
322    pub pairing_pending_text: Option<String>,
323    /// Emission formats the client offers for a dynamic pairing code.
324    ///
325    /// An empty list offers no dynamic method at all; a non-empty one advertises
326    /// `dynamic_pairing_code` in `client/hello`, together with [`ClientConfig::code_out_channels`].
327    /// Both lists must be set for the method to be offered, because the protocol treats a
328    /// descriptor left without a known format or channel as unrecognized. The code itself is
329    /// derived per attempt, never configured.
330    #[cfg(feature = "pairing-code")]
331    pub code_formats: Vec<CodeFormat>,
332    /// Channels the host can carry a dynamic pairing code through.
333    ///
334    /// The host sets what it can render or speak; the server picks the method's format, and the
335    /// client emits the code through [`Event::PairingCode`](crate::Event::PairingCode).
336    #[cfg(feature = "pairing-code")]
337    pub code_out_channels: Vec<CodeOutChannel>,
338    /// The server-initiated half of the connection mode, or `None` for client-initiated
339    /// connections.
340    ///
341    /// Setting it makes [`advertise`](crate::advertise) publish `_sendspin._tcp` and accept the
342    /// servers that connect, and makes a manual [`connect`](crate::connect) fail: `connection.md`
343    /// lets a client use one of the two methods at a time, never both. [`Inbound::new`] fills the
344    /// listen address and the path with the values the spec recommends.
345    ///
346    /// [`Inbound::new`]: crate::Inbound::new
347    #[cfg(feature = "discovery")]
348    pub inbound: Option<crate::Inbound>,
349}
350
351impl fmt::Debug for ClientConfig {
352    /// Formats the configuration without the store and without key material.
353    ///
354    /// The store holds the pairing PSK and the records, and its own `Debug` is the host's; the
355    /// identity redacts its secret. Neither is delegated to here, so a `Debug` log of a
356    /// configuration cannot leak a key.
357    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
358        let mut debug = formatter.debug_struct("ClientConfig");
359        debug
360            .field("server", &self.server)
361            .field("player_name", &self.player_name)
362            .field("device_info", &self.device_info)
363            .field("identity", &self.identity)
364            .field("storage", &self.storage.as_ref().map(|_| "<host storage>"))
365            .field("audio_mode", &self.audio_mode)
366            .field("volume", &self.volume)
367            .field("muted", &self.muted)
368            .field("volume_policy", &self.volume_policy)
369            .field("max_backoff", &self.max_backoff)
370            .field("pairing_timeout", &self.pairing_timeout);
371        // The static code is a credential, so it is named but never printed.
372        #[cfg(feature = "pairing-code")]
373        debug
374            .field(
375                "static_pairing_code",
376                &self.static_pairing_code.as_ref().map(|_| "<redacted>"),
377            )
378            .field("pairing_window", &self.pairing_window)
379            .field("pairing_pending_text", &self.pairing_pending_text)
380            .field("code_formats", &self.code_formats)
381            .field("code_out_channels", &self.code_out_channels);
382        // The backend's own `Debug` belongs to the host, so it is named rather than delegated to;
383        // `Inbound`'s format does the same for the backend it holds.
384        #[cfg(feature = "discovery")]
385        debug.field("inbound", &self.inbound);
386        debug.finish()
387    }
388}
389
390impl ClientConfig {
391    /// Builds a configuration for `server` with the crate's defaults.
392    ///
393    /// Everything a host rarely changes starts at a documented value: no device description, no
394    /// pairing store, [`AudioMode::Decode`], volume 100 and unmuted, [`VolumePolicy::default`],
395    /// [`DEFAULT_MAX_BACKOFF`] and [`DEFAULT_PAIRING_TIMEOUT`](crate::DEFAULT_PAIRING_TIMEOUT). A
396    /// host that restores a level or a mute state sets [`ClientConfig::volume`] and
397    /// [`ClientConfig::muted`] on the value this returns.
398    ///
399    /// The fields stay public, so a host can also build the struct itself and name every field.
400    pub fn new(
401        server: impl Into<String>,
402        player_name: impl Into<String>,
403        identity: Identity,
404    ) -> ClientConfig {
405        ClientConfig {
406            server: server.into(),
407            player_name: player_name.into(),
408            device_info: None,
409            identity,
410            storage: None,
411            audio_mode: AudioMode::Decode,
412            volume: 100,
413            muted: false,
414            volume_policy: VolumePolicy::default(),
415            max_backoff: DEFAULT_MAX_BACKOFF,
416            pairing_timeout: crate::DEFAULT_PAIRING_TIMEOUT,
417            #[cfg(feature = "pairing-code")]
418            static_pairing_code: None,
419            #[cfg(feature = "pairing-code")]
420            pairing_window: DEFAULT_PAIRING_WINDOW,
421            #[cfg(feature = "pairing-code")]
422            pairing_pending_text: None,
423            #[cfg(feature = "pairing-code")]
424            code_formats: Vec::new(),
425            #[cfg(feature = "pairing-code")]
426            code_out_channels: Vec::new(),
427            // The client-initiated mode is the default: nothing is advertised and nothing listens.
428            #[cfg(feature = "discovery")]
429            inbound: None,
430        }
431    }
432
433    /// Rejects a configuration that would put invalid fields on the wire.
434    pub(crate) fn validate(&self) -> Result<()> {
435        self.validate_common()?;
436        if self.server.trim().is_empty() {
437            bail!("ClientConfig::server must not be empty");
438        }
439        Ok(())
440    }
441
442    /// Rejects the fields both connection modes share.
443    ///
444    /// A server that advertises and accepts connections names no server address, so the address
445    /// check belongs to [`validate`](ClientConfig::validate) alone and the inbound listener
446    /// validates without it.
447    pub(crate) fn validate_common(&self) -> Result<()> {
448        if self.player_name.trim().is_empty() {
449            bail!("ClientConfig::player_name must not be empty");
450        }
451        if self.player_name.len() > MAX_PLAYER_NAME_LEN {
452            bail!(
453                "ClientConfig::player_name is {} bytes, more than the {MAX_PLAYER_NAME_LEN} the \
454                 protocol allows",
455                self.player_name.len()
456            );
457        }
458        if self.volume > MAX_VOLUME {
459            bail!(
460                "ClientConfig::volume is {}, outside the 0-{MAX_VOLUME} the protocol defines",
461                self.volume
462            );
463        }
464        if self.volume_policy.threshold > MAX_VOLUME {
465            bail!(
466                "ClientConfig::volume_policy.threshold is {}, outside the 0-{MAX_VOLUME} level \
467                 range",
468                self.volume_policy.threshold
469            );
470        }
471        if self.volume_policy.max_step > MAX_VOLUME {
472            bail!(
473                "ClientConfig::volume_policy.max_step is {}, outside the 0-{MAX_VOLUME} step \
474                 range",
475                self.volume_policy.max_step
476            );
477        }
478        if self.max_backoff.is_zero() {
479            bail!("ClientConfig::max_backoff must not be zero");
480        }
481        if self.pairing_timeout.is_zero() {
482            bail!("ClientConfig::pairing_timeout must not be zero");
483        }
484        #[cfg(feature = "pairing-code")]
485        {
486            if let Some(code) = &self.static_pairing_code {
487                if code.len() != STATIC_PAIRING_CODE_LEN
488                    || !code.bytes().all(|byte| byte.is_ascii_digit())
489                {
490                    // The code itself is a credential, so the error names the shape, never the
491                    // value the host passed.
492                    bail!(
493                        "ClientConfig::static_pairing_code must be {STATIC_PAIRING_CODE_LEN} \
494                         ASCII digits"
495                    );
496                }
497            }
498            if self.pairing_window.is_zero() {
499                bail!("ClientConfig::pairing_window must not be zero");
500            }
501            if let Some(text) = &self.pairing_pending_text {
502                if text.len() > MAX_PAIRING_PENDING_TEXT_LEN {
503                    bail!(
504                        "ClientConfig::pairing_pending_text is {} bytes, more than the \
505                         {MAX_PAIRING_PENDING_TEXT_LEN} the protocol allows",
506                        text.len()
507                    );
508                }
509            }
510            // A descriptor with formats but no channel - or the other way round - is one a server
511            // treats as unrecognized, so the client would advertise a method it cannot complete.
512            if self.code_formats.is_empty() != self.code_out_channels.is_empty() {
513                bail!(
514                    "ClientConfig::code_formats and ClientConfig::code_out_channels must both be \
515                     set or both be empty"
516                );
517            }
518        }
519        // The path becomes TXT record content and the endpoint the listener serves, so it has to be
520        // a `path-absolute` (RFC 3986) the other side can append to an authority: a leading slash,
521        // and not the `//authority` form.
522        #[cfg(feature = "discovery")]
523        if let Some(inbound) = &self.inbound {
524            if !inbound.path.starts_with('/') || inbound.path.starts_with("//") {
525                bail!(
526                    "ClientConfig::inbound.path must be an absolute path such as \
527                     \"/sendspin\", not a relative one and not one starting with //"
528                );
529            }
530        }
531        Ok(())
532    }
533}
534
535#[cfg(test)]
536mod tests {
537    use super::*;
538
539    /// A configuration that passes validation, for tests that change one field.
540    fn valid() -> ClientConfig {
541        ClientConfig {
542            server: "127.0.0.1:1".to_owned(),
543            player_name: "Test player".to_owned(),
544            device_info: None,
545            identity: Identity::generate(),
546            storage: None,
547            audio_mode: AudioMode::Passthrough,
548            volume: 100,
549            muted: false,
550            volume_policy: VolumePolicy::default(),
551            max_backoff: Duration::from_secs(1),
552            pairing_timeout: crate::DEFAULT_PAIRING_TIMEOUT,
553            #[cfg(feature = "discovery")]
554            inbound: None,
555            #[cfg(feature = "pairing-code")]
556            static_pairing_code: None,
557            #[cfg(feature = "pairing-code")]
558            pairing_window: DEFAULT_PAIRING_WINDOW,
559            #[cfg(feature = "pairing-code")]
560            pairing_pending_text: None,
561            #[cfg(feature = "pairing-code")]
562            code_formats: Vec::new(),
563            #[cfg(feature = "pairing-code")]
564            code_out_channels: Vec::new(),
565        }
566    }
567
568    #[test]
569    fn the_constructor_fills_a_configuration_that_validates() {
570        let config = ClientConfig::new("127.0.0.1:8927", "Test player", Identity::generate());
571        config.validate().expect("the defaults are valid");
572        assert_eq!(config.server, "127.0.0.1:8927");
573        assert_eq!(config.player_name, "Test player");
574        assert_eq!(config.audio_mode, AudioMode::Decode);
575        assert_eq!(config.volume, 100);
576        assert!(!config.muted);
577        assert_eq!(config.max_backoff, DEFAULT_MAX_BACKOFF);
578        assert_eq!(config.pairing_timeout, crate::DEFAULT_PAIRING_TIMEOUT);
579        assert!(config.storage.is_none());
580        assert!(config.device_info.is_none());
581        // The client-initiated mode is what a host gets without asking: nothing advertises and no
582        // socket listens until it sets an `Inbound`.
583        #[cfg(feature = "discovery")]
584        assert!(config.inbound.is_none());
585    }
586
587    #[test]
588    fn the_pairing_timeout_must_be_positive() {
589        let config = ClientConfig {
590            pairing_timeout: Duration::ZERO,
591            #[cfg(feature = "discovery")]
592            inbound: None,
593            ..valid()
594        };
595        let error = config
596            .validate()
597            .expect_err("a zero timeout would abort every attempt at once");
598        assert!(
599            format!("{error:#}").contains("pairing_timeout"),
600            "the error must name the field, got: {error:#}"
601        );
602        config_with_default_timeout()
603            .validate()
604            .expect("120s is valid");
605    }
606
607    /// A configuration with the protocol's recommended attempt timeout.
608    fn config_with_default_timeout() -> ClientConfig {
609        let config = valid();
610        assert_eq!(config.pairing_timeout, crate::DEFAULT_PAIRING_TIMEOUT);
611        config
612    }
613
614    #[test]
615    fn a_configuration_debug_names_no_key_material() {
616        let store = std::sync::Arc::new(crate::test_support::MemoryStore::holding([7u8; 32]));
617        let config = ClientConfig {
618            storage: Some(store),
619            ..valid()
620        };
621        let text = format!("{config:?}");
622        assert!(text.contains("ClientConfig"), "unexpected format: {text}");
623        assert!(
624            text.contains("<host storage>"),
625            "the store is named but never delegated to: {text}"
626        );
627        assert!(
628            !text.contains(&config.identity.secret_base64()),
629            "the identity secret must stay out of a debug format: {text}"
630        );
631    }
632
633    #[test]
634    fn a_stored_psk_formats_without_its_key_material() {
635        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
636        use base64::Engine as _;
637
638        let psk = [0xab; 32];
639        let record = StoredPsk {
640            category: PskCategory::Pairing,
641            psk,
642            server_id: "B1y4w7z0c3f6i9l2o5r8u1x4a7d0g3j6m9p2s5v8y1b".to_owned(),
643        };
644        let text = format!("{record:?}");
645        assert!(text.contains("StoredPsk"), "unexpected format: {text}");
646        assert!(text.contains("Pairing"), "the category is not key material");
647        assert!(text.contains("B1y4w7z0c3f6i9l2o5r8u1x4a7d0g3j6m9p2s5v8y1b"));
648        assert!(text.contains("<redacted>"));
649        assert!(
650            !text.contains(&URL_SAFE_NO_PAD.encode(psk)),
651            "the key must never appear in a debug format: {text}"
652        );
653        assert!(
654            !text.contains(&format!("{psk:?}")),
655            "not even the raw bytes may appear: {text}"
656        );
657    }
658
659    /// The dynamic method's descriptor needs a format and a channel; one without the other is
660    /// treated as unrecognized by a server, so the configuration refuses it before a connection.
661    #[cfg(feature = "pairing-code")]
662    #[test]
663    fn the_code_descriptor_lists_are_set_together() {
664        let formats_only = ClientConfig {
665            code_formats: vec![CodeFormat::Digits],
666            ..valid()
667        };
668        let error = formats_only
669            .validate()
670            .expect_err("a format without a channel is not a usable descriptor");
671        assert!(
672            format!("{error:#}").contains("code_out_channels"),
673            "the error names the missing list, got: {error:#}"
674        );
675
676        let channels_only = ClientConfig {
677            code_out_channels: vec![CodeOutChannel::Display],
678            ..valid()
679        };
680        let error = channels_only
681            .validate()
682            .expect_err("a channel without a format is not a usable descriptor");
683        assert!(
684            format!("{error:#}").contains("code_formats"),
685            "the error names the missing list, got: {error:#}"
686        );
687
688        ClientConfig {
689            code_formats: vec![CodeFormat::Digits, CodeFormat::QrCode],
690            code_out_channels: vec![CodeOutChannel::Display],
691            ..valid()
692        }
693        .validate()
694        .expect("both lists make the method offerable");
695    }
696
697    /// The identifiers are the ones `client/hello` and `server/activate` spell.
698    #[cfg(feature = "pairing-code")]
699    #[test]
700    fn the_code_types_round_trip_through_their_wire_names() {
701        assert_eq!(CodeFormat::Digits.as_wire(), "digits");
702        assert_eq!(CodeFormat::QrCode.as_wire(), "qr_code");
703        assert_eq!(CodeFormat::from_wire("digits"), Some(CodeFormat::Digits));
704        assert_eq!(CodeFormat::from_wire("qr_code"), Some(CodeFormat::QrCode));
705        assert_eq!(
706            CodeFormat::from_wire("nfc"),
707            None,
708            "a format this revision does not know selects nothing"
709        );
710        assert_eq!(CodeOutChannel::Display.as_wire(), "display");
711        assert_eq!(CodeOutChannel::Speaker.as_wire(), "speaker");
712    }
713
714    #[test]
715    fn an_empty_server_address_is_rejected() {
716        for server in ["", "   "] {
717            let config = ClientConfig {
718                server: server.to_owned(),
719                ..valid()
720            };
721            let error = config.validate().expect_err("an empty address has no host");
722            assert!(
723                format!("{error:#}").contains("server"),
724                "the error must name the address, got: {error:#}"
725            );
726        }
727    }
728
729    #[test]
730    fn a_player_name_is_bounded_by_the_protocol_length() {
731        let longest = ClientConfig {
732            player_name: "a".repeat(MAX_PLAYER_NAME_LEN),
733            ..valid()
734        };
735        longest
736            .validate()
737            .expect("a name at the limit must be accepted");
738
739        let config = ClientConfig {
740            player_name: "a".repeat(MAX_PLAYER_NAME_LEN + 1),
741            ..valid()
742        };
743        let error = config
744            .validate()
745            .expect_err("a name above the limit must be rejected");
746        let message = format!("{error:#}");
747        assert!(
748            message.contains("player_name")
749                && message.contains(&(MAX_PLAYER_NAME_LEN + 1).to_string()),
750            "the error must name the field and the length, got: {message}"
751        );
752
753        let config = ClientConfig {
754            player_name: " \t ".to_owned(),
755            ..valid()
756        };
757        let error = config
758            .validate()
759            .expect_err("a blank name must be rejected");
760        assert!(format!("{error:#}").contains("player_name"));
761    }
762
763    /// The protocol fixes the code at eight decimal digits; anything else cannot be entered.
764    #[cfg(feature = "pairing-code")]
765    #[test]
766    fn a_static_pairing_code_is_exactly_eight_digits() {
767        for code in ["12345678", "00000000", "99999999"] {
768            let config = ClientConfig {
769                static_pairing_code: Some(code.to_owned()),
770                ..valid()
771            };
772            config
773                .validate()
774                .unwrap_or_else(|error| panic!("{code:?} must be accepted: {error:#}"));
775        }
776
777        for code in [
778            "",
779            "1234567",
780            "123456789",
781            "1234 678",
782            "1234567a",
783            "--------",
784            "12345678",
785        ] {
786            let config = ClientConfig {
787                static_pairing_code: Some(code.to_owned()),
788                ..valid()
789            };
790            let error = config
791                .validate()
792                .expect_err("a code that is not eight digits must be rejected");
793            let message = format!("{error:#}");
794            assert!(
795                message.contains("static_pairing_code"),
796                "the error must name the field, got: {message}"
797            );
798            assert!(
799                !message.contains(code) || code.is_empty(),
800                "the code is a credential and must not appear in the error: {message}"
801            );
802        }
803    }
804
805    /// The window has no pause, so a zero lifetime would close it before any attempt could start.
806    #[cfg(feature = "pairing-code")]
807    #[test]
808    fn the_pairing_window_and_pending_text_are_bounded() {
809        let config = ClientConfig {
810            pairing_window: Duration::ZERO,
811            ..valid()
812        };
813        let error = config
814            .validate()
815            .expect_err("a zero window cannot admit an attempt");
816        assert!(
817            format!("{error:#}").contains("pairing_window"),
818            "the error must name the field, got: {error:#}"
819        );
820
821        let longest = ClientConfig {
822            pairing_pending_text: Some("a".repeat(MAX_PAIRING_PENDING_TEXT_LEN)),
823            ..valid()
824        };
825        longest
826            .validate()
827            .expect("a sentence at the limit must be accepted");
828
829        let config = ClientConfig {
830            pairing_pending_text: Some("a".repeat(MAX_PAIRING_PENDING_TEXT_LEN + 1)),
831            ..valid()
832        };
833        let error = config
834            .validate()
835            .expect_err("a sentence above the limit must be rejected");
836        assert!(
837            format!("{error:#}").contains("pairing_pending_text"),
838            "the error must name the field, got: {error:#}"
839        );
840    }
841
842    /// The static code is a credential, so a `Debug` log of the configuration must not print it.
843    #[cfg(feature = "pairing-code")]
844    #[test]
845    fn a_static_pairing_code_is_redacted_in_debug() {
846        let config = ClientConfig {
847            static_pairing_code: Some("12345678".to_owned()),
848            ..valid()
849        };
850        let text = format!("{config:?}");
851        assert!(
852            text.contains("static_pairing_code: Some(\"<redacted>\")"),
853            "the field must be named but redacted: {text}"
854        );
855        assert!(
856            !text.contains("12345678"),
857            "the code must never appear in a debug format: {text}"
858        );
859    }
860}