twitch_oauth_token 4.0.1

Type-safe Twitch OAuth 2.0 authentication library with CSRF protection and full scope support
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
use std::{
    fmt::{Debug, Display, Formatter, Result as FmtResult},
    marker::PhantomData,
    str::FromStr,
};

use asknothingx2_util::api::IntoRequestBuilder;
use reqwest::Client;

use crate::{
    csrf::{self, CsrfConfig},
    error,
    request::{
        ClientCredentialsRequest, ExchangeCodeRequest, RefreshRequest, RevokeRequest,
        ValidateRequest,
    },
    types::GrantType,
    AccessToken, AuthUrl, AuthorizationCode, AuthrozationRequest, ClientId, ClientSecret, Error,
    RedirectUrl, RefreshToken, RevocationUrl, TokenUrl, ValidateUrl,
};

pub const AUTH_URL: &str = "https://id.twitch.tv/oauth2/authorize";
pub const TOKEN_URL: &str = "https://id.twitch.tv/oauth2/token";
pub const REVOKE_URL: &str = "https://id.twitch.tv/oauth2/revoke";
pub const VALIDATE_URL: &str = "https://id.twitch.tv/oauth2/validate";

mod private {
    pub trait Sealed {}
}

/// Marker trait for OAuth flow types - prevents external implementations
pub trait OauthFlow: private::Sealed + Debug + Clone + Copy {
    type RedirectUrl: Debug;
}

/// **App Authentication** (Client Credentials Flow)
///
/// Use this flow when your application needs to:
/// - Make API calls on behalf of your app (not users)
/// - Access public data (streams, games, users)
/// - Run as a backend service without user interaction
///
/// **Cannot do:**
/// - Access user-specific data (follows, subscriptions)
/// - Perform actions on behalf of users
/// - Handle user login flows
///
#[derive(Debug, Clone, Copy)]
pub struct AppAuth;
impl private::Sealed for AppAuth {}
impl OauthFlow for AppAuth {
    type RedirectUrl = ();
}

/// **User Authentication** (Authorization Code Flow)
///
/// Use this flow when your application needs to:
/// - Allow users to log in with their Twitch account
/// - Access user-specific data (follows, subscriptions, chat)
/// - Perform actions on behalf of users
/// - Get long-lived refresh tokens
///
/// **Requires:**
/// - A redirect URI (where Twitch sends the user after login)
/// - User interaction (they must visit the auth URL)
///
#[derive(Debug, Clone, Copy)]
pub struct UserAuth;
impl private::Sealed for UserAuth {}
impl OauthFlow for UserAuth {
    type RedirectUrl = RedirectUrl;
}

/// **OAuth client for Twitch API authentication**
///
/// The client supports two authentication flows:
/// - **AppAuth**: For server-to-server communication (no user interaction)
/// - **UserAuth**: For user authentication flows (requires redirect URI)
///
/// **App authentication** (most common for backend services):
/// ```no_run
/// use twitch_oauth_token::TwitchOauth;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let oauth = TwitchOauth::new("client_id", "client_secret");
///     
///     let token = oauth.app_access_token().await?;
///     
///     println!("App token: {}", token.access_token.secret());
///     Ok(())
/// }
/// ```
///
/// **User authentication** (for user login flows):
/// ```no_run
/// use std::str::FromStr;
/// use twitch_oauth_token::{TwitchOauth, RedirectUrl};
///
/// #[tokio::main]
/// async fn main() -> Result<(), twitch_oauth_token::Error> {
///     let oauth = TwitchOauth::new("your_client_id", "your_client_secret")
///         .with_redirect_uri(RedirectUrl::from_str("http://localhost:3000/auth/callback").unwrap());
///     
///     // Step 1: Get authorization URL (send user here)
///     let auth_request = oauth.authorization_url();
///     println!("Visit: {}", auth_request.url());
///     
///     // Step 2: After user authorizes, exchange code for token
///     // let token = oauth.exchange_code(code, state).await?;
///     
///     Ok(())
/// }
/// ```
#[derive(Clone)]
pub struct TwitchOauth<Flow = AppAuth>
where
    Flow: OauthFlow,
{
    client_id: ClientId,
    client_secret: ClientSecret,
    redirect_uri: Flow::RedirectUrl,
    secret_key: [u8; 32],
    client: Client,
    token_url: TokenUrl,
    auth_url: AuthUrl,
    revoke_url: RevocationUrl,
    validate_url: ValidateUrl,
    csrf_config: CsrfConfig,
    phanthom: PhantomData<Flow>,
}

impl<Flow> TwitchOauth<Flow>
where
    Flow: OauthFlow,
{
    /// Get the client ID
    pub fn client_id(&self) -> &ClientId {
        &self.client_id
    }

    /// Get the client secret
    #[deprecated(note = "accessing client_secret is discouraged for security reasons")]
    pub fn client_secret(&self) -> &ClientSecret {
        &self.client_secret
    }

    /// Override the HTTP client
    ///
    /// Note: This only affects this OAuth instance, not the global client.
    /// For global configuration, use [client::setup()](crate::client::setup()) instead.
    pub fn with_client(mut self, client: Client) -> Self {
        self.client = client;
        self
    }

    /// Configure CSRF token validation settings
    ///
    /// This controls how CSRF tokens are validated during the OAuth flow.
    /// Tokens use HMAC-SHA256 signatures with timestamp validation.
    ///
    /// Defaults:
    /// - max_age: 1800s (30 minutes)
    /// - clock_skew: None (no tolerance for time differences)
    ///
    /// Note: For multi-server deployments, also use [`TwitchOauth<UserAuth>::with_secret_key`] to share
    /// the same secret across all instances.
    pub fn with_csrf_config(mut self, config: CsrfConfig) -> Self {
        self.csrf_config = config;
        self
    }

    /// Override the authorization URL
    ///
    /// Default: `https://id.twitch.tv/oauth2/authorize`
    pub fn with_auth_url(mut self, auth_url: AuthUrl) -> Self {
        self.auth_url = auth_url;
        self
    }

    /// Override the token URL
    ///
    /// Default: `https://id.twitch.tv/oauth2/token`
    pub fn with_token_url(mut self, token_url: TokenUrl) -> Self {
        self.token_url = token_url;
        self
    }

    /// Override the revocation URL
    ///
    /// Default: `https://id.twitch.tv/oauth2/revoke`
    pub fn with_revoke_url(mut self, revoke_url: RevocationUrl) -> Self {
        self.revoke_url = revoke_url;
        self
    }

    /// Override the token validation URL
    ///
    /// Default: `https://id.twitch.tv/oauth2/validate`
    pub fn with_validate_url(mut self, validate_url: ValidateUrl) -> Self {
        self.validate_url = validate_url;
        self
    }

    /// Update the client secret at runtime
    ///
    /// Use this when you need to rotate credentials in a running application,
    /// especially in `Arc<RwLock<TwitchOauth>>` patterns.
    ///
    /// For initial configuration during construction, use [`TwitchOauth::new`] instead.
    pub fn set_client_secret(&mut self, client_secret: ClientSecret) {
        self.client_secret = client_secret;
    }

    /// Update CSRF token validation settings at runtime
    ///
    /// Use this to adjust CSRF validation behavior in a running application,
    /// especially in `Arc<RwLock<TwitchOauth>>` patterns.
    ///
    /// For initial configuration during construction, use [`TwitchOauth::with_csrf_config`] instead.
    pub fn set_csrf_config(&mut self, config: CsrfConfig) {
        self.csrf_config = config;
    }

    pub async fn send<T>(&self, request: T) -> Result<reqwest::Response, T::Error>
    where
        T: IntoRequestBuilder<Error = Error>,
    {
        let resp = request
            .into_request_builder(&self.client)?
            .send()
            .await
            .map_err(error::network::request)?;

        if !resp.status().is_success() {
            let status = resp.status().as_u16();
            let v = resp.bytes().await?;
            let body = String::from_utf8_lossy(&v).to_string();
            return Err(error::oauth::http_error(status, body));
        }

        Ok(resp)
    }

    /// **Refresh an access token** using a refresh token
    ///
    /// # Example
    /// ```no_run
    /// # use twitch_oauth_token::{TwitchOauth, RefreshToken};
    /// # async fn run(oauth: TwitchOauth, refresh_token: RefreshToken) -> Result<(), twitch_oauth_token::Error> {
    /// let new_token = oauth.refresh_access_token(refresh_token).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// <https://dev.twitch.tv/docs/authentication/refresh-tokens/>
    pub async fn refresh_access_token(
        &self,
        refresh_token: RefreshToken,
    ) -> Result<crate::UserToken, Error> {
        let resp = self
            .send(RefreshRequest::new(
                &self.client_id,
                &self.client_secret,
                refresh_token,
                &self.token_url,
            ))
            .await?;

        decode_response(resp).await
    }

    /// **Revoke/invalidate an access token**
    ///
    /// This immediately invalidates a token, preventing further use.
    /// Use this when:
    /// - User logs out of your application
    /// - You detect a security issue
    /// - You're shutting down/cleaning up
    ///
    /// # Example
    /// ```no_run
    /// # use twitch_oauth_token::{TwitchOauth, AccessToken};
    /// # async fn run(oauth: TwitchOauth, access_token: AccessToken) -> Result<(), twitch_oauth_token::Error> {
    /// oauth.revoke_access_token(&access_token).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// <https://dev.twitch.tv/docs/authentication/revoke-tokens/>
    pub async fn revoke_access_token(&self, access_token: &AccessToken) -> Result<(), Error> {
        let _resp = self
            .send(RevokeRequest::new(
                access_token,
                &self.client_id,
                &self.revoke_url,
            ))
            .await?;

        Ok(())
    }

    /// **Get an app access token** (Client Credentials Flow)
    ///
    /// App tokens are used for server-to-server API calls that don't
    /// require a specific user context. They're simpler than user tokens
    /// but can only access public data.
    ///
    /// # Example
    /// ```no_run
    /// # use twitch_oauth_token::TwitchOauth;
    /// # async fn run() -> Result<(), twitch_oauth_token::Error> {
    /// let oauth = TwitchOauth::new("client_id", "client_secret");
    ///
    /// let token = oauth.app_access_token().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// <https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#client-credentials-grant-flow>
    pub async fn app_access_token(&self) -> Result<crate::AppToken, Error> {
        let resp = self
            .send(ClientCredentialsRequest::new(
                &self.client_id,
                &self.client_secret,
                GrantType::ClientCredentials,
                &self.token_url,
            ))
            .await?;

        decode_response(resp).await
    }

    /// **Validate access token**
    ///
    /// # Example
    /// ```no_run
    /// # use twitch_oauth_token::{TwitchOauth, AccessToken};
    /// # async fn run(oauth: TwitchOauth, access_token: AccessToken) -> Result<(), twitch_oauth_token::Error> {
    /// let user_info = oauth.validate_access_token(&access_token).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// <https://dev.twitch.tv/docs/authentication/validate-tokens/>
    pub async fn validate_access_token(
        &self,
        access_token: &AccessToken,
    ) -> Result<crate::TokenInfo, Error> {
        let resp = self
            .send(ValidateRequest::new(access_token, &self.validate_url))
            .await?;

        decode_response(resp).await
    }
}

impl TwitchOauth<AppAuth> {
    /// Create OAuth client for app authentication
    pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
        Self {
            client_id: ClientId::from(client_id.into()),
            client_secret: ClientSecret::from(client_secret.into()),
            redirect_uri: (),
            secret_key: csrf::generate_secret_key(),
            token_url: TokenUrl::from_str(TOKEN_URL).unwrap(),
            auth_url: AuthUrl::from_str(AUTH_URL).unwrap(),
            revoke_url: RevocationUrl::from_str(REVOKE_URL).unwrap(),
            validate_url: ValidateUrl::from_str(VALIDATE_URL).unwrap(),
            client: crate::client::get().clone(),
            csrf_config: CsrfConfig::default(),
            phanthom: PhantomData,
        }
    }

    /// Upgrade to user authentication by adding redirect URI
    pub fn with_redirect_uri(self, redirect_uri: RedirectUrl) -> TwitchOauth<UserAuth> {
        TwitchOauth {
            client_id: self.client_id,
            client_secret: self.client_secret,
            redirect_uri,
            secret_key: self.secret_key,
            token_url: self.token_url,
            auth_url: self.auth_url,
            revoke_url: self.revoke_url,
            validate_url: self.validate_url,
            client: self.client,
            csrf_config: self.csrf_config,
            phanthom: PhantomData,
        }
    }

    /// Create OAuth client from existing credentials (advanced usage)
    ///
    /// Most users should use [`TwitchOauth::new()`] instead.
    pub fn from_credentials(client_id: ClientId, client_secret: ClientSecret) -> Self {
        Self {
            client_id,
            client_secret,
            redirect_uri: (),
            secret_key: csrf::generate_secret_key(),
            client: crate::client::get().clone(),
            token_url: TokenUrl::from_str(TOKEN_URL).unwrap(),
            auth_url: AuthUrl::from_str(AUTH_URL).unwrap(),
            revoke_url: RevocationUrl::from_str(REVOKE_URL).unwrap(),
            validate_url: ValidateUrl::from_str(VALIDATE_URL).unwrap(),
            csrf_config: CsrfConfig::default(),
            phanthom: PhantomData,
        }
    }
}

impl TwitchOauth<UserAuth> {
    pub fn get_redirect_uri(&self) -> &RedirectUrl {
        &self.redirect_uri
    }

    /// **Generate authorization URL** for user login (Step 1 of user auth)
    ///
    /// This creates a URL that you send users to for Twitch login.
    /// The URL includes:
    /// - Your client ID and redirect URI
    /// - Requested scopes (permissions)
    /// - CSRF protection via HMAC-SHA256 signed state parameter with timestamp
    ///
    /// # Example
    /// ```no_run
    /// # use std::str::FromStr;
    /// # use twitch_oauth_token::{scope::ChatScopes, TwitchOauth, RedirectUrl};
    /// # async fn run() -> Result<(), twitch_oauth_token::Error> {
    /// let oauth = TwitchOauth::new("client_id", "client_secret")
    ///     .with_redirect_uri(RedirectUrl::from_str("http://localhost:3000/auth/callback").unwrap());
    ///
    /// let mut auth_request = oauth.authorization_url();
    /// auth_request.scopes_mut().chat_api();
    ///
    /// let auth_url = auth_request.url();
    /// println!("{}", auth_url);
    ///
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// <https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#authorization-code-grant-flow>
    pub fn authorization_url<'a>(&'a self) -> AuthrozationRequest<'a> {
        AuthrozationRequest::new(
            &self.auth_url,
            &self.client_id,
            &self.redirect_uri,
            csrf::generate(&self.secret_key, Some(&self.client_id)),
        )
    }

    /// **Exchange authorization code for user access token** (Step 2 of user auth)
    ///
    /// After the user authorizes your app, Twitch redirects them back to your
    /// redirect URI with a `code`, `state` and `scope` parameter. Use this method to
    /// exchange that code for actual access tokens.
    ///
    /// # Example Callback Handler
    /// ```no_run
    /// use twitch_oauth_token::{
    ///     AuthorizationCode,
    ///     AuthCallback,
    ///     TwitchOauth,
    ///     UserAuth
    /// };
    ///
    /// async fn handle_callback(
    ///     oauth: &TwitchOauth<UserAuth>,
    ///     oauth_callback: AuthCallback,
    /// ) -> Result<(), twitch_oauth_token::Error> {
    ///     let token = oauth
    ///         .exchange_code(oauth_callback.code, oauth_callback.state)
    ///         .await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    ///
    /// <https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#authorization-code-grant-flow>
    pub async fn exchange_code(
        &self,
        code: AuthorizationCode,
        state: String,
    ) -> Result<crate::UserToken, Error> {
        if csrf::verify_with_config(
            &self.secret_key,
            &state,
            Some(&self.client_id),
            &self.csrf_config,
        )
        .is_err()
        {
            return Err(error::oauth::csrf_token_mismatch());
        }

        let resp = self
            .send(ExchangeCodeRequest::new(
                &self.client_id,
                &self.client_secret,
                code,
                &self.redirect_uri,
                &self.token_url,
            ))
            .await?;

        decode_response(resp).await
    }

    /// Set custom secret key for CSRF token generation
    ///
    /// By default, a random secret key is generated automatically for each `TwitchOauth` instance.
    /// Set custom secret key for CSRF token generation and validation
    ///
    /// # Example
    /// ```rust
    /// use std::str::FromStr;
    /// use twitch_oauth_token::{csrf, RedirectUrl, TwitchOauth};
    ///
    /// # fn run() -> Result<(), Box<dyn std::error::Error>> {
    ///
    /// let shared_secret = csrf::generate_secret_key();
    ///
    /// let oauth = TwitchOauth::new("your_client_id", "your_client_secret")
    ///     .with_redirect_uri(RedirectUrl::from_str("http://localhost:3000/auth/callback")?)
    ///     .with_secret_key(shared_secret);
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_secret_key(mut self, secret_key: [u8; 32]) -> Self {
        self.secret_key = secret_key;
        self
    }

    /// Update the CSRF secret key at runtime
    ///
    /// Use this to rotate CSRF secret keys in a running application,
    /// especially in `Arc<RwLock<TwitchOauth>>` patterns or multi-server deployments.
    ///
    /// For initial configuration during construction, use [`TwitchOauth::with_secret_key`] instead.
    pub fn set_secret_key(&mut self, secret_key: [u8; 32]) {
        self.secret_key = secret_key;
    }
}

#[cfg(feature = "test")]
impl<Flow> TwitchOauth<Flow>
where
    Flow: OauthFlow,
{
    pub fn with_test(self) -> crate::test_oauth::TwitchOauthTest<Flow> {
        crate::test_oauth::TwitchOauthTest::new(self)
    }
}

impl Display for TwitchOauth<AppAuth> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, "TwitchOauth(client_id: {})", self.client_id)
    }
}

impl Display for TwitchOauth<UserAuth> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(
            f,
            "TwitchOauth(client_id: {}, redirect_uri: {})",
            self.client_id, self.redirect_uri
        )
    }
}

impl<Flow> Debug for TwitchOauth<Flow>
where
    Flow: OauthFlow,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.debug_struct("TwitchOauth")
            .field("client_id", &self.client_id)
            .field("client_secret", &self.client_secret)
            .field("redirect_uri", &self.redirect_uri)
            .field("token_url", &self.token_url)
            .field("auth_url", &self.auth_url)
            .field("revoke_url", &self.revoke_url)
            .finish()
    }
}

pub(crate) async fn decode_response<T>(resp: reqwest::Response) -> Result<T, Error>
where
    T: serde::de::DeserializeOwned,
{
    let v = resp.bytes().await?;
    serde_json::from_slice(&v).map_err(|e| error::response::decode(e, String::from_utf8_lossy(&v)))
}