aboutsummaryrefslogtreecommitdiff
path: root/azalea-client/src/account/yggdrasil.rs
blob: 9965030d2051b2cc1d4e9ec260bceaa5545cb084 (plain)
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
use std::path::PathBuf;

use azalea_auth::{
    certs::Certificates,
    sessionserver::{self, ClientSessionServerError, SessionServerJoinOpts},
    yggdrasil::{YggdrasilAuthError, YggdrasilAuthOpts, yggdrasil_auth},
};
use parking_lot::Mutex;
use uuid::Uuid;

use crate::account::{Account, AccountTrait, BoxFuture};

fn default_cache_file() -> PathBuf {
    let minecraft_dir = minecraft_folder_path::minecraft_dir().unwrap_or_else(|| {
        panic!(
            "No {} environment variable found",
            minecraft_folder_path::home_env_var()
        )
    });
    minecraft_dir.join("azalea-auth-yggdrasil.json")
}

fn default_auth_opts() -> YggdrasilAuthOpts {
    YggdrasilAuthOpts {
        cache_file: Some(default_cache_file()),
    }
}

#[derive(Debug, Clone)]
pub struct Backend {
    pub auth: String,
    pub session: String,
    pub player: Option<String>,
}

impl Backend {
    pub fn new_drasl(base_url: &str, certs: bool) -> Self {
        Self {
            auth: format!("{base_url}/auth"),
            session: format!("{base_url}/session"),
            player: certs.then(|| format!("{base_url}/player")),
        }
    }
}

/// A type of account that authenticates with an Yggdrasil server using Azalea's
/// cache.
///
/// This type is not intended to be used directly by the user. To actually make
/// an account that authenticates with an Yggdrasil server, see
/// [`Account::yggdrasil`] or [`Account::yggdrasil_with_opts`].
#[derive(Debug)]
pub struct YggdrasilAccount {
    auth_opts: YggdrasilAuthOpts,
    backend: Backend,

    username: String,
    password: Option<String>,
    uuid: Uuid,

    access_token: Mutex<String>,
    certs: Mutex<Option<Certificates>>,
}

impl YggdrasilAccount {
    // deliberately private, use `Account::yggdrasil` or
    // `Account::yggdrasil_with_opts` instead.
    async fn new(
        username: String,
        password: Option<String>,
        backend: Backend,
        auth_opts: YggdrasilAuthOpts,
    ) -> Result<Self, YggdrasilAuthError> {
        let auth_result = yggdrasil_auth(
            &username,
            password.as_deref(),
            &backend.auth,
            auth_opts.clone(),
        )
        .await?;

        Ok(Self {
            username,
            password,
            uuid: auth_result.user.id,
            access_token: Mutex::new(auth_result.access_token),
            certs: Mutex::new(None),
            backend,
            auth_opts,
        })
    }
}
impl AccountTrait for YggdrasilAccount {
    fn username(&self) -> &str {
        &self.username
    }
    fn uuid(&self) -> Uuid {
        self.uuid
    }
    fn access_token(&self) -> Option<String> {
        Some(self.access_token.lock().to_owned())
    }
    fn certs(&self) -> Option<azalea_auth::certs::Certificates> {
        self.certs.lock().as_ref().cloned()
    }
    fn set_certs(&self, certs: azalea_auth::certs::Certificates) {
        *self.certs.lock() = Some(certs);
    }
    fn certs_backend(&self) -> Option<&str> {
        self.backend.player.as_deref()
    }
    fn refresh(&self) -> BoxFuture<'_, Result<(), azalea_auth::AuthError>> {
        Box::pin(async {
            let new_account = YggdrasilAccount::new(
                self.username.clone(),
                self.password.clone(),
                self.backend.clone(),
                self.auth_opts.clone(),
            )
            .await?;
            let new_access_token = new_account.access_token().unwrap();
            *self.access_token.lock() = new_access_token;
            Ok(())
        })
    }
    fn join<'a>(
        &'a self,
        public_key: &'a [u8],
        private_key: &'a [u8; 16],
        server_id: &'a str,
        proxy: Option<reqwest::Proxy>,
    ) -> BoxFuture<'a, Result<(), ClientSessionServerError>> {
        Box::pin(async move {
            let access_token = self.access_token.lock().clone();
            sessionserver::join_with_backend_url(
                SessionServerJoinOpts {
                    access_token: &access_token,
                    public_key,
                    private_key,
                    uuid: &self.uuid(),
                    server_id,
                    proxy,
                },
                &self.backend.session,
            )
            .await
        })
    }
}

impl Account {
    /// This will create an online-mode account by authenticating with
    /// an Yggdrasil server.
    ///
    /// The cache key is used for avoiding having to log in every time. This is
    /// typically set to the account email, but it can be any string.
    #[cfg(feature = "online-mode")]
    pub async fn yggdrasil(username: String, backend: Backend) -> Result<Self, YggdrasilAuthError> {
        YggdrasilAccount::new(username, None, backend, default_auth_opts())
            .await
            .map(Account::from)
    }

    #[cfg(feature = "online-mode")]
    pub async fn yggdrasil_with_password(
        username: String,
        password: String,
        backend: Backend,
    ) -> Result<Self, YggdrasilAuthError> {
        YggdrasilAccount::new(username, Some(password), backend, default_auth_opts())
            .await
            .map(Account::from)
    }

    /// Similar to [`Account::yggdrasil`] but you can pass custom auth options
    /// (including the cache file location).
    ///
    /// For a custom cache directory, set
    /// `auth_opts.cache_file =
    /// Some(custom_dir.join("azalea-auth-yggdrasil.json"))`.
    ///
    /// If `auth_opts.cache_file` is `None`, it will default to Azalea's
    /// standard cache file (`~/.minecraft/azalea-auth-yggdrasil.json`) to match
    /// [`Account::yggdrasil`].
    #[cfg(feature = "online-mode")]
    pub async fn yggdrasil_with_opts(
        username: String,
        password: Option<String>,
        backend: Backend,
        auth_opts: YggdrasilAuthOpts,
    ) -> Result<Self, YggdrasilAuthError> {
        YggdrasilAccount::new(username, password, backend, auth_opts)
            .await
            .map(Account::from)
    }
}