use std::sync::{Arc, LazyLock};
use std::time::Duration;
use anyhow::Result;
use serde::Deserialize;
use crate::claude::{LinkState, classify_credentials_link};
use crate::lock::with_state_lock;
use crate::profile::{
AppConfig, OAuthToken, clear_staged_credentials, save_app_state, save_profile,
stage_rotated_credentials,
};
use crate::runtime::{RotationGuard, has_live_session};
use crate::usage::{
ActivityKind, ActivityStore, OpResult, OpResultSender, ProfileActivity, RefetchQueue,
UsageStore, clear_activity, iso_to_epoch_secs, mark_activity, now_epoch_secs, now_ms,
};
const TOKEN_ENDPOINT: &str = "https://api.anthropic.com/v1/oauth/token";
const CLIENT_ID: &str = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
const MESSAGES_ENDPOINT: &str = "https://api.anthropic.com/v1/messages";
const KICK_MODEL: &str = "claude-haiku-4-5-20251001";
const KICK_SYSTEM_PROMPT: &str = "You are Claude Code, Anthropic's official CLI for Claude.";
const AUTO_START_COOLDOWN_MS: u64 = 4 * 3600 * 1000 + 30 * 60 * 1000;
const AUTO_START_RETRY_MS: u64 = 5 * 60 * 1000;
#[derive(Deserialize)]
pub(crate) struct TokenResponse {
pub(crate) access_token: String,
pub(crate) refresh_token: String,
pub(crate) expires_in: u64,
#[serde(default)]
pub(crate) scope: Option<String>,
}
static AGENT: LazyLock<ureq::Agent> = LazyLock::new(|| {
ureq::Agent::config_builder()
.timeout_connect(Some(Duration::from_secs(4)))
.timeout_recv_response(Some(Duration::from_secs(15)))
.build()
.into()
});
pub(crate) fn refresh(refresh_token: &str) -> Result<TokenResponse> {
let body = serde_json::to_string(&serde_json::json!({
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"client_id": CLIENT_ID,
}))?;
let text = AGENT
.post(TOKEN_ENDPOINT)
.header("Content-Type", "application/json")
.send(&body)
.map_err(crate::ureq_error::into_anyhow)?
.body_mut()
.read_to_string()
.map_err(crate::ureq_error::into_anyhow)?;
serde_json::from_str(&text).map_err(|e| anyhow::anyhow!("{e}: {text}"))
}
fn kick(access_token: &str) -> Result<()> {
let body = serde_json::to_string(&serde_json::json!({
"model": KICK_MODEL,
"max_tokens": 1,
"system": [{ "type": "text", "text": KICK_SYSTEM_PROMPT }],
"messages": [{ "role": "user", "content": "x" }],
}))?;
let status = AGENT
.post(MESSAGES_ENDPOINT)
.header("Content-Type", "application/json")
.header("Authorization", &format!("Bearer {access_token}"))
.header("anthropic-version", "2023-06-01")
.header("anthropic-beta", "oauth-2025-04-20")
.send(&body)
.map_err(crate::ureq_error::into_anyhow)?
.status()
.as_u16();
if status >= 400 {
return Err(anyhow::anyhow!("HTTP {status}"));
}
Ok(())
}
enum RotateOutcome {
GuardBusy,
Persisted(bool),
}
fn rotate_one_inner(
config: &crate::profile::ConfigHandle,
name: &str,
activity: Option<&ActivityStore>,
sender: &OpResultSender,
force: bool,
) -> RotateOutcome {
let Ok(_rotation_guard) = RotationGuard::acquire(name) else {
return RotateOutcome::GuardBusy;
};
let token = {
let cfg = config.lock().expect("config mutex poisoned");
with_state_lock(|| {
if !force && has_live_session(name) {
return Ok::<_, anyhow::Error>(None);
}
let rt = cfg
.find(name)
.and_then(|p| p.refresh_token().map(str::to_string));
if rt.is_some()
&& let Some(activity) = activity
{
mark_activity(activity, name, ProfileActivity::Refreshing);
}
Ok(rt)
})
.ok()
.flatten()
};
let Some(rt) = token else {
return RotateOutcome::Persisted(false);
};
let outcome = refresh(&rt).and_then(|tok| apply_rotated_tokens_locked(config, name, tok));
let applied = outcome.is_ok();
if let Some(activity) = activity {
clear_activity(activity, name);
}
let _ = sender.send(OpResult {
name: name.to_string(),
kind: ActivityKind::Refreshing,
outcome,
});
RotateOutcome::Persisted(applied)
}
pub(crate) fn rotation_candidates(config: &AppConfig, force: bool) -> Vec<(String, String)> {
let skip_active = !force && active_link_diverged(config);
config
.profiles
.iter()
.filter_map(|p| {
if skip_active && config.is_active(&p.name) {
return None;
}
if !force && has_live_session(&p.name) {
return None;
}
Some((p.name.to_string(), p.refresh_token()?.to_string()))
})
.collect()
}
pub(crate) fn refresh_all(
config: &crate::profile::ConfigHandle,
force: bool,
refetch: &RefetchQueue,
activity: &ActivityStore,
sender: &OpResultSender,
) -> Vec<String> {
let snapshots = {
let cfg = config.lock().expect("config mutex poisoned");
rotation_candidates(&cfg, force)
};
if snapshots.is_empty() {
return Vec::new();
}
for (name, _) in &snapshots {
mark_activity(activity, name, ProfileActivity::Refreshing);
}
let handles: Vec<(String, _)> = snapshots
.into_iter()
.map(|(name, _rt)| {
let config = Arc::clone(config);
let activity = Arc::clone(activity);
let sender = sender.clone();
let name_for_handle = name.clone();
let h = std::thread::spawn(move || {
let outcome = rotate_one_inner(&config, &name, Some(&activity), &sender, force);
(name, outcome)
});
(name_for_handle, h)
})
.collect();
let mut refreshed = Vec::new();
for (name, h) in handles {
match h.join() {
Ok((n, RotateOutcome::Persisted(true))) => refreshed.push(n),
Ok((n, RotateOutcome::GuardBusy)) => {
let _ = sender.send(OpResult {
name: n.clone(),
kind: ActivityKind::Refreshing,
outcome: Err(anyhow::anyhow!("failed to acquire rotation lock")),
});
clear_activity(activity, &n);
}
Ok((n, RotateOutcome::Persisted(false))) => clear_activity(activity, &n),
Err(_) => {
clear_activity(activity, &name);
}
}
}
if let Ok(mut q) = refetch.lock() {
for name in &refreshed {
q.insert(name.clone());
}
}
refreshed
}
pub(crate) fn windowless_auto_start_candidates(
config: &crate::profile::ConfigHandle,
store: &UsageStore,
) -> Vec<String> {
let now_secs = now_epoch_secs();
let has_active_window: std::collections::HashMap<String, bool> = store
.lock()
.ok()
.map(|s| {
s.iter()
.map(|(name, info)| {
let active = info
.five_hour
.as_ref()
.and_then(|w| w.resets_at.as_deref())
.and_then(iso_to_epoch_secs)
.is_some_and(|resets_at| now_secs < resets_at);
(name.clone(), active)
})
.collect()
})
.unwrap_or_default();
let cfg = config.lock().expect("config mutex poisoned");
let skip_active = active_link_diverged(&cfg);
let now = now_ms();
cfg.profiles
.iter()
.filter(|p| {
p.auto_start
&& p.is_oauth()
&& !(skip_active && cfg.is_active(&p.name))
&& !*has_active_window.get(p.name.as_str()).unwrap_or(&false)
&& now.saturating_sub(
cfg.state
.last_auto_start_at
.get(p.name.as_str())
.copied()
.unwrap_or(0),
) >= AUTO_START_COOLDOWN_MS
})
.map(|p| p.name.to_string())
.collect()
}
pub(crate) fn start_window(
config: &crate::profile::ConfigHandle,
name: &str,
refetch: Option<&RefetchQueue>,
activity: Option<&ActivityStore>,
sender: &OpResultSender,
) -> bool {
let access_token = {
let mut cfg = config.lock().expect("config mutex poisoned");
match with_state_lock(|| {
let Some(profile) = cfg.find(name) else {
return Ok::<_, anyhow::Error>(None);
};
if !profile.is_oauth() || !profile.auto_start {
return Ok(None);
}
let Some(token) = profile.access_token().map(str::to_string) else {
return Ok(None);
};
if active_link_diverged(&cfg) && cfg.is_active(name) {
return Ok(None);
}
let now = now_ms();
let last = cfg.state.last_auto_start_at.get(name).copied().unwrap_or(0);
if now.saturating_sub(last) < AUTO_START_COOLDOWN_MS {
return Ok(None);
}
cfg.state.last_auto_start_at.insert(name.to_string(), now);
let _ = save_app_state(&cfg.state);
Ok(Some(token))
}) {
Ok(Some(t)) => t,
_ => return false,
}
};
if let Some(activity) = activity {
mark_activity(activity, name, ProfileActivity::AutoStarting);
}
let outcome = kick(&access_token);
let kicked = outcome.is_ok();
if !kicked {
let mut cfg = config.lock().expect("config mutex poisoned");
let _ = with_state_lock(|| {
let backoff =
now_ms().saturating_sub(AUTO_START_COOLDOWN_MS.saturating_sub(AUTO_START_RETRY_MS));
cfg.state
.last_auto_start_at
.insert(name.to_string(), backoff);
let _ = save_app_state(&cfg.state);
Ok::<_, anyhow::Error>(())
});
}
if let Some(activity) = activity {
clear_activity(activity, name);
}
let _ = sender.send(OpResult {
name: name.to_string(),
kind: ActivityKind::AutoStarting,
outcome,
});
if kicked
&& let Some(refetch) = refetch
&& let Ok(mut q) = refetch.lock()
{
q.insert(name.to_string());
}
kicked
}
fn write_token_fields(oauth: &mut OAuthToken, tok: TokenResponse) {
oauth.access_token = tok.access_token;
oauth.refresh_token = Some(tok.refresh_token);
oauth.expires_at = Some((now_ms() + tok.expires_in * 1000) as i64);
if let Some(scope) = tok.scope {
oauth.scopes = Some(scope.split_whitespace().map(String::from).collect());
}
}
pub(crate) fn apply_rotated_tokens_locked(
config: &crate::profile::ConfigHandle,
name: &str,
tok: TokenResponse,
) -> Result<()> {
let mut cfg = config.lock().expect("config mutex poisoned");
with_state_lock(|| {
let Some(profile) = cfg.find_mut(name) else {
return Err(anyhow::anyhow!("failed to persist rotated tokens"));
};
let Some(creds) = profile.credentials.as_mut() else {
return Err(anyhow::anyhow!("failed to persist rotated tokens"));
};
let Some(oauth) = creds.claude_ai_oauth.as_mut() else {
return Err(anyhow::anyhow!("failed to persist rotated tokens"));
};
write_token_fields(oauth, tok);
if let Some(creds) = profile.credentials.as_ref() {
let _ = stage_rotated_credentials(name, creds);
}
if save_profile(profile).is_err() {
return Err(anyhow::anyhow!("failed to persist rotated tokens"));
}
clear_staged_credentials(name);
Ok(())
})
}
fn active_link_diverged(config: &AppConfig) -> bool {
config.state.active_profile.as_deref().is_some_and(|name| {
matches!(
classify_credentials_link(name).ok(),
Some(LinkState::Diverged)
)
})
}
#[cfg(test)]
#[path = "../tests/inline/oauth.rs"]
mod tests;