acton-service 0.21.2

Production-ready Rust backend framework with type-enforced API versioning
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
//! Refresh token storage and management
//!
//! Provides refresh token storage with rotation and reuse detection.
//! Implementations are available for Redis, PostgreSQL, and Turso.

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::error::Error;

/// Refresh token metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefreshTokenMetadata {
    /// User agent string from the request
    pub user_agent: Option<String>,

    /// Client IP address
    pub ip_address: Option<String>,

    /// Device identifier (for mobile apps)
    pub device_id: Option<String>,

    /// When the token was created
    pub created_at: DateTime<Utc>,
}

impl Default for RefreshTokenMetadata {
    fn default() -> Self {
        Self {
            user_agent: None,
            ip_address: None,
            device_id: None,
            created_at: Utc::now(),
        }
    }
}

/// Refresh token data stored in the backend
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefreshTokenData {
    /// Token ID (jti)
    pub token_id: String,

    /// User ID this token belongs to
    pub user_id: String,

    /// Token family ID for rotation tracking
    pub family_id: String,

    /// Whether this token has been revoked
    pub is_revoked: bool,

    /// When this token expires
    pub expires_at: DateTime<Utc>,

    /// Token metadata
    pub metadata: RefreshTokenMetadata,
}

/// Refresh token storage trait
///
/// Implementations of this trait provide storage for refresh tokens
/// with support for rotation and reuse detection.
#[async_trait]
pub trait RefreshTokenStorage: Send + Sync {
    /// Store a new refresh token
    async fn store(
        &self,
        token_id: &str,
        user_id: &str,
        family_id: &str,
        expires_at: DateTime<Utc>,
        metadata: &RefreshTokenMetadata,
    ) -> Result<(), Error>;

    /// Get refresh token data by token ID
    async fn get(&self, token_id: &str) -> Result<Option<RefreshTokenData>, Error>;

    /// Revoke a specific refresh token
    async fn revoke(&self, token_id: &str) -> Result<(), Error>;

    /// Revoke all tokens in a family (for reuse detection)
    async fn revoke_family(&self, family_id: &str) -> Result<u64, Error>;

    /// Revoke all tokens for a user
    async fn revoke_all_for_user(&self, user_id: &str) -> Result<u64, Error>;

    /// Rotate a token: atomically revoke old and create new
    async fn rotate(
        &self,
        old_token_id: &str,
        new_token_id: &str,
        user_id: &str,
        family_id: &str,
        expires_at: DateTime<Utc>,
        metadata: &RefreshTokenMetadata,
    ) -> Result<(), Error>;

    /// Clean up expired tokens
    async fn cleanup_expired(&self) -> Result<u64, Error>;
}

/// Redis-based refresh token storage
///
/// Uses Redis for fast token lookups with automatic TTL-based expiration.
#[cfg(feature = "cache")]
pub mod redis_storage {
    use super::*;
    use deadpool_redis::Pool;
    use redis::AsyncCommands;

    /// Redis-backed refresh token storage
    #[derive(Clone)]
    pub struct RedisRefreshStorage {
        pool: Pool,
        key_prefix: String,
    }

    impl RedisRefreshStorage {
        /// Create a new Redis refresh token storage
        pub fn new(pool: Pool) -> Self {
            Self {
                pool,
                key_prefix: "refresh_token".to_string(),
            }
        }

        /// Create with a custom key prefix
        pub fn with_prefix(pool: Pool, prefix: impl Into<String>) -> Self {
            Self {
                pool,
                key_prefix: prefix.into(),
            }
        }

        fn token_key(&self, token_id: &str) -> String {
            format!("{}:{}", self.key_prefix, token_id)
        }

        fn family_key(&self, family_id: &str) -> String {
            format!("{}:family:{}", self.key_prefix, family_id)
        }

        fn user_key(&self, user_id: &str) -> String {
            format!("{}:user:{}", self.key_prefix, user_id)
        }
    }

    #[async_trait]
    impl RefreshTokenStorage for RedisRefreshStorage {
        async fn store(
            &self,
            token_id: &str,
            user_id: &str,
            family_id: &str,
            expires_at: DateTime<Utc>,
            metadata: &RefreshTokenMetadata,
        ) -> Result<(), Error> {
            let mut conn =
                self.pool.get().await.map_err(|e| {
                    Error::Internal(format!("Failed to get Redis connection: {}", e))
                })?;

            let data = RefreshTokenData {
                token_id: token_id.to_string(),
                user_id: user_id.to_string(),
                family_id: family_id.to_string(),
                is_revoked: false,
                expires_at,
                metadata: metadata.clone(),
            };

            let json = serde_json::to_string(&data)
                .map_err(|e| Error::Internal(format!("Failed to serialize token: {}", e)))?;

            let ttl = (expires_at - Utc::now()).num_seconds().max(1) as u64;

            // Store the token data with TTL
            let token_key = self.token_key(token_id);
            conn.set_ex::<_, _, ()>(&token_key, &json, ttl)
                .await
                .map_err(|e| Error::Internal(format!("Failed to store refresh token: {}", e)))?;

            // Add to family set for batch revocation
            let family_key = self.family_key(family_id);
            conn.sadd::<_, _, ()>(&family_key, token_id)
                .await
                .map_err(|e| Error::Internal(format!("Failed to add to family set: {}", e)))?;
            conn.expire::<_, ()>(&family_key, ttl as i64)
                .await
                .map_err(|e| Error::Internal(format!("Failed to set family TTL: {}", e)))?;

            // Add to user set for user-level revocation
            let user_key = self.user_key(user_id);
            conn.sadd::<_, _, ()>(&user_key, token_id)
                .await
                .map_err(|e| Error::Internal(format!("Failed to add to user set: {}", e)))?;
            conn.expire::<_, ()>(&user_key, ttl as i64)
                .await
                .map_err(|e| Error::Internal(format!("Failed to set user TTL: {}", e)))?;

            Ok(())
        }

        async fn get(&self, token_id: &str) -> Result<Option<RefreshTokenData>, Error> {
            let mut conn =
                self.pool.get().await.map_err(|e| {
                    Error::Internal(format!("Failed to get Redis connection: {}", e))
                })?;

            let key = self.token_key(token_id);
            let json: Option<String> = conn
                .get(&key)
                .await
                .map_err(|e| Error::Internal(format!("Failed to get refresh token: {}", e)))?;

            match json {
                Some(j) => {
                    let data: RefreshTokenData = serde_json::from_str(&j)
                        .map_err(|e| Error::Internal(format!("Failed to parse token: {}", e)))?;
                    Ok(Some(data))
                }
                None => Ok(None),
            }
        }

        async fn revoke(&self, token_id: &str) -> Result<(), Error> {
            let mut conn =
                self.pool.get().await.map_err(|e| {
                    Error::Internal(format!("Failed to get Redis connection: {}", e))
                })?;

            // Get the token first to mark it as revoked
            if let Some(mut data) = self.get(token_id).await? {
                data.is_revoked = true;
                let json = serde_json::to_string(&data)
                    .map_err(|e| Error::Internal(format!("Failed to serialize token: {}", e)))?;

                let ttl = (data.expires_at - Utc::now()).num_seconds().max(1) as u64;
                let key = self.token_key(token_id);
                conn.set_ex::<_, _, ()>(&key, &json, ttl)
                    .await
                    .map_err(|e| Error::Internal(format!("Failed to revoke token: {}", e)))?;
            }

            Ok(())
        }

        async fn revoke_family(&self, family_id: &str) -> Result<u64, Error> {
            let mut conn =
                self.pool.get().await.map_err(|e| {
                    Error::Internal(format!("Failed to get Redis connection: {}", e))
                })?;

            let family_key = self.family_key(family_id);
            let token_ids: Vec<String> = conn
                .smembers(&family_key)
                .await
                .map_err(|e| Error::Internal(format!("Failed to get family members: {}", e)))?;

            let mut revoked = 0u64;
            for token_id in &token_ids {
                self.revoke(token_id).await?;
                revoked += 1;
            }

            Ok(revoked)
        }

        async fn revoke_all_for_user(&self, user_id: &str) -> Result<u64, Error> {
            let mut conn =
                self.pool.get().await.map_err(|e| {
                    Error::Internal(format!("Failed to get Redis connection: {}", e))
                })?;

            let user_key = self.user_key(user_id);
            let token_ids: Vec<String> = conn
                .smembers(&user_key)
                .await
                .map_err(|e| Error::Internal(format!("Failed to get user tokens: {}", e)))?;

            let mut revoked = 0u64;
            for token_id in &token_ids {
                self.revoke(token_id).await?;
                revoked += 1;
            }

            Ok(revoked)
        }

        async fn rotate(
            &self,
            old_token_id: &str,
            new_token_id: &str,
            user_id: &str,
            family_id: &str,
            expires_at: DateTime<Utc>,
            metadata: &RefreshTokenMetadata,
        ) -> Result<(), Error> {
            // Revoke the old token
            self.revoke(old_token_id).await?;

            // Store the new token
            self.store(new_token_id, user_id, family_id, expires_at, metadata)
                .await?;

            Ok(())
        }

        async fn cleanup_expired(&self) -> Result<u64, Error> {
            // Redis handles expiration automatically via TTL
            // This method is a no-op for Redis but required by the trait
            Ok(0)
        }
    }
}

#[cfg(feature = "cache")]
pub use redis_storage::RedisRefreshStorage;

/// PostgreSQL-based refresh token storage
#[cfg(feature = "database")]
pub mod pg_storage {
    use super::*;
    use sqlx::PgPool;

    /// PostgreSQL-backed refresh token storage
    #[derive(Clone)]
    pub struct PgRefreshStorage {
        pool: PgPool,
    }

    impl PgRefreshStorage {
        /// Create a new PostgreSQL refresh token storage
        pub fn new(pool: PgPool) -> Self {
            Self { pool }
        }
    }

    #[async_trait]
    impl RefreshTokenStorage for PgRefreshStorage {
        async fn store(
            &self,
            token_id: &str,
            user_id: &str,
            family_id: &str,
            expires_at: DateTime<Utc>,
            metadata: &RefreshTokenMetadata,
        ) -> Result<(), Error> {
            let metadata_json = serde_json::to_value(metadata)
                .map_err(|e| Error::Internal(format!("Failed to serialize metadata: {}", e)))?;

            sqlx::query(
                r#"
                INSERT INTO refresh_tokens (id, user_id, family_id, expires_at, metadata, is_revoked)
                VALUES ($1, $2, $3, $4, $5, false)
                "#,
            )
            .bind(token_id)
            .bind(user_id)
            .bind(family_id)
            .bind(expires_at)
            .bind(metadata_json)
            .execute(&self.pool)
            .await
            .map_err(|e| Error::Internal(format!("Failed to store refresh token: {}", e)))?;

            Ok(())
        }

        async fn get(&self, token_id: &str) -> Result<Option<RefreshTokenData>, Error> {
            let row = sqlx::query_as::<
                _,
                (
                    String,
                    String,
                    String,
                    bool,
                    DateTime<Utc>,
                    serde_json::Value,
                ),
            >(
                r#"
                SELECT id, user_id, family_id, is_revoked, expires_at, metadata
                FROM refresh_tokens
                WHERE id = $1 AND expires_at > NOW()
                "#,
            )
            .bind(token_id)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| Error::Internal(format!("Failed to get refresh token: {}", e)))?;

            match row {
                Some((id, user_id, family_id, is_revoked, expires_at, metadata_json)) => {
                    let metadata: RefreshTokenMetadata =
                        serde_json::from_value(metadata_json).unwrap_or_default();
                    Ok(Some(RefreshTokenData {
                        token_id: id,
                        user_id,
                        family_id,
                        is_revoked,
                        expires_at,
                        metadata,
                    }))
                }
                None => Ok(None),
            }
        }

        async fn revoke(&self, token_id: &str) -> Result<(), Error> {
            sqlx::query("UPDATE refresh_tokens SET is_revoked = true WHERE id = $1")
                .bind(token_id)
                .execute(&self.pool)
                .await
                .map_err(|e| Error::Internal(format!("Failed to revoke token: {}", e)))?;

            Ok(())
        }

        async fn revoke_family(&self, family_id: &str) -> Result<u64, Error> {
            let result =
                sqlx::query("UPDATE refresh_tokens SET is_revoked = true WHERE family_id = $1")
                    .bind(family_id)
                    .execute(&self.pool)
                    .await
                    .map_err(|e| Error::Internal(format!("Failed to revoke family: {}", e)))?;

            Ok(result.rows_affected())
        }

        async fn revoke_all_for_user(&self, user_id: &str) -> Result<u64, Error> {
            let result =
                sqlx::query("UPDATE refresh_tokens SET is_revoked = true WHERE user_id = $1")
                    .bind(user_id)
                    .execute(&self.pool)
                    .await
                    .map_err(|e| Error::Internal(format!("Failed to revoke user tokens: {}", e)))?;

            Ok(result.rows_affected())
        }

        async fn rotate(
            &self,
            old_token_id: &str,
            new_token_id: &str,
            user_id: &str,
            family_id: &str,
            expires_at: DateTime<Utc>,
            metadata: &RefreshTokenMetadata,
        ) -> Result<(), Error> {
            // Use a transaction for atomic rotation
            let mut tx = self
                .pool
                .begin()
                .await
                .map_err(|e| Error::Internal(format!("Failed to begin transaction: {}", e)))?;

            // Revoke old token
            sqlx::query("UPDATE refresh_tokens SET is_revoked = true WHERE id = $1")
                .bind(old_token_id)
                .execute(&mut *tx)
                .await
                .map_err(|e| Error::Internal(format!("Failed to revoke old token: {}", e)))?;

            // Insert new token
            let metadata_json = serde_json::to_value(metadata)
                .map_err(|e| Error::Internal(format!("Failed to serialize metadata: {}", e)))?;

            sqlx::query(
                r#"
                INSERT INTO refresh_tokens (id, user_id, family_id, expires_at, metadata, is_revoked)
                VALUES ($1, $2, $3, $4, $5, false)
                "#,
            )
            .bind(new_token_id)
            .bind(user_id)
            .bind(family_id)
            .bind(expires_at)
            .bind(metadata_json)
            .execute(&mut *tx)
            .await
            .map_err(|e| Error::Internal(format!("Failed to store new token: {}", e)))?;

            tx.commit()
                .await
                .map_err(|e| Error::Internal(format!("Failed to commit transaction: {}", e)))?;

            Ok(())
        }

        async fn cleanup_expired(&self) -> Result<u64, Error> {
            let result = sqlx::query("DELETE FROM refresh_tokens WHERE expires_at < NOW()")
                .execute(&self.pool)
                .await
                .map_err(|e| Error::Internal(format!("Failed to cleanup expired tokens: {}", e)))?;

            Ok(result.rows_affected())
        }
    }
}

#[cfg(feature = "database")]
pub use pg_storage::PgRefreshStorage;

/// Turso/libsql-based refresh token storage
#[cfg(feature = "turso")]
pub mod turso_storage {
    use super::*;
    use libsql::Connection;
    use std::sync::Arc;

    /// Turso-backed refresh token storage
    #[derive(Clone)]
    pub struct TursoRefreshStorage {
        conn: Arc<Connection>,
    }

    impl TursoRefreshStorage {
        /// Create a new Turso refresh token storage
        pub fn new(conn: Arc<Connection>) -> Self {
            Self { conn }
        }
    }

    #[async_trait]
    impl RefreshTokenStorage for TursoRefreshStorage {
        async fn store(
            &self,
            token_id: &str,
            user_id: &str,
            family_id: &str,
            expires_at: DateTime<Utc>,
            metadata: &RefreshTokenMetadata,
        ) -> Result<(), Error> {
            let metadata_json = serde_json::to_string(metadata)
                .map_err(|e| Error::Internal(format!("Failed to serialize metadata: {}", e)))?;

            self.conn
                .execute(
                    "INSERT INTO refresh_tokens (id, user_id, family_id, expires_at, metadata, is_revoked) VALUES (?1, ?2, ?3, ?4, ?5, 0)",
                    libsql::params![token_id, user_id, family_id, expires_at.to_rfc3339(), metadata_json],
                )
                .await
                .map_err(|e| Error::Internal(format!("Failed to store refresh token: {}", e)))?;

            Ok(())
        }

        async fn get(&self, token_id: &str) -> Result<Option<RefreshTokenData>, Error> {
            let mut rows = self
                .conn
                .query(
                    "SELECT id, user_id, family_id, is_revoked, expires_at, metadata FROM refresh_tokens WHERE id = ?1 AND expires_at > datetime('now')",
                    libsql::params![token_id],
                )
                .await
                .map_err(|e| Error::Internal(format!("Failed to get refresh token: {}", e)))?;

            if let Some(row) = rows
                .next()
                .await
                .map_err(|e| Error::Internal(format!("Failed to fetch row: {}", e)))?
            {
                let id: String = row
                    .get(0)
                    .map_err(|e| Error::Internal(format!("Failed to get id: {}", e)))?;
                let user_id: String = row
                    .get(1)
                    .map_err(|e| Error::Internal(format!("Failed to get user_id: {}", e)))?;
                let family_id: String = row
                    .get(2)
                    .map_err(|e| Error::Internal(format!("Failed to get family_id: {}", e)))?;
                let is_revoked: i64 = row
                    .get(3)
                    .map_err(|e| Error::Internal(format!("Failed to get is_revoked: {}", e)))?;
                let expires_at_str: String = row
                    .get(4)
                    .map_err(|e| Error::Internal(format!("Failed to get expires_at: {}", e)))?;
                let metadata_str: String = row
                    .get(5)
                    .map_err(|e| Error::Internal(format!("Failed to get metadata: {}", e)))?;

                let expires_at = DateTime::parse_from_rfc3339(&expires_at_str)
                    .map(|dt| dt.with_timezone(&Utc))
                    .unwrap_or_else(|_| Utc::now());

                let metadata: RefreshTokenMetadata =
                    serde_json::from_str(&metadata_str).unwrap_or_default();

                Ok(Some(RefreshTokenData {
                    token_id: id,
                    user_id,
                    family_id,
                    is_revoked: is_revoked != 0,
                    expires_at,
                    metadata,
                }))
            } else {
                Ok(None)
            }
        }

        async fn revoke(&self, token_id: &str) -> Result<(), Error> {
            self.conn
                .execute(
                    "UPDATE refresh_tokens SET is_revoked = 1 WHERE id = ?1",
                    libsql::params![token_id],
                )
                .await
                .map_err(|e| Error::Internal(format!("Failed to revoke token: {}", e)))?;

            Ok(())
        }

        async fn revoke_family(&self, family_id: &str) -> Result<u64, Error> {
            let rows = self
                .conn
                .execute(
                    "UPDATE refresh_tokens SET is_revoked = 1 WHERE family_id = ?1",
                    libsql::params![family_id],
                )
                .await
                .map_err(|e| Error::Internal(format!("Failed to revoke family: {}", e)))?;

            Ok(rows)
        }

        async fn revoke_all_for_user(&self, user_id: &str) -> Result<u64, Error> {
            let rows = self
                .conn
                .execute(
                    "UPDATE refresh_tokens SET is_revoked = 1 WHERE user_id = ?1",
                    libsql::params![user_id],
                )
                .await
                .map_err(|e| Error::Internal(format!("Failed to revoke user tokens: {}", e)))?;

            Ok(rows)
        }

        async fn rotate(
            &self,
            old_token_id: &str,
            new_token_id: &str,
            user_id: &str,
            family_id: &str,
            expires_at: DateTime<Utc>,
            metadata: &RefreshTokenMetadata,
        ) -> Result<(), Error> {
            // Turso doesn't support transactions in the same way, so we do sequential ops
            self.revoke(old_token_id).await?;
            self.store(new_token_id, user_id, family_id, expires_at, metadata)
                .await?;

            Ok(())
        }

        async fn cleanup_expired(&self) -> Result<u64, Error> {
            let rows = self
                .conn
                .execute(
                    "DELETE FROM refresh_tokens WHERE expires_at < datetime('now')",
                    (),
                )
                .await
                .map_err(|e| Error::Internal(format!("Failed to cleanup expired tokens: {}", e)))?;

            Ok(rows)
        }
    }
}

#[cfg(feature = "turso")]
pub use turso_storage::TursoRefreshStorage;

/// SurrealDB-based refresh token storage
#[cfg(feature = "surrealdb")]
pub mod surrealdb_storage {
    use super::*;
    use crate::surrealdb_backend::SurrealClient;
    use std::sync::Arc;

    /// SurrealDB-backed refresh token storage
    #[derive(Clone)]
    pub struct SurrealDbRefreshStorage {
        client: Arc<SurrealClient>,
    }

    impl SurrealDbRefreshStorage {
        /// Create a new SurrealDB refresh token storage
        pub fn new(client: Arc<SurrealClient>) -> Self {
            Self { client }
        }
    }

    #[async_trait]
    impl RefreshTokenStorage for SurrealDbRefreshStorage {
        async fn store(
            &self,
            token_id: &str,
            user_id: &str,
            family_id: &str,
            expires_at: DateTime<Utc>,
            metadata: &RefreshTokenMetadata,
        ) -> Result<(), Error> {
            let data = RefreshTokenData {
                token_id: token_id.to_string(),
                user_id: user_id.to_string(),
                family_id: family_id.to_string(),
                is_revoked: false,
                expires_at,
                metadata: metadata.clone(),
            };

            self.client
                .query("CREATE refresh_tokens CONTENT $data")
                .bind(("data", data))
                .await
                .map_err(|e| Error::Internal(format!("Failed to store refresh token: {}", e)))?;

            Ok(())
        }

        async fn get(&self, token_id: &str) -> Result<Option<RefreshTokenData>, Error> {
            let mut result = self.client
                .query("SELECT * FROM refresh_tokens WHERE token_id = $token_id AND expires_at > time::now() LIMIT 1")
                .bind(("token_id", token_id.to_string()))
                .await
                .map_err(|e| Error::Internal(format!("Failed to get refresh token: {}", e)))?;

            let data: Option<RefreshTokenData> = result
                .take(0)
                .map_err(|e| Error::Internal(format!("Failed to parse refresh token: {}", e)))?;

            Ok(data)
        }

        async fn revoke(&self, token_id: &str) -> Result<(), Error> {
            self.client
                .query("UPDATE refresh_tokens SET is_revoked = true WHERE token_id = $token_id")
                .bind(("token_id", token_id.to_string()))
                .await
                .map_err(|e| Error::Internal(format!("Failed to revoke token: {}", e)))?;

            Ok(())
        }

        async fn revoke_family(&self, family_id: &str) -> Result<u64, Error> {
            let mut result = self
                .client
                .query("UPDATE refresh_tokens SET is_revoked = true WHERE family_id = $family_id")
                .bind(("family_id", family_id.to_string()))
                .await
                .map_err(|e| Error::Internal(format!("Failed to revoke family: {}", e)))?;

            // SurrealDB returns updated records; count them
            let updated: Vec<RefreshTokenData> = result.take(0).unwrap_or_default();
            Ok(updated.len() as u64)
        }

        async fn revoke_all_for_user(&self, user_id: &str) -> Result<u64, Error> {
            let mut result = self
                .client
                .query("UPDATE refresh_tokens SET is_revoked = true WHERE user_id = $user_id")
                .bind(("user_id", user_id.to_string()))
                .await
                .map_err(|e| Error::Internal(format!("Failed to revoke user tokens: {}", e)))?;

            let updated: Vec<RefreshTokenData> = result.take(0).unwrap_or_default();
            Ok(updated.len() as u64)
        }

        async fn rotate(
            &self,
            old_token_id: &str,
            new_token_id: &str,
            user_id: &str,
            family_id: &str,
            expires_at: DateTime<Utc>,
            metadata: &RefreshTokenMetadata,
        ) -> Result<(), Error> {
            // Revoke old and create new
            self.revoke(old_token_id).await?;
            self.store(new_token_id, user_id, family_id, expires_at, metadata)
                .await?;

            Ok(())
        }

        async fn cleanup_expired(&self) -> Result<u64, Error> {
            let mut result = self
                .client
                .query("DELETE FROM refresh_tokens WHERE expires_at < time::now()")
                .await
                .map_err(|e| Error::Internal(format!("Failed to cleanup expired tokens: {}", e)))?;

            let deleted: Vec<RefreshTokenData> = result.take(0).unwrap_or_default();
            Ok(deleted.len() as u64)
        }
    }
}

#[cfg(feature = "surrealdb")]
pub use surrealdb_storage::SurrealDbRefreshStorage;

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

    #[test]
    fn test_refresh_token_metadata_default() {
        let metadata = RefreshTokenMetadata::default();
        assert!(metadata.user_agent.is_none());
        assert!(metadata.ip_address.is_none());
        assert!(metadata.device_id.is_none());
    }

    #[test]
    fn test_refresh_token_data_serialization() {
        let data = RefreshTokenData {
            token_id: "token123".to_string(),
            user_id: "user456".to_string(),
            family_id: "family789".to_string(),
            is_revoked: false,
            expires_at: Utc::now(),
            metadata: RefreshTokenMetadata::default(),
        };

        let json = serde_json::to_string(&data).expect("Failed to serialize");
        let deserialized: RefreshTokenData =
            serde_json::from_str(&json).expect("Failed to deserialize");

        assert_eq!(data.token_id, deserialized.token_id);
        assert_eq!(data.user_id, deserialized.user_id);
        assert_eq!(data.family_id, deserialized.family_id);
        assert_eq!(data.is_revoked, deserialized.is_revoked);
    }
}