mirror of
https://wget.la/https://github.com/leookun/cursor-byok
synced 2026-12-01 01:05:10 +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
@@ -1,15 +1,17 @@
|
||||
//! Implements Cursor account information services.
|
||||
use axum::{
|
||||
body::{Body, Bytes},
|
||||
body::{to_bytes, Body},
|
||||
extract::Extension,
|
||||
http::{header, Request, Response},
|
||||
http::{header, HeaderValue, Request, Response},
|
||||
};
|
||||
use prost::Message;
|
||||
use serde_json::{Map, Value};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{api::cursor::proxy, Result};
|
||||
use crate::{api::cursor::proxy, local_app, Result};
|
||||
|
||||
const LOCAL_AUTH_ID: &str = "local_ultra";
|
||||
use super::entitlement::FreeEntitlementCache;
|
||||
|
||||
const LOCAL_AUTH_ID: &str = "cursor-local-user";
|
||||
const LOCAL_EMAIL: &str = "cursor@ai.com";
|
||||
const LOCAL_ULTRA_PLAN_INCLUDED_CENTS: i32 = 20_000;
|
||||
|
||||
@@ -21,6 +23,20 @@ struct GetEmailResponse {
|
||||
sign_up_type: i32,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
struct GetUserMetaResponse {
|
||||
#[prost(string, tag = "1")]
|
||||
email: String,
|
||||
#[prost(int32, tag = "2")]
|
||||
sign_up_type: i32,
|
||||
#[prost(int64, tag = "3")]
|
||||
user_id: i64,
|
||||
#[prost(string, optional, tag = "4")]
|
||||
workos_id: Option<String>,
|
||||
#[prost(string, optional, tag = "5")]
|
||||
profile_picture_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
struct GetMeResponse {
|
||||
#[prost(string, tag = "1")]
|
||||
@@ -41,6 +57,8 @@ struct GetMeResponse {
|
||||
email_domain_type: Option<String>,
|
||||
#[prost(string, optional, tag = "12")]
|
||||
country: Option<String>,
|
||||
#[prost(string, optional, tag = "13")]
|
||||
profile_picture_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
@@ -134,7 +152,7 @@ pub async fn get_email(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
forward_or(upstream, request, || {
|
||||
local_or_forward(upstream, request, || {
|
||||
proto(GetEmailResponse {
|
||||
email: LOCAL_EMAIL.into(),
|
||||
sign_up_type: 3,
|
||||
@@ -143,11 +161,27 @@ pub async fn get_email(
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_user_meta(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
local_or_forward(upstream, request, || {
|
||||
proto(GetUserMetaResponse {
|
||||
email: LOCAL_EMAIL.into(),
|
||||
sign_up_type: 3,
|
||||
user_id: 1,
|
||||
workos_id: None,
|
||||
profile_picture_url: None,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_me(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
forward_or(upstream, request, || {
|
||||
local_or_forward(upstream, request, || {
|
||||
proto(GetMeResponse {
|
||||
auth_id: LOCAL_AUTH_ID.into(),
|
||||
user_id: 1,
|
||||
@@ -158,6 +192,7 @@ pub async fn get_me(
|
||||
is_enterprise_user: Some(false),
|
||||
email_domain_type: Some("personal".into()),
|
||||
country: Some("US".into()),
|
||||
profile_picture_url: None,
|
||||
})
|
||||
})
|
||||
.await
|
||||
@@ -167,14 +202,14 @@ pub async fn get_teams(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
forward_or(upstream, request, || proto(Empty {})).await
|
||||
local_or_forward(upstream, request, || proto(Empty {})).await
|
||||
}
|
||||
|
||||
pub async fn get_user_profile(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
forward_or(upstream, request, || {
|
||||
local_or_forward(upstream, request, || {
|
||||
proto(GetUserProfileResponse {
|
||||
public_visibility_allowed: Some(true),
|
||||
max_visibility: Some("PUBLIC".into()),
|
||||
@@ -183,85 +218,170 @@ pub async fn get_user_profile(
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn current_period_usage() -> Result<Response<Body>> {
|
||||
let now = chrono::Utc::now();
|
||||
proto(GetCurrentPeriodUsageResponse {
|
||||
billing_cycle_start: (now - chrono::Duration::days(30)).timestamp_millis(),
|
||||
billing_cycle_end: (now + chrono::Duration::days(10 * 365)).timestamp_millis(),
|
||||
plan_usage: Some(PlanUsage {
|
||||
total_spend: 0,
|
||||
included_spend: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
|
||||
remaining: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
|
||||
limit: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
|
||||
remaining_bonus: Some(false),
|
||||
bonus_tooltip: Some("Ultra local account mock is active.".into()),
|
||||
auto_spend: Some(0),
|
||||
api_spend: Some(0),
|
||||
auto_percent_used: Some(0.0),
|
||||
api_percent_used: Some(0.0),
|
||||
total_percent_used: Some(0.0),
|
||||
}),
|
||||
spend_limit_usage: Some(SpendLimitUsage {
|
||||
limit_type: "user".into(),
|
||||
}),
|
||||
display_threshold: Some(99_999_999),
|
||||
enabled: true,
|
||||
display_message: "Ultra plan active".into(),
|
||||
auto_model_selected_display_message: Some("Ultra plan active".into()),
|
||||
named_model_selected_display_message: Some("Ultra plan active".into()),
|
||||
pub async fn current_period_usage(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
Extension(free_entitlements): Extension<FreeEntitlementCache>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
local_or_confirmed_free_or_forward(upstream, &free_entitlements, request, || {
|
||||
let now = chrono::Utc::now();
|
||||
proto(GetCurrentPeriodUsageResponse {
|
||||
billing_cycle_start: (now - chrono::Duration::days(30)).timestamp_millis(),
|
||||
billing_cycle_end: (now + chrono::Duration::days(10 * 365)).timestamp_millis(),
|
||||
plan_usage: Some(PlanUsage {
|
||||
total_spend: 0,
|
||||
included_spend: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
|
||||
remaining: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
|
||||
limit: LOCAL_ULTRA_PLAN_INCLUDED_CENTS,
|
||||
remaining_bonus: Some(false),
|
||||
bonus_tooltip: Some("Ultra local account mock is active.".into()),
|
||||
auto_spend: Some(0),
|
||||
api_spend: Some(0),
|
||||
auto_percent_used: Some(0.0),
|
||||
api_percent_used: Some(0.0),
|
||||
total_percent_used: Some(0.0),
|
||||
}),
|
||||
spend_limit_usage: Some(SpendLimitUsage {
|
||||
limit_type: "user".into(),
|
||||
}),
|
||||
display_threshold: Some(99_999_999),
|
||||
enabled: true,
|
||||
display_message: "Ultra plan active".into(),
|
||||
auto_model_selected_display_message: Some("Ultra plan active".into()),
|
||||
named_model_selected_display_message: Some("Ultra plan active".into()),
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn usage_limit_status() -> Result<Response<Body>> {
|
||||
proto(GetUsageLimitStatusAndActiveGrantsResponse {
|
||||
usage_limit_policy_status: Some(UsageLimitPolicyStatus {
|
||||
is_in_slow_pool: false,
|
||||
features: Default::default(),
|
||||
can_configure_spend_limit: true,
|
||||
has_pending_request: false,
|
||||
allowed_model_ids: Vec::new(),
|
||||
allowed_model_tags: Vec::new(),
|
||||
}),
|
||||
pub async fn usage_limit_status(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
Extension(free_entitlements): Extension<FreeEntitlementCache>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
local_or_confirmed_free_or_forward(upstream, &free_entitlements, request, || {
|
||||
proto(GetUsageLimitStatusAndActiveGrantsResponse {
|
||||
usage_limit_policy_status: Some(UsageLimitPolicyStatus {
|
||||
is_in_slow_pool: false,
|
||||
features: Default::default(),
|
||||
can_configure_spend_limit: true,
|
||||
has_pending_request: false,
|
||||
allowed_model_ids: Vec::new(),
|
||||
allowed_model_tags: Vec::new(),
|
||||
}),
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn stripe_profile(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
Extension(free_entitlements): Extension<FreeEntitlementCache>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
match proxy::forward_buffered(&upstream, request).await {
|
||||
Ok(response) if response.status.is_success() => {
|
||||
let mut profile = serde_json::from_slice::<Map<String, Value>>(&response.body)?;
|
||||
ultra(&mut profile);
|
||||
Ok(response.with_body(Bytes::from(serde_json::to_vec(&profile)?)))
|
||||
}
|
||||
Ok(response) => {
|
||||
tracing::warn!(status = %response.status, "Cursor account upstream rejected profile; using local Ultra identity");
|
||||
json(ultra_profile())
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "Cursor account upstream unavailable; using local Ultra identity");
|
||||
json(ultra_profile())
|
||||
}
|
||||
if local_app::request_uses_local_cursor_token(request.headers()) {
|
||||
return local_stripe_profile(request.headers().get(header::ORIGIN).cloned());
|
||||
}
|
||||
|
||||
let request_headers = request.headers().clone();
|
||||
let origin = request.headers().get(header::ORIGIN).cloned();
|
||||
let upstream_response = match proxy::forward_buffered(&upstream, request).await {
|
||||
Ok(response) => response,
|
||||
Err(error) if free_entitlements.is_confirmed_free(&request_headers) => {
|
||||
tracing::warn!(%error, "using cached Free entitlement after Stripe upstream failure");
|
||||
return local_stripe_profile(origin);
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if !upstream_response.status.is_success() {
|
||||
if should_fallback_to_cached_free(
|
||||
upstream_response.status,
|
||||
&free_entitlements,
|
||||
&request_headers,
|
||||
) {
|
||||
tracing::warn!(
|
||||
status = %upstream_response.status,
|
||||
"using cached Free entitlement after Stripe upstream failure"
|
||||
);
|
||||
return local_stripe_profile(origin);
|
||||
}
|
||||
return Ok(upstream_response.into_response());
|
||||
}
|
||||
|
||||
let Some(membership_type) = membership_type(&upstream_response.body) else {
|
||||
return Ok(upstream_response.into_response());
|
||||
};
|
||||
let observed = free_entitlements.observe_membership(&request_headers, &membership_type);
|
||||
if observed && membership_type.eq_ignore_ascii_case("free") {
|
||||
return local_stripe_profile(origin);
|
||||
}
|
||||
|
||||
Ok(upstream_response.into_response())
|
||||
}
|
||||
|
||||
async fn forward_or(
|
||||
fn should_fallback_to_cached_free(
|
||||
status: axum::http::StatusCode,
|
||||
free_entitlements: &FreeEntitlementCache,
|
||||
headers: &axum::http::HeaderMap,
|
||||
) -> bool {
|
||||
status.is_server_error() && free_entitlements.is_confirmed_free(headers)
|
||||
}
|
||||
|
||||
fn membership_type(body: &[u8]) -> Option<String> {
|
||||
let profile: Value = serde_json::from_slice(body).ok()?;
|
||||
let membership_type = profile.get("membershipType")?.as_str()?.trim();
|
||||
(!membership_type.is_empty()).then(|| membership_type.to_owned())
|
||||
}
|
||||
|
||||
fn local_stripe_profile(origin: Option<HeaderValue>) -> Result<Response<Body>> {
|
||||
let mut response = json(ultra_profile())?;
|
||||
if let Some(origin) = origin {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin);
|
||||
response.headers_mut().insert(
|
||||
header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
|
||||
HeaderValue::from_static("true"),
|
||||
);
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::VARY, HeaderValue::from_static("Origin"));
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn local_or_confirmed_free_or_forward(
|
||||
upstream: proxy::CursorProxy,
|
||||
free_entitlements: &FreeEntitlementCache,
|
||||
request: Request<Body>,
|
||||
local: impl FnOnce() -> Result<Response<Body>>,
|
||||
) -> Result<Response<Body>> {
|
||||
if local_app::request_uses_local_cursor_token(request.headers())
|
||||
|| free_entitlements.is_confirmed_free(request.headers())
|
||||
{
|
||||
consume_body(request).await?;
|
||||
return local();
|
||||
}
|
||||
proxy::forward(Extension(upstream), request).await
|
||||
}
|
||||
|
||||
async fn local_or_forward(
|
||||
upstream: proxy::CursorProxy,
|
||||
request: Request<Body>,
|
||||
fallback: impl FnOnce() -> Result<Response<Body>>,
|
||||
local: impl FnOnce() -> Result<Response<Body>>,
|
||||
) -> Result<Response<Body>> {
|
||||
match proxy::forward_buffered(&upstream, request).await {
|
||||
Ok(response) if response.status.is_success() => Ok(response.into_response()),
|
||||
Ok(response) => {
|
||||
tracing::debug!(status = %response.status, "Cursor identity upstream rejected request; using local identity");
|
||||
fallback()
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "Cursor identity upstream unavailable; using local identity");
|
||||
fallback()
|
||||
}
|
||||
if local_app::request_uses_local_cursor_token(request.headers()) {
|
||||
consume_body(request).await?;
|
||||
return local();
|
||||
}
|
||||
proxy::forward(Extension(upstream), request).await
|
||||
}
|
||||
|
||||
async fn consume_body(request: Request<Body>) -> Result<()> {
|
||||
to_bytes(request.into_body(), usize::MAX)
|
||||
.await
|
||||
.map_err(|error| crate::Error::Protocol(format!("cannot read request body: {error}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn proto(message: impl Message) -> Result<Response<Body>> {
|
||||
@@ -289,15 +409,6 @@ fn response(content_type: &'static str, body: Vec<u8>) -> Result<Response<Body>>
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
fn ultra(profile: &mut Map<String, Value>) {
|
||||
profile.insert("membershipType".into(), Value::String("ultra".into()));
|
||||
profile.insert(
|
||||
"individualMembershipType".into(),
|
||||
Value::String("ultra".into()),
|
||||
);
|
||||
profile.insert("subscriptionStatus".into(), Value::String("active".into()));
|
||||
}
|
||||
|
||||
fn ultra_profile() -> Value {
|
||||
serde_json::json!({
|
||||
"membershipType": "ultra",
|
||||
@@ -310,3 +421,87 @@ fn ultra_profile() -> Value {
|
||||
"isTeamMember": false
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
use axum::body::Bytes;
|
||||
use futures_util::stream;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_account_response_consumes_request_body_before_replying() {
|
||||
let polled = Arc::new(AtomicBool::new(false));
|
||||
let observed = polled.clone();
|
||||
let body = Body::from_stream(stream::once(async move {
|
||||
observed.store(true, Ordering::SeqCst);
|
||||
Ok::<_, std::convert::Infallible>(Bytes::from_static(b"request"))
|
||||
}));
|
||||
|
||||
consume_body(Request::new(body)).await.unwrap();
|
||||
|
||||
assert!(polled.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_free_fallback_accepts_server_failures_but_not_auth_failures() {
|
||||
let cache = FreeEntitlementCache::default();
|
||||
let mut headers = axum::http::HeaderMap::new();
|
||||
headers.insert(
|
||||
header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer official-free-token"),
|
||||
);
|
||||
assert!(cache.observe_membership(&headers, "free"));
|
||||
|
||||
assert!(should_fallback_to_cached_free(
|
||||
axum::http::StatusCode::BAD_GATEWAY,
|
||||
&cache,
|
||||
&headers
|
||||
));
|
||||
assert!(!should_fallback_to_cached_free(
|
||||
axum::http::StatusCode::UNAUTHORIZED,
|
||||
&cache,
|
||||
&headers
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_only_a_non_empty_membership_type() {
|
||||
assert_eq!(
|
||||
membership_type(br#"{"membershipType":"free"}"#).as_deref(),
|
||||
Some("free")
|
||||
);
|
||||
assert_eq!(membership_type(br#"{"membershipType":""}"#), None);
|
||||
assert_eq!(membership_type(br#"{"subscriptionStatus":"active"}"#), None);
|
||||
assert_eq!(membership_type(b"not-json"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_stripe_profile_allows_the_cursor_app_origin() {
|
||||
let origin = HeaderValue::from_static("vscode-file://vscode-app");
|
||||
let response = local_stripe_profile(Some(origin.clone())).unwrap();
|
||||
assert_eq!(
|
||||
response.headers().get(header::ACCESS_CONTROL_ALLOW_ORIGIN),
|
||||
Some(&origin)
|
||||
);
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get(header::ACCESS_CONTROL_ALLOW_CREDENTIALS),
|
||||
Some(&HeaderValue::from_static("true"))
|
||||
);
|
||||
assert_eq!(
|
||||
response.headers().get(header::VARY),
|
||||
Some(&HeaderValue::from_static("Origin"))
|
||||
);
|
||||
assert_eq!(
|
||||
response.headers().get(header::CONTENT_TYPE),
|
||||
Some(&HeaderValue::from_static("application/json"))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
//!
|
||||
//! Cursor sends `aiserver.v1.AiService/WriteGitCommitMessage` with the staged
|
||||
//! diffs. Empty commit-settings `model_id` keeps the original behaviour and
|
||||
//! forwards the RPC unchanged (直连). A configured Cursor model hash answers
|
||||
//! the request locally: truncated diffs + previous commits form the user
|
||||
//! forwards the RPC unchanged (直连). A configured local model identifier
|
||||
//! answers the request locally: truncated diffs + previous commits form the user
|
||||
//! message, the customizable commit prompt is the system prompt, and the raw
|
||||
//! completion is cleaned before being returned.
|
||||
use std::{
|
||||
@@ -30,6 +30,7 @@ use crate::{
|
||||
ContentPart, ModelInvocation, ModelRequest, ModelSpec, ProjectedContent, ProjectedMessage,
|
||||
PromptSpec, Role,
|
||||
},
|
||||
plugin::ADAPTER_ID_PREFIX,
|
||||
provider::{ModelEvent, Provider},
|
||||
store::CommitSettings,
|
||||
Error, Result,
|
||||
@@ -85,19 +86,11 @@ async fn generate_local(
|
||||
if diffs.is_empty() {
|
||||
return Err(Error::Protocol("diffs are required".into()));
|
||||
}
|
||||
let model_hash = settings.model_id.trim();
|
||||
let model = registry
|
||||
.store()
|
||||
.model(model_hash)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
Error::Provider(format!(
|
||||
"commit model {model_hash} is not configured; select a Cursor model in the commit settings"
|
||||
))
|
||||
})?;
|
||||
let model_id = settings.model_id.trim();
|
||||
ensure_configured_model(registry, model_id).await?;
|
||||
let invocation = build_invocation(
|
||||
&settings,
|
||||
&model.model_hash,
|
||||
model_id,
|
||||
build_user_content(&request, &diffs),
|
||||
);
|
||||
let provider = registry.conversations().dependencies().provider.clone();
|
||||
@@ -121,9 +114,25 @@ async fn generate_local(
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn ensure_configured_model(registry: &TransportRegistry, model_id: &str) -> Result<()> {
|
||||
if model_id.starts_with(ADAPTER_ID_PREFIX) {
|
||||
let plugins = registry.plugins().ok_or_else(|| {
|
||||
Error::Provider(format!("commit plugin model {model_id} is unavailable"))
|
||||
})?;
|
||||
plugins.model_descriptor(model_id).await?;
|
||||
return Ok(());
|
||||
}
|
||||
if registry.store().model(model_id).await?.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
Err(Error::Provider(format!(
|
||||
"commit model {model_id} is not configured; select a configured model in the commit settings"
|
||||
)))
|
||||
}
|
||||
|
||||
fn build_invocation(
|
||||
settings: &CommitSettings,
|
||||
model_hash: &str,
|
||||
model_id: &str,
|
||||
user_content: String,
|
||||
) -> ModelInvocation {
|
||||
let call_id = format!("commit-message-{}", uuid::Uuid::new_v4());
|
||||
@@ -137,7 +146,7 @@ fn build_invocation(
|
||||
instructions: settings.effective_prompt().to_owned(),
|
||||
tools: Vec::new(),
|
||||
},
|
||||
model: ModelSpec::new(model_hash.to_owned()),
|
||||
model: ModelSpec::new(model_id.to_owned()),
|
||||
history: vec![ProjectedMessage {
|
||||
message_id: "commit-message".into(),
|
||||
role: Role::User,
|
||||
@@ -360,12 +369,12 @@ mod tests {
|
||||
assert!(CommitSettings::default().is_direct());
|
||||
assert!(CommitSettings {
|
||||
model_id: " ".into(),
|
||||
prompt: String::new(),
|
||||
..CommitSettings::default()
|
||||
}
|
||||
.is_direct());
|
||||
assert!(!CommitSettings {
|
||||
model_id: "abc".into(),
|
||||
prompt: String::new(),
|
||||
..CommitSettings::default()
|
||||
}
|
||||
.is_direct());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Routes Cursor metadata calls according to the supplied authentication token.
|
||||
use axum::{
|
||||
body::{to_bytes, Body},
|
||||
extract::{Extension, Request},
|
||||
http::{header, HeaderValue, Response},
|
||||
};
|
||||
use prost::Message;
|
||||
|
||||
use crate::{
|
||||
api::cursor::proxy::{self, CursorProxy},
|
||||
cursor::protocol::proto::agent::v1 as agent,
|
||||
local_app, Result,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Message)]
|
||||
struct EmptyResponse {}
|
||||
|
||||
pub async fn available_docs(
|
||||
Extension(proxy): Extension<CursorProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
route(&proxy, request, EmptyResponse {}).await
|
||||
}
|
||||
|
||||
pub async fn effective_user_plugins(
|
||||
Extension(proxy): Extension<CursorProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
route(&proxy, request, EmptyResponse {}).await
|
||||
}
|
||||
|
||||
pub async fn user_privacy_mode(
|
||||
Extension(proxy): Extension<CursorProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
route(&proxy, request, EmptyResponse {}).await
|
||||
}
|
||||
|
||||
pub async fn update_conversation_metadata(
|
||||
Extension(proxy): Extension<CursorProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
route(
|
||||
&proxy,
|
||||
request,
|
||||
agent::UpdateConversationMetadataResponse {},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn route<M: Message>(
|
||||
proxy: &CursorProxy,
|
||||
request: Request<Body>,
|
||||
mock: M,
|
||||
) -> Result<Response<Body>> {
|
||||
let local = local_app::request_uses_local_cursor_token(request.headers());
|
||||
if local {
|
||||
consume_body(request).await?;
|
||||
return Ok(proto(mock));
|
||||
}
|
||||
proxy::forward(Extension(proxy.clone()), request).await
|
||||
}
|
||||
|
||||
async fn consume_body(request: Request<Body>) -> Result<()> {
|
||||
to_bytes(request.into_body(), usize::MAX)
|
||||
.await
|
||||
.map_err(|error| crate::Error::Protocol(format!("cannot read request body: {error}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn proto(message: impl Message) -> Response<Body> {
|
||||
let body = message.encode_to_vec();
|
||||
let length = body.len();
|
||||
let mut response = Response::new(Body::from(body));
|
||||
response.headers_mut().insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("application/proto"),
|
||||
);
|
||||
response.headers_mut().insert(
|
||||
header::CONTENT_LENGTH,
|
||||
HeaderValue::from_str(&length.to_string()).expect("body length is valid"),
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
use axum::body::{to_bytes, Bytes};
|
||||
use futures_util::stream;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_response_consumes_request_body_before_replying() {
|
||||
let polled = Arc::new(AtomicBool::new(false));
|
||||
let observed = polled.clone();
|
||||
let body = Body::from_stream(stream::once(async move {
|
||||
observed.store(true, Ordering::SeqCst);
|
||||
Ok::<_, std::convert::Infallible>(Bytes::from_static(b"request"))
|
||||
}));
|
||||
|
||||
consume_body(Request::new(body)).await.unwrap();
|
||||
|
||||
assert!(polled.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn empty_unary_mock_is_bare_protobuf_without_connect_frame() {
|
||||
let response = proto(EmptyResponse {});
|
||||
assert_eq!(response.headers()[header::CONTENT_LENGTH], "0");
|
||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
assert!(body.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Caches a recently confirmed official Cursor Free entitlement.
|
||||
use std::{
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use axum::http::{header, HeaderMap};
|
||||
use parking_lot::Mutex;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::local_app;
|
||||
|
||||
const FREE_ENTITLEMENT_TTL: Duration = Duration::from_secs(5 * 60);
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct FreeEntitlementCache {
|
||||
cached: Arc<Mutex<Option<CachedFreeEntitlement>>>,
|
||||
}
|
||||
|
||||
struct CachedFreeEntitlement {
|
||||
token_hash: [u8; 32],
|
||||
expires_at: Instant,
|
||||
}
|
||||
|
||||
impl FreeEntitlementCache {
|
||||
pub fn is_confirmed_free(&self, headers: &HeaderMap) -> bool {
|
||||
let Some(token_hash) = official_token_hash(headers) else {
|
||||
return false;
|
||||
};
|
||||
let now = Instant::now();
|
||||
let mut cached = self.cached.lock();
|
||||
match cached.as_ref() {
|
||||
Some(entry) if entry.expires_at > now && entry.token_hash == token_hash => true,
|
||||
Some(entry) if entry.expires_at <= now => {
|
||||
*cached = None;
|
||||
false
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn observe_membership(&self, headers: &HeaderMap, membership_type: &str) -> bool {
|
||||
let Some(token_hash) = official_token_hash(headers) else {
|
||||
return false;
|
||||
};
|
||||
let mut cached = self.cached.lock();
|
||||
if membership_type.eq_ignore_ascii_case("free") {
|
||||
*cached = Some(CachedFreeEntitlement {
|
||||
token_hash,
|
||||
expires_at: Instant::now() + FREE_ENTITLEMENT_TTL,
|
||||
});
|
||||
} else if cached
|
||||
.as_ref()
|
||||
.is_some_and(|entry| entry.token_hash == token_hash)
|
||||
{
|
||||
*cached = None;
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn official_token_hash(headers: &HeaderMap) -> Option<[u8; 32]> {
|
||||
if local_app::request_uses_local_cursor_token(headers) {
|
||||
return None;
|
||||
}
|
||||
let token = headers
|
||||
.get(header::AUTHORIZATION)?
|
||||
.to_str()
|
||||
.ok()?
|
||||
.strip_prefix("Bearer ")?;
|
||||
if token.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(Sha256::digest(token.as_bytes()).into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn official_headers(token: &str) -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::AUTHORIZATION,
|
||||
format!("Bearer {token}").parse().unwrap(),
|
||||
);
|
||||
headers
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caches_only_a_confirmed_free_official_token() {
|
||||
let cache = FreeEntitlementCache::default();
|
||||
let free = official_headers("official-free-token");
|
||||
let other = official_headers("another-token");
|
||||
|
||||
cache.observe_membership(&free, "free");
|
||||
|
||||
assert!(cache.is_confirmed_free(&free));
|
||||
assert!(!cache.is_confirmed_free(&other));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirmed_non_free_membership_clears_the_same_token() {
|
||||
let cache = FreeEntitlementCache::default();
|
||||
let headers = official_headers("official-token");
|
||||
cache.observe_membership(&headers, "free");
|
||||
|
||||
cache.observe_membership(&headers, "pro");
|
||||
|
||||
assert!(!cache.is_confirmed_free(&headers));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_token_never_enters_the_entitlement_cache() {
|
||||
let cache = FreeEntitlementCache::default();
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::AUTHORIZATION,
|
||||
crate::local_app::local_cursor_authorization()
|
||||
.parse()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
assert!(!cache.observe_membership(&headers, "free"));
|
||||
|
||||
assert!(!cache.is_confirmed_free(&headers));
|
||||
assert!(cache.cached.lock().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expired_confirmation_is_removed() {
|
||||
let cache = FreeEntitlementCache::default();
|
||||
let headers = official_headers("official-token");
|
||||
let token_hash = official_token_hash(&headers).unwrap();
|
||||
*cache.cached.lock() = Some(CachedFreeEntitlement {
|
||||
token_hash,
|
||||
expires_at: Instant::now() - Duration::from_secs(1),
|
||||
});
|
||||
|
||||
assert!(!cache.is_confirmed_free(&headers));
|
||||
assert!(cache.cached.lock().is_none());
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@ pub mod account;
|
||||
pub mod analytics;
|
||||
pub mod blob_sync;
|
||||
pub mod commit_message;
|
||||
pub mod compatibility;
|
||||
pub mod context_sync;
|
||||
pub(crate) mod entitlement;
|
||||
pub mod knowledge;
|
||||
pub mod model_catalog;
|
||||
pub mod observability;
|
||||
|
||||
Reference in new issue
Block a user