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
use std::time::Duration;

use const_format::concatcp;
use futures::TryFutureExt;
use futures_timer::Delay;
use parking_lot::lock_api::RwLockReadGuard;
use parking_lot::RawRwLock;
use reqwest::Method;
use tracing::debug;

use crate::client::MobileClient;
use crate::errors::AuthError;
use crate::errors::LinkerError;
use crate::utils::dump_cookies_by_domain_and_name;
use crate::utils::generate_canonical_device_id;
use crate::web_handler::steam_guard_linker::types::AddAuthenticatorErrorResponseBase;
use crate::web_handler::steam_guard_linker::types::AddAuthenticatorRequest;
use crate::web_handler::steam_guard_linker::types::AddAuthenticatorResponseBase;
use crate::web_handler::steam_guard_linker::types::FinalizeAddAuthenticatorBase;
use crate::web_handler::steam_guard_linker::types::FinalizeAddAuthenticatorErrorBase;
use crate::web_handler::steam_guard_linker::types::FinalizeAddAuthenticatorRequest;
use crate::web_handler::steam_guard_linker::types::GenericSuccessResponse;
use crate::web_handler::steam_guard_linker::types::HasPhoneResponse;
use crate::web_handler::steam_guard_linker::types::PhoneAjaxRequest;
use crate::web_handler::steam_guard_linker::types::QueryStatusResponseBase;
use crate::web_handler::steam_guard_linker::types::RemoveAuthenticatorRequest;
use crate::web_handler::steam_guard_linker::types::RemoveAuthenticatorResponseBase;
use crate::CacheGuard;
use crate::MobileAuthFile;
use crate::SteamCache;
use crate::STEAM_API_BASE;
use crate::STEAM_COMMUNITY_BASE;
use crate::STEAM_COMMUNITY_HOST;

mod types;

pub use types::QueryStatusResponse;

const PHONEAJAX_URL: &str = concatcp!(STEAM_COMMUNITY_BASE, "/steamguard/phoneajax");
pub const STEAM_ADD_PHONE_CATCHUP_SECS: u64 = 5;

type LinkerResult<T> = Result<T, LinkerError>;

/// By default, your `MobileAuth` file will always be printed to the terminal.
pub struct Authenticator {
    phone_number: String,
}

struct AuthenticatorOptions {
    save_path: String,
    print_output: bool,
}

/// Steps to add an authenticator to a Steam Account.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AddAuthenticatorStep {
    /// The user is signing up for the first time.
    InitialStep,
    /// The authenticator is awaiting the user's email confirmation to enable the addition of a phone number to Steam.
    EmailConfirmation,
    /// Authenticator succeeded and retrieved `MobileAuthFile`.
    MobileAuth(MobileAuthFile),
}

const QUERY_STATUS_ENDPOINT: &str = concatcp!(STEAM_API_BASE, "/ITwoFactorService/QueryStatus/v1/");

/// Queries Steam API to check SteamGuard Status.
pub async fn twofactor_status(client: &MobileClient, cache: CacheGuard) -> LinkerResult<QueryStatusResponse> {
    let cache = cache.read();
    let steamid = &[("steamid", cache.steamid.to_steam64())];
    let query = cache.query_tokens();

    let response = client
        .request_with_session_guard_and_decode::<_, _, QueryStatusResponseBase>(
            QUERY_STATUS_ENDPOINT.to_owned(),
            Method::POST,
            None,
            Some(steamid),
            Some(query),
        )
        .await?
        .inner;

    Ok(response)
}

/// Queries the `/steamguard/phoneajax` to check if the user has a phone number.
/// Returns true if user has already a phone registered.
pub async fn account_has_phone(client: &MobileClient) -> LinkerResult<bool> {
    let session_id =
        dump_cookies_by_domain_and_name(&client.cookie_store.read(), STEAM_COMMUNITY_HOST, "sessionid").unwrap();
    let payload = PhoneAjaxRequest::has_phone(&session_id);

    let response: HasPhoneResponse = client
        .request_with_session_guard(
            PHONEAJAX_URL.to_owned(),
            Method::POST,
            None,
            Some(payload),
            None::<&str>,
        )
        .and_then(|x| x.json::<HasPhoneResponse>().err_into())
        .await?;

    Ok(response.user_has_phone)
}

pub async fn check_sms(client: &MobileClient, sms_code: &str) -> LinkerResult<bool> {
    let session_id =
        dump_cookies_by_domain_and_name(&client.cookie_store.read(), STEAM_COMMUNITY_HOST, "sessionid").unwrap();
    let payload = PhoneAjaxRequest::check_sms(&session_id, sms_code);

    let response = client
        .request_with_session_guard_and_decode::<_, _, GenericSuccessResponse>(
            PHONEAJAX_URL.to_owned(),
            Method::POST,
            None,
            Some(payload),
            None::<&str>,
        )
        .await?;

    Ok(response.success)
}

/// Signals Steam that the user confirmed the phone add request email, and is ready for the next step.
/// Confirming the email allows `SteamAuthenticator` to register a new phone number to account.
pub async fn check_email_confirmation(client: &MobileClient) -> LinkerResult<bool> {
    let session_id =
        dump_cookies_by_domain_and_name(&client.cookie_store.read(), STEAM_COMMUNITY_HOST, "sessionid").unwrap();
    let payload = PhoneAjaxRequest::check_email_confirmation(&*session_id);

    let response: GenericSuccessResponse = client
        .request_with_session_guard_and_decode::<_, _, GenericSuccessResponse>(
            PHONEAJAX_URL.to_owned(),
            Method::POST,
            None,
            Some(payload),
            None::<&str>,
        )
        .await?;

    Ok(response.success)
}

pub async fn add_phone_to_account(client: &MobileClient, phone_number: &str) -> LinkerResult<bool> {
    let session_id =
        dump_cookies_by_domain_and_name(&client.cookie_store.read(), STEAM_COMMUNITY_HOST, "sessionid").unwrap();

    let payload = PhoneAjaxRequest::add_phone(&*session_id, phone_number);

    let response = client
        .request_with_session_guard_and_decode::<_, _, GenericSuccessResponse>(
            PHONEAJAX_URL.to_owned(),
            Method::POST,
            None,
            Some(payload),
            None::<&str>,
        )
        .await?;

    Ok(response.success)
}

pub fn validate_phone_number(phone_number: &str) -> bool {
    phone_number.starts_with('+')
}

/// Last step to add a new authenticator.
pub(crate) async fn finalize(
    client: &MobileClient,
    cached_data: RwLockReadGuard<'_, RawRwLock, SteamCache>,
    mafile: &MobileAuthFile,
    sms_code: &str,
) -> LinkerResult<()> {
    let steamid = cached_data.steam_id().to_string();
    let oauth_token = cached_data.oauth_token();

    let finalize_url = format!(
        "{}{}",
        STEAM_API_BASE, "/ITwoFactorService/FinalizeAddAuthenticator/v0001"
    );

    let mut initial_payload = FinalizeAddAuthenticatorRequest {
        steamid: &*steamid,
        oauth_token,
        sms_activation_code: sms_code,
        ..Default::default()
    };

    let account_secret = steam_totp::Secret::from_b64(&mafile.shared_secret).unwrap();

    let mut tries: usize = 0;
    while tries <= 30 {
        let (code, mut time) = steam_totp::generate_auth_code_with_time_async(account_secret.clone()).await?;
        time.0 += 1;
        initial_payload.swap_codes(code, time.0);

        let response_text = client
            .request_with_session_guard(
                finalize_url.clone(),
                Method::POST,
                None,
                Some(&initial_payload),
                None::<&str>,
            )
            .and_then(|resp| resp.text().err_into())
            .await?;

        debug!("FinalizeAuthenticator raw response: {:#}", response_text);

        let response = match serde_json::from_str::<FinalizeAddAuthenticatorBase>(&*response_text) {
            Ok(resp) => resp.response,
            Err(_err) => {
                let error_resp = serde_json::from_str::<FinalizeAddAuthenticatorErrorBase>(&*response_text).unwrap();
                return match error_resp.response.status {
                    89 => Err(LinkerError::BadSMSCode),
                    88 => {
                        if tries == 30 {
                            return Err(LinkerError::UnableToGenerateCorrectCodes);
                        }
                        continue;
                    }
                    _ => Err(LinkerError::GeneralFailure("Something went wrong".to_string())),
                };
            }
        };

        // Steam want more codes, delay a bit and send all again.
        if response.want_more {
            Delay::new(Duration::from_secs(1)).await;
            tries += 1;
            continue;
        }

        return Ok(());
    }

    Err(LinkerError::GeneralFailure(
        "Maximum tries achieved. Something went wrong.".to_string(),
    ))
}

/// Add a new authenticator to this steam account.
///
///
/// User will receive a SMS message, with the code required to finalize registering the new authenticator.
/// Returns the VERY important `SteamGuardAccount`, that must be saved before the next step(finalize auth) is completed,
/// otherwise the user is on risk of losing the account, since the `revocation_code` will also be lost.
pub(crate) async fn add_authenticator_to_account(
    client: &MobileClient,
    cached_data: RwLockReadGuard<'_, RawRwLock, SteamCache>,
) -> Result<MobileAuthFile, LinkerError> {
    let add_auth_url = format!("{}{}", STEAM_API_BASE, "/ITwoFactorService/AddAuthenticator/v0001");
    let oauth_token = cached_data.oauth_token();
    let steamid = cached_data.steam_id().to_string();
    let time = steam_totp::time::Time::with_offset().await?.to_string();

    let payload = AddAuthenticatorRequest::new(oauth_token, &steamid, time.parse().unwrap());

    let response_text = client
        .request_with_session_guard(add_auth_url, Method::POST, None, Some(payload), None::<&str>)
        .and_then(|resp| resp.text().err_into())
        .await?;

    debug!("Steam addauth raw response: {:?}", response_text);

    let mut mafile = match serde_json::from_str::<AddAuthenticatorResponseBase>(&response_text) {
        Ok(resp) => resp.steam_guard_success_details.mobile_auth,
        Err(err) => {
            eprintln!("Error found deserializing add auth response: {:#?}", err);
            let error_resp = serde_json::from_str::<AddAuthenticatorErrorResponseBase>(&response_text).unwrap();
            return match error_resp.response.status {
                29 => Err(LinkerError::AuthenticatorPresent),
                2 => Err(LinkerError::GeneralFailure(
                    "After too many failed attempts, this may be a lock on the phone number or account. Going to test \
                     this tomorrow."
                        .to_string(),
                )),
                _ => Err(LinkerError::GeneralFailure("Something went wrong".to_string())),
            };
        }
    };
    mafile.set_device_id(generate_canonical_device_id(&steamid));
    Ok(mafile)
}

#[derive(Debug, PartialEq, Copy, Clone)]
pub enum RemoveAuthenticatorScheme {
    ReturnToEmailCodes,
    RemoveSteamGuard,
}

impl RemoveAuthenticatorScheme {
    fn as_str(self) -> &'static str {
        match self {
            RemoveAuthenticatorScheme::ReturnToEmailCodes => "1",
            RemoveAuthenticatorScheme::RemoveSteamGuard => "2",
        }
    }
}

/// Remove authenticator from account.
pub(crate) async fn remove_authenticator(
    client: &MobileClient,
    cached_data: RwLockReadGuard<'_, RawRwLock, SteamCache>,
    revocation_token: &str,
    remove_authenticator_scheme: RemoveAuthenticatorScheme,
) -> Result<(), AuthError> {
    let _url = format!(
        "{}{}",
        STEAM_API_BASE, "/ITwoFactorService/RemoveAuthenticator/v1?access_token="
    );

    let steamid = cached_data.steam_id().to_string();
    let oauth_token = cached_data.oauth_token();
    let payload = RemoveAuthenticatorRequest::new(oauth_token, steamid, revocation_token, remove_authenticator_scheme);

    // FIXME: add error handling and error variants
    client
        .request_with_session_guard_and_decode::<_, _, RemoveAuthenticatorResponseBase>(
            _url,
            Method::POST,
            None,
            Some(payload),
            None::<&str>,
        )
        .await
        .map(|_| ())
        .map_err(Into::into)
}