mcapi 0.3.1

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
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
//! Yggdrasil authentication, session, profile, and optional authlib-injector / RSA verification.

/// Client for `authlib-injector` build metadata and download URLs.
#[cfg(feature = "yggdrasil-authlib")]
#[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil-authlib")))]
pub mod authlib_injector;
/// Data models for Yggdrasil authentication, server metadata, and profiles.
pub mod models;
#[cfg(feature = "yggdrasil-verify")]
#[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil-verify")))]
pub mod verify;

use std::collections::HashSet;

use reqwest::header::{ACCEPT_CHARSET, AUTHORIZATION, HeaderValue};
use reqwest::multipart::{Form, Part};
use serde::Serialize;
use serde::de::DeserializeOwned;
use url::Url;

use self::models::{
    AuthenticateRequest, AuthenticateResponse, GameProfile, MetadataDocument, NameUuidEntry,
    RefreshRequest, RefreshResponse, ServerMetadata, SignoutRequest, SkinModel, TextureType,
    TokenPairRequest,
};
use crate::error::{Error, Result};
use crate::http::{HttpClient, bearer_header};
use crate::profile::JoinServerBody;
use crate::util::define_authed;
use crate::uuid::McUuid;

const ALI_HEADER: &str = "x-authlib-injector-api-location";

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct HasJoinedQuery<'a> {
    username: &'a str,
    server_id: &'a str,
    ip: Option<&'a str>,
}

/// Async client for Yggdrasil authentication, session, and profile endpoints.
#[derive(Clone, Debug)]
pub struct YggdrasilClient {
    api_root: String,
    http: HttpClient,
}

impl YggdrasilClient {
    /// Creates a new [`YggdrasilClient`] pointing at `api_root`.
    pub fn new(api_root: impl AsRef<str>) -> Result<Self> {
        Self::from_http(HttpClient::new()?, api_root)
    }

    /// Creates a new [`YggdrasilClient`] sharing an existing [`HttpClient`].
    ///
    /// Returns [`Error::Url`] or [`Error::InvalidInput`] if `api_root` is not a valid
    /// `http://` or `https://` URL.
    pub fn from_http(http: HttpClient, api_root: impl AsRef<str>) -> Result<Self> {
        let parsed = crate::util::validate_http_url(api_root.as_ref())?;
        Ok(Self {
            api_root: normalize_url(&parsed),
            http,
        })
    }

    /// Discovers the real Yggdrasil API root using the authlib-injector ALI header
    /// (`X-Authlib-Injector-API-Location`).
    pub async fn discover(entry_url: &str) -> Result<Self> {
        Self::discover_with_http(HttpClient::new()?, entry_url).await
    }

    /// Discovers the real Yggdrasil API root using an existing shared [`HttpClient`].
    pub async fn discover_with_http(http: HttpClient, entry_url: &str) -> Result<Self> {
        let initial = Url::parse(entry_url)?;
        if !matches!(initial.scheme(), "http" | "https") {
            return Err(Error::InvalidAliLocation);
        }

        let mut current = initial;
        let mut visited = HashSet::new();
        for _hop in 0..5 {
            visited.insert(normalize_url(&current));
            let response = http
                .send_direct_idempotent(current.as_str(), |client, url| client.get(url))
                .await?;
            let final_url = response.url().clone();
            let final_norm = normalize_url(&final_url);
            visited.insert(final_norm.clone());

            let Some(raw_loc) = response.headers().get(ALI_HEADER) else {
                return Ok(Self {
                    api_root: final_norm,
                    http,
                });
            };

            let loc = raw_loc
                .to_str()
                .map_err(|_| Error::InvalidAliLocation)?
                .trim();
            if loc.is_empty() {
                return Err(Error::InvalidAliLocation);
            }
            let next = final_url.join(loc).map_err(|_| Error::InvalidAliLocation)?;
            if !matches!(next.scheme(), "http" | "https") {
                return Err(Error::InvalidAliLocation);
            }
            if final_url.scheme() == "https" && next.scheme() == "http" {
                return Err(Error::InvalidAliLocation);
            }

            let next_norm = normalize_url(&next);
            if next_norm == final_norm {
                return Ok(Self {
                    api_root: next_norm,
                    http,
                });
            }
            if visited.contains(&next_norm) {
                return Err(Error::InvalidAliLocation);
            }
            current = next;
        }

        Err(Error::InvalidAliLocation)
    }

    /// Returns the normalized Yggdrasil API root URL.
    #[must_use]
    pub fn api_root(&self) -> &str {
        &self.api_root
    }

    /// Returns a reference to the underlying shared [`HttpClient`].
    #[must_use]
    pub fn http(&self) -> &HttpClient {
        &self.http
    }

    /// Returns an authenticated view bound to `access_token`.
    #[must_use]
    pub fn authed<'a>(&'a self, access_token: &'a str) -> Authed<'a> {
        Authed::new(self, access_token)
    }

    /// Fetches the raw and parsed server metadata document from `GET /`.
    pub async fn metadata_document(&self) -> Result<MetadataDocument> {
        let url = format!("{}/", self.api_root);
        self.http
            .send_and_map(
                &url,
                |client, target| {
                    client
                        .get(target)
                        .header(ACCEPT_CHARSET, HeaderValue::from_static("UTF-8"))
                },
                |resp| async move {
                    let raw_json = resp.text().await?;
                    let metadata: ServerMetadata = serde_json::from_str(&raw_json)?;
                    Ok(MetadataDocument { metadata, raw_json })
                },
            )
            .await
    }

    /// Fetches parsed server metadata from `GET /`.
    pub async fn metadata(&self) -> Result<ServerMetadata> {
        Ok(self.metadata_document().await?.metadata)
    }

    /// Authenticates an account via `POST /authserver/authenticate`.
    pub async fn authenticate(&self, req: &AuthenticateRequest) -> Result<AuthenticateResponse> {
        self.post_yggdrasil("/authserver/authenticate", req).await
    }

    /// Refreshes an access token via `POST /authserver/refresh`.
    pub async fn refresh(&self, req: &RefreshRequest) -> Result<RefreshResponse> {
        self.post_yggdrasil("/authserver/refresh", req).await
    }

    /// Validates an access token via `POST /authserver/validate`.
    /// Returns `Ok(true)` on `204` and `Ok(false)` on `403`.
    pub async fn validate(&self, req: &TokenPairRequest) -> Result<bool> {
        let url = self.endpoint("/authserver/validate");
        match self
            .http
            .send_direct_idempotent(&url, |client, target| client.post(target).json(req))
            .await
        {
            Ok(_) => Ok(true),
            Err(Error::ApiStatus(ref err)) if err.status == 403 => Ok(false),
            Err(err) => Err(map_yggdrasil_error(err)),
        }
    }

    /// Invalidates an access token via `POST /authserver/invalidate`.
    pub async fn invalidate(&self, req: &TokenPairRequest) -> Result<()> {
        let url = self.endpoint("/authserver/invalidate");
        self.http
            .send_direct(&url, |client, target| client.post(target).json(req))
            .await
            .map_err(map_yggdrasil_error)?;
        Ok(())
    }

    /// Invalidates all access tokens of an account via `POST /authserver/signout`.
    pub async fn signout(&self, req: &SignoutRequest) -> Result<()> {
        let url = self.endpoint("/authserver/signout");
        self.http
            .send_direct(&url, |client, target| client.post(target).json(req))
            .await
            .map_err(map_yggdrasil_error)?;
        Ok(())
    }

    /// Checks whether a player joined a server via `GET /sessionserver/session/minecraft/hasJoined`.
    pub async fn has_joined(
        &self,
        username: &str,
        server_id: &str,
        ip: Option<&str>,
    ) -> Result<Option<GameProfile>> {
        let url = self.endpoint("/sessionserver/session/minecraft/hasJoined");
        let query = HasJoinedQuery {
            username,
            server_id,
            ip,
        };
        self.http
            .send_optional_json(&url, |client, target| client.get(target).query(&query))
            .await
            .map_err(map_yggdrasil_error)
    }

    /// Fetches a player's unsigned profile via
    /// `GET /sessionserver/session/minecraft/profile/{uuid}?unsigned=true`.
    pub async fn profile(&self, uuid: McUuid) -> Result<Option<GameProfile>> {
        self.profile_inner(uuid, true).await
    }

    /// Fetches a player's signed profile (including RSA signature on `textures`) via
    /// `GET /sessionserver/session/minecraft/profile/{uuid}?unsigned=false`.
    pub async fn signed_profile(&self, uuid: McUuid) -> Result<Option<GameProfile>> {
        self.profile_inner(uuid, false).await
    }

    async fn profile_inner(&self, uuid: McUuid, unsigned: bool) -> Result<Option<GameProfile>> {
        let url = self.endpoint(&format!(
            "/sessionserver/session/minecraft/profile/{}",
            uuid.to_undashed()
        ));
        let query = [("unsigned", if unsigned { "true" } else { "false" })];
        self.http
            .send_optional_json(&url, |client, target| client.get(target).query(&query))
            .await
            .map_err(map_yggdrasil_error)
    }

    /// Looks up UUIDs and canonical names for up to 10 usernames via `POST /api/profiles/minecraft`.
    pub async fn profiles_by_names(&self, names: &[impl AsRef<str>]) -> Result<Vec<NameUuidEntry>> {
        if names.is_empty() || names.len() > 10 {
            return Err(Error::InvalidInput(
                "profiles_by_names accepts between 1 and 10 usernames".to_string(),
            ));
        }
        let name_refs: Vec<&str> = names.iter().map(AsRef::as_ref).collect();
        self.post_yggdrasil_inner("/api/profiles/minecraft", &name_refs, true)
            .await
    }

    fn endpoint(&self, path: &str) -> String {
        format!("{}{}", self.api_root, path)
    }

    async fn post_yggdrasil<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        self.post_yggdrasil_inner(path, body, false).await
    }

    async fn post_yggdrasil_inner<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
        idempotent: bool,
    ) -> Result<T> {
        let url = self.endpoint(path);
        let build = |client: &reqwest::Client, target: &str| {
            client
                .post(target)
                .header(ACCEPT_CHARSET, HeaderValue::from_static("UTF-8"))
                .json(body)
        };
        let resp = if idempotent {
            self.http.send_direct_idempotent(&url, build).await
        } else {
            self.http.send_direct(&url, build).await
        }
        .map_err(map_yggdrasil_error)?;
        Ok(resp.json::<T>().await?)
    }
}

define_authed!(YggdrasilClient);

impl<'a> Authed<'a> {
    /// Records a server join on the session server via `POST /sessionserver/session/minecraft/join`.
    pub async fn join_server(&self, selected_profile: McUuid, server_id: &str) -> Result<()> {
        let url = self
            .client
            .endpoint("/sessionserver/session/minecraft/join");
        let payload = JoinServerBody {
            access_token: self.token,
            selected_profile,
            server_id,
        };
        self.client
            .http
            .send_direct(&url, |client, target| client.post(target).json(&payload))
            .await
            .map_err(map_yggdrasil_error)?;
        Ok(())
    }

    /// Uploads a PNG skin or cape texture via `PUT /api/user/profile/{uuid}/{textureType}`.
    pub async fn upload_texture(
        &self,
        profile_uuid: McUuid,
        texture_type: TextureType,
        model: SkinModel,
        png_bytes: Vec<u8>,
    ) -> Result<()> {
        let url = self.client.endpoint(&format!(
            "/api/user/profile/{}/{}",
            profile_uuid.to_undashed(),
            texture_type.as_path_segment()
        ));
        let auth = bearer_header(self.token)?;
        let model_val = model.as_form_value();

        self.client
            .http
            .send_direct_oneshot(&url, move |client, target| {
                let file_part = Part::bytes(png_bytes)
                    .file_name("texture.png")
                    .mime_str("image/png")
                    .expect("static mime type is valid");
                let mut form = Form::new().part("file", file_part);
                if texture_type == TextureType::Skin {
                    form = form.text("model", model_val);
                }
                client
                    .put(target)
                    .header(AUTHORIZATION, auth)
                    .multipart(form)
            })
            .await
            .map_err(map_yggdrasil_error)?;
        Ok(())
    }

    /// Deletes a skin or cape texture via `DELETE /api/user/profile/{uuid}/{textureType}`.
    pub async fn delete_texture(
        &self,
        profile_uuid: McUuid,
        texture_type: TextureType,
    ) -> Result<()> {
        let url = self.client.endpoint(&format!(
            "/api/user/profile/{}/{}",
            profile_uuid.to_undashed(),
            texture_type.as_path_segment()
        ));
        let auth = bearer_header(self.token)?;
        self.client
            .http
            .send_direct(&url, |client, target| {
                client.delete(target).header(AUTHORIZATION, auth.clone())
            })
            .await
            .map_err(map_yggdrasil_error)?;
        Ok(())
    }
}

fn normalize_url(url: &Url) -> String {
    let mut clean = url.clone();
    clean.set_query(None);
    clean.set_fragment(None);
    clean.as_str().trim_end_matches('/').to_string()
}

fn map_yggdrasil_error(err: Error) -> Error {
    if let Error::ApiStatus(ref api_err) = err
        && let Ok(parsed) = serde_json::from_str::<YggdrasilErrorBody>(&api_err.body)
    {
        return Error::yggdrasil(parsed.error, parsed.error_message, parsed.cause);
    }
    err
}

#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct YggdrasilErrorBody {
    error: String,
    error_message: String,
    #[serde(default)]
    cause: Option<String>,
}