alibi-core 0.1.0

Shared authentication contracts and backend-independent services 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
mod codes;

use codes::upstream_code;
pub mod page;
use thiserror::Error;

/// Authentication framework error types.
///
/// Each variant maps to an HTTP status code via [`AuthError::status_code`].
/// Use [`AuthError::to_auth_response`] to produce a standardized JSON response
/// matching the better-auth `OpenAPI` spec: `{ "message": "..." }`.
#[derive(Error, Debug)]
pub enum AuthError {
    /// An intentional public API error from application policy or input validation.
    ///
    /// The supplied message is returned verbatim, including for a 500 status.
    /// Use internal error variants for database failures or other private details.
    #[error("{message}")]
    Api {
        status: u16,
        code: Option<String>,
        message: String,
    },

    /// A documented upstream API error whose message is safe to return publicly.
    #[error("{message}")]
    Upstream {
        /// HTTP response status defined by the upstream endpoint.
        status: u16,
        /// Stable upstream error code.
        code: &'static str,
        /// Documented public error message. Never include internal failure details.
        message: &'static str,
    },

    #[error("{0}")]
    BadRequest(String),

    #[error("Invalid request: {0}")]
    InvalidRequest(String),

    #[error("Validation error: {0}")]
    Validation(String),

    #[error("Invalid email or password")]
    InvalidCredentials,

    #[error("Authentication required")]
    Unauthenticated,

    #[error("{0}")]
    AuthenticationFailed(String),

    #[error("Session not found or expired")]
    SessionNotFound,

    #[error("{0}")]
    Forbidden(String),

    /// A session-create lifecycle hook explicitly cancelled creation.
    /// Callers may apply endpoint-specific null-session behavior; the default
    /// public response retains the existing cancellation status and message.
    #[error("session creation cancelled by database hook")]
    SessionCreationCancelled,

    /// A user-create database hook explicitly cancelled creation.
    /// Endpoint owners may map the absent user differently from a genuine
    /// application Forbidden error with the same text.
    #[error("user creation cancelled by database hook")]
    UserCreationCancelled,

    #[error("{0}")]
    BannedUser(String),

    #[error("Insufficient permissions")]
    Unauthorized,

    #[error("User not found")]
    UserNotFound,

    #[error("{0}")]
    NotFound(String),

    #[error("{0}")]
    Conflict(String),

    #[error("{0}")]
    MethodNotAllowed(String),

    #[error("{0}")]
    PayloadTooLarge(String),

    #[error("{0}")]
    UnprocessableEntity(String),

    /// `retry_after` is the number of seconds until the next request is
    /// admitted; responses publish it as `X-Retry-After`.
    #[error("Too many requests")]
    RateLimited { retry_after: Option<f64> },

    #[error("{0}")]
    NotImplemented(String),

    #[error("Configuration error: {0}")]
    Config(String),

    #[error("Database error: {0}")]
    Database(#[from] DatabaseError),

    #[error("Serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    #[error("Plugin error: {plugin} - {message}")]
    Plugin { plugin: String, message: String },

    #[error("Internal server error: {0}")]
    Internal(String),

    /// Authentication or encoding of encrypted persistence data failed.
    /// HTTP callers receive an empty 500; private details are logged.
    #[error("Encrypted authentication data failed: {0}")]
    Encryption(String),

    /// An ordinary application callback failure whose HTTP contract is an empty 500.
    /// The private cause is logged, never sent to the client. Explicit API errors
    /// retain their own response and must not be wrapped in this variant.
    #[error("Application callback failed: {0}")]
    CallbackFailure(Box<Self>),

    #[error("Password hashing error: {0}")]
    PasswordHash(String),

    #[error("JWT error: {0}")]
    Jwt(#[from] jsonwebtoken::errors::Error),
}

impl AuthError {
    /// HTTP status code for this error.
    #[must_use]
    pub const fn status_code(&self) -> u16 {
        match self {
            Self::Api { status, .. } | Self::Upstream { status, .. } => *status,
            // 400
            Self::BadRequest(_) | Self::InvalidRequest(_) | Self::Validation(_) => 400,
            // 401
            Self::InvalidCredentials
            | Self::Unauthenticated
            | Self::AuthenticationFailed(_)
            | Self::SessionNotFound => 401,
            // 403
            Self::Forbidden(_)
            | Self::SessionCreationCancelled
            | Self::UserCreationCancelled
            | Self::BannedUser(_)
            | Self::Unauthorized => 403,
            // 404
            Self::UserNotFound | Self::NotFound(_) => 404,
            // 409
            Self::Conflict(_) => 409,
            // 405
            Self::MethodNotAllowed(_) => 405,
            // 413
            Self::PayloadTooLarge(_) => 413,
            // 422
            Self::UnprocessableEntity(_) => 422,
            // 429
            Self::RateLimited { .. } => 429,
            // 501
            Self::NotImplemented(_) => 501,
            // 500
            Self::Config(_)
            | Self::Database(_)
            | Self::Serialization(_)
            | Self::Plugin { .. }
            | Self::Internal(_)
            | Self::Encryption(_)
            | Self::CallbackFailure(_)
            | Self::PasswordHash(_)
            | Self::Jwt(_) => 500,
        }
    }

    /// Resolve the wire error code for a message, if upstream defines one.
    ///
    /// better-auth 1.5 replaced message-derived codes with explicit constants,
    /// and only errors built from one of those constants carry a `code` at all
    /// (`APIError.from` sets it; a plain `new APIError(status, { message })`
    /// does not). So an unknown message yields `None` and the field is omitted,
    /// rather than being back-derived from the text.
    pub fn code_from_message(message: &str) -> Option<String> {
        upstream_code(message).map(str::to_owned)
    }

    /// Compute the HTTP status, error code, and user-facing message.
    ///
    /// The code is `None` for messages upstream has no constant for; those
    /// responses carry only a `message`.
    ///
    /// Internal errors (500) are logged and replaced with a generic message
    /// to avoid leaking details.
    pub fn error_payload(&self) -> (u16, Option<String>, String) {
        let status = self.status_code();
        let (code, message) = match self {
            Self::Api { code, message, .. } => (code.clone(), message.clone()),
            Self::Upstream { code, message, .. } => {
                (Some((*code).to_owned()), (*message).to_owned())
            }
            Self::BannedUser(message) => (Some("BANNED_USER".to_owned()), message.clone()),
            Self::BadRequest(_)
            | Self::InvalidRequest(_)
            | Self::Validation(_)
            | Self::InvalidCredentials
            | Self::Unauthenticated
            | Self::AuthenticationFailed(_)
            | Self::SessionNotFound
            | Self::Forbidden(_)
            | Self::SessionCreationCancelled
            | Self::UserCreationCancelled
            | Self::Unauthorized
            | Self::UserNotFound
            | Self::NotFound(_)
            | Self::Conflict(_)
            | Self::MethodNotAllowed(_)
            | Self::PayloadTooLarge(_)
            | Self::UnprocessableEntity(_)
            | Self::RateLimited { .. }
            | Self::NotImplemented(_)
            | Self::Config(_)
            | Self::Database(_)
            | Self::Serialization(_)
            | Self::Plugin { .. }
            | Self::Internal(_)
            | Self::Encryption(_)
            | Self::CallbackFailure(_)
            | Self::PasswordHash(_)
            | Self::Jwt(_) => {
                let message = match status {
                    500 => {
                        tracing::error!(error = %self, "Internal server error");
                        "Internal server error".to_owned()
                    }
                    _ => self.to_string(),
                };
                let code = Self::code_from_message(&message);
                (code, message)
            }
        };
        (status, code, message)
    }

    /// Convert this error into a standardized [`AuthResponse`](crate::types::AuthResponse) matching the
    /// better-auth spec: `{ "code": "...", "message": "..." }`.
    ///
    /// Named `to_auth_response` to avoid collision with Axum's
    /// `IntoResponse::into_response` when the `axum` feature is enabled.
    #[must_use]
    pub fn to_auth_response(self) -> crate::types::AuthResponse {
        if matches!(&self, Self::CallbackFailure(_) | Self::Encryption(_)) {
            tracing::error!(error = %self, "Authentication operation failed");
            return crate::types::AuthResponse::new(500);
        }
        let retry_after = self.retry_after_header();
        let (status, code, message) = self.error_payload();
        let response = crate::types::AuthResponse::json(
            status,
            &crate::types::ErrorCodeMessageResponse {
                code,
                message: message.clone(),
            },
        )
        .unwrap_or_else(|_| crate::types::AuthResponse::text(status, &message));
        match retry_after {
            Some(seconds) => response.with_header("X-Retry-After", seconds),
            None => response,
        }
    }

    /// The `X-Retry-After` value of a rate-limit rejection, formatted as the
    /// rate-limit middleware publishes it.
    fn retry_after_header(&self) -> Option<String> {
        match self {
            Self::RateLimited {
                retry_after: Some(seconds),
            } => Some(ryu_js::Buffer::new().format(*seconds).to_owned()),
            _ => None,
        }
    }

    /// A `429` rejection that tells the client to retry after `retry_after` seconds,
    /// such as [`RateLimitDecision::Blocked`](crate::middleware::RateLimitDecision::Blocked)'s.
    #[must_use]
    pub const fn rate_limited(retry_after: f64) -> Self {
        Self::RateLimited {
            retry_after: Some(retry_after),
        }
    }

    #[must_use]
    pub fn bad_request(message: impl Into<String>) -> Self {
        Self::BadRequest(message.into())
    }

    #[must_use]
    pub fn forbidden(message: impl Into<String>) -> Self {
        Self::Forbidden(message.into())
    }

    #[must_use]
    pub fn banned_user(message: impl Into<String>) -> Self {
        Self::BannedUser(message.into())
    }

    #[must_use]
    pub fn not_found(message: impl Into<String>) -> Self {
        Self::NotFound(message.into())
    }

    #[must_use]
    pub fn conflict(message: impl Into<String>) -> Self {
        Self::Conflict(message.into())
    }

    #[must_use]
    pub fn method_not_allowed(message: impl Into<String>) -> Self {
        Self::MethodNotAllowed(message.into())
    }

    #[must_use]
    pub fn payload_too_large(message: impl Into<String>) -> Self {
        Self::PayloadTooLarge(message.into())
    }

    #[must_use]
    pub fn not_implemented(message: impl Into<String>) -> Self {
        Self::NotImplemented(message.into())
    }

    #[must_use]
    pub fn plugin(plugin: &str, message: impl Into<String>) -> Self {
        Self::Plugin {
            plugin: plugin.to_owned(),
            message: message.into(),
        }
    }

    #[must_use]
    pub fn config(message: impl Into<String>) -> Self {
        Self::Config(message.into())
    }

    #[must_use]
    pub fn internal(message: impl Into<String>) -> Self {
        Self::Internal(message.into())
    }

    #[must_use]
    pub fn validation(message: impl Into<String>) -> Self {
        Self::Validation(message.into())
    }

    #[must_use]
    pub fn authentication_failed(message: impl Into<String>) -> Self {
        Self::AuthenticationFailed(message.into())
    }
}

#[derive(Error, Debug)]
pub enum DatabaseError {
    /// Multiple physical rows share a provider identity; ownership is ambiguous.
    #[error(
        "Multiple accounts match the same accountId for provider {provider:?}. Resolve duplicate account identities before continuing."
    )]
    AmbiguousAccount { provider: String },

    #[error("Connection error: {0}")]
    Connection(String),

    #[error("Query error: {0}")]
    Query(String),

    #[error("Migration error: {0}")]
    Migration(String),

    #[error("Constraint violation: {0}")]
    Constraint(String),

    #[error("Transaction error: {0}")]
    Transaction(String),
}

pub type AuthResult<T> = Result<T, AuthError>;

#[cfg(feature = "axum")]
impl axum::response::IntoResponse for AuthError {
    fn into_response(self) -> axum::response::Response {
        if matches!(&self, Self::CallbackFailure(_) | Self::Encryption(_)) {
            tracing::error!(error = %self, "Authentication operation failed");
            return axum::http::StatusCode::INTERNAL_SERVER_ERROR.into_response();
        }
        let retry_after = self.retry_after_header();
        let (status_u16, code, message) = self.error_payload();
        let status = axum::http::StatusCode::from_u16(status_u16)
            .unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
        let mut response = (
            status,
            axum::Json(crate::types::ErrorCodeMessageResponse { code, message }),
        )
            .into_response();
        if let Some(value) = retry_after.and_then(|value| value.parse().ok()) {
            drop(response.headers_mut().insert("x-retry-after", value));
        }
        response
    }
}

/// Convert `validator::ValidationErrors` into a standardized error response body.
///
/// Returns a 400 response with `{ "code": "VALIDATION_ERROR", "message": "[body.field] ..." }`
/// matching the TS better-auth error shape.
#[must_use]
pub fn validation_error_response(
    errors: &validator::ValidationErrors,
) -> crate::types::AuthResponse {
    // Build a TS-compatible message: "[body.field] message; [body.field2] message2"
    let messages: Vec<String> = errors
        .field_errors()
        .into_iter()
        .flat_map(|(field, errs)| {
            errs.iter().map(move |e| {
                let msg = e
                    .message
                    .as_ref()
                    .map_or_else(|| format!("Invalid value for {field}"), ToString::to_string);
                format!("[body.{field}] {msg}")
            })
        })
        .collect();
    let message = messages.join("; ");

    let body = crate::types::ErrorCodeMessageResponse {
        code: Some("VALIDATION_ERROR".to_owned()),
        message,
    };

    // Validation errors return 400 (not 422) per the TS spec
    crate::types::AuthResponse::json(400, &body)
        .unwrap_or_else(|_| crate::types::AuthResponse::text(400, "Validation failed"))
}

/// Validate a request body, returning a parsed + validated value or an error response.
///
/// # Errors
///
/// Returns an error response if the request body is missing, malformed, or fails validation.
pub fn validate_request_body<T>(
    req: &crate::types::AuthRequest,
) -> Result<T, crate::types::AuthResponse>
where
    T: serde::de::DeserializeOwned + validator::Validate + 'static,
{
    let value: T = req.body_as_json().map_err(|e| {
        let message = format!("Invalid JSON: {e}");
        let code = AuthError::code_from_message(&message);
        crate::types::AuthResponse::json(
            400,
            &crate::types::ErrorCodeMessageResponse { code, message },
        )
        .unwrap_or_else(|_| crate::types::AuthResponse::text(400, "Invalid JSON"))
    })?;

    value
        .validate()
        .map_err(|e| validation_error_response(&e))?;

    Ok(value)
}

// LCOV_EXCL_START
#[cfg(test)]
mod tests {
    use super::*;

    // ── status_code ─────────────────────────────────────────────────────

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn bad_request_is_400() {
        assert_eq!(AuthError::bad_request("oops").status_code(), 400);
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn invalid_request_is_400() {
        assert_eq!(AuthError::InvalidRequest("x".into()).status_code(), 400);
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn validation_is_400() {
        assert_eq!(AuthError::validation("x").status_code(), 400);
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn invalid_credentials_is_401() {
        assert_eq!(AuthError::InvalidCredentials.status_code(), 401);
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn unauthenticated_is_401() {
        assert_eq!(AuthError::Unauthenticated.status_code(), 401);
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn session_not_found_is_401() {
        assert_eq!(AuthError::SessionNotFound.status_code(), 401);
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn forbidden_is_403() {
        assert_eq!(AuthError::forbidden("nope").status_code(), 403);
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn unauthorized_is_403() {
        assert_eq!(AuthError::Unauthorized.status_code(), 403);
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn not_found_is_404() {
        assert_eq!(AuthError::not_found("gone").status_code(), 404);
        assert_eq!(AuthError::UserNotFound.status_code(), 404);
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn conflict_is_409() {
        assert_eq!(AuthError::conflict("dup").status_code(), 409);
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn unprocessable_entity_is_422() {
        assert_eq!(
            AuthError::UnprocessableEntity("x".into()).status_code(),
            422
        );
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn rate_limited_is_429() {
        assert_eq!(
            AuthError::RateLimited { retry_after: None }.status_code(),
            429
        );
    }

    // Application routes answer with the built-in middleware's retry header.
    #[test]
    fn rate_limited_responses_publish_retry_after() {
        for (seconds, header) in [(9.0, "9"), (2.5, "2.5")] {
            let response = AuthError::rate_limited(seconds).to_auth_response();
            assert_eq!(response.status, 429);
            assert_eq!(
                response.headers.get("X-Retry-After").map(String::as_str),
                Some(header)
            );
            #[cfg(feature = "axum")]
            {
                let response =
                    axum::response::IntoResponse::into_response(AuthError::rate_limited(seconds));
                assert_eq!(response.status(), 429);
                assert_eq!(response.headers()["x-retry-after"], header);
            }
        }
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn not_implemented_is_501() {
        assert_eq!(AuthError::not_implemented("todo").status_code(), 501);
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn internal_errors_are_500() {
        assert_eq!(AuthError::config("bad").status_code(), 500);
        assert_eq!(AuthError::internal("fail").status_code(), 500);
        assert_eq!(AuthError::plugin("p", "m").status_code(), 500);
        assert_eq!(AuthError::PasswordHash("h".into()).status_code(), 500);
        assert_eq!(
            AuthError::Database(DatabaseError::Connection("c".into())).status_code(),
            500
        );
    }

    // ── code_from_message ───────────────────────────────────────────────

    // Upstream reference: BASE_ERROR_CODES in @better-auth/core — a message
    // upstream defines a constant for carries that constant.
    #[test]
    fn code_from_message_returns_the_upstream_constant() {
        assert_eq!(
            AuthError::code_from_message("User not found").as_deref(),
            Some("USER_NOT_FOUND")
        );
    }

    // Upstream reference: packages/core/src/error/index.ts :: `APIError.from`
    // attaches a code, while `new APIError(status, { message })` does not — so
    // a message outside every upstream table has no code on the wire.
    #[test]
    fn code_from_message_is_none_for_unknown_messages() {
        assert_eq!(AuthError::code_from_message("invalid email!"), None);
        assert_eq!(AuthError::code_from_message("Email is the same"), None);
        assert_eq!(AuthError::code_from_message(""), None);
    }

    // Upstream reference: plugin tables built with `defineErrorCodes` are part
    // of the same vocabulary, not just the base set.
    #[test]
    fn code_from_message_covers_plugin_tables() {
        assert_eq!(
            AuthError::code_from_message("Username is already taken. Please try another.")
                .as_deref(),
            Some("USERNAME_IS_ALREADY_TAKEN")
        );
    }

    // Upstream reference: BASE_ERROR_CODES in @better-auth/core ::
    // packages/core/src/error/codes.ts — codes are explicit constants since
    // better-auth 1.5, so these must not be re-derived from the message.
    #[test]
    fn base_error_codes_are_not_derived_from_the_message() {
        for (message, expected) in [
            ("Invalid callbackURL", "INVALID_CALLBACK_URL"),
            ("Invalid redirectURL", "INVALID_REDIRECT_URL"),
            ("Invalid errorCallbackURL", "INVALID_ERROR_CALLBACK_URL"),
            (
                "Invalid newUserCallbackURL",
                "INVALID_NEW_USER_CALLBACK_URL",
            ),
            ("Email is already verified", "EMAIL_ALREADY_VERIFIED"),
            (
                "Verification email isn't enabled",
                "VERIFICATION_EMAIL_NOT_ENABLED",
            ),
            (
                "Session expired. Re-authenticate to perform this action.",
                "SESSION_EXPIRED",
            ),
            (
                "Cross-site navigation login blocked. This request appears to be a CSRF attack.",
                "CROSS_SITE_NAVIGATION_LOGIN_BLOCKED",
            ),
        ] {
            assert_eq!(
                AuthError::code_from_message(message).as_deref(),
                Some(expected),
                "message {message:?} must carry the upstream constant"
            );
        }
    }

    // ── error_payload ───────────────────────────────────────────────────

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn error_payload_for_client_error() {
        // Not an upstream message, so it goes out without a code.
        let (status, code, message) = AuthError::bad_request("Missing field").error_payload();
        assert_eq!(status, 400);
        assert_eq!(code, None);
        assert_eq!(message, "Missing field");

        let (status_2, code_2, message_2) =
            AuthError::bad_request("Field is required").error_payload();
        assert_eq!(status_2, 400);
        assert_eq!(code_2.as_deref(), Some("MISSING_FIELD"));
        assert_eq!(message_2, "Field is required");
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn error_payload_for_internal_error_hides_details() {
        let (status, _code, message) = AuthError::internal("secret detail").error_payload();
        assert_eq!(status, 500);
        assert_eq!(message, "Internal server error");
    }

    // ── to_auth_response ────────────────────────────────────────────────

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn to_auth_response_returns_correct_status() {
        let resp = AuthError::bad_request("oops").to_auth_response();
        assert_eq!(resp.status, 400);
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn to_auth_response_body_contains_code_and_message() {
        let resp = AuthError::UserNotFound.to_auth_response();
        assert_eq!(resp.status, 404);
        let body: serde_json::Value =
            serde_json::from_slice(&resp.body).expect("response body should be valid JSON");
        assert_eq!(
            (*(body).get("code").unwrap_or(&serde_json::Value::Null)),
            "USER_NOT_FOUND"
        );
        assert_eq!(
            (*(body).get("message").unwrap_or(&serde_json::Value::Null)),
            "User not found"
        );
    }

    // ── constructor helpers ──────────────────────────────────────────────

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn constructor_helpers_produce_correct_variants() {
        // Each helper should produce the expected Display output
        assert_eq!(AuthError::bad_request("x").to_string(), "x");
        assert_eq!(AuthError::forbidden("x").to_string(), "x");
        assert_eq!(AuthError::not_found("x").to_string(), "x");
        assert_eq!(AuthError::conflict("x").to_string(), "x");
        assert_eq!(AuthError::not_implemented("x").to_string(), "x");
        assert_eq!(AuthError::config("x").to_string(), "Configuration error: x");
        assert_eq!(
            AuthError::internal("x").to_string(),
            "Internal server error: x"
        );
        assert_eq!(
            AuthError::validation("x").to_string(),
            "Validation error: x"
        );
        assert_eq!(
            AuthError::plugin("p", "m").to_string(),
            "Plugin error: p - m"
        );
    }

    // ── DatabaseError ───────────────────────────────────────────────────

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn database_error_display() {
        let e = DatabaseError::Connection("timeout".into());
        assert_eq!(e.to_string(), "Connection error: timeout");
    }

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn database_error_converts_to_auth_error() {
        let db_err = DatabaseError::Query("bad sql".into());
        let auth_err: AuthError = db_err.into();
        assert_eq!(auth_err.status_code(), 500);
    }

    // ── validation_error_response ───────────────────────────────────────

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn validation_error_response_serializes_field_errors() {
        let mut errors = validator::ValidationErrors::new();
        let mut error = validator::ValidationError::new("email");
        error.message = Some("Email is invalid".into());
        errors.add("email", error);

        let resp = validation_error_response(&errors);
        assert_eq!(resp.status, 400);
        let body: serde_json::Value =
            serde_json::from_slice(&resp.body).expect("response body should be valid JSON");
        assert_eq!(
            (*(body).get("code").unwrap_or(&serde_json::Value::Null)),
            "VALIDATION_ERROR"
        );
        assert_eq!(
            (*(body).get("message").unwrap_or(&serde_json::Value::Null)),
            "[body.email] Email is invalid"
        );
    }

    // ── Display for fixed-message variants ──────────────────────────────

    // Rust-specific surface: `AuthError` and Rust-side response/error conversion behavior are public Rust library APIs with no direct TS analogue.
    #[test]
    fn fixed_message_variants_display() {
        assert_eq!(
            AuthError::InvalidCredentials.to_string(),
            "Invalid email or password"
        );
        assert_eq!(
            AuthError::Unauthenticated.to_string(),
            "Authentication required"
        );
        assert_eq!(
            AuthError::SessionNotFound.to_string(),
            "Session not found or expired"
        );
        assert_eq!(
            AuthError::Unauthorized.to_string(),
            "Insufficient permissions"
        );
        assert_eq!(AuthError::UserNotFound.to_string(), "User not found");
        assert_eq!(
            AuthError::RateLimited { retry_after: None }.to_string(),
            "Too many requests"
        );
    }

    // The framework-neutral response conversion is distinct from Axum's HTTP path.
    #[test]
    fn callback_failure_transport_preserves_empty_body_and_public_api_errors() {
        let response = AuthError::CallbackFailure(Box::new(AuthError::internal("private cause")))
            .to_auth_response();
        assert_eq!(response.status, 500);
        assert!(response.body.is_empty());
        assert!(response.headers.get("content-type").is_none());

        let internal = AuthError::internal("private cause").to_auth_response();
        assert_eq!(internal.status, 500);
        assert_eq!(
            serde_json::from_slice::<serde_json::Value>(&internal.body).unwrap(),
            serde_json::json!({"message":"Internal server error"})
        );
        let explicit = AuthError::Api {
            status: 500,
            code: Some("APPLICATION_ERROR".into()),
            message: "public error".into(),
        }
        .to_auth_response();
        assert_eq!(explicit.status, 500);
        assert_eq!(
            serde_json::from_slice::<serde_json::Value>(&explicit.body).unwrap(),
            serde_json::json!({"code":"APPLICATION_ERROR","message":"public error"})
        );
    }
}
// LCOV_EXCL_STOP