xurl-rs 2.1.0

A fast, ergonomic CLI for the X (Twitter) API — OAuth1/2, Bearer, media upload, streaming
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
//! Token persistence layer — multi-app YAML store at `~/.xurl`.
//!
//! Supports:
//! - Multi-app credential and token management
//! - `OAuth2`, `OAuth1`, and Bearer token types
//! - Legacy JSON migration (auto-converts old format)
//! - `.twurlrc` import (legacy Twitter CLI compatibility)
//! - Credential backfill from environment variables

mod migration;
mod tokens;
pub mod types;

use std::collections::BTreeMap;
use std::fs;
use std::path::PathBuf;

#[allow(unused_imports)] // Re-exported for library consumers and integration tests
pub use types::{App, OAuth1Token, OAuth2Token, Token, TokenType};

use crate::error::{Result, XurlError};

// ── TokenStore ───────────────────────────────────────────────────────

/// Manages authentication tokens across multiple apps.
///
/// The in-memory shape mirrors the on-disk YAML at `~/.xurl`. Library
/// consumers construct via [`TokenStore::new`] (legacy default path),
/// [`TokenStore::new_with_path`] (explicit path, no auto-import), or
/// [`TokenStore::with_credentials`] (auto-backfill).
///
/// # Example
///
/// ```rust,no_run
/// use xurl::store::TokenStore;
///
/// let store = TokenStore::new_with_path("/tmp/my-xurl-store.yaml");
/// let active = store.get_default_app();
/// if let Some(app) = store.get_app(active) {
///     println!("active app {active} has {} oauth2 users", app.oauth2_tokens.len());
/// }
/// ```
pub struct TokenStore {
    /// All registered apps, keyed by name.
    pub apps: BTreeMap<String, App>,
    /// Name of the default app selected when `--app` is not supplied.
    pub default_app: String,
    /// Path to the YAML file backing this store.
    pub file_path: PathBuf,
}

impl Default for TokenStore {
    /// Constructs a `TokenStore` from the default location, identical to
    /// calling [`TokenStore::new`].
    fn default() -> Self {
        Self::new()
    }
}

#[allow(dead_code)] // Public library API — used by consumers and integration tests
impl TokenStore {
    /// Creates a new `TokenStore`, loading from `~/.xurl` (auto-migrating legacy JSON).
    #[must_use]
    pub fn new() -> Self {
        Self::with_credentials("", "")
    }

    /// Creates a `TokenStore` and backfills the given client credentials into any
    /// app that was migrated without them.
    #[must_use]
    pub fn with_credentials(client_id: &str, client_secret: &str) -> Self {
        let home_dir = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
        let file_path = home_dir.join(".xurl");

        let mut store = TokenStore {
            apps: BTreeMap::new(),
            default_app: String::new(),
            file_path,
        };

        if let Ok(data) = fs::read(&store.file_path) {
            store.load_from_data(&data);
        }

        // Backfill credentials into any app that has tokens but no client ID/secret
        if !client_id.is_empty() || !client_secret.is_empty() {
            let mut dirty = false;
            for app in store.apps.values_mut() {
                if app.has_tokens() {
                    if app.client_id.is_empty() && !client_id.is_empty() {
                        app.client_id = client_id.to_string();
                        dirty = true;
                    }
                    if app.client_secret.is_empty() && !client_secret.is_empty() {
                        app.client_secret = client_secret.to_string();
                        dirty = true;
                    }
                }
            }
            if dirty {
                let _ = store.save_to_file();
            }
        }

        // Ensure a default app exists (matches Go: NewTokenStore always returns a usable store)
        if store.apps.is_empty() {
            store.default_app = "default".to_string();
            store.apps.insert("default".to_string(), App::new());
        }

        // Import from .twurlrc if we have no apps or the default app is missing OAuth1/Bearer
        let needs_import = match store.active_app() {
            None => true,
            Some(app) => app.oauth1_token.is_none() || app.bearer_token.is_none(),
        };
        if needs_import {
            let twurlrc_path = home_dir.join(".twurlrc");
            if twurlrc_path.exists()
                && let Err(e) = store.import_from_twurlrc(&twurlrc_path)
            {
                crate::output::warn_stderr(&format!("error importing from .twurlrc: {e}"));
            }
        }

        store
    }

    /// Creates a `TokenStore` from a specific file path (no auto-import).
    #[must_use]
    pub fn new_with_path(path: &str) -> Self {
        let file_path = PathBuf::from(path);
        let mut store = TokenStore {
            apps: BTreeMap::new(),
            default_app: String::new(),
            file_path,
        };
        if let Ok(data) = fs::read(&store.file_path) {
            store.load_from_data(&data);
        }
        if store.apps.is_empty() {
            store.apps.insert("default".to_string(), App::new());
            store.default_app = "default".to_string();
        }
        store
    }

    /// Creates a `TokenStore` from a specific file path with credential backfill.
    #[must_use]
    pub fn new_with_credentials_and_path(client_id: &str, client_secret: &str, path: &str) -> Self {
        let mut store = Self::new_with_path(path);
        if !client_id.is_empty() || !client_secret.is_empty() {
            for app in store.apps.values_mut() {
                if app.has_tokens() || app.client_id.is_empty() {
                    if app.client_id.is_empty() && !client_id.is_empty() {
                        app.client_id = client_id.to_string();
                    }
                    if app.client_secret.is_empty() && !client_secret.is_empty() {
                        app.client_secret = client_secret.to_string();
                    }
                }
            }
            let _ = store.save_to_file();
        }
        store
    }

    /// Creates a `TokenStore` using a custom home directory (for testing).
    #[must_use]
    pub fn new_with_home(home: &str) -> Self {
        let home_path = PathBuf::from(home);
        let file_path = home_path.join(".xurl");
        let mut store = TokenStore {
            apps: BTreeMap::new(),
            default_app: String::new(),
            file_path,
        };
        if let Ok(data) = fs::read(&store.file_path) {
            store.load_from_data(&data);
        }
        if store.apps.is_empty() {
            store.apps.insert("default".to_string(), App::new());
            store.default_app = "default".to_string();
        }
        // Auto-import from .twurlrc if needed
        let needs_import = match store.active_app() {
            None => true,
            Some(app) => app.oauth1_token.is_none(),
        };
        if needs_import {
            let twurlrc_path = home_path.join(".twurlrc");
            if twurlrc_path.exists() {
                let _ = store.import_from_twurlrc(&twurlrc_path);
            }
        }
        store
    }

    /// Loads a `TokenStore` from a specific file path (alias for `new_with_path`).
    #[must_use]
    pub fn load_from_path(path: &str) -> Self {
        Self::new_with_path(path)
    }

    // ── App management ───────────────────────────────────────────────

    /// Registers a new application. If it's the only app it becomes default.
    ///
    /// # Errors
    ///
    /// Returns an error if the app name already exists or the store cannot be saved.
    pub fn add_app(&mut self, name: &str, client_id: &str, client_secret: &str) -> Result<()> {
        if self.apps.contains_key(name) {
            return Err(XurlError::token_store(format!(
                "app {name:?} already exists"
            )));
        }
        self.apps.insert(
            name.to_string(),
            App::with_credentials(client_id, client_secret),
        );
        if self.apps.len() == 1 {
            self.default_app = name.to_string();
        }
        self.save_to_file()
    }

    /// Updates the credentials of an existing application.
    ///
    /// # Errors
    ///
    /// Returns an error if the app is not found or the store cannot be saved.
    pub fn update_app(&mut self, name: &str, client_id: &str, client_secret: &str) -> Result<()> {
        let app = self
            .apps
            .get_mut(name)
            .ok_or_else(|| XurlError::token_store(format!("app {name:?} not found")))?;
        if !client_id.is_empty() {
            app.client_id = client_id.to_string();
        }
        if !client_secret.is_empty() {
            app.client_secret = client_secret.to_string();
        }
        self.save_to_file()
    }

    /// Removes a registered application and its tokens.
    ///
    /// # Errors
    ///
    /// Returns an error if the app is not found or the store cannot be saved.
    pub fn remove_app(&mut self, name: &str) -> Result<()> {
        if !self.apps.contains_key(name) {
            return Err(XurlError::token_store(format!("app {name:?} not found")));
        }
        self.apps.remove(name);
        if self.default_app == name {
            self.default_app = self.apps.keys().next().cloned().unwrap_or_default();
        }
        self.save_to_file()
    }

    /// Sets the default application by name.
    ///
    /// # Errors
    ///
    /// Returns an error if the app is not found or the store cannot be saved.
    pub fn set_default_app(&mut self, name: &str) -> Result<()> {
        if !self.apps.contains_key(name) {
            return Err(XurlError::token_store(format!("app {name:?} not found")));
        }
        self.default_app = name.to_string();
        self.save_to_file()
    }

    /// Returns `true` when the currently-resolved default app holds no
    /// credentials of any kind: no `OAuth2` user tokens, no `OAuth1` token,
    /// no bearer token, and no unnamed `OAuth2` salvage token. The signal
    /// used by [`Self::promote_to_default_if_first_credentialed`] to detect
    /// the placeholder default that a fresh install starts with so the very
    /// first authenticated app can transparently take over.
    #[must_use]
    pub fn default_app_is_uninitialized(&self) -> bool {
        let app = self.resolve_app("");
        app.oauth2_tokens.is_empty()
            && app.oauth1_token.is_none()
            && app.bearer_token.is_none()
            && app.unnamed_oauth2_token.is_none()
    }

    /// Promotes `candidate_app` to the default app iff the current default
    /// is uninitialized (per [`Self::default_app_is_uninitialized`]) and
    /// `candidate_app` is registered and different from the current default.
    /// Returns the new default name when promotion happened, `None` otherwise.
    ///
    /// Idempotent: callers can invoke unconditionally after any
    /// authentication save. No-op on already-credentialed defaults, on
    /// unknown candidates, on empty candidate names, and when the candidate
    /// already IS the default.
    ///
    /// Drives the "first signed-in app becomes the default" UX so a fresh
    /// `xr auth oauth2 --app NAME` (or `oauth1`, or `auth app --bearer-token
    /// --app NAME`) does not leave the placeholder `default` ahead of NAME
    /// in the resolution chain. Users who want a different default later
    /// can still run `xr auth default <name>` explicitly; this helper only
    /// fires on the first authenticated save.
    ///
    /// # Errors
    ///
    /// Returns an error if [`Self::set_default_app`] fails to persist.
    pub fn promote_to_default_if_first_credentialed(
        &mut self,
        candidate_app: &str,
    ) -> Result<Option<String>> {
        if candidate_app.is_empty() || candidate_app == self.default_app {
            return Ok(None);
        }
        if !self.apps.contains_key(candidate_app) {
            return Ok(None);
        }
        if !self.default_app_is_uninitialized() {
            return Ok(None);
        }
        self.set_default_app(candidate_app)?;
        Ok(Some(candidate_app.to_string()))
    }

    /// Returns sorted app names.
    #[must_use]
    pub fn list_apps(&self) -> Vec<String> {
        self.apps.keys().cloned().collect()
    }

    /// Returns an app by name.
    #[must_use]
    pub fn get_app(&self, name: &str) -> Option<&App> {
        self.apps.get(name)
    }

    /// Sets the default `OAuth2` user for the named (or default) app.
    ///
    /// # Errors
    ///
    /// Returns an error if the username is not found in the app or the store cannot be saved.
    pub fn set_default_user(&mut self, app_name: &str, username: &str) -> Result<()> {
        let app = self.resolve_app_mut(app_name);
        if !app.oauth2_tokens.contains_key(username) {
            return Err(XurlError::token_store(format!(
                "user {username:?} not found in app"
            )));
        }
        app.default_user = username.to_string();
        self.save_to_file()
    }

    /// Returns the default `OAuth2` user for the named (or default) app.
    #[must_use]
    pub fn get_default_user(&self, app_name: &str) -> &str {
        let app = self.resolve_app(app_name);
        &app.default_user
    }

    /// Sets the stored `OAuth2` redirect URI for the named (or default) app.
    ///
    /// An empty `uri` clears the stored value; the next serialize omits the
    /// field thanks to `#[serde(skip_serializing_if = "String::is_empty")]`.
    /// A non-empty `uri` is validated via [`crate::config::Config::validate_redirect_uri`]
    /// before persisting; on validation failure the store is not modified.
    ///
    /// # Errors
    ///
    /// Returns an error if the URI fails validation or the store cannot be saved.
    pub fn set_app_redirect_uri(&mut self, name: &str, uri: &str) -> Result<()> {
        if !name.is_empty() && !self.apps.contains_key(name) {
            return Err(XurlError::token_store(format!("app {name:?} not found")));
        }

        if uri.is_empty() {
            let app = self.resolve_app_mut(name);
            app.redirect_uri.clear();
            return self.save_to_file();
        }

        let _ = crate::config::Config::validate_redirect_uri(uri)?;

        let app = self.resolve_app_mut(name);
        app.redirect_uri = uri.to_string();
        self.save_to_file()
    }

    /// Returns the stored `OAuth2` redirect URI for the named (or default) app.
    ///
    /// Returns `None` when the app is absent or its stored URI is empty.
    #[must_use]
    pub fn get_app_redirect_uri(&self, name: &str) -> Option<&str> {
        let app = self.resolve_app(name);
        if app.redirect_uri.is_empty() {
            None
        } else {
            Some(app.redirect_uri.as_str())
        }
    }

    /// Returns the default app name.
    #[must_use]
    pub fn get_default_app(&self) -> &str {
        &self.default_app
    }

    /// Returns the name of the active app (explicit or default).
    #[must_use]
    pub fn get_active_app_name<'a>(&'a self, explicit: &'a str) -> &'a str {
        if explicit.is_empty() {
            &self.default_app
        } else {
            explicit
        }
    }

    /// Returns the current default App, or None.
    pub(crate) fn active_app(&self) -> Option<&App> {
        self.apps.get(&self.default_app)
    }

    /// Returns the active app; creates "default" if none exist.
    pub(crate) fn active_app_or_create(&mut self) -> &mut App {
        if !self.apps.contains_key(&self.default_app) {
            self.apps.insert("default".to_string(), App::new());
            if self.default_app.is_empty() {
                self.default_app = "default".to_string();
            }
        }
        let key = if self.apps.contains_key(&self.default_app) {
            self.default_app.clone()
        } else {
            "default".to_string()
        };
        self.apps.get_mut(&key).expect("just inserted")
    }

    /// Returns the app for the given name, or the default app.
    #[must_use]
    pub fn resolve_app(&self, name: &str) -> &App {
        if !name.is_empty()
            && let Some(app) = self.apps.get(name)
        {
            return app;
        }
        // Fall back to default app, or a static empty app
        self.apps.get(&self.default_app).unwrap_or_else(|| {
            // This is a fallback — should rarely happen
            static EMPTY: std::sync::LazyLock<App> = std::sync::LazyLock::new(App::new);
            &EMPTY
        })
    }

    /// Returns the app for the given name (mutable), or the default app.
    ///
    /// # Panics
    ///
    /// Panics if the internal app map is in an inconsistent state (should never
    /// happen as `active_app_or_create` always inserts a default).
    pub fn resolve_app_mut(&mut self, name: &str) -> &mut App {
        if !name.is_empty() && self.apps.contains_key(name) {
            return self.apps.get_mut(name).expect("just checked");
        }
        self.active_app_or_create()
    }

    // ── Persistence ──────────────────────────────────────────────────

    /// Saves the token store to `~/.xurl` in YAML format.
    pub(crate) fn save_to_file(&self) -> Result<()> {
        let sf = types::StoreFile {
            apps: self.apps.clone(),
            default_app: self.default_app.clone(),
        };
        let data = serde_yaml::to_string(&sf).map_err(|e| XurlError::Json(e.to_string()))?;
        fs::write(&self.file_path, data)?;

        // Match Go's 0600 permissions
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let perms = std::fs::Permissions::from_mode(0o600);
            fs::set_permissions(&self.file_path, perms)?;
        }

        Ok(())
    }
}