1use serde::{Deserialize, Serialize};
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct GeminiOAuthCreds {
20 pub access_token: String,
22 pub refresh_token: String,
24 pub expiry_date: u64,
26 pub token_type: String,
28}
29
30impl GeminiOAuthCreds {
31 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 self.expiry_date > now_ms + 60_000
39 }
40
41 pub fn is_refreshable(&self) -> bool {
46 !self.refresh_token.is_empty()
47 }
48}
49
50pub 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
70pub 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
79pub 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
92pub const GEMINI_OAUTH_CLIENT_ID: &str =
96 "681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com";
97pub const GEMINI_OAUTH_CLIENT_SECRET: &str = "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";
99pub const GOOGLE_TOKEN_ENDPOINT: &str = "https://oauth2.googleapis.com/token";
101
102#[derive(Debug, Clone)]
106pub struct ClaudeOAuthCreds {
107 pub access_token: String,
109 pub refresh_token: String,
111 pub expires_at: u64,
113 pub subscription_type: String,
115}
116
117impl ClaudeOAuthCreds {
118 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
128pub fn read_claude_code_creds() -> Option<ClaudeOAuthCreds> {
133 #[cfg(target_os = "macos")]
134 {
135 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 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
197pub 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 tracing::warn!(
208 "Claude Code OAuth token has expired. Re-run `claude` once to refresh it, then retry."
209 );
210 None
211}
212
213pub fn gemini_cli_auth_available() -> bool {
217 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
227pub fn claude_code_auth_available() -> bool {
229 read_claude_code_creds().is_some()
230}
231
232#[derive(Debug, Clone, Serialize, Deserialize)]
238pub struct CodexOAuthCreds {
239 pub access_token: String,
241 pub refresh_token: Option<String>,
243 pub expires_at: Option<String>,
245}
246
247impl CodexOAuthCreds {
248 pub fn is_valid(&self) -> bool {
250 let Some(ref exp_str) = self.expires_at else {
251 return true; };
253 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
262pub 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
271pub 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
282pub fn codex_auth_available() -> bool {
284 get_codex_token_if_valid().is_some()
285}
286
287pub 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
303pub const ANTIGRAVITY_CLIENT_ID: &str =
320 "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
321pub const ANTIGRAVITY_CLIENT_SECRET: &str = "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";
323
324pub const ANTIGRAVITY_ENDPOINT: &str = "https://daily-cloudcode-pa.sandbox.googleapis.com";
326pub const ANTIGRAVITY_ENDPOINT_AUTOPUSH: &str =
328 "https://autopush-cloudcode-pa.sandbox.googleapis.com";
329pub const ANTIGRAVITY_ENDPOINT_PROD: &str = "https://cloudcode-pa.googleapis.com";
331
332pub const ANTIGRAVITY_ENDPOINTS: &[&str] = &[
334 ANTIGRAVITY_ENDPOINT,
335 ANTIGRAVITY_ENDPOINT_AUTOPUSH,
336 ANTIGRAVITY_ENDPOINT_PROD,
337];
338
339pub const ANTIGRAVITY_DEFAULT_PROJECT_ID: &str = "rising-fact-p41fc";
341
342pub const ANTIGRAVITY_VERSION: &str = "1.15.8";
344
345#[derive(Debug, Clone, Serialize, Deserialize)]
347#[serde(rename_all = "camelCase")]
348pub struct AntigravityAccount {
349 pub email: String,
351 pub refresh_token: String,
353 #[serde(default)]
355 pub project_id: Option<String>,
356 #[serde(default)]
358 pub added_at: Option<serde_json::Value>,
359 #[serde(default)]
361 pub last_used: Option<serde_json::Value>,
362 #[serde(default)]
364 pub fingerprint: Option<serde_json::Value>,
365}
366
367impl AntigravityAccount {
368 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#[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
386pub 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
398pub fn get_primary_antigravity_account() -> Option<AntigravityAccount> {
400 let store = read_antigravity_accounts()?;
401 store.accounts.into_iter().next()
402}
403
404pub fn antigravity_auth_available() -> bool {
406 read_antigravity_accounts()
407 .map(|s| !s.accounts.is_empty())
408 .unwrap_or(false)
409}
410
411pub 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(¶ms)
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
455pub fn get_antigravity_token() -> Option<(String, String)> {
460 let account = get_primary_antigravity_account()?;
461 refresh_antigravity_token(&account)
462}
463
464pub 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 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#[derive(Debug, Clone)]
524pub enum SubscriptionAuth {
525 ClaudeCode {
527 subscription_type: String,
528 valid: bool,
529 },
530 GeminiOAuth {
532 account: Option<String>,
533 valid: bool,
534 },
535 CodexOAuth { valid: bool },
537 OpenRouterKey {
539 masked: String,
541 },
542 AntigravityOAuth {
544 email: String,
546 project_id: String,
548 },
549}
550
551impl SubscriptionAuth {
552 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#[derive(Debug, Clone, Serialize, Deserialize)]
605#[serde(tag = "type", rename_all = "snake_case")]
606pub enum FetchiumAuth {
607 Api { key: String },
609 ApiPool { keys: Vec<String> },
614 Oauth {
616 access: String,
617 refresh: String,
618 expires: u64,
620 },
621}
622
623impl FetchiumAuth {
624 pub fn is_api_key(&self) -> bool {
626 matches!(self, Self::Api { .. } | Self::ApiPool { .. })
627 }
628
629 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 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 pub fn key_count(&self) -> usize {
654 self.api_keys().len()
655 }
656
657 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
678pub 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
686pub 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
700pub fn fetchium_auth_get(provider: &str) -> Option<FetchiumAuth> {
702 fetchium_auth_all().remove(provider)
703}
704
705pub 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 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
739pub 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
762pub 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, 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, 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, subscription_type: "max".into(),
825 };
826 assert!(creds.is_valid());
827 }
828}