feat: initialize server structure and database schema

- Added initial server setup with Cargo.toml defining dependencies and project structure.
- Created build.rs for generating protobuf bindings and validating wire contracts.
- Established database schema with initial migration files for conversations, messages, and runs.
- Introduced tools and prompts for Cursor functionality, enhancing user interaction capabilities.
This commit is contained in:
leookun committed 2026-08-30 01:33:39 +08:00
1 parent d200b3791d
commit 44e2d8057a
206 files changed
+37923 -21

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
//! Integrates local Cursor account state.
use std::path::{Path, PathBuf};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use serde_json::json;
use sqlx::{Connection, Row, SqliteConnection};
use crate::{Error, Result};
const EMAIL: &str = "cursor@ai.com";
const SIGN_UP_TYPE: &str = "Google";
const SUBJECT: &str = "cursor-local-user";
const MEMBERSHIP_TYPE: &str = "ultra";
const SUBSCRIPTION_STATUS: &str = "active";
pub async fn inject_if_missing() -> Result<()> {
inject_if_missing_at(&state_db_path()?).await
}
fn state_db_path() -> Result<PathBuf> {
let home = dirs::home_dir()
.ok_or_else(|| Error::Config("cannot resolve user home directory".into()))?;
match std::env::consts::OS {
"macos" => {
Ok(home.join("Library/Application Support/Cursor/User/globalStorage/state.vscdb"))
}
"windows" => Ok(std::env::var_os("APPDATA")
.map(PathBuf::from)
.unwrap_or_else(|| home.join("AppData/Roaming"))
.join("Cursor/User/globalStorage/state.vscdb")),
"linux" => Ok(std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| home.join(".config"))
.join("Cursor/User/globalStorage/state.vscdb")),
platform => Err(Error::Config(format!(
"Cursor account injection is unsupported on {platform}"
))),
}
}
async fn inject_if_missing_at(path: &Path) -> Result<()> {
if let Some(parent) = path.parent() {
tokio::fs::create_dir_all(parent).await?;
}
let options = sqlx::sqlite::SqliteConnectOptions::new()
.filename(path)
.create_if_missing(true);
let mut connection = SqliteConnection::connect_with(&options).await?;
sqlx::query(
"CREATE TABLE IF NOT EXISTS ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)",
)
.execute(&mut connection)
.await?;
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())
}) {
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/stripeMembershipType", MEMBERSHIP_TYPE),
("cursorAuth/stripeSubscriptionStatus", SUBSCRIPTION_STATUS),
];
let mut transaction = connection.begin().await?;
for (key, value) in values {
sqlx::query("INSERT OR REPLACE INTO ItemTable(key, value) VALUES(?, ?)")
.bind(key)
.bind(value)
.execute(&mut *transaction)
.await?;
}
transaction.commit().await?;
tracing::info!(
email = EMAIL,
subject = SUBJECT,
"injected local Cursor account"
);
Ok(())
}
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,
"email": EMAIL,
"type": "session",
"iss": "cursor-client",
"scope": "openid profile email",
"exp": 4070908800_u64
}))?);
Ok(format!("{header}.{payload}.{SUBJECT}"))
}
+239
View File
@@ -0,0 +1,239 @@
//! Installs and manages the local certificate authority.
use std::{fs, path::PathBuf};
#[cfg(target_os = "macos")]
use std::process::Command;
#[cfg(target_os = "windows")]
mod windows;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use rcgen::{
BasicConstraints, CertificateParams, DistinguishedName, DnType, IsCa, Issuer, KeyPair,
KeyUsagePurpose, RsaKeySize, PKCS_RSA_SHA256,
};
#[cfg(target_os = "macos")]
use sha1::{Digest, Sha1};
use time::{Duration, OffsetDateTime};
use x509_parser::prelude::FromDer;
use crate::{config::managed_data_dir, Error, Result};
use super::CaState;
#[derive(Clone)]
pub struct CaManager {
dir: PathBuf,
}
pub struct LoadedCa {
pub issuer: Issuer<'static, KeyPair>,
}
impl CaManager {
pub fn managed() -> Result<Self> {
Ok(Self {
dir: managed_data_dir()?.join("ca"),
})
}
fn cert_path(&self) -> PathBuf {
self.dir.join("ca.crt")
}
fn key_path(&self) -> PathBuf {
self.dir.join("ca.key")
}
pub fn state(&self) -> Result<CaState> {
let cert = fs::read_to_string(self.cert_path());
let key = fs::read_to_string(self.key_path());
match (cert, key) {
(Err(cert_error), Err(key_error))
if cert_error.kind() == std::io::ErrorKind::NotFound
&& key_error.kind() == std::io::ErrorKind::NotFound =>
{
Ok(CaState::Missing)
}
(Ok(cert), Ok(key)) => {
if parse_issuer(&cert, &key).is_err() {
return Ok(CaState::Invalid);
}
Ok(if is_installed(&cert)? {
CaState::Ready
} else {
CaState::Untrusted
})
}
_ => Ok(CaState::Invalid),
}
}
pub fn load(&self) -> Result<LoadedCa> {
let cert = fs::read_to_string(self.cert_path())?;
let key = fs::read_to_string(self.key_path())?;
Ok(LoadedCa {
issuer: parse_issuer(&cert, &key)?,
})
}
pub fn install_command(&self) -> Option<String> {
let path = self.cert_path().to_string_lossy().replace('\'', "'\\''");
match std::env::consts::OS {
"macos" => dirs::home_dir().map(|_| {
format!(
"sudo security add-trusted-cert -d -r trustRoot -p ssl -k /Library/Keychains/System.keychain '{}'",
path
)
}),
"windows" => Some(format!(
"certutil -addstore -f Root \"{}\"",
self.cert_path().display()
)),
"linux" => {
let anchor = linux_anchor_file();
Some(format!(
"sudo cp '{}' '{}' && sudo {}",
path,
anchor.display(),
linux_refresh_command()
))
}
_ => None,
}
}
pub fn initialize_local(&self) -> Result<()> {
match self.state()? {
CaState::Invalid => {
return Err(Error::Config("CA files are incomplete or invalid".into()))
}
CaState::Ready => return Ok(()),
CaState::Missing => self.generate()?,
CaState::Untrusted => {}
}
Ok(())
}
fn generate(&self) -> Result<()> {
fs::create_dir_all(&self.dir)?;
#[cfg(unix)]
fs::set_permissions(&self.dir, fs::Permissions::from_mode(0o700))?;
let key = KeyPair::generate_rsa_for(&PKCS_RSA_SHA256, RsaKeySize::_3072)
.map_err(|error| Error::Config(format!("generate CA key: {error}")))?;
let mut params = CertificateParams::new(Vec::<String>::new())
.map_err(|error| Error::Config(format!("create CA parameters: {error}")))?;
let mut name = DistinguishedName::new();
name.push(DnType::CommonName, "Cursor BYOK Local CA");
name.push(DnType::OrganizationName, "Cursor BYOK");
params.distinguished_name = name;
params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
params.key_usages = vec![
KeyUsagePurpose::DigitalSignature,
KeyUsagePurpose::KeyCertSign,
KeyUsagePurpose::CrlSign,
];
params.not_before = OffsetDateTime::now_utc() - Duration::minutes(5);
params.not_after = OffsetDateTime::now_utc() + Duration::days(3652);
let cert = params
.self_signed(&key)
.map_err(|error| Error::Config(format!("generate CA certificate: {error}")))?;
write_atomic(&self.key_path(), key.serialize_pem().as_bytes(), 0o600)?;
write_atomic(&self.cert_path(), cert.pem().as_bytes(), 0o644)?;
Ok(())
}
}
fn parse_issuer(cert: &str, key: &str) -> Result<Issuer<'static, KeyPair>> {
let key =
KeyPair::from_pem(key).map_err(|error| Error::Config(format!("parse CA key: {error}")))?;
let pem = pem::parse(cert).map_err(|error| Error::Config(format!("parse CA PEM: {error}")))?;
let (_, parsed) = x509_parser::certificate::X509Certificate::from_der(pem.contents())
.map_err(|error| Error::Config(format!("parse CA X.509 certificate: {error}")))?;
if parsed.public_key().subject_public_key.data.as_ref() != key.public_key_raw() {
return Err(Error::Config(
"CA certificate and private key do not match".into(),
));
}
if !parsed.validity().is_valid() {
return Err(Error::Config(
"CA certificate is outside its validity period".into(),
));
}
if !parsed
.basic_constraints()
.map_err(|error| Error::Config(format!("read CA constraints: {error}")))?
.is_some_and(|constraints| constraints.value.ca)
{
return Err(Error::Config("certificate is not a CA".into()));
}
Issuer::from_ca_cert_pem(cert, key)
.map_err(|error| Error::Config(format!("parse CA certificate: {error}")))
}
fn write_atomic(path: &std::path::Path, data: &[u8], _mode: u32) -> Result<()> {
let temp = path.with_extension("tmp");
fs::write(&temp, data)?;
#[cfg(unix)]
fs::set_permissions(&temp, fs::Permissions::from_mode(_mode))?;
fs::rename(&temp, path)?;
#[cfg(unix)]
fs::set_permissions(path, fs::Permissions::from_mode(_mode))?;
Ok(())
}
#[cfg(target_os = "macos")]
fn fingerprint(cert: &str) -> Result<String> {
let pem = pem::parse(cert).map_err(|error| Error::Config(format!("parse CA PEM: {error}")))?;
Ok(hex::encode_upper(Sha1::digest(pem.contents())))
}
#[cfg(target_os = "macos")]
fn is_installed(cert: &str) -> Result<bool> {
let fingerprint = fingerprint(cert)?;
for keychain in ["login.keychain-db", "/Library/Keychains/System.keychain"] {
let output = Command::new("security")
.args(["find-certificate", "-a", "-Z", keychain])
.output()?;
if output.status.success() && String::from_utf8_lossy(&output.stdout).contains(&fingerprint)
{
return Ok(true);
}
}
Ok(false)
}
#[cfg(target_os = "windows")]
fn is_installed(cert: &str) -> Result<bool> {
windows::is_installed(cert)
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
fn is_installed(cert: &str) -> Result<bool> {
match fs::read_to_string(linux_anchor_file()) {
Ok(installed) => Ok(installed.trim() == cert.trim()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error.into()),
}
}
const LINUX_ANCHOR_NAME: &str = "cursor-byok-local-ca.crt";
fn linux_anchor_file() -> PathBuf {
if PathBuf::from("/etc/pki/ca-trust/source/anchors").is_dir() {
PathBuf::from("/etc/pki/ca-trust/source/anchors").join(LINUX_ANCHOR_NAME)
} else if PathBuf::from("/etc/ca-certificates/trust-source/anchors").is_dir() {
PathBuf::from("/etc/ca-certificates/trust-source/anchors").join(LINUX_ANCHOR_NAME)
} else {
PathBuf::from("/usr/local/share/ca-certificates").join(LINUX_ANCHOR_NAME)
}
}
fn linux_refresh_command() -> &'static str {
match linux_anchor_file().parent().and_then(|dir| dir.to_str()) {
Some("/usr/local/share/ca-certificates") => "update-ca-certificates",
_ => "update-ca-trust extract",
}
}
+75
View File
@@ -0,0 +1,75 @@
//! Implements Windows-specific certificate authority integration.
//! Native Windows system root-store access without external command-line tools.
use std::{ffi::c_void, io, ptr, slice};
use windows_sys::Win32::Security::Cryptography::{
CertCloseStore, CertEnumCertificatesInStore, CertOpenStore, CERT_STORE_OPEN_EXISTING_FLAG,
CERT_STORE_PROV_SYSTEM_W, CERT_STORE_READONLY_FLAG, CERT_SYSTEM_STORE_LOCAL_MACHINE,
};
use crate::{Error, Result};
const ROOT_STORE: [u16; 5] = [b'R' as u16, b'O' as u16, b'O' as u16, b'T' as u16, 0];
pub(super) fn is_installed(cert: &str) -> Result<bool> {
let der = certificate_der(cert)?;
let store = open_root_store()?;
let mut context = ptr::null();
let mut found = false;
loop {
context = unsafe { CertEnumCertificatesInStore(store, context) };
if context.is_null() {
break;
}
let encoded = unsafe {
slice::from_raw_parts((*context).pbCertEncoded, (*context).cbCertEncoded as usize)
};
if encoded == der {
found = true;
break;
}
}
if !context.is_null() {
unsafe { windows_sys::Win32::Security::Cryptography::CertFreeCertificateContext(context) };
}
close_store(store)?;
Ok(found)
}
fn certificate_der(cert: &str) -> Result<Vec<u8>> {
pem::parse(cert)
.map(|pem| pem.into_contents())
.map_err(|error| Error::Config(format!("parse CA PEM: {error}")))
}
fn open_root_store() -> Result<*mut c_void> {
let flags =
CERT_SYSTEM_STORE_LOCAL_MACHINE | CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG;
let store = unsafe {
CertOpenStore(
CERT_STORE_PROV_SYSTEM_W,
0,
0,
flags,
ROOT_STORE.as_ptr().cast(),
)
};
if store.is_null() {
return Err(Error::Config(format!(
"open Windows LocalMachine Root store: {}",
io::Error::last_os_error()
)));
}
Ok(store)
}
fn close_store(store: *mut c_void) -> Result<()> {
if unsafe { CertCloseStore(store, 0) } == 0 {
return Err(Error::Config(format!(
"close Windows certificate store: {}",
io::Error::last_os_error()
)));
}
Ok(())
}
+202
View File
@@ -0,0 +1,202 @@
//! Exposes the local desktop application integration.
mod account;
mod ca;
mod proxy;
mod settings;
use std::{net::SocketAddr, sync::Arc};
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use crate::{
store::{Store, TabMode, TabSettings},
Error, Result,
};
use self::{ca::CaManager, proxy::ProxyRuntime};
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
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CaState {
Missing,
Untrusted,
Ready,
Invalid,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum IntegrationState {
Disabled,
Enabled,
Degraded,
}
#[derive(Clone, Debug, Serialize)]
pub struct CursorHarnessStatus {
pub platform: &'static str,
pub ca: CaState,
pub configured_models: usize,
pub enabled_models: usize,
pub integration: IntegrationState,
pub proxy_url: Option<String>,
pub ca_install_command: Option<String>,
}
#[derive(Clone, Copy, Debug, Deserialize)]
pub struct SetEnabled {
pub enabled: bool,
}
#[derive(Clone)]
pub struct CursorHarness {
inner: Arc<Inner>,
}
struct Inner {
store: Store,
ca: CaManager,
ca_initialization: Mutex<()>,
backend_addr: RwLock<Option<SocketAddr>>,
tab_mode: Arc<RwLock<TabMode>>,
proxy: Mutex<ProxyRuntime>,
}
impl CursorHarness {
pub fn new(store: Store) -> Result<Self> {
Ok(Self {
inner: Arc::new(Inner {
store,
ca: CaManager::managed()?,
ca_initialization: Mutex::new(()),
backend_addr: RwLock::new(None),
tab_mode: Arc::new(RwLock::new(TabMode::default())),
proxy: Mutex::new(ProxyRuntime::default()),
}),
})
}
pub fn set_backend_addr(&self, addr: SocketAddr) {
*self.inner.backend_addr.write() = Some(addr);
}
pub async fn cleanup_stale_settings(&self) -> Result<()> {
settings::clear_stale_managed_settings()
}
pub async fn status(&self) -> Result<CursorHarnessStatus> {
let models = self.inner.store.models().await?;
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()) {
self.enable().await?;
}
let proxy = self.inner.proxy.lock().await;
let proxy_url = proxy.url();
let settings_applied = proxy_url
.as_deref()
.map(settings::settings_match)
.transpose()?
.unwrap_or(false);
let integration = match (proxy.running(), settings_applied) {
(false, false) => IntegrationState::Disabled,
(true, true) => IntegrationState::Enabled,
_ => IntegrationState::Degraded,
};
Ok(CursorHarnessStatus {
platform: std::env::consts::OS,
ca,
configured_models,
enabled_models,
integration,
proxy_url,
ca_install_command: self.inner.ca.install_command(),
})
}
pub async fn initialize_ca(&self) -> Result<CursorHarnessStatus> {
let _initialization = self.inner.ca_initialization.lock().await;
let manager = self.inner.ca.clone();
tokio::task::spawn_blocking(move || manager.initialize_local())
.await
.map_err(|error| Error::Store(format!("CA initialization task failed: {error}")))??;
self.status().await
}
pub async fn set_enabled(&self, enabled: bool) -> Result<CursorHarnessStatus> {
if enabled {
self.enable().await?;
} else {
self.disable().await?;
}
self.status().await
}
pub async fn set_tab_settings(&self, settings: TabSettings) -> Result<TabSettings> {
let saved = self.inner.store.set_tab_settings(settings).await?;
*self.inner.tab_mode.write() = saved.mode;
Ok(saved)
}
async fn enable(&self) -> Result<()> {
if !matches!(self.inner.ca.state()?, CaState::Ready) {
return Err(Error::Config(
"initialize and trust the CA before enabling Cursor".into(),
));
}
let backend_addr = self
.inner
.backend_addr
.read()
.ok_or_else(|| Error::Config("desktop management server is not ready".into()))?;
let mut proxy = self.inner.proxy.lock().await;
if proxy.running() {
if let Some(url) = proxy.url() {
apply_cursor_configuration(&url).await?;
}
return Ok(());
}
let ca = self.inner.ca.load()?;
let requested_port = self.inner.store.port_settings().await?.proxy_port;
*self.inner.tab_mode.write() = self.inner.store.tab_settings().await?.mode;
let (url, actual_port) = proxy
.start(
backend_addr,
ca,
requested_port,
self.inner.tab_mode.clone(),
)
.await?;
if let Err(error) = self.inner.store.set_proxy_port(actual_port).await {
proxy.stop().await;
return Err(error);
}
if let Err(error) = apply_cursor_configuration(&url).await {
proxy.stop().await;
return Err(error);
}
Ok(())
}
pub async fn disable(&self) -> Result<()> {
settings::clear_proxy_settings()?;
self.inner.proxy.lock().await.stop().await;
Ok(())
}
}
async fn apply_cursor_configuration(proxy_url: &str) -> Result<()> {
account::inject_if_missing().await?;
settings::write_proxy_settings(proxy_url)
}
+171
View File
@@ -0,0 +1,171 @@
//! Configures the local application proxy.
use std::{net::SocketAddr, sync::Arc};
use hudsucker::{
certificate_authority::RcgenAuthority,
hyper::{Request, Uri},
rustls::crypto::aws_lc_rs,
Body, HttpContext, HttpHandler, Proxy, RequestOrResponse,
};
use tokio::{net::TcpListener, sync::oneshot, task::JoinHandle};
use parking_lot::RwLock;
use crate::{
api::cursor::proxy::UPSTREAM_URL_HEADER, cursor::services::tab::is_tab_path, store::TabMode,
Error, Result,
};
use super::ca::LoadedCa;
#[derive(Default)]
pub struct ProxyRuntime {
url: Option<String>,
port: Option<u16>,
stop: Option<oneshot::Sender<()>>,
task: Option<JoinHandle<()>>,
}
impl ProxyRuntime {
pub fn running(&self) -> bool {
self.task.as_ref().is_some_and(|task| !task.is_finished())
}
pub fn url(&self) -> Option<String> {
self.running().then(|| self.url.clone()).flatten()
}
pub async fn start(
&mut self,
backend: SocketAddr,
ca: LoadedCa,
requested_port: u16,
tab_mode: Arc<RwLock<TabMode>>,
) -> Result<(String, u16)> {
if let Some(url) = self.url() {
return Ok((url, self.port.unwrap_or_default()));
}
let listener = bind_proxy_listener(requested_port).await?;
let address = listener.local_addr()?;
let (stop, done) = oneshot::channel();
let authority = RcgenAuthority::new(ca.issuer, 1_000, aws_lc_rs::default_provider());
let proxy = Proxy::builder()
.with_listener(listener)
.with_ca(authority)
.with_rustls_connector(aws_lc_rs::default_provider())
.with_http_handler(CursorRelay { backend, tab_mode })
.with_graceful_shutdown(async move {
let _ = done.await;
})
.build()
.map_err(|error| Error::Store(format!("build Cursor proxy: {error}")))?;
self.stop = Some(stop);
self.url = Some(format!("http://{address}"));
self.port = Some(address.port());
self.task = Some(tokio::spawn(async move {
if let Err(error) = proxy.start().await {
tracing::error!(%error, "Cursor proxy stopped unexpectedly");
}
}));
Ok((self.url.clone().unwrap(), address.port()))
}
pub async fn stop(&mut self) {
if let Some(stop) = self.stop.take() {
let _ = stop.send(());
}
if let Some(task) = self.task.take() {
let _ = tokio::time::timeout(std::time::Duration::from_secs(5), task).await;
}
self.url = None;
self.port = None;
}
}
async fn bind_proxy_listener(requested_port: u16) -> Result<TcpListener> {
let requested = SocketAddr::from(([127, 0, 0, 1], requested_port));
match TcpListener::bind(requested).await {
Ok(listener) => Ok(listener),
Err(error) if requested_port != 0 => {
tracing::warn!(%requested, %error, "configured proxy port unavailable; selecting a random port");
Ok(TcpListener::bind("127.0.0.1:0").await?)
}
Err(error) => Err(error.into()),
}
}
#[derive(Clone)]
struct CursorRelay {
backend: SocketAddr,
tab_mode: Arc<RwLock<TabMode>>,
}
impl HttpHandler for CursorRelay {
async fn handle_request(
&mut self,
_ctx: &HttpContext,
mut request: Request<Body>,
) -> RequestOrResponse {
let original = request.uri().clone();
let locally_routed = should_route_locally(original.path(), *self.tab_mode.read());
if is_cursor_host(original.host().unwrap_or_default()) && locally_routed {
if let Ok(value) = original.to_string().parse() {
request.headers_mut().insert(UPSTREAM_URL_HEADER, value);
}
let path = original
.path_and_query()
.map(|value| value.as_str())
.unwrap_or("/");
if let Ok(uri) = format!("http://{}{}", self.backend, path).parse::<Uri>() {
*request.uri_mut() = uri;
}
}
request.into()
}
async fn should_intercept_connect(
&mut self,
_ctx: &HttpContext,
request: &Request<Body>,
) -> bool {
request
.uri()
.authority()
.is_some_and(|authority| is_cursor_host(authority.host()))
}
async fn should_intercept_tls(
&mut self,
_ctx: &HttpContext,
hello: hudsucker::rustls::server::ClientHello<'_>,
) -> bool {
hello.server_name().is_some_and(is_cursor_host)
}
}
pub fn is_cursor_host(host: &str) -> bool {
let host = host.trim_end_matches('.').to_ascii_lowercase();
matches!(host.as_str(), "api2.cursor.sh" | "api3.cursor.sh") || host.ends_with(".cursor.sh")
}
fn is_local_path(path: &str) -> bool {
matches!(
path,
"/agent.v1.AgentService/RunSSE"
| "/aiserver.v1.BidiService/BidiAppend"
| "/aiserver.v1.AiService/AvailableModels"
| "/agent.v1.AgentService/GetUsableModels"
| "/aiserver.v1.AiService/GetUsableModels"
| "/aiserver.v1.AuthService/GetEmail"
| "/aiserver.v1.DashboardService/GetMe"
| "/aiserver.v1.DashboardService/GetTeams"
| "/aiserver.v1.DashboardService/GetUserProfile"
| "/aiserver.v1.DashboardService/GetCurrentPeriodUsage"
| "/aiserver.v1.DashboardService/GetUsageLimitStatusAndActiveGrants"
| "/aiserver.v1.AnalyticsService/BootstrapStatsig"
| "/auth/full_stripe_profile"
)
}
fn should_route_locally(path: &str, tab_mode: TabMode) -> bool {
is_local_path(path) || (is_tab_path(path) && tab_mode != TabMode::Direct)
}
+109
View File
@@ -0,0 +1,109 @@
//! Integrates local application settings.
use std::{collections::BTreeMap, fs, path::PathBuf};
use serde_json::Value;
use crate::{Error, Result};
const KEYS: [&str; 5] = [
"http.proxy",
"http.proxyKerberosServicePrincipal",
"http.proxySupport",
"cursor.general.disableHttp2",
"http.experimental.systemCertificatesV2",
];
fn path() -> Result<PathBuf> {
let home = dirs::home_dir()
.ok_or_else(|| Error::Config("cannot resolve user home directory".into()))?;
match std::env::consts::OS {
"macos" => Ok(home.join("Library/Application Support/Cursor/User/settings.json")),
"windows" => Ok(std::env::var_os("APPDATA")
.map(PathBuf::from)
.unwrap_or_else(|| home.join("AppData/Roaming"))
.join("Cursor/User/settings.json")),
"linux" => Ok(std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| home.join(".config"))
.join("Cursor/User/settings.json")),
platform => Err(Error::Config(format!(
"Cursor settings are unsupported on {platform}"
))),
}
}
fn read() -> Result<BTreeMap<String, Value>> {
let path = path()?;
let data = match fs::read_to_string(path) {
Ok(data) => data,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
Err(error) => return Err(error.into()),
};
if data.trim().is_empty() {
return Ok(BTreeMap::new());
}
json5::from_str(&data)
.map_err(|error| Error::Config(format!("parse Cursor settings JSONC: {error}")))
}
fn write(settings: &BTreeMap<String, Value>) -> Result<()> {
let path = path()?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let data = serde_json::to_vec_pretty(settings)?;
let temp = path.with_extension("json.tmp");
fs::write(&temp, [data.as_slice(), b"\n"].concat())?;
fs::rename(temp, path)?;
Ok(())
}
pub fn write_proxy_settings(proxy_url: &str) -> Result<()> {
let mut settings = read()?;
settings.insert(KEYS[0].into(), Value::String(proxy_url.into()));
settings.insert(KEYS[1].into(), Value::String(proxy_url.into()));
settings.insert(KEYS[2].into(), Value::String("on".into()));
settings.insert(KEYS[3].into(), Value::Bool(true));
settings.insert(KEYS[4].into(), Value::Bool(true));
write(&settings)
}
pub fn clear_proxy_settings() -> Result<()> {
let mut settings = read()?;
let before = settings.len();
for key in KEYS {
settings.remove(key);
}
if settings.len() != before {
write(&settings)?;
}
Ok(())
}
pub fn settings_match(proxy_url: &str) -> Result<bool> {
let settings = read()?;
Ok(
settings.get(KEYS[0]) == Some(&Value::String(proxy_url.into()))
&& settings.get(KEYS[1]) == Some(&Value::String(proxy_url.into()))
&& settings.get(KEYS[2]) == Some(&Value::String("on".into()))
&& settings.get(KEYS[3]) == Some(&Value::Bool(true))
&& settings.get(KEYS[4]) == Some(&Value::Bool(true)),
)
}
pub fn clear_stale_managed_settings() -> Result<()> {
let settings = read()?;
let managed_signature = settings.get(KEYS[2]) == Some(&Value::String("on".into()))
&& settings.get(KEYS[3]) == Some(&Value::Bool(true))
&& settings.get(KEYS[4]) == Some(&Value::Bool(true));
let loopback = settings
.get(KEYS[0])
.and_then(Value::as_str)
.and_then(|value| value.parse::<reqwest::Url>().ok())
.and_then(|url| url.host_str().map(str::to_owned))
.is_some_and(|host| matches!(host.as_str(), "127.0.0.1" | "localhost" | "::1"));
if managed_signature && loopback {
clear_proxy_settings()?;
}
Ok(())
}