Skip to content

Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy

Rust

prefer auth files before keychain entries

Raine Virtaa96c4192fd8d
diff --git a/src/auth.rs b/src/auth.rs
index 85f492e..3db4a2e 100644
--- a/src/auth.rs
+++ b/src/auth.rs
@@ -241,6 +241,9 @@ where
K: Keychain,
{
fn load(&self) -> Result<Option<T>> {
+ if let Some(parsed) = self.file_store.load()? {
+ return Ok(Some(parsed));
+ }
if self.use_keychain
&& let Some(raw) = self.keychain.read(&self.service, &self.account)?
{
@@ -248,7 +251,7 @@ where
.map(Some)
.map_err(|err| anyhow::anyhow!("Failed to parse Keychain auth JSON: {err}"));
}
- self.file_store.load()
+ Ok(None)
}
fn save(&self, value: T) -> Result<()> {
@@ -506,7 +509,7 @@ mod tests {
}
#[test]
- fn keychain_file_store_loads_keychain_before_file() {
+ fn keychain_file_store_loads_file_before_keychain() {
let temp = tempfile::TempDir::new().unwrap();
let file = temp_auth_path(&temp, "auth.json");
let legacy = temp_auth_path(&temp, "legacy.json");
@@ -519,22 +522,23 @@ mod tests {
KeychainFileAuthStore::new(file, legacy, "svc", "acct", true, keychain);
let loaded = store.load().unwrap().unwrap();
- assert_eq!(loaded["source"], json!("keychain"));
+ assert_eq!(loaded["source"], json!("file"));
assert_eq!(store.path(), "macOS Keychain");
}
#[test]
- fn keychain_file_store_falls_back_to_file_when_keychain_missing() {
+ fn keychain_file_store_falls_back_to_keychain_when_file_missing() {
let temp = tempfile::TempDir::new().unwrap();
let file = temp_auth_path(&temp, "auth.json");
let legacy = temp_auth_path(&temp, "legacy.json");
- write_atomically(&file, &json!({"source": "file"})).unwrap();
+ let keychain = MockKeychain::default();
+ keychain.set_raw("svc", "acct", json!({"source": "keychain"}));
let store: KeychainFileAuthStore<serde_json::Value, _> =
- KeychainFileAuthStore::new(file, legacy, "svc", "acct", true, MockKeychain::default());
+ KeychainFileAuthStore::new(file, legacy, "svc", "acct", true, keychain);
let loaded = store.load().unwrap().unwrap();
- assert_eq!(loaded["source"], json!("file"));
+ assert_eq!(loaded["source"], json!("keychain"));
}
#[test]
diff --git a/src/providers/codex/auth/token_store.rs b/src/providers/codex/auth/token_store.rs
index 6bc0d95..393b898 100644
--- a/src/providers/codex/auth/token_store.rs
+++ b/src/providers/codex/auth/token_store.rs
@@ -1,4 +1,6 @@
use serde::{Deserialize, Serialize};
+use std::path::Path;
+use std::time::{SystemTime, UNIX_EPOCH};
use crate::auth::{AuthStorage, KeychainFileAuthStore, SystemKeychain};
use crate::paths;
@@ -17,15 +19,43 @@ pub struct StoredAuth {
pub struct CodexTokenStore<S: AuthStorage<StoredAuth>> {
store: S,
+ codex_cli_fallback: bool,
}
impl<S: AuthStorage<StoredAuth>> CodexTokenStore<S> {
pub fn new(store: S) -> Self {
- Self { store }
+ Self {
+ store,
+ codex_cli_fallback: false,
+ }
+ }
+
+ pub fn new_with_codex_cli_fallback(store: S) -> Self {
+ Self {
+ store,
+ codex_cli_fallback: true,
+ }
}
pub fn load_auth(&self) -> Result<Option<StoredAuth>, anyhow::Error> {
- self.store.load()
+ match self.store.load() {
+ Ok(Some(auth)) => Ok(Some(auth)),
+ Ok(None) => {
+ if self.codex_cli_fallback {
+ load_codex_cli_auth()
+ } else {
+ Ok(None)
+ }
+ }
+ Err(err) => {
+ if self.codex_cli_fallback
+ && let Some(auth) = load_codex_cli_auth()?
+ {
+ return Ok(Some(auth));
+ }
+ Err(err)
+ }
+ }
}
pub fn save_auth(&self, value: StoredAuth) -> Result<(), anyhow::Error> {
@@ -54,17 +84,85 @@ pub fn file_store() -> CodexTokenStore<DefaultCodexAuthStore> {
use_macos_keychain(),
SystemKeychain,
);
- CodexTokenStore::new(store)
+ if std::env::var_os("CCP_CONFIG_DIR").is_none() {
+ CodexTokenStore::new_with_codex_cli_fallback(store)
+ } else {
+ CodexTokenStore::new(store)
+ }
}
fn use_macos_keychain() -> bool {
cfg!(target_os = "macos") && std::env::var_os("CCP_CONFIG_DIR").is_none()
}
+#[derive(Debug, Deserialize)]
+struct CodexCliAuthFile {
+ tokens: Option<CodexCliTokens>,
+}
+
+#[derive(Debug, Deserialize)]
+struct CodexCliTokens {
+ access_token: Option<String>,
+ refresh_token: Option<String>,
+ account_id: Option<String>,
+}
+
+fn load_codex_cli_auth() -> Result<Option<StoredAuth>, anyhow::Error> {
+ let home = std::env::var("HOME")
+ .or_else(|_| std::env::var("USERPROFILE"))
+ .unwrap_or_else(|_| "/".to_string());
+ load_codex_cli_auth_from_path(&Path::new(&home).join(".codex").join("auth.json"))
+}
+
+fn load_codex_cli_auth_from_path(path: &Path) -> Result<Option<StoredAuth>, anyhow::Error> {
+ let raw = match std::fs::read_to_string(path) {
+ Ok(raw) => raw,
+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(err) => return Err(anyhow::Error::from(err)),
+ };
+ let parsed: CodexCliAuthFile = serde_json::from_str(&raw)?;
+ let Some(tokens) = parsed.tokens else {
+ return Ok(None);
+ };
+ let (Some(access), Some(refresh)) = (tokens.access_token, tokens.refresh_token) else {
+ return Ok(None);
+ };
+ Ok(Some(StoredAuth {
+ expires: jwt_exp_ms(&access).unwrap_or_else(|| now_ms() + 3600 * 1000),
+ access,
+ refresh,
+ account_id: tokens.account_id,
+ }))
+}
+
+fn jwt_exp_ms(token: &str) -> Option<u64> {
+ let mut parts = token.split('.');
+ let _header = parts.next()?;
+ let payload = parts.next()?;
+ use base64::Engine;
+ let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
+ .decode(payload)
+ .or_else(|_| {
+ let padded = format!("{payload}{}", "=".repeat((4 - payload.len() % 4) % 4));
+ base64::engine::general_purpose::URL_SAFE.decode(padded)
+ })
+ .ok()?;
+ let claims: serde_json::Value = serde_json::from_slice(&decoded).ok()?;
+ claims.get("exp")?.as_u64().map(|exp| exp * 1000)
+}
+
+fn now_ms() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis() as u64
+}
+
#[cfg(test)]
mod tests {
use super::*;
use crate::auth::InMemoryAuthStore;
+ use base64::Engine;
use serde_json::json;
#[test]
@@ -93,4 +191,42 @@ mod tests {
assert_eq!(loaded.access, "token");
assert_eq!(loaded.account_id.as_deref(), Some("acct_1"));
}
+
+ fn test_jwt_with_exp(exp: u64) -> String {
+ let header = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(br#"{"alg":"none"}"#);
+ let payload =
+ base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(format!(r#"{{"exp":{exp}}}"#));
+ format!("{header}.{payload}.sig")
+ }
+
+ #[test]
+ fn codex_cli_auth_file_maps_tokens_and_expiry() {
+ let temp = tempfile::TempDir::new().unwrap();
+ let path = temp.path().join("auth.json");
+ std::fs::write(
+ &path,
+ serde_json::to_vec(&json!({
+ "tokens": {
+ "access_token": test_jwt_with_exp(1234),
+ "refresh_token": "refresh",
+ "account_id": "acct_cli"
+ }
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+
+ let auth = load_codex_cli_auth_from_path(&path).unwrap().unwrap();
+ assert_eq!(auth.refresh, "refresh");
+ assert_eq!(auth.account_id.as_deref(), Some("acct_cli"));
+ assert_eq!(auth.expires, 1_234_000);
+ }
+
+ #[test]
+ fn codex_cli_auth_file_returns_none_without_tokens() {
+ let temp = tempfile::TempDir::new().unwrap();
+ let path = temp.path().join("auth.json");
+ std::fs::write(&path, br#"{"tokens":{}}"#).unwrap();
+ assert!(load_codex_cli_auth_from_path(&path).unwrap().is_none());
+ }
}