autoreply 0.3.5

autoreply: Model Context Protocol server for Bluesky profile and post search functionality
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
//! Credential storage with keyring and file fallback

use crate::auth::{AuthError, Credentials, Session};
use crate::error::AppError;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;

const SERVICE_NAME: &str = "autoreply-bluesky";
const DEFAULT_ACCOUNT_KEY: &str = "default_account";

/// Storage backend type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StorageBackend {
    /// OS native keyring
    Keyring,
    /// JSON file in user config directory
    File,
}

/// Stored account data
#[derive(Debug, Clone, Serialize, Deserialize)]
struct StoredAccount {
    credentials: Credentials,
    #[serde(skip_serializing_if = "Option::is_none")]
    session: Option<Session>,
}

/// File-based credential storage format
#[derive(Debug, Default, Serialize, Deserialize)]
struct FileStorage {
    accounts: std::collections::HashMap<String, StoredAccount>,
    default_account: Option<String>,
}

/// Manages credential storage
pub struct CredentialStorage {
    backend: StorageBackend,
    file_path: Option<PathBuf>,
}

impl CredentialStorage {
    /// Create a new credential storage, preferring keyring
    pub fn new() -> Result<Self, AppError> {
        // Try keyring first
        if Self::test_keyring() {
            Ok(Self {
                backend: StorageBackend::Keyring,
                file_path: None,
            })
        } else {
            // Fall back to file storage
            let file_path = Self::get_storage_file_path()?;
            Ok(Self {
                backend: StorageBackend::File,
                file_path: Some(file_path),
            })
        }
    }

    /// Test if keyring is available
    fn test_keyring() -> bool {
        let entry = keyring::Entry::new(SERVICE_NAME, "test");
        entry.is_ok()
    }

    /// Get the file storage path
    fn get_storage_file_path() -> Result<PathBuf, AppError> {
        let config_dir = dirs::config_dir()
            .ok_or_else(|| AppError::ConfigError("Could not find config directory".to_string()))?;

        let app_dir = config_dir.join("autoreply");
        fs::create_dir_all(&app_dir).map_err(|e| {
            AppError::ConfigError(format!("Failed to create config directory: {}", e))
        })?;

        Ok(app_dir.join("credentials.json"))
    }

    /// Read file storage
    fn read_file_storage(&self) -> Result<FileStorage, AppError> {
        let path = self
            .file_path
            .as_ref()
            .ok_or_else(|| AppError::ConfigError("No file path set".to_string()))?;

        if !path.exists() {
            return Ok(FileStorage::default());
        }

        let contents = fs::read_to_string(path).map_err(|e| {
            AppError::ConfigError(format!("Failed to read credentials file: {}", e))
        })?;

        serde_json::from_str(&contents)
            .map_err(|e| AppError::ConfigError(format!("Failed to parse credentials file: {}", e)))
    }

    /// Write file storage
    fn write_file_storage(&self, storage: &FileStorage) -> Result<(), AppError> {
        let path = self
            .file_path
            .as_ref()
            .ok_or_else(|| AppError::ConfigError("No file path set".to_string()))?;

        let contents = serde_json::to_string_pretty(storage).map_err(|e| {
            AppError::ConfigError(format!("Failed to serialize credentials: {}", e))
        })?;

        fs::write(path, contents).map_err(|e| {
            AppError::ConfigError(format!("Failed to write credentials file: {}", e))
        })?;

        // Set file permissions to user-only (Unix only)
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(path)
                .map_err(|e| AppError::ConfigError(format!("Failed to get file metadata: {}", e)))?
                .permissions();
            perms.set_mode(0o600);
            fs::set_permissions(path, perms).map_err(|e| {
                AppError::ConfigError(format!("Failed to set file permissions: {}", e))
            })?;
        }

        Ok(())
    }

    /// Store credentials for an account
    pub fn store_credentials(
        &self,
        handle: &str,
        credentials: Credentials,
    ) -> Result<(), AppError> {
        match self.backend {
            StorageBackend::Keyring => {
                let entry = keyring::Entry::new(SERVICE_NAME, handle).map_err(|e| {
                    AppError::ConfigError(format!("Failed to create keyring entry: {}", e))
                })?;

                let data = serde_json::to_string(&credentials).map_err(|e| {
                    AppError::ConfigError(format!("Failed to serialize credentials: {}", e))
                })?;

                entry.set_password(&data).map_err(|e| {
                    // If keyring fails, fall back to file storage
                    tracing::warn!(
                        "Keyring storage failed: {}, falling back to file storage",
                        e
                    );
                    AppError::ConfigError(format!("Platform secure storage failure: {}", e))
                })?;

                Ok(())
            }
            StorageBackend::File => {
                let mut storage = self.read_file_storage()?;
                storage.accounts.insert(
                    handle.to_string(),
                    StoredAccount {
                        credentials,
                        session: None,
                    },
                );
                self.write_file_storage(&storage)
            }
        }
    }

    /// Store credentials with automatic fallback
    pub fn store_credentials_with_fallback(
        &self,
        handle: &str,
        credentials: Credentials,
    ) -> Result<(), AppError> {
        match self.store_credentials(handle, credentials.clone()) {
            Ok(()) => Ok(()),
            Err(e) if self.backend == StorageBackend::Keyring => {
                // If keyring fails, try file storage
                tracing::warn!("Keyring failed ({}), falling back to file storage", e);
                let file_storage = Self {
                    backend: StorageBackend::File,
                    file_path: Some(Self::get_storage_file_path()?),
                };
                file_storage.store_credentials(handle, credentials)
            }
            Err(e) => Err(e),
        }
    }

    /// Retrieve credentials for an account
    pub fn get_credentials(&self, handle: &str) -> Result<Credentials, AppError> {
        match self.backend {
            StorageBackend::Keyring => {
                let entry = keyring::Entry::new(SERVICE_NAME, handle).map_err(|e| {
                    AppError::ConfigError(format!("Failed to create keyring entry: {}", e))
                })?;

                let data = entry
                    .get_password()
                    .map_err(|_| AuthError::NoCredentials(handle.to_string()))?;

                serde_json::from_str(&data).map_err(|e| {
                    AppError::ConfigError(format!("Failed to parse credentials: {}", e))
                })
            }
            StorageBackend::File => {
                let storage = self.read_file_storage()?;
                storage
                    .accounts
                    .get(handle)
                    .map(|account| account.credentials.clone())
                    .ok_or_else(|| AuthError::NoCredentials(handle.to_string()).into())
            }
        }
    }

    /// Store session for an account
    pub fn store_session(&self, handle: &str, session: Session) -> Result<(), AppError> {
        match self.backend {
            StorageBackend::Keyring => {
                // For keyring, attempt to store session; on failure, fall back to file storage
                let session_key = format!("{}_session", handle);
                let entry = keyring::Entry::new(SERVICE_NAME, &session_key).map_err(|e| {
                    AppError::ConfigError(format!("Failed to create keyring entry: {}", e))
                })?;

                let data = serde_json::to_string(&session).map_err(|e| {
                    AppError::ConfigError(format!("Failed to serialize session: {}", e))
                })?;

                match entry.set_password(&data) {
                    Ok(()) => Ok(()),
                    Err(e) => {
                        // On keyring failure, log and attempt file fallback
                        tracing::warn!(
                            "Keyring session storage failed: {}, falling back to file storage",
                            e
                        );
                        let file_storage = Self {
                            backend: StorageBackend::File,
                            file_path: Some(Self::get_storage_file_path()?),
                        };
                        file_storage.store_session(handle, session)
                    }
                }
            }
            StorageBackend::File => {
                let mut storage = self.read_file_storage()?;
                if let Some(account) = storage.accounts.get_mut(handle) {
                    account.session = Some(session);
                    self.write_file_storage(&storage)
                } else {
                    Err(AuthError::NoCredentials(handle.to_string()).into())
                }
            }
        }
    }

    /// Retrieve session for an account
    /// Will be used for token refresh when OAuth is enabled
    #[allow(dead_code)]
    pub fn get_session(&self, handle: &str) -> Result<Option<Session>, AppError> {
        match self.backend {
            StorageBackend::Keyring => {
                let session_key = format!("{}_session", handle);
                let entry = keyring::Entry::new(SERVICE_NAME, &session_key).map_err(|e| {
                    AppError::ConfigError(format!("Failed to create keyring entry: {}", e))
                })?;

                match entry.get_password() {
                    Ok(data) => {
                        let session = serde_json::from_str(&data).map_err(|e| {
                            AppError::ConfigError(format!("Failed to parse session: {}", e))
                        })?;
                        Ok(Some(session))
                    }
                    Err(_) => Ok(None),
                }
            }
            StorageBackend::File => {
                let storage = self.read_file_storage()?;
                Ok(storage
                    .accounts
                    .get(handle)
                    .and_then(|account| account.session.clone()))
            }
        }
    }

    /// Delete credentials for an account
    pub fn delete_credentials(&self, handle: &str) -> Result<(), AppError> {
        match self.backend {
            StorageBackend::Keyring => {
                let entry = keyring::Entry::new(SERVICE_NAME, handle).map_err(|e| {
                    AppError::ConfigError(format!("Failed to create keyring entry: {}", e))
                })?;

                let _ = entry.delete_password(); // Ignore errors if not found

                // Also delete session
                let session_key = format!("{}_session", handle);
                let session_entry =
                    keyring::Entry::new(SERVICE_NAME, &session_key).map_err(|e| {
                        AppError::ConfigError(format!("Failed to create keyring entry: {}", e))
                    })?;
                let _ = session_entry.delete_password();

                Ok(())
            }
            StorageBackend::File => {
                let mut storage = self.read_file_storage()?;
                storage.accounts.remove(handle);
                if storage.default_account.as_ref() == Some(&handle.to_string()) {
                    storage.default_account = None;
                }
                self.write_file_storage(&storage)
            }
        }
    }

    /// List all stored account handles
    pub fn list_accounts(&self) -> Result<Vec<String>, AppError> {
        match self.backend {
            StorageBackend::Keyring => {
                // For keyring, we need to store the list separately
                let list_entry =
                    keyring::Entry::new(SERVICE_NAME, "account_list").map_err(|e| {
                        AppError::ConfigError(format!("Failed to create keyring entry: {}", e))
                    })?;

                match list_entry.get_password() {
                    Ok(data) => serde_json::from_str(&data).map_err(|e| {
                        AppError::ConfigError(format!("Failed to parse account list: {}", e))
                    }),
                    Err(_) => Ok(vec![]),
                }
            }
            StorageBackend::File => {
                let storage = self.read_file_storage()?;
                Ok(storage.accounts.keys().cloned().collect())
            }
        }
    }

    /// Update the account list (for keyring backend)
    fn update_account_list(&self, handle: &str, add: bool) -> Result<(), AppError> {
        if self.backend != StorageBackend::Keyring {
            return Ok(());
        }

        let mut accounts = self.list_accounts()?;

        if add {
            if !accounts.contains(&handle.to_string()) {
                accounts.push(handle.to_string());
            }
        } else {
            accounts.retain(|h| h != handle);
        }

        let list_entry = keyring::Entry::new(SERVICE_NAME, "account_list")
            .map_err(|e| AppError::ConfigError(format!("Failed to create keyring entry: {}", e)))?;

        let data = serde_json::to_string(&accounts).map_err(|e| {
            AppError::ConfigError(format!("Failed to serialize account list: {}", e))
        })?;

        list_entry
            .set_password(&data)
            .map_err(|e| AppError::ConfigError(format!("Failed to store account list: {}", e)))?;

        Ok(())
    }

    /// Store credentials and update account list
    #[allow(dead_code)]
    pub fn add_account(&self, handle: &str, credentials: Credentials) -> Result<(), AppError> {
        self.store_credentials(handle, credentials)?;
        self.update_account_list(handle, true)?;
        Ok(())
    }

    /// Delete credentials and update account list
    pub fn remove_account(&self, handle: &str) -> Result<(), AppError> {
        self.delete_credentials(handle)?;
        self.update_account_list(handle, false)?;
        Ok(())
    }

    /// Get default account handle
    pub fn get_default_account(&self) -> Result<Option<String>, AppError> {
        match self.backend {
            StorageBackend::Keyring => {
                let entry =
                    keyring::Entry::new(SERVICE_NAME, DEFAULT_ACCOUNT_KEY).map_err(|e| {
                        AppError::ConfigError(format!("Failed to create keyring entry: {}", e))
                    })?;

                match entry.get_password() {
                    Ok(handle) => Ok(Some(handle)),
                    Err(_) => Ok(None),
                }
            }
            StorageBackend::File => {
                let storage = self.read_file_storage()?;
                Ok(storage.default_account)
            }
        }
    }

    /// Set default account handle
    pub fn set_default_account(&self, handle: &str) -> Result<(), AppError> {
        match self.backend {
            StorageBackend::Keyring => {
                let entry =
                    keyring::Entry::new(SERVICE_NAME, DEFAULT_ACCOUNT_KEY).map_err(|e| {
                        AppError::ConfigError(format!("Failed to create keyring entry: {}", e))
                    })?;

                match entry.set_password(handle) {
                    Ok(()) => Ok(()),
                    Err(e) => {
                        // If keyring fails, fall back to file storage
                        tracing::warn!(
                            "Keyring set_default_account failed: {}, falling back to file storage",
                            e
                        );
                        let file_storage = Self {
                            backend: StorageBackend::File,
                            file_path: Some(Self::get_storage_file_path()?),
                        };
                        let mut storage = file_storage.read_file_storage()?;
                        storage.default_account = Some(handle.to_string());
                        file_storage.write_file_storage(&storage)
                    }
                }
            }
            StorageBackend::File => {
                let mut storage = self.read_file_storage()?;
                storage.default_account = Some(handle.to_string());
                self.write_file_storage(&storage)
            }
        }
    }

    /// Get the storage backend type
    pub fn backend(&self) -> StorageBackend {
        self.backend
    }
}

impl Default for CredentialStorage {
    fn default() -> Self {
        Self::new().expect("Failed to create CredentialStorage")
    }
}

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

    #[test]
    fn test_storage_backend() {
        let storage = CredentialStorage::new().unwrap();
        // Should be either Keyring or File
        assert!(matches!(
            storage.backend(),
            StorageBackend::Keyring | StorageBackend::File
        ));
    }

    #[test]
    fn test_file_storage_path() {
        let path = CredentialStorage::get_storage_file_path().unwrap();
        assert!(path.to_string_lossy().contains("autoreply"));
        assert!(path.to_string_lossy().ends_with("credentials.json"));
    }
}