azalea_client/
account.rs

1//! Connect to Minecraft servers.
2
3use std::sync::Arc;
4
5use azalea_auth::{
6    AccessTokenResponse,
7    certs::{Certificates, FetchCertificatesError},
8};
9use bevy_ecs::component::Component;
10use parking_lot::Mutex;
11use thiserror::Error;
12use tracing::trace;
13use uuid::Uuid;
14
15/// Something that can join Minecraft servers.
16///
17/// To join a server using this account, use [`Client::join`] or
18/// [`azalea::ClientBuilder`].
19///
20/// This is also an ECS component that is present on our client entities.
21///
22/// # Examples
23///
24/// ```rust,no_run
25/// # use azalea_client::Account;
26/// #
27/// # #[tokio::main]
28/// # async fn main() {
29/// let account = Account::microsoft("[email protected]").await;
30/// // or Account::offline("example");
31/// # }
32/// ```
33///
34/// [`Client::join`]: crate::Client::join
35/// [`azalea::ClientBuilder`]: https://docs.rs/azalea/latest/azalea/struct.ClientBuilder.html
36#[derive(Clone, Debug, Component)]
37pub struct Account {
38    /// The Minecraft username of the account.
39    pub username: String,
40    /// The access token for authentication.
41    ///
42    /// You can obtain one of these manually from azalea-auth.
43    ///
44    /// This is an `Arc<Mutex>` so it can be modified by [`Self::refresh`].
45    pub access_token: Option<Arc<Mutex<String>>>,
46    /// Only required for online-mode accounts.
47    pub uuid: Option<Uuid>,
48
49    /// The parameters (i.e. email) that were passed for creating this
50    /// [`Account`].
51    ///
52    /// This is used for automatic reauthentication when we get "Invalid
53    /// Session" errors. If you don't need that feature (like in
54    /// offline mode), then you can set this to `AuthOpts::default()`.
55    pub account_opts: AccountOpts,
56
57    /// The certificates used for chat signing.
58    ///
59    /// This is set when you call [`Self::request_certs`], but you only
60    /// need to if the servers you're joining require it.
61    pub certs: Arc<Mutex<Option<Certificates>>>,
62}
63
64/// The parameters that were passed for creating the associated [`Account`].
65#[derive(Clone, Debug)]
66pub enum AccountOpts {
67    Offline {
68        username: String,
69    },
70    Microsoft {
71        email: String,
72    },
73    MicrosoftWithAccessToken {
74        msa: Arc<Mutex<azalea_auth::cache::ExpiringValue<AccessTokenResponse>>>,
75    },
76}
77
78impl Account {
79    /// An offline account does not authenticate with Microsoft's servers, and
80    /// as such can only join offline mode servers.
81    ///
82    /// This is useful for testing in LAN worlds.
83    pub fn offline(username: &str) -> Self {
84        Self {
85            username: username.to_string(),
86            access_token: None,
87            uuid: None,
88            account_opts: AccountOpts::Offline {
89                username: username.to_string(),
90            },
91            certs: Arc::new(Mutex::new(None)),
92        }
93    }
94
95    /// This will create an online-mode account by authenticating with
96    /// Microsoft's servers.
97    ///
98    /// The cache key is used for avoiding having to log in every time. This is
99    /// typically set to the account email, but it can be any string.
100    pub async fn microsoft(cache_key: &str) -> Result<Self, azalea_auth::AuthError> {
101        Self::microsoft_with_custom_client_id_and_scope(cache_key, None, None).await
102    }
103
104    /// Similar to [`Account::microsoft`] but you can use your own `client_id`
105    /// and `scope`.
106    ///
107    /// Pass `None` if you want to use default ones.
108    pub async fn microsoft_with_custom_client_id_and_scope(
109        cache_key: &str,
110        client_id: Option<&str>,
111        scope: Option<&str>,
112    ) -> Result<Self, azalea_auth::AuthError> {
113        let minecraft_dir = minecraft_folder_path::minecraft_dir().unwrap_or_else(|| {
114            panic!(
115                "No {} environment variable found",
116                minecraft_folder_path::home_env_var()
117            )
118        });
119        let auth_result = azalea_auth::auth(
120            cache_key,
121            azalea_auth::AuthOpts {
122                cache_file: Some(minecraft_dir.join("azalea-auth.json")),
123                client_id,
124                scope,
125                ..Default::default()
126            },
127        )
128        .await?;
129        Ok(Self {
130            username: auth_result.profile.name,
131            access_token: Some(Arc::new(Mutex::new(auth_result.access_token))),
132            uuid: Some(auth_result.profile.id),
133            account_opts: AccountOpts::Microsoft {
134                email: cache_key.to_string(),
135            },
136            // we don't do chat signing by default unless the user asks for it
137            certs: Arc::new(Mutex::new(None)),
138        })
139    }
140
141    /// This will create an online-mode account through
142    /// [`azalea_auth::get_minecraft_token`] so you can have more control over
143    /// the authentication process (like doing your own caching or
144    /// displaying the Microsoft user code to the user in a different way).
145    ///
146    /// This will refresh the given token if it's expired.
147    ///
148    /// ```
149    /// # use azalea_client::Account;
150    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
151    /// let client = reqwest::Client::new();
152    ///
153    /// let res = azalea_auth::get_ms_link_code(&client, None, None).await?;
154    /// // Or, `azalea_auth::get_ms_link_code(&client, Some(client_id), None).await?`
155    /// // if you want to use your own client_id
156    /// println!(
157    ///     "Go to {} and enter the code {}",
158    ///     res.verification_uri, res.user_code
159    /// );
160    /// let msa = azalea_auth::get_ms_auth_token(&client, res, None).await?;
161    /// Account::with_microsoft_access_token(msa).await?;
162    /// # Ok(())
163    /// # }
164    /// ```
165    pub async fn with_microsoft_access_token(
166        msa: azalea_auth::cache::ExpiringValue<AccessTokenResponse>,
167    ) -> Result<Self, azalea_auth::AuthError> {
168        Self::with_microsoft_access_token_and_custom_client_id_and_scope(msa, None, None).await
169    }
170
171    /// Similar to [`Account::with_microsoft_access_token`] but you can use
172    /// custom `client_id` and `scope`.
173    pub async fn with_microsoft_access_token_and_custom_client_id_and_scope(
174        mut msa: azalea_auth::cache::ExpiringValue<AccessTokenResponse>,
175        client_id: Option<&str>,
176        scope: Option<&str>,
177    ) -> Result<Self, azalea_auth::AuthError> {
178        let client = reqwest::Client::new();
179
180        if msa.is_expired() {
181            trace!("refreshing Microsoft auth token");
182            msa = azalea_auth::refresh_ms_auth_token(
183                &client,
184                &msa.data.refresh_token,
185                client_id,
186                scope,
187            )
188            .await?;
189        }
190
191        let msa_token = &msa.data.access_token;
192
193        let res = azalea_auth::get_minecraft_token(&client, msa_token).await?;
194
195        let profile = azalea_auth::get_profile(&client, &res.minecraft_access_token).await?;
196
197        Ok(Self {
198            username: profile.name,
199            access_token: Some(Arc::new(Mutex::new(res.minecraft_access_token))),
200            uuid: Some(profile.id),
201            account_opts: AccountOpts::MicrosoftWithAccessToken {
202                msa: Arc::new(Mutex::new(msa)),
203            },
204            certs: Arc::new(Mutex::new(None)),
205        })
206    }
207    /// Refresh the access_token for this account to be valid again.
208    ///
209    /// This requires the `auth_opts` field to be set correctly (which is done
210    /// by default if you used the constructor functions). Note that if the
211    /// Account is offline-mode then this function won't do anything.
212    pub async fn refresh(&self) -> Result<(), azalea_auth::AuthError> {
213        match &self.account_opts {
214            // offline mode doesn't need to refresh so just don't do anything lol
215            AccountOpts::Offline { .. } => Ok(()),
216            AccountOpts::Microsoft { email } => {
217                let new_account = Account::microsoft(email).await?;
218                let access_token_mutex = self.access_token.as_ref().unwrap();
219                let new_access_token = new_account.access_token.unwrap().lock().clone();
220                *access_token_mutex.lock() = new_access_token;
221                Ok(())
222            }
223            AccountOpts::MicrosoftWithAccessToken { msa } => {
224                let msa_value = msa.lock().clone();
225                let new_account = Account::with_microsoft_access_token(msa_value).await?;
226
227                let access_token_mutex = self.access_token.as_ref().unwrap();
228                let new_access_token = new_account.access_token.unwrap().lock().clone();
229
230                *access_token_mutex.lock() = new_access_token;
231                let AccountOpts::MicrosoftWithAccessToken { msa: new_msa } =
232                    new_account.account_opts
233                else {
234                    unreachable!()
235                };
236                *msa.lock() = new_msa.lock().clone();
237
238                Ok(())
239            }
240        }
241    }
242
243    /// Get the UUID of this account.
244    ///
245    /// If the `uuid` field is None, the UUID will be determined by using
246    /// Minecraft's offline-mode UUIDv3 algorithm.
247    pub fn uuid_or_offline(&self) -> Uuid {
248        self.uuid
249            .unwrap_or_else(|| azalea_auth::offline::generate_uuid(&self.username))
250    }
251}
252
253#[derive(Error, Debug)]
254pub enum RequestCertError {
255    #[error("Failed to fetch certificates")]
256    FetchCertificates(#[from] FetchCertificatesError),
257    #[error("You can't request certificates for an offline account")]
258    NoAccessToken,
259}
260
261impl Account {
262    /// Request the certificates used for chat signing and set it in
263    /// [`Self::certs`].
264    pub async fn request_certs(&mut self) -> Result<(), RequestCertError> {
265        let access_token = self
266            .access_token
267            .as_ref()
268            .ok_or(RequestCertError::NoAccessToken)?
269            .lock()
270            .clone();
271        let certs = azalea_auth::certs::fetch_certificates(&access_token).await?;
272        *self.certs.lock() = Some(certs);
273
274        Ok(())
275    }
276}