Skip to main content

ai_usagebar/cursor/
fetch.rs

1//! Fetch Cursor's included-usage summary from `GET /api/usage-summary`,
2//! authenticated with the session token read out of the local `state.vscdb`
3//! (see `db.rs`). Cache/stale/error-fallback shape mirrors `kimi::fetch`.
4
5use std::path::Path;
6use std::time::Duration;
7
8use chrono::{DateTime, Utc};
9
10use crate::cache::{Cache, acquire_lock_async};
11use crate::error::{AppError, Result};
12use crate::usage::CursorSnapshot;
13use crate::vendor::{MAX_BODY_BYTES, read_body_capped};
14
15use super::db;
16use super::types::{self, UsageSummary};
17
18pub const BASE_URL: &str = "https://cursor.com";
19const HTTP_TIMEOUT: Duration = Duration::from_secs(10);
20const LOCK_TIMEOUT: Duration = Duration::from_secs(15);
21/// The dashboard endpoint gates on browser-looking headers; a plain
22/// `reqwest` request with only the cookie is rejected by its CORS check.
23const BROWSER_UA: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) \
24    AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
25
26#[derive(Debug, Clone)]
27pub struct Endpoints {
28    pub summary: String,
29}
30
31impl Default for Endpoints {
32    fn default() -> Self {
33        Self {
34            summary: format!("{BASE_URL}/api/usage-summary"),
35        }
36    }
37}
38
39/// This vendor's [`Outcome`](crate::outcome::Outcome) — the shared shape,
40/// specialised to its snapshot.
41pub type FetchOutcome = crate::outcome::Outcome<CursorSnapshot>;
42
43/// Cache-aware fetch. `db_path` is Cursor's `state.vscdb` — the caller resolves
44/// `[cursor] db_path` (config override) vs [`db::default_db_path`], the same
45/// override pattern as `openai.codex_auth_path`. `agent_auth_path` is the
46/// headless `cursor-agent` CLI's own `auth.json`, tried when `db_path` is
47/// missing — see `db::resolve_access_token`.
48pub async fn fetch_snapshot(
49    client: &reqwest::Client,
50    db_path: &Path,
51    agent_auth_path: &Path,
52    cache: &Cache,
53    endpoints: &Endpoints,
54    cache_ttl: Duration,
55) -> Result<FetchOutcome> {
56    fetch_snapshot_at(
57        client,
58        db_path,
59        agent_auth_path,
60        cache,
61        endpoints,
62        cache_ttl,
63        Utc::now(),
64    )
65    .await
66}
67
68/// Clock seam for cache rollover tests. Cursor's payload describes one billing
69/// cycle, so serving it after `reset_at` would knowingly show the prior cycle.
70async fn fetch_snapshot_at(
71    client: &reqwest::Client,
72    db_path: &Path,
73    agent_auth_path: &Path,
74    cache: &Cache,
75    endpoints: &Endpoints,
76    cache_ttl: Duration,
77    now: DateTime<Utc>,
78) -> Result<FetchOutcome> {
79    cache.ensure_dir()?;
80    let _lock = acquire_lock_async(&cache.lock_path(), LOCK_TIMEOUT).await?;
81
82    // Resolve the local identity before accepting a cache hit. Cursor can switch
83    // accounts in-place in this database; returning the cache first would show
84    // the previous account's private usage until the TTL elapsed.
85    let token = db::resolve_access_token(db_path, agent_auth_path)?;
86    let auth = db::session_auth(&token)?;
87
88    if let Some(bytes) = cache.fresh_payload(cache_ttl)?
89        && let Ok(outcome) = reuse_cache(&bytes, cache, false, &auth.account_key, now)
90    {
91        return Ok(outcome);
92    }
93
94    match fetch_live(client, endpoints, &auth).await {
95        Ok(snap) => {
96            let bytes = serde_json::to_vec(&snap_to_json(&snap, &auth.account_key))?;
97            cache.write_payload(&bytes)?;
98            Ok(crate::outcome::Outcome::fresh(snap))
99        }
100        Err(e) if e.is_transient() => fallback_silent(cache, &auth.account_key, now, e),
101        Err(e) => {
102            cache.mark_stale();
103            if let Some((code, msg)) = error_to_pair(&e) {
104                cache.write_last_error(code, &msg);
105            }
106            fallback_with_error(cache, &auth.account_key, now, e)
107        }
108    }
109}
110
111fn fallback_silent(
112    cache: &Cache,
113    account: &str,
114    now: DateTime<Utc>,
115    original: AppError,
116) -> Result<FetchOutcome> {
117    crate::outcome::fallback(cache, None, original, |bytes| {
118        parse_cache_at(bytes, account, now)
119    })
120}
121
122fn fallback_with_error(
123    cache: &Cache,
124    account: &str,
125    now: DateTime<Utc>,
126    original: AppError,
127) -> Result<FetchOutcome> {
128    let last_error = error_to_pair(&original);
129    crate::outcome::fallback(cache, last_error, original, |bytes| {
130        parse_cache_at(bytes, account, now)
131    })
132}
133
134/// Never surface upstream bodies for auth failures: the request carried a
135/// session cookie derived from a signed-in token, and 401/403 bodies from a
136/// scraped web endpoint are not guaranteed not to echo it back.
137fn error_to_pair(e: &AppError) -> Option<(u16, String)> {
138    match e {
139        AppError::Http { status, .. } if matches!(status, 401 | 403) => {
140            Some((*status, "Cursor authentication failed".into()))
141        }
142        AppError::Http { status, body } => Some((*status, body.clone())),
143        e => Some((0, e.to_string())),
144    }
145}
146
147fn reuse_cache(
148    bytes: &[u8],
149    cache: &Cache,
150    stale: bool,
151    account: &str,
152    now: DateTime<Utc>,
153) -> Result<FetchOutcome> {
154    let snap = parse_cache_at(bytes, account, now)?;
155    Ok(crate::outcome::Outcome::cached(snap, cache, stale))
156}
157
158fn parse_cache_at(bytes: &[u8], account: &str, now: DateTime<Utc>) -> Result<CursorSnapshot> {
159    let v: serde_json::Value = serde_json::from_slice(bytes)?;
160    if v.get("account").and_then(serde_json::Value::as_str) != Some(account) {
161        return Err(AppError::Schema(
162            "cursor cache belongs to a different account; refetching".into(),
163        ));
164    }
165    let int = |key: &str| -> Result<i32> {
166        v[key]
167            .as_i64()
168            .filter(|n| *n >= 0)
169            .and_then(|n| i32::try_from(n).ok())
170            .ok_or_else(|| AppError::Schema(format!("cursor cache: invalid {key}")))
171    };
172    let plan = v["plan"]
173        .as_str()
174        .filter(|plan| !plan.trim().is_empty())
175        .ok_or_else(|| AppError::Schema("cursor cache: invalid plan".into()))?
176        .to_string();
177    let reset_at = parse_cache_datetime(&v["reset_at"])?
178        .ok_or_else(|| AppError::Schema("cursor cache: missing reset timestamp".into()))?;
179    if reset_at <= now {
180        return Err(AppError::Schema(
181            "cursor cache is past its billing-cycle reset; refetching".into(),
182        ));
183    }
184    Ok(CursorSnapshot {
185        plan,
186        auto_pct: int("auto_pct")?,
187        api_pct: int("api_pct")?,
188        total_pct: int("total_pct")?,
189        unlimited: v["unlimited"]
190            .as_bool()
191            .ok_or_else(|| AppError::Schema("cursor cache: invalid unlimited flag".into()))?,
192        on_demand_enabled: v["on_demand_enabled"]
193            .as_bool()
194            .ok_or_else(|| AppError::Schema("cursor cache: invalid on-demand flag".into()))?,
195        reset_at: Some(reset_at),
196    })
197}
198
199fn parse_cache_datetime(v: &serde_json::Value) -> Result<Option<DateTime<Utc>>> {
200    match v {
201        serde_json::Value::Null => Ok(None),
202        serde_json::Value::String(s) => DateTime::parse_from_rfc3339(s)
203            .map(|dt| Some(dt.into()))
204            .map_err(|e| AppError::Schema(format!("cursor cache: invalid reset timestamp: {e}"))),
205        _ => Err(AppError::Schema(
206            "cursor cache: invalid reset timestamp".into(),
207        )),
208    }
209}
210
211fn snap_to_json(snap: &CursorSnapshot, account: &str) -> serde_json::Value {
212    serde_json::json!({
213        "account": account,
214        "plan": snap.plan,
215        "auto_pct": snap.auto_pct,
216        "api_pct": snap.api_pct,
217        "total_pct": snap.total_pct,
218        "unlimited": snap.unlimited,
219        "on_demand_enabled": snap.on_demand_enabled,
220        "reset_at": snap.reset_at.map(|dt| dt.to_rfc3339()),
221    })
222}
223
224async fn fetch_live(
225    client: &reqwest::Client,
226    endpoints: &Endpoints,
227    auth: &db::SessionAuth,
228) -> Result<CursorSnapshot> {
229    // usage-summary keys off the session cookie alone (no `?user=` param); the
230    // browser-ish headers get past its CORS gate.
231    let resp = tokio::time::timeout(
232        HTTP_TIMEOUT,
233        client
234            .get(&endpoints.summary)
235            .header(
236                "Cookie",
237                format!("WorkosCursorSessionToken={}", auth.cookie_value),
238            )
239            .header("Origin", BASE_URL)
240            .header("Referer", format!("{BASE_URL}/dashboard"))
241            .header("User-Agent", BROWSER_UA)
242            .send(),
243    )
244    .await
245    .map_err(|_| AppError::Transport(format!("cursor timeout: {}", endpoints.summary)))??;
246
247    let status = resp.status();
248    if !status.is_success() {
249        let body = if matches!(status.as_u16(), 401 | 403) {
250            "Cursor authentication failed".into()
251        } else {
252            format!("Cursor API returned HTTP {}", status.as_u16())
253        };
254        return Err(AppError::Http {
255            status: status.as_u16(),
256            body,
257        });
258    }
259
260    let bytes = read_body_capped(resp, MAX_BODY_BYTES).await?;
261    let parsed: UsageSummary = serde_json::from_slice(&bytes)
262        .map_err(|e| AppError::Schema(format!("cursor usage-summary response: {e}")))?;
263    types::to_snapshot(parsed)
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269    use rusqlite::Connection;
270    use tempfile::TempDir;
271
272    fn cache_fixture() -> (TempDir, Cache) {
273        let td = TempDir::new().unwrap();
274        let cache = Cache::at(td.path().join("cursor"));
275        cache.ensure_dir().unwrap();
276        (td, cache)
277    }
278
279    /// A minimal, unsigned JWT with `sub: "auth0|<user_id>"` — signature
280    /// verification is never performed (see `db::parse_jwt_claims`).
281    fn fake_token(user_id: &str) -> String {
282        use base64::Engine;
283        let header = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(br#"{"alg":"none"}"#);
284        let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
285            .encode(serde_json::json!({"sub": format!("auth0|{user_id}")}).to_string());
286        format!("{header}.{payload}.sig")
287    }
288
289    fn seed_state_db(dir: &TempDir, token: &str) -> std::path::PathBuf {
290        let path = dir.path().join("state.vscdb");
291        let conn = Connection::open(&path).unwrap();
292        conn.execute("CREATE TABLE ItemTable (key TEXT, value TEXT)", [])
293            .unwrap();
294        conn.execute(
295            "INSERT INTO ItemTable (key, value) VALUES ('cursorAuth/accessToken', ?1)",
296            [token],
297        )
298        .unwrap();
299        path
300    }
301
302    fn account_key(token: &str) -> String {
303        db::session_auth(token).unwrap().account_key
304    }
305
306    /// A path that never exists, for tests that only care about the IDE
307    /// `db_path` and want the agent fallback to stay out of the way.
308    fn no_agent_auth() -> std::path::PathBuf {
309        std::path::PathBuf::from("/nonexistent/cursor-agent-auth.json")
310    }
311
312    fn cached_snapshot(account: &str, reset_at: &str) -> Vec<u8> {
313        serde_json::to_vec(&serde_json::json!({
314            "account": account,
315            "plan": "Ultra",
316            "auto_pct": 40,
317            "api_pct": 10,
318            "total_pct": 30,
319            "unlimited": false,
320            "on_demand_enabled": false,
321            "reset_at": reset_at,
322        }))
323        .unwrap()
324    }
325
326    fn sample_json() -> String {
327        r#"{
328            "billingCycleEnd": "2099-08-04T00:35:51.000Z",
329            "membershipType": "ultra",
330            "isUnlimited": false,
331            "individualUsage": {
332                "plan": { "autoPercentUsed": 98.109, "apiPercentUsed": 100, "totalPercentUsed": 98.5 },
333                "onDemand": { "enabled": false }
334            }
335        }"#
336        .to_string()
337    }
338
339    #[tokio::test]
340    async fn live_fetch_reads_token_from_db_and_sends_the_session_cookie() {
341        let mut server = mockito::Server::new_async().await;
342        let token = fake_token("user_123");
343        let m = server
344            .mock("GET", "/api/usage-summary")
345            .match_header(
346                "cookie",
347                format!("WorkosCursorSessionToken=user_123%3A%3A{token}").as_str(),
348            )
349            .with_status(200)
350            .with_body(sample_json())
351            .create_async()
352            .await;
353
354        let db_dir = TempDir::new().unwrap();
355        let db_path = seed_state_db(&db_dir, &token);
356        let (_cache_dir, cache) = cache_fixture();
357        let client = reqwest::Client::new();
358        let endpoints = Endpoints {
359            summary: format!("{}/api/usage-summary", server.url()),
360        };
361
362        let out = fetch_snapshot(
363            &client,
364            &db_path,
365            &no_agent_auth(),
366            &cache,
367            &endpoints,
368            Duration::from_secs(0),
369        )
370        .await
371        .unwrap();
372        m.assert_async().await;
373        assert_eq!(out.snapshot.plan, "Ultra");
374        assert_eq!(out.snapshot.auto_pct, 98);
375        assert_eq!(out.snapshot.api_pct, 100);
376        assert!(!out.stale);
377    }
378
379    #[tokio::test]
380    async fn missing_db_file_is_a_credentials_error_with_no_cache_to_fall_back_on() {
381        let (_cache_dir, cache) = cache_fixture();
382        let client = reqwest::Client::new();
383        let endpoints = Endpoints::default();
384        let db_path = std::path::Path::new("/nonexistent/state.vscdb");
385
386        let err = fetch_snapshot(
387            &client,
388            db_path,
389            &no_agent_auth(),
390            &cache,
391            &endpoints,
392            Duration::from_secs(0),
393        )
394        .await
395        .unwrap_err();
396        assert!(matches!(err, AppError::Credentials(_)));
397    }
398
399    #[tokio::test]
400    async fn agent_auth_file_is_used_when_the_ide_db_is_missing() {
401        let mut server = mockito::Server::new_async().await;
402        let token = fake_token("user_123");
403        let m = server
404            .mock("GET", "/api/usage-summary")
405            .match_header(
406                "cookie",
407                format!("WorkosCursorSessionToken=user_123%3A%3A{token}").as_str(),
408            )
409            .with_status(200)
410            .with_body(sample_json())
411            .create_async()
412            .await;
413
414        let dir = TempDir::new().unwrap();
415        let db_path = dir.path().join("state.vscdb"); // deliberately never seeded
416        let agent_path = dir.path().join("auth.json");
417        std::fs::write(
418            &agent_path,
419            serde_json::json!({"accessToken": token, "refreshToken": "r"}).to_string(),
420        )
421        .unwrap();
422        let (_cache_dir, cache) = cache_fixture();
423        let client = reqwest::Client::new();
424        let endpoints = Endpoints {
425            summary: format!("{}/api/usage-summary", server.url()),
426        };
427
428        let out = fetch_snapshot(
429            &client,
430            &db_path,
431            &agent_path,
432            &cache,
433            &endpoints,
434            Duration::from_secs(0),
435        )
436        .await
437        .unwrap();
438        m.assert_async().await;
439        assert_eq!(out.snapshot.plan, "Ultra");
440        assert!(!out.stale);
441    }
442
443    #[tokio::test]
444    async fn http_error_falls_back_to_cache_and_hides_the_upstream_body() {
445        let mut server = mockito::Server::new_async().await;
446        let token = fake_token("user_123");
447        server
448            .mock("GET", "/api/usage-summary")
449            .with_status(401)
450            .with_body(r#"{"detail":"leaked-looking body"}"#)
451            .create_async()
452            .await;
453
454        let db_dir = TempDir::new().unwrap();
455        let db_path = seed_state_db(&db_dir, &token);
456        let (_cache_dir, cache) = cache_fixture();
457        cache
458            .write_payload(&cached_snapshot(
459                &account_key(&token),
460                "2099-08-04T00:00:00Z",
461            ))
462            .unwrap();
463
464        let client = reqwest::Client::new();
465        let endpoints = Endpoints {
466            summary: format!("{}/api/usage-summary", server.url()),
467        };
468        let out = fetch_snapshot(
469            &client,
470            &db_path,
471            &no_agent_auth(),
472            &cache,
473            &endpoints,
474            Duration::from_secs(0),
475        )
476        .await
477        .unwrap();
478        assert!(out.stale);
479        assert_eq!(out.snapshot.auto_pct, 40);
480        let (code, msg) = out.last_error.unwrap();
481        assert_eq!(code, 401);
482        assert_eq!(msg, "Cursor authentication failed");
483        assert!(!msg.contains("leaked-looking"));
484    }
485
486    #[tokio::test]
487    async fn fresh_cache_is_used_after_verifying_the_current_account() {
488        let token = fake_token("user_123");
489        let db_dir = TempDir::new().unwrap();
490        let db_path = seed_state_db(&db_dir, &token);
491        let (_cache_dir, cache) = cache_fixture();
492        cache
493            .write_payload(
494                serde_json::json!({
495                    "account": account_key(&token),
496                    "plan": "Pro", "auto_pct": 7, "api_pct": 3, "total_pct": 5,
497                    "unlimited": false, "on_demand_enabled": true,
498                    "reset_at": "2099-08-04T00:00:00Z",
499                })
500                .to_string()
501                .as_bytes(),
502            )
503            .unwrap();
504
505        let client = reqwest::Client::new();
506        let endpoints = Endpoints::default();
507        let out = fetch_snapshot(
508            &client,
509            &db_path,
510            &no_agent_auth(),
511            &cache,
512            &endpoints,
513            Duration::from_secs(3600),
514        )
515        .await
516        .unwrap();
517        assert_eq!(out.snapshot.auto_pct, 7);
518        assert!(out.snapshot.on_demand_enabled);
519        assert!(!out.stale);
520    }
521
522    #[tokio::test]
523    async fn switching_accounts_rejects_a_fresh_cache_and_refetches() {
524        let old_token = fake_token("old_account");
525        let new_token = fake_token("new_account");
526        let db_dir = TempDir::new().unwrap();
527        let db_path = seed_state_db(&db_dir, &new_token);
528        let (_cache_dir, cache) = cache_fixture();
529        cache
530            .write_payload(&cached_snapshot(
531                &account_key(&old_token),
532                "2099-08-04T00:00:00Z",
533            ))
534            .unwrap();
535
536        let mut server = mockito::Server::new_async().await;
537        let request = server
538            .mock("GET", "/api/usage-summary")
539            .match_header(
540                "cookie",
541                format!("WorkosCursorSessionToken=new_account%3A%3A{new_token}").as_str(),
542            )
543            .with_status(200)
544            .with_body(sample_json())
545            .expect(1)
546            .create_async()
547            .await;
548        let endpoints = Endpoints {
549            summary: format!("{}/api/usage-summary", server.url()),
550        };
551
552        let out = fetch_snapshot(
553            &reqwest::Client::new(),
554            &db_path,
555            &no_agent_auth(),
556            &cache,
557            &endpoints,
558            Duration::from_secs(3600),
559        )
560        .await
561        .unwrap();
562        request.assert_async().await;
563        assert_eq!(out.snapshot.auto_pct, 98);
564        assert!(!out.stale);
565    }
566
567    #[tokio::test]
568    async fn cache_past_its_billing_reset_is_not_served_during_an_outage() {
569        let token = fake_token("user_123");
570        let db_dir = TempDir::new().unwrap();
571        let db_path = seed_state_db(&db_dir, &token);
572        let (_cache_dir, cache) = cache_fixture();
573        cache
574            .write_payload(&cached_snapshot(
575                &account_key(&token),
576                "2026-08-04T00:00:00Z",
577            ))
578            .unwrap();
579
580        let mut server = mockito::Server::new_async().await;
581        server
582            .mock("GET", "/api/usage-summary")
583            .with_status(503)
584            .create_async()
585            .await;
586        let endpoints = Endpoints {
587            summary: format!("{}/api/usage-summary", server.url()),
588        };
589        let now = DateTime::parse_from_rfc3339("2026-08-05T00:00:00Z")
590            .unwrap()
591            .with_timezone(&Utc);
592        let err = fetch_snapshot_at(
593            &reqwest::Client::new(),
594            &db_path,
595            &no_agent_auth(),
596            &cache,
597            &endpoints,
598            Duration::from_secs(0),
599            now,
600        )
601        .await
602        .unwrap_err();
603        assert!(matches!(err, AppError::Http { status: 503, .. }));
604    }
605
606    #[test]
607    fn cached_percentages_are_range_checked_before_narrowing() {
608        let now = DateTime::parse_from_rfc3339("2026-08-01T00:00:00Z")
609            .unwrap()
610            .with_timezone(&Utc);
611        let mut payload: serde_json::Value =
612            serde_json::from_slice(&cached_snapshot("account", "2026-08-04T00:00:00Z")).unwrap();
613        payload["auto_pct"] = serde_json::json!(i64::MAX);
614        let err =
615            parse_cache_at(&serde_json::to_vec(&payload).unwrap(), "account", now).unwrap_err();
616        assert!(matches!(err, AppError::Schema(_)));
617    }
618}