Skip to main content

steam_user/
session.rs

1//! Session and cookie management for Steam Community.
2
3use std::sync::{Arc, LazyLock};
4
5use parking_lot::Mutex;
6use reqwest::{cookie::Jar, Url};
7use steamid::SteamID;
8
9/// All Steam domains that need cookies set.
10static STEAM_URLS: LazyLock<[Url; 4]> = LazyLock::new(|| ["https://steamcommunity.com".parse().expect("valid Steam URL"), "https://store.steampowered.com".parse().expect("valid Steam URL"), "https://help.steampowered.com".parse().expect("valid Steam URL"), "https://api.steampowered.com".parse().expect("valid Steam URL")]);
11
12/// Pins Steam's server-side date rendering to UTC.
13///
14/// Steam renders human-readable dates (inventory history, trade banners,
15/// purchase history…) in the timezone given by the `timezoneOffset` cookie,
16/// format `<offset_seconds>,<dst_flag>`. Without it Steam falls back to US
17/// Pacific time, which shifts every scraped date by -7/-8 hours depending on
18/// DST. Sending `0,0` makes every page render in UTC, so parsers can safely
19/// interpret scraped date strings as UTC.
20pub(crate) const TIMEZONE_OFFSET_COOKIE: &str = "timezoneOffset=0,0";
21
22/// Session manager for Steam Community.
23///
24/// Handles cookies, session IDs, and authentication state.
25pub struct Session {
26    /// The cookie jar (shared across clones).
27    pub(crate) jar: Arc<Jar>,
28    /// Current Steam ID if logged in.
29    pub steam_id: Option<SteamID>,
30    /// Session ID for CSRF protection.
31    pub session_id: Option<String>,
32    /// Mobile access token for 2FA operations.
33    pub(crate) mobile_access_token: Option<String>,
34    /// OAuth access token.
35    pub(crate) access_token: Option<String>,
36    /// OAuth refresh token.
37    pub(crate) refresh_token: Option<String>,
38    /// Shared secret for 2FA finalization (behind Mutex for interior
39    /// mutability).
40    pub(crate) shared_secret: Mutex<Option<String>>,
41    /// Cached profile URL (e.g., "/id/username" or "/profiles/76561198...")
42    pub(crate) profile_url: Mutex<Option<String>>,
43    /// Raw cookie string for manual header injection.
44    pub(crate) cookie_string: String,
45}
46
47impl std::fmt::Debug for Session {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        f.debug_struct("Session")
50            .field("steam_id", &self.steam_id)
51            .field("session_id", &self.session_id)
52            .field("mobile_access_token", &self.mobile_access_token.as_ref().map(|_| "<redacted>"))
53            .field("access_token", &self.access_token.as_ref().map(|_| "<redacted>"))
54            .field("refresh_token", &self.refresh_token.as_ref().map(|_| "<redacted>"))
55            .field("shared_secret", &self.shared_secret.lock().as_ref().map(|_| "<redacted>"))
56            .field("profile_url", &"<Mutex>")
57            .finish()
58    }
59}
60
61impl Clone for Session {
62    fn clone(&self) -> Self {
63        Self {
64            jar: Arc::clone(&self.jar),
65            steam_id: self.steam_id,
66            session_id: self.session_id.clone(),
67            mobile_access_token: self.mobile_access_token.clone(),
68            access_token: self.access_token.clone(),
69            refresh_token: self.refresh_token.clone(),
70            shared_secret: Mutex::new(self.shared_secret.lock().clone()),
71            profile_url: Mutex::new(self.profile_url.lock().clone()),
72            cookie_string: self.cookie_string.clone(),
73        }
74    }
75}
76
77impl Default for Session {
78    fn default() -> Self {
79        Self::new()
80    }
81}
82
83impl Session {
84    /// Create a new empty session.
85    pub fn new() -> Self {
86        // Seed the jar so requests that rely on the cookie store (login
87        // flows, manual-redirect paths) also get UTC-rendered dates.
88        let jar = Arc::new(Jar::default());
89        for url in STEAM_URLS.iter() {
90            jar.add_cookie_str(TIMEZONE_OFFSET_COOKIE, url);
91        }
92        Self {
93            jar,
94            steam_id: None,
95            session_id: None,
96            mobile_access_token: None,
97            access_token: None,
98            refresh_token: None,
99            shared_secret: Mutex::new(None),
100            profile_url: Mutex::new(None),
101            cookie_string: String::new(),
102        }
103    }
104
105    /// Set cookies from string slice.
106    ///
107    /// Cookies should be in the format "name=value" or full Set-Cookie format.
108    pub fn set_cookies(&mut self, cookies: &[&str]) -> Result<(), crate::SteamUserError> {
109        // Store raw cookie string for manual injection. The manual Cookie
110        // header overrides the jar on those request paths, so the
111        // timezoneOffset pin must be part of this string too (unless the
112        // caller supplies their own).
113        self.cookie_string = cookies.join("; ");
114        let caller_has_tz = cookies.iter().flat_map(|raw| raw.split(';')).any(|c| c.trim().starts_with("timezoneOffset="));
115        if !caller_has_tz {
116            if !self.cookie_string.is_empty() {
117                self.cookie_string.push_str("; ");
118            }
119            self.cookie_string.push_str(TIMEZONE_OFFSET_COOKIE);
120        }
121
122        for raw_cookie in cookies {
123            for cookie in raw_cookie.split(';') {
124                let cookie = cookie.trim();
125                if cookie.is_empty() {
126                    continue;
127                }
128
129                // Extract cookie name
130                let name = cookie.split('=').next().unwrap_or("");
131
132                // Parse steamLoginSecure to get SteamID
133                if name == "steamLoginSecure" || name == "steamLogin" {
134                    if let Some(value) = cookie.split_once('=').map(|x| x.1) {
135                        // Value format: "steamid||token" or just "steamid"
136                        let decoded = urlencoding::decode(value).unwrap_or_default();
137                        if let Some(id_str) = decoded.split("||").next() {
138                            if let Ok(id) = id_str.parse::<u64>() {
139                                self.steam_id = Some(SteamID::from(id));
140                            }
141                        }
142                    }
143                }
144
145                // Extract sessionid
146                if name == "sessionid" {
147                    if let Some(value) = cookie.split_once('=').map(|x| x.1) {
148                        self.session_id = Some(urlencoding::decode(value).unwrap_or_default().to_string());
149                    }
150                }
151
152                // Add cookie to all Steam domains
153                for url in STEAM_URLS.iter() {
154                    self.jar.add_cookie_str(cookie, url);
155                }
156            }
157        }
158
159        Ok(())
160    }
161
162    pub fn ensure_session_id(&mut self) -> &str {
163        if self.session_id.is_none() {
164            use rand::Rng;
165            let bytes: [u8; 12] = rand::rng().random();
166            let new_id = hex::encode(bytes);
167            self.session_id = Some(new_id.clone());
168
169            // Add to jar to ensure CSRF checks pass
170            let cookie_str = format!("sessionid={}", new_id);
171            for url in STEAM_URLS.iter() {
172                self.jar.add_cookie_str(&cookie_str, url);
173            }
174
175            // Update raw cookie string for manual injection
176            if !self.cookie_string.is_empty() {
177                self.cookie_string.push_str("; ");
178            }
179            self.cookie_string.push_str(&cookie_str);
180        }
181        self.session_id.as_deref().expect("session_id was just initialized")
182    }
183
184    /// Get the session ID, ensuring one exists.
185    pub fn get_session_id(&mut self) -> &str {
186        self.ensure_session_id()
187    }
188
189    /// Get the raw cookie string.
190    pub fn get_cookie_string(&self) -> &str {
191        &self.cookie_string
192    }
193
194    /// Get the SteamID for the current session.
195    pub fn get_steam_id(&self) -> SteamID {
196        self.steam_id.unwrap_or_default()
197    }
198
199    /// Check if the session appears to be logged in (has steam_id).
200    pub fn is_logged_in(&self) -> bool {
201        self.steam_id.is_some()
202    }
203
204    /// Get the mobile access token, if set.
205    pub fn mobile_access_token(&self) -> Option<&str> {
206        self.mobile_access_token.as_deref()
207    }
208
209    /// Get the OAuth access token, if set.
210    pub fn access_token(&self) -> Option<&str> {
211        self.access_token.as_deref()
212    }
213
214    /// Get the OAuth refresh token, if set.
215    pub fn refresh_token(&self) -> Option<&str> {
216        self.refresh_token.as_deref()
217    }
218
219    /// Set the mobile access token for 2FA operations.
220    pub fn set_mobile_access_token(&mut self, token: String) {
221        self.mobile_access_token = Some(token);
222    }
223
224    /// Set the refresh token for token enumeration and renewal.
225    pub fn set_refresh_token(&mut self, token: String) {
226        self.refresh_token = Some(token);
227    }
228
229    /// Set the access token.
230    pub fn set_access_token(&mut self, token: String) {
231        self.access_token = Some(token);
232    }
233
234    /// Clear the cached profile URL.
235    pub fn clear_profile_url(&self) {
236        *self.profile_url.lock() = None;
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    #[test]
245    fn test_session_new() {
246        let session = Session::new();
247        assert!(session.steam_id.is_none());
248        assert!(session.session_id.is_none());
249        assert!(!session.is_logged_in());
250    }
251
252    #[test]
253    fn test_set_cookies() {
254        let mut session = Session::new();
255        session.set_cookies(&["steamLoginSecure=76561198012345678%7C%7Ctoken123", "sessionid=abc123def456"]).unwrap();
256
257        assert!(session.is_logged_in());
258        assert_eq!(session.steam_id.unwrap().steam_id64(), 76561198012345678);
259        assert_eq!(session.session_id.as_ref().unwrap(), "abc123def456");
260    }
261
262    #[test]
263    fn test_set_cookies_pins_timezone_offset_to_utc() {
264        let mut session = Session::new();
265        session.set_cookies(&["sessionid=abc123def456"]).unwrap();
266        assert_eq!(session.get_cookie_string(), "sessionid=abc123def456; timezoneOffset=0,0");
267    }
268
269    #[test]
270    fn test_set_cookies_respects_caller_timezone_offset() {
271        let mut session = Session::new();
272        session.set_cookies(&["sessionid=abc123def456; timezoneOffset=25200,0"]).unwrap();
273        assert_eq!(session.get_cookie_string(), "sessionid=abc123def456; timezoneOffset=25200,0");
274    }
275
276    #[test]
277    fn test_ensure_session_id() {
278        let mut session = Session::new();
279        let id = session.ensure_session_id().to_string();
280        assert_eq!(id.len(), 24); // 12 bytes = 24 hex chars
281
282        // Should return same ID on subsequent calls
283        let id2 = session.ensure_session_id();
284        assert_eq!(id, id2);
285    }
286}