steam-user 0.1.0

Steam User web client for Rust - HTTP-based Steam Community interactions
Documentation
use base64::Engine;
use hmac::{Hmac, Mac};
use prost::Message;
use sha2::Sha256;
use steam_protos::{CAuthenticationRefreshTokenEnumerateResponse, CAuthenticationRefreshTokenRevokeRequest, EAuthTokenRevokeAction};
use steam_totp::Secret;

use crate::{client::SteamUser, endpoint::steam_endpoint, error::SteamUserError};

impl SteamUser {
    /// Lists all active authentication refresh tokens for the current account.
    ///
    /// Requires a mobile access token. These tokens represent active sessions
    /// on various devices/browsers.
    #[steam_endpoint(POST, host = Api, path = "/IAuthenticationService/EnumerateTokens/v1", kind = Auth)]
    pub async fn enumerate_tokens(&self) -> Result<CAuthenticationRefreshTokenEnumerateResponse, SteamUserError> {
        let access_token = self.session.access_token.as_ref().or(self.session.mobile_access_token.as_ref()).ok_or_else(|| SteamUserError::Other("Access token is required for enumerate_tokens".into()))?;

        // Construct Protobuf request
        let request = steam_protos::messages::auth::CAuthenticationRefreshTokenEnumerateRequest { include_revoked: Some(false) };

        let mut body = Vec::new();
        request.encode(&mut body).map_err(|e| SteamUserError::Other(e.to_string()))?;

        tracing::debug!(token_len = access_token.len(), "using access_token");

        let response = self.post_path("/IAuthenticationService/EnumerateTokens/v1").header(reqwest::header::AUTHORIZATION, format!("Bearer {}", access_token)).query(&[("origin", "https://store.steampowered.com")]).form(&[("input_protobuf_encoded", base64::engine::general_purpose::STANDARD.encode(body))]).send().await?;

        let status = response.status();
        let bytes = response.bytes().await?;

        if !status.is_success() {
            tracing::error!("Failed to get tokens: HTTP {}", status);
            return Err(SteamUserError::Other(format!("HTTP error {}", status)));
        }

        // Parse as protobuf
        let result = CAuthenticationRefreshTokenEnumerateResponse::decode(bytes).map_err(|e| SteamUserError::Other(format!("Failed to decode protobuf: {}", e)))?;

        Ok(result)
    }

    /// Checks if a refresh token with the specified token ID is currently
    /// active.
    // delegates to `enumerate_tokens` — no #[steam_endpoint]
    #[tracing::instrument(skip(self))]
    pub async fn check_token_exists(&self, token_id: &str) -> Result<bool, SteamUserError> {
        let tokens = self.enumerate_tokens().await?;
        let token_id_u64 = token_id.parse::<u64>().map_err(|_| SteamUserError::Other(format!("Invalid token ID format: {}", token_id)))?;

        Ok(tokens.refresh_tokens.iter().any(|t| t.token_id == Some(token_id_u64)))
    }

    /// Revokes multiple authentication refresh tokens at once, effectively
    /// logging out those sessions.
    ///
    /// Performs a single `enumerate_tokens` pre-check and post-check to
    /// minimise network round-trips. Tokens that are already absent are
    /// reported in `already_gone`; tokens that were sent for revocation but
    /// still appear afterwards are reported in `failed`.
    ///
    /// # Arguments
    ///
    /// * `token_ids` - Slice of numeric token ID strings to revoke.
    /// * `shared_secret` - The base64-encoded shared secret for generating the
    ///   required HMAC signature.
    #[steam_endpoint(POST, host = Api, path = "/IAuthenticationService/RevokeRefreshToken/v1", kind = Auth)]
    pub async fn revoke_tokens(&self, token_ids: &[&str], shared_secret: Option<&str>) -> Result<RevokeTokensResult, SteamUserError> {
        let access_token = self.session.mobile_access_token.as_ref().or(self.session.access_token.as_ref()).ok_or_else(|| SteamUserError::Other("Mobile access token is required for revoke_tokens".into()))?;
        let steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?;
        let base_mac = match shared_secret {
            Some(s) => {
                let secret = Secret::from_string(s).map_err(|e| SteamUserError::Other(e.to_string()))?;
                let mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).map_err(|e| SteamUserError::Other(e.to_string()))?;
                Some(mac)
            }
            None => None,
        };

        // Parse all token IDs upfront
        let parsed: Vec<(&str, u64)> = token_ids
            .iter()
            .map(|id| {
                let n = id.parse::<u64>().map_err(|_| SteamUserError::Other(format!("Invalid token ID format: {}", id)))?;
                Ok((*id, n))
            })
            .collect::<Result<Vec<_>, SteamUserError>>()?;

        // 1. Pre-check: fetch current active tokens
        let initial_tokens = self.enumerate_tokens().await?;
        let active_ids: std::collections::HashSet<u64> = initial_tokens.refresh_tokens.iter().filter_map(|t| t.token_id).collect();

        let mut already_gone = Vec::new();
        let mut to_revoke = Vec::new();

        for &(id_str, id_u64) in &parsed {
            if active_ids.contains(&id_u64) {
                to_revoke.push((id_str, id_u64));
            } else {
                already_gone.push(id_str.to_string());
            }
        }

        if to_revoke.is_empty() {
            return Ok(RevokeTokensResult { success: vec![], failed: vec![], already_gone, response: initial_tokens });
        }

        // 2. Send revocation requests for each active token
        for &(id_str, id_u64) in &to_revoke {
            let signature = match &base_mac {
                Some(mac) => {
                    let mut m = mac.clone();
                    // Sign the ASCII bytes of the token ID string (up to 20 chars).
                    let token_id_ascii = id_str.as_bytes();
                    let len = token_id_ascii.len().min(20);
                    m.update(&token_id_ascii[..len]);
                    Some(m.finalize().into_bytes().to_vec())
                }
                None => None,
            };

            let has_signature = signature.is_some();
            let request = CAuthenticationRefreshTokenRevokeRequest {
                token_id: Some(id_u64),
                steamid: Some(steam_id.steam_id64()),
                revoke_action: Some(EAuthTokenRevokeAction::Permanent.into()),
                signature,
            };

            let mut body = Vec::new();
            request.encode(&mut body).map_err(|e| SteamUserError::Other(e.to_string()))?;

            let response = match self.post_path("/IAuthenticationService/RevokeRefreshToken/v1").header(reqwest::header::AUTHORIZATION, format!("Bearer {}", access_token)).query(&[("origin", "https://store.steampowered.com")]).form(&[("input_protobuf_encoded", base64::engine::general_purpose::STANDARD.encode(&body))]).send().await {
                Ok(resp) => resp,
                Err(e) => {
                    tracing::error!("[RevokeTokens] HTTP request failed for token {}: {}", id_str, e);
                    continue;
                }
            };

            // Check x-eresult header first
            let mut eresult = 1; // Default to OK
            if let Some(er_val) = response.headers().get("x-eresult") {
                if let Ok(er_str) = er_val.to_str() {
                    if let Ok(er_num) = er_str.parse::<i32>() {
                        eresult = er_num;
                    }
                }
            }

            if !response.status().is_success() || eresult != 1 {
                let status = response.status();
                tracing::error!("[RevokeTokens] Steam API rejected revocation for token {}: HTTP {} (EResult: {})", id_str, status, eresult);
                // consume body to allow connection reuse
                let _ = response.bytes().await;

                if eresult == 5 && !has_signature {
                    tracing::warn!("[RevokeTokens] Hint: Token {} might require a `shared_secret` to be revoked, but none was provided.", id_str);
                } else if eresult == 15 && has_signature {
                    tracing::warn!("[RevokeTokens] Hint: Token {} — EResult 15 (BadSignature). Signature was sent but Steam rejected it. The `shared_secret` stored in the DB is likely wrong or stale for this account.", id_str);
                }

                continue;
            } else {
                tracing::debug!("[RevokeTokens] Steam API accepted revocation request for token {}", id_str);
                // consume body to allow connection reuse
                let _ = response.bytes().await;
            }
        }

        // 3. Post-check: verify which tokens were actually removed
        let final_tokens = self.enumerate_tokens().await?;
        let remaining_ids: std::collections::HashSet<u64> = final_tokens.refresh_tokens.iter().filter_map(|t| t.token_id).collect();

        let mut success = Vec::new();
        let mut failed = Vec::new();

        for &(id_str, id_u64) in &to_revoke {
            if remaining_ids.contains(&id_u64) {
                failed.push(id_str.to_string());
            } else {
                success.push(id_str.to_string());
            }
        }

        Ok(RevokeTokensResult { success, failed, already_gone, response: final_tokens })
    }
}

/// Result of a batch revoke operation.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RevokeTokensResult {
    /// Token IDs that were successfully revoked (confirmed gone).
    pub success: Vec<String>,
    /// Token IDs that were sent for revocation but still exist on Steam.
    pub failed: Vec<String>,
    /// Token IDs that were already absent before the revocation request.
    pub already_gone: Vec<String>,
    /// The full token enumeration response from the post-revocation check.
    #[serde(skip)]
    pub response: steam_protos::CAuthenticationRefreshTokenEnumerateResponse,
}