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
|
mod types;
mod oauth;
mod msa;
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::future::Future;
use std::ops::Add;
use std::time::{Duration, Instant, SystemTime};
use chrono::{DateTime, NaiveDateTime, TimeDelta, Utc};
use oauth2::{AccessToken, AuthType, AuthUrl, ClientId, DeviceAuthorizationResponse, DeviceAuthorizationUrl, DeviceCodeErrorResponse, EmptyExtraDeviceAuthorizationFields, EndpointNotSet, EndpointSet, HttpClientError, RefreshToken, RequestTokenError, Scope, StandardDeviceAuthorizationResponse, StandardRevocableToken, StandardTokenResponse, TokenResponse, TokenUrl};
use oauth2::basic::{BasicErrorResponse, BasicRevocationErrorResponse, BasicTokenIntrospectionResponse, BasicTokenResponse};
pub use types::*;
#[derive(Debug)]
pub enum AuthError {
Request { what: &'static str, error: reqwest::Error },
OAuthRequestToken { what: &'static str, error: RequestTokenError<HttpClientError<reqwest::Error>, BasicErrorResponse> },
OAuthRequestDeviceCode { what: &'static str, error: RequestTokenError<HttpClientError<reqwest::Error>, DeviceCodeErrorResponse> },
Internal(String),
Cancel(Option<Box<dyn Error>>),
Timeout
}
impl Display for AuthError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
AuthError::Request { what, error } => write!(f, "auth request error ({}): {}", what, error),
AuthError::OAuthRequestToken { what, error } => write!(f, "oauth error requesting token ({what}): {error}"),
AuthError::OAuthRequestDeviceCode { what, error } => write!(f, "oauth error with device code ({what}): {error}"),
AuthError::Internal(msg) => write!(f, "internal auth error: {}", msg),
AuthError::Cancel(Some(error)) => write!(f, "operation cancelled: {error}"),
AuthError::Cancel(None) => f.write_str("operation cancelled"),
AuthError::Timeout => f.write_str("interactive authentication timed out")
}
}
}
impl Error for AuthError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
AuthError::Request { error, .. } => Some(error),
AuthError::OAuthRequestToken { error, .. } => Some(error),
AuthError::OAuthRequestDeviceCode { error, .. } => Some(error),
AuthError::Cancel(Some(error)) => Some(error.as_ref()),
_ => None
}
}
}
impl Token {
fn is_expired(&self, now: DateTime<Utc>) -> bool {
self.expire.is_some_and(|exp| now < exp)
}
}
macro_rules! create_oauth_client {
($is_azure_client_id:expr, $client_id:expr) => {
oauth2::Client::new($client_id)
.set_token_uri(TokenUrl::new(if $is_azure_client_id { AZURE_TOKEN_URL.into() } else { NON_AZURE_TOKEN_URL.into() }).expect("hardcoded url"))
.set_device_authorization_url(DeviceAuthorizationUrl::new(if $is_azure_client_id { AZURE_TOKEN_URL.into() } else { NON_AZURE_TOKEN_URL.into() }).expect("hardcoded url"))
as oauth2::Client<BasicErrorResponse, BasicTokenResponse, BasicTokenIntrospectionResponse, StandardRevocableToken, BasicRevocationErrorResponse,
EndpointNotSet, EndpointSet, EndpointNotSet, EndpointNotSet, EndpointSet>
}
}
const AZURE_TOKEN_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token";
const AZURE_DEVICE_CODE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token";
const NON_AZURE_TOKEN_URL: &str = "https://login.live.com/oauth20_token.srf";
const NON_AZURE_DEVICE_CODE_URL: &str = "https://login.live.com/oauth20_connect.srf";
const AZURE_LOGIN_SCOPES: &[&str] = ["XboxLive.signin", "offline_access"].as_slice();
const NON_AZURE_LOGIN_SCOPES: &[&str] = ["service::user.auth.xboxlive.com::MBI_SSL"].as_slice();
impl MsaUser {
pub fn create_client() -> reqwest::Client {
reqwest::ClientBuilder::new()
.redirect(reqwest::redirect::Policy::none())
.build().expect("building client should succeed")
}
fn scopes_iter(&self) -> impl Iterator<Item = Scope> {
let to_scope = |f: &&str| Scope::new(String::from(*f));
if self.is_azure_client_id {
AZURE_LOGIN_SCOPES.iter().map(to_scope)
} else {
NON_AZURE_LOGIN_SCOPES.iter().map(to_scope)
}
}
// uses an access token from, for example, a device code grant logs into xbox live
async fn xbl_login(&mut self, token: &AccessToken) -> Result<(), AuthError> {
}
// logs into xbox live using a refresh token
// (panics if no refresh token present)
async fn xbl_login_refresh(&mut self, client: &reqwest::Client) -> Result<(), AuthError> {
let oauth_client = create_oauth_client!(self.is_azure_client_id, self.client_id.clone());
let refresh_token = self.refresh_token.as_ref().expect("refresh_access_token called with no refresh token");
let tokenres: BasicTokenResponse = oauth_client
.exchange_refresh_token(refresh_token)
.add_scopes(self.scopes_iter())
.request_async(client)
.await.map_err(|e| AuthError::OAuthRequestToken { what: "refresh", error: e })?;
self.refresh_token = tokenres.refresh_token().cloned();
self.xbl_login(tokenres.access_token()).await
}
async fn xbl_login_device<D, DF>(&mut self, client: &reqwest::Client, handle_device: D) -> Result<(), AuthError>
where
D: FnOnce(&StandardDeviceAuthorizationResponse) -> DF,
DF: Future<Output = ()>
{
let oauth_client = create_oauth_client!(self.is_azure_client_id, self.client_id.clone());
let device_auth: StandardDeviceAuthorizationResponse = oauth_client.exchange_device_code().add_scopes(self.scopes_iter())
.request_async(client)
.await.map_err(|e| AuthError::OAuthRequestToken { what: "device code", error: e })?;
handle_device(&device_auth).await;
let tokenres = oauth_client.exchange_device_access_token(&device_auth)
.set_max_backoff_interval(Duration::from_secs(20u64))
.request_async(client, tokio::time::sleep, None)
.await.map_err(|e| AuthError::OAuthRequestDeviceCode { what: "device access code", error: e })?;
self.refresh_token = tokenres.refresh_token().cloned();
self.xbl_login(tokenres.access_token()).await
}
// ensure we have an xbox live token for this person
// tasks for this function:
// - check if the XBL token is valid/not expired
// - if it is expired, try to use refresh token to get a new one
// - get rid of auth token if yeah
async fn ensure_xbl(&mut self, client: &reqwest::Client) -> Result<(), AuthError> {
todo!()
}
async fn log_in_silent(&mut self, client: &reqwest::Client) -> Result<(), AuthError> {
let now: DateTime<Utc> = SystemTime::now().into();
if self.auth_token.as_ref().is_some_and(|tok| !tok.is_expired(now.add(TimeDelta::hours(12)))) {
}
todo!()
}
}
#[cfg(test)]
mod test {
use reqwest::Client;
use crate::auth::oauth::device_code;
use super::*;
#[tokio::test]
async fn abc() {
simple_logger::SimpleLogger::new().with_colors(true).with_level(log::LevelFilter::Trace).init().unwrap();
let mut user: MsaUser = MsaUser {
profile: None,
xuid: None,
client_id: ClientId::new("00000000402b5328".into()),
is_azure_client_id: false,
auth_token: None,
xbl_token: None,
refresh_token: None
};
let client = MsaUser::create_client();
user.xbl_login_device(&client, |d| {
dbg!(d);
futures::future::ready(())
}).await.unwrap();
}
}
|