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 {
#[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()))?;
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)));
}
let result = CAuthenticationRefreshTokenEnumerateResponse::decode(bytes).map_err(|e| SteamUserError::Other(format!("Failed to decode protobuf: {}", e)))?;
Ok(result)
}
#[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)))
}
#[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,
};
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>>()?;
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 });
}
for &(id_str, id_u64) in &to_revoke {
let signature = match &base_mac {
Some(mac) => {
let mut m = mac.clone();
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;
}
};
let mut eresult = 1; 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);
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);
let _ = response.bytes().await;
}
}
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 })
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RevokeTokensResult {
pub success: Vec<String>,
pub failed: Vec<String>,
pub already_gone: Vec<String>,
#[serde(skip)]
pub response: steam_protos::CAuthenticationRefreshTokenEnumerateResponse,
}