mirror of
https://wget.la/https://github.com/leookun/cursor-byok
synced 2026-12-01 09:15:33 +08:00
feat: update desktop settings and server compatibility
This commit is contained in:
1 parent
8942287a27
commit
17342167ac
113 files changed
+2424
-19109
No files matched your search
@@ -52,23 +52,24 @@ async fn inject_if_missing_at(path: &Path) -> Result<()> {
|
||||
.execute(&mut connection)
|
||||
.await?;
|
||||
|
||||
let token = local_token()?;
|
||||
let account = sqlx::query("SELECT CAST(value AS TEXT) AS value FROM ItemTable WHERE key = ?")
|
||||
.bind("cursorAuth/accessToken")
|
||||
.fetch_optional(&mut connection)
|
||||
.await?;
|
||||
if account.is_some_and(|row| {
|
||||
row.try_get::<String, _>("value")
|
||||
.is_ok_and(|value| !value.trim().is_empty())
|
||||
.is_ok_and(|value| !value.trim().is_empty() && value != token)
|
||||
}) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let token = local_token()?;
|
||||
let values = [
|
||||
("cursorAuth/accessToken", token.as_str()),
|
||||
("cursorAuth/refreshToken", token.as_str()),
|
||||
("cursorAuth/cachedEmail", EMAIL),
|
||||
("cursorAuth/cachedSignUpType", SIGN_UP_TYPE),
|
||||
("cursorAuth/stripeMembershipAuthId", SUBJECT),
|
||||
("cursorAuth/stripeMembershipType", MEMBERSHIP_TYPE),
|
||||
("cursorAuth/stripeSubscriptionStatus", SUBSCRIPTION_STATUS),
|
||||
];
|
||||
@@ -89,7 +90,17 @@ async fn inject_if_missing_at(path: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn local_token() -> Result<String> {
|
||||
pub(crate) fn is_local_cursor_authorization(authorization: &str) -> bool {
|
||||
authorization
|
||||
.strip_prefix("Bearer ")
|
||||
.is_some_and(is_local_cursor_token)
|
||||
}
|
||||
|
||||
fn is_local_cursor_token(token: &str) -> bool {
|
||||
local_token().is_ok_and(|local| local == token)
|
||||
}
|
||||
|
||||
pub(super) fn local_token() -> Result<String> {
|
||||
let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"HS256","typ":"JWT"}"#);
|
||||
let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json!({
|
||||
"sub": SUBJECT,
|
||||
@@ -101,3 +112,64 @@ fn local_token() -> Result<String> {
|
||||
}))?);
|
||||
Ok(format!("{header}.{payload}.{SUBJECT}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn reinjection_repairs_local_membership_cache() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("state.vscdb");
|
||||
inject_if_missing_at(&path).await.unwrap();
|
||||
|
||||
let mut connection = SqliteConnection::connect(&format!("sqlite:{}", path.display()))
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("UPDATE ItemTable SET value = 'free' WHERE key = ?")
|
||||
.bind("cursorAuth/stripeMembershipType")
|
||||
.execute(&mut connection)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("DELETE FROM ItemTable WHERE key = ?")
|
||||
.bind("cursorAuth/stripeMembershipAuthId")
|
||||
.execute(&mut connection)
|
||||
.await
|
||||
.unwrap();
|
||||
drop(connection);
|
||||
|
||||
inject_if_missing_at(&path).await.unwrap();
|
||||
|
||||
let mut connection = SqliteConnection::connect(&format!("sqlite:{}", path.display()))
|
||||
.await
|
||||
.unwrap();
|
||||
let membership_type: String =
|
||||
sqlx::query_scalar("SELECT CAST(value AS TEXT) FROM ItemTable WHERE key = ?")
|
||||
.bind("cursorAuth/stripeMembershipType")
|
||||
.fetch_one(&mut connection)
|
||||
.await
|
||||
.unwrap();
|
||||
let membership_auth_id: String =
|
||||
sqlx::query_scalar("SELECT CAST(value AS TEXT) FROM ItemTable WHERE key = ?")
|
||||
.bind("cursorAuth/stripeMembershipAuthId")
|
||||
.fetch_one(&mut connection)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(membership_type, MEMBERSHIP_TYPE);
|
||||
assert_eq!(membership_auth_id, SUBJECT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recognizes_only_the_injected_cursor_token() {
|
||||
let token = local_token().unwrap();
|
||||
assert!(is_local_cursor_token(&token));
|
||||
assert!(is_local_cursor_authorization(&format!("Bearer {token}")));
|
||||
assert!(!is_local_cursor_authorization(&token));
|
||||
assert!(!is_local_cursor_authorization(
|
||||
"Bearer official-cursor-token"
|
||||
));
|
||||
assert!(!is_local_cursor_token("official-cursor-token"));
|
||||
assert!(!is_local_cursor_token(""));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Exposes the local desktop application integration.
|
||||
mod account;
|
||||
mod ca;
|
||||
mod process;
|
||||
mod proxy;
|
||||
mod settings;
|
||||
|
||||
@@ -21,8 +22,16 @@ pub(crate) fn proxy_host_allowed(host: &str) -> bool {
|
||||
proxy::is_cursor_host(host)
|
||||
}
|
||||
|
||||
fn integration_prerequisites_ready(ca: &CaState, backend_ready: bool) -> bool {
|
||||
matches!(ca, CaState::Ready) && backend_ready
|
||||
pub(crate) fn request_uses_local_cursor_token(headers: &axum::http::HeaderMap) -> bool {
|
||||
headers
|
||||
.get(axum::http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.is_some_and(account::is_local_cursor_authorization)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn local_cursor_authorization() -> String {
|
||||
format!("Bearer {}", account::local_token().unwrap())
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
@@ -49,6 +58,7 @@ pub struct CursorHarnessStatus {
|
||||
pub configured_models: usize,
|
||||
pub enabled_models: usize,
|
||||
pub integration: IntegrationState,
|
||||
pub settings_applied: bool,
|
||||
pub proxy_url: Option<String>,
|
||||
pub ca_install_command: Option<String>,
|
||||
}
|
||||
@@ -103,7 +113,10 @@ impl CursorHarness {
|
||||
let configured_models = models.len();
|
||||
let enabled_models = configured_models;
|
||||
let ca = self.inner.ca.state()?;
|
||||
if integration_prerequisites_ready(&ca, self.inner.backend_addr.read().is_some()) {
|
||||
if self.inner.store.cursor_takeover_enabled().await?
|
||||
&& matches!(ca, CaState::Ready)
|
||||
&& self.inner.backend_addr.read().is_some()
|
||||
{
|
||||
self.enable().await?;
|
||||
}
|
||||
let proxy = self.inner.proxy.lock().await;
|
||||
@@ -124,6 +137,7 @@ impl CursorHarness {
|
||||
configured_models,
|
||||
enabled_models,
|
||||
integration,
|
||||
settings_applied,
|
||||
proxy_url,
|
||||
ca_install_command: self.inner.ca.install_command(),
|
||||
})
|
||||
@@ -139,9 +153,23 @@ impl CursorHarness {
|
||||
}
|
||||
|
||||
pub async fn set_enabled(&self, enabled: bool) -> Result<CursorHarnessStatus> {
|
||||
let settings_applied = {
|
||||
let proxy = self.inner.proxy.lock().await;
|
||||
proxy
|
||||
.url()
|
||||
.as_deref()
|
||||
.map(settings::settings_match)
|
||||
.transpose()?
|
||||
.unwrap_or(false)
|
||||
};
|
||||
if enabled {
|
||||
if !settings_applied {
|
||||
process::terminate_cursor().await?;
|
||||
}
|
||||
self.inner.store.set_cursor_takeover_enabled(true).await?;
|
||||
self.enable().await?;
|
||||
} else {
|
||||
self.inner.store.set_cursor_takeover_enabled(false).await?;
|
||||
self.disable().await?;
|
||||
}
|
||||
self.status().await
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
//! Terminates the Cursor desktop process before an explicit takeover.
|
||||
|
||||
use tokio::process::Command;
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
pub async fn terminate_cursor() -> Result<()> {
|
||||
terminate_platform_cursor().await
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
async fn terminate_platform_cursor() -> Result<()> {
|
||||
terminate_unix_process("Cursor").await
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
async fn terminate_platform_cursor() -> Result<()> {
|
||||
terminate_unix_process("cursor").await?;
|
||||
terminate_unix_process("Cursor").await
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
async fn terminate_unix_process(name: &str) -> Result<()> {
|
||||
let running = Command::new("pgrep").args(["-x", name]).status().await?;
|
||||
if !running.success() {
|
||||
return match running.code() {
|
||||
Some(1) => Ok(()),
|
||||
_ => Err(Error::Config(format!(
|
||||
"failed to inspect the {name} process"
|
||||
))),
|
||||
};
|
||||
}
|
||||
let terminated = Command::new("pkill").args(["-x", name]).status().await?;
|
||||
if terminated.success() || terminated.code() == Some(1) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Config(format!(
|
||||
"failed to terminate the {name} process"
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
async fn terminate_platform_cursor() -> Result<()> {
|
||||
let processes = Command::new("tasklist")
|
||||
.args(["/FI", "IMAGENAME eq Cursor.exe", "/NH", "/FO", "CSV"])
|
||||
.output()
|
||||
.await?;
|
||||
if !processes.status.success() {
|
||||
return Err(Error::Config(
|
||||
"failed to inspect the Cursor.exe process".into(),
|
||||
));
|
||||
}
|
||||
if !String::from_utf8_lossy(&processes.stdout)
|
||||
.to_ascii_lowercase()
|
||||
.contains("cursor.exe")
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let terminated = Command::new("taskkill")
|
||||
.args(["/F", "/T", "/IM", "Cursor.exe"])
|
||||
.status()
|
||||
.await?;
|
||||
if terminated.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Config(
|
||||
"failed to terminate the Cursor.exe process".into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
|
||||
async fn terminate_platform_cursor() -> Result<()> {
|
||||
Err(Error::Config(format!(
|
||||
"terminating Cursor is unsupported on {}",
|
||||
std::env::consts::OS
|
||||
)))
|
||||
}
|
||||
@@ -159,6 +159,10 @@ fn is_local_path(path: &str) -> bool {
|
||||
path,
|
||||
"/agent.v1.AgentService/RunSSE"
|
||||
| "/aiserver.v1.BidiService/BidiAppend"
|
||||
| "/aiserver.v1.AiService/AvailableDocs"
|
||||
| "/aiserver.v1.DashboardService/GetEffectiveUserPlugins"
|
||||
| "/aiserver.v1.DashboardService/GetUserPrivacyMode"
|
||||
| "/agent.v1.AgentService/UpdateConversationMetadata"
|
||||
| "/aiserver.v1.AiService/GetServerConfig"
|
||||
| "/aiserver.v1.ServerConfigService/GetServerConfig"
|
||||
| "/aiserver.v1.AiService/AvailableModels"
|
||||
@@ -169,6 +173,7 @@ fn is_local_path(path: &str) -> bool {
|
||||
| "/aiserver.v1.AiService/GetDefaultModel"
|
||||
| "/aiserver.v1.AiService/GetDefaultModelNudgeData"
|
||||
| "/aiserver.v1.AuthService/GetEmail"
|
||||
| "/aiserver.v1.AuthService/GetUserMeta"
|
||||
| "/aiserver.v1.DashboardService/GetMe"
|
||||
| "/aiserver.v1.DashboardService/GetTeams"
|
||||
| "/aiserver.v1.DashboardService/GetUserProfile"
|
||||
@@ -182,6 +187,7 @@ fn is_local_path(path: &str) -> bool {
|
||||
| "/aiserver.v1.NetworkService/IsConnected"
|
||||
| "/aiserver.v1.AnalyticsService/BootstrapStatsig"
|
||||
| "/auth/full_stripe_profile"
|
||||
| "/auth/stripe_profile"
|
||||
)
|
||||
}
|
||||
|
||||
@@ -202,6 +208,13 @@ mod tests {
|
||||
"/aiserver.v1.AiService/GetDefaultModelForCli",
|
||||
"/aiserver.v1.AiService/GetDefaultModel",
|
||||
"/aiserver.v1.AiService/GetDefaultModelNudgeData",
|
||||
"/aiserver.v1.AiService/AvailableDocs",
|
||||
"/aiserver.v1.DashboardService/GetEffectiveUserPlugins",
|
||||
"/aiserver.v1.DashboardService/GetUserPrivacyMode",
|
||||
"/aiserver.v1.AuthService/GetUserMeta",
|
||||
"/agent.v1.AgentService/UpdateConversationMetadata",
|
||||
"/auth/full_stripe_profile",
|
||||
"/auth/stripe_profile",
|
||||
] {
|
||||
assert!(is_local_path(path), "{path} must not reach Cursor upstream");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user