better-auth-api 1.0.0-alpha.5

Plugin implementations for better-auth
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
use async_trait::async_trait;
use better_auth_core::{AuthError, AuthResult, FieldDate, FieldValue, NativeRequest, SchemaValue};
use indexmap::IndexMap;
use serde::Deserialize;
use serde_json::Value;

pub(super) mod apple;
mod constructors;
pub(super) mod defaults;
pub(super) mod facebook;
pub(super) mod line;
pub(super) mod microsoft;
pub(super) mod paybin;
pub(super) mod paypal;
pub(super) mod tiktok;
pub(super) mod token_http;
pub(super) mod twitch;
pub(super) mod twitter;
pub(super) mod wechat;
use super::token::{TokenEndpointAuth, TokenEndpointSecretAuthentication, TokenGrantType};
use super::{OAuthAccountSubject, OAuthProfileMapper};
use defaults::ProviderKind;
pub(super) use defaults::github_profile;
use std::{collections::HashSet, sync::Arc};

/// Configuration for the OAuth plugin, containing all registered providers.
#[derive(Clone, Default)]
pub struct OAuthConfig {
    pub providers: IndexMap<String, OAuthProvider>,
}

/// Ordered provider token fields with typed slots and native replacement values.
#[derive(Debug, Clone, Default)]
pub struct OAuthTokenSet {
    /// Source property order. This list does not create missing properties.
    pub field_order: Vec<String>,
    /// Provider fields outside the named slots. A present named slot takes precedence.
    pub additional_fields: better_auth_core::FieldMap,
    pub token_type: SchemaValue<Option<String>>,
    pub access_token: SchemaValue<Option<String>>,
    pub refresh_token: SchemaValue<Option<String>>,
    pub access_token_expires_at: SchemaValue<Option<FieldDate>>,
    pub refresh_token_expires_at: SchemaValue<Option<FieldDate>>,
    pub scopes: SchemaValue<Vec<String>>,
    pub id_token: SchemaValue<Option<String>>,
    pub raw: SchemaValue<Option<Value>>,
}

/// User information extracted from an OAuth provider's user info endpoint.
#[derive(Debug, Clone)]
pub struct OAuthUserInfo {
    /// Mapped application fields validated by the configured user schema.
    pub additional_fields: better_auth_core::FieldMap,
    pub id: String,
    /// Preserve a missing email with `Undefined`, null with `Typed(None)`, or a string.
    pub email: SchemaValue<Option<String>>,
    /// Preserve a missing name with `Undefined`, null with `Typed(None)`, or a string.
    pub name: SchemaValue<Option<String>>,
    /// Omit the image with `None`, clear it with `Some(None)`, or supply a URL.
    pub image: Option<Option<String>>,
    /// Preserve omitted or null provider values without treating either as verified.
    pub email_verified: SchemaValue<Option<bool>>,
}

pub(super) fn decode_profile_name(value: Option<&Value>) -> SchemaValue<Option<String>> {
    match value {
        Some(Value::String(value)) => Some(value.clone()).into(),
        Some(Value::Null) => None.into(),
        None | Some(_) => SchemaValue::Undefined,
    }
}

pub(super) fn profile_email_verified(value: &SchemaValue<Option<bool>>) -> AuthResult<bool> {
    match value {
        SchemaValue::Typed(Some(value)) | SchemaValue::Dynamic(FieldValue::Bool(value)) => {
            Ok(*value)
        }
        SchemaValue::Undefined
        | SchemaValue::Typed(None)
        | SchemaValue::Dynamic(FieldValue::Null) => Ok(false),
        SchemaValue::Dynamic(_) => Err(AuthError::internal(
            "OAuth profile email verification must be a boolean, null, or undefined",
        )),
    }
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OAuthCallbackUserPayload {
    pub name: Option<OAuthCallbackUserName>,
    pub email: Option<String>,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OAuthCallbackUserName {
    pub first_name: Option<String>,
    pub last_name: Option<String>,
}

/// Provider input that preserves token values until the provider consumes each field.
#[derive(Debug, Clone, Default)]
pub struct OAuthUserInfoRequest {
    /// Source property order. This list does not create missing properties.
    pub field_order: Vec<String>,
    /// Provider fields outside the named slots. A present named slot takes precedence.
    pub additional_fields: better_auth_core::FieldMap,
    pub token_type: SchemaValue<Option<String>>,
    pub access_token: SchemaValue<Option<String>>,
    pub refresh_token: SchemaValue<Option<String>>,
    pub access_token_expires_at: SchemaValue<Option<FieldDate>>,
    pub refresh_token_expires_at: SchemaValue<Option<FieldDate>>,
    pub scopes: SchemaValue<Vec<String>>,
    pub id_token: SchemaValue<Option<String>>,
    pub raw: SchemaValue<Option<Value>>,
    pub expected_id_token_nonce: SchemaValue<Option<String>>,
    pub user: SchemaValue<Option<OAuthCallbackUserPayload>>,
}

#[path = "token_record.rs"]
mod token_record;
pub(super) use token_record::{joined_scopes, merge_scopes, split_scopes};

#[path = "profile_record.rs"]
mod profile_record;

pub(super) fn jwt_string(value: &FieldValue) -> AuthResult<std::borrow::Cow<'_, str>> {
    match value {
        FieldValue::String(value) => Ok(std::borrow::Cow::Borrowed(value)),
        FieldValue::Utf16String(value) => Ok(std::borrow::Cow::Owned(String::from_utf16_lossy(
            value.as_utf16(),
        ))),
        _ => Err(AuthError::type_error("JWTs must be a string")),
    }
}

#[derive(Debug, Clone)]
pub struct OAuthUserInfoResponse {
    pub user: OAuthUserInfo,
    pub data: Value,
}

/// Fetch a provider profile while preserving application errors at the endpoint boundary.
#[async_trait]
pub trait OAuthUserInfoHandler: Send + Sync {
    /// Return a typed response at the legacy JSON callback boundary.
    /// Native handlers may implement `get_user_info_native` instead.
    async fn get_user_info(
        &self,
        _request: OAuthUserInfoRequest,
    ) -> AuthResult<Option<OAuthUserInfoResponse>> {
        Err(AuthError::internal(
            "This OAuth user info handler does not implement the typed JSON callback",
        ))
    }

    /// Return the complete provider response without narrowing values or copying object handles.
    /// The default consumes the legacy typed response once at its JSON callback boundary.
    async fn get_user_info_native(&self, request: OAuthUserInfoRequest) -> AuthResult<FieldValue> {
        Ok(self
            .get_user_info(request)
            .await?
            .map_or(FieldValue::Undefined, OAuthUserInfoResponse::into_native))
    }
}

pub(super) fn json_profile_bridge(profile: &FieldValue) -> AuthResult<Value> {
    profile.json()?.ok_or_else(|| {
        AuthError::type_error(
            "The typed JSON profile callback cannot receive an omitted JSON value",
        )
    })
}

#[async_trait]
pub trait OAuthRefreshTokenHandler: Send + Sync {
    /// Endpoint calls supply original request metadata; standalone calls may omit the context.
    async fn refresh_access_token(
        &self,
        refresh_token: &FieldValue,
        context: Option<NativeRequest<'_>>,
    ) -> Result<OAuthTokenSet, String>;
}

#[async_trait]
pub trait OAuthIdTokenVerifier: Send + Sync {
    /// Request metadata is supplied by direct sign-in and linking; standalone calls may omit it.
    async fn verify_id_token(
        &self,
        token: &str,
        nonce: Option<&str>,
        context: Option<NativeRequest<'_>>,
    ) -> Result<bool, String>;
}

/// Input options for a social OAuth provider. Constructors retain omitted options.
#[derive(Clone)]
pub struct OAuthProvider {
    kind: ProviderKind,
    pub client_id: String,
    pub client_secret: String,
    /// Additional key for built-in authorization-code exchanges that accept this option.
    pub client_key: Option<String>,
    pub auth_url: String,
    pub token_url: String,
    /// Cloudflare token endpoint authentication override for code exchange and refresh.
    /// Other Social providers retain their fixed authentication methods.
    pub token_endpoint_auth: Option<TokenEndpointAuth>,
    pub user_info_url: Option<String>,
    /// Provider callback URI for authorization and code exchange; an empty value uses the route URI.
    pub redirect_uri: Option<String>,
    /// OIDC provider endpoint used for RP-initiated logout.
    pub end_session_endpoint: Option<String>,
    /// Default redirect after provider logout; a request callback overrides it.
    pub post_logout_redirect_uri: Option<String>,
    /// Additional scopes for built-in providers; omission preserves their defaults.
    pub scopes: Option<Vec<String>>,
    /// Exclude the built-in provider scopes from authorization requests.
    pub disable_default_scope: bool,
    /// Reject direct ID-token sign-in and linking before invoking the verifier.
    pub disable_id_token_sign_in: bool,
    /// Authentication prompt for providers that support this option.
    /// Omission preserves the provider default.
    pub prompt: Option<String>,
    pub authorization_params: Vec<(String, String)>,
    /// Replace the base JSON decoder for a custom provider.
    pub map_user_info: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
    /// Map local fields after built-in profile decoding without changing account identity.
    pub map_profile_to_user: Option<Arc<dyn OAuthProfileMapper>>,
    pub get_user_info: Option<Arc<dyn OAuthUserInfoHandler>>,
    /// Resolve a custom provider's account identity from its original profile and token record.
    pub account_subject: Option<Arc<dyn OAuthAccountSubject>>,
    pub refresh_access_token: Option<Arc<dyn OAuthRefreshTokenHandler>>,
    pub verify_id_token: Option<Arc<dyn OAuthIdTokenVerifier>>,
    pub disable_implicit_sign_up: Option<bool>,
    pub disable_sign_up: Option<bool>,
    /// Require the local user's email to be verified before issuing a session.
    pub require_email_verification: Option<bool>,
    pub override_user_info_on_sign_in: bool,
}

impl OAuthProvider {
    pub(super) fn microsoft_options(&self) -> Option<&super::MicrosoftOptions> {
        match &self.kind {
            ProviderKind::Microsoft { options, .. } => Some(options),
            _ => None,
        }
    }

    pub(super) fn cognito_options(&self) -> Option<&super::CognitoOptions> {
        match &self.kind {
            ProviderKind::Cognito(options) => Some(options),
            _ => None,
        }
    }

    pub(super) fn supports_refresh(&self) -> bool {
        !matches!(self.kind, ProviderKind::Vercel)
    }

    pub(super) fn user_info_request(
        &self,
        url: &str,
        access_token: &FieldValue,
    ) -> AuthResult<reqwest::RequestBuilder> {
        if self.is_vk() {
            let access_token = token_http::form_string(access_token)?;
            return Ok(reqwest::Client::new()
                .post(url)
                .header("Accept", "*/*")
                .form(&[
                    ("access_token", &access_token),
                    ("client_id", &self.client_id),
                ]));
        }
        let method = match self.kind {
            ProviderKind::Dropbox | ProviderKind::Linear => reqwest::Method::POST,
            _ => reqwest::Method::GET,
        };
        let request = reqwest::Client::new().request(method, url).header(
            reqwest::header::AUTHORIZATION,
            token_http::authorization("Bearer", access_token)?,
        );
        let request = if self.is_tiktok() {
            request
        } else {
            request.header(
                "Accept",
                if self.is_twitter() || self.cognito_options().is_some() {
                    "*/*"
                } else {
                    "application/json"
                },
            )
        };
        Ok(if matches!(self.kind, ProviderKind::Linear) {
            request.json(&serde_json::json!({
                "query": "query { viewer { id name email avatarUrl active createdAt updatedAt } }"
            }))
        } else if self.is_reddit() {
            request.header("User-Agent", "better-auth")
        } else if matches!(self.kind, ProviderKind::Notion) {
            request.header("Notion-Version", "2022-06-28")
        } else {
            request
        })
    }

    pub(super) fn is_figma(&self) -> bool {
        matches!(self.kind, ProviderKind::Figma)
    }

    pub(super) fn is_atlassian(&self) -> bool {
        matches!(self.kind, ProviderKind::Atlassian)
    }

    pub(super) fn is_salesforce(&self) -> bool {
        matches!(self.kind, ProviderKind::Salesforce)
    }

    pub(super) fn required_credentials_message(&self) -> Option<&'static str> {
        if self.is_paypal() {
            return Some(
                "Client Id and Client Secret is required for PayPal. Make sure to provide them in the options.",
            );
        }
        match self.kind {
            ProviderKind::Apple(_) => Some(
                "Client ID and client secret are required for Apple. Make sure to provide them in the options.",
            ),
            ProviderKind::Facebook(_) => Some(
                "Client ID and client secret are required for Facebook. Make sure to provide them in the options.",
            ),
            ProviderKind::Figma => Some(
                "Client Id and Client Secret are required for Figma. Make sure to provide them in the options.",
            ),
            ProviderKind::Atlassian => Some("Client Id and Secret are required for Atlassian"),
            ProviderKind::Salesforce => Some(
                "Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options.",
            ),
            ProviderKind::Paybin { .. } => Some(
                "Client Id and Client Secret is required for Paybin. Make sure to provide them in the options.",
            ),
            _ => None,
        }
    }

    pub(super) fn fixed_authorization_params(&self) -> &'static [(&'static str, &'static str)] {
        match self.kind {
            ProviderKind::Atlassian => &[("audience", "api.atlassian.com")],
            ProviderKind::Notion => &[("owner", "user")],
            _ => &[],
        }
    }

    pub(super) fn wechat_refresh_url(&self) -> Option<&str> {
        match &self.kind {
            ProviderKind::WeChat { refresh_url } => Some(refresh_url),
            _ => None,
        }
    }

    pub(super) fn is_tiktok(&self) -> bool {
        matches!(self.kind, ProviderKind::TikTok)
    }

    pub(super) fn is_twitter(&self) -> bool {
        matches!(self.kind, ProviderKind::Twitter)
    }

    pub(super) fn is_vk(&self) -> bool {
        matches!(self.kind, ProviderKind::Vk)
    }

    pub(super) fn is_discord(&self) -> bool {
        matches!(self.kind, ProviderKind::Discord)
    }

    pub(super) fn is_roblox(&self) -> bool {
        matches!(self.kind, ProviderKind::Roblox)
    }

    pub(super) fn omits_request_nonce(&self) -> bool {
        !matches!(self.kind, ProviderKind::Custom)
    }

    pub(super) fn is_reddit(&self) -> bool {
        matches!(self.kind, ProviderKind::Reddit)
    }

    pub(super) fn uses_pkce(&self) -> bool {
        !matches!(
            self.kind,
            ProviderKind::Facebook(_)
                | ProviderKind::Discord
                | ProviderKind::LinkedIn
                | ProviderKind::Slack
                | ProviderKind::Naver
                | ProviderKind::Linear
                | ProviderKind::Reddit
                | ProviderKind::Roblox
                | ProviderKind::TikTok
                | ProviderKind::Notion
                | ProviderKind::Twitch(_)
                | ProviderKind::Kakao
                | ProviderKind::Zoom { pkce: false }
                | ProviderKind::WeChat { .. }
        )
    }

    pub(super) fn forwards_code_verifier(&self) -> bool {
        matches!(self.kind, ProviderKind::Zoom { .. } | ProviderKind::TikTok) || self.uses_pkce()
    }

    pub(super) fn omits_login_hint(&self) -> bool {
        matches!(
            self.kind,
            ProviderKind::Apple(_)
                | ProviderKind::Cognito(_)
                | ProviderKind::Discord
                | ProviderKind::Spotify
                | ProviderKind::HuggingFace
                | ProviderKind::Polar
                | ProviderKind::Vercel
                | ProviderKind::Figma
                | ProviderKind::Dropbox
                | ProviderKind::Kick
                | ProviderKind::PayPal
                | ProviderKind::Cloudflare
                | ProviderKind::Slack
                | ProviderKind::Naver
                | ProviderKind::Atlassian
                | ProviderKind::Reddit
                | ProviderKind::Salesforce
                | ProviderKind::Railway
                | ProviderKind::Roblox
                | ProviderKind::TikTok
                | ProviderKind::Twitch(_)
                | ProviderKind::Kakao
                | ProviderKind::Zoom { .. }
                | ProviderKind::Twitter
                | ProviderKind::WeChat { .. }
                | ProviderKind::Vk
        )
    }

    pub(super) fn code_client_key(&self) -> Option<&str> {
        match self.kind {
            ProviderKind::Custom
            | ProviderKind::PayPal
            | ProviderKind::Reddit
            | ProviderKind::WeChat { .. }
            | ProviderKind::TikTok => None,
            _ => self.client_key.as_deref(),
        }
    }

    pub(super) fn omits_device_id(&self) -> bool {
        matches!(
            self.kind,
            ProviderKind::Microsoft { .. }
                | ProviderKind::Google { .. }
                | ProviderKind::Apple(_)
                | ProviderKind::Facebook(_)
                | ProviderKind::Discord
                | ProviderKind::Cognito(_)
                | ProviderKind::PayPal
                | ProviderKind::Cloudflare
                | ProviderKind::LinkedIn
                | ProviderKind::Line { .. }
                | ProviderKind::Paybin { .. }
                | ProviderKind::Slack
                | ProviderKind::Naver
                | ProviderKind::Linear
                | ProviderKind::Atlassian
                | ProviderKind::Reddit
                | ProviderKind::Salesforce
                | ProviderKind::Railway
                | ProviderKind::Roblox
                | ProviderKind::TikTok
                | ProviderKind::Notion
                | ProviderKind::Twitch(_)
                | ProviderKind::Kakao
                | ProviderKind::Zoom { .. }
                | ProviderKind::Twitter
                | ProviderKind::WeChat { .. }
        )
    }

    pub(super) fn http_profile_data(
        &self,
        response: &FieldValue,
        error: &FieldValue,
    ) -> AuthResult<Option<FieldValue>> {
        self.kind.http_profile_data(response, error)
    }

    pub(super) fn is_cloudflare(&self) -> bool {
        matches!(self.kind, ProviderKind::Cloudflare)
    }

    pub(super) fn token_endpoint_auth(&self) -> Option<&TokenEndpointAuth> {
        match &self.kind {
            ProviderKind::Microsoft {
                token_endpoint_auth,
                ..
            } => token_endpoint_auth.as_ref(),
            ProviderKind::Cloudflare => self.token_endpoint_auth.as_ref(),
            _ => None,
        }
    }

    pub(super) fn token_authentication(
        &self,
        grant_type: TokenGrantType,
    ) -> Option<TokenEndpointSecretAuthentication> {
        (self.is_paypal()
            || self.is_figma()
            || self.is_reddit()
            || self.is_twitter()
            || matches!(self.kind, ProviderKind::Railway)
            || matches!(self.kind, ProviderKind::Notion)
                && grant_type == TokenGrantType::AuthorizationCode
            || matches!(self.kind, ProviderKind::Cloudflare) && !self.client_secret.is_empty())
        .then_some(TokenEndpointSecretAuthentication::Basic)
    }

    /// Return the effective implicit sign-up policy.
    pub fn disable_implicit_sign_up(&self) -> bool {
        self.disable_implicit_sign_up.unwrap_or(false)
    }

    /// Return the effective sign-up policy.
    pub fn disable_sign_up(&self) -> bool {
        self.disable_sign_up.unwrap_or(false)
    }

    pub(super) fn google_jwks_url(&self) -> Option<&str> {
        match &self.kind {
            ProviderKind::Google { jwks_url, .. } => Some(jwks_url),
            _ => None,
        }
    }

    pub(in crate::plugins) fn google_client_ids(&self) -> Vec<String> {
        let additional = match &self.kind {
            ProviderKind::Google { options, .. } => options.additional_client_ids.as_slice(),
            _ => &[],
        };
        std::iter::once(self.client_id.clone())
            .chain(additional.iter().cloned())
            .collect()
    }

    pub(super) fn google_hosted_domain(&self) -> Option<&str> {
        self.authorization_params
            .iter()
            .find(|(name, _)| name == "hd")
            .map(|(_, value)| value.as_str())
    }

    #[cfg(test)]
    pub(super) fn set_google_jwks_url(&mut self, url: String) {
        let ProviderKind::Google { jwks_url, .. } = &mut self.kind else {
            panic!("Google fixture requires a Google provider");
        };
        *jwks_url = url;
    }

    pub(super) fn github_endpoints(&self) -> Option<(&str, &str)> {
        match &self.kind {
            ProviderKind::GitHub {
                user_url,
                emails_url,
            } => Some((user_url, emails_url)),
            _ => None,
        }
    }

    pub(super) fn builtin_account_subject(
        &self,
        profile: &FieldValue,
    ) -> AuthResult<Option<FieldValue>> {
        self.kind.account_subject(profile)
    }

    pub(super) fn uses_legacy_profile_subject(&self) -> bool {
        matches!(self.kind, ProviderKind::Custom) && self.map_user_info.is_some()
    }

    pub(super) fn is_custom(&self) -> bool {
        matches!(self.kind, ProviderKind::Custom)
    }

    pub(super) fn default_profile_includes_id(&self) -> bool {
        self.get_user_info.is_some()
            || (self.github_endpoints().is_none() && self.map_user_info.is_some())
    }

    pub(super) fn decode_profile(
        &self,
        profile: Value,
    ) -> better_auth_core::AuthResult<Option<OAuthUserInfo>> {
        if let Some(mapper) = self.map_user_info {
            mapper(profile)
                .map(Some)
                .map_err(better_auth_core::AuthError::internal)
        } else {
            self.kind.decode_profile(profile)
        }
    }

    pub(super) async fn native_default_profile(
        &self,
        profile: &FieldValue,
        source: &FieldValue,
    ) -> AuthResult<Option<super::social_profile::ProviderProfile>> {
        if self.map_user_info.is_some() {
            return Ok(None);
        }
        self.kind
            .native_default_profile(profile, source, self.map_profile_to_user.as_deref())
            .await
    }

    pub(super) fn resolve(&self) -> Self {
        let mut provider = self.clone();
        if provider.get_user_info.is_some() {
            // Upstream custom user-info handlers return before profile mapping.
            provider.map_profile_to_user = None;
        }
        provider
    }

    pub(super) fn social_scopes<'a>(&'a self, request: Option<&'a [String]>) -> Vec<&'a str> {
        if matches!(self.kind, ProviderKind::Zoom { .. } | ProviderKind::PayPal) {
            return Vec::new();
        }
        let configured = self.scopes.as_deref().unwrap_or_default();
        if matches!(self.kind, ProviderKind::Custom) {
            return request
                .unwrap_or(configured)
                .iter()
                .map(String::as_str)
                .collect();
        }
        let mut scopes = if self.disable_default_scope {
            Vec::new()
        } else {
            self.kind.scopes().to_vec()
        };
        let request = request.unwrap_or_default();
        let (first, second) = if matches!(self.kind, ProviderKind::Discord | ProviderKind::Slack) {
            (request, configured)
        } else {
            (configured, request)
        };
        scopes.extend(first.iter().chain(second).map(String::as_str));
        if matches!(self.kind, ProviderKind::Cloudflare) {
            let mut seen = HashSet::new();
            scopes.retain(|scope| seen.insert(*scope));
        }
        scopes
    }

    pub(super) fn social_prompt(&self) -> Option<&str> {
        match self.kind {
            ProviderKind::Roblox => self
                .prompt
                .as_deref()
                .filter(|value| !value.is_empty())
                .or(Some("select_account consent")),
            ProviderKind::Custom
            | ProviderKind::Google { .. }
            | ProviderKind::GitHub { .. }
            | ProviderKind::Discord
            | ProviderKind::Polar
            | ProviderKind::PayPal
            | ProviderKind::Cognito(_)
            | ProviderKind::Microsoft { .. }
            | ProviderKind::Paybin { .. }
            | ProviderKind::Atlassian => self
                .prompt
                .as_deref()
                .filter(|value| !value.is_empty())
                .or_else(|| matches!(self.kind, ProviderKind::Discord).then_some("none")),
            ProviderKind::Apple(_)
            | ProviderKind::Facebook(_)
            | ProviderKind::GitLab
            | ProviderKind::Spotify
            | ProviderKind::HuggingFace
            | ProviderKind::Vercel
            | ProviderKind::Figma
            | ProviderKind::Dropbox
            | ProviderKind::Kick
            | ProviderKind::LinkedIn
            | ProviderKind::Line { .. }
            | ProviderKind::Slack
            | ProviderKind::Naver
            | ProviderKind::Linear
            | ProviderKind::Reddit
            | ProviderKind::Cloudflare
            | ProviderKind::Salesforce
            | ProviderKind::Railway
            | ProviderKind::Notion
            | ProviderKind::Twitch(_)
            | ProviderKind::Kakao
            | ProviderKind::Twitter
            | ProviderKind::WeChat { .. }
            | ProviderKind::Vk
            | ProviderKind::TikTok
            | ProviderKind::Zoom { .. } => None,
        }
    }
}

#[cfg(test)]
mod tests;