Skip to content

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

Rust

fill remaining proxy parity gaps

Raine Virta391ba611b4c5
diff --git a/src/anthropic/sse.rs b/src/anthropic/sse.rs
index 8b9c7d3..6abd619 100644
--- a/src/anthropic/sse.rs
+++ b/src/anthropic/sse.rs
@@ -1,5 +1,4 @@
use serde::{Deserialize, Serialize};
-use serde_json;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SseEvent {
@@ -30,9 +29,7 @@ pub fn parse_sse_events_with_stats(input: &[u8]) -> (Vec<SseEvent>, SseParseStat
chunk_count += 1;
bytes_read += segment.len() + 1;
if segment.is_empty() {
- if let Some(event) = parse_block(&block) {
- events.push(event);
- }
+ events.extend(parse_block(&block));
block.clear();
continue;
}
@@ -42,10 +39,8 @@ pub fn parse_sse_events_with_stats(input: &[u8]) -> (Vec<SseEvent>, SseParseStat
block.push_str(segment);
}
- if !block.is_empty()
- && let Some(event) = parse_block(&block)
- {
- events.push(event);
+ if !block.is_empty() {
+ events.extend(parse_block(&block));
}
let event_count = events.len();
@@ -67,11 +62,7 @@ pub fn encode_sse_event(event: Option<&str>, data: &str) -> Vec<u8> {
}
for line in data.split('\n') {
out.push_str("data: ");
- let escaped = serde_json::to_string(line)
- .ok()
- .map(|encoded| encoded.trim_matches('"').to_string())
- .unwrap_or_else(|| line.to_string());
- out.push_str(&escaped);
+ out.push_str(line);
out.push('\n');
}
out.push('\n');
@@ -94,7 +85,7 @@ fn normalize_lines(input: &str) -> String {
normalized
}
-fn parse_block(block: &str) -> Option<SseEvent> {
+fn parse_block(block: &str) -> Vec<SseEvent> {
let mut event: Option<String> = None;
let mut data_lines = Vec::new();
let mut events = Vec::new();
@@ -102,12 +93,10 @@ fn parse_block(block: &str) -> Option<SseEvent> {
if data_lines.is_empty() {
return;
}
- if event.as_deref().is_none_or(|current| current == "final") {
- events.push(SseEvent {
- event,
- data: data_lines.join("\n"),
- });
- }
+ events.push(SseEvent {
+ event,
+ data: data_lines.join("\n"),
+ });
data_lines.clear();
};
@@ -137,19 +126,5 @@ fn parse_block(block: &str) -> Option<SseEvent> {
push_if_relevant(event.take(), &mut data_lines);
- if events.is_empty() {
- None
- } else if events.len() == 1 {
- events.pop()
- } else {
- // Keep behavior aligned with the expected upstream parser: when multiple
- // events are present in a block, keep only the last event when it is
- // final and otherwise surface nothing.
- events.into_iter().last().filter(|event| {
- event
- .event
- .as_deref()
- .is_none_or(|current| current == "final")
- })
- }
+ events
}
diff --git a/src/auth.rs b/src/auth.rs
index 4975e54..85f492e 100644
--- a/src/auth.rs
+++ b/src/auth.rs
@@ -3,6 +3,7 @@ use serde::{Serialize, de::DeserializeOwned};
use serde_json::to_string_pretty;
use std::fs::{self, File};
use std::io::{self, Read, Write};
+use std::marker::PhantomData;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
@@ -17,25 +18,119 @@ where
}
pub trait Keychain: Send + Sync {
- fn read(&self, _service: &str, _account: &str) -> Option<String>;
- fn write(&self, _service: &str, _account: &str, _value: &str) -> bool;
- fn delete(&self, _service: &str, _account: &str) -> bool;
+ fn read(&self, service: &str, account: &str) -> Result<Option<String>>;
+ fn write(&self, service: &str, account: &str, value: &str) -> Result<()>;
+ fn delete(&self, service: &str, account: &str) -> Result<()>;
}
#[derive(Default)]
pub struct StubKeychain;
impl Keychain for StubKeychain {
- fn read(&self, _service: &str, _account: &str) -> Option<String> {
- None
+ fn read(&self, _service: &str, _account: &str) -> Result<Option<String>> {
+ Ok(None)
+ }
+
+ fn write(&self, _service: &str, _account: &str, _value: &str) -> Result<()> {
+ Ok(())
+ }
+
+ fn delete(&self, _service: &str, _account: &str) -> Result<()> {
+ Ok(())
+ }
+}
+
+#[derive(Default, Clone, Copy)]
+pub struct SystemKeychain;
+
+#[cfg(target_os = "macos")]
+impl Keychain for SystemKeychain {
+ fn read(&self, service: &str, account: &str) -> Result<Option<String>> {
+ let output = run_security(&["find-generic-password", "-s", service, "-a", account, "-w"])?;
+ if output.status.success() {
+ let mut raw = String::from_utf8(output.stdout)
+ .map_err(|err| anyhow::anyhow!("Keychain value is not valid UTF-8: {err}"))?;
+ trim_one_trailing_newline(&mut raw);
+ return Ok(Some(raw));
+ }
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ if stderr.contains("could not be found") || stderr.contains("specified item could not") {
+ return Ok(None);
+ }
+ Err(anyhow::anyhow!("Keychain read failed: {}", stderr.trim()))
+ }
+
+ fn write(&self, _service: &str, _account: &str, _value: &str) -> Result<()> {
+ anyhow::bail!("Keychain write is not available through non-interactive compatibility mode")
+ }
+
+ fn delete(&self, service: &str, account: &str) -> Result<()> {
+ let output = run_security(&["delete-generic-password", "-s", service, "-a", account])?;
+ if output.status.success() {
+ return Ok(());
+ }
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ if stderr.contains("could not be found") || stderr.contains("specified item could not") {
+ return Ok(());
+ }
+ Err(anyhow::anyhow!("Keychain delete failed: {}", stderr.trim()))
+ }
+}
+
+#[cfg(target_os = "macos")]
+fn run_security(args: &[&str]) -> Result<std::process::Output> {
+ use std::process::{Command, Stdio};
+ use std::time::{Duration, Instant};
+
+ let mut child = Command::new("/usr/bin/security")
+ .args(args)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .map_err(|err| anyhow::anyhow!("Failed to start /usr/bin/security: {err}"))?;
+ let start = Instant::now();
+ loop {
+ if child
+ .try_wait()
+ .map_err(|err| anyhow::anyhow!("Failed waiting for /usr/bin/security: {err}"))?
+ .is_some()
+ {
+ return child.wait_with_output().map_err(|err| {
+ anyhow::anyhow!("Failed collecting /usr/bin/security output: {err}")
+ });
+ }
+ if start.elapsed() >= Duration::from_secs(10) {
+ let _ = child.kill();
+ let _ = child.wait();
+ anyhow::bail!("Timed out reading macOS Keychain");
+ }
+ std::thread::sleep(Duration::from_millis(25));
+ }
+}
+
+#[cfg(target_os = "macos")]
+fn trim_one_trailing_newline(value: &mut String) {
+ if value.ends_with('\n') {
+ value.pop();
+ if value.ends_with('\r') {
+ value.pop();
+ }
+ }
+}
+
+#[cfg(not(target_os = "macos"))]
+impl Keychain for SystemKeychain {
+ fn read(&self, _service: &str, _account: &str) -> Result<Option<String>> {
+ Ok(None)
}
- fn write(&self, _service: &str, _account: &str, _value: &str) -> bool {
- true
+ fn write(&self, _service: &str, _account: &str, _value: &str) -> Result<()> {
+ anyhow::bail!("Keychain storage is not available on this platform")
}
- fn delete(&self, _service: &str, _account: &str) -> bool {
- true
+ fn delete(&self, _service: &str, _account: &str) -> Result<()> {
+ Ok(())
}
}
@@ -101,6 +196,92 @@ where
}
}
+pub struct KeychainFileAuthStore<T, K = SystemKeychain>
+where
+ T: Serialize + DeserializeOwned + Send + Sync + Clone,
+ K: Keychain,
+{
+ file_store: FileAuthStore<T>,
+ keychain: K,
+ service: String,
+ account: String,
+ use_keychain: bool,
+ keychain_path: String,
+ _marker: PhantomData<T>,
+}
+
+impl<T, K> KeychainFileAuthStore<T, K>
+where
+ T: Serialize + DeserializeOwned + Send + Sync + Clone,
+ K: Keychain,
+{
+ pub fn new(
+ file: String,
+ legacy_file: String,
+ service: impl Into<String>,
+ account: impl Into<String>,
+ use_keychain: bool,
+ keychain: K,
+ ) -> Self {
+ Self {
+ file_store: FileAuthStore::new(file, legacy_file),
+ keychain,
+ service: service.into(),
+ account: account.into(),
+ use_keychain,
+ keychain_path: "macOS Keychain".to_string(),
+ _marker: PhantomData,
+ }
+ }
+}
+
+impl<T, K> AuthStorage<T> for KeychainFileAuthStore<T, K>
+where
+ T: Serialize + DeserializeOwned + Send + Sync + Clone,
+ K: Keychain,
+{
+ fn load(&self) -> Result<Option<T>> {
+ if self.use_keychain
+ && let Some(raw) = self.keychain.read(&self.service, &self.account)?
+ {
+ return serde_json::from_str::<T>(&raw)
+ .map(Some)
+ .map_err(|err| anyhow::anyhow!("Failed to parse Keychain auth JSON: {err}"));
+ }
+ self.file_store.load()
+ }
+
+ fn save(&self, value: T) -> Result<()> {
+ if self.use_keychain {
+ let raw = serde_json::to_string(&value)?;
+ if self
+ .keychain
+ .write(&self.service, &self.account, &raw)
+ .is_ok()
+ {
+ return Ok(());
+ }
+ return self.file_store.save(value);
+ }
+ self.file_store.save(value)
+ }
+
+ fn clear(&self) -> Result<()> {
+ if self.use_keychain {
+ self.keychain.delete(&self.service, &self.account)?;
+ }
+ self.file_store.clear()
+ }
+
+ fn path(&self) -> String {
+ if self.use_keychain {
+ self.keychain_path.clone()
+ } else {
+ self.file_store.path()
+ }
+ }
+}
+
pub fn load_auth_file<T: DeserializeOwned>(path: &str) -> Option<T> {
let mut file = File::open(path).ok()?;
let mut raw = String::new();
@@ -251,3 +432,174 @@ where
{
InMemoryAuthStore::new()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+ use std::collections::HashMap;
+ use std::sync::{Arc, Mutex};
+
+ #[derive(Clone, Default)]
+ struct MockKeychain {
+ values: Arc<Mutex<HashMap<(String, String), String>>>,
+ }
+
+ impl MockKeychain {
+ fn set_raw(&self, service: &str, account: &str, value: serde_json::Value) {
+ self.values.lock().unwrap().insert(
+ (service.to_string(), account.to_string()),
+ value.to_string(),
+ );
+ }
+
+ fn raw(&self, service: &str, account: &str) -> Option<String> {
+ self.values
+ .lock()
+ .unwrap()
+ .get(&(service.to_string(), account.to_string()))
+ .cloned()
+ }
+ }
+
+ impl Keychain for MockKeychain {
+ fn read(&self, service: &str, account: &str) -> Result<Option<String>> {
+ Ok(self.raw(service, account))
+ }
+
+ fn write(&self, service: &str, account: &str, value: &str) -> Result<()> {
+ self.values.lock().unwrap().insert(
+ (service.to_string(), account.to_string()),
+ value.to_string(),
+ );
+ Ok(())
+ }
+
+ fn delete(&self, service: &str, account: &str) -> Result<()> {
+ self.values
+ .lock()
+ .unwrap()
+ .remove(&(service.to_string(), account.to_string()));
+ Ok(())
+ }
+ }
+
+ #[derive(Clone, Default)]
+ struct ReadOnlyKeychain(MockKeychain);
+
+ impl Keychain for ReadOnlyKeychain {
+ fn read(&self, service: &str, account: &str) -> Result<Option<String>> {
+ self.0.read(service, account)
+ }
+
+ fn write(&self, _service: &str, _account: &str, _value: &str) -> Result<()> {
+ anyhow::bail!("read-only")
+ }
+
+ fn delete(&self, service: &str, account: &str) -> Result<()> {
+ self.0.delete(service, account)
+ }
+ }
+
+ fn temp_auth_path(dir: &tempfile::TempDir, name: &str) -> String {
+ dir.path().join(name).to_string_lossy().to_string()
+ }
+
+ #[test]
+ fn keychain_file_store_loads_keychain_before_file() {
+ 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, keychain);
+
+ let loaded = store.load().unwrap().unwrap();
+ assert_eq!(loaded["source"], json!("keychain"));
+ assert_eq!(store.path(), "macOS Keychain");
+ }
+
+ #[test]
+ fn keychain_file_store_falls_back_to_file_when_keychain_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 store: KeychainFileAuthStore<serde_json::Value, _> =
+ KeychainFileAuthStore::new(file, legacy, "svc", "acct", true, MockKeychain::default());
+
+ let loaded = store.load().unwrap().unwrap();
+ assert_eq!(loaded["source"], json!("file"));
+ }
+
+ #[test]
+ fn keychain_file_store_saves_and_clears_keychain_when_enabled() {
+ 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();
+ let store: KeychainFileAuthStore<serde_json::Value, _> =
+ KeychainFileAuthStore::new(file.clone(), legacy, "svc", "acct", true, keychain.clone());
+
+ store.save(json!({"source": "saved"})).unwrap();
+ let raw = keychain.raw("svc", "acct").unwrap();
+ assert_eq!(
+ serde_json::from_str::<serde_json::Value>(&raw).unwrap()["source"],
+ json!("saved")
+ );
+
+ store.clear().unwrap();
+ assert!(keychain.raw("svc", "acct").is_none());
+ assert!(!std::path::Path::new(&file).exists());
+ }
+
+ #[test]
+ fn keychain_file_store_falls_back_to_file_when_keychain_write_fails() {
+ let temp = tempfile::TempDir::new().unwrap();
+ let file = temp_auth_path(&temp, "auth.json");
+ let legacy = temp_auth_path(&temp, "legacy.json");
+ let store: KeychainFileAuthStore<serde_json::Value, _> = KeychainFileAuthStore::new(
+ file.clone(),
+ legacy,
+ "svc",
+ "acct",
+ true,
+ ReadOnlyKeychain::default(),
+ );
+
+ store.save(json!({"source": "file-fallback"})).unwrap();
+ assert_eq!(
+ store.load().unwrap().unwrap()["source"],
+ json!("file-fallback")
+ );
+ assert!(std::path::Path::new(&file).exists());
+ }
+
+ #[test]
+ fn keychain_file_store_uses_file_when_keychain_disabled() {
+ let temp = tempfile::TempDir::new().unwrap();
+ let file = temp_auth_path(&temp, "auth.json");
+ let legacy = temp_auth_path(&temp, "legacy.json");
+ let keychain = MockKeychain::default();
+ let store: KeychainFileAuthStore<serde_json::Value, _> = KeychainFileAuthStore::new(
+ file.clone(),
+ legacy,
+ "svc",
+ "acct",
+ false,
+ keychain.clone(),
+ );
+
+ store.save(json!({"source": "file"})).unwrap();
+ assert!(keychain.raw("svc", "acct").is_none());
+ assert_eq!(store.path(), file);
+ assert_eq!(store.load().unwrap().unwrap()["source"], json!("file"));
+ }
+}
diff --git a/src/providers/codex/auth/token_store.rs b/src/providers/codex/auth/token_store.rs
index 9f7da74..6bc0d95 100644
--- a/src/providers/codex/auth/token_store.rs
+++ b/src/providers/codex/auth/token_store.rs
@@ -1,8 +1,11 @@
use serde::{Deserialize, Serialize};
-use crate::auth::{AuthStorage, FileAuthStore};
+use crate::auth::{AuthStorage, KeychainFileAuthStore, SystemKeychain};
use crate::paths;
+pub const KEYCHAIN_SERVICE: &str = "claude-code-proxy.codex";
+pub const KEYCHAIN_ACCOUNT: &str = "auth";
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct StoredAuth {
pub access: String,
@@ -38,16 +41,26 @@ impl<S: AuthStorage<StoredAuth>> CodexTokenStore<S> {
}
}
-pub fn file_store() -> CodexTokenStore<FileAuthStore<StoredAuth>> {
+pub type DefaultCodexAuthStore = KeychainFileAuthStore<StoredAuth, SystemKeychain>;
+
+pub fn file_store() -> CodexTokenStore<DefaultCodexAuthStore> {
let primary = paths::provider_auth_file("codex");
let legacy = paths::provider_legacy_auth_file("codex");
- let store = FileAuthStore::new(
+ let store = KeychainFileAuthStore::new(
primary.to_string_lossy().to_string(),
legacy.to_string_lossy().to_string(),
+ KEYCHAIN_SERVICE,
+ KEYCHAIN_ACCOUNT,
+ use_macos_keychain(),
+ SystemKeychain,
);
CodexTokenStore::new(store)
}
+fn use_macos_keychain() -> bool {
+ cfg!(target_os = "macos") && std::env::var_os("CCP_CONFIG_DIR").is_none()
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/providers/codex/client.rs b/src/providers/codex/client.rs
index ce2719a..16ee556 100644
--- a/src/providers/codex/client.rs
+++ b/src/providers/codex/client.rs
@@ -6,7 +6,7 @@ use crate::retry::{compute_backoff_delay, sleep};
use super::auth::constants::{CODEX_API_ENDPOINT, ORIGINATOR};
use super::auth::manager::CodexAuthManager;
-use super::auth::token_store::{StoredAuth, file_store};
+use super::auth::token_store::{DefaultCodexAuthStore, StoredAuth, file_store};
use super::translate::request::ResponsesRequest;
// ---------------------------------------------------------------------------
@@ -155,6 +155,7 @@ pub fn build_websocket_request(
// Omit the stream field for WebSocket transport
obj.remove("stream");
+ obj.insert("type".to_string(), serde_json::json!("response.create"));
// Apply continuation if available
if let Some(candidate) = continuation {
@@ -191,7 +192,7 @@ pub struct CodexResponse {
pub struct CodexHttpClient {
client: reqwest::Client,
- auth_manager: CodexAuthManager<crate::auth::FileAuthStore<StoredAuth>>,
+ auth_manager: CodexAuthManager<DefaultCodexAuthStore>,
base_url: String,
header_timeout_ms: u64,
#[allow(dead_code)]
@@ -222,7 +223,7 @@ impl CodexHttpClient {
pub fn new_with_client(
client: reqwest::Client,
- auth_manager: CodexAuthManager<crate::auth::FileAuthStore<StoredAuth>>,
+ auth_manager: CodexAuthManager<DefaultCodexAuthStore>,
base_url: String,
) -> Self {
Self {
@@ -250,7 +251,7 @@ impl CodexHttpClient {
}
}
- pub fn auth_manager(&self) -> &CodexAuthManager<crate::auth::FileAuthStore<StoredAuth>> {
+ pub fn auth_manager(&self) -> &CodexAuthManager<DefaultCodexAuthStore> {
&self.auth_manager
}
@@ -667,6 +668,10 @@ mod tests {
reasoning: None,
};
let payload = build_websocket_request(&req, None);
+ assert_eq!(
+ payload.get("type").and_then(|v| v.as_str()),
+ Some("response.create")
+ );
assert!(payload.get("stream").is_none());
assert!(payload.get("previous_response_id").is_none());
}
diff --git a/tests/foundation.rs b/tests/foundation.rs
index 547d3a3..7d028a1 100644
--- a/tests/foundation.rs
+++ b/tests/foundation.rs
@@ -25,11 +25,13 @@ fn messages_fixture_and_sse_parsing() {
let raw_sse = std::fs::read_to_string("tests/fixtures/sse-basic.txt").unwrap();
let events = parse_sse_events(raw_sse.as_bytes());
- assert_eq!(events.len(), 2);
+ assert_eq!(events.len(), 3);
assert_eq!(events[0].event, None);
assert_eq!(events[0].data, "{\"chunk\":1}");
- assert_eq!(events[1].event.as_deref(), Some("final"));
- assert_eq!(events[1].data, "{\"done\":true}");
+ assert_eq!(events[1].event.as_deref(), Some("update"));
+ assert_eq!(events[1].data, "{\"text\":\"line1\"}\n{\"text\":\"line2\"}");
+ assert_eq!(events[2].event.as_deref(), Some("final"));
+ assert_eq!(events[2].data, "{\"done\":true}");
let (events_with_stats, stats) = parse_sse_events_with_stats(raw_sse.as_bytes());
assert_eq!(events_with_stats.len(), events.len());
@@ -38,8 +40,14 @@ fn messages_fixture_and_sse_parsing() {
let encoded = encode_sse_event(Some("message"), "{\"a\":1}\n{\"b\":2}");
assert_eq!(
encoded,
- b"event: message\ndata: {\\\"a\\\":1}\ndata: {\\\"b\\\":2}\n\n".to_vec()
+ b"event: message\ndata: {\"a\":1}\ndata: {\"b\":2}\n\n".to_vec()
);
+ let reparsed = parse_sse_events(&encoded);
+ assert_eq!(reparsed[0].event.as_deref(), Some("message"));
+ assert_eq!(reparsed[0].data, "{\"a\":1}\n{\"b\":2}");
+ let first_line: serde_json::Value =
+ serde_json::from_str(reparsed[0].data.lines().next().unwrap()).unwrap();
+ assert_eq!(first_line["a"], json!(1));
}
#[test]
diff --git a/tests/smoke_cutover.rs b/tests/smoke_cutover.rs
index b6c844e..1d12cf4 100644
--- a/tests/smoke_cutover.rs
+++ b/tests/smoke_cutover.rs
@@ -361,8 +361,7 @@ async fn smoke_codex_websocket_messages_uses_mock_upstream() {
String::from_utf8_lossy(&ws_body_bytes)
);
});
- // WebSocket transport sends the ResponsesRequest JSON directly; the
- // protocol context implies response.create so no "type" field is injected.
+ assert_eq!(sent["type"], "response.create");
assert_eq!(sent["model"], "gpt-5.5");
assert!(sent.get("stream").is_none());
}