feat: Yandex sign-in with device code, keychain storage and account status
- 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
This commit is contained in:
1 parent
c4928ae7fe
commit
43e8f86a5d
17 files changed
+2811
-127
No files matched your search
@@ -0,0 +1,207 @@
|
||||
//! 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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
use crate::Result;
|
||||
use crate::auth::Credentials;
|
||||
|
||||
/// The signed-in user as the UI needs them.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Account {
|
||||
pub uid: i64,
|
||||
pub login: String,
|
||||
/// Best human-readable name: display name, then full name, then login.
|
||||
pub name: String,
|
||||
/// Yandex Plus unlocks full-length tracks; without it the API serves 30-second previews.
|
||||
pub has_plus: bool,
|
||||
/// When the current subscription ends, as Yandex formats it (ISO 8601).
|
||||
pub subscription_end: Option<String>,
|
||||
}
|
||||
|
||||
impl Account {
|
||||
/// One letter for the avatar.
|
||||
pub fn initial(&self) -> char {
|
||||
self.name.chars().find(|c| c.is_alphanumeric()).map_or('?', |c| {
|
||||
c.to_uppercase().next().unwrap_or(c)
|
||||
})
|
||||
}
|
||||
|
||||
fn from_status(status: yamuse::models::Status) -> Option<Self> {
|
||||
let account = status.account?;
|
||||
let uid = account.uid?;
|
||||
let login = account.login.unwrap_or_default();
|
||||
let non_empty = |s: Option<String>| s.filter(|s| !s.trim().is_empty());
|
||||
let name = non_empty(account.display_name)
|
||||
.or_else(|| non_empty(account.full_name))
|
||||
.unwrap_or_else(|| login.clone());
|
||||
Some(Self {
|
||||
uid,
|
||||
login,
|
||||
name,
|
||||
has_plus: status.plus.and_then(|p| p.has_plus).unwrap_or(false),
|
||||
subscription_end: status.subscription.and_then(|s| {
|
||||
s.end.or_else(|| s.auto_renewable.into_iter().find_map(|a| a.expires))
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An authenticated API client. Cheap to clone.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct YmClient {
|
||||
inner: yamuse::Client,
|
||||
}
|
||||
|
||||
impl YmClient {
|
||||
/// Builds a client for `credentials` and loads the account. Fails with
|
||||
/// [`crate::Error::Unauthorized`] when the token is no longer valid.
|
||||
pub async fn connect(credentials: &Credentials) -> Result<(Self, Account)> {
|
||||
let inner = yamuse::Client::builder().token(&credentials.access_token).build()?;
|
||||
let status = inner.refresh_account().await?;
|
||||
let account = Account::from_status(status)
|
||||
.ok_or_else(|| crate::Error::Unauthorized("account status has no user".into()))?;
|
||||
Ok((Self { inner }, account))
|
||||
}
|
||||
|
||||
/// A client with no token, for previews and tests. Every account call fails.
|
||||
pub fn unauthenticated() -> Result<Self> {
|
||||
Ok(Self { inner: yamuse::Client::anonymous()? })
|
||||
}
|
||||
|
||||
/// Re-reads the account, e.g. after a subscription may have changed.
|
||||
pub async fn account(&self) -> Result<Account> {
|
||||
let status = self.inner.refresh_account().await?;
|
||||
Account::from_status(status)
|
||||
.ok_or_else(|| crate::Error::Unauthorized("account status has no user".into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn status(json: &str) -> yamuse::models::Status {
|
||||
serde_json::from_str(json).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_prefers_display_name_and_reads_plus() {
|
||||
let a = Account::from_status(status(
|
||||
r#"{"account":{"uid":42,"login":"yuriy.panov","displayName":"Юрий","fullName":"Юрий Панов"},
|
||||
"plus":{"hasPlus":true},"subscription":{"end":"2027-01-01T00:00:00+03:00"}}"#,
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(a.uid, 42);
|
||||
assert_eq!(a.name, "Юрий");
|
||||
assert_eq!(a.initial(), 'Ю');
|
||||
assert!(a.has_plus);
|
||||
assert_eq!(a.subscription_end.as_deref(), Some("2027-01-01T00:00:00+03:00"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_falls_back_to_login_and_no_plus() {
|
||||
let a = Account::from_status(status(
|
||||
r#"{"account":{"uid":7,"login":"listener","displayName":" "}}"#,
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(a.name, "listener");
|
||||
assert!(!a.has_plus);
|
||||
assert_eq!(a.subscription_end, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anonymous_status_is_not_an_account() {
|
||||
assert!(Account::from_status(status(r#"{"account":{"now":"2026-10-15"}}"#)).is_none());
|
||||
assert!(Account::from_status(status("{}")).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/// Errors the app can act on. Messages are for logs, not for display.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// The token is missing, revoked or expired. Sign in again.
|
||||
#[error("unauthorized: {0}")]
|
||||
Unauthorized(String),
|
||||
/// The sign-in code ran out before the user confirmed it.
|
||||
#[error("sign-in code expired")]
|
||||
CodeExpired,
|
||||
/// The user declined access on Yandex's page.
|
||||
#[error("sign-in was declined")]
|
||||
Denied,
|
||||
/// No connection, DNS failure, timeout: worth retrying.
|
||||
#[error("network: {0}")]
|
||||
Network(String),
|
||||
/// Anything else the server or the decoder rejected.
|
||||
#[error("api: {0}")]
|
||||
Api(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
impl Error {
|
||||
pub fn is_retryable(&self) -> bool {
|
||||
matches!(self, Error::Network(_))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<yamuse::Error> for Error {
|
||||
fn from(e: yamuse::Error) -> Self {
|
||||
use yamuse::Error as Y;
|
||||
match e {
|
||||
Y::Unauthorized(m) => Error::Unauthorized(m),
|
||||
Y::Network(m) => Error::Network(m),
|
||||
Y::TimedOut => Error::Network("timed out".into()),
|
||||
Y::RateLimited { message, .. } => Error::Network(message),
|
||||
Y::DeviceAuth(m) => classify_oauth(&m),
|
||||
other => Error::Api(other.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// OAuth rejections arrive as free text carrying the RFC 8628 error code.
|
||||
fn classify_oauth(message: &str) -> Error {
|
||||
let m = message.to_ascii_lowercase();
|
||||
if m.contains("expired") || m.contains("timed out") {
|
||||
Error::CodeExpired
|
||||
} else if m.contains("denied") {
|
||||
Error::Denied
|
||||
} else if m.contains("invalid_grant") || m.contains("bad refresh") {
|
||||
Error::Unauthorized(message.to_owned())
|
||||
} else {
|
||||
Error::Api(message.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn oauth_codes_map_to_actionable_errors() {
|
||||
assert_eq!(classify_oauth("expired_token: code expired"), Error::CodeExpired);
|
||||
assert_eq!(classify_oauth("device authorization timed out"), Error::CodeExpired);
|
||||
assert_eq!(classify_oauth("access_denied"), Error::Denied);
|
||||
assert!(matches!(classify_oauth("invalid_grant"), Error::Unauthorized(_)));
|
||||
assert!(matches!(classify_oauth("something new"), Error::Api(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_network_errors_retry() {
|
||||
assert!(Error::Network("dns".into()).is_retryable());
|
||||
assert!(!Error::Unauthorized(String::new()).is_retryable());
|
||||
assert!(!Error::CodeExpired.is_retryable());
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,11 @@
|
||||
//! Client for the unofficial Yandex Music API.
|
||||
//!
|
||||
//! Filled in by milestone 3 (sign-in) onwards; the app depends on this crate's
|
||||
//! own types only, never on whichever upstream wrapper it uses internally.
|
||||
//! Wraps [`yamuse`] so the app only ever sees this crate's own types: if the
|
||||
//! upstream wrapper changes or is swapped out, the UI doesn't move.
|
||||
|
||||
pub mod auth;
|
||||
mod client;
|
||||
mod error;
|
||||
|
||||
pub use client::{Account, YmClient};
|
||||
pub use error::{Error, Result};
|
||||
Reference in new issue
Block a user