Compare commits

...
21 changed files with 10073 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
name: rust-replatform
on:
pull_request:
paths:
- "rust/**"
- "docs/rust-replatform.md"
- ".github/workflows/rust-replatform.yml"
push:
branches:
- rust-replatform-v2
paths:
- "rust/**"
- "docs/rust-replatform.md"
- ".github/workflows/rust-replatform.yml"
workflow_dispatch:
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Rust
uses: dtolnay/rust-toolchain@stable
- name: Test
working-directory: rust
run: cargo test -p proxypilot-rs
+100
View File
@@ -0,0 +1,100 @@
# ProxyPilot Rust Replatform
This branch carries the Rust rewrite line for ProxyPilot.
## Branch contract
- Go `main` remains the shipping line while Rust grows.
- Rust lives under [`rust/`](/home/fsos/code-lean/ai-tools/ProxyPilot/rust).
- The Rust line is terminal-first and does not treat the browser dashboard as a required early target.
- The first real milestone is a working Rust executable that can proxy a Codex-compatible request end-to-end.
## Current milestone
`proxypilot-rs` is the first Rust binary in the repo. It currently provides:
- a `run` command that starts a local proxy server
- a `tui` command that opens a minimal terminal operator view
- a TOML config model plus a separate local state file for saved accounts
- explicit Codex-facing routes for `/v1/models`, `/v1/chat/completions`, `/v1/responses`, `/v1/responses/compact`, and Codex direct `/backend-api/codex/responses` aliases
- a local `/v0/runtime/stats` operator surface for runtime-memory counters, auth-health, and last refresh status
- read-only `/v0/management/status`, `/v0/management/config`, and `/v0/management/accounts` endpoints with API key and token material redacted
- CLI account commands for adding, importing, exporting, device-login, refresh, listing, activating, and removing accounts; these manage saved disk state only and do not pretend a running proxy has already adopted the change
- optional `codex.refresh_token_url` config support for redirecting Codex refresh exchanges to a local stub during validation, while preserving the live OpenAI default when unset
- a TUI operator console that shows live runtime stats, runtime-unavailable copy, local accounts, selected-account details, token state labels, terminal actions for activate/refresh/delete, separate selected-account vs active-account refresh handling, and the `r` / `c` reload-clear controls
- runtime credential resolution that prefers the active saved account over the config fallback key
- proactive Codex token refresh when the active saved account is already expired or within the refresh window, plus the existing 401-retry refresh fallback
- end-to-end tests against a mocked upstream server
## Design defaults
- Go is the behavioral reference, not a line-by-line port target.
- The Rust branch is allowed to redesign config and management surfaces.
- The product identity does not change: ProxyPilot still exists to be a local proxy for coding tools.
## Local workflow
From the repo root:
```bash
cd rust
cargo run -p proxypilot-rs -- init
cargo run -p proxypilot-rs -- account add-codex --name primary --api-key sk-...
cargo run -p proxypilot-rs -- account import-codex --file ../auths/codex-example.json --activate
cargo run -p proxypilot-rs -- account export --file proxypilot-rs.accounts.toml
cargo run -p proxypilot-rs -- account import --file proxypilot-rs.accounts.toml
cargo run -p proxypilot-rs -- account import --file proxypilot-rs.accounts.toml --replace
cargo run -p proxypilot-rs -- account login-codex-device --activate
cargo run -p proxypilot-rs -- account refresh-codex
cargo run -p proxypilot-rs -- account remove --name old-account
cargo run -p proxypilot-rs -- run --config proxypilot-rs.toml
```
Run the local Codex-compatible smoke check without touching real provider
accounts:
```bash
cd rust
./scripts/codex-smoke.sh
```
The smoke check starts a local mock upstream, saves a temporary Codex account,
starts the Rust proxy, and verifies `/healthz`, `/v0/runtime/stats`,
`/v1/models`, `/v1/chat/completions`, and `/v1/responses`.
Run the local Claude API-key smoke check:
```bash
cd rust
./scripts/claude-smoke.sh
```
The Claude smoke starts a local mock Anthropic-compatible upstream, starts the
Rust proxy with `providers.active = "claude"`, and verifies Claude API-key
headers on `/v1/models` and `/v1/messages`.
## Current Codex Gaps
The Rust line is not ready to replace the Go Codex surface yet. Current status:
- `/health` and `/healthz` both return Rust health status.
- `/v1/responses/compact` forwards to the active provider upstream.
- `/backend-api/codex/responses` and `/backend-api/codex/responses/compact`
forward through the Codex-compatible `/v1/responses` paths when the active
provider is `codex`; they reject non-Codex active providers instead of
silently routing a Codex direct alias to Claude or another provider.
- `GET /v1/responses` and `GET /backend-api/codex/responses` return explicit
`501 Not Implemented` responses because Rust websocket response proxying is
still deferred.
- Codex websocket streaming
- Codex image generation and image edit handling
- Browser dashboard and broad `/v0/management/**` parity beyond status, config,
and accounts
- Go model registry and model-mapping behavior
Open the TUI with:
```bash
cd rust
cargo run -p proxypilot-rs -- tui --config proxypilot-rs.toml
```
+1
View File
@@ -0,0 +1 @@
target/
+2346
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
[workspace]
members = ["proxypilot-rs"]
resolver = "2"
[workspace.package]
edition = "2024"
license = "MIT"
version = "0.1.0"
[workspace.dependencies]
anyhow = "1.0.100"
axum = { version = "0.8.8", features = ["macros", "json"] }
base64 = "0.22.1"
clap = { version = "4.6.0", features = ["derive"] }
crossterm = "0.29.0"
http = "1.3.1"
ratatui = "0.29.0"
reqwest = { version = "0.12.25", default-features = false, features = ["http2", "json", "rustls-tls"] }
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.145"
tokio = { version = "1.48.0", features = ["macros", "rt-multi-thread", "signal", "time", "sync", "net"] }
toml = "0.9.8"
tower = "0.5.2"
tower-http = { version = "0.6.6", features = ["trace"] }
tracing = "0.1.41"
tracing-subscriber = { version = "0.3.20", features = ["env-filter"] }
url = "2.5.7"
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "proxypilot-rs"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
anyhow.workspace = true
axum.workspace = true
base64.workspace = true
clap.workspace = true
crossterm.workspace = true
http.workspace = true
ratatui.workspace = true
reqwest.workspace = true
serde.workspace = true
serde_json.workspace = true
tokio.workspace = true
toml.workspace = true
tower-http.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
url.workspace = true
[dev-dependencies]
tower = { workspace = true, features = ["util"] }
+703
View File
@@ -0,0 +1,703 @@
use std::fs;
use std::path::Path;
use anyhow::{Context, Result};
use crate::codex;
use crate::config::AppConfig;
use crate::state::{AccountState, ImportedCodexAuth};
fn saved_account_message(provider_label: &str, name: &str, active: bool) -> String {
if active {
format!(
"saved {} account `{}` in local state and marked it active",
provider_label, name
)
} else {
format!("saved {} account `{}` in local state", provider_label, name)
}
}
fn imported_account_message(name: &str, active: bool) -> String {
if active {
format!(
"imported Codex auth `{}` into local state and marked it active",
name
)
} else {
format!("imported Codex auth `{}` into local state", name)
}
}
fn device_login_message(name: &str, active: bool) -> String {
if active {
format!(
"saved Codex device login `{}` in local state and marked it active",
name
)
} else {
format!("saved Codex device login `{}` in local state", name)
}
}
fn refresh_message(name: &str) -> String {
format!("refreshed saved Codex account `{}` in local state", name)
}
fn refresh_mode_label(refresh_token: Option<&str>) -> &'static str {
if refresh_token
.map(|value| !value.trim().is_empty())
.unwrap_or(false)
{
"refreshable"
} else {
"static"
}
}
fn account_list_row(account: &crate::state::AccountEntry, active_name: Option<&str>) -> String {
let marker = if active_name == Some(account.name.as_str()) {
"*"
} else {
"-"
};
let email = account.email.as_deref().unwrap_or("-");
let source = account.source.as_deref().unwrap_or("-");
let plan = account.plan_type.as_deref().unwrap_or("-");
let refresh = refresh_mode_label(account.refresh_token.as_deref());
format!(
"{marker} {:<16} provider={} email={} plan={} refresh={} source={}",
account.name, account.provider, email, plan, refresh, source
)
}
pub fn add_codex_account(
config: &AppConfig,
config_path: &Path,
name: String,
api_key: String,
activate: bool,
) -> Result<()> {
let state_path = config.resolve_state_path(config_path);
let mut state = AccountState::load_or_default(&state_path)?;
state.add_or_replace_codex_account(name.clone(), api_key, activate)?;
state.save(&state_path)?;
println!(
"{}",
saved_account_message(
"Codex",
&name,
state.active_account.as_deref() == Some(name.as_str())
)
);
println!("state file: {}", state_path.display());
Ok(())
}
pub fn add_claude_account(
config: &AppConfig,
config_path: &Path,
name: String,
api_key: String,
activate: bool,
) -> Result<()> {
let state_path = config.resolve_state_path(config_path);
let mut state = AccountState::load_or_default(&state_path)?;
state.add_or_replace_manual_account(
crate::provider::CLAUDE_PROVIDER,
name.clone(),
api_key,
activate,
)?;
state.save(&state_path)?;
println!(
"{}",
saved_account_message(
"Claude",
&name,
state.active_account.as_deref() == Some(name.as_str())
)
);
println!("state file: {}", state_path.display());
Ok(())
}
pub async fn refresh_claude_account(
config: &AppConfig,
config_path: &Path,
name: Option<String>,
) -> Result<()> {
let state_path = config.resolve_state_path(config_path);
let state = AccountState::load_or_default(&state_path)?;
let target = if let Some(name) = name.filter(|value| !value.trim().is_empty()) {
state
.account_by_name_and_provider(&name, crate::provider::CLAUDE_PROVIDER)
.ok_or_else(|| anyhow::anyhow!("no saved Claude account named {}", name))?
} else {
state
.active_account_for_provider(crate::provider::CLAUDE_PROVIDER)
.ok_or_else(|| anyhow::anyhow!("no active Claude account to refresh"))?
};
let _ = target;
anyhow::bail!("Claude refresh is not implemented yet")
}
pub fn list_accounts(config: &AppConfig, config_path: &Path) -> Result<()> {
let state_path = config.resolve_state_path(config_path);
let state = AccountState::load_or_default(&state_path)?;
if state.accounts.is_empty() {
println!("No local Rust accounts saved yet.");
println!("state file: {}", state_path.display());
return Ok(());
}
println!("ProxyPilot Rust local account state");
println!("state file: {}", state_path.display());
println!();
for account in &state.accounts {
println!(
"{}",
account_list_row(account, state.active_account.as_deref())
);
}
Ok(())
}
pub fn activate_account(config: &AppConfig, config_path: &Path, name: String) -> Result<()> {
let state_path = config.resolve_state_path(config_path);
let mut state = AccountState::load_or_default(&state_path)?;
state.activate(&name)?;
state.save(&state_path)?;
println!("local active account set to `{}`", name);
println!("state file: {}", state_path.display());
Ok(())
}
pub fn remove_account(config: &AppConfig, config_path: &Path, name: String) -> Result<()> {
let state_path = config.resolve_state_path(config_path);
let mut state = AccountState::load_or_default(&state_path)?;
state.remove_account(&name)?;
state.save(&state_path)?;
println!("removed account `{}` from local state", name);
match state.active_account.as_deref() {
Some(active) => println!("local active account is now `{}`", active),
None => println!("no local active account remains"),
}
println!("state file: {}", state_path.display());
Ok(())
}
pub fn import_codex_account(
config: &AppConfig,
config_path: &Path,
auth_file: &Path,
name: Option<String>,
activate: bool,
) -> Result<()> {
let raw = fs::read_to_string(auth_file)
.with_context(|| format!("failed to read Codex auth file {}", auth_file.display()))?;
let imported: ImportedCodexAuth = serde_json::from_str(&raw)
.with_context(|| format!("failed to parse Codex auth file {}", auth_file.display()))?;
let resolved_name = name
.filter(|value| !value.trim().is_empty())
.or_else(|| {
if imported.email.trim().is_empty() {
None
} else {
Some(imported.email.trim().to_string())
}
})
.or_else(|| {
auth_file
.file_stem()
.map(|value| value.to_string_lossy().to_string())
})
.unwrap_or_else(|| "codex-import".to_string());
let state_path = config.resolve_state_path(config_path);
let mut state = AccountState::load_or_default(&state_path)?;
state.add_imported_codex_account(
resolved_name.clone(),
imported,
format!("import:{}", auth_file.display()),
activate,
)?;
state.save(&state_path)?;
println!(
"{}",
imported_account_message(
&resolved_name,
state.active_account.as_deref() == Some(resolved_name.as_str())
)
);
println!("source file: {}", auth_file.display());
println!("state file: {}", state_path.display());
Ok(())
}
pub fn export_accounts(config: &AppConfig, config_path: &Path, export_file: &Path) -> Result<()> {
let state_path = config.resolve_state_path(config_path);
let state = AccountState::load_or_default(&state_path)?;
if let Some(parent) = export_file.parent()
&& !parent.as_os_str().is_empty()
{
fs::create_dir_all(parent)
.with_context(|| format!("failed to create export directory {}", parent.display()))?;
}
let raw = toml::to_string_pretty(&state).context("failed to serialize account state export")?;
fs::write(export_file, raw)
.with_context(|| format!("failed to write account export {}", export_file.display()))?;
println!(
"exported {} local account(s) to {}",
state.accounts.len(),
export_file.display()
);
println!("source state file: {}", state_path.display());
Ok(())
}
pub fn import_accounts(
config: &AppConfig,
config_path: &Path,
import_file: &Path,
replace: bool,
) -> Result<()> {
let raw = fs::read_to_string(import_file)
.with_context(|| format!("failed to read account import {}", import_file.display()))?;
let imported: AccountState = toml::from_str(&raw)
.with_context(|| format!("failed to parse account import {}", import_file.display()))?;
let imported_count = imported.accounts.len();
let state_path = config.resolve_state_path(config_path);
let mut state = if replace {
imported
} else {
let mut state = AccountState::load_or_default(&state_path)?;
state.merge_from(imported);
state
};
state.accounts.sort_by(|a, b| a.name.cmp(&b.name));
state.save(&state_path)?;
println!(
"{} {} local account(s) from {}",
if replace { "replaced with" } else { "imported" },
imported_count,
import_file.display()
);
println!("state file: {}", state_path.display());
Ok(())
}
pub async fn login_codex_device(
config: &AppConfig,
config_path: &Path,
name: Option<String>,
activate: bool,
) -> Result<()> {
let result = codex::login_with_device_flow().await?;
let resolved_name = name
.filter(|value| !value.trim().is_empty())
.or_else(|| result.email.clone())
.or_else(|| result.account_id.clone())
.unwrap_or_else(|| "codex-device".to_string());
let state_path = config.resolve_state_path(config_path);
let mut state = AccountState::load_or_default(&state_path)?;
state.add_device_codex_account(resolved_name.clone(), result, activate)?;
state.save(&state_path)?;
println!(
"{}",
device_login_message(
&resolved_name,
state.active_account.as_deref() == Some(resolved_name.as_str())
)
);
println!("state file: {}", state_path.display());
Ok(())
}
pub async fn refresh_codex_account(
config: &AppConfig,
config_path: &Path,
name: Option<String>,
) -> Result<()> {
let state_path = config.resolve_state_path(config_path);
let mut state = AccountState::load_or_default(&state_path)?;
let target = if let Some(name) = name.filter(|value| !value.trim().is_empty()) {
state
.codex_account_by_name(&name)
.ok_or_else(|| anyhow::anyhow!("no saved Codex account named {}", name))?
} else {
state
.active_codex_account()
.ok_or_else(|| anyhow::anyhow!("no active Codex account to refresh"))?
};
let refresh_token = target.refresh_token.as_deref().ok_or_else(|| {
anyhow::anyhow!(
"account `{}` is static and has no refresh token",
target.name
)
})?;
let result = codex::refresh_with_refresh_token_from_config(config, refresh_token).await?;
let refreshed_name = target.name.clone();
state.update_codex_account_tokens(&refreshed_name, result)?;
state.save(&state_path)?;
println!("{}", refresh_message(&refreshed_name));
println!("state file: {}", state_path.display());
Ok(())
}
#[cfg(test)]
mod tests {
use std::fs;
use std::time::{SystemTime, UNIX_EPOCH};
use super::*;
fn temp_paths(label: &str) -> (std::path::PathBuf, std::path::PathBuf) {
let stamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let base = std::env::temp_dir().join(format!("proxypilot-rs-{label}-{stamp}"));
let config_path = base.with_extension("toml");
let state_path = base.with_extension("state.toml");
(config_path, state_path)
}
#[test]
fn list_accounts_marks_refreshability_in_operator_copy() {
assert_eq!(refresh_mode_label(Some("token")), "refreshable");
assert_eq!(refresh_mode_label(None), "static");
assert_eq!(refresh_mode_label(Some(" ")), "static");
}
#[test]
fn account_list_row_marks_active_and_static_accounts_readably() {
let account = crate::state::AccountEntry {
name: "primary".to_string(),
provider: "codex".to_string(),
api_key: "key".to_string(),
refresh_token: None,
id_token: None,
email: Some("dev@example.com".to_string()),
account_id: None,
plan_type: Some("pro".to_string()),
expires_at: None,
source: Some("manual".to_string()),
};
let row = account_list_row(&account, Some("primary"));
assert!(row.starts_with("* primary"));
assert!(row.contains("refresh=static"));
assert!(row.contains("source=manual"));
}
#[test]
fn saved_account_messages_stay_explicit_about_local_state() {
assert_eq!(
saved_account_message("Codex", "primary", true),
"saved Codex account `primary` in local state and marked it active"
);
assert_eq!(
saved_account_message("Codex", "backup", false),
"saved Codex account `backup` in local state"
);
assert_eq!(
imported_account_message("imported", true),
"imported Codex auth `imported` into local state and marked it active"
);
assert_eq!(
device_login_message("device", false),
"saved Codex device login `device` in local state"
);
assert_eq!(
refresh_message("primary"),
"refreshed saved Codex account `primary` in local state"
);
}
#[test]
fn saved_account_messages_can_describe_claude_accounts() {
assert_eq!(
saved_account_message("Claude", "claude-main", true),
"saved Claude account `claude-main` in local state and marked it active"
);
}
#[test]
fn account_list_row_includes_provider_name_for_claude() {
let account = crate::state::AccountEntry {
name: "claude-main".to_string(),
provider: crate::provider::CLAUDE_PROVIDER.to_string(),
api_key: "key".to_string(),
refresh_token: None,
id_token: None,
email: Some("dev@example.com".to_string()),
account_id: None,
plan_type: Some("max".to_string()),
expires_at: None,
source: Some("manual".to_string()),
};
let row = account_list_row(&account, Some("claude-main"));
assert!(row.contains("provider=claude"));
assert!(row.contains("plan=max"));
}
#[tokio::test]
async fn refresh_codex_account_reports_static_accounts_clearly() {
let (config_path, state_path) = temp_paths("static-refresh");
let config = AppConfig {
state: crate::config::StateConfig {
path: state_path.display().to_string(),
},
..AppConfig::default()
};
fs::write(&config_path, AppConfig::example_toml()).unwrap();
let mut state = AccountState::default();
state
.add_or_replace_codex_account("primary".to_string(), "sk-test".to_string(), true)
.unwrap();
state.save(&state_path).unwrap();
let error = refresh_codex_account(&config, &config_path, Some("primary".to_string()))
.await
.unwrap_err()
.to_string();
assert!(error.contains("static"));
assert!(error.contains("no refresh token"));
let _ = fs::remove_file(config_path);
let _ = fs::remove_file(state_path);
}
#[tokio::test]
async fn refresh_codex_account_reports_missing_targets_clearly() {
let (config_path, state_path) = temp_paths("missing-refresh");
let config = AppConfig {
state: crate::config::StateConfig {
path: state_path.display().to_string(),
},
..AppConfig::default()
};
fs::write(&config_path, AppConfig::example_toml()).unwrap();
AccountState::default().save(&state_path).unwrap();
let error = refresh_codex_account(&config, &config_path, Some("missing".to_string()))
.await
.unwrap_err()
.to_string();
assert!(error.contains("no saved Codex account named missing"));
let _ = fs::remove_file(config_path);
let _ = fs::remove_file(state_path);
}
#[test]
fn export_and_import_accounts_round_trip_full_state() {
let (config_path, state_path) = temp_paths("export-import");
let export_path = state_path.with_extension("export.toml");
let config = AppConfig {
state: crate::config::StateConfig {
path: state_path.display().to_string(),
},
..AppConfig::default()
};
fs::write(&config_path, AppConfig::example_toml()).unwrap();
let mut state = AccountState::default();
state
.add_or_replace_codex_account("primary".to_string(), "codex-key".to_string(), true)
.unwrap();
state
.add_or_replace_manual_account(
crate::provider::CLAUDE_PROVIDER,
"claude-main".to_string(),
"claude-key".to_string(),
false,
)
.unwrap();
state.save(&state_path).unwrap();
export_accounts(&config, &config_path, &export_path).unwrap();
fs::remove_file(&state_path).unwrap();
import_accounts(&config, &config_path, &export_path, true).unwrap();
let imported = AccountState::load_or_default(&state_path).unwrap();
assert_eq!(imported.active_account.as_deref(), Some("primary"));
assert_eq!(imported.accounts.len(), 2);
assert_eq!(
imported.codex_account_by_name("primary").unwrap().api_key,
"codex-key"
);
assert_eq!(
imported
.account_by_name_and_provider("claude-main", crate::provider::CLAUDE_PROVIDER)
.unwrap()
.api_key,
"claude-key"
);
let _ = fs::remove_file(config_path);
let _ = fs::remove_file(state_path);
let _ = fs::remove_file(export_path);
}
#[test]
fn import_accounts_merges_without_overwriting_active_account() {
let (config_path, state_path) = temp_paths("merge-import");
let import_path = state_path.with_extension("import.toml");
let config = AppConfig {
state: crate::config::StateConfig {
path: state_path.display().to_string(),
},
..AppConfig::default()
};
fs::write(&config_path, AppConfig::example_toml()).unwrap();
let mut local = AccountState::default();
local
.add_or_replace_codex_account("primary".to_string(), "old-key".to_string(), true)
.unwrap();
local.save(&state_path).unwrap();
let mut imported = AccountState::default();
imported
.add_or_replace_codex_account("primary".to_string(), "new-key".to_string(), true)
.unwrap();
imported
.add_or_replace_manual_account(
crate::provider::CLAUDE_PROVIDER,
"claude-main".to_string(),
"claude-key".to_string(),
false,
)
.unwrap();
imported.save(&import_path).unwrap();
import_accounts(&config, &config_path, &import_path, false).unwrap();
let merged = AccountState::load_or_default(&state_path).unwrap();
assert_eq!(merged.active_account.as_deref(), Some("primary"));
assert_eq!(
merged.codex_account_by_name("primary").unwrap().api_key,
"new-key"
);
assert_eq!(
merged
.account_by_name_and_provider("claude-main", crate::provider::CLAUDE_PROVIDER)
.unwrap()
.api_key,
"claude-key"
);
let _ = fs::remove_file(config_path);
let _ = fs::remove_file(state_path);
let _ = fs::remove_file(import_path);
}
#[tokio::test]
async fn refresh_codex_account_uses_configured_refresh_endpoint() {
use axum::{Json, Router, routing::post};
use serde_json::json;
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use tokio::net::TcpListener;
async fn refresh_handler() -> impl axum::response::IntoResponse {
Json(json!({
"access_token": "refreshed-access",
"refresh_token": "refreshed-refresh",
"id_token": "TEST_ID_TOKEN_PLACEHOLDER",
"expires_in": 3600
}))
}
let refresh_hits = Arc::new(AtomicUsize::new(0));
let refresh_hits_for_handler = refresh_hits.clone();
let refresh_app = Router::new().route(
"/oauth/token",
post(move || {
let refresh_hits_for_handler = refresh_hits_for_handler.clone();
async move {
refresh_hits_for_handler.fetch_add(1, Ordering::SeqCst);
refresh_handler().await
}
}),
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let refresh_addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
axum::serve(listener, refresh_app).await.unwrap();
});
let (config_path, state_path) = temp_paths("refresh-endpoint");
let mut config = AppConfig::default();
config.state.path = state_path.display().to_string();
config.codex.refresh_token_url = format!("http://{refresh_addr}/oauth/token");
fs::write(&config_path, AppConfig::example_toml()).unwrap();
let mut state = AccountState::default();
state
.add_device_codex_account(
"primary".to_string(),
crate::codex::DeviceAuthResult {
access_token: "old-access".to_string(),
refresh_token: "old-refresh".to_string(),
id_token: "old-id".to_string(),
email: Some("refresh@example.com".to_string()),
account_id: Some("acct".to_string()),
plan_type: Some("pro".to_string()),
expires_at: Some("1970-01-01T00:00:00Z".to_string()),
},
true,
)
.unwrap();
state.save(&state_path).unwrap();
refresh_codex_account(&config, &config_path, Some("primary".to_string()))
.await
.unwrap();
assert_eq!(refresh_hits.load(Ordering::SeqCst), 1);
let updated = AccountState::load_or_default(&state_path).unwrap();
let refreshed = updated.codex_account_by_name("primary").unwrap();
assert_eq!(refreshed.api_key, "refreshed-access");
assert_eq!(
refreshed.refresh_token.as_deref(),
Some("refreshed-refresh")
);
// The placeholder id_token does not encode an exp claim, so expires_at
// is derived from the current time + expires_in rather than a fixed value.
assert!(
refreshed.expires_at.is_some(),
"expires_at should be set after refresh"
);
server.abort();
let _ = fs::remove_file(config_path);
let _ = fs::remove_file(state_path);
}
}
+510
View File
@@ -0,0 +1,510 @@
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
pub const EXPIRING_SOON_WINDOW_SECS: i64 = 300;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthHealthState {
Valid,
ExpiringSoon,
Expired,
Static,
Unknown,
}
impl AuthHealthState {
pub fn label(self) -> &'static str {
match self {
Self::Valid => "valid",
Self::ExpiringSoon => "expiring soon",
Self::Expired => "expired",
Self::Static => "static",
Self::Unknown => "unknown",
}
}
pub fn is_refresh_worthy(self) -> bool {
matches!(self, Self::ExpiringSoon | Self::Expired)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthCredentialSource {
ActiveAccount,
ConfigFallbackKey,
NoCredential,
}
impl AuthCredentialSource {
pub fn label(self) -> &'static str {
match self {
Self::ActiveAccount => "saved account",
Self::ConfigFallbackKey => "config fallback key",
Self::NoCredential => "no credential",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthMetadataState {
Present,
Missing,
Malformed,
}
impl AuthMetadataState {
pub fn label(self) -> &'static str {
match self {
Self::Present => "present",
Self::Missing => "missing",
Self::Malformed => "malformed",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthHealthSnapshot {
pub state: AuthHealthState,
pub source: AuthCredentialSource,
pub metadata_state: AuthMetadataState,
pub expires_at: Option<String>,
pub expires_at_unix_secs: Option<i64>,
pub expires_in_secs: Option<i64>,
}
impl AuthHealthSnapshot {
pub fn summary_label(&self) -> &'static str {
self.state.label()
}
pub fn source_label(&self) -> &'static str {
self.source.label()
}
pub fn expiry_detail(&self) -> String {
match self.state {
AuthHealthState::Valid => self
.expires_at
.as_deref()
.map(|value| format!("valid until {}", value))
.unwrap_or_else(|| "valid".to_string()),
AuthHealthState::ExpiringSoon => self
.expires_at
.as_deref()
.map(|value| format!("expiring soon at {}", value))
.unwrap_or_else(|| "expiring soon".to_string()),
AuthHealthState::Expired => self
.expires_at
.as_deref()
.map(|value| format!("expired at {}", value))
.unwrap_or_else(|| "expired".to_string()),
AuthHealthState::Static => match self.source {
AuthCredentialSource::ConfigFallbackKey => "config fallback key".to_string(),
_ => "static access token".to_string(),
},
AuthHealthState::Unknown => match self.metadata_state {
AuthMetadataState::Malformed => self
.expires_at
.as_deref()
.map(|value| format!("malformed expiry metadata ({value})"))
.unwrap_or_else(|| "malformed expiry metadata".to_string()),
AuthMetadataState::Missing => "expiry metadata missing".to_string(),
AuthMetadataState::Present => "auth state unknown".to_string(),
},
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum RefreshStatusKind {
Success,
Failure,
Skipped,
#[default]
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct RefreshStatusSnapshot {
pub kind: RefreshStatusKind,
pub account_name: Option<String>,
pub occurred_at_unix_secs: Option<i64>,
pub message: Option<String>,
}
impl RefreshStatusSnapshot {
pub fn success(account_name: impl Into<String>, occurred_at_unix_secs: i64) -> Self {
Self {
kind: RefreshStatusKind::Success,
account_name: Some(account_name.into()),
occurred_at_unix_secs: Some(occurred_at_unix_secs),
message: None,
}
}
pub fn failure(
account_name: Option<impl Into<String>>,
occurred_at_unix_secs: i64,
message: impl Into<String>,
) -> Self {
Self {
kind: RefreshStatusKind::Failure,
account_name: account_name.map(Into::into),
occurred_at_unix_secs: Some(occurred_at_unix_secs),
message: Some(message.into()),
}
}
pub fn skipped(message: impl Into<String>) -> Self {
Self {
kind: RefreshStatusKind::Skipped,
account_name: None,
occurred_at_unix_secs: None,
message: Some(message.into()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct RuntimeRequestCounters {
pub total_proxied_requests: u64,
pub successful_upstream_responses: u64,
pub auth_refresh_attempts: u64,
pub auth_refresh_failures: u64,
pub upstream_401_count: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RuntimeStatsSnapshot {
pub bind_address: String,
pub upstream_base_url: String,
pub active_account_name: Option<String>,
pub account_count: usize,
pub auth_health: AuthHealthSnapshot,
pub request_counters: RuntimeRequestCounters,
pub last_refresh: RefreshStatusSnapshot,
}
impl RuntimeStatsSnapshot {
pub fn new(
bind_address: impl Into<String>,
upstream_base_url: impl Into<String>,
active_account_name: Option<String>,
account_count: usize,
auth_health: AuthHealthSnapshot,
) -> Self {
Self {
bind_address: bind_address.into(),
upstream_base_url: upstream_base_url.into(),
active_account_name,
account_count,
auth_health,
request_counters: RuntimeRequestCounters::default(),
last_refresh: RefreshStatusSnapshot::default(),
}
}
}
pub fn now_unix_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_secs() as i64)
.unwrap_or_default()
}
pub fn parse_rfc3339_z(value: &str) -> Option<i64> {
if value.len() != 20 || !value.ends_with('Z') {
return None;
}
if value.as_bytes().get(4) != Some(&b'-')
|| value.as_bytes().get(7) != Some(&b'-')
|| value.as_bytes().get(10) != Some(&b'T')
|| value.as_bytes().get(13) != Some(&b':')
|| value.as_bytes().get(16) != Some(&b':')
{
return None;
}
let year = value.get(0..4)?.parse::<i64>().ok()?;
let month = value.get(5..7)?.parse::<i64>().ok()?;
let day = value.get(8..10)?.parse::<i64>().ok()?;
let hour = value.get(11..13)?.parse::<i64>().ok()?;
let minute = value.get(14..16)?.parse::<i64>().ok()?;
let second = value.get(17..19)?.parse::<i64>().ok()?;
if !(1..=12).contains(&month)
|| !(1..=31).contains(&day)
|| !(0..=23).contains(&hour)
|| !(0..=59).contains(&minute)
|| !(0..=59).contains(&second)
{
return None;
}
if day > i64::from(days_in_month(year, month as u32)?) {
return None;
}
let adjusted_year = year - if month <= 2 { 1 } else { 0 };
let era = if adjusted_year >= 0 {
adjusted_year
} else {
adjusted_year - 399
} / 400;
let yoe = adjusted_year - era * 400;
let month_prime = month + if month > 2 { -3 } else { 9 };
let doy = (153 * month_prime + 2) / 5 + day - 1;
if !(0..=365).contains(&doy) {
return None;
}
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146_097 + doe - 719_468;
Some(days * 86_400 + hour * 3_600 + minute * 60 + second)
}
fn days_in_month(year: i64, month: u32) -> Option<u8> {
Some(match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if is_leap_year(year) => 29,
2 => 28,
_ => return None,
})
}
fn is_leap_year(year: i64) -> bool {
let year = year.rem_euclid(400);
year % 4 == 0 && (year % 100 != 0 || year == 0)
}
pub fn evaluate_auth_health(
source: AuthCredentialSource,
refresh_token: Option<&str>,
expires_at: Option<&str>,
now_unix_secs: i64,
) -> AuthHealthSnapshot {
let expires_at = normalize_optional(expires_at);
let refresh_token = normalize_optional(refresh_token);
match source {
AuthCredentialSource::ConfigFallbackKey => AuthHealthSnapshot {
state: AuthHealthState::Static,
source,
metadata_state: if expires_at.is_some() {
AuthMetadataState::Present
} else {
AuthMetadataState::Missing
},
expires_at,
expires_at_unix_secs: None,
expires_in_secs: None,
},
AuthCredentialSource::NoCredential => AuthHealthSnapshot {
state: AuthHealthState::Unknown,
source,
metadata_state: if expires_at.is_some() {
AuthMetadataState::Present
} else {
AuthMetadataState::Missing
},
expires_at: expires_at.clone(),
expires_at_unix_secs: expires_at.as_deref().and_then(parse_rfc3339_z),
expires_in_secs: None,
},
AuthCredentialSource::ActiveAccount => {
if refresh_token.is_none() {
return AuthHealthSnapshot {
state: AuthHealthState::Static,
source,
metadata_state: if expires_at.is_some() {
AuthMetadataState::Present
} else {
AuthMetadataState::Missing
},
expires_at: expires_at.clone(),
expires_at_unix_secs: expires_at.as_deref().and_then(parse_rfc3339_z),
expires_in_secs: None,
};
}
let Some(expires_at_text) = expires_at.clone() else {
return AuthHealthSnapshot {
state: AuthHealthState::Unknown,
source,
metadata_state: AuthMetadataState::Missing,
expires_at: None,
expires_at_unix_secs: None,
expires_in_secs: None,
};
};
let Some(expires_at_unix_secs) = parse_rfc3339_z(&expires_at_text) else {
return AuthHealthSnapshot {
state: AuthHealthState::Unknown,
source,
metadata_state: AuthMetadataState::Malformed,
expires_at: Some(expires_at_text),
expires_at_unix_secs: None,
expires_in_secs: None,
};
};
let expires_in_secs = expires_at_unix_secs - now_unix_secs;
let state = if expires_in_secs <= 0 {
AuthHealthState::Expired
} else if expires_in_secs <= EXPIRING_SOON_WINDOW_SECS {
AuthHealthState::ExpiringSoon
} else {
AuthHealthState::Valid
};
AuthHealthSnapshot {
state,
source,
metadata_state: AuthMetadataState::Present,
expires_at: Some(expires_at_text),
expires_at_unix_secs: Some(expires_at_unix_secs),
expires_in_secs: Some(expires_in_secs),
}
}
}
}
fn normalize_optional(value: Option<&str>) -> Option<String> {
value
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_rfc3339_z_timestamps() {
assert_eq!(parse_rfc3339_z("1970-01-01T00:00:00Z"), Some(0));
assert_eq!(parse_rfc3339_z("1970-01-02T00:00:00Z"), Some(86_400));
}
#[test]
fn rejects_non_rfc3339_z_timestamps() {
assert_eq!(parse_rfc3339_z("2026-04-05 12:00:00"), None);
assert_eq!(parse_rfc3339_z("2026-13-05T12:00:00Z"), None);
assert_eq!(parse_rfc3339_z("2026-04-31T12:00:00Z"), None);
assert_eq!(parse_rfc3339_z("2023-02-29T12:00:00Z"), None);
}
#[test]
fn accepts_valid_leap_day_timestamps() {
assert_eq!(parse_rfc3339_z("2024-02-29T12:00:00Z"), Some(1_709_208_000));
assert_eq!(parse_rfc3339_z("2000-02-29T23:59:59Z"), Some(951_868_799));
}
#[test]
fn classifies_active_account_auth_health_states() {
let now = 1_700_000_000;
let valid = evaluate_auth_health(
AuthCredentialSource::ActiveAccount,
Some("refresh"),
Some("2023-11-15T12:00:30Z"),
now,
);
assert_eq!(valid.state, AuthHealthState::Valid);
assert_eq!(valid.summary_label(), "valid");
let expiring_soon = evaluate_auth_health(
AuthCredentialSource::ActiveAccount,
Some("refresh"),
Some("2023-11-14T22:14:05Z"),
now,
);
assert_eq!(expiring_soon.state, AuthHealthState::ExpiringSoon);
assert!(expiring_soon.state.is_refresh_worthy());
let expired = evaluate_auth_health(
AuthCredentialSource::ActiveAccount,
Some("refresh"),
Some("2023-11-14T22:07:00Z"),
now,
);
assert_eq!(expired.state, AuthHealthState::Expired);
assert!(expired.state.is_refresh_worthy());
}
#[test]
fn classifies_static_fallback_and_malformed_metadata_explicitly() {
let static_fallback = evaluate_auth_health(
AuthCredentialSource::ConfigFallbackKey,
None,
None,
1_700_000_000,
);
assert_eq!(static_fallback.state, AuthHealthState::Static);
assert_eq!(static_fallback.source_label(), "config fallback key");
let static_saved_token = evaluate_auth_health(
AuthCredentialSource::ActiveAccount,
None,
Some("2026-04-06T00:00:00Z"),
1_700_000_000,
);
assert_eq!(static_saved_token.state, AuthHealthState::Static);
let malformed = evaluate_auth_health(
AuthCredentialSource::ActiveAccount,
Some("refresh"),
Some("not-a-timestamp"),
1_700_000_000,
);
assert_eq!(malformed.state, AuthHealthState::Unknown);
assert_eq!(malformed.metadata_state, AuthMetadataState::Malformed);
assert!(
malformed
.expiry_detail()
.contains("malformed expiry metadata")
);
let impossible_calendar_date = evaluate_auth_health(
AuthCredentialSource::ActiveAccount,
Some("refresh"),
Some("2023-02-29T12:00:00Z"),
1_700_000_000,
);
assert_eq!(impossible_calendar_date.state, AuthHealthState::Unknown);
assert_eq!(
impossible_calendar_date.metadata_state,
AuthMetadataState::Malformed
);
}
#[test]
fn runtime_stats_snapshot_serializes_with_stable_fields() {
let snapshot = RuntimeStatsSnapshot::new(
"127.0.0.1:8318",
"https://upstream.example/v1",
Some("primary".to_string()),
2,
AuthHealthSnapshot {
state: AuthHealthState::Valid,
source: AuthCredentialSource::ActiveAccount,
metadata_state: AuthMetadataState::Present,
expires_at: Some("2026-04-06T00:00:00Z".to_string()),
expires_at_unix_secs: Some(1_765_440_000),
expires_in_secs: Some(86_400),
},
);
let payload = serde_json::to_value(snapshot).unwrap();
assert_eq!(payload["bind_address"], "127.0.0.1:8318");
assert_eq!(payload["auth_health"]["state"], "valid");
assert_eq!(payload["request_counters"]["total_proxied_requests"], 0);
assert_eq!(payload["last_refresh"]["kind"], "unknown");
}
}
+56
View File
@@ -0,0 +1,56 @@
use anyhow::{Result, bail};
use crate::provider::{Provider, ProviderId, RefreshResult};
pub struct ClaudeProvider {
upstream_base_url: String,
}
impl ClaudeProvider {
pub fn new(upstream_base_url: String) -> Self {
Self { upstream_base_url }
}
pub fn from_config(config: &crate::config::AppConfig) -> Self {
Self::new(config.claude.upstream_base_url.clone())
}
}
impl Provider for ClaudeProvider {
fn id(&self) -> ProviderId {
ProviderId::CLAUDE
}
fn display_name(&self) -> &'static str {
"Claude"
}
fn upstream_base_url(&self) -> &str {
&self.upstream_base_url
}
fn default_upstream_base_url() -> &'static str
where
Self: Sized,
{
"https://api.anthropic.com"
}
fn apply_auth_headers(
&self,
request: reqwest::RequestBuilder,
api_key: &str,
) -> reqwest::RequestBuilder {
request
.header("x-api-key", api_key)
.header("anthropic-version", "2023-06-01")
}
fn refresh_token<'a>(
&'a self,
_refresh_token: &'a str,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<RefreshResult>> + Send + 'a>>
{
Box::pin(async move { bail!("Claude refresh is not implemented yet") })
}
}
+139
View File
@@ -0,0 +1,139 @@
use std::path::PathBuf;
use clap::{Args, Parser, Subcommand};
#[derive(Debug, Parser)]
#[command(name = "proxypilot-rs")]
#[command(about = "Experimental terminal-first Rust replatform for ProxyPilot")]
#[command(version)]
pub struct Cli {
#[command(subcommand)]
pub command: Command,
}
#[derive(Debug, Subcommand)]
pub enum Command {
/// Write an example config to disk.
Init {
#[arg(long, default_value = "proxypilot-rs.toml")]
config: PathBuf,
#[arg(long, default_value_t = false)]
force: bool,
},
/// Run the local proxy server.
Run {
#[arg(long, default_value = "proxypilot-rs.toml")]
config: PathBuf,
},
/// Open a terminal operator view for the Rust rewrite.
Tui {
#[arg(long, default_value = "proxypilot-rs.toml")]
config: PathBuf,
},
/// Manage local account state for the Rust rewrite.
Account {
#[command(subcommand)]
command: AccountCommand,
},
}
#[derive(Debug, Clone, Args)]
pub struct SharedConfig {
#[arg(long, default_value = "proxypilot-rs.toml")]
pub config: PathBuf,
}
#[derive(Debug, Subcommand)]
pub enum AccountCommand {
/// Add or replace a Codex account in the local state file.
AddCodex {
#[command(flatten)]
shared: SharedConfig,
#[arg(long)]
name: String,
#[arg(long)]
api_key: String,
#[arg(long, default_value_t = false)]
activate: bool,
},
/// Add or replace a Claude account in the local state file.
AddClaude {
#[command(flatten)]
shared: SharedConfig,
#[arg(long)]
name: String,
#[arg(long)]
api_key: String,
#[arg(long, default_value_t = false)]
activate: bool,
},
/// Import a Codex auth JSON file from the Go/ProxyPilot world.
ImportCodex {
#[command(flatten)]
shared: SharedConfig,
#[arg(long)]
file: PathBuf,
#[arg(long)]
name: Option<String>,
#[arg(long, default_value_t = false)]
activate: bool,
},
/// Export the full local Rust account state to a TOML file.
Export {
#[command(flatten)]
shared: SharedConfig,
#[arg(long)]
file: PathBuf,
},
/// Import a full local Rust account state TOML file.
Import {
#[command(flatten)]
shared: SharedConfig,
#[arg(long)]
file: PathBuf,
#[arg(long, default_value_t = false)]
replace: bool,
},
/// Start the Codex device flow and save the resulting account locally.
LoginCodexDevice {
#[command(flatten)]
shared: SharedConfig,
#[arg(long)]
name: Option<String>,
#[arg(long, default_value_t = false)]
activate: bool,
},
/// Refresh a saved Codex account using its refresh token.
RefreshCodex {
#[command(flatten)]
shared: SharedConfig,
#[arg(long)]
name: Option<String>,
},
/// Refresh a saved Claude account.
RefreshClaude {
#[command(flatten)]
shared: SharedConfig,
#[arg(long)]
name: Option<String>,
},
/// List saved accounts and show which one is active.
List {
#[command(flatten)]
shared: SharedConfig,
},
/// Select the active account used by the proxy.
Activate {
#[command(flatten)]
shared: SharedConfig,
#[arg(long)]
name: String,
},
/// Remove a saved account from the local state file.
Remove {
#[command(flatten)]
shared: SharedConfig,
#[arg(long)]
name: String,
},
}
+753
View File
@@ -0,0 +1,753 @@
use std::time::Duration;
use anyhow::{Context, Result, bail};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::time::sleep;
use crate::provider::{Provider, ProviderId, RefreshResult};
pub const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
pub const DEVICE_USER_CODE_URL: &str = "https://auth.openai.com/api/accounts/deviceauth/usercode";
pub const DEVICE_TOKEN_URL: &str = "https://auth.openai.com/api/accounts/deviceauth/token";
pub const DEVICE_VERIFICATION_URL: &str = "https://auth.openai.com/codex/device";
pub const DEVICE_REDIRECT_URI: &str = "https://auth.openai.com/deviceauth/callback";
pub const OAUTH_TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
const DEFAULT_POLL_INTERVAL_SECS: u64 = 5;
const DEVICE_TIMEOUT_SECS: u64 = 15 * 60;
#[derive(Debug, Clone)]
pub struct DeviceAuthResult {
pub access_token: String,
pub refresh_token: String,
pub id_token: String,
pub email: Option<String>,
pub account_id: Option<String>,
pub plan_type: Option<String>,
pub expires_at: Option<String>,
}
pub struct CodexProvider {
upstream_base_url: String,
refresh_token_url: String,
client: Client,
}
impl CodexProvider {
pub fn new(upstream_base_url: String, refresh_token_url: String) -> Self {
Self {
upstream_base_url,
refresh_token_url,
client: Client::new(),
}
}
pub fn from_config(config: &crate::config::AppConfig) -> Self {
Self::new(
config.codex.upstream_base_url.clone(),
config.codex.refresh_token_url.clone(),
)
}
}
impl Provider for CodexProvider {
fn id(&self) -> ProviderId {
ProviderId::CODEX
}
fn display_name(&self) -> &'static str {
"Codex (OpenAI)"
}
fn upstream_base_url(&self) -> &str {
&self.upstream_base_url
}
fn default_upstream_base_url() -> &'static str {
"https://api.openai.com"
}
fn refresh_token<'a>(
&'a self,
refresh_token: &'a str,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<RefreshResult>> + Send + 'a>>
{
Box::pin(async move {
let endpoints = if self.refresh_token_url.trim().is_empty() {
DeviceEndpoints::default()
} else {
DeviceEndpoints {
oauth_token_url: self.refresh_token_url.clone(),
..DeviceEndpoints::default()
}
};
let result =
refresh_with_refresh_token_for_test(self.client.clone(), endpoints, refresh_token)
.await?;
Ok(RefreshResult {
access_token: result.access_token,
refresh_token: Some(result.refresh_token),
id_token: Some(result.id_token),
email: result.email,
account_id: result.account_id,
plan_type: result.plan_type,
expires_at: result.expires_at,
})
})
}
}
#[derive(Debug, Clone)]
pub struct DeviceEndpoints {
pub user_code_url: String,
pub token_poll_url: String,
pub verification_url: String,
pub oauth_token_url: String,
pub redirect_uri: String,
}
impl Default for DeviceEndpoints {
fn default() -> Self {
Self {
user_code_url: DEVICE_USER_CODE_URL.to_string(),
token_poll_url: DEVICE_TOKEN_URL.to_string(),
verification_url: DEVICE_VERIFICATION_URL.to_string(),
oauth_token_url: OAUTH_TOKEN_URL.to_string(),
redirect_uri: DEVICE_REDIRECT_URI.to_string(),
}
}
}
pub fn device_endpoints_from_config(config: &crate::config::AppConfig) -> DeviceEndpoints {
let refresh_token_url = config.codex.refresh_token_url.trim();
if refresh_token_url.is_empty() {
DeviceEndpoints::default()
} else {
DeviceEndpoints {
oauth_token_url: refresh_token_url.to_string(),
..DeviceEndpoints::default()
}
}
}
#[derive(Debug, Serialize)]
struct DeviceCodeRequest<'a> {
client_id: &'a str,
}
#[derive(Debug, Deserialize)]
struct DeviceCodeResponse {
device_auth_id: String,
#[serde(default)]
user_code: String,
#[serde(default)]
usercode: String,
#[serde(default)]
interval: Option<Value>,
}
#[derive(Debug, Serialize)]
struct DeviceTokenPollRequest<'a> {
device_auth_id: &'a str,
user_code: &'a str,
}
#[derive(Debug, Deserialize)]
struct DeviceTokenPollResponse {
authorization_code: String,
code_verifier: String,
}
#[derive(Debug, Serialize)]
struct TokenExchangeRequest<'a> {
grant_type: &'a str,
client_id: &'a str,
code: &'a str,
redirect_uri: &'a str,
code_verifier: &'a str,
}
#[derive(Debug, Deserialize)]
struct TokenExchangeResponse {
access_token: String,
refresh_token: String,
id_token: String,
#[serde(default)]
expires_in: i64,
}
#[derive(Debug, Deserialize)]
struct JwtClaims {
#[serde(default)]
email: String,
#[serde(default)]
exp: i64,
#[serde(default, rename = "https://api.openai.com/auth")]
codex_auth: JwtCodexAuth,
}
#[derive(Debug, Default, Deserialize)]
struct JwtCodexAuth {
#[serde(default)]
chatgpt_account_id: String,
#[serde(default)]
chatgpt_plan_type: String,
}
pub async fn login_with_device_flow() -> Result<DeviceAuthResult> {
login_with_device_flow_for_test(Client::new(), DeviceEndpoints::default()).await
}
pub async fn refresh_with_refresh_token(refresh_token: &str) -> Result<DeviceAuthResult> {
refresh_with_refresh_token_for_test(Client::new(), DeviceEndpoints::default(), refresh_token)
.await
}
pub async fn refresh_with_refresh_token_from_config(
config: &crate::config::AppConfig,
refresh_token: &str,
) -> Result<DeviceAuthResult> {
refresh_with_refresh_token_for_test(
Client::new(),
device_endpoints_from_config(config),
refresh_token,
)
.await
}
pub async fn login_with_device_flow_for_test(
client: Client,
endpoints: DeviceEndpoints,
) -> Result<DeviceAuthResult> {
let code_response = request_device_code(&client, &endpoints).await?;
let user_code = if code_response.user_code.trim().is_empty() {
code_response.usercode.trim().to_string()
} else {
code_response.user_code.trim().to_string()
};
let device_auth_id = code_response.device_auth_id.trim().to_string();
if user_code.is_empty() || device_auth_id.is_empty() {
bail!("codex device flow did not return required fields");
}
let poll_interval = parse_poll_interval(code_response.interval.as_ref());
println!("Starting Codex device authentication...");
println!("Codex device URL: {}", endpoints.verification_url);
println!("Codex device code: {}", user_code);
println!("Approve the login in your browser, then come back here.");
let device_tokens = poll_for_authorization(
&client,
&endpoints,
&device_auth_id,
&user_code,
poll_interval,
)
.await?;
if device_tokens.authorization_code.trim().is_empty()
|| device_tokens.code_verifier.trim().is_empty()
{
bail!("codex device flow token response missing required fields");
}
exchange_authorization_code(&client, &endpoints, &device_tokens).await
}
pub async fn refresh_with_refresh_token_for_test(
client: Client,
endpoints: DeviceEndpoints,
refresh_token: &str,
) -> Result<DeviceAuthResult> {
let trimmed = refresh_token.trim();
if trimmed.is_empty() {
bail!("refresh token is required");
}
let response = client
.post(&endpoints.oauth_token_url)
.header("Accept", "application/json")
.form(&[
("client_id", CLIENT_ID),
("grant_type", "refresh_token"),
("refresh_token", trimmed),
("scope", "openid profile email"),
])
.send()
.await
.context("failed to refresh Codex tokens")?;
let status = response.status();
let body = response
.text()
.await
.context("failed to read Codex refresh response")?;
if !status.is_success() {
bail!(
"codex token refresh failed with status {}: {}",
status,
body
);
}
let payload: TokenExchangeResponse =
serde_json::from_str(&body).context("failed to decode Codex refresh response")?;
build_auth_result(payload)
}
async fn request_device_code(
client: &Client,
endpoints: &DeviceEndpoints,
) -> Result<DeviceCodeResponse> {
let response = client
.post(&endpoints.user_code_url)
.header("Accept", "application/json")
.json(&DeviceCodeRequest {
client_id: CLIENT_ID,
})
.send()
.await
.context("failed to request Codex device code")?;
let status = response.status();
let body = response
.text()
.await
.context("failed to read device code response")?;
if !status.is_success() {
bail!(
"codex device code request failed with status {}: {}",
status,
body
);
}
serde_json::from_str(&body).context("failed to decode Codex device code response")
}
async fn poll_for_authorization(
client: &Client,
endpoints: &DeviceEndpoints,
device_auth_id: &str,
user_code: &str,
poll_interval: Duration,
) -> Result<DeviceTokenPollResponse> {
let deadline = tokio::time::Instant::now() + Duration::from_secs(DEVICE_TIMEOUT_SECS);
loop {
if tokio::time::Instant::now() >= deadline {
bail!("codex device authentication timed out after 15 minutes");
}
let response = client
.post(&endpoints.token_poll_url)
.header("Accept", "application/json")
.json(&DeviceTokenPollRequest {
device_auth_id,
user_code,
})
.send()
.await
.context("failed to poll Codex device token")?;
let status = response.status();
let body = response
.text()
.await
.context("failed to read Codex device poll response")?;
if status.is_success() {
return serde_json::from_str(&body)
.context("failed to decode Codex device token response");
}
if status.as_u16() == 403 || status.as_u16() == 404 {
sleep(poll_interval).await;
continue;
}
let trimmed = body.trim();
bail!(
"codex device token polling failed with status {}: {}",
status,
if trimmed.is_empty() {
"empty response body"
} else {
trimmed
}
);
}
}
async fn exchange_authorization_code(
client: &Client,
endpoints: &DeviceEndpoints,
device_tokens: &DeviceTokenPollResponse,
) -> Result<DeviceAuthResult> {
let response = client
.post(&endpoints.oauth_token_url)
.header("Accept", "application/json")
.form(&TokenExchangeRequest {
grant_type: "authorization_code",
client_id: CLIENT_ID,
code: device_tokens.authorization_code.trim(),
redirect_uri: &endpoints.redirect_uri,
code_verifier: device_tokens.code_verifier.trim(),
})
.send()
.await
.context("failed to exchange device authorization code for tokens")?;
let status = response.status();
let body = response
.text()
.await
.context("failed to read OAuth token response")?;
if !status.is_success() {
bail!(
"codex token exchange failed with status {}: {}",
status,
body
);
}
let payload: TokenExchangeResponse =
serde_json::from_str(&body).context("failed to decode OAuth token response")?;
build_auth_result(payload)
}
fn build_auth_result(payload: TokenExchangeResponse) -> Result<DeviceAuthResult> {
let claims = parse_jwt_claims(&payload.id_token).ok();
let expires_at = claims
.as_ref()
.and_then(|claims| {
if claims.exp > 0 {
Some(claims.exp)
} else {
None
}
})
.map(format_unix_timestamp)
.or_else(|| {
if payload.expires_in > 0 {
Some(format_unix_timestamp(
chrono_like_now_secs() + payload.expires_in,
))
} else {
None
}
});
Ok(DeviceAuthResult {
access_token: payload.access_token,
refresh_token: payload.refresh_token,
id_token: payload.id_token,
email: claims
.as_ref()
.and_then(|claims| trimmed_option(&claims.email)),
account_id: claims
.as_ref()
.and_then(|claims| trimmed_option(&claims.codex_auth.chatgpt_account_id)),
plan_type: claims
.as_ref()
.and_then(|claims| trimmed_option(&claims.codex_auth.chatgpt_plan_type)),
expires_at,
})
}
fn parse_poll_interval(value: Option<&Value>) -> Duration {
let default = Duration::from_secs(DEFAULT_POLL_INTERVAL_SECS);
let Some(value) = value else {
return default;
};
match value {
Value::Number(number) => number.as_u64().map(Duration::from_secs).unwrap_or(default),
Value::String(text) => text
.trim()
.parse::<u64>()
.map(Duration::from_secs)
.unwrap_or(default),
_ => default,
}
}
fn parse_jwt_claims(token: &str) -> Result<JwtClaims> {
let payload = token
.split('.')
.nth(1)
.context("invalid JWT token format")?;
let bytes = URL_SAFE_NO_PAD
.decode(payload)
.context("failed to decode JWT payload")?;
serde_json::from_slice(&bytes).context("failed to parse JWT claims")
}
fn trimmed_option(value: &str) -> Option<String> {
let trimmed = value.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
fn chrono_like_now_secs() -> i64 {
use std::time::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_secs() as i64)
.unwrap_or_default()
}
fn format_unix_timestamp(timestamp: i64) -> String {
use std::time::{Duration as StdDuration, UNIX_EPOCH};
let when = UNIX_EPOCH + StdDuration::from_secs(timestamp.max(0) as u64);
let datetime: chrono_like::DateTime = when.into();
datetime.to_rfc3339()
}
mod chrono_like {
use std::time::SystemTime;
pub struct DateTime(SystemTime);
impl From<SystemTime> for DateTime {
fn from(value: SystemTime) -> Self {
Self(value)
}
}
impl DateTime {
pub fn to_rfc3339(&self) -> String {
use std::time::UNIX_EPOCH;
let duration = self
.0
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64;
let secs = duration;
let tm = time_parts(secs);
format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second
)
}
}
struct Parts {
year: i64,
month: i64,
day: i64,
hour: i64,
minute: i64,
second: i64,
}
fn time_parts(mut secs: i64) -> Parts {
let second = secs.rem_euclid(60);
secs = (secs - second) / 60;
let minute = secs.rem_euclid(60);
secs = (secs - minute) / 60;
let hour = secs.rem_euclid(24);
let days = (secs - hour) / 24;
civil_from_days(days).with_time(hour, minute, second)
}
struct Civil {
year: i64,
month: i64,
day: i64,
}
impl Civil {
fn with_time(self, hour: i64, minute: i64, second: i64) -> Parts {
Parts {
year: self.year,
month: self.month,
day: self.day,
hour,
minute,
second,
}
}
}
fn civil_from_days(days: i64) -> Civil {
let z = days + 719468;
let era = if z >= 0 { z } else { z - 146096 } / 146097;
let doe = z - era * 146097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = mp + if mp < 10 { 3 } else { -9 };
let year = y + if m <= 2 { 1 } else { 0 };
Civil {
year,
month: m,
day: d,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::extract::State;
use axum::response::IntoResponse;
use axum::routing::post;
use axum::{Json, Router};
use serde_json::json;
use tokio::sync::oneshot;
async fn start_listener(app: Router) -> (String, oneshot::Sender<()>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = oneshot::channel::<()>();
tokio::spawn(async move {
let server = axum::serve(listener, app).with_graceful_shutdown(async {
let _ = rx.await;
});
let _ = server.await;
});
(format!("http://{}", addr), tx)
}
#[tokio::test]
async fn device_flow_returns_tokens_and_claims() {
async fn user_code() -> impl axum::response::IntoResponse {
Json(json!({
"device_auth_id": "device-auth-id",
"user_code": "ABCD-EFGH",
"interval": 0
}))
}
async fn token_poll(
State(done): State<std::sync::Arc<std::sync::atomic::AtomicBool>>,
) -> impl axum::response::IntoResponse {
if done.swap(true, std::sync::atomic::Ordering::SeqCst) {
(
axum::http::StatusCode::FORBIDDEN,
Json(json!({"pending": true})),
)
.into_response()
} else {
Json(json!({
"authorization_code": "auth-code",
"code_verifier": "verifier",
"code_challenge": "challenge"
}))
.into_response()
}
}
async fn exchange() -> impl axum::response::IntoResponse {
let payload = json!({
"email": "device@example.com",
"exp": 1767225600_i64,
"https://api.openai.com/auth": {
"chatgpt_account_id": "acct_device",
"chatgpt_plan_type": "plus"
}
});
let claims = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).unwrap());
Json(json!({
"access_token": "device-access-token",
"refresh_token": "device-refresh-token",
"id_token": format!("header.{}.sig", claims),
"expires_in": 3600
}))
}
let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let user_code_app = Router::new().route("/usercode", post(user_code));
let token_app = Router::new()
.route("/token", post(token_poll))
.with_state(done);
let exchange_app = Router::new().route("/oauth/token", post(exchange));
let (user_code_url, user_shutdown) = start_listener(user_code_app).await;
let (token_url, token_shutdown) = start_listener(token_app).await;
let (oauth_url, oauth_shutdown) = start_listener(exchange_app).await;
let result = login_with_device_flow_for_test(
Client::new(),
DeviceEndpoints {
user_code_url: format!("{user_code_url}/usercode"),
token_poll_url: format!("{token_url}/token"),
verification_url: "https://example.test/device".to_string(),
oauth_token_url: format!("{oauth_url}/oauth/token"),
redirect_uri: "https://example.test/callback".to_string(),
},
)
.await
.unwrap();
assert_eq!(result.access_token, "device-access-token");
assert_eq!(result.refresh_token, "device-refresh-token");
assert_eq!(result.email.as_deref(), Some("device@example.com"));
assert_eq!(result.account_id.as_deref(), Some("acct_device"));
assert_eq!(result.plan_type.as_deref(), Some("plus"));
let _ = user_shutdown.send(());
let _ = token_shutdown.send(());
let _ = oauth_shutdown.send(());
}
#[tokio::test]
async fn refresh_flow_returns_updated_tokens_and_claims() {
async fn refresh_exchange() -> impl axum::response::IntoResponse {
let payload = json!({
"email": "refresh@example.com",
"exp": 1767225600_i64,
"https://api.openai.com/auth": {
"chatgpt_account_id": "acct_refresh",
"chatgpt_plan_type": "pro"
}
});
let claims = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).unwrap());
Json(json!({
"access_token": "refreshed-access-token",
"refresh_token": "refreshed-refresh-token",
"id_token": format!("header.{}.sig", claims),
"expires_in": 3600
}))
}
let refresh_app = Router::new().route("/oauth/token", post(refresh_exchange));
let (refresh_url, refresh_shutdown) = start_listener(refresh_app).await;
let result = refresh_with_refresh_token_for_test(
Client::new(),
DeviceEndpoints {
oauth_token_url: format!("{refresh_url}/oauth/token"),
..DeviceEndpoints::default()
},
"old-refresh-token",
)
.await
.unwrap();
assert_eq!(result.access_token, "refreshed-access-token");
assert_eq!(result.refresh_token, "refreshed-refresh-token");
assert_eq!(result.email.as_deref(), Some("refresh@example.com"));
assert_eq!(result.account_id.as_deref(), Some("acct_refresh"));
assert_eq!(result.plan_type.as_deref(), Some("pro"));
let _ = refresh_shutdown.send(());
}
}
+262
View File
@@ -0,0 +1,262 @@
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AppConfig {
#[serde(default)]
pub server: ServerConfig,
#[serde(default)]
pub state: StateConfig,
#[serde(default)]
pub codex: CodexConfig,
#[serde(default)]
pub claude: ClaudeConfig,
#[serde(default)]
pub providers: ProvidersConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProvidersConfig {
#[serde(default)]
pub active: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
#[serde(default = "default_bind")]
pub bind: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateConfig {
#[serde(default = "default_state_path")]
pub path: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodexConfig {
#[serde(default = "default_codex_base_url")]
pub upstream_base_url: String,
#[serde(default)]
pub api_key: String,
#[serde(default)]
pub refresh_token_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaudeConfig {
#[serde(default = "default_claude_base_url")]
pub upstream_base_url: String,
#[serde(default)]
pub api_key: String,
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
bind: default_bind(),
}
}
}
impl Default for StateConfig {
fn default() -> Self {
Self {
path: default_state_path(),
}
}
}
impl Default for CodexConfig {
fn default() -> Self {
Self {
upstream_base_url: default_codex_base_url(),
api_key: "set-me".to_string(),
refresh_token_url: String::new(),
}
}
}
impl Default for ClaudeConfig {
fn default() -> Self {
Self {
upstream_base_url: default_claude_base_url(),
api_key: String::new(),
}
}
}
impl AppConfig {
pub fn load(path: &Path) -> Result<Self> {
let raw = fs::read_to_string(path)
.with_context(|| format!("failed to read config at {}", path.display()))?;
let config: Self = toml::from_str(&raw)
.with_context(|| format!("failed to parse TOML config at {}", path.display()))?;
config.validate()?;
Ok(config)
}
pub fn write_example(path: &Path, force: bool) -> Result<()> {
if path.exists() && !force {
bail!(
"config already exists at {} (pass --force to overwrite)",
path.display()
);
}
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
{
fs::create_dir_all(parent).with_context(|| {
format!("failed to create config directory {}", parent.display())
})?;
}
fs::write(path, Self::example_toml())
.with_context(|| format!("failed to write example config to {}", path.display()))?;
Ok(())
}
pub fn validate(&self) -> Result<()> {
if self.server.bind.trim().is_empty() {
bail!("server.bind cannot be empty");
}
if self.codex.upstream_base_url.trim().is_empty() {
bail!("codex.upstream_base_url cannot be empty");
}
if self.state.path.trim().is_empty() {
bail!("state.path cannot be empty");
}
Ok(())
}
pub fn health_url(&self) -> String {
format!("http://{}/healthz", self.server.bind)
}
pub fn config_summary(&self, path: &Path) -> Vec<String> {
let lines = vec![
format!("config: {}", path.display()),
format!("listen: {}", self.server.bind),
format!("state path: {}", self.resolve_state_path(path).display()),
format!("active provider: {}", self.active_provider_label()),
format!("codex upstream: {}", self.codex.upstream_base_url),
format!(
"codex refresh token endpoint: {}",
if self.codex.refresh_token_url.trim().is_empty() {
"live default".to_string()
} else {
self.codex.refresh_token_url.clone()
}
),
format!(
"codex fallback api key: {}",
if self.codex.api_key.trim().is_empty() {
"missing"
} else {
"configured"
}
),
format!("claude upstream: {}", self.claude.upstream_base_url),
format!(
"claude fallback api key: {}",
if self.claude.api_key.trim().is_empty() {
"missing"
} else {
"configured"
}
),
];
lines
}
pub fn active_provider(&self) -> &str {
self.providers
.active
.as_deref()
.unwrap_or(crate::provider::CODEX_PROVIDER)
}
pub fn active_provider_label(&self) -> String {
let tag = self.active_provider();
match tag {
crate::provider::CODEX_PROVIDER => "codex (default)".to_string(),
crate::provider::CLAUDE_PROVIDER => "claude".to_string(),
other => other.to_string(),
}
}
pub fn example_toml() -> &'static str {
r#"# ProxyPilot Rust replatform config
#
# The rewrite keeps long-lived account state in a separate local file.
[server]
bind = "127.0.0.1:8318"
[state]
path = "proxypilot-rs.state.toml"
[providers]
# active = "codex" # default; change to "claude" or "gemini" when available
[codex]
upstream_base_url = "https://api.openai.com"
api_key = ""
# refresh_token_url = "http://127.0.0.1:18319/oauth/token"
[claude]
upstream_base_url = "https://api.anthropic.com"
api_key = ""
"#
}
pub fn resolve_state_path(&self, config_path: &Path) -> PathBuf {
let raw = PathBuf::from(self.state.path.trim());
if raw.is_absolute() {
raw
} else if let Some(parent) = config_path.parent() {
parent.join(raw)
} else {
raw
}
}
}
pub fn default_config_path() -> PathBuf {
PathBuf::from("proxypilot-rs.toml")
}
fn default_bind() -> String {
"127.0.0.1:8318".to_string()
}
fn default_codex_base_url() -> String {
"https://api.openai.com".to_string()
}
fn default_claude_base_url() -> String {
"https://api.anthropic.com".to_string()
}
fn default_state_path() -> String {
"proxypilot-rs.state.toml".to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_example_config() {
let config: AppConfig = toml::from_str(AppConfig::example_toml()).unwrap();
assert_eq!(config.server.bind, "127.0.0.1:8318");
assert_eq!(config.state.path, "proxypilot-rs.state.toml");
assert_eq!(config.codex.upstream_base_url, "https://api.openai.com");
assert!(config.codex.refresh_token_url.is_empty());
assert_eq!(config.claude.upstream_base_url, "https://api.anthropic.com");
}
}
+11
View File
@@ -0,0 +1,11 @@
pub mod accounts;
pub mod auth_runtime;
pub mod claude;
pub mod cli;
pub mod codex;
pub mod config;
pub mod provider;
pub mod provider_registry;
pub mod proxy;
pub mod state;
pub mod tui;
+135
View File
@@ -0,0 +1,135 @@
use std::path::PathBuf;
use anyhow::Result;
use clap::Parser;
use proxypilot_rs::cli::{AccountCommand, Cli, Command};
use proxypilot_rs::config::{AppConfig, default_config_path};
use tracing_subscriber::EnvFilter;
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("proxypilot_rs=info,tower_http=info")),
)
.with_target(false)
.compact()
.init();
let cli = Cli::parse();
match cli.command {
Command::Init { config, force } => {
let path = resolve_config_path(config);
AppConfig::write_example(&path, force)?;
println!("wrote {}", path.display());
}
Command::Run { config } => {
let path = resolve_config_path(config);
let config = AppConfig::load(&path)?;
proxypilot_rs::proxy::run(config, &path).await?;
}
Command::Tui { config } => {
let path = resolve_config_path(config);
let config = AppConfig::load(&path)?;
proxypilot_rs::tui::run(config, &path).await?;
}
Command::Account { command, .. } => match command {
AccountCommand::AddCodex {
shared,
name,
api_key,
activate,
} => {
let path = resolve_config_path(shared.config);
let config = AppConfig::load(&path)?;
proxypilot_rs::accounts::add_codex_account(
&config, &path, name, api_key, activate,
)?;
}
AccountCommand::AddClaude {
shared,
name,
api_key,
activate,
} => {
let path = resolve_config_path(shared.config);
let config = AppConfig::load(&path)?;
proxypilot_rs::accounts::add_claude_account(
&config, &path, name, api_key, activate,
)?;
}
AccountCommand::List { shared } => {
let path = resolve_config_path(shared.config);
let config = AppConfig::load(&path)?;
proxypilot_rs::accounts::list_accounts(&config, &path)?;
}
AccountCommand::ImportCodex {
shared,
file,
name,
activate,
} => {
let path = resolve_config_path(shared.config);
let config = AppConfig::load(&path)?;
proxypilot_rs::accounts::import_codex_account(
&config, &path, &file, name, activate,
)?;
}
AccountCommand::Export { shared, file } => {
let path = resolve_config_path(shared.config);
let config = AppConfig::load(&path)?;
proxypilot_rs::accounts::export_accounts(&config, &path, &file)?;
}
AccountCommand::Import {
shared,
file,
replace,
} => {
let path = resolve_config_path(shared.config);
let config = AppConfig::load(&path)?;
proxypilot_rs::accounts::import_accounts(&config, &path, &file, replace)?;
}
AccountCommand::LoginCodexDevice {
shared,
name,
activate,
} => {
let path = resolve_config_path(shared.config);
let config = AppConfig::load(&path)?;
proxypilot_rs::accounts::login_codex_device(&config, &path, name, activate).await?;
}
AccountCommand::RefreshCodex { shared, name } => {
let path = resolve_config_path(shared.config);
let config = AppConfig::load(&path)?;
proxypilot_rs::accounts::refresh_codex_account(&config, &path, name).await?;
}
AccountCommand::RefreshClaude { shared, name } => {
let path = resolve_config_path(shared.config);
let config = AppConfig::load(&path)?;
proxypilot_rs::accounts::refresh_claude_account(&config, &path, name).await?;
}
AccountCommand::Activate { shared, name } => {
let path = resolve_config_path(shared.config);
let config = AppConfig::load(&path)?;
proxypilot_rs::accounts::activate_account(&config, &path, name)?;
}
AccountCommand::Remove { shared, name } => {
let path = resolve_config_path(shared.config);
let config = AppConfig::load(&path)?;
proxypilot_rs::accounts::remove_account(&config, &path, name)?;
}
},
}
Ok(())
}
fn resolve_config_path(path: PathBuf) -> PathBuf {
if path.as_os_str().is_empty() {
default_config_path()
} else {
path
}
}
+134
View File
@@ -0,0 +1,134 @@
use std::future::Future;
use std::pin::Pin;
use anyhow::Result;
use reqwest;
use serde::{Deserialize, Serialize};
use crate::state::AccountEntry;
pub const CODEX_PROVIDER: &str = "codex";
pub const CLAUDE_PROVIDER: &str = "claude";
pub const GEMINI_PROVIDER: &str = "gemini";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct ProviderId(pub &'static str);
impl ProviderId {
pub const CODEX: ProviderId = ProviderId(CODEX_PROVIDER);
pub const CLAUDE: ProviderId = ProviderId(CLAUDE_PROVIDER);
pub const GEMINI: ProviderId = ProviderId(GEMINI_PROVIDER);
pub fn as_str(&self) -> &'static str {
self.0
}
}
impl std::fmt::Display for ProviderId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthResult {
pub access_token: String,
pub refresh_token: Option<String>,
pub id_token: Option<String>,
pub email: Option<String>,
pub account_id: Option<String>,
pub plan_type: Option<String>,
pub expires_at: Option<String>,
}
impl AuthResult {
pub fn into_account_entry(self, name: String, source: String, _activate: bool) -> AccountEntry {
AccountEntry {
name,
provider: self.access_token_provider_name().to_string(),
api_key: self.access_token,
refresh_token: self.refresh_token,
id_token: self.id_token,
email: self.email,
account_id: self.account_id,
plan_type: self.plan_type,
expires_at: self.expires_at,
source: Some(source),
}
}
fn access_token_provider_name(&self) -> &str {
CODEX_PROVIDER
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefreshResult {
pub access_token: String,
pub refresh_token: Option<String>,
pub id_token: Option<String>,
pub email: Option<String>,
pub account_id: Option<String>,
pub plan_type: Option<String>,
pub expires_at: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelInfo {
pub id: String,
pub owned_by: Option<String>,
}
pub trait Provider: Send + Sync + 'static {
fn id(&self) -> ProviderId;
fn display_name(&self) -> &'static str;
fn provider_tag(&self) -> &'static str {
self.id().as_str()
}
fn upstream_base_url(&self) -> &str;
fn default_upstream_base_url() -> &'static str
where
Self: Sized;
fn refresh_token<'a>(
&'a self,
refresh_token: &'a str,
) -> Pin<Box<dyn Future<Output = Result<RefreshResult>> + Send + 'a>>;
fn models_path(&self) -> &str {
"/v1/models"
}
fn chat_completions_path(&self) -> &str {
"/v1/chat/completions"
}
fn responses_path(&self) -> &str {
"/v1/responses"
}
fn apply_auth_headers(
&self,
request: reqwest::RequestBuilder,
api_key: &str,
) -> reqwest::RequestBuilder {
request.bearer_auth(api_key)
}
}
pub fn provider_from_tag(tag: &str) -> Option<ProviderId> {
match tag {
CODEX_PROVIDER => Some(ProviderId::CODEX),
CLAUDE_PROVIDER => Some(ProviderId::CLAUDE),
GEMINI_PROVIDER => Some(ProviderId::GEMINI),
_ => None,
}
}
pub fn is_known_provider(tag: &str) -> bool {
provider_from_tag(tag).is_some()
}
@@ -0,0 +1,95 @@
use std::sync::Arc;
use tokio::sync::RwLock;
use crate::claude::ClaudeProvider;
use crate::codex::CodexProvider;
use crate::config::AppConfig;
use crate::provider::{Provider, ProviderId};
use crate::state::AccountState;
pub struct ProviderRegistry {
providers: Vec<Arc<dyn Provider>>,
}
impl ProviderRegistry {
pub fn new(config: &AppConfig) -> Self {
let providers: Vec<Arc<dyn Provider>> = vec![
Arc::new(CodexProvider::from_config(config)),
Arc::new(ClaudeProvider::from_config(config)),
];
Self { providers }
}
pub fn active_provider(&self, config: &AppConfig) -> Arc<dyn Provider> {
let tag = config.active_provider();
self.providers
.iter()
.find(|p| p.provider_tag() == tag)
.cloned()
.unwrap_or_else(|| {
self.providers
.first()
.cloned()
.expect("at least one provider must be registered")
})
}
pub fn get(&self, id: ProviderId) -> Option<Arc<dyn Provider>> {
self.providers.iter().find(|p| p.id() == id).cloned()
}
}
#[derive(Clone)]
pub struct ResolvedProvider {
pub provider: Arc<dyn Provider>,
pub api_key: Option<String>,
pub refresh_token: Option<String>,
pub account_name: Option<String>,
}
pub async fn resolve_active_provider(
config: &AppConfig,
registry: &ProviderRegistry,
accounts: &RwLock<AccountState>,
) -> ResolvedProvider {
let provider = registry.active_provider(config);
let tag = provider.provider_tag();
let (api_key, refresh_token, account_name) = {
let state = accounts.read().await;
let active = state.active_account_for_provider(tag);
let key = active
.as_ref()
.map(|a| a.api_key.clone())
.or_else(|| match tag {
crate::provider::CODEX_PROVIDER => {
let fallback = config.codex.api_key.trim();
if fallback.is_empty() {
None
} else {
Some(fallback.to_string())
}
}
crate::provider::CLAUDE_PROVIDER => {
let fallback = config.claude.api_key.trim();
if fallback.is_empty() {
None
} else {
Some(fallback.to_string())
}
}
_ => None,
});
let refresh = active.as_ref().and_then(|a| a.refresh_token.clone());
let name = active.as_ref().map(|a| a.name.clone());
(key, refresh, name)
};
ResolvedProvider {
provider,
api_key,
refresh_token,
account_name,
}
}
File diff suppressed because it is too large Load Diff
+675
View File
@@ -0,0 +1,675 @@
use std::fs;
use std::path::Path;
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use crate::config::AppConfig;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AccountState {
#[serde(default)]
pub active_account: Option<String>,
#[serde(default)]
pub accounts: Vec<AccountEntry>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountEntry {
pub name: String,
pub provider: String,
pub api_key: String,
#[serde(default)]
pub refresh_token: Option<String>,
#[serde(default)]
pub id_token: Option<String>,
#[serde(default)]
pub email: Option<String>,
#[serde(default)]
pub account_id: Option<String>,
#[serde(default)]
pub plan_type: Option<String>,
#[serde(default)]
pub expires_at: Option<String>,
#[serde(default)]
pub source: Option<String>,
}
#[derive(Debug, Clone)]
pub struct ActiveCodexAccount {
pub name: String,
pub api_key: String,
pub refresh_token: Option<String>,
pub id_token: Option<String>,
pub email: Option<String>,
pub account_id: Option<String>,
pub plan_type: Option<String>,
pub expires_at: Option<String>,
}
impl AccountState {
pub fn load_or_default(path: &Path) -> Result<Self> {
if !path.exists() {
return Ok(Self::default());
}
let raw = fs::read_to_string(path)
.with_context(|| format!("failed to read state file {}", path.display()))?;
let state: Self = toml::from_str(&raw)
.with_context(|| format!("failed to parse state file {}", path.display()))?;
Ok(state)
}
pub fn save(&self, path: &Path) -> Result<()> {
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
{
fs::create_dir_all(parent).with_context(|| {
format!("failed to create state directory {}", parent.display())
})?;
}
let raw = toml::to_string_pretty(self).context("failed to serialize account state")?;
fs::write(path, raw)
.with_context(|| format!("failed to write state file {}", path.display()))?;
Ok(())
}
pub fn add_or_replace_manual_account(
&mut self,
provider: &str,
name: String,
api_key: String,
activate: bool,
) -> Result<()> {
let trimmed_name = name.trim();
let trimmed_key = api_key.trim();
if trimmed_name.is_empty() {
bail!("account name cannot be empty");
}
if trimmed_key.is_empty() {
bail!("api key cannot be empty");
}
self.accounts.retain(|account| account.name != trimmed_name);
self.accounts.push(AccountEntry {
name: trimmed_name.to_string(),
provider: provider.to_string(),
api_key: trimmed_key.to_string(),
refresh_token: None,
id_token: None,
email: None,
account_id: None,
plan_type: None,
expires_at: None,
source: Some("manual".to_string()),
});
if activate || self.active_account.is_none() {
self.active_account = Some(trimmed_name.to_string());
}
self.accounts.sort_by(|a, b| a.name.cmp(&b.name));
Ok(())
}
pub fn add_or_replace_codex_account(
&mut self,
name: String,
api_key: String,
activate: bool,
) -> Result<()> {
self.add_or_replace_manual_account(crate::provider::CODEX_PROVIDER, name, api_key, activate)
}
pub fn activate(&mut self, name: &str) -> Result<()> {
let trimmed = name.trim();
if trimmed.is_empty() {
bail!("account name cannot be empty");
}
if self.accounts.iter().any(|account| account.name == trimmed) {
self.active_account = Some(trimmed.to_string());
Ok(())
} else {
bail!("no saved account named {}", trimmed)
}
}
pub fn remove_account(&mut self, name: &str) -> Result<()> {
let trimmed = name.trim();
if trimmed.is_empty() {
bail!("account name cannot be empty");
}
let original_len = self.accounts.len();
self.accounts.retain(|account| account.name != trimmed);
if self.accounts.len() == original_len {
bail!("no saved account named {}", trimmed);
}
if self.active_account.as_deref() == Some(trimmed) {
self.active_account = self.accounts.first().map(|account| account.name.clone());
}
Ok(())
}
pub fn merge_from(&mut self, imported: AccountState) -> usize {
let mut imported_count = 0;
for imported_account in imported.accounts {
self.accounts
.retain(|account| account.name != imported_account.name);
self.accounts.push(imported_account);
imported_count += 1;
}
if self.active_account.is_none() {
self.active_account = imported.active_account;
}
if let Some(active) = self.active_account.as_deref()
&& !self.accounts.iter().any(|account| account.name == active)
{
self.active_account = self.accounts.first().map(|account| account.name.clone());
}
self.accounts.sort_by(|a, b| a.name.cmp(&b.name));
imported_count
}
pub fn active_account_for_provider(&self, provider: &str) -> Option<ActiveCodexAccount> {
let active_name = self.active_account.as_deref()?;
self.accounts
.iter()
.find(|account| account.provider == provider && account.name == active_name)
.map(|account| ActiveCodexAccount {
name: account.name.clone(),
api_key: account.api_key.clone(),
refresh_token: account.refresh_token.clone(),
id_token: account.id_token.clone(),
email: account.email.clone(),
account_id: account.account_id.clone(),
plan_type: account.plan_type.clone(),
expires_at: account.expires_at.clone(),
})
}
pub fn account_by_name_and_provider(
&self,
name: &str,
provider: &str,
) -> Option<ActiveCodexAccount> {
let trimmed = name.trim();
self.accounts
.iter()
.find(|account| account.provider == provider && account.name == trimmed)
.map(|account| ActiveCodexAccount {
name: account.name.clone(),
api_key: account.api_key.clone(),
refresh_token: account.refresh_token.clone(),
id_token: account.id_token.clone(),
email: account.email.clone(),
account_id: account.account_id.clone(),
plan_type: account.plan_type.clone(),
expires_at: account.expires_at.clone(),
})
}
pub fn runtime_usable_account_count_for_provider(&self, provider: &str) -> usize {
self.accounts
.iter()
.filter(|account| account.provider == provider && !account.api_key.trim().is_empty())
.count()
}
pub fn update_account_tokens_for_provider(
&mut self,
account_name: &str,
provider: &str,
access_token: String,
refresh_token: Option<String>,
id_token: Option<String>,
email: Option<String>,
account_id: Option<String>,
plan_type: Option<String>,
expires_at: Option<String>,
) -> Result<()> {
let trimmed = account_name.trim();
let entry = self
.accounts
.iter_mut()
.find(|account| account.provider == provider && account.name == trimmed)
.ok_or_else(|| anyhow::anyhow!("no saved {} account named {}", provider, trimmed))?;
entry.api_key = access_token;
if refresh_token.is_some() {
entry.refresh_token = refresh_token;
}
if id_token.is_some() {
entry.id_token = id_token;
}
if email.is_some() {
entry.email = email;
}
if account_id.is_some() {
entry.account_id = account_id;
}
if plan_type.is_some() {
entry.plan_type = plan_type;
}
if expires_at.is_some() {
entry.expires_at = expires_at;
}
Ok(())
}
// Legacy codex-specific wrappers (delegate to provider-agnostic methods)
pub fn active_codex_account(&self) -> Option<ActiveCodexAccount> {
self.active_account_for_provider(crate::provider::CODEX_PROVIDER)
}
pub fn runtime_usable_codex_account_count(&self) -> usize {
self.runtime_usable_account_count_for_provider(crate::provider::CODEX_PROVIDER)
}
pub fn codex_account_by_name(&self, name: &str) -> Option<ActiveCodexAccount> {
self.account_by_name_and_provider(name, crate::provider::CODEX_PROVIDER)
}
pub fn effective_codex_api_key(&self, config: &AppConfig) -> Option<String> {
self.active_codex_account()
.map(|account| account.api_key)
.or_else(|| {
let fallback = config.codex.api_key.trim();
if fallback.is_empty() {
None
} else {
Some(fallback.to_string())
}
})
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct ImportedCodexAuth {
#[serde(default)]
pub id_token: String,
#[serde(default)]
pub access_token: String,
#[serde(default)]
pub refresh_token: String,
#[serde(default)]
pub email: String,
#[serde(default)]
pub account_id: String,
#[serde(default, alias = "expired")]
pub expires_at: String,
#[serde(default, rename = "type")]
pub provider_type: String,
}
impl AccountState {
pub fn add_imported_codex_account(
&mut self,
name: String,
imported: ImportedCodexAuth,
source: String,
activate: bool,
) -> Result<()> {
let trimmed_name = name.trim();
if trimmed_name.is_empty() {
bail!("account name cannot be empty");
}
if imported.access_token.trim().is_empty() {
bail!("imported Codex auth file is missing access_token");
}
self.accounts.retain(|account| account.name != trimmed_name);
self.accounts.push(AccountEntry {
name: trimmed_name.to_string(),
provider: if imported.provider_type.trim().is_empty() {
"codex".to_string()
} else {
imported.provider_type.trim().to_string()
},
api_key: imported.access_token.trim().to_string(),
refresh_token: optional_trimmed(imported.refresh_token),
id_token: optional_trimmed(imported.id_token),
email: optional_trimmed(imported.email),
account_id: optional_trimmed(imported.account_id),
plan_type: None,
expires_at: optional_trimmed(imported.expires_at),
source: Some(source),
});
if activate || self.active_account.is_none() {
self.active_account = Some(trimmed_name.to_string());
}
self.accounts.sort_by(|a, b| a.name.cmp(&b.name));
Ok(())
}
}
impl AccountState {
pub fn add_device_codex_account(
&mut self,
name: String,
result: crate::codex::DeviceAuthResult,
activate: bool,
) -> Result<()> {
let trimmed_name = name.trim();
if trimmed_name.is_empty() {
bail!("account name cannot be empty");
}
if result.access_token.trim().is_empty() {
bail!("device auth result missing access token");
}
self.accounts.retain(|account| account.name != trimmed_name);
self.accounts.push(AccountEntry {
name: trimmed_name.to_string(),
provider: "codex".to_string(),
api_key: result.access_token,
refresh_token: optional_trimmed(result.refresh_token),
id_token: optional_trimmed(result.id_token),
email: result.email,
account_id: result.account_id,
plan_type: result.plan_type,
expires_at: result.expires_at,
source: Some("device-login".to_string()),
});
if activate || self.active_account.is_none() {
self.active_account = Some(trimmed_name.to_string());
}
self.accounts.sort_by(|a, b| a.name.cmp(&b.name));
Ok(())
}
pub fn update_codex_account_tokens(
&mut self,
account_name: &str,
result: crate::codex::DeviceAuthResult,
) -> Result<()> {
self.update_account_tokens_for_provider(
account_name,
crate::provider::CODEX_PROVIDER,
result.access_token,
optional_trimmed(result.refresh_token),
optional_trimmed(result.id_token),
result.email,
result.account_id,
result.plan_type,
result.expires_at,
)
}
}
fn optional_trimmed(value: String) -> Option<String> {
let trimmed = value.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn active_account_overrides_config_fallback() {
let mut state = AccountState::default();
state
.add_or_replace_codex_account("primary".to_string(), "state-key".to_string(), true)
.unwrap();
let config = AppConfig::default();
assert_eq!(
state.effective_codex_api_key(&config).as_deref(),
Some("state-key")
);
}
#[test]
fn config_fallback_is_used_when_no_account_exists() {
let config = AppConfig {
codex: crate::config::CodexConfig {
upstream_base_url: "https://api.openai.com".to_string(),
api_key: "fallback-key".to_string(),
refresh_token_url: String::new(),
},
..AppConfig::default()
};
let state = AccountState::default();
assert_eq!(
state.effective_codex_api_key(&config).as_deref(),
Some("fallback-key")
);
}
#[test]
fn imported_codex_account_carries_metadata() {
let mut state = AccountState::default();
state
.add_imported_codex_account(
"imported".to_string(),
ImportedCodexAuth {
id_token: "id".to_string(),
access_token: "imported-token".to_string(),
refresh_token: "refresh".to_string(),
email: "dev@example.com".to_string(),
account_id: "acct_123".to_string(),
expires_at: "2026-04-06T00:00:00Z".to_string(),
provider_type: "codex".to_string(),
},
"file".to_string(),
true,
)
.unwrap();
let account = state
.accounts
.iter()
.find(|entry| entry.name == "imported")
.unwrap();
assert_eq!(account.email.as_deref(), Some("dev@example.com"));
assert_eq!(account.account_id.as_deref(), Some("acct_123"));
assert_eq!(account.id_token.as_deref(), Some("id"));
assert_eq!(account.plan_type.as_deref(), None);
assert_eq!(account.expires_at.as_deref(), Some("2026-04-06T00:00:00Z"));
assert_eq!(account.source.as_deref(), Some("file"));
}
#[test]
fn imported_codex_auth_accepts_go_token_storage_shape() {
let imported: ImportedCodexAuth = serde_json::from_str(
r#"{
"id_token": "go-id-token",
"access_token": "go-access-token",
"refresh_token": "go-refresh-token",
"account_id": "acct_go",
"last_refresh": "2026-04-05T00:00:00Z",
"email": "go@example.com",
"type": "codex",
"expired": "2026-04-06T00:00:00Z"
}"#,
)
.unwrap();
let mut state = AccountState::default();
state
.add_imported_codex_account(
"go-file".to_string(),
imported,
"fixture".to_string(),
true,
)
.unwrap();
let account = state.active_codex_account().unwrap();
assert_eq!(account.api_key, "go-access-token");
assert_eq!(account.refresh_token.as_deref(), Some("go-refresh-token"));
assert_eq!(account.id_token.as_deref(), Some("go-id-token"));
assert_eq!(account.email.as_deref(), Some("go@example.com"));
assert_eq!(account.account_id.as_deref(), Some("acct_go"));
assert_eq!(account.expires_at.as_deref(), Some("2026-04-06T00:00:00Z"));
}
#[test]
fn removing_active_account_promotes_next_saved_account() {
let mut state = AccountState::default();
state
.add_or_replace_codex_account("primary".to_string(), "key-1".to_string(), true)
.unwrap();
state
.add_or_replace_codex_account("backup".to_string(), "key-2".to_string(), false)
.unwrap();
state.remove_account("primary").unwrap();
assert_eq!(state.active_account.as_deref(), Some("backup"));
assert_eq!(state.accounts.len(), 1);
assert_eq!(state.accounts[0].name, "backup");
}
#[test]
fn merge_from_replaces_named_accounts_and_preserves_existing_active_account() {
let mut state = AccountState::default();
state
.add_or_replace_codex_account("primary".to_string(), "old-key".to_string(), true)
.unwrap();
let mut imported = AccountState {
active_account: Some("imported-active".to_string()),
accounts: Vec::new(),
};
imported
.add_or_replace_codex_account("primary".to_string(), "new-key".to_string(), false)
.unwrap();
imported
.add_or_replace_manual_account(
crate::provider::CLAUDE_PROVIDER,
"claude-main".to_string(),
"claude-key".to_string(),
false,
)
.unwrap();
assert_eq!(state.merge_from(imported), 2);
assert_eq!(state.active_account.as_deref(), Some("primary"));
assert_eq!(state.accounts.len(), 2);
assert_eq!(
state.codex_account_by_name("primary").unwrap().api_key,
"new-key"
);
assert_eq!(
state
.account_by_name_and_provider("claude-main", crate::provider::CLAUDE_PROVIDER)
.unwrap()
.api_key,
"claude-key"
);
}
#[test]
fn merge_from_uses_imported_active_when_local_has_none() {
let mut state = AccountState::default();
let mut imported = AccountState::default();
imported
.add_or_replace_codex_account("imported".to_string(), "key".to_string(), true)
.unwrap();
state.merge_from(imported);
assert_eq!(state.active_account.as_deref(), Some("imported"));
}
#[test]
fn device_account_carries_plan_type() {
let mut state = AccountState::default();
state
.add_device_codex_account(
"device".to_string(),
crate::codex::DeviceAuthResult {
access_token: "access".to_string(),
refresh_token: "refresh".to_string(),
id_token: "id".to_string(),
email: Some("dev@example.com".to_string()),
account_id: Some("acct_123".to_string()),
plan_type: Some("pro".to_string()),
expires_at: Some("2026-04-06T00:00:00Z".to_string()),
},
true,
)
.unwrap();
let account = state.active_codex_account().unwrap();
assert_eq!(account.plan_type.as_deref(), Some("pro"));
}
#[test]
fn manual_claude_account_uses_provider_generic_path() {
let mut state = AccountState::default();
state
.add_or_replace_manual_account(
crate::provider::CLAUDE_PROVIDER,
"claude-main".to_string(),
"claude-key".to_string(),
true,
)
.unwrap();
let account = state
.active_account_for_provider(crate::provider::CLAUDE_PROVIDER)
.unwrap();
assert_eq!(account.name, "claude-main");
assert_eq!(account.api_key, "claude-key");
assert_eq!(
state.runtime_usable_account_count_for_provider(crate::provider::CLAUDE_PROVIDER),
1
);
}
#[test]
fn runtime_usable_codex_account_count_ignores_mixed_provider_and_empty_key_entries() {
let mut state = AccountState::default();
state.accounts.push(AccountEntry {
name: "primary".to_string(),
provider: "codex".to_string(),
api_key: "state-key".to_string(),
refresh_token: None,
id_token: None,
email: None,
account_id: None,
plan_type: None,
expires_at: None,
source: Some("manual".to_string()),
});
state.accounts.push(AccountEntry {
name: "mixed".to_string(),
provider: "anthropic".to_string(),
api_key: "other-key".to_string(),
refresh_token: None,
id_token: None,
email: None,
account_id: None,
plan_type: None,
expires_at: None,
source: Some("manual".to_string()),
});
state.accounts.push(AccountEntry {
name: "broken".to_string(),
provider: "codex".to_string(),
api_key: " ".to_string(),
refresh_token: None,
id_token: None,
email: None,
account_id: None,
plan_type: None,
expires_at: None,
source: Some("manual".to_string()),
});
assert_eq!(state.runtime_usable_codex_account_count(), 1);
}
}
File diff suppressed because it is too large Load Diff
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
RUST_DIR="$ROOT_DIR/rust"
TMP_DIR="$(mktemp -d)"
MOCK_PORT=18320
PROXY_PORT=18321
MOCK_PID=""
PROXY_PID=""
BIN="$RUST_DIR/target/debug/proxypilot-rs"
cleanup() {
if [[ -n "$PROXY_PID" ]]; then
kill "$PROXY_PID" 2>/dev/null || true
wait "$PROXY_PID" 2>/dev/null || true
fi
if [[ -n "$MOCK_PID" ]]; then
kill "$MOCK_PID" 2>/dev/null || true
wait "$MOCK_PID" 2>/dev/null || true
fi
rm -rf "$TMP_DIR"
}
trap cleanup EXIT
cat > "$TMP_DIR/mock_claude.py" <<'PY'
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class Handler(BaseHTTPRequestHandler):
def _send(self, payload):
body = json.dumps(payload).encode("utf-8")
self.send_response(200)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _headers(self):
return {
"x_api_key": self.headers.get("x-api-key", ""),
"authorization": self.headers.get("authorization", ""),
"anthropic_version": self.headers.get("anthropic-version", ""),
}
def do_GET(self):
if self.path == "/v1/models":
payload = {
"object": "list",
"data": [{"id": "claude-3-5-sonnet-smoke"}],
"headers": self._headers(),
}
self._send(payload)
return
self.send_error(404)
def do_POST(self):
length = int(self.headers.get("content-length", "0"))
self.rfile.read(length)
if self.path == "/v1/messages":
payload = {
"id": "msg_smoke",
"type": "message",
"role": "assistant",
"content": [{"type": "text", "text": "ok"}],
"headers": self._headers(),
}
self._send(payload)
return
self.send_error(404)
def log_message(self, format, *args):
return
ThreadingHTTPServer(("127.0.0.1", 18320), Handler).serve_forever()
PY
python3 "$TMP_DIR/mock_claude.py" &
MOCK_PID="$!"
(
cd "$RUST_DIR"
cargo build -q -p proxypilot-rs
)
cat > "$TMP_DIR/proxypilot-rs.toml" <<EOF
[server]
bind = "127.0.0.1:${PROXY_PORT}"
[state]
path = "$TMP_DIR/proxypilot-rs.state.toml"
[providers]
active = "claude"
[codex]
upstream_base_url = "https://api.openai.com"
api_key = ""
[claude]
upstream_base_url = "http://127.0.0.1:${MOCK_PORT}"
api_key = "claude-smoke-token"
EOF
"$BIN" run --config "$TMP_DIR/proxypilot-rs.toml" &
PROXY_PID="$!"
for _ in {1..100}; do
if curl -fs "http://127.0.0.1:${PROXY_PORT}/healthz" >/dev/null 2>&1; then
break
fi
sleep 0.1
done
curl -fsS "http://127.0.0.1:${PROXY_PORT}/healthz" | grep -q '"provider":"claude"'
curl -fsS "http://127.0.0.1:${PROXY_PORT}/v0/runtime/stats" | grep -q '"source":"config_fallback_key"'
curl -fsS "http://127.0.0.1:${PROXY_PORT}/v1/models" | grep -q "claude-3-5-sonnet-smoke"
curl -fsS "http://127.0.0.1:${PROXY_PORT}/v1/models" | grep -q "claude-smoke-token"
curl -fsS \
-H "content-type: application/json" \
-d '{"model":"claude-3-5-sonnet-smoke","max_tokens":16,"messages":[{"role":"user","content":"ping"}]}' \
"http://127.0.0.1:${PROXY_PORT}/v1/messages" | grep -q "msg_smoke"
curl -fsS \
-H "content-type: application/json" \
-d '{"model":"claude-3-5-sonnet-smoke","max_tokens":16,"messages":[{"role":"user","content":"ping"}]}' \
"http://127.0.0.1:${PROXY_PORT}/v1/messages" | grep -q "claude-smoke-token"
echo "Claude Rust smoke passed"
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
RUST_DIR="$ROOT_DIR/rust"
TMP_DIR="$(mktemp -d)"
MOCK_PORT=18318
PROXY_PORT=18319
MOCK_PID=""
PROXY_PID=""
BIN="$RUST_DIR/target/debug/proxypilot-rs"
cleanup() {
if [[ -n "$PROXY_PID" ]]; then
kill "$PROXY_PID" 2>/dev/null || true
wait "$PROXY_PID" 2>/dev/null || true
fi
if [[ -n "$MOCK_PID" ]]; then
kill "$MOCK_PID" 2>/dev/null || true
wait "$MOCK_PID" 2>/dev/null || true
fi
rm -rf "$TMP_DIR"
}
trap cleanup EXIT
cat > "$TMP_DIR/mock_codex.py" <<'PY'
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class Handler(BaseHTTPRequestHandler):
def _send(self, payload):
body = json.dumps(payload).encode("utf-8")
self.send_response(200)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == "/v1/models":
self._send({"object": "list", "data": [{"id": "gpt-5.1-codex-smoke"}]})
return
self.send_error(404)
def do_POST(self):
length = int(self.headers.get("content-length", "0"))
self.rfile.read(length)
if self.path == "/v1/chat/completions":
self._send({
"id": "chatcmpl-smoke",
"object": "chat.completion",
"choices": [{"message": {"role": "assistant", "content": "ok"}}],
})
return
if self.path == "/v1/responses":
self._send({
"id": "resp_smoke",
"object": "response",
"output": [{"type": "message", "content": [{"type": "output_text", "text": "ok"}]}],
})
return
if self.path == "/v1/responses/compact":
self._send({
"id": "resp_compact_smoke",
"object": "response.compaction",
"usage": {"input_tokens": 1, "output_tokens": 2, "total_tokens": 3},
})
return
self.send_error(404)
def log_message(self, format, *args):
return
ThreadingHTTPServer(("127.0.0.1", 18318), Handler).serve_forever()
PY
python3 "$TMP_DIR/mock_codex.py" &
MOCK_PID="$!"
(
cd "$RUST_DIR"
cargo build -q -p proxypilot-rs
)
cat > "$TMP_DIR/proxypilot-rs.toml" <<EOF
[server]
bind = "127.0.0.1:${PROXY_PORT}"
[state]
path = "$TMP_DIR/proxypilot-rs.state.toml"
[providers]
active = "codex"
[codex]
upstream_base_url = "http://127.0.0.1:${MOCK_PORT}"
api_key = ""
[claude]
upstream_base_url = "https://api.anthropic.com"
api_key = ""
EOF
(
"$BIN" account add-codex \
--config "$TMP_DIR/proxypilot-rs.toml" \
--name smoke \
--api-key smoke-token \
--activate
"$BIN" run --config "$TMP_DIR/proxypilot-rs.toml"
) &
PROXY_PID="$!"
for _ in {1..100}; do
if curl -fs "http://127.0.0.1:${PROXY_PORT}/healthz" >/dev/null 2>&1; then
break
fi
sleep 0.1
done
curl -fsS "http://127.0.0.1:${PROXY_PORT}/healthz" >/dev/null
curl -fsS "http://127.0.0.1:${PROXY_PORT}/health" >/dev/null
curl -fsS "http://127.0.0.1:${PROXY_PORT}/v0/runtime/stats" | grep -q '"active_account_name":"smoke"'
curl -fsS "http://127.0.0.1:${PROXY_PORT}/v1/models" | grep -q "gpt-5.1-codex-smoke"
curl -fsS \
-H "content-type: application/json" \
-d '{"model":"gpt-5.1-codex-smoke","messages":[{"role":"user","content":"ping"}]}' \
"http://127.0.0.1:${PROXY_PORT}/v1/chat/completions" | grep -q "chatcmpl-smoke"
curl -fsS \
-H "content-type: application/json" \
-d '{"model":"gpt-5.1-codex-smoke","input":"ping"}' \
"http://127.0.0.1:${PROXY_PORT}/v1/responses" | grep -q "resp_smoke"
curl -fsS \
-H "content-type: application/json" \
-d '{"model":"gpt-5.1-codex-smoke","instructions":"compact this"}' \
"http://127.0.0.1:${PROXY_PORT}/v1/responses/compact" | grep -q "resp_compact_smoke"
curl -fsS \
-H "content-type: application/json" \
-d '{"model":"gpt-5.1-codex-smoke","input":"alias ping"}' \
"http://127.0.0.1:${PROXY_PORT}/backend-api/codex/responses" | grep -q "resp_smoke"
echo "Codex Rust smoke passed"