mcapi 0.2.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, Java Runtimes, and SLP)
Documentation
//! CurseForge Core REST API (v1/v2) client and Murmur2 file fingerprinting.

mod files;
pub mod fingerprint;
mod fingerprints;
mod games;
mod minecraft;
pub mod models;
mod mods;

pub use fingerprint::{
    Murmur2Hasher, cf_fingerprint, cf_fingerprint_file, cf_fingerprint_read_seek,
    cf_fingerprint_reader, cf_fingerprint_with_len,
};

use reqwest::header::HeaderValue;
use serde::Serialize;
use serde::de::DeserializeOwned;

use self::models::{DataEnvelope, PaginatedData};
use crate::error::{Error, Result};
use crate::http::HttpCore;
use crate::mirror::Mirror;
use crate::util::{impl_redacted_debug, trim_trailing_slash};

pub const DEFAULT_BASE_URL: &str = "https://api.curseforge.com";
const API_KEY_HEADER: &str = "x-api-key";

/// Async client for the CurseForge Core REST API (<https://docs.curseforge.com/rest-api/>).
///
/// May be constructed with an official `x-api-key`, or without one via
/// [`CurseForgeClient::with_mirror`] / [`CurseForgeClient::from_http`] (`api_key = None`)
/// when routing requests through keyless mirrors such as `Mirror::Mcim`. When an API key is
/// configured, it is attached **only** to requests targeting `base_url` and never forwarded
/// to third-party mirrors.
#[derive(Clone)]
pub struct CurseForgeClient {
    base_url: String,
    api_key: Option<HeaderValue>,
    http: HttpCore,
}

impl_redacted_debug!(CurseForgeClient {
    base_url, http;
    redacted:;
    optional_redacted: api_key,
});

impl CurseForgeClient {
    /// Creates a new [`CurseForgeClient`] authenticated with `api_key`.
    pub fn new(api_key: impl Into<String>) -> Result<Self> {
        let key = api_key.into();
        Self::from_http(HttpCore::new()?, Some(&key))
    }

    /// Creates a keyless [`CurseForgeClient`] configured with `mirror` (e.g. `Mirror::Mcim`).
    pub fn with_mirror(mirror: Mirror) -> Result<Self> {
        Self::from_http(HttpCore::builder().mirror(mirror).build()?, None)
    }

    /// Creates a [`CurseForgeClient`] sharing `http` with an optional official `api_key`.
    ///
    /// - When `api_key` is `Some(key)` (non-blank), attaches `x-api-key` only for official
    ///   requests (never forwarded to third-party mirrors).
    /// - When `api_key` is `None` (or blank) and `http.mirror()` rewrites [`DEFAULT_BASE_URL`],
    ///   constructs a keyless mirror client.
    /// - Otherwise returns [`Error::InvalidInput`].
    pub fn from_http(http: HttpCore, api_key: Option<&str>) -> Result<Self> {
        match api_key.filter(|k| !k.trim().is_empty()) {
            Some(key) => {
                let mut val = HeaderValue::from_str(key)?;
                val.set_sensitive(true);
                Ok(Self {
                    base_url: DEFAULT_BASE_URL.to_string(),
                    api_key: Some(val),
                    http,
                })
            }
            None if http.mirror().is_rewritten(DEFAULT_BASE_URL) => Ok(Self {
                base_url: DEFAULT_BASE_URL.to_string(),
                api_key: None,
                http,
            }),
            None => Err(Error::InvalidInput(
                "CurseForge official API requires an x-api-key (or a mirror rewriting api.curseforge.com)"
                    .to_string(),
            )),
        }
    }

    /// Overrides the base API URL (e.g., for mock servers or custom gateways).
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = trim_trailing_slash(base_url);
        self
    }

    /// Returns the configured base API URL.
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Returns the underlying shared [`HttpCore`].
    pub fn http(&self) -> &HttpCore {
        &self.http
    }

    fn ensure_target_auth(&self, url: &str) -> Result<()> {
        if !self.http.mirror().is_rewritten(url)
            && self.api_key.is_none()
            && self.base_url == DEFAULT_BASE_URL
        {
            return Err(Error::InvalidInput(
                "CurseForge official API requires an x-api-key".to_string(),
            ));
        }
        Ok(())
    }

    async fn send_json<F, T>(&self, path: &str, mut build: F) -> Result<T>
    where
        F: FnMut(&reqwest::Client, &str) -> reqwest::RequestBuilder,
        T: DeserializeOwned,
    {
        let url = format!("{}{}", self.base_url, path);
        self.ensure_target_auth(&url)?;
        self.http
            .send_json_with(&url, |client, target| {
                let req = build(client, target);
                // Never leak the developer's private x-api-key to third-party mirrors.
                if let Some(ref key) = self.api_key
                    && target.starts_with(&self.base_url)
                {
                    req.header(API_KEY_HEADER, key.clone())
                } else {
                    req
                }
            })
            .await
    }

    pub(crate) async fn get_data<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        let env: DataEnvelope<T> = self
            .send_json(path, |client, target| client.get(target))
            .await?;
        Ok(env.data)
    }

    pub(crate) async fn get_data_query<Q: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        query: &Q,
    ) -> Result<T> {
        let env: DataEnvelope<T> = self
            .send_json(path, |client, target| client.get(target).query(query))
            .await?;
        Ok(env.data)
    }

    pub(crate) async fn get_paginated<Q: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        query: &Q,
    ) -> Result<PaginatedData<T>> {
        self.send_json(path, |client, target| client.get(target).query(query))
            .await
    }

    pub(crate) async fn post_data<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        let env: DataEnvelope<T> = self
            .send_json(path, |client, target| client.post(target).json(body))
            .await?;
        Ok(env.data)
    }
}