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