steam-user 0.1.0

Steam User web client for Rust - HTTP-based Steam Community interactions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! Email management services.
//!
//! This module provides functionality for:
//! - Getting the account email address
//! - Getting the current Steam login username
//! - Changing the account email (multi-step wizard flow)

use std::{future::Future, sync::OnceLock, time::Duration};

use regex::Regex;
use scraper::{Html, Selector};

static SEL_ACCOUNT_BLOCK: OnceLock<Selector> = OnceLock::new();
fn sel_account_block() -> &'static Selector {
    SEL_ACCOUNT_BLOCK.get_or_init(|| Selector::parse(".account_setting_block").expect("valid CSS selector"))
}

static SEL_ACCOUNT_LABEL: OnceLock<Selector> = OnceLock::new();
fn sel_account_label() -> &'static Selector {
    SEL_ACCOUNT_LABEL.get_or_init(|| Selector::parse(".account_manage_label").expect("valid CSS selector"))
}

static SEL_ACCOUNT_FIELD: OnceLock<Selector> = OnceLock::new();
fn sel_account_field() -> &'static Selector {
    SEL_ACCOUNT_FIELD.get_or_init(|| Selector::parse(".account_data_field").expect("valid CSS selector"))
}

static SEL_CLIENT_CONN_MACHINE: OnceLock<Selector> = OnceLock::new();
fn sel_client_conn_machine() -> &'static Selector {
    SEL_CLIENT_CONN_MACHINE.get_or_init(|| Selector::parse(".clientConnMachineText").expect("valid CSS selector"))
}

static SEL_HELP_WIZARD_BUTTON: OnceLock<Selector> = OnceLock::new();
fn sel_help_wizard_button() -> &'static Selector {
    SEL_HELP_WIZARD_BUTTON.get_or_init(|| Selector::parse("a.help_wizard_button").expect("valid CSS selector"))
}

static SEL_FORGOT_LOGIN_FORM: OnceLock<Selector> = OnceLock::new();
fn sel_forgot_login_form() -> &'static Selector {
    SEL_FORGOT_LOGIN_FORM.get_or_init(|| Selector::parse("#forgot_login_code_form").expect("valid CSS selector"))
}

static RE_SESSION_ID: OnceLock<Regex> = OnceLock::new();
fn re_session_id() -> &'static Regex {
    RE_SESSION_ID.get_or_init(|| Regex::new(r#"var g_sessionID = "([^"]+)";"#).expect("valid regex"))
}

static RE_WIZARD_PARAMS: OnceLock<Regex> = OnceLock::new();
fn re_wizard_params() -> &'static Regex {
    RE_WIZARD_PARAMS.get_or_init(|| Regex::new(r"g_rgDefaultWizardPageParams = (\{.*?\});").expect("valid regex"))
}

use crate::{
    client::SteamUser,
    endpoint::{steam_endpoint, Host},
    error::SteamUserError,
    types::{AccountRecoveryStatus, ChangeEmailResult, ConfirmEmailResponse, SendRecoveryCodeResponse, SubmitEmailResponse, WizardDefaultParams, WizardIssue, WizardPageParams},
};

impl SteamUser {
    /// Retrieves the email address associated with the current Steam account.
    ///
    /// Scrapes the account settings page at `https://store.steampowered.com/account/`.
    ///
    /// # Returns
    ///
    /// Returns the account email address as a `String`, or an empty string if
    /// not found.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let email = user.get_account_email().await?;
    /// println!("Account email: {}", email);
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(GET, host = Store, path = "/account/", kind = Read)]
    pub async fn get_account_email(&self) -> Result<String, SteamUserError> {
        let response = self.get_path("/account/").send().await?.text().await?;

        let document = Html::parse_document(&response);

        for block in document.select(sel_account_block()) {
            // Find label and adjacent field
            if let Some(label) = block.select(sel_account_label()).next() {
                let label_text = label.text().collect::<String>();
                if label_text.trim() == "Email address:" {
                    // Look for the next sibling field
                    if let Some(field) = block.select(sel_account_field()).next() {
                        return Ok(field.text().collect::<String>().trim().to_string());
                    }
                }
            }
        }

        Ok(String::new())
    }

    /// Retrieves the current Steam login username.
    ///
    /// Scrapes the games page to extract the logged-in machine text.
    ///
    /// # Returns
    ///
    /// Returns the current login username as a `String`, or an empty string if
    /// not found.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let login = user.get_current_steam_login().await?;
    /// println!("Current login: {}", login);
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(GET, host = Community, path = "/my/games/", kind = Read)]
    pub async fn get_current_steam_login(&self) -> Result<String, SteamUserError> {
        let response = self.get_path("/my/games/?tab=all").send().await?.text().await?;

        let document = Html::parse_document(&response);

        if let Some(el) = document.select(sel_client_conn_machine()).next() {
            let text = el.text().collect::<String>();
            // Extract text before the last "|"
            if let Some(pos) = text.rfind('|') {
                return Ok(text[..pos].trim().to_string());
            }
            return Ok(text.trim().to_string());
        }

        Ok(String::new())
    }

    /// Changes the email address associated with the Steam account.
    ///
    /// This is a multi-step wizard flow that:
    /// 1. Initiates the help wizard for email change
    /// 2. Requests mobile app confirmation
    /// 3. Sends account recovery code
    /// 4. Accepts mobile confirmations
    /// 5. Polls for confirmation completion
    /// 6. Submits the new email address
    /// 7. Confirms with OTP code from the new email
    ///
    /// # Arguments
    ///
    /// * `new_email` - The new email address to set.
    /// * `identity_secret` - The identity secret for mobile confirmations.
    /// * `get_email_otp` - An async function that returns OTP codes from the
    ///   new email inbox. This will be called multiple times with increasing
    ///   delays.
    ///
    /// # Returns
    ///
    /// Returns [`ChangeEmailResult::Success`] if the email was changed
    /// successfully, or [`ChangeEmailResult::Error`] with an error message
    /// if it failed.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let result = user
    ///     .change_email(
    ///         "new_email@example.com",
    ///         "identity_secret_base64",
    ///         || async {
    ///             // Fetch OTP code from new email inbox
    ///             // Return None if not available yet, or Some(codes) with list of codes
    ///             Some(vec!["123456".to_string()])
    ///         },
    ///     )
    ///     .await;
    ///
    /// match result {
    ///     Ok(r) if r.is_success() => println!("Email changed!"),
    ///     Ok(r) => println!("Failed: {:?}", r.error_message()),
    ///     Err(e) => println!("Error: {}", e),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    // composite multi-step wizard — delegates to private helpers — no #[steam_endpoint]
    #[tracing::instrument(skip(self, identity_secret, get_email_otp, new_email))]
    pub async fn change_email<F, Fut>(&self, new_email: &str, identity_secret: &str, get_email_otp: F) -> Result<ChangeEmailResult, SteamUserError>
    where
        F: Fn() -> Fut,
        Fut: Future<Output = Option<Vec<String>>>,
    {
        let account = self.get_miniprofile_id();

        // Step 1: Get help link
        let help_link = match self.get_email_help_link().await? {
            Some(link) => link,
            None => return Ok(ChangeEmailResult::Error("Can't get help link".into())),
        };

        // Step 2: Send app confirmation and get wizard params
        let wizard_params = match self.send_email_app_confirmation(&help_link).await? {
            Some(params) => params,
            None => return Ok(ChangeEmailResult::Error("Can't send app confirmation".into())),
        };

        let issue = &wizard_params.issue;
        let default_params = &wizard_params.default_params;

        // Navigate to the enter code page
        let enter_code_path = format!(
            "/en/wizard/HelpWithLoginInfoEnterCode?s={}&account={}&reset={}&lost={}&issueid={}&wizard_ajax=1&gamepad=0",
            urlencoding::encode(&issue.s),
            account,
            urlencoding::encode(&issue.reset),
            urlencoding::encode(&issue.lost),
            urlencoding::encode(&issue.issueid),
        );
        let _ = self.get_path_on(Host::Help, &enter_code_path).send().await;

        // Step 3: Send account recovery code
        if !self.send_email_recovery_code(issue, default_params, &help_link).await? {
            return Ok(ChangeEmailResult::Error("Can't send app recovery code".into()));
        }

        // Step 4: Accept mobile confirmations
        tokio::time::sleep(Duration::from_millis(1000)).await;

        let confirmations = self.get_confirmations(identity_secret, None).await;
        let confirmations = match confirmations {
            Ok(c) => c,
            Err(e) => {
                tracing::warn!(error = %e, "change_email: first get_confirmations failed; retrying after 2s");
                tokio::time::sleep(Duration::from_millis(2000)).await;
                self.get_confirmations(identity_secret, None).await?
            }
        };

        if confirmations.is_empty() {
            return Ok(ChangeEmailResult::Error("Can't get app recovery code".into()));
        }

        for confirmation in &confirmations {
            let creator_id = confirmation.creator.parse::<u64>().map_err(|_| SteamUserError::InvalidInput(format!("Invalid confirmation creator ID: {:?}", confirmation.creator)))?;
            self.accept_confirmation_for_object(identity_secret, creator_id).await?;
        }

        // Step 5: Poll for confirmation completion
        let mut checking_ok = AccountRecoveryStatus { r#continue: true, success: false, error: None };

        for _ in 0..10 {
            checking_ok = self.poll_account_recovery_confirmation(issue, default_params, &help_link).await?;

            if checking_ok.r#continue {
                tokio::time::sleep(Duration::from_millis(5000)).await;
            } else {
                break;
            }
        }

        if !checking_ok.success {
            return Ok(ChangeEmailResult::Error("Can't confirm app recovery code".into()));
        }

        // Navigate to reset page
        let reset_path = format!(
            "/en/wizard/HelpWithLoginInfoReset/?s={}&account={}&reset={}&issueid={}",
            urlencoding::encode(&issue.s),
            account,
            urlencoding::encode(&issue.reset),
            urlencoding::encode(&issue.issueid),
        );
        let _ = self.get_path_on(Host::Help, &reset_path).send().await;

        // Step 6: Submit new email
        let submit_result = self.submit_new_email(issue, default_params, account, new_email).await?;

        if !submit_result.error_msg.is_empty() {
            return Ok(ChangeEmailResult::Error(format!("submitNewEmail Failed: {}", submit_result.error_msg)));
        }

        // Step 7: Confirm with OTP from new email
        for _ in 0..5 {
            if let Some(codes) = get_email_otp().await {
                for code in codes {
                    let confirm_result = self.confirm_new_email(issue, default_params, account, new_email, &code).await?;

                    if confirm_result.hash.contains("HelpWithLoginInfoComplete") {
                        return Ok(ChangeEmailResult::Success);
                    }

                    tokio::time::sleep(Duration::from_millis(1000)).await;
                }
            } else {
                tokio::time::sleep(Duration::from_millis(5000)).await;
            }
        }

        Ok(ChangeEmailResult::Error("Can't confirm new email code".into()))
    }

    /// Gets the help wizard link for email change.
    #[steam_endpoint(GET, host = Help, path = "/en/wizard/HelpChangeEmail", kind = Recovery)]
    async fn get_email_help_link(&self) -> Result<Option<String>, SteamUserError> {
        let response = self.get_path("/en/wizard/HelpChangeEmail?redir=store/account/").send().await?.text().await?;

        let document = Html::parse_document(&response);

        for button in document.select(sel_help_wizard_button()) {
            let text = button.text().collect::<String>();
            if text.trim() == "Send a confirmation to my Steam Mobile app" {
                return Ok(button.value().attr("href").map(|s| s.to_string()));
            }
        }

        Ok(None)
    }

    /// Sends app confirmation and parses wizard page params.
    // dynamic URL from help_link — no #[steam_endpoint]
    #[tracing::instrument(skip(self, help_link))]
    async fn send_email_app_confirmation(&self, help_link: &str) -> Result<Option<WizardPageParams>, SteamUserError> {
        // `help_link` comes from a button `href` on the Help host and may be
        // either an absolute URL (`https://help.steampowered.com/...`) or a
        // relative path. Normalise to a path on Host::Help.
        let help_path = help_link.strip_prefix("https://help.steampowered.com").or_else(|| help_link.strip_prefix("http://help.steampowered.com")).unwrap_or(help_link);
        let response = self.get_path_on(Host::Help, help_path).send().await?.text().await?;

        // Check for expected content
        if !response.contains("For security, verify that the code in the box below matches the code we display on the confirmations page.") {
            return Ok(None);
        }

        Ok(Self::parse_wizard_page_params(&response))
    }

    /// Parses wizard page parameters from HTML.
    fn parse_wizard_page_params(html: &str) -> Option<WizardPageParams> {
        let document = Html::parse_document(html);

        let form = document.select(sel_forgot_login_form()).next()?;

        let get_input_value = |name: &str| -> String {
            let selector = Selector::parse(&format!("input[name=\"{}\"]", name)).expect("valid CSS selector");
            form.select(&selector).next().and_then(|el| el.value().attr("value")).unwrap_or("").to_string()
        };

        let issue = WizardIssue {
            s: get_input_value("s"),
            reset: get_input_value("reset"),
            lost: get_input_value("lost"),
            method: get_input_value("method"),
            issueid: get_input_value("issueid"),
        };

        // Extract g_sessionID from JavaScript
        let session_id = re_session_id().captures(html).map(|c| c[1].to_string()).unwrap_or_default();

        // Extract g_rgDefaultWizardPageParams
        let default_params = re_wizard_params().captures(html).and_then(|c| serde_json::from_str::<WizardDefaultParams>(&c[1]).ok()).unwrap_or_default();

        Some(WizardPageParams { session_id, issue, default_params })
    }

    /// Sends account recovery code request.
    #[steam_endpoint(POST, host = Help, path = "/en/wizard/AjaxSendAccountRecoveryCode", kind = Recovery)]
    async fn send_email_recovery_code(&self, issue: &WizardIssue, default_params: &WizardDefaultParams, help_link: &str) -> Result<bool, SteamUserError> {
        let params = Self::merge_params(default_params, &[("s", &issue.s), ("method", &issue.method), ("link", "")]);

        let response: SendRecoveryCodeResponse = self.post_path("/en/wizard/AjaxSendAccountRecoveryCode").header("content-type", "application/x-www-form-urlencoded").header("x-requested-with", "XMLHttpRequest").header("referer", help_link).form(&params).send().await?.json().await?;

        Ok(response.success)
    }

    /// Polls for account recovery confirmation status.
    #[steam_endpoint(POST, host = Help, path = "/en/wizard/AjaxPollAccountRecoveryConfirmation", kind = Recovery)]
    async fn poll_account_recovery_confirmation(&self, issue: &WizardIssue, default_params: &WizardDefaultParams, help_link: &str) -> Result<AccountRecoveryStatus, SteamUserError> {
        let params = Self::merge_params(default_params, &[("s", &issue.s), ("reset", &issue.reset), ("lost", &issue.lost), ("method", &issue.method), ("issueid", &issue.issueid)]);

        let response: AccountRecoveryStatus = self.post_path("/en/wizard/AjaxPollAccountRecoveryConfirmation").header("content-type", "application/x-www-form-urlencoded").header("x-requested-with", "XMLHttpRequest").header("referer", help_link).form(&params).send().await?.json().await?;

        Ok(response)
    }

    /// Submits the new email address.
    #[steam_endpoint(POST, host = Help, path = "/en/wizard/AjaxAccountRecoveryChangeEmail/", kind = Recovery)]
    async fn submit_new_email(&self, issue: &WizardIssue, default_params: &WizardDefaultParams, account: u32, new_email: &str) -> Result<SubmitEmailResponse, SteamUserError> {
        let referer = format!(
            "https://help.steampowered.com/en/wizard/HelpWithLoginInfoReset/?s={}&account={}&reset={}&issueid={}",
            urlencoding::encode(&issue.s),
            account,
            urlencoding::encode(&issue.reset),
            urlencoding::encode(&issue.issueid),
        );

        let account_str = account.to_string();
        let params = Self::merge_params(default_params, &[("s", issue.s.as_str()), ("account", &account_str), ("email", new_email)]);

        let response: SubmitEmailResponse = self.post_path("/en/wizard/AjaxAccountRecoveryChangeEmail/").header("content-type", "application/x-www-form-urlencoded").header("x-requested-with", "XMLHttpRequest").header("referer", &referer).form(&params).send().await?.json().await?;

        Ok(response)
    }

    /// Confirms the new email with OTP code.
    #[steam_endpoint(POST, host = Help, path = "/en/wizard/AjaxAccountRecoveryConfirmChangeEmail/", kind = Recovery)]
    async fn confirm_new_email(&self, issue: &WizardIssue, default_params: &WizardDefaultParams, account: u32, new_email: &str, code: &str) -> Result<ConfirmEmailResponse, SteamUserError> {
        let referer = format!(
            "https://help.steampowered.com/en/wizard/HelpWithLoginInfoReset/?s={}&account={}&reset={}&issueid={}",
            urlencoding::encode(&issue.s),
            account,
            urlencoding::encode(&issue.reset),
            urlencoding::encode(&issue.issueid),
        );

        let account_str = account.to_string();
        let params = Self::merge_params(default_params, &[("s", issue.s.as_str()), ("account", &account_str), ("email", new_email), ("email_change_code", code)]);

        let response: ConfirmEmailResponse = self.post_path("/en/wizard/AjaxAccountRecoveryConfirmChangeEmail/").header("content-type", "application/x-www-form-urlencoded").header("x-requested-with", "XMLHttpRequest").header("referer", &referer).form(&params).send().await?.json().await?;

        Ok(response)
    }

    /// Merges default wizard parameters with specific request parameters.
    fn merge_params(default_params: &WizardDefaultParams, specific_params: &[(&str, &str)]) -> std::collections::HashMap<String, String> {
        let mut map = default_params.extra.clone();
        if let Some(acc) = default_params.account {
            map.insert("account".to_string(), acc.to_string());
        }
        if let Some(wiz) = &default_params.wizard {
            map.insert("wizard".to_string(), wiz.clone());
        }
        for (k, v) in specific_params {
            map.insert(k.to_string(), v.to_string());
        }
        map
    }

    /// Gets the miniprofile ID (account ID) from the SteamID.
    fn get_miniprofile_id(&self) -> u32 {
        self.steam_id().map(|id| id.account_id).unwrap_or(0)
    }
}