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    /// Whether a `group_id` outside the spec's 43 base64url characters closes the connection.
293    ///
294    /// The spec makes such a value a protocol error, and with `true` the client behaves that way:
295    /// the attempt ends and [`Event::Disconnected`](crate::Event::Disconnected) reports why.
296    ///
297    /// The default is `false`. A non-canonical but well-formed identifier - non-empty, at most 128
298    /// bytes, valid UTF-8 without control characters - is then accepted as an opaque string and
299    /// reported once per connection as [`Event::GroupIdNotCanonical`](crate::Event::GroupIdNotCanonical).
300    /// That tolerance exists because a real server sends a UUID instead; see
301    /// `docs/spec-deviations.md`. A host that talks to a conformant server, or that wants the
302    /// spec's rule enforced, sets this to `true`.
303    pub strict_group_id: bool,
304    /// Whether this client admits a server with no pairing record.
305    ///
306    /// The value is advertised in `client/hello` as `unpaired_access.enabled` and both sides act on
307    /// it. With `false` this client refuses to activate a session that is not keyed by a long-term
308    /// PSK for playback: such a `server/activate` ends the connection with `client/goodbye` reason
309    /// `pairing_required`. A server that honours the advertisement grants no roles to an unpaired
310    /// client whose hello says `false`. Pairing is unaffected: both pairing flows run over a
311    /// Sentinel-keyed session and stay admissible.
312    ///
313    /// `pairing.md` leaves the default to the manufacturer and recommends `false` for a client whose
314    /// input a stranger could reach, such as a microphone. The default here is `true`, which is what
315    /// every release before this setting did.
316    pub unpaired_access: bool,
317    /// How long one pairing attempt may run, measured from `client/pair-init`.
318    ///
319    /// On expiry the client sends `pair/abort` with reason `attempt_timeout` and reports
320    /// [`Event::PairingFailed`](crate::Event::PairingFailed). The protocol recommends two minutes,
321    /// which is [`DEFAULT_PAIRING_TIMEOUT`](crate::DEFAULT_PAIRING_TIMEOUT); a host shortens it
322    /// only for tests or for a deployment that wants a tighter bound.
323    pub pairing_timeout: Duration,
324    /// The operator-facing static pairing code, exactly eight decimal digits.
325    ///
326    /// The code is configuration, never generated: a manufacturer provisions one per device, and
327    /// the operator reads it off the device or its leaflet. Offering the static code method in
328    /// `client/hello` depends on this field being set, so a client without a code never advertises
329    /// a method it cannot complete.
330    ///
331    /// The code is a credential: anyone who knows it and can reach the server may pair. It is
332    /// never formatted - [`ClientConfig`]'s `Debug` prints it redacted - and never logged.
333    #[cfg(feature = "pairing-code")]
334    pub static_pairing_code: Option<String>,
335    /// How long an operator-opened pairing window admits attempts, recommended five minutes.
336    ///
337    /// The window runs from [`ControlHandle::open_pairing_window`](crate::ControlHandle::open_pairing_window)
338    /// and does not pause during an attempt. On expiry it closes silently; an attempt already in
339    /// progress runs to its own end.
340    #[cfg(feature = "pairing-code")]
341    pub pairing_window: Duration,
342    /// Sentence sent in `client/pair-pending`, in the host's language.
343    ///
344    /// A host that wants to tell the operator what to do sets it here; without one the message is
345    /// sent with no text, because the crate does not invent operator-facing prose.
346    #[cfg(feature = "pairing-code")]
347    pub pairing_pending_text: Option<String>,
348    /// Emission formats the client offers for a dynamic pairing code.
349    ///
350    /// An empty list offers no dynamic method at all; a non-empty one advertises
351    /// `dynamic_pairing_code` in `client/hello`, together with [`ClientConfig::code_out_channels`].
352    /// Both lists must be set for the method to be offered, because the protocol treats a
353    /// descriptor left without a known format or channel as unrecognized. The code itself is
354    /// derived per attempt, never configured.
355    #[cfg(feature = "pairing-code")]
356    pub code_formats: Vec<CodeFormat>,
357    /// Channels the host can carry a dynamic pairing code through.
358    ///
359    /// The host sets what it can render or speak; the server picks the method's format, and the
360    /// client emits the code through [`Event::PairingCode`](crate::Event::PairingCode).
361    #[cfg(feature = "pairing-code")]
362    pub code_out_channels: Vec<CodeOutChannel>,
363    /// The server-initiated half of the connection mode, or `None` for client-initiated
364    /// connections.
365    ///
366    /// Setting it makes [`advertise`](crate::advertise) publish `_sendspin._tcp` and accept the
367    /// servers that connect, and makes a manual [`connect`](crate::connect) fail: `connection.md`
368    /// lets a client use one of the two methods at a time, never both. [`Inbound::new`] fills the
369    /// listen address and the path with the values the spec recommends.
370    ///
371    /// [`Inbound::new`]: crate::Inbound::new
372    #[cfg(feature = "discovery")]
373    pub inbound: Option<crate::Inbound>,
374}
375
376impl fmt::Debug for ClientConfig {
377    /// Formats the configuration without the store and without key material.
378    ///
379    /// The store holds the pairing PSK and the records, and its own `Debug` is the host's; the
380    /// identity redacts its secret. Neither is delegated to here, so a `Debug` log of a
381    /// configuration cannot leak a key.
382    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
383        let mut debug = formatter.debug_struct("ClientConfig");
384        debug
385            .field("server", &self.server)
386            .field("player_name", &self.player_name)
387            .field("device_info", &self.device_info)
388            .field("identity", &self.identity)
389            .field("storage", &self.storage.as_ref().map(|_| "<host storage>"))
390            .field("audio_mode", &self.audio_mode)
391            .field("volume", &self.volume)
392            .field("muted", &self.muted)
393            .field("volume_policy", &self.volume_policy)
394            .field("max_backoff", &self.max_backoff)
395            .field("strict_group_id", &self.strict_group_id)
396            .field("unpaired_access", &self.unpaired_access)
397            .field("pairing_timeout", &self.pairing_timeout);
398        // The static code is a credential, so it is named but never printed.
399        #[cfg(feature = "pairing-code")]
400        debug
401            .field(
402                "static_pairing_code",
403                &self.static_pairing_code.as_ref().map(|_| "<redacted>"),
404            )
405            .field("pairing_window", &self.pairing_window)
406            .field("pairing_pending_text", &self.pairing_pending_text)
407            .field("code_formats", &self.code_formats)
408            .field("code_out_channels", &self.code_out_channels);
409        // The backend's own `Debug` belongs to the host, so it is named rather than delegated to;
410        // `Inbound`'s format does the same for the backend it holds.
411        #[cfg(feature = "discovery")]
412        debug.field("inbound", &self.inbound);
413        debug.finish()
414    }
415}
416
417impl ClientConfig {
418    /// Builds a configuration for `server` with the crate's defaults.
419    ///
420    /// Everything a host rarely changes starts at a documented value: no device description, no
421    /// pairing store, [`AudioMode::Decode`], volume 100 and unmuted, [`VolumePolicy::default`],
422    /// [`DEFAULT_MAX_BACKOFF`], the tolerated foreign `group_id`, unpaired access admitted, and
423    /// [`DEFAULT_PAIRING_TIMEOUT`](crate::DEFAULT_PAIRING_TIMEOUT). A
424    /// host that restores a level or a mute state sets [`ClientConfig::volume`] and
425    /// [`ClientConfig::muted`] on the value this returns.
426    ///
427    /// The fields stay public, so a host can also build the struct itself and name every field.
428    pub fn new(
429        server: impl Into<String>,
430        player_name: impl Into<String>,
431        identity: Identity,
432    ) -> ClientConfig {
433        ClientConfig {
434            server: server.into(),
435            player_name: player_name.into(),
436            device_info: None,
437            identity,
438            storage: None,
439            audio_mode: AudioMode::Decode,
440            volume: 100,
441            muted: false,
442            volume_policy: VolumePolicy::default(),
443            max_backoff: DEFAULT_MAX_BACKOFF,
444            // The documented tolerance is the default: a foreign group id does not close the
445            // connection unless the host asks for the spec's strictness.
446            strict_group_id: false,
447            // Earlier releases admitted every session, so the setting starts where they left off.
448            unpaired_access: true,
449            pairing_timeout: crate::DEFAULT_PAIRING_TIMEOUT,
450            #[cfg(feature = "pairing-code")]
451            static_pairing_code: None,
452            #[cfg(feature = "pairing-code")]
453            pairing_window: DEFAULT_PAIRING_WINDOW,
454            #[cfg(feature = "pairing-code")]
455            pairing_pending_text: None,
456            #[cfg(feature = "pairing-code")]
457            code_formats: Vec::new(),
458            #[cfg(feature = "pairing-code")]
459            code_out_channels: Vec::new(),
460            // The client-initiated mode is the default: nothing is advertised and nothing listens.
461            #[cfg(feature = "discovery")]
462            inbound: None,
463        }
464    }
465
466    /// Rejects a configuration that would put invalid fields on the wire.
467    pub(crate) fn validate(&self) -> Result<()> {
468        self.validate_common()?;
469        if self.server.trim().is_empty() {
470            bail!("ClientConfig::server must not be empty");
471        }
472        Ok(())
473    }
474
475    /// Rejects the fields both connection modes share.
476    ///
477    /// A server that advertises and accepts connections names no server address, so the address
478    /// check belongs to [`validate`](ClientConfig::validate) alone and the inbound listener
479    /// validates without it.
480    pub(crate) fn validate_common(&self) -> Result<()> {
481        if self.player_name.trim().is_empty() {
482            bail!("ClientConfig::player_name must not be empty");
483        }
484        if self.player_name.len() > MAX_PLAYER_NAME_LEN {
485            bail!(
486                "ClientConfig::player_name is {} bytes, more than the {MAX_PLAYER_NAME_LEN} the \
487                 protocol allows",
488                self.player_name.len()
489            );
490        }
491        if self.volume > MAX_VOLUME {
492            bail!(
493                "ClientConfig::volume is {}, outside the 0-{MAX_VOLUME} the protocol defines",
494                self.volume
495            );
496        }
497        if self.volume_policy.threshold > MAX_VOLUME {
498            bail!(
499                "ClientConfig::volume_policy.threshold is {}, outside the 0-{MAX_VOLUME} level \
500                 range",
501                self.volume_policy.threshold
502            );
503        }
504        if self.volume_policy.max_step > MAX_VOLUME {
505            bail!(
506                "ClientConfig::volume_policy.max_step is {}, outside the 0-{MAX_VOLUME} step \
507                 range",
508                self.volume_policy.max_step
509            );
510        }
511        if self.max_backoff.is_zero() {
512            bail!("ClientConfig::max_backoff must not be zero");
513        }
514        if self.pairing_timeout.is_zero() {
515            bail!("ClientConfig::pairing_timeout must not be zero");
516        }
517        #[cfg(feature = "pairing-code")]
518        {
519            if let Some(code) = &self.static_pairing_code {
520                if code.len() != STATIC_PAIRING_CODE_LEN
521                    || !code.bytes().all(|byte| byte.is_ascii_digit())
522                {
523                    // The code itself is a credential, so the error names the shape, never the
524                    // value the host passed.
525                    bail!(
526                        "ClientConfig::static_pairing_code must be {STATIC_PAIRING_CODE_LEN} \
527                         ASCII digits"
528                    );
529                }
530            }
531            if self.pairing_window.is_zero() {
532                bail!("ClientConfig::pairing_window must not be zero");
533            }
534            if let Some(text) = &self.pairing_pending_text {
535                if text.len() > MAX_PAIRING_PENDING_TEXT_LEN {
536                    bail!(
537                        "ClientConfig::pairing_pending_text is {} bytes, more than the \
538                         {MAX_PAIRING_PENDING_TEXT_LEN} the protocol allows",
539                        text.len()
540                    );
541                }
542            }
543            // A descriptor with formats but no channel - or the other way round - is one a server
544            // treats as unrecognized, so the client would advertise a method it cannot complete.
545            if self.code_formats.is_empty() != self.code_out_channels.is_empty() {
546                bail!(
547                    "ClientConfig::code_formats and ClientConfig::code_out_channels must both be \
548                     set or both be empty"
549                );
550            }
551        }
552        // The path becomes TXT record content and the endpoint the listener serves, so it has to be
553        // a `path-absolute` (RFC 3986) the other side can append to an authority: a leading slash,
554        // and not the `//authority` form.
555        #[cfg(feature = "discovery")]
556        if let Some(inbound) = &self.inbound {
557            if !inbound.path.starts_with('/') || inbound.path.starts_with("//") {
558                bail!(
559                    "ClientConfig::inbound.path must be an absolute path such as \
560                     \"/sendspin\", not a relative one and not one starting with //"
561                );
562            }
563        }
564        Ok(())
565    }
566}
567
568#[cfg(test)]
569mod tests {
570    use super::*;
571
572    /// A configuration that passes validation, for tests that change one field.
573    fn valid() -> ClientConfig {
574        ClientConfig {
575            server: "127.0.0.1:1".to_owned(),
576            player_name: "Test player".to_owned(),
577            device_info: None,
578            identity: Identity::generate(),
579            storage: None,
580            audio_mode: AudioMode::Passthrough,
581            volume: 100,
582            muted: false,
583            volume_policy: VolumePolicy::default(),
584            max_backoff: Duration::from_secs(1),
585            strict_group_id: false,
586            unpaired_access: true,
587            pairing_timeout: crate::DEFAULT_PAIRING_TIMEOUT,
588            #[cfg(feature = "discovery")]
589            inbound: None,
590            #[cfg(feature = "pairing-code")]
591            static_pairing_code: None,
592            #[cfg(feature = "pairing-code")]
593            pairing_window: DEFAULT_PAIRING_WINDOW,
594            #[cfg(feature = "pairing-code")]
595            pairing_pending_text: None,
596            #[cfg(feature = "pairing-code")]
597            code_formats: Vec::new(),
598            #[cfg(feature = "pairing-code")]
599            code_out_channels: Vec::new(),
600        }
601    }
602
603    #[test]
604    fn the_constructor_fills_a_configuration_that_validates() {
605        let config = ClientConfig::new("127.0.0.1:8927", "Test player", Identity::generate());
606        config.validate().expect("the defaults are valid");
607        assert_eq!(config.server, "127.0.0.1:8927");
608        assert_eq!(config.player_name, "Test player");
609        assert_eq!(config.audio_mode, AudioMode::Decode);
610        assert_eq!(config.volume, 100);
611        assert!(!config.muted);
612        assert_eq!(config.max_backoff, DEFAULT_MAX_BACKOFF);
613        assert!(
614            !config.strict_group_id,
615            "the documented tolerance is the default; a host opts into the spec's strictness"
616        );
617        assert!(
618            config.unpaired_access,
619            "unpaired access is admitted by default, as every earlier release did"
620        );
621        assert_eq!(config.pairing_timeout, crate::DEFAULT_PAIRING_TIMEOUT);
622        assert!(config.storage.is_none());
623        assert!(config.device_info.is_none());
624        // The client-initiated mode is what a host gets without asking: nothing advertises and no
625        // socket listens until it sets an `Inbound`.
626        #[cfg(feature = "discovery")]
627        assert!(config.inbound.is_none());
628    }
629
630    #[test]
631    fn the_pairing_timeout_must_be_positive() {
632        let config = ClientConfig {
633            pairing_timeout: Duration::ZERO,
634            #[cfg(feature = "discovery")]
635            inbound: None,
636            ..valid()
637        };
638        let error = config
639            .validate()
640            .expect_err("a zero timeout would abort every attempt at once");
641        assert!(
642            format!("{error:#}").contains("pairing_timeout"),
643            "the error must name the field, got: {error:#}"
644        );
645        config_with_default_timeout()
646            .validate()
647            .expect("120s is valid");
648    }
649
650    /// A configuration with the protocol's recommended attempt timeout.
651    fn config_with_default_timeout() -> ClientConfig {
652        let config = valid();
653        assert_eq!(config.pairing_timeout, crate::DEFAULT_PAIRING_TIMEOUT);
654        config
655    }
656
657    #[test]
658    fn a_configuration_debug_names_no_key_material() {
659        let store = std::sync::Arc::new(crate::test_support::MemoryStore::holding([7u8; 32]));
660        let config = ClientConfig {
661            storage: Some(store),
662            ..valid()
663        };
664        let text = format!("{config:?}");
665        assert!(text.contains("ClientConfig"), "unexpected format: {text}");
666        assert!(
667            text.contains("<host storage>"),
668            "the store is named but never delegated to: {text}"
669        );
670        assert!(
671            !text.contains(&config.identity.secret_base64()),
672            "the identity secret must stay out of a debug format: {text}"
673        );
674    }
675
676    #[test]
677    fn a_stored_psk_formats_without_its_key_material() {
678        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
679        use base64::Engine as _;
680
681        let psk = [0xab; 32];
682        let record = StoredPsk {
683            category: PskCategory::Pairing,
684            psk,
685            server_id: "B1y4w7z0c3f6i9l2o5r8u1x4a7d0g3j6m9p2s5v8y1b".to_owned(),
686        };
687        let text = format!("{record:?}");
688        assert!(text.contains("StoredPsk"), "unexpected format: {text}");
689        assert!(text.contains("Pairing"), "the category is not key material");
690        assert!(text.contains("B1y4w7z0c3f6i9l2o5r8u1x4a7d0g3j6m9p2s5v8y1b"));
691        assert!(text.contains("<redacted>"));
692        assert!(
693            !text.contains(&URL_SAFE_NO_PAD.encode(psk)),
694            "the key must never appear in a debug format: {text}"
695        );
696        assert!(
697            !text.contains(&format!("{psk:?}")),
698            "not even the raw bytes may appear: {text}"
699        );
700    }
701
702    /// The dynamic method's descriptor needs a format and a channel; one without the other is
703    /// treated as unrecognized by a server, so the configuration refuses it before a connection.
704    #[cfg(feature = "pairing-code")]
705    #[test]
706    fn the_code_descriptor_lists_are_set_together() {
707        let formats_only = ClientConfig {
708            code_formats: vec![CodeFormat::Digits],
709            ..valid()
710        };
711        let error = formats_only
712            .validate()
713            .expect_err("a format without a channel is not a usable descriptor");
714        assert!(
715            format!("{error:#}").contains("code_out_channels"),
716            "the error names the missing list, got: {error:#}"
717        );
718
719        let channels_only = ClientConfig {
720            code_out_channels: vec![CodeOutChannel::Display],
721            ..valid()
722        };
723        let error = channels_only
724            .validate()
725            .expect_err("a channel without a format is not a usable descriptor");
726        assert!(
727            format!("{error:#}").contains("code_formats"),
728            "the error names the missing list, got: {error:#}"
729        );
730
731        ClientConfig {
732            code_formats: vec![CodeFormat::Digits, CodeFormat::QrCode],
733            code_out_channels: vec![CodeOutChannel::Display],
734            ..valid()
735        }
736        .validate()
737        .expect("both lists make the method offerable");
738    }
739
740    /// The identifiers are the ones `client/hello` and `server/activate` spell.
741    #[cfg(feature = "pairing-code")]
742    #[test]
743    fn the_code_types_round_trip_through_their_wire_names() {
744        assert_eq!(CodeFormat::Digits.as_wire(), "digits");
745        assert_eq!(CodeFormat::QrCode.as_wire(), "qr_code");
746        assert_eq!(CodeFormat::from_wire("digits"), Some(CodeFormat::Digits));
747        assert_eq!(CodeFormat::from_wire("qr_code"), Some(CodeFormat::QrCode));
748        assert_eq!(
749            CodeFormat::from_wire("nfc"),
750            None,
751            "a format this revision does not know selects nothing"
752        );
753        assert_eq!(CodeOutChannel::Display.as_wire(), "display");
754        assert_eq!(CodeOutChannel::Speaker.as_wire(), "speaker");
755    }
756
757    #[test]
758    fn an_empty_server_address_is_rejected() {
759        for server in ["", "   "] {
760            let config = ClientConfig {
761                server: server.to_owned(),
762                ..valid()
763            };
764            let error = config.validate().expect_err("an empty address has no host");
765            assert!(
766                format!("{error:#}").contains("server"),
767                "the error must name the address, got: {error:#}"
768            );
769        }
770    }
771
772    #[test]
773    fn a_player_name_is_bounded_by_the_protocol_length() {
774        let longest = ClientConfig {
775            player_name: "a".repeat(MAX_PLAYER_NAME_LEN),
776            ..valid()
777        };
778        longest
779            .validate()
780            .expect("a name at the limit must be accepted");
781
782        let config = ClientConfig {
783            player_name: "a".repeat(MAX_PLAYER_NAME_LEN + 1),
784            ..valid()
785        };
786        let error = config
787            .validate()
788            .expect_err("a name above the limit must be rejected");
789        let message = format!("{error:#}");
790        assert!(
791            message.contains("player_name")
792                && message.contains(&(MAX_PLAYER_NAME_LEN + 1).to_string()),
793            "the error must name the field and the length, got: {message}"
794        );
795
796        let config = ClientConfig {
797            player_name: " \t ".to_owned(),
798            ..valid()
799        };
800        let error = config
801            .validate()
802            .expect_err("a blank name must be rejected");
803        assert!(format!("{error:#}").contains("player_name"));
804    }
805
806    /// The protocol fixes the code at eight decimal digits; anything else cannot be entered.
807    #[cfg(feature = "pairing-code")]
808    #[test]
809    fn a_static_pairing_code_is_exactly_eight_digits() {
810        for code in ["12345678", "00000000", "99999999"] {
811            let config = ClientConfig {
812                static_pairing_code: Some(code.to_owned()),
813                ..valid()
814            };
815            config
816                .validate()
817                .unwrap_or_else(|error| panic!("{code:?} must be accepted: {error:#}"));
818        }
819
820        for code in [
821            "",
822            "1234567",
823            "123456789",
824            "1234 678",
825            "1234567a",
826            "--------",
827            "12345678",
828        ] {
829            let config = ClientConfig {
830                static_pairing_code: Some(code.to_owned()),
831                ..valid()
832            };
833            let error = config
834                .validate()
835                .expect_err("a code that is not eight digits must be rejected");
836            let message = format!("{error:#}");
837            assert!(
838                message.contains("static_pairing_code"),
839                "the error must name the field, got: {message}"
840            );
841            assert!(
842                !message.contains(code) || code.is_empty(),
843                "the code is a credential and must not appear in the error: {message}"
844            );
845        }
846    }
847
848    /// The window has no pause, so a zero lifetime would close it before any attempt could start.
849    #[cfg(feature = "pairing-code")]
850    #[test]
851    fn the_pairing_window_and_pending_text_are_bounded() {
852        let config = ClientConfig {
853            pairing_window: Duration::ZERO,
854            ..valid()
855        };
856        let error = config
857            .validate()
858            .expect_err("a zero window cannot admit an attempt");
859        assert!(
860            format!("{error:#}").contains("pairing_window"),
861            "the error must name the field, got: {error:#}"
862        );
863
864        let longest = ClientConfig {
865            pairing_pending_text: Some("a".repeat(MAX_PAIRING_PENDING_TEXT_LEN)),
866            ..valid()
867        };
868        longest
869            .validate()
870            .expect("a sentence at the limit must be accepted");
871
872        let config = ClientConfig {
873            pairing_pending_text: Some("a".repeat(MAX_PAIRING_PENDING_TEXT_LEN + 1)),
874            ..valid()
875        };
876        let error = config
877            .validate()
878            .expect_err("a sentence above the limit must be rejected");
879        assert!(
880            format!("{error:#}").contains("pairing_pending_text"),
881            "the error must name the field, got: {error:#}"
882        );
883    }
884
885    /// The static code is a credential, so a `Debug` log of the configuration must not print it.
886    #[cfg(feature = "pairing-code")]
887    #[test]
888    fn a_static_pairing_code_is_redacted_in_debug() {
889        let config = ClientConfig {
890            static_pairing_code: Some("12345678".to_owned()),
891            ..valid()
892        };
893        let text = format!("{config:?}");
894        assert!(
895            text.contains("static_pairing_code: Some(\"<redacted>\")"),
896            "the field must be named but redacted: {text}"
897        );
898        assert!(
899            !text.contains("12345678"),
900            "the code must never appear in a debug format: {text}"
901        );
902    }
903}