turbomcp-wasm 3.0.2

WebAssembly bindings for TurboMCP - MCP client for browsers and WASI environments
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
//! Storage traits for OAuth 2.1 provider.
//!
//! This module provides pluggable storage backends for OAuth state:
//! - Authorization codes
//! - Access tokens
//! - Refresh tokens
//!
//! # Security
//!
//! Tokens are stored by hash only (never plaintext) and grant data is encrypted
//! using the token as key material. This follows the security patterns from
//! Cloudflare's workers-oauth-provider.

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, RwLock};

use serde::{Deserialize, Serialize};

/// Result type for storage operations.
pub type StorageResult<T> = Result<T, StorageError>;

/// Errors that can occur during storage operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StorageError {
    /// Item not found
    NotFound(String),
    /// Item has expired
    Expired(String),
    /// Storage backend error
    Backend(String),
    /// Serialization error
    Serialization(String),
    /// Encryption/decryption error
    Crypto(String),
}

impl std::fmt::Display for StorageError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotFound(key) => write!(f, "Not found: {}", key),
            Self::Expired(key) => write!(f, "Expired: {}", key),
            Self::Backend(msg) => write!(f, "Storage error: {}", msg),
            Self::Serialization(msg) => write!(f, "Serialization error: {}", msg),
            Self::Crypto(msg) => write!(f, "Crypto error: {}", msg),
        }
    }
}

impl std::error::Error for StorageError {}

/// Authorization code grant data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorizationCodeGrant {
    /// Client that requested authorization
    pub client_id: String,
    /// Redirect URI used in the request
    pub redirect_uri: String,
    /// Scopes granted
    pub scopes: Vec<String>,
    /// PKCE code challenge
    pub code_challenge: Option<String>,
    /// PKCE code challenge method (S256 or plain)
    pub code_challenge_method: Option<String>,
    /// User/subject identifier
    pub subject: String,
    /// Expiration timestamp (Unix seconds)
    pub expires_at: u64,
    /// Nonce for OpenID Connect
    pub nonce: Option<String>,
    /// State parameter
    pub state: Option<String>,
}

/// Access token data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessTokenData {
    /// Subject (user) the token was issued for
    pub subject: String,
    /// Client the token was issued to
    pub client_id: String,
    /// Scopes granted
    pub scopes: Vec<String>,
    /// Expiration timestamp (Unix seconds)
    pub expires_at: u64,
    /// Issue timestamp (Unix seconds)
    pub issued_at: u64,
    /// Associated refresh token hash (for revocation)
    pub refresh_token_hash: Option<String>,
}

/// Refresh token data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefreshTokenData {
    /// Subject (user) the token was issued for
    pub subject: String,
    /// Client the token was issued to
    pub client_id: String,
    /// Scopes granted
    pub scopes: Vec<String>,
    /// Expiration timestamp (Unix seconds)
    pub expires_at: u64,
    /// Issue timestamp (Unix seconds)
    pub issued_at: u64,
    /// Generation number (incremented on refresh for dual-token resilience)
    pub generation: u32,
    /// Family ID (links all tokens in a refresh chain)
    pub family_id: String,
    /// Whether this token has been used (for single-use enforcement)
    pub used: bool,
}

/// Boxed future for storage operations.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// Trait for OAuth token storage backends.
///
/// Implementations should store tokens by hash and encrypt grant data.
///
/// # Implementations
///
/// - [`MemoryTokenStore`] - In-memory storage (single-request lifetime in Workers)
/// - Future: KV-based storage for cross-request persistence
/// - Future: Durable Objects for strong consistency
pub trait TokenStore: Send + Sync + 'static {
    // =========================================================================
    // Authorization Codes
    // =========================================================================

    /// Store an authorization code.
    ///
    /// The code is stored by its hash, and grant data is encrypted.
    fn store_authorization_code(
        &self,
        code_hash: &str,
        grant: &AuthorizationCodeGrant,
    ) -> BoxFuture<'_, StorageResult<()>>;

    /// Retrieve and consume an authorization code.
    ///
    /// Returns the grant data if found and not expired, then deletes the code.
    /// This ensures single-use of authorization codes.
    fn consume_authorization_code(
        &self,
        code_hash: &str,
    ) -> BoxFuture<'_, StorageResult<AuthorizationCodeGrant>>;

    // =========================================================================
    // Access Tokens
    // =========================================================================

    /// Store access token metadata.
    ///
    /// Note: We don't need to store the full token, only metadata for introspection
    /// and revocation. JWTs are self-contained.
    fn store_access_token(
        &self,
        token_hash: &str,
        data: &AccessTokenData,
    ) -> BoxFuture<'_, StorageResult<()>>;

    /// Get access token data for introspection.
    fn get_access_token(&self, token_hash: &str) -> BoxFuture<'_, StorageResult<AccessTokenData>>;

    /// Revoke an access token.
    fn revoke_access_token(&self, token_hash: &str) -> BoxFuture<'_, StorageResult<()>>;

    // =========================================================================
    // Refresh Tokens
    // =========================================================================

    /// Store a refresh token.
    fn store_refresh_token(
        &self,
        token_hash: &str,
        data: &RefreshTokenData,
    ) -> BoxFuture<'_, StorageResult<()>>;

    /// Get refresh token data.
    fn get_refresh_token(&self, token_hash: &str)
    -> BoxFuture<'_, StorageResult<RefreshTokenData>>;

    /// Mark a refresh token as used (for single-use enforcement).
    fn mark_refresh_token_used(&self, token_hash: &str) -> BoxFuture<'_, StorageResult<()>>;

    /// Revoke a refresh token and all tokens in its family.
    fn revoke_refresh_token_family(&self, family_id: &str) -> BoxFuture<'_, StorageResult<()>>;

    // =========================================================================
    // Cleanup
    // =========================================================================

    /// Clean up expired tokens.
    ///
    /// Returns the number of tokens cleaned up.
    fn cleanup_expired(&self) -> BoxFuture<'_, StorageResult<u64>> {
        Box::pin(async { Ok(0) })
    }
}

/// In-memory token store for testing and single-request scenarios.
///
/// # ⚠️ Production Warning
///
/// **DO NOT USE IN PRODUCTION.** In Cloudflare Workers, memory is not
/// persisted across requests. Worker isolates restart approximately every
/// 15-30 minutes, causing all tokens to be lost.
///
/// This will result in:
/// - Users being logged out unexpectedly
/// - Refresh tokens becoming invalid
/// - Authorization codes being lost mid-flow
///
/// # Production Alternative
///
/// Use `DurableObjectTokenStore` with Cloudflare Durable Objects for
/// production deployments. Durable Objects provide:
/// - Strong consistency
/// - Automatic persistence
/// - Cross-request state management
///
/// # Example
///
/// ```ignore
/// // ❌ DON'T DO THIS IN PRODUCTION
/// let store = MemoryTokenStore::new();
///
/// // ✅ DO THIS INSTEAD
/// let store = DurableObjectTokenStore::new(env.durable_object("OAUTH_STORAGE")?);
/// let oauth = OAuthProvider::new(config).with_store(Arc::new(store));
/// ```
#[deprecated(
    note = "Use DurableObjectTokenStore for production. MemoryTokenStore loses all tokens \
            on Worker restart (~15-30 minutes). Only use for testing or development."
)]
#[derive(Debug, Default)]
pub struct MemoryTokenStore {
    authorization_codes: RwLock<HashMap<String, AuthorizationCodeGrant>>,
    access_tokens: RwLock<HashMap<String, AccessTokenData>>,
    refresh_tokens: RwLock<HashMap<String, RefreshTokenData>>,
}

impl MemoryTokenStore {
    /// Create a new in-memory token store.
    ///
    /// # ⚠️ Production Warning
    ///
    /// **DO NOT USE IN PRODUCTION.** This store loses all tokens when the
    /// Worker restarts (~15-30 minutes). Use `DurableObjectTokenStore` instead.
    #[allow(deprecated)]
    pub fn new() -> Self {
        // Warn users about the limitations of this store
        #[cfg(target_arch = "wasm32")]
        web_sys::console::warn_1(
            &"⚠️  Using MemoryTokenStore - tokens will be lost on Worker restart (~15-30 minutes). \
              Use DurableObjectTokenStore for production deployments."
                .into(),
        );

        Self::default()
    }

    /// Get current Unix timestamp in seconds.
    fn now_secs() -> u64 {
        (js_sys::Date::now() / 1000.0) as u64
    }
}

impl TokenStore for MemoryTokenStore {
    fn store_authorization_code(
        &self,
        code_hash: &str,
        grant: &AuthorizationCodeGrant,
    ) -> BoxFuture<'_, StorageResult<()>> {
        let code_hash = code_hash.to_string();
        let grant = grant.clone();
        Box::pin(async move {
            let mut codes = self
                .authorization_codes
                .write()
                .map_err(|e| StorageError::Backend(format!("Lock error: {}", e)))?;
            codes.insert(code_hash, grant);
            Ok(())
        })
    }

    fn consume_authorization_code(
        &self,
        code_hash: &str,
    ) -> BoxFuture<'_, StorageResult<AuthorizationCodeGrant>> {
        let code_hash = code_hash.to_string();
        Box::pin(async move {
            let mut codes = self
                .authorization_codes
                .write()
                .map_err(|e| StorageError::Backend(format!("Lock error: {}", e)))?;

            let grant = codes
                .remove(&code_hash)
                .ok_or_else(|| StorageError::NotFound(code_hash.clone()))?;

            // Check expiration
            if Self::now_secs() > grant.expires_at {
                return Err(StorageError::Expired(code_hash));
            }

            Ok(grant)
        })
    }

    fn store_access_token(
        &self,
        token_hash: &str,
        data: &AccessTokenData,
    ) -> BoxFuture<'_, StorageResult<()>> {
        let token_hash = token_hash.to_string();
        let data = data.clone();
        Box::pin(async move {
            let mut tokens = self
                .access_tokens
                .write()
                .map_err(|e| StorageError::Backend(format!("Lock error: {}", e)))?;
            tokens.insert(token_hash, data);
            Ok(())
        })
    }

    fn get_access_token(&self, token_hash: &str) -> BoxFuture<'_, StorageResult<AccessTokenData>> {
        let token_hash = token_hash.to_string();
        Box::pin(async move {
            let tokens = self
                .access_tokens
                .read()
                .map_err(|e| StorageError::Backend(format!("Lock error: {}", e)))?;

            let data = tokens
                .get(&token_hash)
                .ok_or_else(|| StorageError::NotFound(token_hash.clone()))?
                .clone();

            // Check expiration
            if Self::now_secs() > data.expires_at {
                return Err(StorageError::Expired(token_hash));
            }

            Ok(data)
        })
    }

    fn revoke_access_token(&self, token_hash: &str) -> BoxFuture<'_, StorageResult<()>> {
        let token_hash = token_hash.to_string();
        Box::pin(async move {
            let mut tokens = self
                .access_tokens
                .write()
                .map_err(|e| StorageError::Backend(format!("Lock error: {}", e)))?;
            tokens.remove(&token_hash);
            Ok(())
        })
    }

    fn store_refresh_token(
        &self,
        token_hash: &str,
        data: &RefreshTokenData,
    ) -> BoxFuture<'_, StorageResult<()>> {
        let token_hash = token_hash.to_string();
        let data = data.clone();
        Box::pin(async move {
            let mut tokens = self
                .refresh_tokens
                .write()
                .map_err(|e| StorageError::Backend(format!("Lock error: {}", e)))?;
            tokens.insert(token_hash, data);
            Ok(())
        })
    }

    fn get_refresh_token(
        &self,
        token_hash: &str,
    ) -> BoxFuture<'_, StorageResult<RefreshTokenData>> {
        let token_hash = token_hash.to_string();
        Box::pin(async move {
            let tokens = self
                .refresh_tokens
                .read()
                .map_err(|e| StorageError::Backend(format!("Lock error: {}", e)))?;

            let data = tokens
                .get(&token_hash)
                .ok_or_else(|| StorageError::NotFound(token_hash.clone()))?
                .clone();

            // Check expiration
            if Self::now_secs() > data.expires_at {
                return Err(StorageError::Expired(token_hash));
            }

            Ok(data)
        })
    }

    fn mark_refresh_token_used(&self, token_hash: &str) -> BoxFuture<'_, StorageResult<()>> {
        let token_hash = token_hash.to_string();
        Box::pin(async move {
            let mut tokens = self
                .refresh_tokens
                .write()
                .map_err(|e| StorageError::Backend(format!("Lock error: {}", e)))?;

            if let Some(data) = tokens.get_mut(&token_hash) {
                data.used = true;
            }
            Ok(())
        })
    }

    fn revoke_refresh_token_family(&self, family_id: &str) -> BoxFuture<'_, StorageResult<()>> {
        let family_id = family_id.to_string();
        Box::pin(async move {
            let mut tokens = self
                .refresh_tokens
                .write()
                .map_err(|e| StorageError::Backend(format!("Lock error: {}", e)))?;

            tokens.retain(|_, v| v.family_id != family_id);
            Ok(())
        })
    }

    fn cleanup_expired(&self) -> BoxFuture<'_, StorageResult<u64>> {
        Box::pin(async move {
            let now = Self::now_secs();
            let mut count = 0u64;

            // Clean authorization codes
            {
                let mut codes = self
                    .authorization_codes
                    .write()
                    .map_err(|e| StorageError::Backend(format!("Lock error: {}", e)))?;
                let before = codes.len();
                codes.retain(|_, v| v.expires_at > now);
                count += (before - codes.len()) as u64;
            }

            // Clean access tokens
            {
                let mut tokens = self
                    .access_tokens
                    .write()
                    .map_err(|e| StorageError::Backend(format!("Lock error: {}", e)))?;
                let before = tokens.len();
                tokens.retain(|_, v| v.expires_at > now);
                count += (before - tokens.len()) as u64;
            }

            // Clean refresh tokens
            {
                let mut tokens = self
                    .refresh_tokens
                    .write()
                    .map_err(|e| StorageError::Backend(format!("Lock error: {}", e)))?;
                let before = tokens.len();
                tokens.retain(|_, v| v.expires_at > now);
                count += (before - tokens.len()) as u64;
            }

            Ok(count)
        })
    }
}

/// Wrapper for thread-safe token store.
pub type SharedTokenStore = Arc<dyn TokenStore>;

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

    #[tokio::test]
    async fn test_memory_store_authorization_code() {
        let store = MemoryTokenStore::new();
        let now = (js_sys::Date::now() / 1000.0) as u64;

        let grant = AuthorizationCodeGrant {
            client_id: "test-client".to_string(),
            redirect_uri: "https://example.com/callback".to_string(),
            scopes: vec!["read".to_string()],
            code_challenge: Some("challenge".to_string()),
            code_challenge_method: Some("S256".to_string()),
            subject: "user123".to_string(),
            expires_at: now + 300, // 5 minutes
            nonce: None,
            state: Some("state123".to_string()),
        };

        // Store code
        store
            .store_authorization_code("code_hash_123", &grant)
            .await
            .unwrap();

        // Consume code (should succeed)
        let retrieved = store
            .consume_authorization_code("code_hash_123")
            .await
            .unwrap();
        assert_eq!(retrieved.client_id, "test-client");
        assert_eq!(retrieved.subject, "user123");

        // Consume again (should fail - single use)
        let result = store.consume_authorization_code("code_hash_123").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_memory_store_refresh_token_family_revocation() {
        let store = MemoryTokenStore::new();
        let now = (js_sys::Date::now() / 1000.0) as u64;

        // Store multiple refresh tokens in same family
        for i in 0..3 {
            let data = RefreshTokenData {
                subject: "user123".to_string(),
                client_id: "test-client".to_string(),
                scopes: vec!["read".to_string()],
                expires_at: now + 3600,
                issued_at: now,
                generation: i,
                family_id: "family-abc".to_string(),
                used: false,
            };
            store
                .store_refresh_token(&format!("token_{}", i), &data)
                .await
                .unwrap();
        }

        // Store token in different family
        let other_data = RefreshTokenData {
            subject: "user456".to_string(),
            client_id: "test-client".to_string(),
            scopes: vec!["read".to_string()],
            expires_at: now + 3600,
            issued_at: now,
            generation: 0,
            family_id: "family-xyz".to_string(),
            used: false,
        };
        store
            .store_refresh_token("token_other", &other_data)
            .await
            .unwrap();

        // Revoke family
        store
            .revoke_refresh_token_family("family-abc")
            .await
            .unwrap();

        // Tokens in family should be gone
        assert!(store.get_refresh_token("token_0").await.is_err());
        assert!(store.get_refresh_token("token_1").await.is_err());
        assert!(store.get_refresh_token("token_2").await.is_err());

        // Other family token should still exist
        assert!(store.get_refresh_token("token_other").await.is_ok());
    }
}