use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeminiOAuthCreds {
pub access_token: String,
pub refresh_token: String,
pub expiry_date: u64,
pub token_type: String,
}
impl GeminiOAuthCreds {
pub fn is_valid(&self) -> bool {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
self.expiry_date > now_ms + 60_000
}
pub fn is_refreshable(&self) -> bool {
!self.refresh_token.is_empty()
}
}
pub fn invalidate_gemini_creds() {
if let Some(path) = dirs::home_dir().map(|h| h.join(".gemini").join("oauth_creds.json")) {
let cleared = serde_json::json!({
"access_token": "",
"refresh_token": "",
"expiry_date": 0u64,
"token_type": "Bearer",
});
let _ = std::fs::write(
&path,
serde_json::to_string_pretty(&cleared).unwrap_or_default(),
);
}
}
pub fn read_gemini_creds() -> Option<GeminiOAuthCreds> {
let path = dirs::home_dir()?.join(".gemini").join("oauth_creds.json");
let content = std::fs::read_to_string(path).ok()?;
serde_json::from_str(&content).ok()
}
pub fn get_gemini_access_token_if_valid() -> Option<String> {
let creds = read_gemini_creds()?;
if creds.is_valid() {
Some(creds.access_token.clone())
} else {
tracing::debug!("Gemini OAuth token expired — refresh needed");
None
}
}
pub const GEMINI_OAUTH_CLIENT_ID: &str =
"681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com";
pub const GEMINI_OAUTH_CLIENT_SECRET: &str = "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";
pub const GOOGLE_TOKEN_ENDPOINT: &str = "https://oauth2.googleapis.com/token";
#[derive(Debug, Clone)]
pub struct ClaudeOAuthCreds {
pub access_token: String,
pub refresh_token: String,
pub expires_at: u64,
pub subscription_type: String,
}
impl ClaudeOAuthCreds {
pub fn is_valid(&self) -> bool {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
self.expires_at > now_ms + 60_000
}
}
pub fn read_claude_code_creds() -> Option<ClaudeOAuthCreds> {
#[cfg(target_os = "macos")]
{
let output = std::process::Command::new("security")
.args([
"find-generic-password",
"-s",
"Claude Code-credentials",
"-w",
])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let raw = String::from_utf8(output.stdout).ok()?;
let json: serde_json::Value = serde_json::from_str(raw.trim()).ok()?;
let oauth = json.get("claudeAiOauth")?;
let access_token = oauth.get("accessToken")?.as_str()?.to_string();
let refresh_token = oauth.get("refreshToken")?.as_str()?.to_string();
let expires_at = oauth.get("expiresAt")?.as_u64().unwrap_or(0);
let subscription = oauth
.get("subscriptionType")
.and_then(|s| s.as_str())
.unwrap_or("unknown")
.to_string();
Some(ClaudeOAuthCreds {
access_token,
refresh_token,
expires_at,
subscription_type: subscription,
})
}
#[cfg(not(target_os = "macos"))]
{
let path = dirs::home_dir()?.join(".claude").join("credentials.json");
let content = std::fs::read_to_string(path).ok()?;
let json: serde_json::Value = serde_json::from_str(&content).ok()?;
let oauth = json.get("claudeAiOauth")?;
let access_token = oauth.get("accessToken")?.as_str()?.to_string();
let refresh_token = oauth.get("refreshToken")?.as_str()?.to_string();
let expires_at = oauth.get("expiresAt")?.as_u64().unwrap_or(0);
let subscription = oauth
.get("subscriptionType")
.and_then(|s| s.as_str())
.unwrap_or("unknown")
.to_string();
Some(ClaudeOAuthCreds {
access_token,
refresh_token,
expires_at,
subscription_type: subscription,
})
}
}
pub fn get_claude_code_token() -> Option<ClaudeOAuthCreds> {
let creds = read_claude_code_creds()?;
if creds.is_valid() {
return Some(creds);
}
tracing::warn!(
"Claude Code OAuth token has expired. Re-run `claude` once to refresh it, then retry."
);
None
}
pub fn gemini_cli_auth_available() -> bool {
let has_binary = std::process::Command::new("gemini")
.arg("--version")
.output()
.map(|o| o.status.success())
.unwrap_or(false);
has_binary && read_gemini_creds().is_some()
}
pub fn claude_code_auth_available() -> bool {
read_claude_code_creds().is_some()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodexOAuthCreds {
pub access_token: String,
pub refresh_token: Option<String>,
pub expires_at: Option<String>,
}
impl CodexOAuthCreds {
pub fn is_valid(&self) -> bool {
let Some(ref exp_str) = self.expires_at else {
return true; };
let Ok(exp) = chrono::DateTime::parse_from_rfc3339(exp_str) else {
return true;
};
let now = chrono::Utc::now();
exp.signed_duration_since(now).num_seconds() > 60
}
}
pub fn read_codex_creds() -> Option<CodexOAuthCreds> {
let path = dirs::home_dir()?.join(".codex").join("auth.json");
let content = std::fs::read_to_string(path).ok()?;
serde_json::from_str(&content).ok()
}
pub fn get_codex_token_if_valid() -> Option<String> {
let creds = read_codex_creds()?;
if creds.is_valid() {
Some(creds.access_token.clone())
} else {
tracing::debug!("OpenAI Codex token expired — re-run `codex auth login` to refresh");
None
}
}
pub fn codex_auth_available() -> bool {
get_codex_token_if_valid().is_some()
}
pub fn read_openrouter_key() -> Option<String> {
let path = dirs::home_dir()?.join(".openrouter").join("config.json");
let content = std::fs::read_to_string(path).ok()?;
let json: serde_json::Value = serde_json::from_str(&content).ok()?;
json.get("api_key")
.or_else(|| json.get("apiKey"))
.or_else(|| json.get("key"))
.and_then(|v| v.as_str())
.map(|s| s.to_string())
}
pub const ANTIGRAVITY_CLIENT_ID: &str =
"1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
pub const ANTIGRAVITY_CLIENT_SECRET: &str = "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";
pub const ANTIGRAVITY_ENDPOINT: &str = "https://daily-cloudcode-pa.sandbox.googleapis.com";
pub const ANTIGRAVITY_ENDPOINT_AUTOPUSH: &str =
"https://autopush-cloudcode-pa.sandbox.googleapis.com";
pub const ANTIGRAVITY_ENDPOINT_PROD: &str = "https://cloudcode-pa.googleapis.com";
pub const ANTIGRAVITY_ENDPOINTS: &[&str] = &[
ANTIGRAVITY_ENDPOINT,
ANTIGRAVITY_ENDPOINT_AUTOPUSH,
ANTIGRAVITY_ENDPOINT_PROD,
];
pub const ANTIGRAVITY_DEFAULT_PROJECT_ID: &str = "rising-fact-p41fc";
pub const ANTIGRAVITY_VERSION: &str = "1.15.8";
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AntigravityAccount {
pub email: String,
pub refresh_token: String,
#[serde(default)]
pub project_id: Option<String>,
#[serde(default)]
pub added_at: Option<serde_json::Value>,
#[serde(default)]
pub last_used: Option<serde_json::Value>,
#[serde(default)]
pub fingerprint: Option<serde_json::Value>,
}
impl AntigravityAccount {
pub fn effective_project_id(&self) -> &str {
self.project_id
.as_deref()
.filter(|s| !s.is_empty())
.unwrap_or(ANTIGRAVITY_DEFAULT_PROJECT_ID)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AntigravityAccountStore {
#[serde(default)]
pub version: u32,
#[serde(default)]
pub accounts: Vec<AntigravityAccount>,
}
pub fn read_antigravity_accounts() -> Option<AntigravityAccountStore> {
let path = dirs::home_dir()?
.join(".config")
.join("opencode")
.join("antigravity-accounts.json");
let content = std::fs::read_to_string(path).ok()?;
serde_json::from_str(&content).ok()
}
pub fn get_primary_antigravity_account() -> Option<AntigravityAccount> {
let store = read_antigravity_accounts()?;
store.accounts.into_iter().next()
}
pub fn antigravity_auth_available() -> bool {
read_antigravity_accounts()
.map(|s| !s.accounts.is_empty())
.unwrap_or(false)
}
pub fn refresh_antigravity_token(account: &AntigravityAccount) -> Option<(String, String)> {
let client = reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(15))
.build()
.ok()?;
let params = [
("client_id", ANTIGRAVITY_CLIENT_ID),
("client_secret", ANTIGRAVITY_CLIENT_SECRET),
("refresh_token", account.refresh_token.as_str()),
("grant_type", "refresh_token"),
];
let resp = client
.post(GOOGLE_TOKEN_ENDPOINT)
.form(¶ms)
.send()
.ok()?;
if !resp.status().is_success() {
tracing::warn!(
"Antigravity token refresh failed (HTTP {}): email={}",
resp.status(),
account.email
);
return None;
}
let json: serde_json::Value = resp.json().ok()?;
let access_token = json["access_token"].as_str()?.to_string();
let project_id = account.effective_project_id().to_string();
tracing::debug!(
email = %account.email,
project = %project_id,
"Antigravity OAuth token refreshed"
);
Some((access_token, project_id))
}
pub fn get_antigravity_token() -> Option<(String, String)> {
let account = get_primary_antigravity_account()?;
refresh_antigravity_token(&account)
}
pub fn detect_subscription_auth() -> Vec<SubscriptionAuth> {
let mut found = Vec::new();
if let Some(creds) = read_claude_code_creds() {
found.push(SubscriptionAuth::ClaudeCode {
subscription_type: creds.subscription_type.clone(),
valid: creds.is_valid(),
});
}
if let Some(creds) = read_gemini_creds() {
let account = std::fs::read_to_string(
dirs::home_dir()
.unwrap_or_default()
.join(".gemini")
.join("google_accounts.json"),
)
.ok()
.and_then(|s| {
let json: serde_json::Value = serde_json::from_str(&s).ok()?;
json["active"].as_str().map(|s| s.to_string())
});
found.push(SubscriptionAuth::GeminiOAuth {
account,
valid: creds.is_valid(),
});
}
if let Some(creds) = read_codex_creds() {
found.push(SubscriptionAuth::CodexOAuth {
valid: creds.is_valid(),
});
}
if let Some(key) = read_openrouter_key() {
let masked = if key.len() > 4 {
format!("…{}", &key[key.len() - 4..])
} else {
"****".into()
};
found.push(SubscriptionAuth::OpenRouterKey { masked });
}
if let Some(account) = get_primary_antigravity_account() {
found.push(SubscriptionAuth::AntigravityOAuth {
email: account.email.clone(),
project_id: account.effective_project_id().to_string(),
});
}
found
}
#[derive(Debug, Clone)]
pub enum SubscriptionAuth {
ClaudeCode {
subscription_type: String,
valid: bool,
},
GeminiOAuth {
account: Option<String>,
valid: bool,
},
CodexOAuth { valid: bool },
OpenRouterKey {
masked: String,
},
AntigravityOAuth {
email: String,
project_id: String,
},
}
impl SubscriptionAuth {
pub fn description(&self) -> String {
match self {
Self::ClaudeCode {
subscription_type,
valid,
} => format!(
"Claude Code session ({subscription_type}) — {}",
if *valid { "valid" } else { "expired" }
),
Self::GeminiOAuth { account, valid } => format!(
"Gemini OAuth ({}) — {}",
account.as_deref().unwrap_or("unknown account"),
if *valid {
"valid"
} else {
"expired (needs refresh)"
}
),
Self::CodexOAuth { valid } => format!(
"OpenAI Codex CLI session — {}",
if *valid {
"valid"
} else {
"expired (run `codex auth login`)"
}
),
Self::OpenRouterKey { masked } => {
format!("OpenRouter API key ({masked}) — stored in ~/.openrouter/config.json")
}
Self::AntigravityOAuth { email, project_id } => format!(
"OpenCode Antigravity OAuth ({email}, project: {project_id}) — Gemini 3 + Claude"
),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum FetchiumAuth {
Api { key: String },
ApiPool { keys: Vec<String> },
Oauth {
access: String,
refresh: String,
expires: u64,
},
}
impl FetchiumAuth {
pub fn is_api_key(&self) -> bool {
matches!(self, Self::Api { .. } | Self::ApiPool { .. })
}
pub fn api_key(&self) -> Option<&str> {
match self {
Self::Api { key } => Some(key.as_str()),
Self::ApiPool { keys } => keys.first().map(|k| k.as_str()),
_ => None,
}
}
pub fn api_keys(&self) -> Vec<&str> {
match self {
Self::Api { key } => vec![key.as_str()],
Self::ApiPool { keys } => keys.iter().map(|k| k.as_str()).collect(),
Self::Oauth { .. } => vec![],
}
}
pub fn key_count(&self) -> usize {
self.api_keys().len()
}
pub fn valid_access_token(&self) -> Option<&str> {
match self {
Self::Oauth {
access, expires, ..
} => {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
if *expires > now_ms + 60_000 {
Some(access.as_str())
} else {
None
}
}
_ => None,
}
}
}
pub fn fetchium_auth_path() -> std::path::PathBuf {
let home = dirs::home_dir().unwrap_or_default();
home.join(".fetchium").join("auth.json")
}
pub fn fetchium_auth_all() -> std::collections::HashMap<String, FetchiumAuth> {
let path = fetchium_auth_path();
let content = match std::fs::read_to_string(&path) {
Ok(c) => c,
Err(_) => return std::collections::HashMap::new(),
};
let raw: std::collections::HashMap<String, serde_json::Value> =
serde_json::from_str(&content).unwrap_or_default();
raw.into_iter()
.filter_map(|(k, v)| serde_json::from_value(v).ok().map(|auth| (k, auth)))
.collect()
}
pub fn fetchium_auth_get(provider: &str) -> Option<FetchiumAuth> {
fetchium_auth_all().remove(provider)
}
pub fn fetchium_auth_set(
provider: &str,
auth: FetchiumAuth,
) -> Result<(), Box<dyn std::error::Error>> {
let home = dirs::home_dir().unwrap_or_default();
let path = home.join(".fetchium").join("auth.json");
let mut map = fetchium_auth_all();
map.insert(provider.to_string(), auth);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let content = serde_json::to_string_pretty(
&map.into_iter()
.map(|(k, v)| (k, serde_json::to_value(v).unwrap()))
.collect::<std::collections::HashMap<_, _>>(),
)?;
std::fs::write(&path, &content)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
}
Ok(())
}
pub fn fetchium_auth_add_api_key(
provider: &str,
new_key: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let mut existing: Vec<String> = fetchium_auth_get(provider)
.map(|a| a.api_keys().into_iter().map(|s| s.to_string()).collect())
.unwrap_or_default();
let key_str = new_key.to_string();
if !existing.contains(&key_str) {
existing.push(key_str);
}
fetchium_auth_set(provider, FetchiumAuth::ApiPool { keys: existing })
}
pub fn fetchium_auth_remove(provider: &str) -> Result<(), Box<dyn std::error::Error>> {
let home = dirs::home_dir().unwrap_or_default();
let path = home.join(".fetchium").join("auth.json");
let mut map = fetchium_auth_all();
map.remove(provider);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let content = serde_json::to_string_pretty(
&map.into_iter()
.map(|(k, v)| (k, serde_json::to_value(v).unwrap()))
.collect::<std::collections::HashMap<_, _>>(),
)?;
std::fs::write(&path, content)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gemini_creds_validity_future() {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
let creds = GeminiOAuthCreds {
access_token: "test".into(),
refresh_token: "rt".into(),
expiry_date: now_ms + 3_600_000, token_type: "Bearer".into(),
};
assert!(creds.is_valid());
}
#[test]
fn gemini_creds_validity_expired() {
let creds = GeminiOAuthCreds {
access_token: "test".into(),
refresh_token: "rt".into(),
expiry_date: 1_000_000, token_type: "Bearer".into(),
};
assert!(!creds.is_valid());
}
#[test]
fn claude_oauth_validity_future() {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
let creds = ClaudeOAuthCreds {
access_token: "sk-ant-oat01-test".into(),
refresh_token: "rt".into(),
expires_at: now_ms + 7_200_000, subscription_type: "max".into(),
};
assert!(creds.is_valid());
}
}