koan-core 0.66.3

Core library for koan — bit-perfect music player. Audio engine, player, database, format strings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Pairing: signing in a device that has no keyboard to type a password with.
//!
//! The device knows only the server's address. It opens a WebSocket at
//! `/rest/koanPair` and is given a pairing: an unguessable id for a link, and
//! a short code to read off the screen. Someone signed in elsewhere — the
//! phone, the Mac, the server's web page — approves it, and the server makes
//! an API key on their account and sends it down the waiting socket. Nothing
//! asks the server whether it has happened yet: the answer arrives when it
//! does. A koan extension, `koanPair`.
//!
//! The link carries the server and the id in the fragment of a koan.rocks
//! address, as invites do, so the site serving the page never sees them.
//!
//! RFC 8628's device grant in shape (code for user code, link for
//! `verification_uri_complete`, the socket for the device code) but not its
//! protocol: see the RFC 8628 section of the pairing protocol reference.

use std::net::{Shutdown, TcpStream};
use std::time::Duration;

use serde::{Deserialize, Serialize};
use tungstenite::stream::MaybeTlsStream;
use url::{Url, form_urlencoded};

use crate::config::Config;
use crate::helpers::SignInError;
use crate::remote::client::SubsonicError;

pub const PAIR_PAGE: &str = "https://koan.rocks/pair/";

/// The server pings a waiting device every half minute. Three missed mean
/// the connection is gone.
const SILENCE: Duration = Duration::from_secs(90);

/// What the server sends down a pairing socket: `Pending` once it is open,
/// then one outcome before it closes.
#[cfg_attr(test, derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum PairMessage {
    #[serde(rename_all = "camelCase")]
    Pending {
        id: String,
        /// `XXXX-XXXX`, for someone to type.
        code: String,
        /// Seconds until the pairing lapses.
        expires_in: u64,
    },
    #[serde(rename_all = "camelCase")]
    Approved {
        username: String,
        api_key: String,
    },
    Declined,
    Expired,
}

#[derive(Debug, thiserror::Error)]
pub enum PairError {
    #[error("not an http(s) server address: {0}")]
    BadUrl(String),
    #[error("could not reach the server: {0}")]
    Connect(String),
    /// The server answered, and has no pairing to offer: not koan, or a koan
    /// from before pairing.
    #[error("this server does not pair devices")]
    Unsupported,
    #[error("too many devices are waiting to pair from this network; try again in a few minutes")]
    TooMany,
    #[error("the server answered with something unexpected")]
    BadResponse,
    #[error("the sign-in was declined")]
    Declined,
    #[error("the code expired before anyone approved it")]
    Expired,
    #[error("the connection to the server closed")]
    Closed,
    #[error("no server is signed in")]
    NotSignedIn,
    /// No device is waiting on that id or code: it was mistyped, lapsed, or
    /// the device stopped waiting.
    #[error(
        "no device is waiting with that code; codes last ten minutes, so check the device for a new one"
    )]
    NotWaiting,
    /// Signed in with a credential that may not sign devices in: an app
    /// password.
    #[error("signing a device in needs this account's password or an API key, not an app password")]
    NotAllowed,
    #[error(transparent)]
    Remote(#[from] SubsonicError),
    #[error(transparent)]
    SignIn(#[from] SignInError),
}

type Socket = tungstenite::WebSocket<MaybeTlsStream<TcpStream>>;

/// A pairing the server is holding open for this device.
pub struct Pending {
    pub id: String,
    pub code: String,
    /// The universal link that opens the approval in the app, or the server's
    /// own page for someone without it.
    pub link: String,
    server: String,
    socket: Socket,
}

/// Ends a wait from another thread.
pub struct Cancel(TcpStream);

impl Cancel {
    pub fn cancel(&self) {
        let _ = self.0.shutdown(Shutdown::Both);
    }
}

/// Ask the server at `url` to pair this device, which approvers will see
/// called `device`.
pub fn start(url: &str, device: &str) -> Result<Pending, PairError> {
    let server = url.trim().trim_end_matches('/').to_owned();
    let socket_url = pair_url(&server, device)?;
    let (mut socket, _) = tungstenite::connect(socket_url.as_str()).map_err(|e| match e {
        // Any answer but an upgrade is a server without pairing, except a
        // koan turning away a busy address and a proxy whose server is down.
        tungstenite::Error::Http(ref response) => match response.status().as_u16() {
            429 => PairError::TooMany,
            502..=504 => PairError::Connect(e.to_string()),
            _ => PairError::Unsupported,
        },
        e => PairError::Connect(e.to_string()),
    })?;
    if let Some(tcp) = tcp(&socket) {
        let _ = tcp.set_read_timeout(Some(SILENCE));
    }
    match read(&mut socket)? {
        PairMessage::Pending { id, code, .. } => Ok(Pending {
            link: link(&server, &id),
            id,
            code,
            server,
            socket,
        }),
        _ => Err(PairError::BadResponse),
    }
}

impl Pending {
    /// What stops `wait`, for whoever gives up on it.
    pub fn canceller(&self) -> Option<Cancel> {
        tcp(&self.socket)?.try_clone().ok().map(Cancel)
    }

    /// Block until the pairing is approved, declined or lapses. Approved, the
    /// key it brings is stored as an invite's is, and the app is signed in.
    pub fn wait(mut self) -> Result<(), PairError> {
        let outcome = read(&mut self.socket);
        let _ = self.socket.close(None);
        match outcome? {
            PairMessage::Approved { username, api_key } => {
                crate::helpers::adopt_api_key(&self.server, &username, &api_key)?;
                Ok(())
            }
            PairMessage::Declined => Err(PairError::Declined),
            PairMessage::Expired => Err(PairError::Expired),
            PairMessage::Pending { .. } => Err(PairError::BadResponse),
        }
    }
}

/// The next message, answering pings while it waits.
fn read(socket: &mut Socket) -> Result<PairMessage, PairError> {
    loop {
        match socket.read() {
            Ok(tungstenite::Message::Text(text)) => {
                if let Some(message) = message(&text)? {
                    return Ok(message);
                }
            }
            Ok(tungstenite::Message::Close(_)) => return Err(PairError::Closed),
            Ok(_) => {}
            Err(_) => return Err(PairError::Closed),
        }
    }
}

/// A message from the server; `None` for one of a type from a newer server,
/// which is passed over. A known type that does not read, or anything that is
/// not a message at all, is a bad response.
fn message(text: &str) -> Result<Option<PairMessage>, PairError> {
    if let Ok(message) = serde_json::from_str(text) {
        return Ok(Some(message));
    }
    let value = serde_json::from_str::<serde_json::Value>(text).ok();
    match value.as_ref().and_then(|v| v.get("type")?.as_str()) {
        Some("pending" | "approved" | "declined" | "expired") | None => Err(PairError::BadResponse),
        Some(_) => Ok(None),
    }
}

fn tcp(socket: &Socket) -> Option<&TcpStream> {
    match socket.get_ref() {
        MaybeTlsStream::Plain(s) => Some(s),
        MaybeTlsStream::Rustls(s) => Some(s.get_ref()),
        _ => None,
    }
}

fn pair_url(server: &str, device: &str) -> Result<Url, PairError> {
    let bad = || PairError::BadUrl(server.to_owned());
    let mut url = Url::parse(&format!("{server}/rest/koanPair")).map_err(|_| bad())?;
    let scheme = match url.scheme() {
        "https" => "wss",
        "http" => "ws",
        _ => return Err(bad()),
    };
    url.set_scheme(scheme).map_err(|()| bad())?;
    url.query_pairs_mut().append_pair("name", device);
    Ok(url)
}

/// The link that approves pairing `id` on `server`.
pub fn link(server: &str, id: &str) -> String {
    let fragment = form_urlencoded::Serializer::new(String::new())
        .append_pair("s", server)
        .append_pair("p", id)
        .finish();
    format!("{PAIR_PAGE}#{fragment}")
}

/// A pairing link's server and pairing id. `None` for anything else.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PairLink {
    pub server: String,
    pub id: String,
}

impl PairLink {
    pub fn parse(link: &str) -> Option<Self> {
        let url = Url::parse(link.trim()).ok()?;
        let params = match (url.scheme(), url.host_str()) {
            ("https", Some("koan.rocks")) if url.path().trim_end_matches('/') == "/pair" => {
                url.fragment()?
            }
            // The same link through the app's own scheme, where the universal
            // link cannot reach the app: a simulator, an unsigned build.
            ("koan", Some("pair")) => url.fragment().or(url.query())?,
            _ => return None,
        };
        let (mut server, mut id) = (None, None);
        for (k, v) in form_urlencoded::parse(params.as_bytes()) {
            let v = Some(v.trim().to_owned()).filter(|v| !v.is_empty());
            match &*k {
                "s" => server = v,
                "p" => id = v,
                _ => {}
            }
        }
        let server = server?.trim_end_matches('/').to_owned();
        if !matches!(Url::parse(&server).ok()?.scheme(), "http" | "https") {
            return None;
        }
        Some(Self { server, id: id? })
    }
}

fn client() -> Result<std::sync::Arc<crate::remote::client::SubsonicClient>, PairError> {
    crate::helpers::subsonic_client(&Config::load().unwrap_or_default())
        .ok_or(PairError::NotSignedIn)
}

/// The device waiting on `pair` (an id or a code) on the signed-in server,
/// and where it asked from.
pub fn info(pair: &str) -> Result<crate::remote::client::KoanPair, PairError> {
    client()?.koan_pair_info(pair).map_err(refused)
}

/// Sign the device waiting on `pair` in as the signed-in account. Answers
/// with the device's name.
pub fn approve(pair: &str) -> Result<String, PairError> {
    client()?.koan_pair_approve(pair, false).map_err(refused)
}

/// Turn the device waiting on `pair` away.
pub fn decline(pair: &str) -> Result<String, PairError> {
    client()?.koan_pair_approve(pair, true).map_err(refused)
}

/// The server's refusals that the person can act on, as their own errors.
/// Anything else, such as too many codes tried, keeps the server's words.
fn refused(e: SubsonicError) -> PairError {
    match e {
        SubsonicError::Api { code: 70, .. } => PairError::NotWaiting,
        SubsonicError::Api { code: 50, .. } => PairError::NotAllowed,
        e => PairError::Remote(e),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_message_from_a_newer_server_is_passed_over() {
        assert_eq!(
            message(r#"{"type":"declined"}"#).unwrap(),
            Some(PairMessage::Declined)
        );
        assert_eq!(message(r#"{"type":"somethingNew","x":1}"#).unwrap(), None);
        assert!(matches!(
            message(r#"{"type":"approved","key":"renamed"}"#),
            Err(PairError::BadResponse)
        ));
        assert!(matches!(message("<html>"), Err(PairError::BadResponse)));
    }

    #[test]
    fn a_link_reads_back() {
        let made = link("https://music.example.com:8443/koan", "abc_-123");
        assert!(made.starts_with("https://koan.rocks/pair/#s=https%3A%2F%2Fmusic"));
        assert_eq!(
            PairLink::parse(&made),
            Some(PairLink {
                server: "https://music.example.com:8443/koan".into(),
                id: "abc_-123".into(),
            })
        );
        assert!(PairLink::parse("https://koan.rocks/pair#s=https%3A%2F%2Fa.example&p=x").is_some());
    }

    #[test]
    fn the_apps_own_scheme_carries_the_same_link() {
        let expected = Some(PairLink {
            server: "https://a.example".into(),
            id: "x".into(),
        });
        assert_eq!(
            PairLink::parse("koan://pair#s=https%3A%2F%2Fa.example&p=x"),
            expected
        );
        assert_eq!(
            PairLink::parse("koan://pair?s=https%3A%2F%2Fa.example&p=x"),
            expected
        );
        assert_eq!(
            PairLink::parse("koan://join?s=https%3A%2F%2Fa.example&p=x"),
            None
        );
    }

    #[test]
    fn other_links_are_not_pairings() {
        for link in [
            "https://koan.rocks/join/#s=https%3A%2F%2Fa.example&p=x",
            "https://evil.example/pair/#s=https%3A%2F%2Fa.example&p=x",
            "https://koan.rocks/pair/#s=javascript%3Aalert(1)&p=x",
            "https://koan.rocks/pair/#s=https%3A%2F%2Fa.example",
            "https://koan.rocks/pair/#p=x",
        ] {
            assert_eq!(PairLink::parse(link), None, "{link}");
        }
    }

    #[test]
    fn the_socket_address_follows_the_scheme() {
        let url = pair_url("https://music.example.com/koan", "Living room TV").unwrap();
        assert_eq!(
            url.as_str(),
            "wss://music.example.com/koan/rest/koanPair?name=Living+room+TV"
        );
        let url = pair_url("http://10.0.0.2:4533", "tv").unwrap();
        assert_eq!(url.scheme(), "ws");
        assert!(pair_url("ftp://x", "tv").is_err());
    }

    #[test]
    fn info_carries_where_the_request_came_from() {
        let info: crate::remote::client::KoanPair =
            serde_json::from_str(r#"{"device":"Den TV","from":"192.168.1.20","local":true}"#)
                .unwrap();
        assert_eq!((info.from.as_str(), info.local), ("192.168.1.20", true));
    }

    #[test]
    fn messages_are_the_wire_format() {
        let pending: PairMessage = serde_json::from_str(
            r#"{"type":"pending","id":"i","code":"ABCD-EFGH","expiresIn":600}"#,
        )
        .unwrap();
        assert_eq!(
            pending,
            PairMessage::Pending {
                id: "i".into(),
                code: "ABCD-EFGH".into(),
                expires_in: 600
            }
        );
        let approved = PairMessage::Approved {
            username: "alice".into(),
            api_key: "k".into(),
        };
        assert_eq!(
            serde_json::to_string(&approved).unwrap(),
            r#"{"type":"approved","username":"alice","apiKey":"k"}"#
        );
        assert_eq!(
            serde_json::to_string(&PairMessage::Expired).unwrap(),
            r#"{"type":"expired"}"#
        );
    }
}