oauth2-passkey 0.6.0

OAuth2 and Passkey authentication library for Rust web applications
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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sqlx::FromRow;

use super::errors::OAuth2Error;
use super::main::OidcIdInfo;
use super::provider::{ProviderConfig, ProviderName};

use crate::session::UserId;
use crate::storage::CacheData;

/// Represents an OAuth2 account linked to a user
///
/// This struct contains information about an OAuth2 account that has been
/// authenticated and linked to a user in the system. It stores both
/// the provider-specific information and internal tracking data.
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct OAuth2Account {
    /// Database-assigned sequential primary key (internal, not exposed in API responses)
    #[serde(skip_serializing)]
    pub sequence_number: Option<i64>,
    /// Unique identifier for this OAuth2 account in our system
    pub id: String,
    /// Internal user ID this OAuth2 account is linked to
    pub user_id: String,
    /// OAuth2 provider name (e.g., "google")
    pub provider: String,
    /// User identifier from the OAuth2 provider
    pub provider_user_id: String,
    /// User's display name from the OAuth2 provider
    pub name: String,
    /// User's email address from the OAuth2 provider
    pub email: String,
    /// Optional URL to user's profile picture
    pub picture: Option<String>,
    /// Additional provider-specific metadata as JSON
    pub metadata: Value,
    /// When this OAuth2 account was first linked
    pub created_at: DateTime<Utc>,
    /// When this OAuth2 account was last updated
    pub updated_at: DateTime<Utc>,
}

impl Default for OAuth2Account {
    fn default() -> Self {
        Self {
            sequence_number: None,
            id: String::new(),
            user_id: String::new(),
            provider: String::new(),
            provider_user_id: String::new(),
            name: String::new(),
            email: String::new(),
            picture: None,
            metadata: Value::Null,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        }
    }
}

/// Userinfo endpoint response.
///
/// `email` and `name` are optional per OIDC Core 1.0 (they are standard claims,
/// not required ones).  When `email` is absent the implementation falls back to
/// `preferred_username` (e.g. Microsoft personal accounts return email only there).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct OidcUserInfo {
    pub(crate) sub: String,
    pub(crate) family_name: Option<String>,
    pub name: Option<String>,
    pub picture: Option<String>,
    pub(crate) email: Option<String>,
    pub(crate) given_name: Option<String>,
    pub(crate) hd: Option<String>,
    pub(crate) email_verified: Option<bool>,
    /// Fallback for `email` when the provider omits the standard claim
    /// (e.g. Microsoft personal accounts return email only in `preferred_username`).
    pub(crate) preferred_username: Option<String>,
}

/// Build an `OAuth2Account` from an ID token payload.
///
/// Free function rather than `impl From<OidcIdInfo>` because `From` takes only one
/// argument and cannot accept the provider context parameter.
///
/// `ctx.provider_name` is taken from the URL path (primary dispatch signal) and
/// cross-checked against `StateParams.provider`.  It is **not** hardcoded,
/// so DB rows reflect the actual provider that issued the token.
pub(crate) fn oauth2_account_from_idinfo(
    idinfo: &OidcIdInfo,
    ctx: &ProviderConfig,
) -> Result<OAuth2Account, OAuth2Error> {
    let provider_name = ctx.provider_name;
    let email = idinfo
        .email
        .clone()
        .or_else(|| idinfo.preferred_username.clone())
        .ok_or_else(|| {
            OAuth2Error::Validation(format!(
                "OIDC id_token from '{provider_name}' is missing both `email` and `preferred_username` claims"
            ))
        })?;
    let name = idinfo.name.clone().unwrap_or_else(|| email.clone());
    Ok(OAuth2Account {
        sequence_number: None,
        id: String::new(),
        user_id: String::new(),
        name,
        email,
        picture: idinfo.picture.clone(),
        provider: provider_name.to_string(),
        provider_user_id: format!("{}_{}", provider_name, idinfo.sub),
        metadata: json!({
            "family_name": idinfo.family_name,
            "given_name": idinfo.given_name,
            "hd": idinfo.hd,
            "verified_email": idinfo.email_verified,
        }),
        created_at: Utc::now(),
        updated_at: Utc::now(),
    })
}

/// Build an `OAuth2Account` from both the verified ID token and the userinfo
/// endpoint response, preferring the ID token per field and falling back to
/// /userinfo when the ID token omits it.
///
/// Rationale: OIDC providers split profile claims inconsistently. Some assert
/// `email` / `name` in the ID token only (Google, Entra, Okta); others only in
/// /userinfo (Zitadel, some Keycloak configs). Neither source alone is
/// universally sufficient, so the main callback needs a merged view.
///
/// The ID token wins when both sources populate a field. It is cryptographically
/// signed by the IdP and its audience/issuer/nonce have already been verified,
/// so it is the stronger trust root for identity-critical claims (email, sub).
/// /userinfo is retrieved over TLS using an access token and is not itself
/// signed, so it is used only to fill gaps left by the ID token.
///
/// The `sub` equality invariant (`idinfo.sub == userinfo.sub`) is assumed to
/// have been verified upstream by `get_idinfo_userinfo`; this function uses
/// `idinfo.sub` when building `provider_user_id`.
pub(crate) fn oauth2_account_from_idinfo_and_userinfo(
    idinfo: &OidcIdInfo,
    userinfo: &OidcUserInfo,
    ctx: &ProviderConfig,
) -> Result<OAuth2Account, OAuth2Error> {
    validate_claim_match(idinfo, userinfo, ctx)?;

    let provider_name = ctx.provider_name;
    let email = idinfo
        .email
        .clone()
        .or_else(|| userinfo.email.clone())
        .or_else(|| idinfo.preferred_username.clone())
        .or_else(|| userinfo.preferred_username.clone())
        .ok_or_else(|| {
            OAuth2Error::Validation(format!(
                "OIDC response from '{provider_name}' is missing `email` / `preferred_username` in both id_token and userinfo"
            ))
        })?;
    let name = idinfo
        .name
        .clone()
        .or_else(|| userinfo.name.clone())
        .unwrap_or_else(|| email.clone());
    let picture = idinfo.picture.clone().or_else(|| userinfo.picture.clone());
    let family_name = idinfo
        .family_name
        .clone()
        .or_else(|| userinfo.family_name.clone());
    let given_name = idinfo
        .given_name
        .clone()
        .or_else(|| userinfo.given_name.clone());
    let hd = idinfo.hd.clone().or_else(|| userinfo.hd.clone());
    let email_verified = idinfo.email_verified.or(userinfo.email_verified);
    Ok(OAuth2Account {
        sequence_number: None,
        id: String::new(),
        user_id: String::new(),
        name,
        email,
        picture,
        provider: provider_name.to_string(),
        provider_user_id: format!("{}_{}", provider_name, idinfo.sub),
        metadata: json!({
            "family_name": family_name,
            "given_name": given_name,
            "hd": hd,
            "email_verified": email_verified,
        }),
        created_at: Utc::now(),
        updated_at: Utc::now(),
    })
}

/// Detect divergence between the verified ID token and the /userinfo response.
///
/// Both sources are fetched within milliseconds of each other in a single OAuth2
/// flow and reflect the same user snapshot; any field-level divergence is
/// therefore anomalous, not legitimate drift.
///
/// Classification:
///
/// * **Identity-tier** (`email`, `email_verified`, `preferred_username`, `hd`) —
///   always rejected on mismatch. These drive authn/authz decisions and silent
///   divergence is a security concern. Not configurable.
/// * **Display-tier** (`name`, `picture`, `family_name`, `given_name`) —
///   rejected when `ctx.strict_display_claims` is `true` (default); otherwise a
///   warning is emitted and the id_token value is used (Option B merge priority
///   preserved).
///
/// The check fires only when **both sides are `Some`** and the values differ.
/// One-sided `None` is a normal merge case and is silently allowed.
fn validate_claim_match(
    idinfo: &OidcIdInfo,
    userinfo: &OidcUserInfo,
    ctx: &ProviderConfig,
) -> Result<(), OAuth2Error> {
    let provider = ctx.provider_name;

    // Tier 1 — identity/authorization-critical, always strict.
    check_strict(
        "email",
        idinfo.email.as_deref(),
        userinfo.email.as_deref(),
        provider,
    )?;
    check_strict_bool(
        "email_verified",
        idinfo.email_verified,
        userinfo.email_verified,
        provider,
    )?;
    check_strict(
        "preferred_username",
        idinfo.preferred_username.as_deref(),
        userinfo.preferred_username.as_deref(),
        provider,
    )?;
    check_strict("hd", idinfo.hd.as_deref(), userinfo.hd.as_deref(), provider)?;

    // Tier 2 — display/metadata, flag-controlled.
    let strict = ctx.strict_display_claims;
    check_display(
        "name",
        idinfo.name.as_deref(),
        userinfo.name.as_deref(),
        provider,
        strict,
    )?;
    check_display(
        "picture",
        idinfo.picture.as_deref(),
        userinfo.picture.as_deref(),
        provider,
        strict,
    )?;
    check_display(
        "family_name",
        idinfo.family_name.as_deref(),
        userinfo.family_name.as_deref(),
        provider,
        strict,
    )?;
    check_display(
        "given_name",
        idinfo.given_name.as_deref(),
        userinfo.given_name.as_deref(),
        provider,
        strict,
    )?;

    Ok(())
}

fn check_strict(
    field: &'static str,
    idinfo_value: Option<&str>,
    userinfo_value: Option<&str>,
    provider: ProviderName,
) -> Result<(), OAuth2Error> {
    match (idinfo_value, userinfo_value) {
        (Some(a), Some(b)) if a != b => Err(OAuth2Error::ClaimMismatch {
            field,
            idinfo_value: a.to_string(),
            userinfo_value: b.to_string(),
            provider: provider.to_string(),
        }),
        _ => Ok(()),
    }
}

fn check_strict_bool(
    field: &'static str,
    idinfo_value: Option<bool>,
    userinfo_value: Option<bool>,
    provider: ProviderName,
) -> Result<(), OAuth2Error> {
    match (idinfo_value, userinfo_value) {
        (Some(a), Some(b)) if a != b => Err(OAuth2Error::ClaimMismatch {
            field,
            idinfo_value: a.to_string(),
            userinfo_value: b.to_string(),
            provider: provider.to_string(),
        }),
        _ => Ok(()),
    }
}

fn check_display(
    field: &'static str,
    idinfo_value: Option<&str>,
    userinfo_value: Option<&str>,
    provider: ProviderName,
    strict: bool,
) -> Result<(), OAuth2Error> {
    match (idinfo_value, userinfo_value) {
        (Some(a), Some(b)) if a != b => {
            if strict {
                Err(OAuth2Error::ClaimMismatch {
                    field,
                    idinfo_value: a.to_string(),
                    userinfo_value: b.to_string(),
                    provider: provider.to_string(),
                })
            } else {
                tracing::warn!(
                    security_event = "oauth2_claim_mismatch",
                    field = field,
                    idinfo_value = a,
                    userinfo_value = b,
                    provider = %provider,
                    "claim mismatch between id_token and /userinfo; using id_token value (set OAUTH2_<provider>_STRICT_DISPLAY_CLAIMS=true to reject)"
                );
                Ok(())
            }
        }
        _ => Ok(()),
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub(crate) struct StateParams {
    pub(crate) csrf_id: String,
    pub(crate) nonce_id: String,
    pub(crate) pkce_id: String,
    pub(crate) misc_id: Option<String>,
    pub(crate) mode_id: Option<String>,
    /// Provider name embedded in state as a defense-in-depth cross-check.
    /// The URL path (`/oauth2/{provider}/authorized`) is the primary dispatch
    /// signal; this field is only used to detect URL/state mismatches.
    pub(crate) provider: String,
}

#[derive(Serialize, Clone, Deserialize, Debug)]
pub(crate) struct StoredToken {
    pub(crate) token: String,
    pub(crate) expires_at: DateTime<Utc>,
    pub(crate) user_agent: Option<String>,
    pub(crate) ttl: u64,
}

/// Response from an OAuth2 authorization request
///
/// This struct represents the data received from an OAuth2 provider's
/// authorization endpoint. It contains the authorization code and state
/// parameter needed to complete the OAuth2 flow.
#[derive(Debug, Deserialize)]
pub struct AuthResponse {
    /// Authorization code from the OAuth2 provider
    pub(crate) code: String,
    /// State parameter that was included in the original request
    pub state: String,
    /// Optional ID token if provided directly by the authorization endpoint
    _id_token: Option<String>,
}

#[derive(Debug, Deserialize, Serialize)]
pub(super) struct OidcTokenResponse {
    pub(super) access_token: String,
    token_type: String,
    // Optional per RFC 6749 §5.1 (RECOMMENDED, not REQUIRED). Some
    // providers (e.g. older Keycloak builds, some Ory Hydra configs)
    // omit it entirely.
    expires_in: Option<u64>,
    refresh_token: Option<String>,
    scope: Option<String>,
    pub(super) id_token: Option<String>,
}

impl From<StoredToken> for CacheData {
    fn from(data: StoredToken) -> Self {
        Self {
            value: serde_json::to_string(&data).expect("Failed to serialize StoredToken"),
        }
    }
}

impl TryFrom<CacheData> for StoredToken {
    type Error = OAuth2Error;

    fn try_from(data: CacheData) -> Result<Self, Self::Error> {
        serde_json::from_str(&data.value).map_err(|e| OAuth2Error::Storage(e.to_string()))
    }
}

/// Search field options for credential lookup
#[allow(dead_code)]
#[derive(Debug, PartialEq)]
pub(crate) enum AccountSearchField {
    /// Search by ID (type-safe)
    Id(AccountId),
    /// Search by user ID (database ID, type-safe)
    UserId(UserId),
    /// Search by provider (type-safe)
    Provider(Provider),
    /// Search by provider user ID (type-safe)
    ProviderUserId(ProviderUserId),
    /// Search by name (type-safe)
    Name(DisplayName),
    /// Search by email (type-safe)
    Email(Email),
}

/// Mode of OAuth2 operation to explicitly indicate user intent.
///
/// This enum defines the available modes for OAuth2 authentication, determining
/// the behavior when a user authenticates with an OAuth2 provider.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OAuth2Mode {
    /// Add an OAuth2 account to an existing user.
    ///
    /// This mode is used when an authenticated user wants to link an additional
    /// OAuth2 provider account to their existing account.
    AddToUser,

    /// Create a new user account from the OAuth2 provider data.
    ///
    /// This mode is used specifically for new user registration using OAuth2.
    CreateUser,

    /// Login with an existing OAuth2 account.
    ///
    /// This mode is used when a user wants to authenticate using a previously
    /// linked OAuth2 provider account.
    Login,

    /// Create a new user if no matching account exists, otherwise login.
    ///
    /// This flexible mode attempts to login with an existing account if one matches
    /// the OAuth2 provider data, or creates a new user account if none is found.
    CreateUserOrLogin,
}

impl OAuth2Mode {
    /// Converts the OAuth2Mode enum variant to its string representation.
    ///
    /// This method returns a static string representing the mode, which can be
    /// used in URLs, API responses, or for logging purposes.
    ///
    /// # Returns
    ///
    /// * A string representation of the OAuth2Mode
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::AddToUser => "add_to_user",
            Self::CreateUser => "create_user",
            Self::Login => "login",
            Self::CreateUserOrLogin => "create_user_or_login",
        }
    }
}

impl std::str::FromStr for OAuth2Mode {
    type Err = OAuth2Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "add_to_user" => Ok(Self::AddToUser),
            "create_user" => Ok(Self::CreateUser),
            "login" => Ok(Self::Login),
            "create_user_or_login" => Ok(Self::CreateUserOrLogin),
            _ => Err(OAuth2Error::InvalidMode(s.to_string())),
        }
    }
}

/// Type-safe wrapper for OAuth2 account identifiers.
///
/// This provides compile-time safety to prevent mixing up account IDs with other string types.
/// Account IDs are database-specific identifiers for OAuth2 accounts.
#[derive(Debug, Clone, PartialEq)]
pub struct AccountId(String);

impl AccountId {
    /// Creates a new AccountId from a string with validation.
    ///
    /// # Arguments
    /// * `id` - The account ID string
    ///
    /// # Returns
    /// * `Ok(AccountId)` - If the ID is valid
    /// * `Err(OAuth2Error)` - If the ID is invalid
    ///
    /// # Validation Rules
    /// * Must not be empty
    /// * Must contain only safe characters (alphanumeric + basic symbols)
    /// * Must not contain control characters or dangerous sequences
    pub fn new(id: String) -> Result<Self, crate::oauth2::OAuth2Error> {
        use crate::oauth2::OAuth2Error;

        // Validate ID is not empty
        if id.is_empty() {
            return Err(OAuth2Error::Validation(
                "Account ID cannot be empty".to_string(),
            ));
        }

        // Validate ID length (reasonable bounds)
        if id.len() > 255 {
            return Err(OAuth2Error::Validation("Account ID too long".to_string()));
        }

        // Validate ID contains only safe characters
        if !id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '@' | '+'))
        {
            return Err(OAuth2Error::Validation(
                "Account ID contains invalid characters".to_string(),
            ));
        }

        // Check for dangerous sequences
        if id.contains("..") || id.contains("--") || id.contains("__") {
            return Err(OAuth2Error::Validation(
                "Account ID contains dangerous character sequences".to_string(),
            ));
        }

        Ok(AccountId(id))
    }

    /// Returns the account ID as a string slice.
    ///
    /// # Returns
    /// * A string slice containing the account ID
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Type-safe wrapper for OAuth2 provider names.
///
/// This provides compile-time safety to prevent mixing up provider names with other string types.
/// Provider names identify the OAuth2 service (e.g., "google", "github").
#[derive(Debug, Clone, PartialEq)]
pub struct Provider(String);

impl Provider {
    /// Creates a new Provider from a string with validation.
    ///
    /// # Arguments
    /// * `provider` - The provider name string
    ///
    /// # Returns
    /// * `Ok(Provider)` - If the provider name is valid
    /// * `Err(OAuth2Error)` - If the provider name is invalid
    ///
    /// # Validation Rules
    /// * Must not be empty
    /// * Must contain only safe characters (alphanumeric, hyphens, underscores, periods)
    /// * Must not start with special characters
    pub fn new(provider: String) -> Result<Self, crate::oauth2::OAuth2Error> {
        use crate::oauth2::OAuth2Error;

        // Validate provider is not empty
        if provider.is_empty() {
            return Err(OAuth2Error::Validation(
                "Provider name cannot be empty".to_string(),
            ));
        }

        // Validate provider length (reasonable bounds for provider names)
        if provider.len() > 50 {
            return Err(OAuth2Error::Validation(
                "Provider name too long".to_string(),
            ));
        }

        // Validate provider contains only safe characters (alphanumeric, hyphens, underscores, periods)
        // Must not start with special characters
        if !provider
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
        {
            return Err(OAuth2Error::Validation(
                "Provider name contains invalid characters".to_string(),
            ));
        }

        if provider.starts_with('-') || provider.starts_with('_') || provider.starts_with('.') {
            return Err(OAuth2Error::Validation(
                "Provider name cannot start with special characters".to_string(),
            ));
        }

        Ok(Provider(provider))
    }

    /// Returns the provider name as a string slice.
    ///
    /// # Returns
    /// * A string slice containing the provider name
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Type-safe wrapper for provider-specific user identifiers.
///
/// This provides compile-time safety to prevent mixing up provider user IDs with database user IDs.
/// Provider user IDs are external identifiers from OAuth2 providers (e.g., Google user ID).
#[derive(Debug, Clone, PartialEq)]
pub struct ProviderUserId(String);

impl ProviderUserId {
    /// Creates a new ProviderUserId from a string with validation.
    ///
    /// # Arguments
    /// * `id` - The provider user ID string
    ///
    /// # Returns
    /// * `Ok(ProviderUserId)` - If the ID is valid
    /// * `Err(OAuth2Error)` - If the ID is invalid
    ///
    /// # Validation Rules
    /// * Must not be empty
    /// * Must contain only safe characters (alphanumeric + basic symbols)
    /// * Must not contain control characters or dangerous sequences
    pub fn new(id: String) -> Result<Self, crate::oauth2::OAuth2Error> {
        use crate::oauth2::OAuth2Error;

        // Validate ID is not empty
        if id.is_empty() {
            return Err(OAuth2Error::Validation(
                "Provider user ID cannot be empty".to_string(),
            ));
        }

        // Validate ID length (provider IDs can be long but reasonable bounds)
        if id.len() > 512 {
            return Err(OAuth2Error::Validation(
                "Provider user ID too long".to_string(),
            ));
        }

        // Validate ID contains only safe characters
        // '|' is included to support Auth0's sub format: "auth0|{id}"
        if !id.chars().all(|c| {
            c.is_ascii_alphanumeric()
                || matches!(c, '-' | '_' | '.' | '@' | '+' | '=' | '(' | ')' | '|')
        }) {
            return Err(OAuth2Error::Validation(
                "Provider user ID contains invalid characters".to_string(),
            ));
        }

        // Check for dangerous sequences
        if id.contains("..") || id.contains("--") || id.contains("__") {
            return Err(OAuth2Error::Validation(
                "Provider user ID contains dangerous character sequences".to_string(),
            ));
        }

        Ok(ProviderUserId(id))
    }

    /// Returns the provider user ID as a string slice.
    ///
    /// # Returns
    /// * A string slice containing the provider user ID
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Type-safe wrapper for user display names.
///
/// This provides compile-time safety to prevent mixing up display names with other string types.
/// Display names are user-facing names from OAuth2 providers.
#[derive(Debug, Clone, PartialEq)]
pub struct DisplayName(String);

impl DisplayName {
    /// Creates a new DisplayName from a string with validation.
    ///
    /// This constructor is part of the public type-safe search API and is used
    /// internally by the AccountSearchField enum for database queries.
    ///
    /// # Arguments
    /// * `name` - The display name string
    ///
    /// # Returns
    /// * `Ok(DisplayName)` - If the name is valid
    /// * `Err(OAuth2Error)` - If the name is invalid
    ///
    /// # Validation Rules
    /// * Must not be empty
    /// * Must not consist only of whitespace
    /// * Must not contain dangerous sequences
    #[allow(dead_code)] // Part of type-safe search API, used in tests but not by library's public interface
    pub fn new(name: String) -> Result<Self, crate::oauth2::OAuth2Error> {
        use crate::oauth2::OAuth2Error;

        // Validate name is not empty
        if name.is_empty() {
            return Err(OAuth2Error::Validation(
                "Display name cannot be empty".to_string(),
            ));
        }

        // Validate name length (reasonable bounds for display names)
        if name.len() > 100 {
            return Err(OAuth2Error::Validation("Display name too long".to_string()));
        }

        // Validate name doesn't consist only of whitespace
        if name.trim().is_empty() {
            return Err(OAuth2Error::Validation(
                "Display name cannot consist only of whitespace".to_string(),
            ));
        }

        // Check for dangerous sequences
        if name.contains("..") || name.contains("--") || name.contains("__") {
            return Err(OAuth2Error::Validation(
                "Display name contains dangerous character sequences".to_string(),
            ));
        }

        Ok(DisplayName(name))
    }

    /// Returns the display name as a string slice.
    ///
    /// # Returns
    /// * A string slice containing the display name
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Type-safe wrapper for email addresses.
///
/// This provides compile-time safety to prevent mixing up email addresses with other string types.
/// Email addresses are provided by OAuth2 providers for user identification.
#[derive(Debug, Clone, PartialEq)]
pub struct Email(String);

impl Email {
    /// Creates a new Email from a string with validation.
    ///
    /// This constructor is part of the public type-safe search API and is used
    /// internally by the AccountSearchField enum for database queries.
    ///
    /// # Arguments
    /// * `email` - The email address string
    ///
    /// # Returns
    /// * `Ok(Email)` - If the email is valid
    /// * `Err(OAuth2Error)` - If the email is invalid
    ///
    /// # Validation Rules
    /// * Must not be empty
    /// * Must contain @ symbol
    /// * Must have reasonable length
    #[allow(dead_code)] // Part of type-safe search API, used in tests but not by library's public interface
    pub fn new(email: String) -> Result<Self, crate::oauth2::OAuth2Error> {
        use crate::oauth2::OAuth2Error;

        // Validate email is not empty
        if email.is_empty() {
            return Err(OAuth2Error::Validation("Email cannot be empty".to_string()));
        }

        // Validate email length (RFC 5321 limits: maximum 254 characters)
        if email.len() < 3 {
            return Err(OAuth2Error::Validation("Email too short".to_string()));
        }

        if email.len() > 254 {
            return Err(OAuth2Error::Validation("Email too long".to_string()));
        }

        // Basic email format validation (must contain @ and reasonable structure)
        if !email.contains('@') {
            return Err(OAuth2Error::Validation(
                "Email must contain @ symbol".to_string(),
            ));
        }

        let parts: Vec<&str> = email.split('@').collect();
        if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() {
            return Err(OAuth2Error::Validation(
                "Email format is invalid".to_string(),
            ));
        }

        Ok(Email(email))
    }

    /// Returns the email address as a string slice.
    ///
    /// # Returns
    /// * A string slice containing the email address
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Type-safe wrapper for OAuth2 state parameters.
///
/// This provides compile-time safety to prevent mixing up OAuth2 state strings with other string types.
/// OAuth2 state parameters are base64url-encoded JSON that carries CSRF protection and flow parameters
/// between authorization requests and callbacks. Proper validation is critical for security.
#[derive(Debug, Clone, PartialEq)]
pub struct OAuth2State(String);

impl std::fmt::Display for OAuth2State {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl OAuth2State {
    /// Creates a new OAuth2State from a string with validation.
    ///
    /// This constructor validates the OAuth2 state format to ensure it meets
    /// security requirements for CSRF protection and parameter integrity.
    ///
    /// # Arguments
    /// * `state` - The OAuth2 state string (should be base64url-encoded)
    ///
    /// # Returns
    /// * `Ok(OAuth2State)` - If the state is valid
    /// * `Err(OAuth2Error)` - If the state is invalid
    ///
    /// # Validation Rules
    /// * Must not be empty
    /// * Must be valid base64url encoding
    /// * Must contain valid JSON when decoded
    /// * Must be reasonable length
    pub fn new(state: String) -> Result<Self, super::errors::OAuth2Error> {
        use super::errors::OAuth2Error;
        use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};

        // Validate state is not empty
        if state.is_empty() {
            return Err(OAuth2Error::DecodeState(
                "OAuth2 state cannot be empty".to_string(),
            ));
        }

        // Validate state length (reasonable bounds)
        if state.len() < 10 {
            return Err(OAuth2Error::DecodeState(
                "OAuth2 state too short".to_string(),
            ));
        }

        if state.len() > 8192 {
            return Err(OAuth2Error::DecodeState(
                "OAuth2 state too long".to_string(),
            ));
        }

        // Validate state is valid base64url
        let decoded_bytes = URL_SAFE_NO_PAD
            .decode(&state)
            .map_err(|e| OAuth2Error::DecodeState(format!("Invalid base64url encoding: {e}")))?;

        // Validate decoded content is valid UTF-8
        let decoded_string = String::from_utf8(decoded_bytes).map_err(|e| {
            OAuth2Error::DecodeState(format!("Invalid UTF-8 in decoded state: {e}"))
        })?;

        // Validate decoded content is valid JSON
        let _: StateParams = serde_json::from_str(&decoded_string)
            .map_err(|e| OAuth2Error::DecodeState(format!("Invalid JSON in decoded state: {e}")))?;

        Ok(OAuth2State(state))
    }

    /// Returns the OAuth2 state as a string slice.
    ///
    /// # Returns
    /// * A string slice containing the OAuth2 state
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Checks if the state contains a substring.
    ///
    /// # Arguments
    /// * `needle` - The substring to search for
    ///
    /// # Returns
    /// * `true` if the substring is found, `false` otherwise
    pub fn contains(&self, needle: char) -> bool {
        self.0.contains(needle)
    }
}

/// Type-safe wrapper for OAuth2 token types.
///
/// This enum provides compile-time safety to prevent mixing up different types of OAuth2 tokens.
/// It ensures that token types are clearly defined and prevents typos in token type strings.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TokenType {
    /// CSRF protection token for OAuth2 authorization flow
    Csrf,
    /// Nonce token for OpenID Connect
    Nonce,
    /// PKCE (Proof Key for Code Exchange) verifier token
    Pkce,
}

impl std::fmt::Display for TokenType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl TokenType {
    /// Returns the token type as a string slice.
    ///
    /// # Returns
    /// * A string slice containing the token type name
    pub fn as_str(&self) -> &str {
        match self {
            TokenType::Csrf => "csrf",
            TokenType::Nonce => "nonce",
            TokenType::Pkce => "pkce",
        }
    }
}

/// Response from the FedCM nonce generation endpoint
///
/// Contains the nonce for the FedCM `navigator.credentials.get()` call
/// and the cache ID for server-side nonce validation during callback.
#[derive(Debug, Serialize, Deserialize)]
pub struct FedCMNonceResponse {
    /// Nonce value to pass to `navigator.credentials.get()`
    pub nonce: String,
    /// Cache key for retrieving the stored nonce during callback
    pub nonce_id: String,
}

/// Request body for the FedCM callback endpoint
///
/// Contains the JWT ID token received from FedCM, the cache ID for
/// nonce verification, and the optional OAuth2 mode.
#[derive(Debug, Deserialize)]
pub struct FedCMCallbackRequest {
    /// JWT ID token from `credential.token` returned by FedCM
    pub credential: String,
    /// Cache key for the stored nonce (for verification)
    pub nonce_id: String,
    /// OAuth2 mode (e.g., "login", "create_user") sent directly by the client
    pub mode: Option<String>,
}

#[cfg(test)]
mod tests;