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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
//! Steam Community client.
//!
//! The main client for interacting with Steam Community web endpoints.

use std::{sync::Arc, time::Duration};

use base64::Engine;
use parking_lot::Mutex;
use prost::Message;
use reqwest::{Response, StatusCode};
use reqwest_middleware::{ClientBuilder, ClientWithMiddleware};
use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};

use crate::retry::KindAwareRetryStrategy;
use steam_enums::etokenrenewaltype::ETokenRenewalType;
use steam_protos::messages::auth::{CAuthenticationAccessTokenGenerateForAppRequest, CAuthenticationAccessTokenGenerateForAppResponse, CAuthenticationGetAuthSessionInfoRequest, CAuthenticationGetAuthSessionInfoResponse};
use steamid::SteamID;

use crate::{error::SteamUserError, session::Session, utils::qr::decode_login_qr_url};

/// Default User-Agent (Chrome-like).
const DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36";

const DEFAULT_TIMEOUT: Duration = Duration::from_secs(300);
const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(30);

/// Timeout for fetches to non-Steam hosts (image CDNs, user-supplied URLs).
/// Shorter than `DEFAULT_TIMEOUT` because we don't owe arbitrary external
/// hosts the same patience we owe Steam.
const EXTERNAL_TIMEOUT: Duration = Duration::from_secs(60);

/// Inner wrapper to prevent accidental bypass of request builder overrides
#[derive(Debug, Clone)]
pub(crate) struct InnerHttpClient(ClientWithMiddleware);

/// Steam Community web client.
///
/// Provides HTTP-based interactions with Steam Community endpoints.
///
/// `SteamUser` implements `Clone`. All clones share the same cookie jar
/// (`Arc<Jar>`) and rate-limiter (`Arc<SteamRateLimiter>`), so they stay in
/// sync for cookies and rate limits. The `time_offset` is copied by value at
/// clone time.
#[derive(Debug)]
pub struct SteamUser {
    /// HTTP client with cookie support.
    pub(crate) client: InnerHttpClient,
    /// HTTP client for non-Steam hosts. Has no cookie jar, no Steam
    /// rate-limiter, and a shorter timeout. Use via `external_get` /
    /// `external_post` for arbitrary external URLs (e.g. user-supplied
    /// image URLs); never use it for Steam endpoints.
    pub(crate) external_client: reqwest::Client,
    /// HTTP client for Steam endpoints with redirect-following disabled,
    /// used by `get_with_manual_redirects`. Shares the same cookie jar
    /// as `client` so cookies stay in sync across redirect hops. Built
    /// once in the constructor instead of per-call.
    pub(crate) no_redirect_client: reqwest::Client,
    /// Session state (cookies, steam_id, etc.).
    pub session: Session,
    /// Time offset from Steam servers (for TOTP), behind Mutex for interior
    /// mutability.
    pub(crate) time_offset: Mutex<Option<i64>>,
    /// Optional per-session rate limiter.
    pub(crate) session_limiter: Option<Arc<crate::limiter::SteamRateLimiter>>,
}

impl Clone for SteamUser {
    fn clone(&self) -> Self {
        Self {
            client: self.client.clone(),
            external_client: self.external_client.clone(),
            no_redirect_client: self.no_redirect_client.clone(),
            session: self.session.clone(),
            time_offset: Mutex::new(*self.time_offset.lock()),
            session_limiter: self.session_limiter.clone(),
        }
    }
}

/// Builder for [`SteamUser`].
///
/// Obtained via [`SteamUser::builder`]. Required field: cookies. All other
/// fields fall back to the same defaults that [`SteamUser::new`] uses.
#[derive(Debug, Default)]
pub struct SteamUserBuilder {
    cookies: Vec<String>,
    rate_limit: Option<(u32, u32)>,
    timeout: Option<Duration>,
    connect_timeout: Option<Duration>,
    external_timeout: Option<Duration>,
    user_agent: Option<String>,
    retry_count: Option<u32>,
}

impl SteamUserBuilder {
    /// Set the session cookies. Replaces any previously-set cookies.
    pub fn cookies<S: AsRef<str>>(mut self, cookies: &[S]) -> Self {
        self.cookies = cookies.iter().map(|s| s.as_ref().to_string()).collect();
        self
    }

    /// Set a per-session rate limit (requests-per-minute, burst).
    /// Applied in addition to the global IP-wide limit.
    pub fn rate_limit(mut self, requests_per_minute: u32, burst: u32) -> Self {
        self.rate_limit = Some((requests_per_minute, burst));
        self
    }

    /// Override the per-request timeout (default: 300s).
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Override the TCP connect timeout (default: 30s).
    pub fn connect_timeout(mut self, connect_timeout: Duration) -> Self {
        self.connect_timeout = Some(connect_timeout);
        self
    }

    /// Override the timeout for the external (non-Steam) client (default: 60s).
    pub fn external_timeout(mut self, external_timeout: Duration) -> Self {
        self.external_timeout = Some(external_timeout);
        self
    }

    /// Override the User-Agent header.
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = Some(user_agent.into());
        self
    }

    /// Override the retry count (default: 3 retries = 4 total attempts).
    pub fn retry_count(mut self, retry_count: u32) -> Self {
        self.retry_count = Some(retry_count);
        self
    }

    /// Build the `SteamUser`. Validates inputs and constructs all three
    /// HTTP clients (Steam, no-redirect Steam, external).
    pub fn build(self) -> Result<SteamUser, SteamUserError> {
        let timeout = self.timeout.unwrap_or(DEFAULT_TIMEOUT);
        let connect_timeout = self.connect_timeout.unwrap_or(DEFAULT_CONNECT_TIMEOUT);
        let external_timeout = self.external_timeout.unwrap_or(EXTERNAL_TIMEOUT);
        let user_agent = self.user_agent.as_deref().unwrap_or(DEFAULT_USER_AGENT);
        let retry_count = self.retry_count.unwrap_or(3);

        let mut session = Session::new();
        let cookie_refs: Vec<&str> = self.cookies.iter().map(|s| s.as_str()).collect();
        session.set_cookies(&cookie_refs)?;
        session.ensure_session_id();

        let reqwest_client = reqwest::Client::builder().cookie_provider(Arc::clone(&session.jar)).connect_timeout(connect_timeout).timeout(timeout).user_agent(user_agent).gzip(true).min_tls_version(reqwest::tls::Version::TLS_1_2).https_only(true).build().map_err(|e| SteamUserError::ClientBuild(e.to_string()))?;

        let retry_policy = ExponentialBackoff::builder().build_with_max_retries(retry_count);
        let client = ClientBuilder::new(reqwest_client).with(reqwest_tracing::TracingMiddleware::default()).with(RetryTransientMiddleware::new_with_policy_and_strategy(retry_policy, KindAwareRetryStrategy)).build();

        let external_client = reqwest::Client::builder().connect_timeout(connect_timeout).timeout(external_timeout).user_agent(user_agent).gzip(true).min_tls_version(reqwest::tls::Version::TLS_1_2).https_only(true).build().map_err(|e| SteamUserError::ClientBuild(e.to_string()))?;

        let no_redirect_client = reqwest::Client::builder().cookie_provider(Arc::clone(&session.jar)).connect_timeout(connect_timeout).timeout(timeout).user_agent(user_agent).gzip(true).min_tls_version(reqwest::tls::Version::TLS_1_2).https_only(true).redirect(reqwest::redirect::Policy::none()).build().map_err(|e| SteamUserError::ClientBuild(e.to_string()))?;

        let session_limiter = match self.rate_limit {
            Some((rpm, burst)) => {
                use std::num::NonZeroU32;

                use governor::{Quota, RateLimiter};
                let rpm = NonZeroU32::new(rpm).ok_or_else(|| SteamUserError::InvalidInput("`requests_per_minute` must be non-zero".into()))?;
                let burst = NonZeroU32::new(burst).ok_or_else(|| SteamUserError::InvalidInput("`burst` must be non-zero".into()))?;
                Some(Arc::new(RateLimiter::direct(Quota::per_minute(rpm).allow_burst(burst))))
            }
            None => None,
        };

        Ok(SteamUser { client: InnerHttpClient(client), external_client, no_redirect_client, session, time_offset: Mutex::new(None), session_limiter })
    }
}

impl SteamUser {
    /// Creates a new `SteamUser` client with the provided cookies.
    ///
    /// Convenience wrapper over [`SteamUser::builder`] with default
    /// timeouts and user-agent. Use the builder when you need to tweak
    /// any of those.
    ///
    /// # Arguments
    ///
    /// * `cookies` - A slice of cookie strings in "name=value" format.
    ///
    /// # Errors
    ///
    /// Returns a `SteamUserError` if the cookies are invalid or could not be
    /// parsed.
    #[tracing::instrument(skip(cookies))]
    pub fn new(cookies: &[&str]) -> Result<Self, SteamUserError> {
        Self::builder().cookies(cookies).build()
    }

    /// Returns a builder for configuring a new `SteamUser`.
    ///
    /// Use the builder to override defaults (timeouts, user-agent, retry
    /// count) or to set a per-session rate limit at construction time
    /// instead of via [`Self::with_rate_limit`].
    pub fn builder() -> SteamUserBuilder {
        SteamUserBuilder::default()
    }

    /// Sets a per-session rate limit for this `SteamUser`.
    ///
    /// This limit is applied *in addition* to the global IP-wide limit.
    ///
    /// # Errors
    ///
    /// Returns an error if `requests_per_minute` or `burst` is zero.
    pub fn with_rate_limit(mut self, requests_per_minute: u32, burst: u32) -> Result<Self, crate::SteamUserError> {
        use std::num::NonZeroU32;

        use governor::{Quota, RateLimiter};

        let rpm = NonZeroU32::new(requests_per_minute).ok_or_else(|| crate::SteamUserError::InvalidInput("`requests_per_minute` must be non-zero".into()))?;
        let burst = NonZeroU32::new(burst).ok_or_else(|| crate::SteamUserError::InvalidInput("`burst` must be non-zero".into()))?;

        self.session_limiter = Some(Arc::new(RateLimiter::direct(Quota::per_minute(rpm).allow_burst(burst))));
        Ok(self)
    }

    /// Returns the current `SteamID` if the user is logged in.
    pub fn steam_id(&self) -> Option<SteamID> {
        self.session.steam_id
    }

    /// Creates a GET request with default query parameters (e.g., language set
    /// to English).
    ///
    /// # Arguments
    ///
    /// * `url` - The target URL for the GET request.
    pub fn get(&self, url: impl reqwest::IntoUrl) -> SteamRequestBuilder {
        // GET requests don't typically need sessionid in body/form, only query.
        // The base request method already adds it to query.
        self.request(reqwest::Method::GET, url)
    }

    /// Creates a POST request to the specified URL.
    ///
    /// This method returns a `SteamRequestBuilder` which automatically appends
    /// the session ID to form or multipart data if it's available.
    pub fn post(&self, url: impl reqwest::IntoUrl) -> SteamRequestBuilder {
        self.request(reqwest::Method::POST, url)
    }

    /// Creates a GET request using a relative path resolved against the
    /// current `#[steam_endpoint]`'s host.
    ///
    /// # Panics
    ///
    /// Panics if called outside a `#[steam_endpoint]`-annotated method.
    pub fn get_path(&self, path: impl std::fmt::Display) -> SteamRequestBuilder {
        self.request_path(reqwest::Method::GET, path)
    }

    /// Creates a POST request using a relative path resolved against the
    /// current `#[steam_endpoint]`'s host.
    ///
    /// # Panics
    ///
    /// Panics if called outside a `#[steam_endpoint]`-annotated method.
    pub fn post_path(&self, path: impl std::fmt::Display) -> SteamRequestBuilder {
        self.request_path(reqwest::Method::POST, path)
    }

    fn request_path(&self, method: reqwest::Method, path: impl std::fmt::Display) -> SteamRequestBuilder {
        let base = crate::endpoint::current_endpoint()
            .expect("*_path() called outside a #[steam_endpoint] method")
            .host
            .base_url();
        self.request(method, format!("{base}{path}"))
    }

    /// Creates a GET request against an explicit Steam host, regardless of
    /// the current `#[steam_endpoint]` (if any).
    ///
    /// Use when a Steam endpoint is reached on a host other than the one
    /// declared by the enclosing method's `#[steam_endpoint]` attribute —
    /// for example, a Help-host URL composed at runtime from inside a
    /// Community-host method.
    ///
    /// Cookies, `sessionid` injection, and the per-host rate limiter are
    /// applied exactly as in `get_path`.
    pub fn get_path_on(&self, host: crate::endpoint::Host, path: impl std::fmt::Display) -> SteamRequestBuilder {
        self.request(reqwest::Method::GET, format!("{}{}", host.base_url(), path))
    }

    /// Creates a POST request against an explicit Steam host. See
    /// [`Self::get_path_on`] for the use case.
    pub fn post_path_on(&self, host: crate::endpoint::Host, path: impl std::fmt::Display) -> SteamRequestBuilder {
        self.request(reqwest::Method::POST, format!("{}{}", host.base_url(), path))
    }

    /// Creates a GET request to a non-Steam URL using the external client.
    ///
    /// **Use only for URLs that are NOT on Steam-owned hosts** — for
    /// example, fetching a user-supplied avatar image from an arbitrary
    /// CDN. Steam cookies are not attached, the Steam rate limiter is not
    /// engaged, and middleware (retry, tracing) is bypassed.
    ///
    /// Returns a plain `reqwest::RequestBuilder`, not a `SteamRequestBuilder`,
    /// because session-id injection and Steam-specific behaviour are
    /// inappropriate for external hosts.
    pub fn external_get(&self, url: impl reqwest::IntoUrl) -> reqwest::RequestBuilder {
        self.external_client.get(url)
    }

    /// Creates a POST request to a non-Steam URL using the external
    /// client. See [`Self::external_get`] for the use case.
    pub fn external_post(&self, url: impl reqwest::IntoUrl) -> reqwest::RequestBuilder {
        self.external_client.post(url)
    }

    /// Creates a request with the specified HTTP method and URL, including
    /// common query parameters.
    ///
    /// This is a low-level method used by `get` and `post`. It sets the default
    /// language and includes the session ID in the query parameters if it's
    /// available.
    #[allow(clippy::disallowed_methods)] // This IS the low-level wrapper; must call inner client.
    pub fn request(&self, method: reqwest::Method, url: impl reqwest::IntoUrl) -> SteamRequestBuilder {
        let mut builder = self.client.0.request(method.clone(), url).query(&[("l", "english")]);

        // Manually inject cookies if available
        if !self.session.cookie_string.is_empty() {
            builder = builder.header("Cookie", &self.session.cookie_string);
        }

        SteamRequestBuilder {
            builder,
            session_id: self.session.session_id.clone(),
            session_limiter: self.session_limiter.clone(),
            request_body: None,
            // Tracking-only field for debug logging; populated lazily when
            // `query()` is called. The `?l=english` is already on the
            // underlying `builder`.
            query: None,
            http_method: method,
        }
    }

    /// Steam host allowlist for redirect validation.
    ///
    /// A redirect `Location` whose host is not on this list (or a subdomain
    /// thereof) is rejected to prevent header-stripping / open-redirect abuse.
    fn is_steam_host(host: &str) -> bool {
        const ALLOWED: &[&str] = &[
            "steamcommunity.com",
            "store.steampowered.com",
            "help.steampowered.com",
            "api.steampowered.com",
            "steampowered.com",
            "s.team",
        ];
        for allowed in ALLOWED {
            if host == *allowed || host.ends_with(&format!(".{}", allowed)) {
                return true;
            }
        }
        false
    }

    /// Performs a GET request with manual redirect handling.
    ///
    /// This is needed for pages like trade offers where Steam redirects through
    /// `/market/eligibilitycheck/` which can fail with automatic redirect
    /// following. Uses a temporary no-redirect client and manually follows
    /// the redirect chain.
    pub async fn get_with_manual_redirects(&self, url: &str) -> Result<String, SteamUserError> {
        let no_redirect_client = &self.no_redirect_client;

        let mut current_url = url.to_string();
        let max_redirects = 10;
        let mut seen_urls = std::collections::HashSet::new();

        for i in 0..max_redirects {
            // Only add l=english on the first request; redirect URLs already contain it.
            // Do NOT manually set the Cookie header — the cookie jar (cookie_provider)
            // handles cookies automatically. This is critical: the eligibility
            // check response sets cookies that must be sent on subsequent
            // requests, and a static Cookie header would override the jar and
            // prevent those new cookies from being included.
            let mut request = no_redirect_client.get(&current_url);
            if i == 0 {
                request = request.query(&[("l", "english")]);
            }

            let response = request.send().await?;
            let status = response.status();

            if status.is_redirection() {
                if let Some(location) = response.headers().get(reqwest::header::LOCATION) {
                    let location_str = location.to_str().map_err(|e| SteamUserError::RedirectError(format!("Invalid Location header: {e}")))?;

                    // Resolve relative URLs against the current URL
                    let base = reqwest::Url::parse(&current_url).map_err(|e| SteamUserError::RedirectError(format!("Invalid base URL: {e}")))?;
                    let next_url = base.join(location_str).map_err(|e| SteamUserError::RedirectError(format!("Invalid redirect URL: {e}")))?;

                    // Reject redirects to non-Steam hosts to prevent open-redirect abuse.
                    let next_host = next_url.host_str().unwrap_or("");
                    if !Self::is_steam_host(next_host) {
                        return Err(SteamUserError::RedirectError(format!(
                            "Redirect to non-Steam host rejected: {}",
                            next_host
                        )));
                    }

                    tracing::debug!("[TradeOffers] Following redirect: {} -> {}", current_url, next_url);

                    // Detect redirect loops by checking the URL path (ignore query params)
                    let loop_key = next_url.path().to_string();
                    if !seen_urls.insert(loop_key) {
                        tracing::warn!("[TradeOffers] Redirect loop detected at {}, attempting direct fetch", next_url.path());
                        let direct_response = no_redirect_client.get(next_url.as_str()).send().await?;
                        if direct_response.status().is_success() {
                            return direct_response.text().await.map_err(SteamUserError::HttpError);
                        }
                        return Err(SteamUserError::HttpStatus { status: direct_response.status().as_u16(), url: next_url.to_string() });
                    }

                    current_url = next_url.to_string();
                    continue;
                }
                return Err(SteamUserError::RedirectError("Redirect without Location header".into()));
            }

            if status.is_success() {
                return response.text().await.map_err(SteamUserError::HttpError);
            }

            return Err(SteamUserError::HttpStatus { status: status.as_u16(), url: current_url.clone() });
        }

        Err(SteamUserError::RedirectError("Too many redirects".into()))
    }

    /// Returns the current session ID, generating one from cookies if it's not
    /// already cached.
    pub fn get_session_id(&mut self) -> &str {
        self.session.get_session_id()
    }

    /// Returns `true` if the client session has a Steam ID and session ID,
    /// suggesting the user is logged in.
    ///
    /// Note: This does not verify the session with Steam servers; use
    /// `logged_in()` for a definitive check.
    pub fn is_logged_in(&self) -> bool {
        self.session.is_logged_in()
    }

    /// Sets the mobile access token used for two-factor authentication (2FA)
    /// operations.
    pub fn set_mobile_access_token(&mut self, token: String) {
        self.session.set_mobile_access_token(token);
    }

    /// Sets the refresh token used for token enumeration and renewal.
    pub fn set_refresh_token(&mut self, token: String) {
        self.session.set_refresh_token(token);
    }

    /// Sets the access token.
    pub fn set_access_token(&mut self, token: String) {
        self.session.set_access_token(token);
    }

    /// Returns the cookies formatted as a string for web requests.
    ///
    /// This constructs the cookies using the access token and Steam ID,
    /// similar to the "simple" cookie logic in `steam-auth`.
    pub fn get_web_cookies(&self) -> String {
        let steam_id = self.session.steam_id.map(|id| id.steam_id64().to_string()).unwrap_or_default();
        let access_token = self.session.access_token.as_deref().unwrap_or_default();
        let session_id = self.session.session_id.as_deref().unwrap_or_default();

        let mut cookies = Vec::new();
        cookies.push(format!("steamLoginSecure={}||{}", steam_id, access_token));
        cookies.push(format!("sessionid={}", session_id));

        // Add domain-specific sessionid cookies if needed, but for string
        // representation this is usually sufficient or we'd need to know the
        // target domain. For general use, these two are the core authentication
        // cookies.

        cookies.join("; ")
    }

    /// Verifies the current login status by making a request to Steam.
    ///
    /// Returns a tuple containing:
    /// * `bool` - Whether the user is actually logged in.
    /// * `bool` - Whether the account is currently restricted by Family View.
    #[tracing::instrument(skip(self))]
    #[allow(clippy::disallowed_methods)] // Deliberately bypasses rate limiter for lightweight session check.
    pub async fn logged_in(&self) -> Result<(bool, bool), SteamUserError> {
        // Use the no-redirect client so we see the raw 302 that Steam issues
        // when `/my` resolves. The middleware client auto-follows redirects,
        // making the FOUND branch unreachable with it.
        let mut request = self.no_redirect_client.get("https://steamcommunity.com/my");

        // Manually inject cookies if available
        if !self.session.cookie_string.is_empty() {
            request = request.header("Cookie", &self.session.cookie_string);
        }

        let response = request.send().await?;

        let status = response.status();

        if status == StatusCode::FORBIDDEN {
            // 403 = Family View restricted but logged in
            return Ok((true, true));
        }

        if status == StatusCode::FOUND {
            // Primary login signal: Steam redirects /my to the user's profile
            // on success and to a login URL on failure.
            if let Some(location) = response.headers().get("location") {
                let loc_str = location.to_str().unwrap_or("");
                // Redirected to login page → not logged in
                if loc_str.contains("/login") || loc_str.contains("steampowered.com/login") {
                    return Ok((false, false));
                }
                // Redirected to profile page → logged in
                if loc_str.contains("/id/") || loc_str.contains("/profiles/") {
                    return Ok((true, false));
                }
            }
        }

        // Secondary signal: follow through to the resolved page body (rare fallback).
        if status == StatusCode::OK {
            let body = response.text().await.unwrap_or_default();
            // If we can see profile page content, we're logged in
            if body.contains("g_rgProfileData") || body.contains("actual_persona_name") {
                return Ok((true, false));
            }
        }

        // Any other case means not logged in
        Ok((false, false))
    }

    /// Renews the current access token using the stored refresh token.
    ///
    /// This is typically used when an access token has expired.
    #[tracing::instrument(skip(self))]
    #[allow(clippy::disallowed_methods)] // Uses raw API endpoint, not community page — rate limiter N/A.
    pub async fn renew_access_token(&mut self) -> Result<(), SteamUserError> {
        let refresh_token = self.session.refresh_token.clone().ok_or(SteamUserError::MissingCredential { field: "refresh_token" })?;

        let steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?;

        let request = CAuthenticationAccessTokenGenerateForAppRequest {
            refresh_token: Some(refresh_token.clone()),
            steamid: Some(steam_id.steam_id64()),
            renewal_type: Some(ETokenRenewalType::None as i32),
        };

        let mut body = Vec::new();
        request.encode(&mut body)?;

        // Construct query parameters (access_token moved to Authorization: Bearer)
        let params = [("origin", "https://store.steampowered.com")];

        let mut builder = self.client.0.post("https://api.steampowered.com/IAuthenticationService/GenerateAccessTokenForApp/v1").query(&params).form(&[("input_protobuf_encoded", base64::engine::general_purpose::STANDARD.encode(body))]);

        if let Some(token) = self.session.access_token.as_deref() {
            builder = builder.bearer_auth(token);
        }

        let response = builder.send().await?;

        if !response.status().is_success() {
            let status = response.status();
            let url = response.url().to_string();
            let text = response.text().await.unwrap_or_default();
            tracing::error!("Renew response error: {} - {}", status, text);
            return Err(SteamUserError::HttpStatus { status: status.as_u16(), url });
        }

        let bytes = response.bytes().await?;
        let response_proto = CAuthenticationAccessTokenGenerateForAppResponse::decode(bytes)?;

        // Debug logging
        tracing::debug!("[renew_access_token] Response received:");
        tracing::debug!("  - access_token present: {}", response_proto.access_token.is_some());
        tracing::debug!("  - refresh_token present: {}", response_proto.refresh_token.is_some());
        if let Some(ref token) = response_proto.access_token {
            tracing::info!(token_len = token.len(), "new access_token acquired");
        }

        if let Some(new_access_token) = response_proto.access_token {
            self.session.access_token = Some(new_access_token);
        } else {
            tracing::warn!("No new access token returned by Steam!");
        }

        if let Some(new_refresh_token) = response_proto.refresh_token {
            self.session.refresh_token = Some(new_refresh_token);
        }

        Ok(())
    }

    /// Retrieves authentication session information for a given QR challenge
    /// URL.
    ///
    /// This is used during the QR code login process to get details about the
    /// pending session.
    #[tracing::instrument(skip(self))]
    #[allow(clippy::disallowed_methods)] // Uses raw API endpoint, not community page — rate limiter N/A.
    pub async fn get_auth_session_info(&self, qr_challenge_url: &str) -> Result<CAuthenticationGetAuthSessionInfoResponse, SteamUserError> {
        let (client_id, _version) = decode_login_qr_url(qr_challenge_url).ok_or_else(|| SteamUserError::InvalidInput("Invalid QR challenge URL".into()))?;

        let request = CAuthenticationGetAuthSessionInfoRequest { client_id: Some(client_id) };

        let mut body = Vec::new();
        request.encode(&mut body)?;

        // We need an access token for this request
        let access_token = self.session.access_token.as_deref().ok_or(SteamUserError::MissingCredential { field: "access_token" })?;

        let params = [("access_token", access_token), ("spoof_steamid", ""), ("origin", "https://store.steampowered.com")];

        let response = self.client.0.post("https://api.steampowered.com/IAuthenticationService/GetAuthSessionInfo/v1/").query(&params).multipart(reqwest::multipart::Form::new().part("input_protobuf_encoded", reqwest::multipart::Part::bytes(body))).send().await?;

        self.check_response(&response)?;

        let bytes = response.bytes().await?;
        let response_proto = CAuthenticationGetAuthSessionInfoResponse::decode(bytes)?;

        Ok(response_proto)
    }

    /// Retrieves the Steam Chat client JS token.
    ///
    /// This token is used for authenticating with the Steam Chat WebSocket
    /// connection. It is fetched from `https://steamcommunity.com/chat/clientjstoken`.
    ///
    /// # Returns
    ///
    /// Returns a `ClientJsToken` struct if successful.
    ///
    /// # Errors
    ///
    /// Returns a `SteamUserError` if the request fails or the user is not
    /// logged in.
    #[allow(clippy::disallowed_methods)] // Utility on client itself, not a service endpoint.
    pub async fn get_client_js_token(&self) -> Result<ClientJsToken, SteamUserError> {
        let url = "https://steamcommunity.com/chat/clientjstoken";
        let response = self.get(url).send().await?;
        self.check_response(&response)?;

        let token: ClientJsToken = response.json().await?;

        if !token.logged_in {
            return Err(SteamUserError::NotLoggedIn);
        }

        Ok(token)
    }

    // ========================================================================
    // Internal HTTP helpers
    // ========================================================================

    /// Check response for common errors.
    pub(crate) fn check_response(&self, response: &Response) -> Result<(), SteamUserError> {
        let status = response.status();

        // Detect login redirects that were auto-followed by reqwest.
        // The final status is 200 but the URL reveals we landed on the login page.
        // Strict host match (apex or true subdomain) prevents lookalikes like `evil-steamcommunity.com`.
        // Note: reqwest follows 30x by default, so a 302→/login arrives here as 200; the legacy
        // `is_redirection()` branch below would be dead code if we relied only on status.
        let url = response.url();
        let on_steam_host = url.host_str().is_some_and(|h| {
            h == "steamcommunity.com" || h.ends_with(".steamcommunity.com") || h == "steampowered.com" || h.ends_with(".steampowered.com")
        });
        let path = url.path();
        if on_steam_host && (path == "/login" || path.starts_with("/login/")) {
            return Err(SteamUserError::NotLoggedIn);
        }

        if status.is_success() {
            return Ok(());
        }

        if status == StatusCode::FORBIDDEN {
            return Err(SteamUserError::FamilyViewRestricted);
        }

        if status.is_client_error() || status.is_server_error() {
            let url = response.url().to_string();
            return Err(SteamUserError::HttpStatus { status: status.as_u16(), url });
        }

        Ok(())
    }

    /// Check if a JSON response indicates success.
    pub(crate) fn check_json_success<'a>(json: &'a serde_json::Value, error_msg: &str) -> Result<&'a serde_json::Value, SteamUserError> {
        if let Some(success) = json.get("success") {
            if let Some(b) = success.as_bool() {
                if b {
                    return Ok(json);
                }
            } else if let Some(i) = success.as_i64() {
                if i == 1 {
                    return Ok(json);
                }
            }
        }

        if let Some(eresult) = json.get("eresult").and_then(|v| v.as_i64()) {
            if eresult != 1 {
                return Err(SteamUserError::from_eresult(eresult as i32));
            }
        }

        Err(SteamUserError::SteamError(error_msg.to_string()))
    }
}

/// A wrapper around request builder that automatically appends
/// the session ID to POST data.
pub struct SteamRequestBuilder {
    builder: reqwest_middleware::RequestBuilder,
    session_id: Option<String>,
    session_limiter: Option<Arc<crate::limiter::SteamRateLimiter>>,
    request_body: Option<serde_json::Value>,
    query: Option<serde_json::Value>,
    http_method: reqwest::Method,
}

impl SteamRequestBuilder {
    /// Adds a form body to the request.
    ///
    /// If a session ID is available, it is automatically injected as
    /// `sessionid` and `sessionID` into the form data.
    pub fn form<T: serde::Serialize + ?Sized>(mut self, form: &T) -> Self {
        if let Some(session_id) = &self.session_id {
            // We need to merge the session ID into the form.
            // This is tricky because T is generic.
            // We convert to a Value first.
            if let Ok(mut value) = serde_json::to_value(form) {
                if let Some(obj) = value.as_object_mut() {
                    obj.insert("sessionid".to_string(), serde_json::Value::String(session_id.clone()));
                    obj.insert("sessionID".to_string(), serde_json::Value::String(session_id.clone()));
                    self.request_body = Some(serde_json::Value::Object(obj.clone()));
                    self.builder = self.builder.form(&value);
                    return self;
                } else if let Some(arr) = value.as_array() {
                    // Handle array of tuples [["key", "val"], ...] or [("key", "val"), ...]
                    // Convert to a map for proper form serialization
                    let mut map = serde_json::Map::new();
                    for item in arr {
                        if let Some(tuple_arr) = item.as_array() {
                            if tuple_arr.len() == 2 {
                                if let (Some(key), Some(val)) = (tuple_arr[0].as_str(), tuple_arr[1].as_str()) {
                                    map.insert(key.to_string(), serde_json::Value::String(val.to_string()));
                                }
                            }
                        }
                    }
                    map.insert("sessionid".to_string(), serde_json::Value::String(session_id.clone()));
                    map.insert("sessionID".to_string(), serde_json::Value::String(session_id.clone()));
                    self.request_body = Some(serde_json::Value::Object(map.clone()));
                    self.builder = self.builder.form(&serde_json::Value::Object(map));
                    return self;
                }
            }
        }
        self.request_body = serde_json::to_value(form).ok();
        self.builder = self.builder.form(form);
        self
    }

    /// Adds a multipart form body to the request.
    ///
    /// If a session ID is available, it is automatically appended to the
    /// multipart data.
    pub fn multipart(mut self, mut form: reqwest::multipart::Form) -> Self {
        if let Some(session_id) = &self.session_id {
            form = form.text("sessionid", session_id.clone()).text("sessionID", session_id.clone());
        }
        self.builder = self.builder.multipart(form);
        self
    }

    /// Adds a query parameter to the request.
    pub fn query<T: serde::Serialize + ?Sized>(mut self, query: &T) -> Self {
        if let Ok(value) = serde_json::to_value(query) {
            if let Some(ref mut existing) = self.query {
                if let (Some(e_obj), Some(n_obj)) = (existing.as_object_mut(), value.as_object()) {
                    for (k, v) in n_obj {
                        e_obj.insert(k.clone(), v.clone());
                    }
                } else {
                    self.query = Some(value);
                }
            } else {
                self.query = Some(value);
            }
        }
        self.builder = self.builder.query(query);
        self
    }

    /// Adds a header to the request.
    pub fn header<K, V>(mut self, key: K, value: V) -> Self
    where
        reqwest::header::HeaderName: TryFrom<K>,
        <reqwest::header::HeaderName as TryFrom<K>>::Error: Into<http::Error>,
        reqwest::header::HeaderValue: TryFrom<V>,
        <reqwest::header::HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
    {
        self.builder = self.builder.header(key, value);
        self
    }

    /// Sends the request and returns the response.
    pub async fn send(self) -> Result<reqwest::Response, reqwest_middleware::Error> {
        // Record the HTTP method on the current tracing span so the
        // `MongoLogLayer` can pick it up from the span tree.
        tracing::Span::current().record("http_method", self.http_method.as_str());

        // Resolve the active endpoint metadata (set by #[steam_endpoint]).
        // `None` is fine — utility methods like `logged_in` and
        // `renew_access_token` issue HTTP without going through an annotated
        // method; they fall back to global rate limiting only.
        let endpoint = crate::endpoint::current_endpoint();

        // 1. Per-session limit (sequential — bounded to this caller, never blocks others)
        if let Some(limiter) = &self.session_limiter {
            limiter.until_ready().await;
        }

        // 2. Acquire global permit first, then per-host permit sequentially.
        //    Acquiring them concurrently via tokio::join! wastes the host
        //    permit when the global limiter is mid-lockout (the host permit
        //    is consumed immediately, then we wait on global anyway).
        crate::limiter::wait_for_permit().await;
        if let Some(ep) = endpoint {
            crate::limiter::wait_for_host_permit(ep.host).await;
        }

        // Send request
        let response = self.builder.send().await?;

        let status = response.status();
        let url = response.url().clone();
        let headers = response.headers().clone();

        // Record the URL on the current span for the MongoLogLayer,
        // stripping sensitive query parameters.
        let safe_url = redact_url_params(&url);
        tracing::Span::current().record("url", safe_url.as_str());

        tracing::info!(status = %status, url = %safe_url, "steam response");

        // Bump the metric counter once per request. Deliberately not
        // status-code-aware in v1 — that lives on the tracing layer.
        if let Some(ep) = endpoint {
            crate::endpoint::metrics().record_call(ep);
        }

        // 4. Handle 429 Reactive Backoff (before consuming the body).
        //    Read Retry-After; accept delta-seconds and HTTP-date formats.
        if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
            let retry_after = headers
                .get(reqwest::header::RETRY_AFTER)
                .and_then(|v| v.to_str().ok())
                .and_then(|s| {
                    // Try delta-seconds first
                    if let Ok(secs) = s.trim().parse::<u64>() {
                        return Some(std::time::Duration::from_secs(secs));
                    }
                    // Try HTTP-date format (RFC 7231)
                    if let Ok(dt) = httpdate::parse_http_date(s) {
                        let now = std::time::SystemTime::now();
                        return dt.duration_since(now).ok();
                    }
                    None
                })
                .unwrap_or_else(|| std::time::Duration::from_secs(60));
            crate::limiter::penalize_abuse(retry_after);
        }

        if tracing::enabled!(tracing::Level::DEBUG) {
            if let Some(ref req_body) = self.request_body {
                tracing::debug!(body = %req_body, "request body");
            }
            if let Some(ref query) = self.query {
                tracing::debug!(query = %query, "request query");
            }
        }

        // Stash the final URL before consuming the response — reqwest::Response::from(http::Response)
        // does not preserve it, so we capture it here for logging/debugging.
        let final_url = response.url().clone();

        // Buffer the response body so we can record `raw_response` on the
        // span for MongoLogLayer, then reconstruct the response for the caller.
        let version = response.version();
        let headers = response.headers().clone();
        let bytes = response.bytes().await?;

        let content_type = headers
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|h| h.to_str().ok())
            .unwrap_or("");

        // Record response metadata on the span for MongoLogLayer.
        if !content_type.is_empty() {
            tracing::Span::current().record("content_type", content_type);
        }
        let response_type_str = if content_type.contains("json") {
            "json"
        } else if content_type.contains("html") {
            "html"
        } else if content_type.contains("xml") {
            "xml"
        } else if content_type.contains("javascript") || content_type.contains("text") {
            "text"
        } else if content_type.contains("protobuf")
            || content_type.contains("octet-stream")
            || content_type.contains("image")
        {
            "binary"
        } else {
            "unknown"
        };
        tracing::Span::current().record("response_type", response_type_str);

        if content_type.contains("text")
            || content_type.contains("json")
            || content_type.contains("javascript")
            || content_type.contains("xml")
        {
            let body_str = String::from_utf8_lossy(&bytes);
            tracing::Span::current().record("raw_response", body_str.as_ref());
            if tracing::enabled!(tracing::Level::DEBUG) {
                tracing::debug!(body = %body_str, "response body");
            }
        } else if tracing::enabled!(tracing::Level::DEBUG) {
            tracing::debug!(bytes = bytes.len(), content_type, url = %final_url, "response body (binary)");
        }

        let mut builder = http::Response::builder().status(status).version(version);
        for (name, value) in headers.iter() {
            builder = builder.header(name, value);
        }
        let http_resp = builder.body(bytes).map_err(|e| {
            reqwest_middleware::Error::Middleware(anyhow::anyhow!(
                "Failed to reconstruct response: {e}"
            ))
        })?;
        Ok(reqwest::Response::from(http_resp))
    }

    /// Sets the request body.
    pub fn body<T: Into<reqwest::Body>>(mut self, body: T) -> Self {
        self.builder = self.builder.body(body);
        self
    }
}

const REDACTED_PARAMS: &[&str] = &["access_token", "key", "oauth_token", "webapi_token"];

fn redact_url_params(url: &reqwest::Url) -> String {
    if url.query().is_none() {
        return url.to_string();
    }

    let has_sensitive = url
        .query_pairs()
        .any(|(k, _)| REDACTED_PARAMS.contains(&k.as_ref()));

    if !has_sensitive {
        return url.to_string();
    }

    let mut redacted = url.clone();
    let filtered: Vec<(String, String)> = url
        .query_pairs()
        .map(|(k, v)| {
            if REDACTED_PARAMS.contains(&k.as_ref()) {
                (k.into_owned(), "[REDACTED]".to_string())
            } else {
                (k.into_owned(), v.into_owned())
            }
        })
        .collect();

    let qs: String = filtered
        .iter()
        .map(|(k, v)| format!("{k}={v}"))
        .collect::<Vec<_>>()
        .join("&");
    redacted.set_query(Some(&qs));
    redacted.to_string()
}

/// Token response from /chat/clientjstoken endpoint.
#[derive(Debug, serde::Deserialize)]
pub struct ClientJsToken {
    pub logged_in: bool,
    pub steamid: Option<String>,
    pub account_name: Option<String>,
    pub token: Option<String>,
}