Skip to main content

fetchium_core/ai/
credentials.rs

1//! Subscription-based credential detection for AI providers.
2//!
3//! Reads OAuth tokens that have already been set up by first-party CLIs:
4//! - **Gemini**: reads `~/.gemini/oauth_creds.json` (populated by `gemini auth login`)
5//! - **Claude Code**: reads from macOS Keychain service `"Claude Code-credentials"`
6//! - **OpenAI Codex**: reads `~/.codex/auth.json` (populated by `codex auth login`)
7//! - **OpenCode Antigravity**: reads `~/.config/opencode/antigravity-accounts.json`
8//!   (populated by the `opencode-antigravity-auth` plugin; grants access to Gemini 3
9//!   and Claude Sonnet/Opus models via Google Cloud Code Assist for free)
10//!
11//! No browser flows are initiated here — this module only reads existing credentials.
12
13use serde::{Deserialize, Serialize};
14
15// ─── Gemini OAuth credentials ─────────────────────────────────────────────────
16
17/// Google OAuth credentials stored by the Gemini CLI at `~/.gemini/oauth_creds.json`.
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct GeminiOAuthCreds {
20    /// Current access token (short-lived, ~1 hour).
21    pub access_token: String,
22    /// Long-lived refresh token.
23    pub refresh_token: String,
24    /// Expiry as Unix timestamp in **milliseconds**.
25    pub expiry_date: u64,
26    /// Always `"Bearer"`.
27    pub token_type: String,
28}
29
30impl GeminiOAuthCreds {
31    /// True if the access token has not yet expired.
32    pub fn is_valid(&self) -> bool {
33        let now_ms = std::time::SystemTime::now()
34            .duration_since(std::time::UNIX_EPOCH)
35            .map(|d| d.as_millis() as u64)
36            .unwrap_or(0);
37        // Allow 60-second grace period
38        self.expiry_date > now_ms + 60_000
39    }
40
41    /// True if a non-empty refresh token is present (can attempt a token refresh).
42    ///
43    /// Returns `false` after [`invalidate_gemini_creds`] has been called, indicating
44    /// the session is permanently dead and the user must re-authenticate.
45    pub fn is_refreshable(&self) -> bool {
46        !self.refresh_token.is_empty()
47    }
48}
49
50/// Zero-out the Gemini OAuth credentials in `~/.gemini/oauth_creds.json`.
51///
52/// Called when a token-refresh attempt returns HTTP 401 (refresh token revoked).
53/// After this, [`read_gemini_creds`] returns a struct where `is_refreshable()` is
54/// `false`, so `check_provider` correctly reports Gemini as unavailable.
55pub fn invalidate_gemini_creds() {
56    if let Some(path) = dirs::home_dir().map(|h| h.join(".gemini").join("oauth_creds.json")) {
57        let cleared = serde_json::json!({
58            "access_token":  "",
59            "refresh_token": "",
60            "expiry_date":   0u64,
61            "token_type":    "Bearer",
62        });
63        let _ = std::fs::write(
64            &path,
65            serde_json::to_string_pretty(&cleared).unwrap_or_default(),
66        );
67    }
68}
69
70/// Read Gemini CLI OAuth credentials from `~/.gemini/oauth_creds.json`.
71///
72/// Returns `None` if the file does not exist or cannot be parsed.
73pub fn read_gemini_creds() -> Option<GeminiOAuthCreds> {
74    let path = dirs::home_dir()?.join(".gemini").join("oauth_creds.json");
75    let content = std::fs::read_to_string(path).ok()?;
76    serde_json::from_str(&content).ok()
77}
78
79/// Return a valid access token if one is cached locally, or `None` if expired/absent.
80///
81/// Call [`refresh_gemini_token`] (async) when this returns `None` due to expiry.
82pub fn get_gemini_access_token_if_valid() -> Option<String> {
83    let creds = read_gemini_creds()?;
84    if creds.is_valid() {
85        Some(creds.access_token.clone())
86    } else {
87        tracing::debug!("Gemini OAuth token expired — refresh needed");
88        None
89    }
90}
91
92/// Google's public OAuth client ID baked into the Gemini CLI package.
93/// This is a "native app" / "installed app" OAuth client — the client_secret
94/// is **not secret** for this client type.
95pub const GEMINI_OAUTH_CLIENT_ID: &str =
96    "681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com";
97/// Public client secret for the Gemini CLI's installed-app OAuth client.
98pub const GEMINI_OAUTH_CLIENT_SECRET: &str = "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";
99/// Google OAuth token endpoint.
100pub const GOOGLE_TOKEN_ENDPOINT: &str = "https://oauth2.googleapis.com/token";
101
102// ─── Claude Code (Anthropic) OAuth credentials ───────────────────────────────
103
104/// Claude Code OAuth credentials stored in the macOS Keychain.
105#[derive(Debug, Clone)]
106pub struct ClaudeOAuthCreds {
107    /// OAuth access token for the Anthropic API (`sk-ant-oat01-...`).
108    pub access_token: String,
109    /// Refresh token (`sk-ant-ort01-...`).
110    pub refresh_token: String,
111    /// Token expiry as Unix timestamp in milliseconds.
112    pub expires_at: u64,
113    /// Subscription tier (e.g. `"max"`, `"pro"`).
114    pub subscription_type: String,
115}
116
117impl ClaudeOAuthCreds {
118    /// True if the access token has not yet expired.
119    pub fn is_valid(&self) -> bool {
120        let now_ms = std::time::SystemTime::now()
121            .duration_since(std::time::UNIX_EPOCH)
122            .map(|d| d.as_millis() as u64)
123            .unwrap_or(0);
124        self.expires_at > now_ms + 60_000
125    }
126}
127
128/// Read Claude Code OAuth credentials from the macOS Keychain.
129///
130/// Claude Code stores its session under service `"Claude Code-credentials"`.
131/// Returns `None` on non-macOS systems or if credentials are not present.
132pub fn read_claude_code_creds() -> Option<ClaudeOAuthCreds> {
133    #[cfg(target_os = "macos")]
134    {
135        // Use the macOS `security` CLI to read from Keychain without extra deps.
136        let output = std::process::Command::new("security")
137            .args([
138                "find-generic-password",
139                "-s",
140                "Claude Code-credentials",
141                "-w",
142            ])
143            .output()
144            .ok()?;
145
146        if !output.status.success() {
147            return None;
148        }
149
150        let raw = String::from_utf8(output.stdout).ok()?;
151        let json: serde_json::Value = serde_json::from_str(raw.trim()).ok()?;
152        let oauth = json.get("claudeAiOauth")?;
153
154        let access_token = oauth.get("accessToken")?.as_str()?.to_string();
155        let refresh_token = oauth.get("refreshToken")?.as_str()?.to_string();
156        let expires_at = oauth.get("expiresAt")?.as_u64().unwrap_or(0);
157        let subscription = oauth
158            .get("subscriptionType")
159            .and_then(|s| s.as_str())
160            .unwrap_or("unknown")
161            .to_string();
162
163        Some(ClaudeOAuthCreds {
164            access_token,
165            refresh_token,
166            expires_at,
167            subscription_type: subscription,
168        })
169    }
170
171    #[cfg(not(target_os = "macos"))]
172    {
173        // On Linux/Windows, check for a credentials file that users can create manually.
174        let path = dirs::home_dir()?.join(".claude").join("credentials.json");
175        let content = std::fs::read_to_string(path).ok()?;
176        let json: serde_json::Value = serde_json::from_str(&content).ok()?;
177        let oauth = json.get("claudeAiOauth")?;
178
179        let access_token = oauth.get("accessToken")?.as_str()?.to_string();
180        let refresh_token = oauth.get("refreshToken")?.as_str()?.to_string();
181        let expires_at = oauth.get("expiresAt")?.as_u64().unwrap_or(0);
182        let subscription = oauth
183            .get("subscriptionType")
184            .and_then(|s| s.as_str())
185            .unwrap_or("unknown")
186            .to_string();
187
188        Some(ClaudeOAuthCreds {
189            access_token,
190            refresh_token,
191            expires_at,
192            subscription_type: subscription,
193        })
194    }
195}
196
197/// Get a usable Anthropic access token from Claude Code's session.
198///
199/// Returns `None` if Claude Code is not installed or the session has expired.
200pub fn get_claude_code_token() -> Option<ClaudeOAuthCreds> {
201    let creds = read_claude_code_creds()?;
202    if creds.is_valid() {
203        return Some(creds);
204    }
205    // Token expired — refreshing Anthropic OAuth requires hitting their
206    // token endpoint which may change. For now, instruct user to re-run Claude Code.
207    tracing::warn!(
208        "Claude Code OAuth token has expired. Re-run `claude` once to refresh it, then retry."
209    );
210    None
211}
212
213// ─── Detection helpers ────────────────────────────────────────────────────────
214
215/// Returns `true` if Gemini CLI is installed and has OAuth credentials.
216pub fn gemini_cli_auth_available() -> bool {
217    // Check gemini binary exists
218    let has_binary = std::process::Command::new("gemini")
219        .arg("--version")
220        .output()
221        .map(|o| o.status.success())
222        .unwrap_or(false);
223
224    has_binary && read_gemini_creds().is_some()
225}
226
227/// Returns `true` if Claude Code OAuth credentials are available.
228pub fn claude_code_auth_available() -> bool {
229    read_claude_code_creds().is_some()
230}
231
232// ─── OpenAI Codex CLI credentials ────────────────────────────────────────────
233
234/// OpenAI Codex CLI OAuth credentials stored at `~/.codex/auth.json`.
235///
236/// Populated by `codex auth login` (ChatGPT sign-in flow).
237#[derive(Debug, Clone, Serialize, Deserialize)]
238pub struct CodexOAuthCreds {
239    /// Short-lived access token (JWT, used as `Authorization: Bearer`).
240    pub access_token: String,
241    /// Refresh token for obtaining a new access token.
242    pub refresh_token: Option<String>,
243    /// Expiry as ISO 8601 / RFC 3339 string (e.g. `"2025-04-01T10:30:00Z"`).
244    pub expires_at: Option<String>,
245}
246
247impl CodexOAuthCreds {
248    /// True if the access token has not yet expired (or expiry is unknown).
249    pub fn is_valid(&self) -> bool {
250        let Some(ref exp_str) = self.expires_at else {
251            return true; // no expiry field → assume valid
252        };
253        // Parse as RFC 3339; if parsing fails also assume valid
254        let Ok(exp) = chrono::DateTime::parse_from_rfc3339(exp_str) else {
255            return true;
256        };
257        let now = chrono::Utc::now();
258        exp.signed_duration_since(now).num_seconds() > 60
259    }
260}
261
262/// Read OpenAI Codex CLI credentials from `~/.codex/auth.json`.
263///
264/// Returns `None` if the file does not exist, cannot be read, or cannot be parsed.
265pub fn read_codex_creds() -> Option<CodexOAuthCreds> {
266    let path = dirs::home_dir()?.join(".codex").join("auth.json");
267    let content = std::fs::read_to_string(path).ok()?;
268    serde_json::from_str(&content).ok()
269}
270
271/// Return a valid OpenAI Codex access token, or `None` if absent/expired.
272pub fn get_codex_token_if_valid() -> Option<String> {
273    let creds = read_codex_creds()?;
274    if creds.is_valid() {
275        Some(creds.access_token.clone())
276    } else {
277        tracing::debug!("OpenAI Codex token expired — re-run `codex auth login` to refresh");
278        None
279    }
280}
281
282/// Returns `true` if OpenAI Codex CLI credentials are present and valid.
283pub fn codex_auth_available() -> bool {
284    get_codex_token_if_valid().is_some()
285}
286
287// ─── OpenRouter ───────────────────────────────────────────────────────────────
288
289/// Read OpenRouter API key from its config file at `~/.openrouter/config.json`.
290///
291/// OpenRouter stores credentials in a simple JSON file after `openrouter auth`.
292pub fn read_openrouter_key() -> Option<String> {
293    let path = dirs::home_dir()?.join(".openrouter").join("config.json");
294    let content = std::fs::read_to_string(path).ok()?;
295    let json: serde_json::Value = serde_json::from_str(&content).ok()?;
296    json.get("api_key")
297        .or_else(|| json.get("apiKey"))
298        .or_else(|| json.get("key"))
299        .and_then(|v| v.as_str())
300        .map(|s| s.to_string())
301}
302
303// ─── OpenCode Antigravity OAuth credentials ───────────────────────────────────
304//
305// The `opencode-antigravity-auth` plugin stores Google OAuth credentials at
306// `~/.config/opencode/antigravity-accounts.json`. These credentials grant access
307// to Google Cloud Code Assist, which proxies requests to Gemini 3 and Claude models.
308//
309// OAuth application (public installed-app client — secret is not sensitive):
310//   Client ID:     1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com
311//   Client secret: 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
312//
313// API endpoints (primary → autopush → prod fallback order):
314//   https://daily-cloudcode-pa.sandbox.googleapis.com/v1internal:generateContent
315//   https://autopush-cloudcode-pa.sandbox.googleapis.com/v1internal:generateContent
316//   https://cloudcode-pa.googleapis.com/v1internal:generateContent
317
318/// OAuth client ID for the OpenCode Antigravity plugin (installed-app, public).
319pub const ANTIGRAVITY_CLIENT_ID: &str =
320    "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
321/// Public client secret for the Antigravity installed-app OAuth client.
322pub const ANTIGRAVITY_CLIENT_SECRET: &str = "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";
323
324/// Primary Cloud Code Assist API endpoint (daily sandbox, mirrors CLIProxy behaviour).
325pub const ANTIGRAVITY_ENDPOINT: &str = "https://daily-cloudcode-pa.sandbox.googleapis.com";
326/// Fallback autopush endpoint.
327pub const ANTIGRAVITY_ENDPOINT_AUTOPUSH: &str =
328    "https://autopush-cloudcode-pa.sandbox.googleapis.com";
329/// Fallback production endpoint.
330pub const ANTIGRAVITY_ENDPOINT_PROD: &str = "https://cloudcode-pa.googleapis.com";
331
332/// Ordered list of Cloud Code Assist endpoints to try (first success wins).
333pub const ANTIGRAVITY_ENDPOINTS: &[&str] = &[
334    ANTIGRAVITY_ENDPOINT,
335    ANTIGRAVITY_ENDPOINT_AUTOPUSH,
336    ANTIGRAVITY_ENDPOINT_PROD,
337];
338
339/// Default fallback project ID when the account has none.
340pub const ANTIGRAVITY_DEFAULT_PROJECT_ID: &str = "rising-fact-p41fc";
341
342/// Antigravity plugin version string (must stay in sync with the installed plugin).
343pub const ANTIGRAVITY_VERSION: &str = "1.15.8";
344
345/// A single account entry stored in `antigravity-accounts.json`.
346#[derive(Debug, Clone, Serialize, Deserialize)]
347#[serde(rename_all = "camelCase")]
348pub struct AntigravityAccount {
349    /// Google account email address.
350    pub email: String,
351    /// Google OAuth refresh token (long-lived).
352    pub refresh_token: String,
353    /// Google Cloud project ID for quota routing.
354    #[serde(default)]
355    pub project_id: Option<String>,
356    /// Timestamp when this account was added (string ISO 8601 or integer epoch ms).
357    #[serde(default)]
358    pub added_at: Option<serde_json::Value>,
359    /// Timestamp when this account was last used (string ISO 8601 or integer epoch ms).
360    #[serde(default)]
361    pub last_used: Option<serde_json::Value>,
362    /// Device fingerprint headers injected into requests.
363    #[serde(default)]
364    pub fingerprint: Option<serde_json::Value>,
365}
366
367impl AntigravityAccount {
368    /// Returns the effective Google Cloud project ID, falling back to the default.
369    pub fn effective_project_id(&self) -> &str {
370        self.project_id
371            .as_deref()
372            .filter(|s| !s.is_empty())
373            .unwrap_or(ANTIGRAVITY_DEFAULT_PROJECT_ID)
374    }
375}
376
377/// The root structure of `antigravity-accounts.json`.
378#[derive(Debug, Clone, Serialize, Deserialize)]
379pub struct AntigravityAccountStore {
380    #[serde(default)]
381    pub version: u32,
382    #[serde(default)]
383    pub accounts: Vec<AntigravityAccount>,
384}
385
386/// Read OpenCode Antigravity accounts from `~/.config/opencode/antigravity-accounts.json`.
387///
388/// Returns `None` if the file is absent, unreadable, or malformed.
389pub fn read_antigravity_accounts() -> Option<AntigravityAccountStore> {
390    let path = dirs::home_dir()?
391        .join(".config")
392        .join("opencode")
393        .join("antigravity-accounts.json");
394    let content = std::fs::read_to_string(path).ok()?;
395    serde_json::from_str(&content).ok()
396}
397
398/// Return the first valid Antigravity account, or `None` if none exist.
399pub fn get_primary_antigravity_account() -> Option<AntigravityAccount> {
400    let store = read_antigravity_accounts()?;
401    store.accounts.into_iter().next()
402}
403
404/// Returns `true` if at least one Antigravity account is stored locally.
405pub fn antigravity_auth_available() -> bool {
406    read_antigravity_accounts()
407        .map(|s| !s.accounts.is_empty())
408        .unwrap_or(false)
409}
410
411/// Refresh an Antigravity Google OAuth access token using the stored refresh token.
412///
413/// Uses the Antigravity installed-app OAuth client (client ID/secret are public).
414/// Returns `(access_token, project_id)` on success, or `None` on failure.
415pub fn refresh_antigravity_token(account: &AntigravityAccount) -> Option<(String, String)> {
416    let client = reqwest::blocking::Client::builder()
417        .timeout(std::time::Duration::from_secs(15))
418        .build()
419        .ok()?;
420
421    let params = [
422        ("client_id", ANTIGRAVITY_CLIENT_ID),
423        ("client_secret", ANTIGRAVITY_CLIENT_SECRET),
424        ("refresh_token", account.refresh_token.as_str()),
425        ("grant_type", "refresh_token"),
426    ];
427
428    let resp = client
429        .post(GOOGLE_TOKEN_ENDPOINT)
430        .form(&params)
431        .send()
432        .ok()?;
433
434    if !resp.status().is_success() {
435        tracing::warn!(
436            "Antigravity token refresh failed (HTTP {}): email={}",
437            resp.status(),
438            account.email
439        );
440        return None;
441    }
442
443    let json: serde_json::Value = resp.json().ok()?;
444    let access_token = json["access_token"].as_str()?.to_string();
445    let project_id = account.effective_project_id().to_string();
446
447    tracing::debug!(
448        email = %account.email,
449        project = %project_id,
450        "Antigravity OAuth token refreshed"
451    );
452    Some((access_token, project_id))
453}
454
455/// Get a usable Antigravity access token (always refreshes — access tokens are short-lived).
456///
457/// Returns `(access_token, project_id)` or `None` if no account is configured
458/// or the refresh request fails.
459pub fn get_antigravity_token() -> Option<(String, String)> {
460    let account = get_primary_antigravity_account()?;
461    refresh_antigravity_token(&account)
462}
463
464// ─── Combined detection ───────────────────────────────────────────────────────
465
466/// Describe which subscription auth methods are available on this machine.
467pub fn detect_subscription_auth() -> Vec<SubscriptionAuth> {
468    let mut found = Vec::new();
469
470    if let Some(creds) = read_claude_code_creds() {
471        found.push(SubscriptionAuth::ClaudeCode {
472            subscription_type: creds.subscription_type.clone(),
473            valid: creds.is_valid(),
474        });
475    }
476
477    if let Some(creds) = read_gemini_creds() {
478        // Try to get the active account email
479        let account = std::fs::read_to_string(
480            dirs::home_dir()
481                .unwrap_or_default()
482                .join(".gemini")
483                .join("google_accounts.json"),
484        )
485        .ok()
486        .and_then(|s| {
487            let json: serde_json::Value = serde_json::from_str(&s).ok()?;
488            json["active"].as_str().map(|s| s.to_string())
489        });
490
491        found.push(SubscriptionAuth::GeminiOAuth {
492            account,
493            valid: creds.is_valid(),
494        });
495    }
496
497    if let Some(creds) = read_codex_creds() {
498        found.push(SubscriptionAuth::CodexOAuth {
499            valid: creds.is_valid(),
500        });
501    }
502
503    if let Some(key) = read_openrouter_key() {
504        let masked = if key.len() > 4 {
505            format!("…{}", &key[key.len() - 4..])
506        } else {
507            "****".into()
508        };
509        found.push(SubscriptionAuth::OpenRouterKey { masked });
510    }
511
512    if let Some(account) = get_primary_antigravity_account() {
513        found.push(SubscriptionAuth::AntigravityOAuth {
514            email: account.email.clone(),
515            project_id: account.effective_project_id().to_string(),
516        });
517    }
518
519    found
520}
521
522/// A detected subscription-based authentication method.
523#[derive(Debug, Clone)]
524pub enum SubscriptionAuth {
525    /// Claude Code OAuth session (Anthropic).
526    ClaudeCode {
527        subscription_type: String,
528        valid: bool,
529    },
530    /// Google OAuth session (Gemini CLI).
531    GeminiOAuth {
532        account: Option<String>,
533        valid: bool,
534    },
535    /// OpenAI Codex CLI OAuth session (ChatGPT subscription).
536    CodexOAuth { valid: bool },
537    /// OpenRouter API key stored in `~/.openrouter/config.json`.
538    OpenRouterKey {
539        /// Masked key (last 4 chars visible).
540        masked: String,
541    },
542    /// OpenCode Antigravity OAuth session (Gemini 3 + Claude via Cloud Code Assist).
543    AntigravityOAuth {
544        /// Google account email.
545        email: String,
546        /// Google Cloud project ID used for quota routing.
547        project_id: String,
548    },
549}
550
551impl SubscriptionAuth {
552    /// Human-readable description.
553    pub fn description(&self) -> String {
554        match self {
555            Self::ClaudeCode {
556                subscription_type,
557                valid,
558            } => format!(
559                "Claude Code session ({subscription_type}) — {}",
560                if *valid { "valid" } else { "expired" }
561            ),
562            Self::GeminiOAuth { account, valid } => format!(
563                "Gemini OAuth ({}) — {}",
564                account.as_deref().unwrap_or("unknown account"),
565                if *valid {
566                    "valid"
567                } else {
568                    "expired (needs refresh)"
569                }
570            ),
571            Self::CodexOAuth { valid } => format!(
572                "OpenAI Codex CLI session — {}",
573                if *valid {
574                    "valid"
575                } else {
576                    "expired (run `codex auth login`)"
577                }
578            ),
579            Self::OpenRouterKey { masked } => {
580                format!("OpenRouter API key ({masked}) — stored in ~/.openrouter/config.json")
581            }
582            Self::AntigravityOAuth { email, project_id } => format!(
583                "OpenCode Antigravity OAuth ({email}, project: {project_id}) — Gemini 3 + Claude"
584            ),
585        }
586    }
587}
588
589// ─── Unified Fetchium auth store (~/.fetchium/auth.json) ─────────────────────
590//
591// Modelled after OpenCode's auth.json. Stores API keys and OAuth tokens for all
592// providers in a single JSON file with 0o600 permissions (owner read/write only).
593//
594// Format:
595// {
596//   "gemini":     { "type": "api", "key": "AIza..." }
597//   "anthropic":  { "type": "oauth", "access": "...", "refresh": "...", "expires": 1234567890000 }
598// }
599//
600// Path:
601// ~/.fetchium/auth.json
602
603/// Credential stored in `~/.fetchium/auth.json`.
604#[derive(Debug, Clone, Serialize, Deserialize)]
605#[serde(tag = "type", rename_all = "snake_case")]
606pub enum FetchiumAuth {
607    /// Single API key credential.
608    Api { key: String },
609    /// Multiple API keys — random selection with 429/rate-limit failover.
610    ///
611    /// Store additional keys with `fetchium provider set <name> --add-key KEY`.
612    /// Keys are tried in random order; on HTTP 429 the next key is tried.
613    ApiPool { keys: Vec<String> },
614    /// OAuth token credential (access + refresh).
615    Oauth {
616        access: String,
617        refresh: String,
618        /// Expiry as Unix timestamp in milliseconds.
619        expires: u64,
620    },
621}
622
623impl FetchiumAuth {
624    /// True if this credential contains at least one API key.
625    pub fn is_api_key(&self) -> bool {
626        matches!(self, Self::Api { .. } | Self::ApiPool { .. })
627    }
628
629    /// Return the first API key (single `Api` or first of `ApiPool`).
630    ///
631    /// Prefer [`api_keys`] when you need all keys for pool-based rotation.
632    pub fn api_key(&self) -> Option<&str> {
633        match self {
634            Self::Api { key } => Some(key.as_str()),
635            Self::ApiPool { keys } => keys.first().map(|k| k.as_str()),
636            _ => None,
637        }
638    }
639
640    /// Return all stored API keys.
641    ///
642    /// Returns a single-element slice for `Api`, all keys for `ApiPool`,
643    /// and an empty vec for `Oauth`.
644    pub fn api_keys(&self) -> Vec<&str> {
645        match self {
646            Self::Api { key } => vec![key.as_str()],
647            Self::ApiPool { keys } => keys.iter().map(|k| k.as_str()).collect(),
648            Self::Oauth { .. } => vec![],
649        }
650    }
651
652    /// Number of API keys stored (0 for OAuth credentials).
653    pub fn key_count(&self) -> usize {
654        self.api_keys().len()
655    }
656
657    /// Return the access token if this is a valid, non-expired `Oauth` credential.
658    pub fn valid_access_token(&self) -> Option<&str> {
659        match self {
660            Self::Oauth {
661                access, expires, ..
662            } => {
663                let now_ms = std::time::SystemTime::now()
664                    .duration_since(std::time::UNIX_EPOCH)
665                    .map(|d| d.as_millis() as u64)
666                    .unwrap_or(0);
667                if *expires > now_ms + 60_000 {
668                    Some(access.as_str())
669                } else {
670                    None
671                }
672            }
673            _ => None,
674        }
675    }
676}
677
678/// Path to the unified auth store file.
679///
680/// Returns `~/.fetchium/auth.json`.
681pub fn fetchium_auth_path() -> std::path::PathBuf {
682    let home = dirs::home_dir().unwrap_or_default();
683    home.join(".fetchium").join("auth.json")
684}
685
686/// Read all entries from the auth store.
687pub fn fetchium_auth_all() -> std::collections::HashMap<String, FetchiumAuth> {
688    let path = fetchium_auth_path();
689    let content = match std::fs::read_to_string(&path) {
690        Ok(c) => c,
691        Err(_) => return std::collections::HashMap::new(),
692    };
693    let raw: std::collections::HashMap<String, serde_json::Value> =
694        serde_json::from_str(&content).unwrap_or_default();
695    raw.into_iter()
696        .filter_map(|(k, v)| serde_json::from_value(v).ok().map(|auth| (k, auth)))
697        .collect()
698}
699
700/// Read one entry from the auth store.
701pub fn fetchium_auth_get(provider: &str) -> Option<FetchiumAuth> {
702    fetchium_auth_all().remove(provider)
703}
704
705/// Write one entry to the auth store (creates the file if absent, 0o600 permissions).
706///
707/// Always writes to `~/.fetchium/auth.json`.
708pub fn fetchium_auth_set(
709    provider: &str,
710    auth: FetchiumAuth,
711) -> Result<(), Box<dyn std::error::Error>> {
712    let home = dirs::home_dir().unwrap_or_default();
713    let path = home.join(".fetchium").join("auth.json");
714
715    let mut map = fetchium_auth_all();
716    map.insert(provider.to_string(), auth);
717
718    if let Some(parent) = path.parent() {
719        std::fs::create_dir_all(parent)?;
720    }
721
722    let content = serde_json::to_string_pretty(
723        &map.into_iter()
724            .map(|(k, v)| (k, serde_json::to_value(v).unwrap()))
725            .collect::<std::collections::HashMap<_, _>>(),
726    )?;
727
728    // Write with restrictive permissions (0o600 — owner only)
729    std::fs::write(&path, &content)?;
730    #[cfg(unix)]
731    {
732        use std::os::unix::fs::PermissionsExt;
733        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
734    }
735
736    Ok(())
737}
738
739/// Add an API key to the provider's key pool in the auth store.
740///
741/// - If no entry exists, creates a new `ApiPool` with the single key.
742/// - If a single `Api` key exists, converts it to an `ApiPool`.
743/// - Deduplicates: if the key is already in the pool, this is a no-op.
744///
745/// Use `fetchium_auth_set` with `FetchiumAuth::ApiPool` to **replace** the entire pool.
746pub fn fetchium_auth_add_api_key(
747    provider: &str,
748    new_key: &str,
749) -> Result<(), Box<dyn std::error::Error>> {
750    let mut existing: Vec<String> = fetchium_auth_get(provider)
751        .map(|a| a.api_keys().into_iter().map(|s| s.to_string()).collect())
752        .unwrap_or_default();
753
754    let key_str = new_key.to_string();
755    if !existing.contains(&key_str) {
756        existing.push(key_str);
757    }
758
759    fetchium_auth_set(provider, FetchiumAuth::ApiPool { keys: existing })
760}
761
762/// Remove one entry from the auth store.
763///
764/// Always writes to `~/.fetchium/auth.json` (new canonical location).
765pub fn fetchium_auth_remove(provider: &str) -> Result<(), Box<dyn std::error::Error>> {
766    let home = dirs::home_dir().unwrap_or_default();
767    let path = home.join(".fetchium").join("auth.json");
768
769    let mut map = fetchium_auth_all();
770    map.remove(provider);
771
772    if let Some(parent) = path.parent() {
773        std::fs::create_dir_all(parent)?;
774    }
775    let content = serde_json::to_string_pretty(
776        &map.into_iter()
777            .map(|(k, v)| (k, serde_json::to_value(v).unwrap()))
778            .collect::<std::collections::HashMap<_, _>>(),
779    )?;
780    std::fs::write(&path, content)?;
781    Ok(())
782}
783
784#[cfg(test)]
785mod tests {
786    use super::*;
787
788    #[test]
789    fn gemini_creds_validity_future() {
790        let now_ms = std::time::SystemTime::now()
791            .duration_since(std::time::UNIX_EPOCH)
792            .map(|d| d.as_millis() as u64)
793            .unwrap_or(0);
794        let creds = GeminiOAuthCreds {
795            access_token: "test".into(),
796            refresh_token: "rt".into(),
797            expiry_date: now_ms + 3_600_000, // 1 hour from now
798            token_type: "Bearer".into(),
799        };
800        assert!(creds.is_valid());
801    }
802
803    #[test]
804    fn gemini_creds_validity_expired() {
805        let creds = GeminiOAuthCreds {
806            access_token: "test".into(),
807            refresh_token: "rt".into(),
808            expiry_date: 1_000_000, // way in the past
809            token_type: "Bearer".into(),
810        };
811        assert!(!creds.is_valid());
812    }
813
814    #[test]
815    fn claude_oauth_validity_future() {
816        let now_ms = std::time::SystemTime::now()
817            .duration_since(std::time::UNIX_EPOCH)
818            .map(|d| d.as_millis() as u64)
819            .unwrap_or(0);
820        let creds = ClaudeOAuthCreds {
821            access_token: "sk-ant-oat01-test".into(),
822            refresh_token: "rt".into(),
823            expires_at: now_ms + 7_200_000, // 2 hours
824            subscription_type: "max".into(),
825        };
826        assert!(creds.is_valid());
827    }
828}