Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat(cursor): surface Cursor Pro plan usage on provider-limits dashboard (#2128)

payne0420ee228e66571f
diff --git a/open-sse/config/providerHeaderProfiles.ts b/open-sse/config/providerHeaderProfiles.ts
index 99cf3386bb..2e58750055 100644
--- a/open-sse/config/providerHeaderProfiles.ts
+++ b/open-sse/config/providerHeaderProfiles.ts
@@ -186,17 +186,3 @@ export function getCursorRegistryHeaders(
"User-Agent": getCursorUserAgent(version),
};
}
-
-export function getCursorUsageHeaders(
- accessToken: string,
- version = CURSOR_REGISTRY_VERSION
-): Record<string, string> {
- const userAgent = getCursorUserAgent(version);
- return {
- Authorization: `Bearer ${accessToken}`,
- Accept: "application/json",
- "User-Agent": userAgent,
- "x-cursor-client-version": version,
- "x-cursor-user-agent": userAgent,
- };
-}
diff --git a/open-sse/services/usage.ts b/open-sse/services/usage.ts
index b55959ddd6..86187a01a0 100644
--- a/open-sse/services/usage.ts
+++ b/open-sse/services/usage.ts
@@ -9,11 +9,7 @@ import {
} from "../config/antigravityUpstream.ts";
import { isUserCallableAntigravityModelId } from "../config/antigravityModelAliases.ts";
import { getGlmQuotaUrl } from "../config/glmProvider.ts";
-import {
- CURSOR_REGISTRY_VERSION,
- getCursorUsageHeaders,
- getGitHubCopilotInternalUserHeaders,
-} from "../config/providerHeaderProfiles.ts";
+import { getGitHubCopilotInternalUserHeaders } from "../config/providerHeaderProfiles.ts";
import { safePercentage } from "@/shared/utils/formatting";
import { fetchBailianQuota, type BailianTripleWindowQuota } from "./bailianQuotaFetcher.ts";
import { fetchDeepseekQuota, type DeepseekQuota } from "./deepseekQuotaFetcher.ts";
@@ -72,17 +68,22 @@ const KIMI_CONFIG = {
apiVersion: "2023-06-01",
};
-const CURSOR_USAGE_CONFIG = {
- usageUrl: "https://www.cursor.com/api/usage",
- userMetaUrl: "https://www.cursor.com/api/auth/me",
- subscriptionUrl: "https://www.cursor.com/api/subscription",
- clientVersion: CURSOR_REGISTRY_VERSION,
-};
-
const NANOGPT_CONFIG = {
usageUrl: "https://nano-gpt.com/api/subscription/v1/usage",
};
+// Cursor dashboard usage API config
+// The endpoint that powers https://cursor.com/dashboard/spending. Validates the WorkOS
+// session via the WorkosCursorSessionToken cookie (format: `${userId}::${jwt}`) and
+// rejects requests without a matching Origin/Referer (Invalid origin for state-changing request).
+const CURSOR_USAGE_CONFIG = {
+ usageUrl: "https://cursor.com/api/dashboard/get-current-period-usage",
+ origin: "https://cursor.com",
+ referer: "https://cursor.com/dashboard/spending",
+ userAgent:
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
+};
+
const MINIMAX_USAGE_CONFIG = {
minimax: {
usageUrls: [
@@ -859,6 +860,143 @@ async function getNanoGptUsage(apiKey: string) {
}
}
+/**
+ * Decode the `sub` claim of a Cursor JWT (the WorkOS user id).
+ * Returns null if the token is not a parseable JWT.
+ */
+function decodeCursorJwtSub(token: string): string | null {
+ if (!token || typeof token !== "string") return null;
+ const parts = token.split(".");
+ if (parts.length !== 3) return null;
+ try {
+ let payload = parts[1].replace(/-/g, "+").replace(/_/g, "/");
+ while (payload.length % 4 !== 0) payload += "=";
+ const decoded = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
+ const sub = decoded?.sub;
+ return typeof sub === "string" && sub.length > 0 ? sub : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Cursor Pro Plan Usage
+ * Fetches current-billing-cycle spend from the cursor.com dashboard API and exposes three
+ * windows that mirror the cursor.com/dashboard/spending UI: Total / Auto + Composer / API.
+ */
+async function getCursorUsage(accessToken: string, providerSpecificData?: unknown) {
+ if (!accessToken) {
+ return { message: "Cursor access token missing. Re-import the connection from Cursor IDE." };
+ }
+
+ const storedUserId = (() => {
+ const raw = toRecord(providerSpecificData).userId;
+ return typeof raw === "string" && raw.length > 0 ? raw : null;
+ })();
+ const userId = storedUserId || decodeCursorJwtSub(accessToken);
+
+ if (!userId) {
+ return {
+ message: "Cursor token missing user id. Re-import the connection from Cursor IDE.",
+ };
+ }
+
+ try {
+ const response = await fetch(CURSOR_USAGE_CONFIG.usageUrl, {
+ method: "POST",
+ redirect: "manual",
+ headers: {
+ Cookie: `WorkosCursorSessionToken=${userId}::${accessToken}`,
+ Origin: CURSOR_USAGE_CONFIG.origin,
+ Referer: CURSOR_USAGE_CONFIG.referer,
+ "Content-Type": "application/json",
+ Accept: "application/json",
+ "User-Agent": CURSOR_USAGE_CONFIG.userAgent,
+ },
+ body: "{}",
+ });
+
+ // 3xx redirect to WorkOS authkit means the session cookie was rejected.
+ if (response.status >= 300 && response.status < 400) {
+ return {
+ plan: "Cursor",
+ message: "Cursor session expired. Re-import the token from Cursor IDE.",
+ };
+ }
+
+ if (!response.ok) {
+ const errorText = (await response.text()).slice(0, 200);
+ if (response.status === 401 || response.status === 403) {
+ return {
+ plan: "Cursor",
+ message: "Cursor session unauthorized. Re-import the token from Cursor IDE.",
+ };
+ }
+ return {
+ plan: "Cursor",
+ message: `Cursor usage endpoint error (${response.status}): ${errorText}`,
+ };
+ }
+
+ const data = toRecord(await response.json());
+ const planUsage = toRecord(data.planUsage);
+
+ if (Object.keys(planUsage).length === 0) {
+ return {
+ plan: "Cursor",
+ message: "Cursor connected. No active plan usage returned.",
+ };
+ }
+
+ const limitCents = Math.max(0, toNumber(planUsage.limit, 0));
+ const totalSpendCents = Math.max(0, toNumber(planUsage.totalSpend, 0));
+ const autoPercentUsed = clampPercentage(toNumber(planUsage.autoPercentUsed, 0));
+ const apiPercentUsed = clampPercentage(toNumber(planUsage.apiPercentUsed, 0));
+ const totalPercentUsed = clampPercentage(toNumber(planUsage.totalPercentUsed, 0));
+
+ // billingCycleEnd is a numeric-string in ms; coerce so parseResetTime sees a number.
+ const billingCycleEndMs = toNumber(data.billingCycleEnd, 0);
+ const resetAt = billingCycleEndMs > 0 ? parseResetTime(billingCycleEndMs) : null;
+
+ // Convert cents → dollars rounded to 2 decimal places.
+ const toDollars = (cents: number) => Math.round(cents) / 100;
+
+ const limitDollars = toDollars(limitCents);
+ const buildWindow = (percentUsed: number, usedCentsOverride?: number): UsageQuota => {
+ const usedCents =
+ typeof usedCentsOverride === "number"
+ ? usedCentsOverride
+ : Math.round((limitCents * percentUsed) / 100);
+ const used = toDollars(Math.min(usedCents, limitCents));
+ const remaining = toDollars(Math.max(limitCents - Math.min(usedCents, limitCents), 0));
+ return {
+ used,
+ total: limitDollars,
+ remaining,
+ remainingPercentage: clampPercentage(100 - percentUsed),
+ resetAt,
+ unlimited: false,
+ };
+ };
+
+ const quotas: Record<string, UsageQuota> = {
+ Total: buildWindow(totalPercentUsed, totalSpendCents),
+ "Auto + Composer": buildWindow(autoPercentUsed),
+ API: buildWindow(apiPercentUsed),
+ };
+
+ return {
+ plan: "Cursor Pro",
+ quotas,
+ };
+ } catch (error) {
+ return {
+ plan: "Cursor",
+ message: `Cursor connected. Unable to fetch usage: ${(error as Error).message}`,
+ };
+ }
+}
+
/**
* Get usage data for a provider connection
* @param {Object} connection - Provider connection with accessToken
@@ -878,6 +1016,8 @@ export async function getUsageForProvider(connection, options: { forceRefresh?:
return await getClaudeUsage(accessToken);
case "codex":
return await getCodexUsage(accessToken, providerSpecificData);
+ case "cursor":
+ return await getCursorUsage(accessToken, providerSpecificData);
case "kiro":
case "amazon-q":
return await getKiroUsage(accessToken, providerSpecificData);
@@ -900,8 +1040,6 @@ export async function getUsageForProvider(connection, options: { forceRefresh?:
return await getMiniMaxUsage(apiKey, provider);
case "crof":
return await getCrofUsage(apiKey);
- case "cursor":
- return await getCursorUsage(accessToken);
case "bailian-coding-plan":
return await getBailianCodingPlanUsage(id, apiKey, providerSpecificData);
case "nanogpt":
@@ -1134,172 +1272,6 @@ function inferGitHubPlanName(data: JsonRecord, premiumQuota: UsageQuota | null):
return "GitHub Copilot";
}
-function buildCursorUsageHeaders(accessToken: string): Record<string, string> {
- return getCursorUsageHeaders(accessToken, CURSOR_USAGE_CONFIG.clientVersion);
-}
-
-function getFirstPositiveNumber(...values: unknown[]): number {
- for (const value of values) {
- const parsed = toNumber(value, Number.NaN);
- if (Number.isFinite(parsed) && parsed > 0) {
- return parsed;
- }
- }
- return 0;
-}
-
-function getCursorMonthlyRequestLimit(usageData: JsonRecord, subscriptionData: JsonRecord): number {
- return getFirstPositiveNumber(
- getFieldValue(subscriptionData, "team_max_monthly_requests", "teamMaxMonthlyRequests"),
- getFieldValue(usageData, "team_max_request_usage", "teamMaxRequestUsage"),
- getFieldValue(subscriptionData, "team_max_request_usage", "teamMaxRequestUsage"),
- getFieldValue(usageData, "hard_limit", "hardLimit"),
- getFieldValue(subscriptionData, "max_monthly_requests", "maxMonthlyRequests")
- );
-}
-
-function getCursorOnDemandLimit(usageData: JsonRecord, subscriptionData: JsonRecord): number {
- const onDemand = toRecord(getFieldValue(usageData, "on_demand", "onDemand"));
- return getFirstPositiveNumber(
- getFieldValue(onDemand, "max_requests", "maxRequests"),
- getCursorMonthlyRequestLimit(usageData, subscriptionData)
- );
-}
-
-function formatCursorQuota(
- usedValue: unknown,
- totalValue: unknown,
- resetValue: unknown
-): UsageQuota {
- const total = Math.max(0, toNumber(totalValue, 0));
- const rawUsed = Math.max(0, toNumber(usedValue, 0));
- const used = total > 0 ? Math.min(rawUsed, total) : rawUsed;
- const remaining = total > 0 ? Math.max(total - used, 0) : 0;
-
- return {
- used,
- total,
- remaining,
- remainingPercentage: total > 0 ? clampPercentage((remaining / total) * 100) : 0,
- resetAt: parseResetTime(resetValue),
- unlimited: false,
- };
-}
-
-function inferCursorPlanName(userMeta: JsonRecord, subscriptionData: JsonRecord): string {
- const teamInfo = toRecord(getFieldValue(userMeta, "team_info", "teamInfo"));
- const candidates = [
- getFieldValue(userMeta, "plan", "plan"),
- getFieldValue(userMeta, "subscription_type", "subscriptionType"),
- getFieldValue(subscriptionData, "subscription_type", "subscriptionType"),
- getFieldValue(subscriptionData, "plan", "plan"),
- ];
- const planText = candidates.find((value) => typeof value === "string" && value.trim().length > 0);
- const normalized = typeof planText === "string" ? planText.trim().toLowerCase() : "";
-
- if (Object.keys(teamInfo).length > 0 || normalized.includes("team")) return "Cursor Team";
- if (normalized.includes("enterprise")) return "Cursor Enterprise";
- if (normalized.includes("pro")) return "Cursor Pro";
- if (normalized.includes("free")) return "Cursor Free";
- return "Cursor";
-}
-
-async function fetchCursorUsageDocument(url: string, accessToken: string) {
- const response = await fetch(url, {
- method: "GET",
- headers: buildCursorUsageHeaders(accessToken),
- });
-
- const text = await response.text();
- if (!response.ok) {
- return {
- ok: false,
- status: response.status,
- data: {} as JsonRecord,
- text,
- };
- }
-
- try {
- const parsed = text ? JSON.parse(text) : {};
- return {
- ok: true,
- status: response.status,
- data: toRecord(parsed),
- text,
- };
- } catch {
- return {
- ok: false,
- status: response.status,
- data: {} as JsonRecord,
- text,
- };
- }
-}
-
-async function getCursorUsage(accessToken: string) {
- try {
- if (!accessToken) {
- return {
- message: "Cursor token expired or unavailable. Please re-authenticate the connection.",
- };
- }
-
- const [usageSummary, userMeta, subscription] = await Promise.all([
- fetchCursorUsageDocument(CURSOR_USAGE_CONFIG.usageUrl, accessToken),
- fetchCursorUsageDocument(CURSOR_USAGE_CONFIG.userMetaUrl, accessToken),
- fetchCursorUsageDocument(CURSOR_USAGE_CONFIG.subscriptionUrl, accessToken),
- ]);
-
- const authDenied = [usageSummary, userMeta, subscription].some(
- (result) => result.status === 401 || result.status === 403
- );
- if (authDenied) {
- return {
- message:
- "Cursor token expired or permission denied. Please re-authenticate the connection.",
- };
- }
-
- const usageData = usageSummary.data;
- const userMetaData = userMeta.data;
- const subscriptionData = subscription.data;
- const plan = inferCursorPlanName(userMetaData, subscriptionData);
-
- const quotas: Record<string, UsageQuota> = {};
- const totalUsed = getFieldValue(usageData, "num_requests_total", "numRequestsTotal");
- const totalLimit = getCursorMonthlyRequestLimit(usageData, subscriptionData);
- const totalReset =
- getFieldValue(usageData, "reset_date", "resetDate") ||
- getFieldValue(subscriptionData, "reset_date", "resetDate");
-
- if (toNumber(totalUsed, 0) > 0 || totalLimit > 0) {
- quotas.requests = formatCursorQuota(totalUsed, totalLimit, totalReset);
- }
-
- const onDemand = toRecord(getFieldValue(usageData, "on_demand", "onDemand"));
- const onDemandUsed = getFieldValue(onDemand, "num_requests", "numRequests");
- const onDemandLimit = getCursorOnDemandLimit(usageData, subscriptionData);
- const onDemandReset =
- getFieldValue(onDemand, "reset_date", "resetDate") ||
- getFieldValue(usageData, "reset_date", "resetDate") ||
- getFieldValue(subscriptionData, "reset_date", "resetDate");
-
- if (toNumber(onDemandUsed, 0) > 0 || onDemandLimit > 0) {
- quotas.on_demand = formatCursorQuota(onDemandUsed, onDemandLimit, onDemandReset);
- }
-
- if (Object.keys(quotas).length > 0) {
- return { plan, quotas };
- }
-
- return { plan, message: "Cursor connected. Unable to parse quota data." };
- } catch (error) {
- return { message: `Unable to fetch Cursor usage: ${(error as Error).message}` };
- }
-}
-
// ── Gemini CLI subscription info cache ──────────────────────────────────────
// Prevents duplicate loadCodeAssist calls within the same quota cycle.
// Key: accessToken → { data, fetchedAt }
@@ -2459,11 +2431,6 @@ export const __testing = {
parseResetTime,
formatGitHubQuotaSnapshot,
inferGitHubPlanName,
- buildCursorUsageHeaders,
- formatCursorQuota,
- getCursorMonthlyRequestLimit,
- getCursorOnDemandLimit,
- inferCursorPlanName,
getGeminiCliPlanLabel,
getAntigravityPlanLabel,
};
diff --git a/src/app/api/oauth/cursor/import/route.ts b/src/app/api/oauth/cursor/import/route.ts
index f2ba171d62..8e747c8041 100755
--- a/src/app/api/oauth/cursor/import/route.ts
+++ b/src/app/api/oauth/cursor/import/route.ts
@@ -58,22 +58,33 @@ export async function POST(request: Request) {
cursorService.validateImportToken(accessToken.trim(), machineId?.trim())
);
- // Try to extract user info from token
- const userInfo = cursorService.extractUserInfo(tokenData.accessToken);
+ // Try to extract user info from token (JWT decode, no API call)
+ const jwtInfo = cursorService.extractUserInfo(tokenData.accessToken);
- // Save to database
+ // Best-effort fetch real profile (email + name) from cursor.com using the
+ // same WorkOS session cookie format we use for usage limits.
+ const profile = jwtInfo?.userId
+ ? await runWithProxyContext(proxy, () =>
+ cursorService.fetchUserInfo(tokenData.accessToken, jwtInfo.userId)
+ )
+ : null;
+
+ const email = profile?.email || jwtInfo?.email || null;
+
+ // Save to database (no `name` — let the dashboard fall back to email so the
+ // privacy mask toggle applies, matching the codex/claude rendering).
const connection: any = await createProviderConnection({
provider: "cursor",
authType: "oauth",
accessToken: tokenData.accessToken,
refreshToken: null, // Cursor doesn't have public refresh endpoint
expiresAt: new Date(Date.now() + tokenData.expiresIn * 1000).toISOString(),
- email: userInfo?.email || null,
+ email,
providerSpecificData: {
machineId: tokenData.machineId,
authMethod: "imported",
provider: "Imported",
- userId: userInfo?.userId,
+ userId: jwtInfo?.userId,
},
testStatus: "active",
});
diff --git a/src/lib/oauth/services/cursor.ts b/src/lib/oauth/services/cursor.ts
index d460520879..2d1e5af620 100644
--- a/src/lib/oauth/services/cursor.ts
+++ b/src/lib/oauth/services/cursor.ts
@@ -143,8 +143,10 @@ export class CursorService {
const decoded = JSON.parse(
Buffer.from(payload.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString()
);
+ const email =
+ typeof decoded.email === "string" && decoded.email.includes("@") ? decoded.email : null;
return {
- email: decoded.email || decoded.sub,
+ email,
userId: decoded.sub || decoded.user_id,
};
}
@@ -155,6 +157,41 @@ export class CursorService {
return null;
}
+ /**
+ * Fetch real user profile from cursor.com using the same WorkOS-session cookie
+ * format that powers the dashboard. Returns null on any failure so the import
+ * flow can fall back to whatever it can extract from the JWT.
+ */
+ async fetchUserInfo(
+ accessToken: string,
+ userId: string
+ ): Promise<{ email: string | null; name: string | null; sub: string | null } | null> {
+ if (!accessToken || !userId) return null;
+ try {
+ const response = await fetch("https://cursor.com/api/auth/me", {
+ method: "GET",
+ redirect: "manual",
+ headers: {
+ Cookie: `WorkosCursorSessionToken=${userId}::${accessToken}`,
+ Origin: "https://cursor.com",
+ Referer: "https://cursor.com/dashboard",
+ Accept: "application/json",
+ "User-Agent": getCursorUserAgent(this.config.clientVersion),
+ },
+ });
+
+ if (!response.ok) return null;
+ const data = (await response.json()) as Record<string, unknown>;
+ return {
+ email: typeof data.email === "string" ? data.email : null,
+ name: typeof data.name === "string" ? data.name : null,
+ sub: typeof data.sub === "string" ? data.sub : null,
+ };
+ } catch {
+ return null;
+ }
+ }
+
/**
* Get token storage path instructions for user
*/
diff --git a/src/shared/constants/providers.ts b/src/shared/constants/providers.ts
index ef53efc4b1..ab3ae1edc5 100644
--- a/src/shared/constants/providers.ts
+++ b/src/shared/constants/providers.ts
@@ -1979,6 +1979,7 @@ export const USAGE_SUPPORTED_PROVIDERS = [
"github",
"codex",
"claude",
+ "cursor",
"kimi-coding",
"glm",
"glm-cn",
diff --git a/tests/unit/cursor-usage-fetcher.test.ts b/tests/unit/cursor-usage-fetcher.test.ts
new file mode 100644
index 0000000000..60cc78d63c
--- /dev/null
+++ b/tests/unit/cursor-usage-fetcher.test.ts
@@ -0,0 +1,238 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+const usageService = await import("../../open-sse/services/usage.ts");
+
+const CURSOR_USAGE_URL = "https://cursor.com/api/dashboard/get-current-period-usage";
+
+function makeJwt(payload: Record<string, unknown>): string {
+ const b64url = (input: string) =>
+ Buffer.from(input)
+ .toString("base64")
+ .replace(/=+$/, "")
+ .replace(/\+/g, "-")
+ .replace(/\//g, "_");
+ const header = b64url(JSON.stringify({ alg: "HS256", typ: "JWT" }));
+ const body = b64url(JSON.stringify(payload));
+ return `${header}.${body}.signature`;
+}
+
+const SAMPLE_RESPONSE = {
+ billingCycleStart: "1776672371000",
+ billingCycleEnd: "1779264371000",
+ planUsage: {
+ totalSpend: 1529,
+ includedSpend: 1529,
+ remaining: 471,
+ limit: 2000,
+ autoPercentUsed: 13.20952380952381,
+ apiPercentUsed: 3.155555555555556,
+ totalPercentUsed: 10.193333333333333,
+ },
+ spendLimitUsage: { limitType: "user" },
+ enabled: true,
+};
+
+interface CapturedRequest {
+ url: string;
+ init: RequestInit;
+}
+
+function installFetchMock(
+ responder: (url: string, init: RequestInit) => Response | Promise<Response>
+): { restore: () => void; calls: CapturedRequest[] } {
+ const calls: CapturedRequest[] = [];
+ const original = globalThis.fetch;
+ globalThis.fetch = (async (input: any, init: RequestInit = {}) => {
+ const url = typeof input === "string" ? input : (input as Request).url;
+ calls.push({ url, init });
+ return await responder(url, init);
+ }) as typeof fetch;
+ return {
+ restore: () => {
+ globalThis.fetch = original;
+ },
+ calls,
+ };
+}
+
+test("cursor usage: happy path returns three windows with correct percentages and reset", async () => {
+ const userId = "user_01TESTSTOREDID";
+ const accessToken = makeJwt({ sub: `google-oauth2|${userId}` });
+
+ const mock = installFetchMock(
+ async () =>
+ new Response(JSON.stringify(SAMPLE_RESPONSE), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ })
+ );
+
+ try {
+ const usage = await usageService.getUsageForProvider({
+ provider: "cursor",
+ accessToken,
+ providerSpecificData: { userId },
+ });
+
+ assert.equal(usage.plan, "Cursor Pro");
+ assert.deepEqual(Object.keys(usage.quotas), ["Total", "Auto + Composer", "API"]);
+
+ const total = usage.quotas.Total;
+ assert.equal(total.total, 20); // limit 2000 cents = $20
+ assert.equal(total.used, 15.29); // totalSpend 1529 cents = $15.29
+ assert.equal(total.remaining, 4.71);
+ assert.ok(Math.abs(total.remainingPercentage - (100 - 10.193333333333333)) < 1e-6);
+ assert.equal(total.unlimited, false);
+ assert.equal(total.resetAt, new Date(Number("1779264371000")).toISOString());
+
+ const auto = usage.quotas["Auto + Composer"];
+ assert.equal(auto.total, 20);
+ // 2000 cents * 13.2095% ≈ 264 cents = $2.64
+ assert.equal(auto.used, 2.64);
+ assert.ok(Math.abs(auto.remainingPercentage - (100 - 13.20952380952381)) < 1e-6);
+
+ const api = usage.quotas.API;
+ assert.equal(api.total, 20);
+ // 2000 cents * 3.1556% ≈ 63 cents = $0.63
+ assert.equal(api.used, 0.63);
+ assert.ok(Math.abs(api.remainingPercentage - (100 - 3.155555555555556)) < 1e-6);
+ } finally {
+ mock.restore();
+ }
+});
+
+test("cursor usage: sends correct cookie, origin, body, and method", async () => {
+ const userId = "user_01HEADERCHECK";
+ const accessToken = makeJwt({ sub: userId });
+
+ const mock = installFetchMock(
+ async () =>
+ new Response(JSON.stringify(SAMPLE_RESPONSE), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ })
+ );
+
+ try {
+ await usageService.getUsageForProvider({
+ provider: "cursor",
+ accessToken,
+ providerSpecificData: { userId },
+ });
+
+ assert.equal(mock.calls.length, 1);
+ const { url, init } = mock.calls[0];
+ assert.equal(url, CURSOR_USAGE_URL);
+ assert.equal(init.method, "POST");
+ assert.equal(init.body, "{}");
+
+ const headers = init.headers as Record<string, string>;
+ assert.equal(headers.Cookie, `WorkosCursorSessionToken=${userId}::${accessToken}`);
+ assert.equal(headers.Origin, "https://cursor.com");
+ assert.match(headers.Referer, /^https:\/\/cursor\.com\/dashboard/);
+ assert.equal(headers["Content-Type"], "application/json");
+ assert.ok(headers["User-Agent"]);
+ } finally {
+ mock.restore();
+ }
+});
+
+test("cursor usage: falls back to JWT sub when providerSpecificData.userId is missing", async () => {
+ const userId = "user_01JWTFALLBACK";
+ const accessToken = makeJwt({ sub: `google-oauth2|${userId}` });
+
+ const mock = installFetchMock(
+ async () =>
+ new Response(JSON.stringify(SAMPLE_RESPONSE), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ })
+ );
+
+ try {
+ const usage = await usageService.getUsageForProvider({
+ provider: "cursor",
+ accessToken,
+ providerSpecificData: {},
+ });
+
+ assert.equal(usage.plan, "Cursor Pro");
+ assert.equal(mock.calls.length, 1);
+ const headers = mock.calls[0].init.headers as Record<string, string>;
+ // Cookie should use the full sub claim (google-oauth2|user_...) since Cursor accepts both forms.
+ assert.equal(
+ headers.Cookie,
+ `WorkosCursorSessionToken=google-oauth2|${userId}::${accessToken}`
+ );
+ } finally {
+ mock.restore();
+ }
+});
+
+test("cursor usage: returns message and skips fetch when userId is unrecoverable", async () => {
+ const mock = installFetchMock(async () => new Response("should not be called", { status: 500 }));
+
+ try {
+ const usage = await usageService.getUsageForProvider({
+ provider: "cursor",
+ accessToken: "not-a-jwt-and-too-short",
+ providerSpecificData: {},
+ });
+
+ assert.equal(mock.calls.length, 0);
+ assert.match(usage.message, /missing user id/i);
+ assert.equal(usage.quotas, undefined);
+ } finally {
+ mock.restore();
+ }
+});
+
+test("cursor usage: 307 redirect surfaces as expired session message", async () => {
+ const accessToken = makeJwt({ sub: "user_01EXPIRED" });
+ const mock = installFetchMock(
+ async () =>
+ new Response("", {
+ status: 307,
+ headers: { Location: "https://api.workos.com/user_management/authorize?..." },
+ })
+ );
+
+ try {
+ const usage = await usageService.getUsageForProvider({
+ provider: "cursor",
+ accessToken,
+ providerSpecificData: { userId: "user_01EXPIRED" },
+ });
+
+ assert.equal(usage.plan, "Cursor");
+ assert.match(usage.message, /session expired|Re-import/i);
+ assert.equal(usage.quotas, undefined);
+ } finally {
+ mock.restore();
+ }
+});
+
+test("cursor usage: empty planUsage returns informational message", async () => {
+ const accessToken = makeJwt({ sub: "user_01EMPTY" });
+ const mock = installFetchMock(
+ async () =>
+ new Response(
+ JSON.stringify({ billingCycleStart: "0", billingCycleEnd: "0", planUsage: {} }),
+ { status: 200, headers: { "content-type": "application/json" } }
+ )
+ );
+
+ try {
+ const usage = await usageService.getUsageForProvider({
+ provider: "cursor",
+ accessToken,
+ providerSpecificData: { userId: "user_01EMPTY" },
+ });
+
+ assert.equal(usage.plan, "Cursor");
+ assert.match(usage.message, /No active plan usage/i);
+ } finally {
+ mock.restore();
+ }
+});
diff --git a/tests/unit/provider-header-profiles.test.ts b/tests/unit/provider-header-profiles.test.ts
index df7e79b340..46e2f0a0da 100644
--- a/tests/unit/provider-header-profiles.test.ts
+++ b/tests/unit/provider-header-profiles.test.ts
@@ -2,7 +2,6 @@ import test from "node:test";
import assert from "node:assert/strict";
import {
- CURSOR_REGISTRY_VERSION,
GITHUB_COPILOT_API_VERSION,
GITHUB_COPILOT_CHAT_PLUGIN_VERSION,
GITHUB_COPILOT_CHAT_USER_AGENT,
@@ -12,7 +11,6 @@ import {
KIRO_AMZ_USER_AGENT,
KIRO_SDK_USER_AGENT,
QWEN_CLI_VERSION,
- getCursorUsageHeaders,
getQwenCliUserAgent,
getGitHubCopilotChatHeaders,
getGitHubCopilotInternalUserHeaders,
@@ -39,7 +37,7 @@ test("provider header profiles expose current GitHub chat and internal headers",
assert.equal(internalHeaders["X-GitHub-Api-Version"], GITHUB_COPILOT_API_VERSION);
});
-test("provider header profiles expose dedicated refresh, qwen, qoder, kiro and cursor variants", () => {
+test("provider header profiles expose dedicated refresh, qwen, qoder and kiro variants", () => {
const refreshHeaders = getGitHubCopilotRefreshHeaders("token gh-access");
assert.equal(refreshHeaders.Authorization, "token gh-access");
assert.equal(refreshHeaders["User-Agent"], GITHUB_COPILOT_REFRESH_USER_AGENT);
@@ -65,12 +63,6 @@ test("provider header profiles expose dedicated refresh, qwen, qoder, kiro and c
assert.equal(kiroHeaders.Accept, "application/json");
assert.equal(kiroHeaders["User-Agent"], KIRO_SDK_USER_AGENT);
assert.equal(kiroHeaders["X-Amz-User-Agent"], KIRO_AMZ_USER_AGENT);
-
- const cursorHeaders = getCursorUsageHeaders("cursor-token");
- assert.equal(cursorHeaders.Authorization, "Bearer cursor-token");
- assert.equal(cursorHeaders["User-Agent"], `Cursor/${CURSOR_REGISTRY_VERSION}`);
- assert.equal(cursorHeaders["x-cursor-user-agent"], `Cursor/${CURSOR_REGISTRY_VERSION}`);
- assert.equal(cursorHeaders["x-cursor-client-version"], CURSOR_REGISTRY_VERSION);
});
test("provider header profiles tolerate browser-like process shims", async () => {
diff --git a/tests/unit/usage-service-hardening.test.ts b/tests/unit/usage-service-hardening.test.ts
index 3b77cff9dd..3e2d19e404 100644
--- a/tests/unit/usage-service-hardening.test.ts
+++ b/tests/unit/usage-service-hardening.test.ts
@@ -1119,68 +1119,6 @@ test("usage service treats MiniMax token-plan counts as used usage", async () =>
assert.ok(Date.parse(usage.quotas["session (5h)"].resetAt) >= beforeCall + 240_000);
});
-test("usage service parses Cursor team quotas and clamps on-demand ratio", async () => {
- const calls: any[] = [];
- globalThis.fetch = async (url, init = {}) => {
- calls.push({ url: String(url), init });
-
- if (String(url).endsWith("/api/usage")) {
- return new Response(
- JSON.stringify({
- numRequestsTotal: 450,
- hard_limit: 100,
- teamMaxRequestUsage: 500,
- onDemand: {
- numRequests: 600,
- },
- }),
- { status: 200 }
- );
- }
-
- if (String(url).endsWith("/api/auth/me")) {
- return new Response(
- JSON.stringify({
- plan: "team",
- teamInfo: { id: "team-1", name: "Core Team" },
- }),
- { status: 200 }
- );
- }
-
- if (String(url).endsWith("/api/subscription")) {
- return new Response(
- JSON.stringify({
- teamMaxMonthlyRequests: 500,
- }),
- { status: 200 }
- );
- }
-
- throw new Error(`unexpected fetch: ${url}`);
- };
-
- const usage: any = await usageService.getUsageForProvider({
- provider: "cursor",
- accessToken: "cursor-token",
- });
-
- assert.equal(calls.length, 3);
- for (const call of calls) {
- assert.equal(call.init.headers.Authorization, "Bearer cursor-token");
- assert.equal(call.init.headers["User-Agent"], "Cursor/3.3");
- assert.equal(call.init.headers["x-cursor-client-version"], "3.3");
- }
-
- assert.equal(usage.plan, "Cursor Team");
- assert.equal(usage.quotas.requests.total, 500);
- assert.equal(usage.quotas.requests.used, 450);
- assert.equal(usage.quotas.requests.remainingPercentage, 10);
- assert.equal(usage.quotas.on_demand.total, 500);
- assert.equal(usage.quotas.on_demand.used, 500);
- assert.equal(usage.quotas.on_demand.remainingPercentage, 0);
-});
-
test("usage helper branches cover reset parsing, GitHub quota math, and plan inference fallbacks", () => {
const fixedDate = new Date("2026-01-02T03:04:05.000Z");
@@ -1279,32 +1217,6 @@ test("usage helper branches cover reset parsing, GitHub quota math, and plan inf
"Copilot Student"
);
assert.equal(__testing.inferGitHubPlanName({}, null), "GitHub Copilot");
-
- assert.deepEqual(__testing.buildCursorUsageHeaders("cursor-token"), {
- Authorization: "Bearer cursor-token",
- Accept: "application/json",
- "User-Agent": "Cursor/3.3",
- "x-cursor-client-version": "3.3",
- "x-cursor-user-agent": "Cursor/3.3",
- });
- assert.equal(
- __testing.getCursorMonthlyRequestLimit(
- { hard_limit: 100, teamMaxRequestUsage: 400 },
- { teamMaxMonthlyRequests: 500 }
- ),
- 500
- );
- assert.equal(__testing.getCursorOnDemandLimit({ onDemand: { maxRequests: 120 } }, {}), 120);
- assert.deepEqual(__testing.formatCursorQuota(150, 100, null), {
- used: 100,
- total: 100,
- remaining: 0,
- remainingPercentage: 0,
- resetAt: null,
- unlimited: false,
- });
- assert.equal(__testing.inferCursorPlanName({ teamInfo: { id: "team-1" } }, {}), "Cursor Team");
- assert.equal(__testing.inferCursorPlanName({ plan: "pro" }, {}), "Cursor Pro");
});
test("usage helper branches cover Gemini CLI and Antigravity plan label fallbacks", () => {