1use std::sync::{Arc, LazyLock};
4
5use parking_lot::Mutex;
6use reqwest::{cookie::Jar, Url};
7use steamid::SteamID;
8
9static 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
12pub(crate) const TIMEZONE_OFFSET_COOKIE: &str = "timezoneOffset=0,0";
21
22pub struct Session {
26 pub(crate) jar: Arc<Jar>,
28 pub steam_id: Option<SteamID>,
30 pub session_id: Option<String>,
32 pub(crate) mobile_access_token: Option<String>,
34 pub(crate) access_token: Option<String>,
36 pub(crate) refresh_token: Option<String>,
38 pub(crate) shared_secret: Mutex<Option<String>>,
41 pub(crate) profile_url: Mutex<Option<String>>,
43 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 pub fn new() -> Self {
86 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 pub fn set_cookies(&mut self, cookies: &[&str]) -> Result<(), crate::SteamUserError> {
109 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 let name = cookie.split('=').next().unwrap_or("");
131
132 if name == "steamLoginSecure" || name == "steamLogin" {
134 if let Some(value) = cookie.split_once('=').map(|x| x.1) {
135 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 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 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 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 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 pub fn get_session_id(&mut self) -> &str {
186 self.ensure_session_id()
187 }
188
189 pub fn get_cookie_string(&self) -> &str {
191 &self.cookie_string
192 }
193
194 pub fn get_steam_id(&self) -> SteamID {
196 self.steam_id.unwrap_or_default()
197 }
198
199 pub fn is_logged_in(&self) -> bool {
201 self.steam_id.is_some()
202 }
203
204 pub fn mobile_access_token(&self) -> Option<&str> {
206 self.mobile_access_token.as_deref()
207 }
208
209 pub fn access_token(&self) -> Option<&str> {
211 self.access_token.as_deref()
212 }
213
214 pub fn refresh_token(&self) -> Option<&str> {
216 self.refresh_token.as_deref()
217 }
218
219 pub fn set_mobile_access_token(&mut self, token: String) {
221 self.mobile_access_token = Some(token);
222 }
223
224 pub fn set_refresh_token(&mut self, token: String) {
226 self.refresh_token = Some(token);
227 }
228
229 pub fn set_access_token(&mut self, token: String) {
231 self.access_token = Some(token);
232 }
233
234 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); let id2 = session.ensure_session_id();
284 assert_eq!(id, id2);
285 }
286}