- ym-api wraps yamuse: device-code flow, token refresh, account status, and its own Error type that the UI acts on (expired, denied, network) - Credentials live in the system keychain, never print their tokens, and refresh when within a week of expiry; a rejected token is forgotten - Sign-in screen with code, QR, copy/open-in-browser, countdown and a pasted-token fallback; restoring/unreachable screens on startup - Sidebar account chip and Settings account card with Plus status and sign-out; Settings re-reads the account when opened - Live device-code test behind --ignored
208 lines
7.7 KiB
Rust
208 lines
7.7 KiB
Rust
//! Yandex OAuth device flow: show a code, the user confirms it on Yandex's
|
|
//! page, poll until a token arrives.
|
|
//!
|
|
//! Uses the official Android app's public client id (via `yamuse`), because
|
|
//! third parties can't register an app for the music API.
|
|
|
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use crate::{Error, Result};
|
|
|
|
/// Shown on Yandex's list of signed-in devices.
|
|
const DEVICE_NAME: &str = "Musyx";
|
|
/// Yandex rate-limits polling; faster than this turns a pending login into a rejected one.
|
|
const MIN_POLL: Duration = Duration::from_secs(3);
|
|
/// Refresh once less than this much lifetime is left.
|
|
const REFRESH_MARGIN: Duration = Duration::from_secs(7 * 24 * 3600);
|
|
|
|
/// A pending sign-in: what to show the user and what to poll with.
|
|
#[derive(Clone, PartialEq, Eq)]
|
|
pub struct DeviceCode {
|
|
pub user_code: String,
|
|
pub verification_url: String,
|
|
pub expires_in: Duration,
|
|
pub interval: Duration,
|
|
device_code: String,
|
|
}
|
|
|
|
impl std::fmt::Debug for DeviceCode {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
f.debug_struct("DeviceCode")
|
|
.field("user_code", &self.user_code)
|
|
.field("verification_url", &self.verification_url)
|
|
.field("expires_in", &self.expires_in)
|
|
.field("interval", &self.interval)
|
|
.finish_non_exhaustive()
|
|
}
|
|
}
|
|
|
|
/// What the keychain stores. `Debug` never prints the tokens.
|
|
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct Credentials {
|
|
pub access_token: String,
|
|
#[serde(default)]
|
|
pub refresh_token: Option<String>,
|
|
/// Unix seconds; `None` when Yandex didn't say (pasted tokens).
|
|
#[serde(default)]
|
|
pub expires_at: Option<u64>,
|
|
}
|
|
|
|
impl std::fmt::Debug for Credentials {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
f.debug_struct("Credentials")
|
|
.field("access_token", &"<redacted>")
|
|
.field("refresh_token", &self.refresh_token.as_ref().map(|_| "<redacted>"))
|
|
.field("expires_at", &self.expires_at)
|
|
.finish()
|
|
}
|
|
}
|
|
|
|
impl Credentials {
|
|
/// A token the user pasted. Its lifetime is unknown, so it is never refreshed.
|
|
pub fn from_token(token: impl Into<String>) -> Self {
|
|
Self { access_token: token.into().trim().to_owned(), refresh_token: None, expires_at: None }
|
|
}
|
|
|
|
/// True when the token expires within a week and can be refreshed.
|
|
pub fn needs_refresh(&self, now: SystemTime) -> bool {
|
|
let (Some(_), Some(expires_at)) = (&self.refresh_token, self.expires_at) else {
|
|
return false;
|
|
};
|
|
let now = now.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
|
|
expires_at.saturating_sub(now) < REFRESH_MARGIN.as_secs()
|
|
}
|
|
|
|
fn from_oauth(token: yamuse::models::OAuthToken, now: SystemTime) -> Result<Self> {
|
|
let access_token = token
|
|
.access_token
|
|
.filter(|t| !t.is_empty())
|
|
.ok_or_else(|| Error::Api("token response carried no access token".into()))?;
|
|
let now = now.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
|
|
Ok(Self {
|
|
access_token,
|
|
refresh_token: token.refresh_token.filter(|t| !t.is_empty()),
|
|
expires_at: token.expires_in.map(|s| now + s),
|
|
})
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum Poll {
|
|
/// The user hasn't confirmed yet. Keep polling at `DeviceCode::interval`.
|
|
Pending,
|
|
Granted(Credentials),
|
|
}
|
|
|
|
/// Talks to oauth.yandex.ru. Cheap to clone.
|
|
#[derive(Debug, Clone)]
|
|
pub struct Auth {
|
|
client: yamuse::Client,
|
|
options: yamuse::DeviceAuthOptions,
|
|
}
|
|
|
|
impl Auth {
|
|
pub fn new() -> Result<Self> {
|
|
Ok(Self {
|
|
client: yamuse::Client::anonymous()?,
|
|
options: yamuse::DeviceAuthOptions {
|
|
device_name: DEVICE_NAME.to_owned(),
|
|
..Default::default()
|
|
},
|
|
})
|
|
}
|
|
|
|
pub async fn request_code(&self) -> Result<DeviceCode> {
|
|
let code = self.client.request_device_code(&self.options).await?;
|
|
let missing = |what: &str| Error::Api(format!("device code response carried no {what}"));
|
|
Ok(DeviceCode {
|
|
device_code: code.device_code.ok_or_else(|| missing("device code"))?,
|
|
user_code: code.user_code.ok_or_else(|| missing("user code"))?,
|
|
verification_url: code
|
|
.verification_url
|
|
.unwrap_or_else(|| "https://ya.ru/device".to_owned()),
|
|
expires_in: Duration::from_secs(code.expires_in.unwrap_or(300)),
|
|
interval: Duration::from_secs(code.interval.unwrap_or(5)).max(MIN_POLL),
|
|
})
|
|
}
|
|
|
|
/// Poll once. `Pending` is the normal answer until the user confirms.
|
|
pub async fn poll(&self, code: &DeviceCode) -> Result<Poll> {
|
|
match self.client.poll_device_token(&code.device_code, &self.options).await? {
|
|
None => Ok(Poll::Pending),
|
|
Some(token) => Ok(Poll::Granted(Credentials::from_oauth(token, SystemTime::now())?)),
|
|
}
|
|
}
|
|
|
|
/// Swap a refresh token for a new pair. Store the result: Yandex rotates the refresh token.
|
|
pub async fn refresh(&self, credentials: &Credentials) -> Result<Credentials> {
|
|
let refresh = credentials
|
|
.refresh_token
|
|
.as_deref()
|
|
.ok_or_else(|| Error::Unauthorized("no refresh token".into()))?;
|
|
let token = self.client.refresh_token(refresh, &self.options).await?;
|
|
let mut fresh = Credentials::from_oauth(token, SystemTime::now())?;
|
|
// Keep the old refresh token if Yandex didn't rotate it.
|
|
if fresh.refresh_token.is_none() {
|
|
fresh.refresh_token = credentials.refresh_token.clone();
|
|
}
|
|
Ok(fresh)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn at(secs: u64) -> SystemTime {
|
|
UNIX_EPOCH + Duration::from_secs(secs)
|
|
}
|
|
|
|
#[test]
|
|
fn debug_never_prints_tokens() {
|
|
let c = Credentials {
|
|
access_token: "secret-access".into(),
|
|
refresh_token: Some("secret-refresh".into()),
|
|
expires_at: Some(10),
|
|
};
|
|
let shown = format!("{c:?}");
|
|
assert!(!shown.contains("secret"), "{shown}");
|
|
}
|
|
|
|
#[test]
|
|
fn credentials_round_trip_and_tolerate_old_shape() {
|
|
let c = Credentials { access_token: "a".into(), refresh_token: Some("r".into()), expires_at: Some(5) };
|
|
let json = serde_json::to_string(&c).unwrap();
|
|
assert_eq!(serde_json::from_str::<Credentials>(&json).unwrap(), c);
|
|
let bare: Credentials = serde_json::from_str(r#"{"access_token":"a"}"#).unwrap();
|
|
assert_eq!(bare, Credentials::from_token("a"));
|
|
}
|
|
|
|
#[test]
|
|
fn refresh_only_near_expiry_and_only_with_refresh_token() {
|
|
let week = 7 * 24 * 3600;
|
|
let c = Credentials { access_token: "a".into(), refresh_token: Some("r".into()), expires_at: Some(10 * week) };
|
|
assert!(!c.needs_refresh(at(8 * week)));
|
|
assert!(c.needs_refresh(at(9 * week + 1)));
|
|
assert!(c.needs_refresh(at(11 * week)));
|
|
let pasted = Credentials::from_token(" a \n");
|
|
assert_eq!(pasted.access_token, "a");
|
|
assert!(!pasted.needs_refresh(at(u64::MAX / 2)));
|
|
}
|
|
|
|
#[test]
|
|
fn oauth_token_converts_with_absolute_expiry() {
|
|
let token = yamuse::models::OAuthToken {
|
|
access_token: Some("a".into()),
|
|
refresh_token: Some(String::new()),
|
|
expires_in: Some(100),
|
|
token_type: Some("bearer".into()),
|
|
};
|
|
let c = Credentials::from_oauth(token, at(1_000)).unwrap();
|
|
assert_eq!(c.expires_at, Some(1_100));
|
|
assert_eq!(c.refresh_token, None);
|
|
assert!(Credentials::from_oauth(Default::default(), at(0)).is_err());
|
|
}
|
|
}
|