Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy
Rust
fix cursor auth and protocol handling
Raine Virta7019acf5b243
diff --git a/src/providers/cursor/auth.rs b/src/providers/cursor/auth.rsindex dfab337..bcbbdc5 100644--- a/src/providers/cursor/auth.rs+++ b/src/providers/cursor/auth.rs@@ -1,98 +1,476 @@-use std::collections::HashMap;--/// Load the Cursor auth token from environment variables or auth file.-///-/// Resolution order:-/// 1. `CCP_CURSOR_AUTH_TOKEN` env var-/// 2. `CURSOR_AUTH_TOKEN` env var-/// 3. Proxy auth file at `<config_dir>/cursor/auth.json` (accessToken field)-/// 4. Legacy auth file at `<legacy_config_dir>/cursor/auth.json`-pub fn load_cursor_token() -> Option<String> {- let env: HashMap<_, _> = std::env::vars().collect();- if let Some(token) = env.get("CCP_CURSOR_AUTH_TOKEN") {- if !token.is_empty() {- return Some(token.clone());+use base64::Engine;+use rand::RngCore;+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use std::time::{Duration, SystemTime, UNIX_EPOCH};++use crate::auth::{AuthStorage, KeychainFileAuthStore, SystemKeychain};+use crate::{config, paths};++pub const KEYCHAIN_SERVICE: &str = "claude-code-proxy.cursor";+pub const KEYCHAIN_ACCOUNT: &str = "auth";++const REFRESH_EXPIRY_SKEW_MS: u64 = 60_000;+const CURSOR_WEBSITE_URL: &str = "https://cursor.com";++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]+#[serde(rename_all = "camelCase")]+pub struct StoredCursorAuth {+ pub access_token: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub refresh_token: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub api_key: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct CursorAuth {+ pub access_token: String,+ pub refresh_token: Option<String>,+ pub api_key: Option<String>,+ pub expires: Option<u64>,+ pub user_id: Option<String>,+ pub email: Option<String>,+ pub source: String,+}++pub type DefaultCursorAuthStore = KeychainFileAuthStore<StoredCursorAuth, SystemKeychain>;++pub struct CursorTokenStore<S: AuthStorage<StoredCursorAuth>> {+ store: S,+}++impl<S: AuthStorage<StoredCursorAuth>> CursorTokenStore<S> {+ pub fn new(store: S) -> Self {+ Self { store }+ }++ pub fn load_auth(&self) -> anyhow::Result<Option<CursorAuth>> {+ let Some(stored) = self.store.load()? else {+ return Ok(None);+ };+ if stored.access_token.trim().is_empty() {+ return Ok(None);}+ let auth = enrich(stored, self.auth_path());+ self.refresh_if_needed(auth)}- if let Some(token) = env.get("CURSOR_AUTH_TOKEN") {- if !token.is_empty() {- return Some(token.clone());++ pub fn save_auth(&self, auth: StoredCursorAuth) -> anyhow::Result<CursorAuth> {+ if auth.access_token.trim().is_empty() {+ anyhow::bail!("Cursor auth accessToken is required");}+ self.store.save(auth.clone())?;+ Ok(enrich(auth, self.auth_path()))}- let path = crate::paths::provider_auth_file("cursor");- let legacy = crate::paths::provider_legacy_auth_file("cursor");+ pub fn clear_auth(&self) -> anyhow::Result<()> {+ self.store.clear()+ }- if path == legacy {- return load_token_from_file(&path);+ pub fn auth_path(&self) -> String {+ self.store.path()}- load_token_from_file(&path).or_else(|| load_token_from_file(&legacy))-}-fn load_token_from_file(path: &std::path::Path) -> Option<String> {- let value: serde_json::Value = crate::auth::load_auth_file_value(path)?;- // Try accessToken first, then token- if let Some(token) = value.get("accessToken").and_then(|v| v.as_str()) {- if !token.is_empty() {- return Some(token.to_string());+ fn refresh_if_needed(&self, auth: CursorAuth) -> anyhow::Result<Option<CursorAuth>> {+ let Some(refresh_token) = auth.refresh_token.as_deref() else {+ return Ok(Some(auth));+ };+ let Some(expires) = auth.expires else {+ return Ok(Some(auth));+ };+ if expires > now_ms() + REFRESH_EXPIRY_SKEW_MS {+ return Ok(Some(auth));}++ let Some(refreshed) = refresh_cursor_auth(refresh_token)? else {+ return Ok(Some(auth));+ };+ self.save_auth(StoredCursorAuth {+ access_token: refreshed.access_token,+ refresh_token: Some(refreshed.refresh_token),+ api_key: auth.api_key,+ })+ .map(Some)}- if let Some(token) = value.get("token").and_then(|v| v.as_str()) {- if !token.is_empty() {- return Some(token.to_string());- }+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct CursorLogin {+ pub login_url: String,+ pub uuid: String,+ pub verifier: String,+}++#[derive(Debug, Deserialize)]+pub struct RefreshResponse {+ #[serde(rename = "accessToken")]+ access_token: String,+ #[serde(rename = "refreshToken")]+ refresh_token: String,+}++pub fn file_store() -> CursorTokenStore<DefaultCursorAuthStore> {+ let primary = paths::provider_auth_file("cursor");+ let legacy = paths::provider_legacy_auth_file("cursor");+ CursorTokenStore::new(KeychainFileAuthStore::new(+ primary.to_string_lossy().to_string(),+ legacy.to_string_lossy().to_string(),+ KEYCHAIN_SERVICE,+ KEYCHAIN_ACCOUNT,+ use_macos_keychain(),+ SystemKeychain,+ ))+}++pub fn load_cursor_auth() -> anyhow::Result<Option<CursorAuth>> {+ if let Some(token) = env_cursor_token() {+ return Ok(Some(enrich(+ StoredCursorAuth {+ access_token: token,+ refresh_token: None,+ api_key: None,+ },+ "environment".to_string(),+ )));}- // If the file contains a plain string token- if let Some(token) = value.as_str() {- if !token.is_empty() {- return Some(token.to_string());+ file_store().load_auth()+}++/// Load only the bearer token for call sites that do not need auth metadata.+pub fn load_cursor_token() -> Option<String> {+ load_cursor_auth()+ .ok()+ .flatten()+ .map(|auth| auth.access_token)+}++pub fn save_cursor_auth(auth: StoredCursorAuth) -> anyhow::Result<CursorAuth> {+ file_store().save_auth(auth)+}++pub fn clear_cursor_auth() -> anyhow::Result<()> {+ file_store().clear_auth()+}++pub fn cursor_auth_location() -> String {+ file_store().auth_path()+}++pub fn missing_auth_message() -> String {+ [+ "Cursor authentication was not found.",+ "Run `claude-code-proxy cursor auth login`, or set CCP_CURSOR_AUTH_TOKEN/CURSOR_AUTH_TOKEN.",+ "The proxy stores Cursor credentials in its own claude-code-proxy.cursor storage, not Cursor Agent's Keychain/auth.json.",+ ]+ .join(" ")+}++pub fn expired_auth_message(auth: &CursorAuth) -> String {+ let expires = auth+ .expires+ .map(format_unix_ms)+ .unwrap_or_else(|| "unknown".to_string());+ format!(+ "Cursor access token from {} is expired or near expiry ({}). Run `claude-code-proxy cursor auth login` again or set CCP_CURSOR_AUTH_TOKEN.",+ auth.source, expires+ )+}++pub fn create_cursor_login() -> CursorLogin {+ let verifier = random_base64_url(32);+ let challenge = base64_url(Sha256::digest(verifier.as_bytes()).as_ref());+ let uuid = uuid::Uuid::new_v4().to_string();+ let login_url = format!(+ "{CURSOR_WEBSITE_URL}/loginDeepControl?challenge={challenge}&uuid={uuid}&mode=login&redirectTarget=cli"+ );+ CursorLogin {+ login_url,+ uuid,+ verifier,+ }+}++pub fn run_cursor_login() -> anyhow::Result<Option<CursorAuth>> {+ let login = create_cursor_login();+ println!("Open this URL to authenticate with Cursor:");+ println!("{}", login.login_url);+ println!();+ if let Err(err) = open_cursor_login_url(&login.login_url) {+ println!("Could not open browser automatically: {err}");+ }+ println!("Waiting for Cursor login...");+ let result = wait_for_cursor_login(&login, 150, |attempt| {+ if attempt > 0 && attempt % 10 == 0 {+ print!(".");+ let _ = std::io::Write::flush(&mut std::io::stdout());+ }+ })?;+ let Some(result) = result else {+ return Ok(None);+ };+ save_cursor_auth(StoredCursorAuth {+ access_token: result.access_token,+ refresh_token: Some(result.refresh_token),+ api_key: None,+ })+ .map(Some)+}++pub fn wait_for_cursor_login(+ login: &CursorLogin,+ max_attempts: usize,+ mut on_progress: impl FnMut(usize),+) -> anyhow::Result<Option<RefreshResponse>> {+ let client = reqwest::blocking::Client::new();+ let base = config::cursor_base_url().trim_end_matches('/').to_string();+ let mut consecutive_errors = 0usize;++ for attempt in 0..max_attempts {+ let delay =+ Duration::from_millis((1000.0 * 1.2_f64.powi(attempt as i32)).min(10_000.0) as u64);+ let url = format!(+ "{base}/auth/poll?uuid={}&verifier={}",+ login.uuid, login.verifier+ );+ match client+ .get(url)+ .header("content-type", "application/json")+ .send()+ {+ Ok(resp) if resp.status() == reqwest::StatusCode::NOT_FOUND => {+ consecutive_errors = 0;+ on_progress(attempt);+ std::thread::sleep(delay);+ }+ Ok(resp) if resp.status().is_success() => {+ let parsed: serde_json::Value = resp.json()?;+ return Ok(parse_cursor_auth_tokens(&parsed));+ }+ Ok(_) | Err(_) => {+ consecutive_errors += 1;+ if consecutive_errors >= 3 {+ return Ok(None);+ }+ std::thread::sleep(delay);+ }}}- None+ Ok(None)+}++fn refresh_cursor_auth(refresh_token: &str) -> anyhow::Result<Option<RefreshResponse>> {+ let client = reqwest::blocking::Client::new();+ let url = format!(+ "{}/auth/refresh",+ config::cursor_base_url().trim_end_matches('/')+ );+ let resp = client+ .post(url)+ .header("content-type", "application/json")+ .bearer_auth(refresh_token)+ .body("{}")+ .send()?;+ if !resp.status().is_success() {+ return Ok(None);+ }+ let parsed: serde_json::Value = resp.json()?;+ Ok(parse_cursor_auth_tokens(&parsed))+}++fn parse_cursor_auth_tokens(parsed: &serde_json::Value) -> Option<RefreshResponse> {+ Some(RefreshResponse {+ access_token: parsed.get("accessToken")?.as_str()?.to_string(),+ refresh_token: parsed.get("refreshToken")?.as_str()?.to_string(),+ })+}++fn env_cursor_token() -> Option<String> {+ env_cursor_token_from(|key| std::env::var(key).ok())+}++fn env_cursor_token_from(get: impl Fn(&str) -> Option<String>) -> Option<String> {+ get("CCP_CURSOR_AUTH_TOKEN")+ .filter(|token| !token.trim().is_empty())+ .or_else(|| get("CURSOR_AUTH_TOKEN").filter(|token| !token.trim().is_empty()))+}++fn enrich(stored: StoredCursorAuth, source: String) -> CursorAuth {+ let claims = parse_jwt_claims(&stored.access_token);+ CursorAuth {+ expires: token_expiry_ms(&stored.access_token),+ user_id: claims+ .as_ref()+ .and_then(|claims| claims.get("sub"))+ .and_then(|sub| sub.as_str())+ .map(str::to_string),+ email: claims+ .as_ref()+ .and_then(|claims| claims.get("email"))+ .and_then(|email| email.as_str())+ .map(str::to_string),+ source,+ access_token: stored.access_token,+ refresh_token: stored.refresh_token,+ api_key: stored.api_key,+ }+}++fn token_expiry_ms(token: &str) -> Option<u64> {+ parse_jwt_claims(token)?+ .get("exp")?+ .as_u64()+ .map(|exp| exp * 1000)+}++fn parse_jwt_claims(token: &str) -> Option<serde_json::Value> {+ let mut parts = token.split('.');+ let _header = parts.next()?;+ let payload = parts.next()?;+ 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()?;+ serde_json::from_slice(&decoded).ok()+}++fn open_cursor_login_url(url: &str) -> anyhow::Result<()> {+ let status = if cfg!(target_os = "macos") {+ std::process::Command::new("open").arg(url).status()?+ } else if cfg!(target_os = "windows") {+ std::process::Command::new("cmd")+ .args(["/c", "start", "", url])+ .status()?+ } else {+ std::process::Command::new("xdg-open").arg(url).status()?+ };+ if !status.success() {+ anyhow::bail!("open command exited with {status}");+ }+ Ok(())+}++fn random_base64_url(len: usize) -> String {+ let mut bytes = vec![0u8; len];+ rand::thread_rng().fill_bytes(&mut bytes);+ base64_url(&bytes)+}++fn base64_url(bytes: &[u8]) -> String {+ base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)+}++fn use_macos_keychain() -> bool {+ cfg!(target_os = "macos") && std::env::var_os("CCP_CONFIG_DIR").is_none()+}++fn now_ms() -> u64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis() as u64+}++fn format_unix_ms(ms: u64) -> String {+ let secs = (ms / 1000) as i64;+ match time::OffsetDateTime::from_unix_timestamp(secs) {+ Ok(ts) => ts+ .format(&time::format_description::well_known::Rfc3339)+ .unwrap_or_else(|_| ms.to_string()),+ Err(_) => ms.to_string(),+ }}#[cfg(test)]mod tests {use super::*;- use once_cell::sync::Lazy;- use std::sync::Mutex;-- static ENV_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));+ use crate::auth::InMemoryAuthStore;#[test]fn auth_uses_cursor_auth_token_env() {- let _guard = ENV_LOCK.lock().unwrap();- unsafe {- std::env::set_var("CURSOR_AUTH_TOKEN", "tok_from_cursor");- std::env::remove_var("CCP_CURSOR_AUTH_TOKEN");- }- assert_eq!(load_cursor_token().as_deref(), Some("tok_from_cursor"));- unsafe {- std::env::remove_var("CURSOR_AUTH_TOKEN");- }+ let token = env_cursor_token_from(|key| match key {+ "CURSOR_AUTH_TOKEN" => Some("tok_from_cursor".into()),+ _ => None,+ });+ assert_eq!(token.as_deref(), Some("tok_from_cursor"));}#[test]fn auth_prioritizes_ccp_env_over_cursor_env() {- let _guard = ENV_LOCK.lock().unwrap();- unsafe {- std::env::set_var("CCP_CURSOR_AUTH_TOKEN", "tok_ccp");- std::env::set_var("CURSOR_AUTH_TOKEN", "tok_cursor");- }- assert_eq!(load_cursor_token().as_deref(), Some("tok_ccp"));- unsafe {- std::env::remove_var("CCP_CURSOR_AUTH_TOKEN");- std::env::remove_var("CURSOR_AUTH_TOKEN");- }+ let token = env_cursor_token_from(|key| match key {+ "CCP_CURSOR_AUTH_TOKEN" => Some("tok_ccp".into()),+ "CURSOR_AUTH_TOKEN" => Some("tok_cursor".into()),+ _ => None,+ });+ assert_eq!(token.as_deref(), Some("tok_ccp"));}#[test]fn auth_returns_none_when_not_set() {- let _guard = ENV_LOCK.lock().unwrap();- unsafe {- std::env::remove_var("CCP_CURSOR_AUTH_TOKEN");- std::env::remove_var("CURSOR_AUTH_TOKEN");+ assert!(env_cursor_token_from(|_| None).is_none());+ }++ #[test]+ fn stored_auth_uses_camel_case_fields() {+ let auth: StoredCursorAuth = serde_json::from_value(serde_json::json!({+ "accessToken": "access",+ "refreshToken": "refresh",+ "apiKey": "api"+ }))+ .unwrap();+ assert_eq!(auth.access_token, "access");+ assert_eq!(auth.refresh_token.as_deref(), Some("refresh"));++ let value = serde_json::to_value(auth).unwrap();+ assert_eq!(value["accessToken"], "access");+ assert_eq!(value["refreshToken"], "refresh");+ assert!(value.get("access_token").is_none());+ }++ #[test]+ fn cursor_token_store_enriches_jwt_claims() {+ let store = CursorTokenStore::new(InMemoryAuthStore::new());+ let auth = store+ .save_auth(StoredCursorAuth {+ access_token: test_jwt(4_102_444_800, Some("user_1"), Some("[email protected]")),+ refresh_token: Some("refresh".into()),+ api_key: None,+ })+ .unwrap();++ assert_eq!(auth.user_id.as_deref(), Some("user_1"));+ assert_eq!(auth.email.as_deref(), Some("[email protected]"));+ assert_eq!(auth.expires, Some(4_102_444_800_000));+ }++ #[test]+ fn create_login_matches_cursor_deep_control_shape() {+ let login = create_cursor_login();+ assert!(+ login+ .login_url+ .starts_with("https://cursor.com/loginDeepControl?challenge=")+ );+ assert!(login.login_url.contains("&uuid="));+ assert!(login.login_url.contains("&mode=login&redirectTarget=cli"));+ assert!(!login.verifier.contains('='));+ }++ fn test_jwt(exp: u64, sub: Option<&str>, email: Option<&str>) -> String {+ let mut payload = serde_json::json!({ "exp": exp });+ if let Some(sub) = sub {+ payload["sub"] = serde_json::Value::String(sub.to_string());+ }+ if let Some(email) = email {+ payload["email"] = serde_json::Value::String(email.to_string());}- assert!(load_cursor_token().is_none());+ let header = base64::engine::general_purpose::URL_SAFE_NO_PAD+ .encode(br#"{"alg":"none","typ":"JWT"}"#);+ let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD+ .encode(serde_json::to_vec(&payload).unwrap());+ format!("{header}.{payload}.sig")}}diff --git a/src/providers/cursor/mod.rs b/src/providers/cursor/mod.rsindex 90551e9..1df378b 100644--- a/src/providers/cursor/mod.rs+++ b/src/providers/cursor/mod.rs@@ -20,11 +20,16 @@ use crate::anthropic::error::json_error;use crate::anthropic::schema::{CountTokensResponse, MessagesRequest};use crate::monitor::usage_from_anthropic_sse;use crate::provider::{CliHandlers, Provider, RequestContext};-use crate::providers::cursor::auth::load_cursor_token;+use crate::providers::cursor::auth::{+ clear_cursor_auth, expired_auth_message, load_cursor_auth, missing_auth_message,+ run_cursor_login,+};use crate::providers::cursor::client::CursorHttpClient;use crate::providers::cursor::model::resolve_cursor_model;use crate::providers::cursor::request::render_cursor_prompt;-use crate::providers::cursor::response::{decode_cursor_upstream, decode_upstream_response};+use crate::providers::cursor::response::{+ CursorDecodeError, decode_cursor_upstream, decode_upstream_response,+};use crate::providers::cursor::tool_bridge::{BridgeRegistry, advertised_tool_names, can_bridge_cursor_native_tools, find_tool_result,resume_cursor_tool_bridge, start_cursor_tool_bridge,@@ -101,17 +106,34 @@ impl Provider for CursorProvider {}}- let token = match load_cursor_token() {- Some(t) => t,- None => {+ let auth = match load_cursor_auth() {+ Ok(Some(auth)) => auth,+ Ok(None) => {+ return json_error(+ StatusCode::UNAUTHORIZED,+ "authentication_error",+ missing_auth_message(),+ );+ }+ Err(err) => {return json_error(StatusCode::UNAUTHORIZED,"authentication_error",- "Cursor auth token not found. Set CCP_CURSOR_AUTH_TOKEN or CURSOR_AUTH_TOKEN",+ format!("Cursor auth failed: {err}"),);}};+ if matches!(auth.expires, Some(expires) if expires <= now_ms() + 60_000) {+ return json_error(+ StatusCode::UNAUTHORIZED,+ "authentication_error",+ expired_auth_message(&auth),+ );+ }++ let token = auth.access_token;+let prompt = render_cursor_prompt(&body);let images = request::cursor_selected_images(&body);@@ -133,13 +155,7 @@ impl Provider for CursorProvider {if bridge_eligible {let events = match decode_upstream_response(&upstream.body) {Ok(e) => e,- Err(e) => {- return json_error(- StatusCode::BAD_GATEWAY,- "api_error",- format!("Response decoding error: {e}"),- );- }+ Err(e) => return map_cursor_decode_error_to_response(&e),};let allowed = advertised_tool_names(&body);@@ -200,11 +216,7 @@ impl Provider for CursorProvider {}(StatusCode::OK, Json(json)).into_response()}- Err(e) => json_error(- StatusCode::BAD_GATEWAY,- "api_error",- format!("Response decoding error: {e}"),- ),+ Err(e) => map_cursor_decode_error_to_response(&e),}}}@@ -229,6 +241,13 @@ fn count_sse_events(bytes: &[u8]) -> u64 {String::from_utf8_lossy(bytes).matches("event:").count() as u64}+fn now_ms() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis() as u64+}+// ---------------------------------------------------------------------------// Error mapping// ---------------------------------------------------------------------------@@ -258,6 +277,26 @@ fn map_cursor_error_to_response(err: &client::CursorError) -> Response {}}+fn map_cursor_decode_error_to_response(err: &CursorDecodeError) -> Response {+ match err.status() {+ Some(401 | 403) => json_error(+ StatusCode::UNAUTHORIZED,+ "authentication_error",+ err.to_string(),+ ),+ Some(429) => json_error(+ StatusCode::TOO_MANY_REQUESTS,+ "rate_limit_error",+ err.to_string(),+ ),+ _ => json_error(+ StatusCode::BAD_GATEWAY,+ "api_error",+ format!("Response decoding error: {err}"),+ ),+ }+}+// ---------------------------------------------------------------------------// CLI// ---------------------------------------------------------------------------@@ -266,9 +305,15 @@ pub(crate) struct CursorCli;impl CliHandlers for CursorCli {fn login(&self) -> Result<(), anyhow::Error> {- anyhow::bail!(- "cursor: browser login not supported; use env CCP_CURSOR_AUTH_TOKEN or CURSOR_AUTH_TOKEN"- );+ let auth = run_cursor_login()?.ok_or_else(|| anyhow::anyhow!("Cursor login timed out"))?;+ println!("Cursor auth saved in {}", auth.source);+ if let Some(ref user_id) = auth.user_id {+ println!("User: {user_id}");+ }+ if let Some(ref email) = auth.email {+ println!("Email: {email}");+ }+ Ok(())}fn device(&self) -> Result<(), anyhow::Error> {@@ -276,9 +321,21 @@ impl CliHandlers for CursorCli {}fn status(&self) -> Result<(), anyhow::Error> {- match load_cursor_token() {- Some(_) => {- println!("Cursor auth token: found");+ match load_cursor_auth()? {+ Some(auth) => {+ println!("Auth source: {}", auth.source);+ if let Some(ref user_id) = auth.user_id {+ println!("User: {user_id}");+ }+ if let Some(ref email) = auth.email {+ println!("Email: {email}");+ }+ if let Some(expires) = auth.expires {+ let remaining = expires.saturating_sub(now_ms()) / 1000;+ println!("Access token expires in: {remaining}s");+ } else {+ println!("Access token expiry: unknown");+ }Ok(())}None => {@@ -288,8 +345,9 @@ impl CliHandlers for CursorCli {}fn logout(&self) -> Result<(), anyhow::Error> {+ clear_cursor_auth()?;println!(- "cursor: env-based auth has no persistent file to clear; unset CCP_CURSOR_AUTH_TOKEN or CURSOR_AUTH_TOKEN"+ "Cursor persistent auth cleared. Unset CCP_CURSOR_AUTH_TOKEN or CURSOR_AUTH_TOKEN if using env auth.");Ok(())}@@ -311,23 +369,6 @@ mod tests {assert!(models.contains(&"cursor-ask".to_string()));}- #[test]- fn cursor_cli_status_unauthenticated() {- // Unset env vars for the test scope- unsafe {- std::env::remove_var("CCP_CURSOR_AUTH_TOKEN");- std::env::remove_var("CURSOR_AUTH_TOKEN");- }- let result = CURSOR_CLI.status();- assert!(result.is_err());- assert!(- result- .unwrap_err()- .to_string()- .contains("Not authenticated")- );- }-#[test]fn cursor_cli_logout_does_not_error() {let result = CURSOR_CLI.logout();diff --git a/src/providers/cursor/response.rs b/src/providers/cursor/response.rsindex e2867aa..2bc7258 100644--- a/src/providers/cursor/response.rs+++ b/src/providers/cursor/response.rs@@ -2,7 +2,7 @@ use crate::anthropic::schema::MessagesRequest;use crate::providers::cursor::client::{CursorUpstreamResponse, decode_frame_payload, decode_upstream_frames,};-use crate::providers::cursor::connect::{FLAG_END, parse_connect_error};+use crate::providers::cursor::connect::{ConnectEndError, FLAG_END, parse_connect_error};use crate::providers::cursor::proto::AgentServerMessage;/// A decoded event from the Cursor upstream response stream.@@ -26,12 +26,39 @@ pub enum CursorStreamEvent {End,}+#[derive(Debug, Clone)]+pub enum CursorDecodeError {+ ConnectEnd(ConnectEndError),+ Decode(String),+}++impl CursorDecodeError {+ pub fn status(&self) -> Option<u16> {+ match self {+ CursorDecodeError::ConnectEnd(err) => Some(err.status),+ CursorDecodeError::Decode(_) => None,+ }+ }+}++impl std::fmt::Display for CursorDecodeError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ CursorDecodeError::ConnectEnd(err) => write!(f, "{err}"),+ CursorDecodeError::Decode(message) => write!(f, "{message}"),+ }+ }+}++impl std::error::Error for CursorDecodeError {}+/// Decode upstream response bytes into a sequence of CursorStreamEvents.////// Returns both the events and the final usage for the response, since the/// upstream may send multiple update frames.-pub fn decode_upstream_response(body: &[u8]) -> Result<Vec<CursorStreamEvent>, String> {- let frames = decode_upstream_frames(body).map_err(|e| e.to_string())?;+pub fn decode_upstream_response(body: &[u8]) -> Result<Vec<CursorStreamEvent>, CursorDecodeError> {+ let frames =+ decode_upstream_frames(body).map_err(|e| CursorDecodeError::Decode(e.to_string()))?;let mut events = Vec::new();for frame in &frames {@@ -39,7 +66,7 @@ pub fn decode_upstream_response(body: &[u8]) -> Result<Vec<CursorStreamEvent>, S// Check for Connect error in end frameif !frame.payload.is_empty() {if let Some(err) = parse_connect_error(&frame.payload) {- return Err(format!("{err}"));+ return Err(CursorDecodeError::ConnectEnd(err));}}events.push(CursorStreamEvent::End);@@ -63,7 +90,7 @@ pub fn decode_cursor_upstream(upstream: &CursorUpstreamResponse,message_id: &str,model: &str,-) -> Result<serde_json::Value, String> {+) -> Result<serde_json::Value, CursorDecodeError> {let events = decode_upstream_response(&upstream.body)?;let mut text_content = String::new();@@ -268,7 +295,9 @@ mod tests {let frame = encode_connect_frame(&payload, FLAG_END);let result = decode_upstream_response(&frame);assert!(result.is_err());- assert!(result.unwrap_err().contains("quota exceeded"));+ let err = result.unwrap_err();+ assert_eq!(err.status(), Some(429));+ assert!(err.to_string().contains("quota exceeded"));}#[test]diff --git a/src/providers/cursor/sse.rs b/src/providers/cursor/sse.rsindex c541260..dccacf8 100644--- a/src/providers/cursor/sse.rs+++ b/src/providers/cursor/sse.rs@@ -28,7 +28,7 @@ pub fn frame_cursor_stream(let events = match decode_upstream_response(&upstream.body) {Ok(e) => e,Err(e) => {- return format_sse_error(&e);+ return format_sse_error(&e.to_string());}};diff --git a/tests/cli.rs b/tests/cli.rsindex ecb75ad..ca5e122 100644--- a/tests/cli.rs+++ b/tests/cli.rs@@ -61,13 +61,13 @@ fn provider_auth_status_unauthenticated_and_logout() -> Result<(), Box<dyn std::}#[test]-fn invalid_provider_login_is_unsupported_exit_two() -> Result<(), Box<dyn std::error::Error>> {+fn unsupported_provider_auth_command_exits_two() -> Result<(), Box<dyn std::error::Error>> {let mut cmd = Command::cargo_bin("claude-code-proxy")?;- cmd.args(["cursor", "auth", "login"]);+ cmd.args(["cursor", "auth", "device"]);let output = cmd.output()?;assert_eq!(output.status.code(), Some(2));let out = String::from_utf8(output.stderr)?;- assert!(out.contains("not supported") || out.contains("unsupported"));+ assert!(out.contains("not yet implemented") || out.contains("unsupported"));Ok(())}diff --git a/tests/cursor_native.rs b/tests/cursor_native.rsindex fb38171..0131f19 100644--- a/tests/cursor_native.rs+++ b/tests/cursor_native.rs@@ -255,6 +255,200 @@ fn cursor_error_display_works() {assert!(display.contains("rate limited"));}+#[tokio::test(flavor = "current_thread")]+async fn cursor_client_sends_connect_proto_headers_and_run_request_frame() {+ use axum::{Router, routing::post};+ use claude_code_proxy::providers::cursor::client::CursorHttpClient;+ use claude_code_proxy::providers::cursor::connect::{+ ConnectFrameDecoder, encode_connect_frame,+ };+ use claude_code_proxy::providers::cursor::proto::*;+ use claude_code_proxy::providers::cursor::request::CursorSelectedImage;+ use prost::Message;+ use std::sync::{Arc, Mutex};++ #[derive(Debug, Clone)]+ struct ObservedRequest {+ headers: axum::http::HeaderMap,+ body: Vec<u8>,+ }++ let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let observed: Arc<Mutex<Option<ObservedRequest>>> = Arc::new(Mutex::new(None));+ let observed_handler = Arc::clone(&observed);++ let response_body = {+ let msg = AgentServerMessage {+ interaction_update: Some(InteractionUpdate {+ thinking_delta: None,+ text_delta: Some(TextDelta { text: "ok".into() }),+ turn_ended: Some(TurnEnded {+ input_tokens: 1,+ output_tokens: 1,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ }),+ }),+ exec_server_message: None,+ };+ let mut payload = Vec::new();+ msg.encode(&mut payload).unwrap();+ let mut body = encode_connect_frame(&payload, 0).to_vec();+ body.extend_from_slice(&encode_connect_frame(b"", 2));+ body+ };++ let app = Router::new().route(+ "/agent.v1.AgentService/Run",+ post(+ move |headers: axum::http::HeaderMap, body: axum::body::Bytes| {+ let response_body = response_body.clone();+ let observed_handler = Arc::clone(&observed_handler);+ async move {+ *observed_handler.lock().unwrap() = Some(ObservedRequest {+ headers,+ body: body.to_vec(),+ });+ (+ [(+ axum::http::header::CONTENT_TYPE,+ "application/connect+proto",+ )],+ response_body,+ )+ }+ },+ ),+ );++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let mock_url = format!("http://{}", addr);++ unsafe {+ std::env::set_var("CCP_CURSOR_BASE_URL", &mock_url);+ std::env::set_var("CCP_CURSOR_CLIENT_VERSION", "test-client-version");+ }++ let _handle = tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });++ tokio::time::sleep(std::time::Duration::from_millis(50)).await;++ let client = CursorHttpClient::new();+ let upstream = client+ .run_agent(+ "wire-token",+ "wire prompt",+ "cursor:gpt-5.5",+ &[CursorSelectedImage {+ data: "aGVsbG8=".into(),+ uuid: "image-id".into(),+ path: "claude-image-1.png".into(),+ mime_type: "image/png".into(),+ }],+ )+ .await+ .expect("mock upstream request should succeed");+ assert!(upstream.is_success());++ let observed = observed.lock().unwrap().clone().expect("request captured");+ assert_eq!(+ observed+ .headers+ .get(axum::http::header::AUTHORIZATION)+ .and_then(|v| v.to_str().ok()),+ Some("Bearer wire-token")+ );+ assert_eq!(+ observed+ .headers+ .get(axum::http::header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok()),+ Some("application/connect+proto")+ );+ assert_eq!(+ observed+ .headers+ .get("connect-protocol-version")+ .and_then(|v| v.to_str().ok()),+ Some("1")+ );+ assert_eq!(+ observed+ .headers+ .get("x-cursor-client-type")+ .and_then(|v| v.to_str().ok()),+ Some("cli")+ );+ assert_eq!(+ observed+ .headers+ .get("x-cursor-client-version")+ .and_then(|v| v.to_str().ok()),+ Some("test-client-version")+ );+ assert_eq!(+ observed+ .headers+ .get("x-cursor-streaming")+ .and_then(|v| v.to_str().ok()),+ Some("true")+ );+ let request_id = observed+ .headers+ .get("x-request-id")+ .and_then(|v| v.to_str().ok())+ .expect("x-request-id");+ assert_eq!(+ observed+ .headers+ .get("x-original-request-id")+ .and_then(|v| v.to_str().ok()),+ Some(request_id)+ );++ let mut decoder = ConnectFrameDecoder::new();+ let frames = decoder.push(&observed.body).unwrap();+ assert_eq!(frames.len(), 1);+ assert_eq!(frames[0].flags, 0);+ let msg = AgentClientMessage::decode(&frames[0].payload[..]).unwrap();+ let run = msg.run_request.expect("run request");+ assert!(msg.client_heartbeat.is_none());+ assert_eq!(run.conversation_id, "");+ assert_eq!(run.conversation_group_id, "");+ assert!(run.client_supports_inline_images);+ assert!(!run.exclude_workspace_context);+ assert_eq!(run.requested_model.unwrap().model_id, "gpt-5.5");+ let user_message = run+ .action+ .unwrap()+ .user_message_action+ .unwrap()+ .user_message+ .unwrap();+ assert_eq!(user_message.text, "wire prompt");+ assert_eq!(user_message.message_id, request_id);+ assert_eq!(user_message.mode, "AGENT_MODE_AGENT");+ let image = user_message+ .selected_context+ .unwrap()+ .selected_images+ .into_iter()+ .next()+ .unwrap();+ assert_eq!(image.data, "aGVsbG8=");+ assert_eq!(image.uuid, "image-id");+ assert_eq!(image.path, "claude-image-1.png");+ assert_eq!(image.mime_type, "image/png");++ unsafe {+ std::env::remove_var("CCP_CURSOR_BASE_URL");+ std::env::remove_var("CCP_CURSOR_CLIENT_VERSION");+ }+}+// ---------------------------------------------------------------------------// Response decoding// ---------------------------------------------------------------------------@@ -701,6 +895,166 @@ async fn cursor_provider_handle_messages_returns_anthropic_json() {}}+#[tokio::test(flavor = "current_thread")]+async fn cursor_proxy_http_path_reaches_mock_cursor_upstream() {+ use axum::{Router, routing::post};+ use claude_code_proxy::providers::cursor::connect::{+ ConnectFrameDecoder, encode_connect_frame,+ };+ use claude_code_proxy::providers::cursor::proto::*;+ use prost::Message;+ use std::sync::{Arc, Mutex};++ #[derive(Debug, Clone)]+ struct ObservedRequest {+ authorization: Option<String>,+ body: Vec<u8>,+ }++ let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let observed: Arc<Mutex<Option<ObservedRequest>>> = Arc::new(Mutex::new(None));+ let observed_handler = Arc::clone(&observed);++ let response_body = {+ let text_msg = AgentServerMessage {+ interaction_update: Some(InteractionUpdate {+ thinking_delta: None,+ text_delta: Some(TextDelta {+ text: "proxy path works".into(),+ }),+ turn_ended: None,+ }),+ exec_server_message: None,+ };+ let mut text_payload = Vec::new();+ text_msg.encode(&mut text_payload).unwrap();++ let usage_msg = AgentServerMessage {+ interaction_update: Some(InteractionUpdate {+ thinking_delta: None,+ text_delta: None,+ turn_ended: Some(TurnEnded {+ input_tokens: 12,+ output_tokens: 3,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ }),+ }),+ exec_server_message: None,+ };+ let mut usage_payload = Vec::new();+ usage_msg.encode(&mut usage_payload).unwrap();++ let mut body = encode_connect_frame(&text_payload, 0).to_vec();+ body.extend_from_slice(&encode_connect_frame(&usage_payload, 0));+ body.extend_from_slice(&encode_connect_frame(b"", 2));+ body+ };++ let upstream_app = Router::new().route(+ "/agent.v1.AgentService/Run",+ post(+ move |headers: axum::http::HeaderMap, body: axum::body::Bytes| {+ let response_body = response_body.clone();+ let observed_handler = Arc::clone(&observed_handler);+ async move {+ *observed_handler.lock().unwrap() = Some(ObservedRequest {+ authorization: headers+ .get(axum::http::header::AUTHORIZATION)+ .and_then(|v| v.to_str().ok())+ .map(str::to_string),+ body: body.to_vec(),+ });+ (+ [(+ axum::http::header::CONTENT_TYPE,+ "application/connect+proto",+ )],+ response_body,+ )+ }+ },+ ),+ );++ let upstream_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let upstream_addr = upstream_listener.local_addr().unwrap();+ let upstream_url = format!("http://{}", upstream_addr);+ let _upstream_handle = tokio::spawn(async move {+ axum::serve(upstream_listener, upstream_app).await.unwrap();+ });++ let proxy_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let proxy_addr = proxy_listener.local_addr().unwrap();+ let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();+ let _proxy_handle = tokio::spawn(async move {+ claude_code_proxy::server::serve_listener(proxy_listener, None, async move {+ let _ = shutdown_rx.await;+ })+ .await+ .unwrap();+ });++ unsafe {+ std::env::set_var("CCP_CURSOR_BASE_URL", &upstream_url);+ std::env::set_var("CCP_CURSOR_AUTH_TOKEN", "proxy-token");+ std::env::set_var("CCP_CURSOR_CLIENT_VERSION", "proxy-test-version");+ }++ tokio::time::sleep(std::time::Duration::from_millis(50)).await;++ let client = reqwest::Client::new();+ let resp = client+ .post(format!("http://{proxy_addr}/v1/messages"))+ .header("authorization", "Bearer ignored")+ .json(&serde_json::json!({+ "model": "cursor:gpt-5.5",+ "max_tokens": 64,+ "messages": [{"role": "user", "content": "hello over proxy"}]+ }))+ .send()+ .await+ .unwrap();++ assert_eq!(resp.status(), reqwest::StatusCode::OK);+ let json: serde_json::Value = resp.json().await.unwrap();+ assert_eq!(json["content"][0]["text"], "proxy path works");+ assert_eq!(json["usage"]["input_tokens"], 12);+ assert_eq!(json["usage"]["output_tokens"], 3);++ let observed = observed+ .lock()+ .unwrap()+ .clone()+ .expect("upstream request captured");+ assert_eq!(+ observed.authorization.as_deref(),+ Some("Bearer proxy-token")+ );++ let mut decoder = ConnectFrameDecoder::new();+ let frames = decoder.push(&observed.body).unwrap();+ assert_eq!(frames.len(), 1);+ let msg = AgentClientMessage::decode(&frames[0].payload[..]).unwrap();+ let user_message = msg+ .run_request+ .unwrap()+ .action+ .unwrap()+ .user_message_action+ .unwrap()+ .user_message+ .unwrap();+ assert!(user_message.text.contains("hello over proxy"));++ let _ = shutdown_tx.send(());+ unsafe {+ std::env::remove_var("CCP_CURSOR_BASE_URL");+ std::env::remove_var("CCP_CURSOR_AUTH_TOKEN");+ std::env::remove_var("CCP_CURSOR_CLIENT_VERSION");+ }+}+// ---------------------------------------------------------------------------// Cursor tool bridge integration tests// ---------------------------------------------------------------------------