alibi-plugins 0.8.0

Built-in authentication plugins and API metadata for Alibi
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
mod discord;
mod generic;
mod github;
mod gitlab;
mod google;
pub(super) mod remaining_profile;
pub use generic::{
    GenericOAuthConfig, GenericOAuthError, GenericOAuthMetadata, GenericOAuthResolved,
};
mod roblox;
pub use roblox::RobloxOptions;
mod salesforce;
pub use salesforce::{SalesforceEnvironment, SalesforceOptions};
mod slack;
pub use slack::SlackOptions;
mod spotify;
pub use spotify::SpotifyOptions;
mod tiktok;
pub use tiktok::TikTokOptions;
mod twitch;
pub use twitch::TwitchOptions;
mod twitter;
pub use twitter::TwitterOptions;
mod vercel;
pub use vercel::VercelOptions;
mod vk;
pub use vk::VkOptions;
mod wechat;
pub use wechat::{WeChatLanguage, WeChatOptions};
mod zoom;
pub use zoom::ZoomOptions;

mod reddit;
pub use reddit::RedditOptions;
mod railway;
pub use railway::RailwayOptions;
mod paypal;
pub use paypal::{PayPalEnvironment, PayPalOptions};

mod paybin;
pub use paybin::PaybinOptions;
mod polar;
pub use polar::PolarOptions;

mod notion;
pub use notion::NotionOptions;

mod cloudflare;
pub use cloudflare::CloudflareOptions;

mod cognito;
pub use cognito::CognitoOptions;

mod dropbox;
pub use dropbox::{DropboxAccessType, DropboxOptions};
mod figma;
pub use figma::FigmaOptions;

mod facebook;
pub use facebook::FacebookOptions;

mod atlassian;
pub use atlassian::AtlassianOptions;

mod apple;
pub use apple::AppleOptions;

mod microsoft;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
pub use microsoft::{MicrosoftOptions, MicrosoftProfilePhotoSize};
use serde::Deserialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;

/// Trusted OIDC logout endpoint and optional default return URI.
#[derive(Debug, Clone)]
pub struct OAuthEndSessionConfig {
    pub endpoint: String,
    pub post_logout_redirect_uri: Option<String>,
}

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

/// A provider grant, and the typed result of [`OAuthAccountApi`](crate::oauth::OAuthAccountApi)'s
/// token operations.
#[derive(Debug, Clone, Default)]
pub struct OAuthTokenSet {
    pub token_type: Option<String>,
    pub access_token: Option<String>,
    pub refresh_token: Option<String>,
    pub access_token_expires_at: Option<DateTime<Utc>>,
    pub refresh_token_expires_at: Option<DateTime<Utc>>,
    pub scopes: Vec<String>,
    pub id_token: Option<String>,
    pub raw: Option<Value>,
}

/// User information extracted from an OAuth provider's user info endpoint.
#[derive(Debug, Clone)]
pub struct OAuthUserInfo {
    /// Trusted mapped application values; writes select initialized declared input fields.
    pub additional_fields: alibi_core::field_policy::FieldOutput,
    pub id: String,
    pub email: String,
    pub name: Option<String>,
    pub image: Option<String>,
    pub email_verified: bool,
}

impl OAuthUserInfo {
    /// Original mapped public values. This is output, never account authority.
    #[must_use]
    pub fn public_profile(&self, include_id: bool) -> alibi_core::field_policy::FieldOutput {
        let mut output = self.additional_fields.clone();
        _ = output.insert("email".into(), Value::String(self.email.clone()));
        _ = output.insert("emailVerified".into(), Value::Bool(self.email_verified));
        if include_id {
            _ = output.insert("id".into(), Value::String(self.id.clone()));
        }
        if let Some(name) = &self.name {
            _ = output.insert("name".into(), Value::String(name.clone()));
        }
        if let Some(image) = &self.image {
            _ = output.insert("image".into(), Value::String(image.clone()));
        }
        output
    }
}

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

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

#[derive(Debug, Clone, Default)]
pub struct OAuthUserInfoRequest {
    pub token_type: Option<String>,
    pub access_token: Option<String>,
    pub refresh_token: Option<String>,
    pub access_token_expires_at: Option<DateTime<Utc>>,
    pub refresh_token_expires_at: Option<DateTime<Utc>>,
    pub scopes: Vec<String>,
    pub id_token: Option<String>,
    pub raw: Option<Value>,
    pub user: Option<OAuthCallbackUserPayload>,
}

#[derive(Debug, Clone)]
pub struct OAuthUserInfoResponse {
    /// Original mapped public profile, captured before raw account-subject resolution.
    pub user_output: Option<alibi_core::field_policy::FieldOutput>,
    pub user: OAuthUserInfo,
    pub data: Value,
}

/// Resolve a provider's stable account identity from its original profile.
pub type OAuthAccountSubject = fn(&Value) -> Result<String, String>;

#[async_trait]
pub trait OAuthUserInfoHandler: Send + Sync {
    /// Retain factory-specific use of the original configured client array.
    fn configured_client_ids(&self, _ids: &[String]) -> Option<Arc<dyn OAuthUserInfoHandler>> {
        None
    }

    /// Custom application callbacks throw on failure; factory transports can
    /// return a missing profile and tag only their uncaught projection failures.
    fn errors_are_exceptions(&self) -> bool {
        true
    }

    /// Factory handlers can install application mapping before projecting raw
    /// profile fields. Custom getUserInfo callbacks retain their precedence.
    fn mapped_handler(
        &self,
        _mapper: Arc<dyn OAuthProfileMapper>,
    ) -> Option<Arc<dyn OAuthUserInfoHandler>> {
        None
    }

    async fn get_user_info(
        &self,
        request: OAuthUserInfoRequest,
    ) -> Result<OAuthUserInfoResponse, String>;
}

/// Asynchronous partial application mapping of the original provider profile.
/// Absent keys retain published defaults; raw output remains independent from
/// typed persistence, and returned IDs never replace original account authority.
#[async_trait]
pub trait OAuthProfileMapper: Send + Sync {
    async fn map_profile(
        &self,
        profile: Value,
    ) -> Result<alibi_core::field_policy::FieldOutput, String>;
}

pub(super) fn apply_application_mapping(
    response: &mut OAuthUserInfoResponse,
    mapped: alibi_core::field_policy::FieldOutput,
) -> Result<(), String> {
    let output = response
        .user_output
        .get_or_insert_with(|| response.user.public_profile(true));
    output.extend(mapped.clone());
    for (key, value) in mapped {
        match key.as_str() {
            "id" => response.user.id = remaining_profile::js_string(&value)?,
            "email" => response.user.email = value.as_str().unwrap_or_default().into(),
            "emailVerified" => response.user.email_verified = remaining_profile::truthy(&value),
            "name" => {
                response.user.name = remaining_profile::scalar(
                    Some(&value).filter(|value| remaining_profile::truthy(value)),
                )?;
            }
            "image" => response.user.image = remaining_profile::scalar(Some(&value))?,
            _ => {
                _ = response.user.additional_fields.insert(key, value);
            }
        }
    }
    Ok(())
}

/// Metadata of the request triggering an OAuth token refresh.
/// Headers, cookies and body fields are untrusted. Applications must validate
/// tenant/scope/audience entitlements before forwarding derived values.
#[derive(Clone, Copy)]
pub struct OAuthRefreshContext<'a> {
    pub request: &'a alibi_core::AuthRequest,
}

/// An asynchronous alternative to static `refreshTokenParams`.
#[async_trait]
pub trait OAuthRefreshTokenParamsResolver: Send + Sync {
    async fn resolve(
        &self,
        context: Option<OAuthRefreshContext<'_>>,
    ) -> Result<Option<std::collections::BTreeMap<String, String>>, String>;
}

#[derive(Clone)]
pub struct OAuthRefreshTokenParams(pub Arc<dyn OAuthRefreshTokenParamsResolver>);
impl std::fmt::Debug for OAuthRefreshTokenParams {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("OAuthRefreshTokenParams(..)")
    }
}

#[async_trait]
pub trait OAuthRefreshTokenHandler: Send + Sync {
    /// Reconfigure a factory transport that directly interpolates client IDs.
    fn configured_client_ids(&self, _ids: &[String]) -> Option<Arc<dyn OAuthRefreshTokenHandler>> {
        None
    }

    async fn refresh_access_token(&self, refresh_token: &str) -> Result<OAuthTokenSet, String>;

    /// Context-aware application handlers may override this method. Existing
    /// factory handlers retain their token-only implementation.
    async fn refresh_access_token_with_context(
        &self,
        refresh_token: &str,
        _context: Option<OAuthRefreshContext<'_>>,
    ) -> Result<OAuthTokenSet, String> {
        self.refresh_access_token(refresh_token).await
    }
}

#[async_trait]
pub trait OAuthIdTokenVerifier: Send + Sync {
    async fn verify_id_token(&self, token: &str, nonce: Option<&str>) -> Result<bool, String>;
}

/// The actual token grant for an application's asynchronous client assertion.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OAuthTokenGrant {
    AuthorizationCode,
    RefreshToken,
}

#[derive(Debug, Clone)]
pub struct OAuthClientAssertionContext {
    pub client_id: String,
    pub token_endpoint: String,
    pub grant_type: OAuthTokenGrant,
}

/// Produces a fresh application credential for the actual bound token request.
#[async_trait]
pub trait OAuthClientAssertionGetter: Send + Sync {
    async fn get_client_assertion(
        &self,
        context: OAuthClientAssertionContext,
    ) -> Result<String, String>;
}

/// Cloneable application callback whose Debug output never prints credentials.
#[derive(Clone)]
pub struct OAuthClientAssertion(pub Arc<dyn OAuthClientAssertionGetter>);

impl std::fmt::Debug for OAuthClientAssertion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OAuthClientAssertion")
            .finish_non_exhaustive()
    }
}

/// Configuration for a single OAuth provider.
#[derive(Clone)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "Preserve independent public provider policy switches"
)]
pub struct OAuthProvider {
    pub client_id: String,
    /// Additional Google client IDs accepted when verifying ID tokens.
    pub additional_client_ids: Vec<String>,
    /// Google Workspace domain restriction, independently of authorization parameters.
    pub hosted_domain: Option<String>,
    /// Require a verified provider email before creating the authentication session.
    pub require_email_verification: bool,
    pub client_secret: String,
    pub auth_url: String,
    pub token_url: String,
    pub user_info_url: Option<String>,
    pub scopes: Vec<String>,
    /// Built-in authorization behavior. `None` preserves custom-provider behavior.
    /// `scopes` remains the provider's base scope list; this policy adds configured
    /// and request scopes in the provider's published order.
    pub authorization: Option<OAuthAuthorizationPolicy>,
    pub authorization_params: Vec<(String, String)>,
    /// Query parameter names accepted from per-request `authorizationParams`.
    /// Empty by default. Unlisted names and reserved OAuth parameters are ignored.
    /// Allowed values override `authorization_params` and `additionalParams`,
    /// but provider policy's `fixed_authorization_params` take precedence.
    pub allowed_request_params: Vec<String>,
    /// Selects the factory account subject from the original provider profile.
    pub account_subject: Option<OAuthAccountSubject>,
    pub map_user_info: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
    pub get_user_info: Option<Arc<dyn OAuthUserInfoHandler>>,
    pub refresh_access_token: Option<Arc<dyn OAuthRefreshTokenHandler>>,
    /// Application override takes precedence over the trusted built-in JWKS policy.
    pub verify_id_token: Option<Arc<dyn OAuthIdTokenVerifier>>,
    pub id_token: Option<super::id_token::OAuthIdTokenConfig>,
    /// Disable the complete ID-token branch, including an application verifier override.
    pub disable_id_token_sign_in: bool,
    pub disable_implicit_sign_up: bool,
    pub disable_sign_up: bool,
    /// Start a new state-bound authorization flow for a callback without state.
    pub allow_idp_initiated: bool,
    pub override_user_info_on_sign_in: bool,
}

/// Ordering of configured and per-request additions to a provider's base scopes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OAuthScopeOrder {
    ConfiguredThenRequested,
    RequestedThenConfigured,
}

/// Encoding of the scope query value required by a provider's authorization endpoint.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum OAuthScopeEncoding {
    #[default]
    Form,
    UriComponent,
}

/// OAuth token-endpoint credential transport selected by a provider.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OAuthTokenEndpointAuth {
    ClientSecretBasic,
    ClientSecretPost,
    PrivateKeyJwt,
    None,
    /// `TikTok` authenticates with `client_key` and `client_secret`, never `client_id`.
    ClientKeyPost,
}

#[derive(Debug, Clone)]
pub struct OAuthAuthorizationCodeContext {
    pub code: String,
    pub redirect_uri: String,
    pub code_verifier: Option<String>,
    pub device_id: Option<String>,
}

#[async_trait]
pub trait OAuthAuthorizationCodeHandler: Send + Sync {
    /// Reconfigure a factory transport that directly interpolates client IDs.
    fn configured_client_ids(
        &self,
        _ids: &[String],
    ) -> Option<Arc<dyn OAuthAuthorizationCodeHandler>> {
        None
    }

    async fn validate_authorization_code(
        &self,
        context: OAuthAuthorizationCodeContext,
    ) -> Result<OAuthTokenSet, String>;
}

#[derive(Clone)]
pub struct OAuthAuthorizationCodeCallback(pub Arc<dyn OAuthAuthorizationCodeHandler>);
impl std::fmt::Debug for OAuthAuthorizationCodeCallback {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("OAuthAuthorizationCodeCallback(..)")
    }
}

/// Raw provider profile and actual grant tokens for application account authority.
#[derive(Debug, Clone)]
pub struct OAuthAccountKeyContext {
    pub tokens: OAuthTokenSet,
    pub profile: Value,
}
#[async_trait]
pub trait OAuthAccountKeyResolver: Send + Sync {
    async fn resolve(&self, context: OAuthAccountKeyContext) -> Result<Value, String>;
}
#[derive(Clone)]
pub struct OAuthAccountKey(pub Arc<dyn OAuthAccountKeyResolver>);
impl std::fmt::Debug for OAuthAccountKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OAuthAccountKey").finish_non_exhaustive()
    }
}

/// Immutable authorization configuration used by the built-in social providers.
/// Scope entries retain their original order and whitespace; providers may
/// opt into removing exact duplicates.
#[derive(Debug, Clone)]
pub struct OAuthAuthorizationPolicy {
    /// Optional application subject resolver; precedes the profile-only factory subject.
    pub account_key: Option<OAuthAccountKey>,
    /// Application callback path, normalized relative to the authentication base.
    pub callback_path: Option<String>,
    /// Preserve explicit false separately from absent provider signup configuration.
    pub disable_sign_up_option: Option<bool>,
    /// Trusted discovery issuer for authorization-response mixup protection.
    pub issuer: Option<String>,
    /// RP-initiated logout from trusted generic-provider configuration.
    pub end_session: Option<OAuthEndSessionConfig>,
    /// Verify code-grant ID tokens against trusted discovery metadata before profile admission.
    pub verify_grant_id_token: bool,
    /// Bind discovered ID tokens to a nonce in authenticated OAuth state.
    pub id_token_nonce_binding: bool,
    /// Discovery advertised OIDC signing algorithms; prepend openid if absent.
    pub discovery_openid_scope: bool,
    /// Application-owned or provider-specific code grant implementation.
    pub authorization_code: Option<OAuthAuthorizationCodeCallback>,
    /// A code grant can retain PKCE even when authorization disables it (Zoom).
    pub authorization_code_pkce: Option<bool>,
    /// Name of the client identifier in custom authorization URLs.
    pub client_id_parameter: String,
    /// Custom URL factories may interpolate the entire client array.
    pub literal_client_id: Option<String>,
    /// `WeChat`'s custom factory constructs an expiry even for zero/null seconds.
    pub token_expiry_always: bool,
    /// Custom factory token objects can omit returned grant ID tokens.
    pub token_response_omits_id_token: bool,
    pub scope_separator: String,
    pub emit_empty_scope: bool,
    pub authorization_fragment: Option<String>,
    /// Dedicated factories may lack a built-in refresh implementation (Vercel).
    pub supports_refresh: bool,
    /// `TikTok`'s published factory ignores mapProfileToUser.
    pub supports_profile_mapper: bool,
    /// Published social factories pass through omitted access tokens to userinfo.
    pub allow_missing_access_token: bool,
    /// Generic-provider fallback, applied only when a grant omits actual expiry.
    pub default_access_token_expires_in: Option<f64>,
    pub configured_scopes: Vec<String>,
    /// Providers such as `PayPal` deliberately omit even configured/requested scopes.
    pub omit_scopes: bool,
    pub scope_encoding: OAuthScopeEncoding,
    /// Retain the first occurrence of each scope, as Cloudflare requires.
    pub deduplicate_scopes: bool,
    pub require_client_id: bool,
    /// `None` preserves the existing generic provider credential transport.
    pub token_endpoint_auth: Option<OAuthTokenEndpointAuth>,
    /// Grant-specific authentication when refresh differs from code exchange.
    pub refresh_token_endpoint_auth: Option<OAuthTokenEndpointAuth>,
    /// Provider parameters applied after caller additions.
    pub fixed_authorization_params: Vec<(String, String)>,
    /// Optional application client key sent in authorization-code forms only.
    pub authorization_code_client_key: Option<String>,
    /// Trusted provider headers applied to authorization-code grants only.
    pub authorization_code_headers: Vec<(String, String)>,
    /// Trusted additional code-grant form fields (`tokenUrlParams`). Fields
    /// already supplied by the grant, including PKCE, are preserved. Token
    /// authentication is applied afterwards and retains credential authority.
    pub authorization_code_params: std::collections::BTreeMap<String, String>,
    /// Trusted static refresh form fields (`refreshTokenParams`). Ordinary
    /// fields replace defaults; grant type and refresh token cannot be replaced.
    /// Validate tenant, scope, and audience entitlements before configuring them.
    pub refresh_token_params: std::collections::BTreeMap<String, String>,
    /// When configured, replaces the static map at each default refresh grant.
    /// `Ok(None)` supplies no additions; errors abort before transport/writes.
    /// Custom refresh handlers take precedence and bypass this resolver.
    pub refresh_token_params_resolver: Option<OAuthRefreshTokenParams>,
    /// Required by `private_key_jwt`; invoked afresh for each real token grant.
    pub client_assertion: Option<OAuthClientAssertion>,
    /// Exact configured refresh scope, including an explicitly empty value.
    pub refresh_scope: Option<String>,
    pub response_type: String,
    /// Application callback URI overrides the generated provider callback.
    pub redirect_uri: Option<String>,
    pub response_mode: Option<String>,
    pub require_client_secret: bool,
    pub login_hint: bool,
    pub disable_default_scopes: bool,
    pub scope_order: OAuthScopeOrder,
    pub pkce: bool,
    pub prompt: Option<String>,
    /// Used when `prompt` is absent or empty; Discord defaults to `none`.
    pub default_prompt: Option<String>,
    /// Discord emits this JS number only when the effective scopes contain `bot`.
    pub discord_permissions: Option<f64>,
    /// Preserve thrown decoded grant-profile failures instead of redirecting.
    /// Missing/falsy ID tokens still follow the absent-profile redirect.
    pub propagate_grant_profile_errors: bool,
    /// Preserve effective raw email type errors at their callback stage.
    /// Typed native profile fields remain unchanged.
    pub preserve_raw_email_errors: bool,
    /// Retain the published adapter scalar rather than discarding it in bool projection.
    pub preserve_raw_profile_scalars: bool,
    /// Some published factories omit their returned options object entirely.
    pub honor_factory_options: bool,
    /// Preserve uncaught published profile/application callback exceptions.
    pub source_profile_exceptions: bool,
}

impl Default for OAuthAuthorizationPolicy {
    fn default() -> Self {
        Self {
            account_key: None,
            callback_path: None,
            disable_sign_up_option: None,
            issuer: None,
            end_session: None,
            verify_grant_id_token: false,
            id_token_nonce_binding: false,
            discovery_openid_scope: false,
            authorization_code: None,
            authorization_code_pkce: None,
            client_id_parameter: "client_id".into(),
            literal_client_id: None,
            token_expiry_always: false,
            token_response_omits_id_token: false,
            scope_separator: " ".into(),
            emit_empty_scope: false,
            authorization_fragment: None,
            supports_refresh: true,
            supports_profile_mapper: true,
            default_access_token_expires_in: None,
            allow_missing_access_token: false,
            configured_scopes: Vec::new(),
            omit_scopes: false,
            scope_encoding: OAuthScopeEncoding::Form,
            deduplicate_scopes: false,
            require_client_id: false,
            token_endpoint_auth: None,
            refresh_token_endpoint_auth: None,
            fixed_authorization_params: Vec::new(),
            authorization_code_client_key: None,
            authorization_code_headers: Vec::new(),
            authorization_code_params: std::collections::BTreeMap::new(),
            refresh_token_params: std::collections::BTreeMap::new(),
            refresh_token_params_resolver: None,
            client_assertion: None,
            refresh_scope: None,
            response_type: "code".into(),
            redirect_uri: None,
            response_mode: None,
            require_client_secret: false,
            login_hint: true,
            disable_default_scopes: false,
            scope_order: OAuthScopeOrder::ConfiguredThenRequested,
            pkce: true,
            prompt: None,
            default_prompt: None,
            discord_permissions: None,
            propagate_grant_profile_errors: false,
            preserve_raw_email_errors: false,
            preserve_raw_profile_scalars: false,
            honor_factory_options: true,
            source_profile_exceptions: false,
        }
    }
}

impl OAuthProvider {
    /// Install asynchronous partial mapping on the dedicated factory's profile
    /// handler. Installing a custom userinfo handler afterwards replaces both
    /// the default transport and mapping, matching getUserInfo precedence.
    #[must_use]
    pub fn with_profile_mapper(mut self, mapper: Arc<dyn OAuthProfileMapper>) -> Self {
        if self
            .authorization
            .as_ref()
            .is_none_or(|policy| policy.supports_profile_mapper)
            && let Some(handler) = self.get_user_info.take()
        {
            self.get_user_info = Some(handler.mapped_handler(mapper).unwrap_or(handler));
        }
        self
    }

    #[must_use]
    pub fn with_client_ids(mut self, client_ids: Vec<String>) -> Self {
        if let Some(handler) = self
            .get_user_info
            .as_ref()
            .and_then(|handler| handler.configured_client_ids(&client_ids))
        {
            self.get_user_info = Some(handler);
        }
        if let Some(handler) = self
            .refresh_access_token
            .as_ref()
            .and_then(|handler| handler.configured_client_ids(&client_ids))
        {
            self.refresh_access_token = Some(handler);
        }
        if let Some(policy) = self.authorization.as_mut() {
            if policy.client_id_parameter == "appid" {
                policy.literal_client_id = Some(client_ids.join(","));
            }
            if let Some(handler) = policy
                .authorization_code
                .as_ref()
                .and_then(|callback| callback.0.configured_client_ids(&client_ids))
            {
                policy.authorization_code = Some(OAuthAuthorizationCodeCallback(handler));
            }
        }
        if let Some(policy) = self.id_token.as_mut() {
            policy.client_ids = Some(client_ids.clone());
        }
        let mut ids = client_ids.into_iter();
        self.client_id = ids.next().unwrap_or_default();
        self.additional_client_ids = ids.collect();
        self
    }

    #[must_use]
    pub const fn require_email_verification(mut self, required: bool) -> Self {
        self.require_email_verification = required;
        self
    }
}

impl std::fmt::Debug for OAuthConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OAuthConfig").finish_non_exhaustive()
    }
}

impl std::fmt::Debug for OAuthProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OAuthProvider").finish_non_exhaustive()
    }
}

mod huggingface;
mod kakao;
mod kick;
mod line;
pub use huggingface::HuggingFaceOptions;
pub use kakao::KakaoOptions;
pub use kick::KickOptions;
pub use line::LineOptions;

mod naver;
pub use naver::NaverOptions;

// LCOV_EXCL_START
#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::sync::Mutex;

    async fn start_github_mock_server(
        profile: Value,
        emails: Value,
    ) -> (String, String, Arc<Mutex<Vec<String>>>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let requests = Arc::new(Mutex::new(Vec::new()));
        let captured_requests = std::sync::Arc::clone(&requests);

        tokio::spawn(async move {
            loop {
                let Ok((mut stream, _)) = listener.accept().await else {
                    break;
                };
                let profile = profile.clone();
                let emails = emails.clone();
                let requests_2 = std::sync::Arc::clone(&captured_requests);
                tokio::spawn(async move {
                    let mut buffer = vec![0u8; 4096];
                    let read = stream.read(&mut buffer).await.unwrap_or(0);
                    let request = String::from_utf8_lossy(
                        (buffer)
                            .get(..read)
                            .expect("fixture contains the requested index"),
                    )
                    .to_string();
                    requests_2.lock().await.push(request.clone());

                    let (status, body) = if request.contains("/user/emails") {
                        ("200 OK", emails.to_string())
                    } else if request.contains("/user") {
                        ("200 OK", profile.to_string())
                    } else {
                        (
                            "404 Not Found",
                            serde_json::json!({ "error": "not found" }).to_string(),
                        )
                    };

                    let response = format!(
                        "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                        body.len(),
                    );

                    _ = stream.write_all(response.as_bytes()).await;
                    _ = stream.flush().await;
                });
            }
        });

        let base_url = format!("http://127.0.0.1:{}", addr.port());
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        (
            format!("{base_url}/user"),
            format!("{base_url}/user/emails"),
            requests,
        )
    }

    // Upstream source: packages/core/src/social-providers/github.ts :: github().createAuthorizationURL default scope list.
    #[test]
    fn github_provider_uses_ts_default_scopes() {
        let provider = OAuthProvider::github("github-client-id", "github-client-secret");

        assert_eq!(
            provider.scopes,
            vec!["read:user".to_owned(), "user:email".to_owned()]
        );
        assert!(provider.get_user_info.is_some());
        assert!(provider.map_user_info.is_none());
    }

    // Upstream source: packages/core/src/social-providers/github.ts :: github().getUserInfo fallback from profile.email to /user/emails, login fallback for name, and request headers.
    #[tokio::test]
    async fn github_provider_get_user_info_uses_email_fallback_and_login_name() {
        let (user_url, emails_url, requests) = start_github_mock_server(
            serde_json::json!({
                "id": 42,
                "login": "octocat",
                "name": null,
                "email": null,
                "avatar_url": "https://avatars.githubusercontent.com/u/42?v=4",
            }),
            serde_json::json!([
                {
                    "email": "octocat@example.com",
                    "primary": true,
                    "verified": true,
                    "visibility": "private"
                },
                {
                    "email": "secondary@example.com",
                    "primary": false,
                    "verified": false,
                    "visibility": "private"
                }
            ]),
        )
        .await;

        let provider = OAuthProvider::github_with_endpoints(
            "github-client-id",
            "github-client-secret",
            "https://github.com/login/oauth/authorize",
            "https://github.com/login/oauth/access_token",
            &user_url,
            &emails_url,
        );
        let handler = provider.get_user_info.as_ref().unwrap();

        let response = handler
            .get_user_info(OAuthUserInfoRequest {
                access_token: Some("github-access-token".to_owned()),
                ..Default::default()
            })
            .await
            .unwrap();

        assert_eq!(response.user.id, "42");
        assert_eq!(response.user.email, "octocat@example.com");
        assert_eq!(response.user.name.as_deref(), Some("octocat"));
        assert_eq!(
            response.user.image.as_deref(),
            Some("https://avatars.githubusercontent.com/u/42?v=4")
        );
        assert!(response.user.email_verified);
        assert_eq!(
            (*(response.data)
                .get("email")
                .expect("fixture contains the requested index")),
            serde_json::json!("octocat@example.com")
        );

        let requests = requests.lock().await;
        assert_eq!(requests.len(), 2);
        for request in requests.iter() {
            let lowered = request.to_ascii_lowercase();
            assert!(lowered.contains("authorization: bearer github-access-token"));
            assert!(lowered.contains("user-agent: better-auth"));
        }
    }

    // Upstream source: packages/core/src/social-providers/github.ts :: github().getUserInfo keeps profile.email when present and resolves verified status from the matching email record.
    #[tokio::test]
    async fn github_provider_get_user_info_keeps_inline_email() {
        let (user_url, emails_url, _) = start_github_mock_server(
            serde_json::json!({
                "id": "github-inline-email",
                "login": "octocat",
                "name": "Octo Cat",
                "email": "public@example.com",
                "avatar_url": null,
            }),
            serde_json::json!([
                {
                    "email": "primary@example.com",
                    "primary": true,
                    "verified": true,
                    "visibility": "private"
                },
                {
                    "email": "public@example.com",
                    "primary": false,
                    "verified": false,
                    "visibility": "public"
                }
            ]),
        )
        .await;

        let provider = OAuthProvider::github_with_endpoints(
            "github-client-id",
            "github-client-secret",
            "https://github.com/login/oauth/authorize",
            "https://github.com/login/oauth/access_token",
            &user_url,
            &emails_url,
        );
        let handler = provider.get_user_info.as_ref().unwrap();

        let response = handler
            .get_user_info(OAuthUserInfoRequest {
                access_token: Some("github-access-token".to_owned()),
                ..Default::default()
            })
            .await
            .unwrap();

        assert_eq!(response.user.email, "public@example.com");
        assert_eq!(response.user.name.as_deref(), Some("Octo Cat"));
        assert!(!response.user.email_verified);
    }
}
// LCOV_EXCL_STOP

mod linkedin;
pub use linkedin::LinkedInOptions;
mod linear;
pub use linear::LinearOptions;