Skip to main content

shunt/
proxy.rs

1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3
4use axum::extract::{Request, State};
5use axum::http::StatusCode;
6use axum::response::{IntoResponse, Response};
7use axum::routing::{get, post};
8use axum::Router;
9use bytes::Bytes;
10use serde_json::json;
11use tokio::sync::RwLock;
12use tracing::{error, warn};
13
14use crate::config::{state_path, Config, CredentialsStore};
15use crate::forwarder::Forwarder;
16use crate::oauth::OAuthCredential;
17use crate::provider::Provider;
18use crate::quota;
19use crate::router;
20use crate::state::StateStore;
21
22#[derive(Clone)]
23struct AppState {
24    config: Arc<Config>,
25    forwarder: Arc<Forwarder>,
26    state: StateStore,
27    /// Live credentials — can be refreshed at runtime without restarting.
28    credentials: Arc<RwLock<HashMap<String, OAuthCredential>>>,
29    /// Epoch-ms when this proxy instance started.
30    started_ms: u64,
31    /// If set, /v1/chat/completions requests are translated and forwarded here
32    /// (the Anthropic proxy base URL, e.g. "http://127.0.0.1:8082").
33    anthropic_base_url: Option<String>,
34}
35
36pub fn create_app(config: Config) -> anyhow::Result<Router> {
37    let (app, _) = create_app_with_state(config, StateStore::load(&state_path()), None)?;
38    Ok(app)
39}
40
41/// Shared live credentials map — can be written to without restarting the proxy.
42pub type LiveCredentials = Arc<RwLock<HashMap<String, OAuthCredential>>>;
43
44pub fn create_app_with_state(
45    config: Config,
46    state: StateStore,
47    anthropic_base_url: Option<String>,
48) -> anyhow::Result<(Router, LiveCredentials)> {
49    let forwarder = Forwarder::new(&config.server.upstream_url, config.server.request_timeout_secs)?;
50
51    // Accounts with no credential are shown in status but skipped during routing.
52    // Mark them disabled immediately so the router ignores them.
53    for a in config.accounts.iter().filter(|a| a.credential.is_none()) {
54        state.set_auth_failed(&a.name);
55    }
56
57    let credentials: LiveCredentials = Arc::new(RwLock::new(
58        config.accounts.iter()
59            .filter_map(|a| a.credential.as_ref().map(|c| (a.name.clone(), c.clone())))
60            .collect::<HashMap<_, _>>(),
61    ));
62
63    let app_state = AppState {
64        config: Arc::new(config),
65        forwarder: Arc::new(forwarder),
66        state,
67        credentials: Arc::clone(&credentials),
68        started_ms: now_ms(),
69        anthropic_base_url,
70    };
71
72    // Register proxy routes appropriate for the provider.
73    // Anthropic: explicit paths only (maintains existing behaviour).
74    // OpenAI/others: wildcard catches all paths; also expose OpenAI-compat
75    //   endpoints that translate to Claude when anthropic_base_url is set.
76    let provider = app_state.config.accounts.first()
77        .map(|a| &a.provider)
78        .cloned()
79        .unwrap_or_default();
80
81    let proxy_routes = match provider {
82        Provider::Anthropic => Router::new()
83            .route("/v1/messages", post(proxy_handler))
84            .route("/v1/messages/count_tokens", post(proxy_handler)),
85        Provider::OpenAI => Router::new()
86            .route("/v1/chat/completions", post(openai_compat_handler))
87            .route("/v1/models", get(openai_models_handler))
88            .fallback(proxy_handler),
89    };
90
91    let app = Router::new()
92        .route("/health", get(health))
93        .route("/status", get(status_handler))
94        .route("/use", post(use_handler))
95        .merge(proxy_routes)
96        .with_state(app_state);
97
98    Ok((app, credentials))
99}
100
101async fn health() -> impl IntoResponse {
102    axum::Json(json!({"status": "ok"}))
103}
104
105async fn status_handler(State(s): State<AppState>) -> impl IntoResponse {
106    let account_states = s.state.account_states();
107    let quotas = s.state.quota_snapshot();
108    let rate_limits = s.state.rate_limit_snapshot();
109
110    let accounts: Vec<_> = s.config.accounts.iter().map(|a| {
111        let st = account_states.get(&a.name);
112        let avail_status = if st.map(|s| s.auth_failed).unwrap_or(false) {
113            "reauth_required"
114        } else if st.map(|s| s.disabled).unwrap_or(false) {
115            "disabled"
116        } else if s.state.is_available(&a.name) {
117            "available"
118        } else {
119            "cooling"
120        };
121
122        let quota = quotas.get(&a.name);
123        let window_expires_ms = quota.and_then(|q| q.window_expires_ms());
124        let window_expires_ms = window_expires_ms.filter(|&e| e > now_ms());
125        let tokens_used = quota.map(|q| json!({
126            "input": q.input_tokens,
127            "output": q.output_tokens,
128            "total": q.total_tokens(),
129        }));
130
131        let rl = rate_limits.get(&a.name);
132        let rate_limit = rl.map(|r| json!({
133            "utilization_5h": r.utilization_5h,
134            "reset_5h": r.reset_5h,
135            "status_5h": r.status_5h,
136            "utilization_7d": r.utilization_7d,
137            "reset_7d": r.reset_7d,
138            "status_7d": r.status_7d,
139            "representative_claim": r.representative_claim,
140            "updated_ms": r.updated_ms,
141        }));
142
143        let acc_state = account_states.get(&a.name);
144        let email = a.credential.as_ref().and_then(|c| c.email.as_deref()).map(|e| e.to_owned());
145        let disabled = acc_state.map(|s| s.disabled).unwrap_or(false);
146        let auth_failed = acc_state.map(|s| s.auth_failed).unwrap_or(false);
147        let cooldown_until_ms = acc_state.map(|s| s.cooldown_until_ms).unwrap_or(0);
148        let utilization_5h = rl.and_then(|r| r.utilization_5h).unwrap_or(0.0);
149        let reset_5h = rl.and_then(|r| r.reset_5h);
150        let total_tokens = quota.map(|q| q.total_tokens()).unwrap_or(0);
151        let available = s.state.is_available(&a.name);
152
153        json!({
154            "name": a.name,
155            "email": email,
156            "plan_type": a.plan_type,
157            "status": avail_status,
158            "available": available,
159            "disabled": disabled,
160            "auth_failed": auth_failed,
161            "cooldown_until_ms": cooldown_until_ms,
162            "utilization_5h": utilization_5h,
163            "reset_5h": reset_5h,
164            "total_tokens": total_tokens,
165            "window_expires_ms": window_expires_ms,
166            "tokens_used": tokens_used,
167            "rate_limit": rate_limit,
168        })
169    }).collect();
170
171    let recent_requests = s.state.recent_requests_snapshot();
172    let savings = s.state.savings_snapshot();
173
174    axum::Json(json!({
175        "version": env!("CARGO_PKG_VERSION"),
176        "started_ms": s.started_ms,
177        "accounts": accounts,
178        "pinned_account": s.state.get_pinned(),
179        "last_used_account": s.state.get_last_used(),
180        "recent_requests": recent_requests,
181        "savings": savings,
182    }))
183}
184
185async fn use_handler(
186    State(s): State<AppState>,
187    axum::Json(body): axum::Json<serde_json::Value>,
188) -> impl IntoResponse {
189    let account = body["account"].as_str().map(|s| s.to_owned());
190    // Validate the account name exists (unless clearing to auto)
191    if let Some(ref name) = account {
192        if name != "auto" && !s.config.accounts.iter().any(|a| &a.name == name) {
193            return axum::Json(json!({
194                "error": format!("unknown account '{name}'")
195            }));
196        }
197        let pinned = if name == "auto" { None } else { Some(name.clone()) };
198        s.state.set_pinned(pinned);
199        axum::Json(json!({ "pinned": name }))
200    } else {
201        s.state.set_pinned(None);
202        axum::Json(json!({ "pinned": null }))
203    }
204}
205
206fn now_ms() -> u64 {
207    use std::time::{SystemTime, UNIX_EPOCH};
208    SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis() as u64
209}
210
211async fn proxy_handler(
212    State(s): State<AppState>,
213    req: Request,
214) -> Result<Response, ProxyError> {
215    // Remote auth: if a remote_key is configured, the client must supply it as x-api-key.
216    if let Some(ref expected) = s.config.server.remote_key {
217        let provided = req.headers()
218            .get("x-api-key")
219            .and_then(|v| v.to_str().ok())
220            .unwrap_or("");
221        if provided != expected {
222            return Err(ProxyError::Unauthorized);
223        }
224    }
225
226    let method = req.method().as_str().to_owned();
227    let path = req.uri().path().to_owned();
228    let headers = req.headers().clone();
229
230    let body_bytes: Bytes = axum::body::to_bytes(req.into_body(), usize::MAX)
231        .await
232        .map_err(|_| ProxyError::BodyRead)?;
233
234    let model = serde_json::from_slice::<serde_json::Value>(&body_bytes)
235        .ok()
236        .and_then(|v| v["model"].as_str().map(|s| s.to_owned()))
237        .unwrap_or_default();
238    let req_start_ms = now_ms();
239
240    let fp = router::fingerprint(&body_bytes);
241    let fp_ref = fp.as_deref();
242
243    let mut tried: HashSet<String> = HashSet::new();
244    // Track accounts we've already attempted a token refresh for this request.
245    let mut refreshed: HashSet<String> = HashSet::new();
246    // Total wait budget: up to 5 hours (Claude's rate-limit reset window).
247    let wait_deadline_ms = now_ms() + 5 * 60 * 60 * 1_000;
248
249    loop {
250        let account = match router::pick_account(
251            &s.config.accounts, &s.state, fp_ref, &tried,
252            s.config.server.sticky_ttl_ms, s.config.server.expiry_soon_secs,
253        ) {
254            Some(a) => a,
255            None => {
256                // Check whether any accounts are just temporarily cooling down
257                // (429/529 backoff) rather than permanently disabled / auth_failed.
258                // If so, wait for the soonest one to recover and retry.
259                let account_states = s.state.account_states();
260                let now = now_ms();
261                let soonest_ms = s.config.accounts.iter()
262                    .filter_map(|a| {
263                        let st = account_states.get(&a.name)?;
264                        if st.disabled { return None; } // auth_failed or permanently off
265                        if st.cooldown_until_ms > now { Some(st.cooldown_until_ms) } else { None }
266                    })
267                    .min();
268
269                match soonest_ms {
270                    Some(wake_ms) if wake_ms <= wait_deadline_ms => {
271                        let wait_ms = wake_ms.saturating_sub(now_ms()) + 50; // +50 ms buffer
272                        warn!(wait_ms, "all accounts cooling — waiting for next available account");
273                        tokio::time::sleep(std::time::Duration::from_millis(wait_ms)).await;
274                        tried.clear(); // accounts may have recovered; try them again
275                    }
276                    _ => return Err(ProxyError::AllAccountsUnavailable),
277                }
278                continue;
279            }
280        };
281
282        let account_name = account.name.clone();
283
284        // Use the live (possibly refreshed) token rather than the one baked into config.
285        // For OpenAI/chatgpt.com accounts, use the id_token (short-lived OIDC JWT) as
286        // the bearer — chatgpt.com's API authenticates via id_token, not access_token.
287        let token = {
288            let creds = s.credentials.read().await;
289            let cred = creds.get(&account_name)
290                .cloned()
291                .or_else(|| account.credential.clone());
292            match cred {
293                Some(c) if account.provider == crate::provider::Provider::OpenAI => {
294                    c.id_token.unwrap_or(c.access_token)
295                }
296                Some(c) => c.access_token,
297                None => String::new(),
298            }
299        };
300
301        let response = s.forwarder
302            .forward(&method, &path, body_bytes.clone(), &headers, account, &token)
303            .await
304            .map_err(|e| {
305                error!("Forward error: {:#}", e);
306                ProxyError::Upstream
307            })?;
308
309        match response.status().as_u16() {
310            200..=299 => {
311                s.state.set_last_used(&account_name);
312                if let Some(info) = account.provider.parse_rate_limits(response.headers()) {
313                    s.state.update_rate_limits(&account_name, info);
314                }
315                return Ok(tap_usage(response, &s.state, &account_name, &model, req_start_ms).await);
316            }
317            429 => {
318                let info = account.provider.parse_rate_limits(response.headers());
319                // Sleep until the actual reset time if the headers tell us when that is;
320                // otherwise fall back to 60s so we don't hammer the API.
321                let cooldown_ms = info.as_ref()
322                    .and_then(|i| i.reset_5h.or(i.reset_7d))
323                    .map(|reset_secs| {
324                        let reset_ms = reset_secs.saturating_mul(1_000);
325                        reset_ms.saturating_sub(now_ms()).saturating_add(500) // +500ms buffer
326                    })
327                    .unwrap_or(60_000);
328                warn!(account = %account_name, cooldown_ms, "429 rate-limited — cooling until reset");
329                if let Some(info) = info {
330                    s.state.update_rate_limits(&account_name, info);
331                }
332                s.state.set_cooldown(&account_name, cooldown_ms);
333                tried.insert(account_name);
334            }
335            529 => {
336                warn!(account = %account_name, "529 overloaded — cooling 30s");
337                if let Some(info) = account.provider.parse_rate_limits(response.headers()) {
338                    s.state.update_rate_limits(&account_name, info);
339                }
340                s.state.set_cooldown(&account_name, 30_000);
341                tried.insert(account_name);
342            }
343            401 => {
344                if !refreshed.contains(&account_name) {
345                    // Access token invalidated (e.g. user logged out) — try refresh.
346                    let cred = {
347                        let creds = s.credentials.read().await;
348                        creds.get(&account_name).cloned()
349                            .or_else(|| account.credential.clone())
350                    };
351                    let Some(cred) = cred else {
352                        tried.insert(account_name);
353                        continue;
354                    };
355                    match tokio::time::timeout(
356                        std::time::Duration::from_secs(10),
357                        account.provider.refresh_token(&cred),
358                    ).await {
359                        Ok(Ok(fresh)) => {
360                            warn!(account = %account_name, "401 — token refreshed, retrying");
361                            {
362                                let mut creds = s.credentials.write().await;
363                                creds.insert(account_name.clone(), fresh.clone());
364                            }
365                            // Persist to disk so the refreshed token survives a restart.
366                            let name = account_name.clone();
367                            let fresh = fresh.clone();
368                            tokio::task::spawn_blocking(move || {
369                                let mut store = CredentialsStore::load();
370                                store.accounts.insert(name, fresh.clone());
371                                store.save().ok();
372                                if fresh.id_token.is_some() {
373                                    crate::oauth::write_codex_auth_file(&fresh);
374                                }
375                            });
376                            // Mark as refreshed but don't add to tried — retry this account.
377                            refreshed.insert(account_name);
378                        }
379                        _ => {
380                            // Refresh failed/timed out — cool down, don't permanently disable.
381                            error!(account = %account_name, "401 — token refresh failed, cooling 5min");
382                            s.state.set_cooldown(&account_name, 5 * 60_000);
383                            tried.insert(account_name);
384                        }
385                    }
386                } else {
387                    // Already refreshed once and still 401 — cool down this account.
388                    error!(account = %account_name, "401 after refresh — cooling 5min");
389                    s.state.set_cooldown(&account_name, 5 * 60_000);
390                    tried.insert(account_name);
391                }
392            }
393            403 => {
394                // Forbidden — subscription lapsed or org restriction; refreshing won't help.
395                error!(account = %account_name, "403 forbidden — cooling 30min");
396                s.state.set_cooldown(&account_name, 30 * 60_000);
397                tried.insert(account_name);
398            }
399            _ => {
400                // 400, 404, 500, etc. — return as-is, no retry
401                return Ok(response);
402            }
403        }
404    }
405}
406
407// ---------------------------------------------------------------------------
408// Usage extraction
409// ---------------------------------------------------------------------------
410
411/// Intercept a successful response to record token usage, then pass it through.
412///
413/// - Streaming: wraps the body stream with an SSE scanner (zero latency).
414/// - Non-streaming: buffers the body, parses usage, rebuilds the response.
415async fn tap_usage(
416    resp: Response,
417    state: &StateStore,
418    account: &str,
419    model: &str,
420    req_start_ms: u64,
421) -> Response {
422    use axum::body::Body;
423    use crate::state::RequestLog;
424
425    if quota::is_streaming_response(&resp) {
426        let state = state.clone();
427        let account = account.to_owned();
428        let model = model.to_owned();
429        let on_complete = Arc::new(move |input: u64, output: u64| {
430            state.record_usage(&account, input, output);
431            state.record_global(&model, input, output);
432            state.record_request(RequestLog {
433                ts_ms: req_start_ms,
434                account: account.clone(),
435                model: model.clone(),
436                status: 200,
437                input_tokens: input,
438                output_tokens: output,
439                duration_ms: now_ms().saturating_sub(req_start_ms),
440            });
441        });
442        let (parts, body) = resp.into_parts();
443        let wrapped = quota::wrap_streaming_body(body, on_complete);
444        return Response::from_parts(parts, wrapped);
445    }
446
447    // Non-streaming: buffer, extract, rebuild
448    let (parts, body) = resp.into_parts();
449    let bytes = match axum::body::to_bytes(body, 64 * 1024 * 1024).await {
450        Ok(b) => b,
451        Err(_) => return Response::from_parts(parts, Body::empty()),
452    };
453    let (input, output) = quota::extract_usage_from_json(&bytes);
454    state.record_usage(account, input, output);
455    state.record_global(model, input, output);
456    state.record_request(RequestLog {
457        ts_ms: req_start_ms,
458        account: account.to_owned(),
459        model: model.to_owned(),
460        status: 200,
461        input_tokens: input,
462        output_tokens: output,
463        duration_ms: now_ms().saturating_sub(req_start_ms),
464    });
465    Response::from_parts(parts, Body::from(bytes))
466}
467
468
469// ---------------------------------------------------------------------------
470// Rate limit prefetch
471// ---------------------------------------------------------------------------
472
473/// For any account with no rate-limit data yet, make a cheap request directly
474/// to the upstream API so we populate metrics without waiting for a real user
475/// request. Runs as a background task after startup.
476pub async fn prefetch_rate_limits(config: Arc<Config>, state: StateStore) {
477    let client = reqwest::Client::builder()
478        .timeout(std::time::Duration::from_secs(20))
479        .build()
480        .unwrap_or_default();
481
482    for account in &config.accounts {
483        // Skip if we already have data for this account.
484        let rl = state.rate_limit_snapshot();
485        if let Some(r) = rl.get(&account.name) {
486            if r.utilization_5h.is_some() || r.utilization_7d.is_some() {
487                continue;
488            }
489        }
490
491        // Skip accounts with no credentials or no prefetch support.
492        let creds = match account.credential.clone() {
493            Some(c) => c,
494            None => continue,
495        };
496
497        let Some((path, body)) = account.provider.prefetch_request() else {
498            // No POST prefetch for this provider — do a lightweight GET auth check instead.
499            if let Some(probe_path) = account.provider.auth_probe_get_path() {
500                auth_probe_get(&client, probe_path, account, &state).await;
501            }
502            continue;
503        };
504        let url = format!("{}{}", config.server.upstream_url, path);
505
506        let resp = prefetch_send(&client, &url, &account.provider, &creds.access_token, &body).await;
507
508        let r = match resp {
509            Ok(r) => r,
510            Err(e) => { tracing::warn!(account = %account.name, "prefetch failed: {e}"); continue; }
511        };
512
513        if r.status() == reqwest::StatusCode::UNAUTHORIZED {
514            tracing::info!(account = %account.name, "prefetch: token expired, refreshing");
515            let fresh = match account.provider.refresh_token(&creds).await {
516                Ok(f) => f,
517                Err(e) => {
518                    tracing::warn!(account = %account.name, "token refresh failed: {e}");
519                    state.set_auth_failed(&account.name);
520                    continue;
521                }
522            };
523            let mut store = crate::config::CredentialsStore::load();
524            store.accounts.insert(account.name.clone(), fresh.clone());
525            store.save().ok();
526            if fresh.id_token.is_some() {
527                crate::oauth::write_codex_auth_file(&fresh);
528            }
529
530            match prefetch_send(&client, &url, &account.provider, &fresh.access_token, &body).await {
531                Ok(r2) if r2.status() == reqwest::StatusCode::UNAUTHORIZED => {
532                    tracing::error!(account = %account.name, "401 after refresh — needs re-authorization");
533                    state.set_auth_failed(&account.name);
534                }
535                Ok(r2) => {
536                    if let Some(info) = account.provider.parse_rate_limits(r2.headers()) {
537                        state.update_rate_limits(&account.name, info);
538                    }
539                }
540                Err(e) => tracing::warn!(account = %account.name, "prefetch retry failed: {e}"),
541            }
542        } else {
543            tracing::info!(account = %account.name, status = %r.status(), "prefetch response");
544            if let Some(info) = account.provider.parse_rate_limits(r.headers()) {
545                state.update_rate_limits(&account.name, info);
546            }
547        }
548    }
549}
550
551/// Build and send a prefetch request for the given provider + token.
552async fn prefetch_send(
553    client: &reqwest::Client,
554    url: &str,
555    provider: &crate::provider::Provider,
556    token: &str,
557    body: &serde_json::Value,
558) -> anyhow::Result<reqwest::Response> {
559    let mut headers = reqwest::header::HeaderMap::new();
560    provider.inject_auth_headers(&mut headers, token)?;
561    for (name, value) in provider.prefetch_extra_headers() {
562        headers.insert(
563            reqwest::header::HeaderName::from_bytes(name.as_bytes())?,
564            reqwest::header::HeaderValue::from_static(value),
565        );
566    }
567    Ok(client.post(url).headers(headers).json(body).send().await?)
568}
569
570/// GET a cheap endpoint to verify credentials are still valid for providers that
571/// don't expose rate-limit headers (e.g. OpenAI). On 401, attempts a token refresh;
572/// marks the account as `reauth_required` if the refresh also fails.
573async fn auth_probe_get(
574    client: &reqwest::Client,
575    path: &str,
576    account: &crate::config::AccountConfig,
577    state: &StateStore,
578) {
579    let creds = match account.credential.clone() {
580        Some(c) => c,
581        None => return,
582    };
583    let upstream = match account.provider {
584        crate::provider::Provider::OpenAI => "https://chatgpt.com",
585        crate::provider::Provider::Anthropic => "https://api.anthropic.com",
586    };
587    let url = format!("{}{}", upstream, path);
588
589    let do_get = |token: &str| -> reqwest::RequestBuilder {
590        let mut headers = reqwest::header::HeaderMap::new();
591        let _ = account.provider.inject_auth_headers(&mut headers, token);
592        client.get(&url).headers(headers)
593    };
594
595    // Use id_token for chatgpt.com (same as the proxy handler).
596    let probe_token = creds.id_token.as_deref().unwrap_or(&creds.access_token);
597    let resp = match do_get(probe_token).send().await {
598        Ok(r) => r,
599        Err(e) => { tracing::warn!(account = %account.name, "auth probe failed: {e}"); return; }
600    };
601
602    if resp.status() == reqwest::StatusCode::UNAUTHORIZED {
603        tracing::info!(account = %account.name, "auth probe: access token rejected, refreshing");
604        let fresh = match account.provider.refresh_token(&creds).await {
605            Ok(f) => f,
606            Err(e) => {
607                tracing::warn!(account = %account.name, "token refresh failed: {e}");
608                state.set_auth_failed(&account.name);
609                return;
610            }
611        };
612        let mut store = crate::config::CredentialsStore::load();
613        store.accounts.insert(account.name.clone(), fresh.clone());
614        store.save().ok();
615        if fresh.id_token.is_some() {
616            crate::oauth::write_codex_auth_file(&fresh);
617        }
618
619        let fresh_token = fresh.id_token.as_deref().unwrap_or(&fresh.access_token);
620        match do_get(fresh_token).send().await {
621            Ok(r2) if r2.status() == reqwest::StatusCode::UNAUTHORIZED => {
622                tracing::error!(account = %account.name, "401 after refresh — needs re-authorization");
623                state.set_auth_failed(&account.name);
624            }
625            Ok(_) => tracing::info!(account = %account.name, "auth probe ok after refresh"),
626            Err(e) => tracing::warn!(account = %account.name, "auth probe retry failed: {e}"),
627        }
628    } else {
629        tracing::info!(account = %account.name, status = %resp.status(), "auth probe ok");
630        // Access token is valid. Do NOT refresh here — rotating the refresh_token races
631        // with codex CLI, which also tries to refresh at startup using the same token.
632        // Proactive refreshing is handled solely by openai_token_refresh_loop.
633    }
634}
635
636// ---------------------------------------------------------------------------
637// Proactive OpenAI token refresh loop
638// ---------------------------------------------------------------------------
639
640/// Returns true if the id_token inside `cred` has fewer than `threshold_mins`
641/// minutes remaining, or if there is no id_token / it cannot be parsed.
642fn id_token_expires_soon(cred: &crate::oauth::OAuthCredential, threshold_mins: u64) -> bool {
643    let Some(ref id_tok) = cred.id_token else { return true };
644    let Some(exp_ms) = crate::oauth::jwt_exp_ms(id_tok) else { return true };
645    let now_ms = std::time::SystemTime::now()
646        .duration_since(std::time::UNIX_EPOCH)
647        .unwrap_or_default()
648        .as_millis() as u64;
649    exp_ms < now_ms + threshold_mins * 60 * 1_000
650}
651
652/// Sync live_creds from auth.json if auth.json has a newer token.
653///
654/// Codex CLI refreshes its own token and writes auth.json. Before we refresh,
655/// we pull that in so we don't use a stale refresh_token that codex already rotated.
656async fn sync_live_creds_from_auth_json(
657    account_name: &str,
658    live_creds: &LiveCredentials,
659) {
660    let Some(from_file) = crate::oauth::read_codex_credentials() else { return };
661    let current_exp = live_creds.read().await
662        .get(account_name)
663        .map(|c| c.expires_at)
664        .unwrap_or(0);
665    if from_file.expires_at > current_exp {
666        tracing::info!(account = %account_name, "synced fresher token from auth.json");
667        live_creds.write().await.insert(account_name.to_owned(), from_file);
668    }
669}
670
671/// Perform a single proactive refresh for one account and persist the result.
672async fn do_proactive_refresh(
673    account: &crate::config::AccountConfig,
674    creds: &crate::oauth::OAuthCredential,
675    live_creds: &LiveCredentials,
676    state: &StateStore,
677) {
678    tracing::info!(account = %account.name, "proactive OpenAI token refresh");
679    match account.provider.refresh_token(creds).await {
680        Ok(fresh) => {
681            tracing::info!(account = %account.name, "proactive refresh ok — auth.json updated");
682            {
683                let mut map = live_creds.write().await;
684                map.insert(account.name.clone(), fresh.clone());
685            }
686            let mut store = crate::config::CredentialsStore::load();
687            store.accounts.insert(account.name.clone(), fresh.clone());
688            store.save().ok();
689            if fresh.id_token.is_some() {
690                crate::oauth::write_codex_auth_file(&fresh);
691            }
692            state.clear_auth_failed(&account.name);
693        }
694        Err(e) => {
695            tracing::warn!(account = %account.name, "proactive refresh failed: {e}");
696            state.set_auth_failed(&account.name);
697        }
698    }
699}
700
701
702/// Keeps shunt's live credentials in sync with Codex CLI's auth.json.
703///
704/// Strategy: never proactively rotate the refresh_token — that races with
705/// Codex CLI's own refresh logic and causes "invalid_grant" errors. Instead,
706/// just periodically sync from auth.json so shunt picks up whatever Codex wrote.
707/// On-demand refresh (401 handler) covers the case where Codex isn't running
708/// and the token has actually expired.
709pub async fn openai_token_refresh_loop(
710    config: Arc<Config>,
711    state: StateStore,
712    live_creds: LiveCredentials,
713) {
714    // Startup: sync from auth.json first (Codex may have refreshed since shunt last ran).
715    for account in config.accounts.iter()
716        .filter(|a| a.provider == crate::provider::Provider::OpenAI)
717    {
718        if state.account_states().get(&account.name).map(|s| s.auth_failed).unwrap_or(false) {
719            continue;
720        }
721        sync_live_creds_from_auth_json(&account.name, &live_creds).await;
722
723        let creds = {
724            let map = live_creds.read().await;
725            map.get(&account.name).cloned().or_else(|| account.credential.clone())
726        };
727        if let Some(creds) = creds {
728            if id_token_expires_soon(&creds, 2) {
729                // Token is already dead — refresh now so shunt can serve requests immediately.
730                // (Codex is unlikely to be running at the exact same moment with a dead token.)
731                do_proactive_refresh(account, &creds, &live_creds, &state).await;
732            } else {
733                tracing::info!(account = %account.name, "id_token fresh at startup");
734            }
735        }
736    }
737
738    // Periodic sync every 5 minutes — picks up any token Codex CLI has written.
739    // No proactive refresh: Codex owns the refresh lifecycle; shunt uses what Codex produces.
740    loop {
741        tokio::time::sleep(std::time::Duration::from_secs(5 * 60)).await;
742        for account in config.accounts.iter()
743            .filter(|a| a.provider == crate::provider::Provider::OpenAI)
744        {
745            sync_live_creds_from_auth_json(&account.name, &live_creds).await;
746        }
747    }
748}
749
750// ---------------------------------------------------------------------------
751// Error type
752// ---------------------------------------------------------------------------
753
754enum ProxyError {
755    BodyRead,
756    Upstream,
757    AllAccountsUnavailable,
758    Unauthorized,
759}
760
761impl IntoResponse for ProxyError {
762    fn into_response(self) -> Response {
763        let (status, msg) = match self {
764            ProxyError::BodyRead => (StatusCode::BAD_REQUEST, "failed to read request body"),
765            ProxyError::Upstream => (StatusCode::BAD_GATEWAY, "upstream request failed"),
766            ProxyError::AllAccountsUnavailable => {
767                (StatusCode::SERVICE_UNAVAILABLE, "all accounts are on cooldown or disabled")
768            }
769            ProxyError::Unauthorized => (StatusCode::UNAUTHORIZED, "invalid or missing api key"),
770        };
771
772        (status, axum::Json(json!({
773            "type": "error",
774            "error": {"type": "api_error", "message": msg}
775        }))).into_response()
776    }
777}
778
779// ---------------------------------------------------------------------------
780// Recovery watcher — periodically retries token refresh for auth_failed accounts
781// ---------------------------------------------------------------------------
782
783/// Runs as a background task. Every 2 minutes, tries to refresh tokens for any
784/// auth_failed account. If refresh succeeds the account is brought back online
785/// without a process restart. If all accounts remain unrecoverable, fires a
786/// macOS notification (at most once per hour).
787pub async fn recovery_watcher(
788    config: Arc<Config>,
789    state: StateStore,
790    credentials: LiveCredentials,
791) {
792    use std::time::{Duration, Instant};
793    const CHECK_INTERVAL: Duration = Duration::from_secs(120);
794    const NOTIFY_COOLDOWN: Duration = Duration::from_secs(3600);
795
796    let account_names: Vec<String> = config.accounts.iter().map(|a| a.name.clone()).collect();
797    let mut last_notified: Option<Instant> = None;
798
799    loop {
800        tokio::time::sleep(CHECK_INTERVAL).await;
801
802        let name_refs: Vec<&str> = account_names.iter().map(String::as_str).collect();
803        let failed = state.auth_failed_accounts(&name_refs);
804        if failed.is_empty() {
805            last_notified = None;
806            continue;
807        }
808
809        tracing::warn!(
810            accounts = ?failed,
811            "recovery: {} account(s) auth_failed, attempting token refresh",
812            failed.len()
813        );
814
815        let mut any_recovered = false;
816
817        for name in &failed {
818            let cred = {
819                let map = credentials.read().await;
820                map.get(*name).cloned()
821            };
822            let Some(cred) = cred else { continue };
823            if cred.refresh_token.is_empty() { continue; }
824
825            let provider = config.accounts.iter()
826                .find(|a| a.name == *name)
827                .map(|a| a.provider.clone())
828                .unwrap_or_default();
829
830            let result = tokio::time::timeout(
831                Duration::from_secs(20),
832                provider.refresh_token(&cred),
833            ).await;
834
835            match result {
836                Ok(Ok(fresh)) => {
837                    tracing::info!(account = %name, "recovery: token refreshed — account back online");
838                    {
839                        let mut map = credentials.write().await;
840                        map.insert(name.to_string(), fresh.clone());
841                    }
842                    let name_owned = name.to_string();
843                    let fresh_owned = fresh.clone();
844                    tokio::task::spawn_blocking(move || {
845                        let mut store = crate::config::CredentialsStore::load();
846                        store.accounts.insert(name_owned, fresh_owned.clone());
847                        store.save().ok();
848                        if fresh_owned.id_token.is_some() {
849                            crate::oauth::write_codex_auth_file(&fresh_owned);
850                        }
851                    });
852                    state.clear_auth_failed(name);
853                    any_recovered = true;
854                }
855                Ok(Err(e)) => {
856                    tracing::error!(account = %name, error = %e, "recovery: token refresh failed");
857                }
858                Err(_) => {
859                    tracing::error!(account = %name, "recovery: token refresh timed out");
860                }
861            }
862        }
863
864        if any_recovered {
865            tracing::info!("recovery: at least one account is back online");
866            continue;
867        }
868
869        // All accounts still auth_failed after refresh attempts — notify.
870        let still_failed = state.auth_failed_accounts(&name_refs);
871        if still_failed.len() == account_names.len() {
872            let should_notify = last_notified
873                .map(|t| t.elapsed() >= NOTIFY_COOLDOWN)
874                .unwrap_or(true);
875            if should_notify {
876                error!(
877                    "ALL accounts are offline (auth failed). \
878                     Run `shunt add-account` to re-authorize."
879                );
880                notify_all_accounts_offline();
881                last_notified = Some(Instant::now());
882            }
883        }
884    }
885}
886
887fn notify_all_accounts_offline() {
888    #[cfg(target_os = "macos")]
889    {
890        let _ = std::process::Command::new("osascript")
891            .args(["-e", concat!(
892                r#"display notification "#,
893                r#""All accounts have lost authentication. Run `shunt add-account` to re-authorize." "#,
894                r#"with title "shunt: All Accounts Offline" sound name "Basso""#
895            )])
896            .status();
897    }
898}
899
900// ---------------------------------------------------------------------------
901// OpenAI-compatible API (translates to Anthropic Claude)
902// ---------------------------------------------------------------------------
903//
904// When the OpenAI proxy receives a request at /v1/chat/completions, if an
905// anthropic_base_url is configured, it translates the request to Anthropic
906// Messages format and forwards it to the Anthropic proxy (which handles
907// account selection, token management, and rate limiting).
908// The response is translated back to OpenAI Chat Completions format.
909
910/// Map OpenAI model names → Claude model names.
911fn map_model(openai_model: &str) -> &'static str {
912    match openai_model {
913        m if m.starts_with("claude-") => {
914            // Already a Claude model name — but we need a &'static str, so match known ones
915            // or fall through to default
916            if m.contains("opus")   { "claude-opus-4-6" }
917            else if m.contains("haiku") { "claude-haiku-4-5-20251001" }
918            else                    { "claude-sonnet-4-6" }
919        }
920        "gpt-4o" | "gpt-4.5" | "o1" | "o1-pro" | "o3" | "o3-pro" | "gpt-5" | "gpt-5.5" => {
921            "claude-opus-4-6"
922        }
923        "gpt-4o-mini" | "gpt-4o-mini-2024-07-18" | "o1-mini" | "o3-mini" => {
924            "claude-haiku-4-5-20251001"
925        }
926        _ => "claude-sonnet-4-6",
927    }
928}
929
930/// Translate an OpenAI Chat Completions request body to an Anthropic Messages body.
931fn translate_to_anthropic(body: serde_json::Value) -> serde_json::Value {
932    let model = body["model"].as_str().unwrap_or("gpt-4o");
933    let claude_model = map_model(model).to_owned();
934
935    // Extract system message from messages array.
936    let mut system: Option<String> = None;
937    let mut messages = Vec::new();
938    if let Some(arr) = body["messages"].as_array() {
939        for msg in arr {
940            let role = msg["role"].as_str().unwrap_or("");
941            let content = msg["content"].as_str().unwrap_or("").to_owned();
942            if role == "system" {
943                system = Some(content);
944            } else {
945                messages.push(json!({ "role": role, "content": content }));
946            }
947        }
948    }
949
950    let max_tokens = body["max_tokens"].as_u64().unwrap_or(8096);
951    let stream = body["stream"].as_bool().unwrap_or(false);
952
953    let mut req = json!({
954        "model": claude_model,
955        "messages": messages,
956        "max_tokens": max_tokens,
957        "stream": stream,
958    });
959
960    if let Some(sys) = system {
961        req["system"] = json!(sys);
962    }
963    if let Some(temp) = body.get("temperature") {
964        req["temperature"] = temp.clone();
965    }
966    if let Some(sp) = body.get("stop") {
967        req["stop_sequences"] = sp.clone();
968    }
969
970    req
971}
972
973/// Translate a complete (non-streaming) Anthropic Messages response to OpenAI format.
974fn translate_from_anthropic(body: serde_json::Value) -> serde_json::Value {
975    let id = format!("chatcmpl-{}", &uuid_v4()[..8]);
976    let model = body["model"].as_str().unwrap_or("claude-sonnet-4-6").to_owned();
977    let content = body["content"]
978        .as_array()
979        .and_then(|arr| arr.iter().find_map(|b| b["text"].as_str()))
980        .unwrap_or("")
981        .to_owned();
982    let stop_reason = body["stop_reason"].as_str().unwrap_or("end_turn");
983    let finish_reason = if stop_reason == "end_turn" { "stop" } else { stop_reason };
984    let input_tokens = body["usage"]["input_tokens"].as_u64().unwrap_or(0);
985    let output_tokens = body["usage"]["output_tokens"].as_u64().unwrap_or(0);
986
987    json!({
988        "id": id,
989        "object": "chat.completion",
990        "model": model,
991        "choices": [{
992            "index": 0,
993            "message": { "role": "assistant", "content": content },
994            "finish_reason": finish_reason,
995        }],
996        "usage": {
997            "prompt_tokens": input_tokens,
998            "completion_tokens": output_tokens,
999            "total_tokens": input_tokens + output_tokens,
1000        }
1001    })
1002}
1003
1004fn uuid_v4() -> String {
1005    use crate::oauth::rand_bytes;
1006    let b: [u8; 16] = rand_bytes();
1007    format!("{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
1008        u32::from_be_bytes(b[0..4].try_into().unwrap()),
1009        u16::from_be_bytes(b[4..6].try_into().unwrap()),
1010        u16::from_be_bytes(b[6..8].try_into().unwrap()),
1011        u16::from_be_bytes(b[8..10].try_into().unwrap()),
1012        {
1013            let mut v = 0u64;
1014            for &x in &b[10..16] { v = (v << 8) | x as u64; }
1015            v
1016        }
1017    )
1018}
1019
1020/// GET /v1/models — return Claude models in OpenAI format.
1021async fn openai_models_handler() -> impl IntoResponse {
1022    axum::Json(json!({
1023        "object": "list",
1024        "data": [
1025            { "id": "claude-opus-4-6",           "object": "model", "owned_by": "anthropic" },
1026            { "id": "claude-sonnet-4-6",          "object": "model", "owned_by": "anthropic" },
1027            { "id": "claude-haiku-4-5-20251001",  "object": "model", "owned_by": "anthropic" },
1028        ]
1029    }))
1030}
1031
1032/// POST /v1/chat/completions — translate OpenAI request to Anthropic, proxy through Claude pool.
1033async fn openai_compat_handler(
1034    State(s): State<AppState>,
1035    req: Request,
1036) -> Result<Response, ProxyError> {
1037    let Some(ref anthropic_url) = s.anthropic_base_url else {
1038        // No Anthropic proxy configured — fall back to normal forwarding
1039        return proxy_handler(State(s), req).await;
1040    };
1041
1042    let body_bytes = axum::body::to_bytes(req.into_body(), usize::MAX)
1043        .await
1044        .map_err(|_| ProxyError::BodyRead)?;
1045
1046    let openai_body: serde_json::Value = serde_json::from_slice(&body_bytes)
1047        .unwrap_or(json!({}));
1048
1049    let stream = openai_body["stream"].as_bool().unwrap_or(false);
1050    let anthropic_body = translate_to_anthropic(openai_body);
1051
1052    let client = reqwest::Client::builder()
1053        .timeout(std::time::Duration::from_secs(300))
1054        .build()
1055        .map_err(|_| ProxyError::Upstream)?;
1056
1057    let resp = client
1058        .post(format!("{anthropic_url}/v1/messages"))
1059        .header("content-type", "application/json")
1060        .header("anthropic-version", "2023-06-01")
1061        .header("anthropic-beta", "claude-code-20250219,oauth-2025-04-20")
1062        .header("x-shunt-compat", "openai")
1063        .json(&anthropic_body)
1064        .send()
1065        .await
1066        .map_err(|_| ProxyError::Upstream)?;
1067
1068    if !resp.status().is_success() {
1069        let status = resp.status();
1070        let body = resp.text().await.unwrap_or_default();
1071        let code = status.as_u16();
1072        return Ok(axum::response::Response::builder()
1073            .status(code)
1074            .header("content-type", "application/json")
1075            .body(axum::body::Body::from(body))
1076            .unwrap());
1077    }
1078
1079    if stream {
1080        // Translate Anthropic SSE stream → OpenAI SSE stream
1081        let chat_id = format!("chatcmpl-{}", &uuid_v4()[..8]);
1082        let stream = translate_anthropic_stream(resp, chat_id);
1083        Ok(axum::response::Response::builder()
1084            .status(200)
1085            .header("content-type", "text/event-stream")
1086            .header("cache-control", "no-cache")
1087            .body(axum::body::Body::from_stream(stream))
1088            .unwrap())
1089    } else {
1090        let anthropic_resp: serde_json::Value = resp.json().await.map_err(|_| ProxyError::Upstream)?;
1091        let openai_resp = translate_from_anthropic(anthropic_resp);
1092        Ok(axum::Json(openai_resp).into_response())
1093    }
1094}
1095
1096/// Translate Anthropic SSE events to OpenAI SSE format, yielding raw bytes.
1097fn translate_anthropic_stream(
1098    resp: reqwest::Response,
1099    chat_id: String,
1100) -> impl futures_util::Stream<Item = Result<bytes::Bytes, std::io::Error>> {
1101    use futures_util::StreamExt;
1102
1103    let id = chat_id;
1104    let byte_stream = resp.bytes_stream();
1105
1106    async_stream::stream! {
1107        let mut buf = String::new();
1108        futures_util::pin_mut!(byte_stream);
1109
1110        // Send initial role chunk
1111        let init = format!(
1112            "data: {}\n\n",
1113            serde_json::to_string(&json!({
1114                "id": id,
1115                "object": "chat.completion.chunk",
1116                "choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": null}]
1117            })).unwrap()
1118        );
1119        yield Ok(bytes::Bytes::from(init));
1120
1121        while let Some(chunk) = byte_stream.next().await {
1122            let chunk = match chunk {
1123                Ok(c) => c,
1124                Err(_) => break,
1125            };
1126            buf.push_str(&String::from_utf8_lossy(&chunk));
1127
1128            // Process complete SSE lines
1129            while let Some(nl) = buf.find('\n') {
1130                let line = buf[..nl].trim_end_matches('\r').to_owned();
1131                buf = buf[nl + 1..].to_owned();
1132
1133                if !line.starts_with("data: ") { continue; }
1134                let data = &line["data: ".len()..];
1135                if data == "[DONE]" { continue; }
1136
1137                let Ok(event) = serde_json::from_str::<serde_json::Value>(data) else { continue };
1138                let event_type = event["type"].as_str().unwrap_or("");
1139
1140                let maybe_chunk = match event_type {
1141                    "content_block_delta" => {
1142                        let text = event["delta"]["text"].as_str().unwrap_or("");
1143                        if text.is_empty() { continue; }
1144                        Some(json!({
1145                            "id": id,
1146                            "object": "chat.completion.chunk",
1147                            "choices": [{"index": 0, "delta": {"content": text}, "finish_reason": null}]
1148                        }))
1149                    }
1150                    "message_delta" => {
1151                        let stop_reason = event["delta"]["stop_reason"].as_str().unwrap_or("stop");
1152                        let finish = if stop_reason == "end_turn" { "stop" } else { stop_reason };
1153                        Some(json!({
1154                            "id": id,
1155                            "object": "chat.completion.chunk",
1156                            "choices": [{"index": 0, "delta": {}, "finish_reason": finish}]
1157                        }))
1158                    }
1159                    _ => None,
1160                };
1161
1162                if let Some(c) = maybe_chunk {
1163                    let out = format!("data: {}\n\n", serde_json::to_string(&c).unwrap());
1164                    yield Ok(bytes::Bytes::from(out));
1165                }
1166            }
1167        }
1168
1169        yield Ok(bytes::Bytes::from("data: [DONE]\n\n"));
1170    }
1171}