mcapi 0.2.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, Java Runtimes, and SLP)
Documentation
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::time::Duration;

use reqwest::header::{ACCEPT, HeaderValue};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use super::models::auth::{
    DeviceCodePollStatus, DeviceCodeResponse, MinecraftAuthResponse, MinecraftLoginSession,
    MsOAuthTokenResponse, PkcePair, XboxLiveToken, XstsToken,
};
use super::{
    DEFAULT_MINECRAFT_SERVICES_URL, DEFAULT_MS_OAUTH_URL, DEFAULT_XBL_AUTH_URL,
    DEFAULT_XSTS_AUTH_URL, MojangClient, XstsError, XstsErrorKind,
};
use crate::error::{Error, Result};

const XBOX_LIVE_SCOPE: &str = "XboxLive.signin offline_access";
const ACCEPT_JSON: HeaderValue = HeaderValue::from_static("application/json");

#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct XboxAuthResponseRaw {
    issue_instant: String,
    not_after: String,
    token: String,
    display_claims: XboxDisplayClaims,
}

#[derive(Deserialize)]
struct XboxDisplayClaims {
    #[serde(default)]
    xui: Vec<XboxXuiClaim>,
}

#[derive(Deserialize)]
struct XboxXuiClaim {
    #[serde(default)]
    uhs: String,
}

impl XboxAuthResponseRaw {
    fn into_parts(self) -> Result<(String, String, String, String)> {
        let user_hash = self
            .display_claims
            .xui
            .into_iter()
            .next()
            .map(|c| c.uhs)
            .filter(|uhs| !uhs.trim().is_empty())
            .ok_or(Error::MissingUserHash)?;
        Ok((self.token, user_hash, self.issue_instant, self.not_after))
    }
}

#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct XstsErrorRaw {
    #[serde(rename = "XErr")]
    x_err: u64,
    #[serde(default)]
    message: String,
    #[serde(default)]
    redirect: Option<String>,
}

#[derive(Deserialize)]
struct MsTokenErrorBody {
    error: String,
    #[serde(default)]
    error_description: Option<String>,
}

#[derive(Serialize)]
#[serde(rename_all = "PascalCase")]
struct XboxAuthRequest<'a, P: Serialize> {
    properties: P,
    relying_party: &'a str,
    token_type: &'a str,
}

#[derive(Serialize)]
#[serde(rename_all = "PascalCase")]
struct XblProperties<'a> {
    auth_method: &'a str,
    site_name: &'a str,
    rps_ticket: &'a str,
}

#[derive(Serialize)]
#[serde(rename_all = "PascalCase")]
struct XstsProperties<'a> {
    sandbox_id: &'a str,
    user_tokens: [&'a str; 1],
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct MinecraftXboxLoginBody<'a> {
    identity_token: &'a str,
}

impl MojangClient {
    async fn post_ms_form<F: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        form: &F,
    ) -> Result<T> {
        let url = self.url(DEFAULT_MS_OAUTH_URL, path);
        let resp = self
            .http
            .send_direct(&url, |client, target| client.post(target).form(form))
            .await?;
        Ok(resp.json().await?)
    }

    /// Starts the Microsoft OAuth2 Device Code flow via
    /// `POST /consumers/oauth2/v2.0/devicecode`
    /// (RFC 8628, <https://datatracker.ietf.org/doc/html/rfc8628>).
    pub async fn request_ms_device_code(&self, client_id: &str) -> Result<DeviceCodeResponse> {
        self.post_ms_form(
            "/consumers/oauth2/v2.0/devicecode",
            &[("client_id", client_id), ("scope", XBOX_LIVE_SCOPE)],
        )
        .await
    }

    /// Performs a single poll of the Microsoft OAuth2 token endpoint for a device code.
    pub async fn poll_ms_device_code_once(
        &self,
        client_id: &str,
        device_code: &str,
    ) -> Result<DeviceCodePollStatus> {
        let url = self.url(DEFAULT_MS_OAUTH_URL, "/consumers/oauth2/v2.0/token");
        let form = [
            ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
            ("client_id", client_id),
            ("device_code", device_code),
        ];

        match self
            .http
            .send_direct(&url, |client, target| client.post(target).form(&form))
            .await
        {
            Ok(resp) => Ok(DeviceCodePollStatus::Authorized(resp.json().await?)),
            Err(Error::ApiStatus {
                status, ref body, ..
            }) => {
                if let Ok(parsed) = serde_json::from_str::<MsTokenErrorBody>(body) {
                    match parsed.error.as_str() {
                        "authorization_pending" => Ok(DeviceCodePollStatus::Pending),
                        "slow_down" => Ok(DeviceCodePollStatus::SlowDown),
                        "expired_token" => Err(Error::DeviceCodeExpired),
                        "authorization_declined" => Err(Error::DeviceCodeDeclined),
                        _ => Err(Error::InvalidInput(
                            parsed.error_description.unwrap_or(parsed.error),
                        )),
                    }
                } else {
                    Err(Error::ApiStatus {
                        status,
                        url,
                        message: "unexpected OAuth token polling response".to_string(),
                        body: body.clone(),
                    })
                }
            }
            Err(err) => Err(err),
        }
    }

    /// Polls Microsoft OAuth2 until the user authorizes, declines, or the device code expires.
    pub async fn wait_for_ms_device_code(
        &self,
        client_id: &str,
        device: &DeviceCodeResponse,
    ) -> Result<MsOAuthTokenResponse> {
        let mut interval = Duration::from_secs(device.interval.clamp(1, 300));
        let deadline =
            tokio::time::Instant::now() + Duration::from_secs(device.expires_in.clamp(1, 86_400));

        loop {
            if tokio::time::Instant::now() >= deadline {
                return Err(Error::DeviceCodeExpired);
            }
            tokio::time::sleep(interval).await;

            match self
                .poll_ms_device_code_once(client_id, &device.device_code)
                .await?
            {
                DeviceCodePollStatus::Authorized(tokens) => return Ok(tokens),
                DeviceCodePollStatus::Pending => {}
                DeviceCodePollStatus::SlowDown => {
                    interval = (interval + Duration::from_secs(5)).min(Duration::from_secs(300));
                }
            }
        }
    }

    /// Builds the interactive Microsoft OAuth2 authorization URL (`GET /consumers/oauth2/v2.0/authorize`)
    /// with optional RFC 7636 `S256` PKCE challenge (<https://datatracker.ietf.org/doc/html/rfc7636>)
    /// and CSRF `state`.
    pub fn build_ms_authorize_url(
        &self,
        client_id: &str,
        redirect_uri: &str,
        pkce: Option<&PkcePair>,
        state: Option<&str>,
    ) -> Result<url::Url> {
        let mut url =
            url::Url::parse(&self.url(DEFAULT_MS_OAUTH_URL, "/consumers/oauth2/v2.0/authorize"))?;
        {
            let mut pairs = url.query_pairs_mut();
            pairs.append_pair("client_id", client_id);
            pairs.append_pair("response_type", "code");
            pairs.append_pair("redirect_uri", redirect_uri);
            pairs.append_pair("scope", XBOX_LIVE_SCOPE);
            if let Some(pair) = pkce {
                pairs.append_pair("code_challenge", &pair.code_challenge);
                pairs.append_pair("code_challenge_method", "S256");
            }
            if let Some(st) = state {
                pairs.append_pair("state", st);
            }
        }
        Ok(url)
    }

    /// Exchanges an OAuth2 authorization code for Microsoft tokens.
    pub async fn exchange_ms_auth_code(
        &self,
        client_id: &str,
        code: &str,
        redirect_uri: &str,
        code_verifier: Option<&str>,
    ) -> Result<MsOAuthTokenResponse> {
        let mut form = vec![
            ("client_id", client_id),
            ("grant_type", "authorization_code"),
            ("code", code),
            ("redirect_uri", redirect_uri),
            ("scope", XBOX_LIVE_SCOPE),
        ];
        if let Some(verifier) = code_verifier {
            form.push(("code_verifier", verifier));
        }
        self.post_ms_form("/consumers/oauth2/v2.0/token", &form)
            .await
    }

    /// Refreshes Microsoft OAuth2 tokens using a `refresh_token`.
    pub async fn refresh_ms_token(
        &self,
        client_id: &str,
        refresh_token: &str,
    ) -> Result<MsOAuthTokenResponse> {
        self.post_ms_form(
            "/consumers/oauth2/v2.0/token",
            &[
                ("client_id", client_id),
                ("grant_type", "refresh_token"),
                ("refresh_token", refresh_token),
                ("scope", XBOX_LIVE_SCOPE),
            ],
        )
        .await
    }

    /// Authenticates with Xbox Live User Auth (`POST /user/authenticate`)
    /// per <https://minecraft.wiki/w/Microsoft_authentication>.
    pub async fn authenticate_xbox_live(&self, ms_access_token: &str) -> Result<XboxLiveToken> {
        let url = self.url(DEFAULT_XBL_AUTH_URL, "/user/authenticate");
        let ticket = format!("d={ms_access_token}");
        let body = XboxAuthRequest {
            properties: XblProperties {
                auth_method: "RPS",
                site_name: "user.auth.xboxlive.com",
                rps_ticket: &ticket,
            },
            relying_party: "http://auth.xboxlive.com",
            token_type: "JWT",
        };

        let resp = self
            .http
            .send_direct(&url, |client, target| {
                client.post(target).header(ACCEPT, ACCEPT_JSON).json(&body)
            })
            .await?;
        let (token, user_hash, issue_instant, not_after) =
            resp.json::<XboxAuthResponseRaw>().await?.into_parts()?;

        Ok(XboxLiveToken {
            token,
            user_hash,
            issue_instant,
            not_after,
        })
    }

    /// Authorizes an XSTS token for Minecraft Services (`POST /xsts/authorize`),
    /// parsing known `XErr` rejection codes into [`Error::XstsRejected`].
    pub async fn authorize_xsts(&self, xbl_token: &str) -> Result<XstsToken> {
        let url = self.url(DEFAULT_XSTS_AUTH_URL, "/xsts/authorize");
        let body = XboxAuthRequest {
            properties: XstsProperties {
                sandbox_id: "RETAIL",
                user_tokens: [xbl_token],
            },
            relying_party: "rp://api.minecraftservices.com/",
            token_type: "JWT",
        };

        let resp = match self
            .http
            .send_direct(&url, |client, target| {
                client.post(target).header(ACCEPT, ACCEPT_JSON).json(&body)
            })
            .await
        {
            Ok(resp) => resp,
            Err(Error::ApiStatus {
                status: status @ (400 | 401 | 403),
                ref body,
                ..
            }) => {
                if let Ok(raw_err) = serde_json::from_str::<XstsErrorRaw>(body) {
                    return Err(Error::XstsRejected(XstsError {
                        xerr: raw_err.x_err,
                        kind: XstsErrorKind::from_xerr(raw_err.x_err),
                        message: raw_err.message,
                        redirect: raw_err.redirect,
                    }));
                }
                return Err(Error::ApiStatus {
                    status,
                    url,
                    message: "XSTS unauthorized".to_string(),
                    body: body.clone(),
                });
            }
            Err(err) => return Err(err),
        };

        let (token, user_hash, issue_instant, not_after) =
            resp.json::<XboxAuthResponseRaw>().await?.into_parts()?;

        Ok(XstsToken {
            token,
            user_hash,
            issue_instant,
            not_after,
        })
    }

    /// Exchanges Xbox Live `uhs` and `xsts_token` for a Minecraft Services access token
    /// via `POST /authentication/login_with_xbox`.
    pub async fn login_with_xbox(
        &self,
        user_hash: &str,
        xsts_token: &str,
    ) -> Result<MinecraftAuthResponse> {
        let url = self.url(
            DEFAULT_MINECRAFT_SERVICES_URL,
            "/authentication/login_with_xbox",
        );
        let identity_token = format!("XBL3.0 x={user_hash};{xsts_token}");
        self.http
            .post_direct_json(
                &url,
                &MinecraftXboxLoginBody {
                    identity_token: &identity_token,
                },
            )
            .await
    }

    /// Executes the full authentication chain from an existing Microsoft OAuth access token:
    /// Xbox Live → XSTS → `login_with_xbox` → optional entitlement verification → profile fetch.
    ///
    /// If the account owns Minecraft but has not yet created a Java Edition profile
    /// (`GET /minecraft/profile` returns HTTP `404`), `profile` is returned as `None`.
    pub async fn login_full_from_ms_token(
        &self,
        ms_access_token: &str,
        check_ownership: bool,
    ) -> Result<MinecraftLoginSession> {
        let xbox_live = self.authenticate_xbox_live(ms_access_token).await?;
        let xsts = self.authorize_xsts(&xbox_live.token).await?;
        let minecraft = self.login_with_xbox(&xsts.user_hash, &xsts.token).await?;

        let authed = self.authed(&minecraft.access_token);
        let entitlements = if check_ownership {
            let ent = authed.entitlements().await?;
            if !ent.owns_minecraft_java() {
                return Err(Error::DoesNotOwnMinecraft);
            }
            Some(ent)
        } else {
            None
        };

        let profile = match authed.profile().await {
            Ok(p) => Some(p),
            Err(Error::ApiStatus { status: 404, .. }) => None,
            Err(err) => return Err(err),
        };

        Ok(MinecraftLoginSession {
            xbox_live,
            xsts,
            minecraft,
            entitlements,
            profile,
        })
    }
}